Error while creating a new "OpportunityLineItemSchedule" using SFDC Partner API - java

When I try to create a new OpportunityLineItemSchedule I'm running into following error..
Error code: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY
Error message: insufficient access rights on cross-reference id
Attached is the code snippet. Any help will be extremely useful.
SObject[] rs = new SObject[1];
MessageElement[] specificRS = new MessageElement[6];
specificRS[0] = new MessageElement(new QName("OpportunityLineItemId"),"00k7000000DFLqfAAH");
specificRS[1] = new MessageElement(new QName("Description"),"Rev Schedule Descr");
specificRS[2] = new MessageElement(new QName("Type"),"Quantity");
specificRS[3] = new MessageElement(new QName("Quantity"),(double)2);
specificRS[4] = new MessageElement(new QName("Revenue"),(double)400000.00);
specificRS[5] = new MessageElement(new QName("ScheduleDate"),"2010-10-30");
rs[0] = new SObject();
rs[0].setType("OpportunityLineItemSchedule");
rs[0].set_any(specificRS);
SaveResult[] sr = null;
try {
sr = binding.create(rs);
} catch (Exception ex) {
System.out.println("An unexpected error has occurred." + ex.getMessage());
ex.printStackTrace();
return;
}

Following works..
MessageElement[] specificRS2 = new MessageElement[5];
specificRS2[0] = new MessageElement(new QName("OpportunityLineItemId"),"00k7000000DFcOG");
// PricebookEntryId can be found by joining PricebookEntry and Pricebook2 tables (on Product2Id and
specificRS2[1] = new MessageElement(new QName("Description"),"Rev Schedule Descr2");
specificRS2[2] = new MessageElement(new QName("ScheduleDate"),"2010-10-31");
//specificRS[3] = new MessageElement(new QName("Quantity"),(double)2);
specificRS2[3] = new MessageElement(new QName("Revenue"),(double)10.00);
//specificRS[4] = new MessageElement(new QName("Type"),"Quantity"); // and/or "Revenue"
specificRS2[4] = new MessageElement(new QName("Type"),"Revenue"); // and/or "Quantity"
rs[1] = new SObject();
rs[1].setType("OpportunityLineItemSchedule");
rs[1].set_any(specificRS2);
SaveResult[] sr = null;
try {
sr = binding.create(rs);
} catch (Exception ex) {
System.out.println("An unexpected error has occurred." + ex.getMessage());
ex.printStackTrace();
return;
}

This is usually an error when code is trying to use an ID for an object that doesn't exist, or that the user doesn't have access to. I take it the only difference between the 2 snippets is the OpportunityLineItem ID? Check that the user running the code can access the item with that ID.

Have a look at the Allowed Type Field Values and Allowed Quantity and Revenue Field Values documentation for OpportunityLineItemSchedule.
The allowed Type values for an OpportunityLineItemSchedule depend on the product-level schedule preferences and whether the line item has any existing schedules
You may need to check if there are existing OpportunityLineItemSchedule records.
The allowable Quantity and Revenue field values depend on the value of the Type field
You only set the Quantity or Revenue field, not both.

Related

CmisObjectNotFoundException on getRootFolder()

I'm getting CMISNotFoundException while accessing the root folder even though i already have many documents uploaded to the repository.I'm able to fetch the repository id but getRootFolder throws error
could not fetch folder due to org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException: Object not found
s = d.getSession().session;
p.append("Successfully established session \n");
p.append("id:"+s.getRepositoryInfo().getId()+"\n");
try {
Folder folder = s.getRootFolder();
}catch(Exception e) {
p.append("could not fetch folder due to "+e.toString()+"\n");
}
I'm able to get the root folder now after creating a new repository.But now for applying ACLS i'm facing problem.
LWhen i try to apply ACl to the root folder i get CmisObjectNotFound exception.
When i apply ACL to subfolders, it workds but the permission is not applied correctly.I want to give user1 all the permission and user 2 read permission.But for user1 , now i'm not able to even view the folder.And for user2 i'm able to do everything except download.
I have referred to this link for doing so sap-link
response.getWriter().println("<html><body>");
try {
// Use a unique name with package semantics e.g. com.foo.MyRepository
String uniqueName = "com.vat.VatDocumentsRepo";
// Use a secret key only known to your application (min. 10 chars)
String secretKey = "****";
Session openCmisSession = null;
InitialContext ctx = new InitialContext();
String lookupName = "java:comp/env/" + "EcmService";
EcmService ecmSvc = (EcmService) ctx.lookup(lookupName);
try {
// connect to my repository
openCmisSession = ecmSvc.connect(uniqueName, secretKey);
}
catch (CmisObjectNotFoundException e) {
// repository does not exist, so try to create it
RepositoryOptions options = new RepositoryOptions();
options.setUniqueName(uniqueName);
options.setRepositoryKey(secretKey);
options.setVisibility(Visibility.PROTECTED);
ecmSvc.createRepository(options);
// should be created now, so connect to it
openCmisSession = ecmSvc.connect(uniqueName, secretKey);
openCmisSession.getDefaultContext().setIncludeAcls(true);
openCmisSession.getDefaultContext().setIncludeAllowableActions(true);
openCmisSession.getDefaultContext().setIncludePolicies(false);
}
response.getWriter().println(
"<h3>You are now connected to the Repository with Id "
+ openCmisSession.getRepositoryInfo().getId()
+ "</h3>");
Folder folder = openCmisSession.getRootFolder();
Map<String, String> newFolderProps = new HashMap<String, String>();
newFolderProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
newFolderProps.put(PropertyIds.NAME, "Attachments");
try {
folder.createFolder(newFolderProps);
} catch (CmisNameConstraintViolationException e) {
// Folder exists already, nothing to do
}
String userIdOfUser1 = "user1 ";
String userIdOfUser2 = "user2";
response.getWriter().println("<h3>Created By :"+folder.getCreatedBy()+"</h3>");
List<Ace> addAcl = new ArrayList<Ace>();
// build and add ACE for user U1
List<String> permissionsUser1 = new ArrayList<String>();
permissionsUser1.add("cmis:all");
Ace aceUser1 = openCmisSession.getObjectFactory().createAce(userIdOfUser1, permissionsUser1);
addAcl.add(aceUser1);
// build and add ACE for user U2
List<String> permissionsUser2 = new ArrayList<String>();
permissionsUser2.add("cmis:read");
Ace aceUser2 = openCmisSession.getObjectFactory().createAce(userIdOfUser2,
permissionsUser1);
addAcl.add(aceUser2);
response.getWriter().println("<b>Permissions for users"+addAcl.toString()+"</b>");
// list of ACEs which should be removed
List<Ace> removeAcl = new ArrayList<Ace>();
// build and add ACE for user {sap:builtin}everyone
List<String> permissionsEveryone = new ArrayList<String>();
permissionsEveryone.add("cmis:all");
Ace aceEveryone = openCmisSession.getObjectFactory().createAce(
"{sap:builtin}everyone", permissionsEveryone);
removeAcl.add(aceEveryone);
response.getWriter().println("<b>Removing Permissions for users"+removeAcl.toString()+"</b>");
ItemIterable<CmisObject> children = folder.getChildren();
response.getWriter().println("<h1> changing permissions of the following objects: </h1><ul>");
for (CmisObject o : children) {
response.getWriter().println("<li>");
if (o instanceof Folder) {
response.getWriter().println(" createdBy: " + o.getCreatedBy());
o.applyAcl(addAcl, removeAcl, AclPropagation.OBJECTONLY);
response.getWriter().println("Changed permission</li>");
} else {
Document doc = (Document) o;
response.getWriter().println(" createdBy: " + o.getCreatedBy() + " filesize: "
+ doc.getContentStreamLength() + " bytes");
doc.applyAcl(addAcl, removeAcl, AclPropagation.OBJECTONLY);
response.getWriter().println("Changed permission</li>");
}
}
response.getWriter().println("</ul>");
} catch (Exception e) {
response.getWriter().println("<h1>Error: "+e.toString()+"</h1>");
} finally {
response.getWriter().println("</body></html>");
}

Read windows registry info from remote system using Jacob

Im trying to run some WMI queries using JACOB, and so far i've been successfull in getting the services and processes however i need to query the registry to see if a certain key is there
i've stummbled across this link
but i dont understand how to implement it
in order to query the services i've used the following code
ActiveXComponent wmi = null;
wmi = new ActiveXComponent("WbemScripting.SWbemLocator"); <-- side question what is the WbemScripting...
variantParameters[0] = new Variant("localhost");
variantParameters[1] = new Variant("root\\cimv2"); <-- what is this root?
String query = "Select ExitCode,Name,ProcessId,StartMode,State,Status from Win32_Service where State='Running' and Name='MSDTC'";
Variant vCollection = wmiconnect
.invoke("ExecQuery", new Variant(query));
is there a place with decent documentation for this?
and how to implement queries on the registry?
Thanks
UPDATE
Im trying a new implementation where i try to call the StdRegProv
and i have the following code
int HKEY_LOCAL_MACHINE = 0x80000002;
String strKeyPath = "SYSTEM\\CurrentControlSet\\Services";
String [] sNames = new String [5];
ActiveXComponent wmi = new ActiveXComponent("WbemScripting.SWbemLocator");
// no connection parameters means to connect to the local machine
Variant variantParameters[] = new Variant[4];
variantParameters[0] = new Variant("192.168.1.2");
variantParameters[1] = new Variant("root\\default");
variantParameters[2] = new Variant("admin");
variantParameters[3] = new Variant("pass");
Dispatch services = wmi.invoke("ConnectServer", variantParameters).toDispatch();
Dispatch oReg = Dispatch.call(services, "Get", "StdRegProv").toDispatch();
Variant ret = Dispatch.call(oReg, "EnumKey", HKEY_LOCAL_MACHINE, strKeyPath, sNames);
System.out.println("EnumKey: HKEY_LOCAL_MACHINE\\"+strKeyPath+"="+ret);
I was hoping to get the sNames array filled with data but its just nulls
I was unable to do it with Jacob but succeeded using j-interop library
here is the code that cost me so much suffering
IJIAuthInfo authInfo = new JIDefaultAuthInfoImpl("remoteComputerIpAddress", "wmiUserName", "wmiUserPassword");
IJIWinReg registry = null;
try {
registry = JIWinRegFactory.getSingleTon().getWinreg(authInfo, "remoteComputerIpAddress", true);
JIPolicyHandle policyHandle = registry.winreg_OpenHKLM();
JIPolicyHandle policyHandle2 = registry.winreg_OpenKey(policyHandle, "SOFTWARE\\wisemon",
IJIWinReg.KEY_ALL_ACCESS);
// JIPolicyHandle policyHandle3 =
// registry.winreg_OpenKey(policyHandle2,"wisemon",IJIWinReg.KEY_ALL_ACCESS);
System.out.println("Printing first 1000 entries under HKEY_LOCAL_MACHINE\\BCD00000000...");
for (int i = 0; i < 1; i++) {
// String[] values = registry.winreg_EnumKey(policyHandle3,i);
// Object[] values = registry.winreg_EnumValue(policyHandle3,i);
Object[] values = registry.winreg_QueryValue(policyHandle2, "name", 100);
Object[] values2 = registry.winreg_QueryValue(policyHandle2, "date", 100);
System.out.println(new String((byte[]) values[1]));
System.out.println(new String((byte[]) values2[1]));
}
} catch (UnknownHostException | JIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("Closing registry connection");
registry.closeConnection();
}

How to use Wordnet Synonyms with Hibernate Search?

I've been trying to figure out how to use WordNet synonyms with a search function I'm developing which uses Hibernate Search 5.6.1. At first, I thought about using Hibernate Search annotations:
#TokenFilterDef(factory = SynonymFilterFactory.class, params = {#Parameter(name = "ignoreCase", value = "true"),
#Parameter(name = "expand", value = "true"),#Parameter(name = "synonyms", value = "synonymsfile") })
However, this requires an actual file populated with synonyms. From WordNet I was only able to get ".pl" files. So I tried manually making a SynonymAnalyzer class which would read from the ".pl" file:
public class SynonymAnalyzer extends Analyzer {
#Override
protected TokenStreamComponents createComponents(String fieldName) {
final Tokenizer source = new StandardTokenizer();
TokenStream result = new StandardFilter(source);
result = new LowerCaseFilter(result);
SynonymMap wordnetSynonyms = null;
try {
wordnetSynonyms = loadSynonyms();
} catch (IOException e) {
e.printStackTrace();
}
result = new SynonymFilter(result, wordnetSynonyms, false);
result = new StopFilter(result, StopAnalyzer.ENGLISH_STOP_WORDS_SET);
return new TokenStreamComponents(source, result);
}
private SynonymMap loadSynonyms() throws IOException {
File file = new File("synonyms\\wn_s.pl");
InputStream stream = new FileInputStream(file);
Reader reader = new InputStreamReader(stream);
SynonymMap.Builder parser = null;
parser = new WordnetSynonymParser(true, true, new StandardAnalyzer(CharArraySet.EMPTY_SET));
try {
((WordnetSynonymParser) parser).parse(reader);
} catch (ParseException e) {
e.printStackTrace();
}
return parser.build();
}
}
The problem with this method is that I'm getting java.lang.OutOfMemoryError which I'm assuming is because there's too many synonyms or something? What is the proper way to do this, everywhere I've looked online has suggested using WordNet but I can't seem to find an example with Hibernate Search Annotations. Any help is appreciated, thanks!
The wordnet format is actually supported by SynonymFilterFactory. You're simply missing the "format" parameter in your annotation configuration; by default, the factory uses the Solr format.
Change your annotation to this:
#TokenFilterDef(
factory = SynonymFilterFactory.class,
params = {
#Parameter(name = "ignoreCase", value = "true"),
#Parameter(name = "expand", value = "true"),
#Parameter(name = "synonyms", value = "synonymsfile"),
#Parameter(name = "format", value = "wordnet") // Add this
}
)
Also, make sure that the value of the "synonyms" parameter is the path of a file in your classpath (e.g. "com/acme/synonyms.pl", or just "synonyms.pl" if the file is at the root of your "resources" directory).
In general when you have an issue with the parameters of a Lucene filter/tokenizer factory, your best bet is having a look at the source code of that factory, or having a look at this page.

Azure Table batch insert from Java Using SAS fails

Trying to use a batch insert to azure table fails if using a SAS ("Shared access signature").
When using account key (which is less secure I guess) it works.
Example code:
StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature("sig=.....");
CloudTableClient cloudTableClient = new CloudTableClient(new URI("https://<storage account>.table.core.windows.net/<tablename>"), credentials);
CloudTable cloudTable = cloudTableClient.getTableReference("<tablename>");
//these 2 will be in a batch
TableServiceEntity d1 = new TableServiceEntity("3333333333333", "22222222222222" + System.currentTimeMillis());
TableServiceEntity d2 = new TableServiceEntity("3333333333333", "eeeeeeeeeee" + System.currentTimeMillis());
//single
TableServiceEntity d3 = new TableServiceEntity("ddddddddddddddddddd", "dddddddddd" + System.currentTimeMillis());
//prepare batch
TableBatchOperation batch = new TableBatchOperation();
batch.insert(d1);
batch.insert(d2);
try {
// this will work (not batch, just to show that regular insert works)
cloudTable.execute(TableOperation.insert(d3));
// this will fail
cloudTable.execute(batch);
} catch (StorageException e) {
//here we get "Unsupported Media Type" (415 error)
e.printStackTrace();
return;
}
System.out.println("OK");
The error I get is:
com.microsoft.azure.storage.StorageException: Unsupported Media Type
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:89)
at com.microsoft.azure.storage.core.StorageRequest.materializeException(StorageRequest.java:315)
at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:175)
at com.microsoft.azure.storage.table.TableBatchOperation.execute(TableBatchOperation.java:418)
at com.microsoft.azure.storage.table.CloudTable.execute(CloudTable.java:475)
at com.microsoft.azure.storage.table.CloudTable.execute(CloudTable.java:432)
at com.bgprotect.azurestorage.Test.main(Test.java:49)
SAS
sig=<sig>&se=2020-01-01T00%3A00%3A00Z&sv=2015-04-05&tn=<table name>&sp=raud
Based on the issue on Github, please try to change the following line of code:
CloudTableClient cloudTableClient = new CloudTableClient(new URI("https://<storage account>.table.core.windows.net/<tablename>"), credentials);
to:
CloudTableClient cloudTableClient = new CloudTableClient(new URI("https://<storage account>.table.core.windows.net"), credentials);
Essentially don't include the name of the table in the URI. It should only be https://account-name.table.core.windows.net.
P.S. I didn't realize you had also opened an issue on Github regarding this :).

Json and multiple User defined objects error

I have the following JSON database:
{"houses":[{"doors":[{"state":false,"requests":[]}],"users":[{"username":"blucas","password":"Phantom1"}],"passcode":"1324"},null,null,null,null,null,null,null,null,null]}
which I have generated using this code:
File database = new File("database.json");
Door door1 = new Door();
ArrayList<Door> doors = new ArrayList<Door>();
doors.add(door1);
User blucas = new User("blucas", "Phantom1");
ArrayList<User> users= new ArrayList<User>();
users.add(blucas);
House house1 = new House(doors, users);
ArrayList<House> houseList = new ArrayList<House>();
houseList.add(house1);
Houses houses = new Houses(houseList);
objMapper.writeValue(database, houses);
when I try to access the database in the simplest way that I can find:
byte[] jsonData = null;
try {
jsonData = Files.readAllBytes(Paths.get("database.json"));
} catch (IOException e) {
e.printStackTrace();
}
ObjectMapper objectMapper = new ObjectMapper();
try {
houses = objectMapper.readValue(jsonData, Houses.class);
} catch (IOException e) {
e.printStackTrace();
}
House[] myHouses = houses.getHouses();
House house1 = myHouses[0];
System.out.println(house1.checkPasscode("1324"));
System.exit(1);
I get the error:
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of Server.House: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: database.json; line: 1, column: 13] (through reference chain: Server.Houses["houses"]->java.lang.Object[][0])
Door, House, Users, and Houses are all user defined classes that exist in the same package as each other along with the code that generates the database, and the code that attempts to open and process the database.
I have looked thoroughly for a solution to this problem, but I cannot seem to find why I would be getting this error, I am very new to JSON and databases so any advice is greatly appreciated.
In House class there is no default constructor. Add default constructor in House class with no parameter.

Categories

Resources