append a Name Value pair to other one - java

here is the code of the calling method -
NameValuePair[] data = {
new NameValuePair("first_name", firstName),
new NameValuePair("last_name", lastName),
new NameValuePair("email", email),
new NameValuePair("company", organization),
new NameValuePair("phone", phone)
};
SalesForceFormSubmissionUtil.submitForm(data,CONTACT_FOR_TYPE);
In the called method -
public static void submitForm(NameValuePair[] givendata, String contactType) {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(Constants.SALESFORCE_URL);
NameValuePair[] data = {
new NameValuePair("oid", Constants.SALESFORCE_OID),
new NameValuePair(Constants.SALESFORCE_CAMPAIGN_ID, contactType)
};
post.setRequestBody(data);
i want to add both the givendata & data and send it as a post request. Can you guys suggest me how to append both.

If you just want to combine the two arrays you can create a third array (combinedData) with a size of givenData.length + data.length, then you'll have to copy the elements from your source arrays.
Though, there are plenty of other methods to solve this, as an example; below is an implementation using a ArrayList as a middle-man/helper.
String[] A1 = {"hello","world"};
String[] A2 = {"I","am","bored"};
...
ArrayList<String> temp = new ArrayList<String> (A1.length + A2.length);
temp.addAll (Arrays.asList (A1));
temp.addAll (Arrays.asList (A2));
String[] A3 = temp.toArray (new String[temp.size ()]);
...
for (int i=0; i < A3.length; ++i)
System.out.println (A3[i]);
output
hello
world
I
am
bored

public static void submitForm(NameValuePair[] givendata, String contactType) {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(Constants.SALESFORCE_URL);
post.setRequestBody(givendata);
post.addParameters({
new NameValuePair("oid", Constants.SALESFORCE_OID),
new NameValuePair(Constants.SALESFORCE_CAMPAIGN_ID, contactType)
});
...

Related

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 pass a dynamic test instance in document classification in java using weka [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am new to weka. Currently I am working on text classification using weka and java. My training data-set has one String attribute and one class attribute.
#RELATION test
#ATTRIBUTE tweet string
#ATTRIBUTE class {positive,negative}
I want to create a test instant dynamically and get it classified using Naive-Bayes classifier.
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
StringToWordVector filter = new StringToWordVector();
//training set
BufferedReader reader = null;
reader = new BufferedReader(new FileReader("D:/suicideTest.arff"));
Instances train = new Instances(reader);
train.setClassIndex(train.numAttributes() -1);
filter.setInputFormat(train);
train = Filter.useFilter(train, filter);
reader.close();
Attribute tweet = new Attribute("tweet");
FastVector classVal = new FastVector(2);
classVal.addElement("positive");
classVal.addElement("negative");
FastVector testAttributes = new FastVector(2);
testAttributes.addElement(tweet);
testAttributes.addElement(classVal);
Instance testcase;
testcase = null;
testcase.setValue(tweet,"Hello my world");
testcase.setValue((Attribute)testAttributes.elementAt(1),"?");
Instances test = null;
test.add(testcase);
test = Filter.useFilter(test, filter);
NaiveBayes nb = new NaiveBayes();
nb.buildClassifier(train);
Evaluation eval = new Evaluation(train);
eval.crossValidateModel(nb, train, 10,new Random(1));
double pred = nb.classifyInstance(test.instance(0));
System.out.println("the result is "+ pred);
}
I have followed this previous question How to test a single test case in Weka, entered by a User?.
But still I am getting and java.lang.NullPointerException when I tried to set values to test instance,
testcase.setValue(tweet,"Hello my world");
This code is working fine.
It is possible to create Instances,
Instances testSet = new Instances("", allAtt, 1);
double pred = nb.classifyInstance(testSet.instance(0));
and pass one instance to the classifier,
public static void main(String[] args) throws Exception{
StringToWordVector filter = new StringToWordVector();
//training set
BufferedReader reader;
reader = new BufferedReader(new FileReader("D:/test.arff"));
Instances train = new Instances(reader);
train.setClassIndex(train.numAttributes() -1);
filter.setInputFormat(train);
train = Filter.useFilter(train, filter);
reader.close();
NaiveBayes nb = new NaiveBayes();
nb.buildClassifier(train);
ArrayList cls = new ArrayList(2);
cls.add("negative");
cls.add("positive");
Attribute clsAtt = new Attribute("class", cls);
//ArrayList<String> tweet = new ArrayList(1);
//String tweet = "";
//Attribute tweetAtt = new Attribute("tweet", tweet);
ArrayList allAtt = new ArrayList(2);
//allAtt.add(tweetAtt);
allAtt.add(new Attribute("tweet", (FastVector) null));
allAtt.add(clsAtt);
// Create an empty test set
Instances testSet = new Instances("", allAtt, 1);
// Set class index
testSet.setClassIndex(testSet.numAttributes() - 1);
String names= "I want to suiceide";
Instance inst = new DenseInstance(2);
inst.setValue((Attribute)allAtt.get(0), names.toString());
testSet.add(inst);
System.out.println(testSet.instance(0).toString());
double pred = nb.classifyInstance(testSet.instance(0));
filter.setInputFormat(testSet);
testSet = Filter.useFilter(testSet, filter);
String predictString = testSet.classAttribute().value((int) pred);
}

How to deserialize multiple objects sequentially using jackson-databind

I am using msgpack to serialize data. I have some code works fine with serializing data.
public void testJackson() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
String data1 = "test data";
int data2 = 10;
List<String> data3 = new ArrayList<String>();
data3.add("list data1");
data3.add("list data1");
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, data1);
mapper.writeValue(out, data2);
mapper.writeValue(out, data3);
// TODO: How to deserialize?
}
But now I don't know how to deserialize data.
I am not finding any solution anywhere. It will be good if anyone can help how to proceed.
The problem
I have tried many of the readValue methods, but I only can get the first String, about the second and third value I have no idea
The thing is, Jackson always reads the first data, since the data is neither deleted from the nor did you explicitly tell Jackson that the next data is from position A to position B
Solutions
this example works and is similar to your code, but is not very elegant. Here I explicitly tell Jackson where my data is, but I have to know how it got written, which is a way too specific solution
File dataFile = new File("jackson.txt");
if(!dataFile.exists())
dataFile.createNewFile();
FileOutputStream fileOut = new FileOutputStream(dataFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileInputStream fileIn = new FileInputStream(dataFile);
String writeData1 = "test data";
int writeData2 = 10;
List<String> writeData3 = new ArrayList<String>();
writeData3.add("list data1");
writeData3.add("list data1");
ObjectMapper mapper = new ObjectMapper();
byte[] writeData1Bytes = mapper.writeValueAsBytes(writeData1);
out.write(writeData1Bytes);
byte[] writeData2Bytes = mapper.writeValueAsBytes(writeData2);
out.write(writeData2Bytes);
byte[] writeData3Bytes = mapper.writeValueAsBytes(writeData3);
out.write(writeData3Bytes);
out.writeTo(fileOut);
// TODO: How to deserialize?
int pos = 0;
byte[] readData = new byte[1000];
fileIn.read(readData);
String readData1 = mapper.readValue(readData, pos, writeData1Bytes.length, String.class);
pos += writeData1Bytes.length;
Integer readData2 = mapper.readValue(readData, pos, writeData2Bytes.length, Integer.class);
pos += writeData2Bytes.length;
ArrayList readData3 = mapper.readValue(readData, pos, writeData3Bytes.length, ArrayList.class);
pos += writeData3Bytes.length;
System.out.printf("readData1 = %s%n", readData1);
System.out.printf("readData2 = %s%n", readData2);
System.out.printf("readData3 = %s%n", readData3);
the file looks then like this
"test data"10["list data1","list data1"]
How to do it correctly
a way more elegant way is to encapsulate your data in an object which can be turned into a valid JSON string and from that Jackson won't need any more information
public class JacksonTest {
public static class DataNode {
#JsonProperty("data1")
private String data1;
#JsonProperty("data2")
private int data2;
#JsonProperty("data3")
private List<String> data3;
//needed for Jackson
public DataNode() {
}
public DataNode(String data1, int data2, List<String> data3) {
this.data1 = data1;
this.data2 = data2;
this.data3 = data3;
}
}
public static void main(String[] args) throws Exception {
File dataFile = new File("jackson.txt");
if(!dataFile.exists())
dataFile.createNewFile();
FileOutputStream fileOut = new FileOutputStream(dataFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileInputStream fileIn = new FileInputStream(dataFile);
String writeData1 = "test data";
int writeData2 = 10;
List<String> writeData3 = new ArrayList<String>();
writeData3.add("list data1");
writeData3.add("list data1");
DataNode writeData = new DataNode(writeData1, writeData2, writeData3);
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, writeData);
out.writeTo(fileOut);
// TODO: How to deserialize?
DataNode readData = mapper.readValue(fileIn, DataNode.class);
System.out.printf("readData1 = %s%n", readData.data1);
System.out.printf("readData2 = %s%n", readData.data2);
System.out.printf("readData3 = %s%n", readData.data3);
}
}
the content of the file looks like this
{"data1":"test data","data2":10,"data3":["list data1","list data1"]}
You'll want to use one of the readValue methods from ObjectMapper - probably one that has a Reader or InputStream as the first parameter.
#Japu_D_Cret Thank you for such a detailed answer!
Actually I want to use msgpack to transfer data, and I made it work by using msgpack, here is my code
ByteArrayOutputStream out = new ByteArrayOutputStream();
String data1 = "test data";
int data2 = 10;
List<String> data3 = new ArrayList<String>();
data3.add("list data1");
data3.add("list data1");
MessagePack packer = new MessagePack();
packer.write(out, data1);
packer.write(out, data2);
packer.write(out, data3);
// TODO: How to deserialize?
BufferUnpacker unpacker = packer.createBufferUnpacker(out.toByteArray());
System.out.println(unpacker.readString());
System.out.println(unpacker.readInt());
System.out.println(unpacker.read(Templates.tList(Templates.TString)));
Then I found jackson-databind on msgpack website and it supports msgpack format also.
I do some tests on these two and found that jackson's serialize performance is better than msgpack, so I want to use jackson instead of msgpack.

How to add List into properties file?

I am converting properties file into xml format like below .
public class XmlPropertiesWriter {
public static void main(String args[]) throws FileNotFoundException, IOException {
//Reading properties files in Java example
Properties props = new Properties();
FileOutputStream fos = new FileOutputStream("C:\\Users\\Desktop\\myxml.xml");
props.setProperty("key1", "test");
props.setProperty("key2", "test1");
//writing properites into properties file from Java
props.storeToXML(fos, "Properties file in xml format generated from Java program");
fos.close();
}
}
This is working fine.But I want to add one ArrayList into this xml file,How can I do this,Any one help me.
You can (un)serialized the list into string representation to store the data into the properties file:
ArrayList<String> list = new ArrayList<>( );
String serialized = list.stream( ).collect( Collectors.joining( "," ) );
String input = "data,data"
List<String> unserialized = Arrays.asList( input.split( "," ) );
With this method, take care to use a seperator which is never contained in your data.
Otherwise, write a xml (or json) file reader/writer to do what you want with support of list element
Depends on what type the ArrayList is. If it's a String type you can do
arrayList.toArray(new String[arrayList.size()]);
If the type is an object you can create a StringBuilder and add all the values seperated by a ; or : so you can split when needed
final StringBuilder builder = new Stringbuilder();
final List<Point> list = new ArrayList<Point>();
list.add(new Point(0, 0));
list.add(new Point(1, 0));
for(final Point p : list) {
builder.append(p.toString()).append(";");
}
properties.setProperty("list", builder.toString());
When you load the properties you can simply do then
final List<Point> list = new ArrayList<Point>();
final String[] points = properties.getProperty("list").split(";");
for(final String p : points) {
final int x = Integer.parseInt(p.substring(0, p.indexOf(","));
final int y = Integer.parseInt(p.substring(p.indexOf(","), p.indexOf(")"));
list.add(new Point(x, y);
}

How to save bulk documents in couchdb using lightcouch api in java

I am using the lightcouch API to connect to couchdb through Java. I am able to save a single document using dbclient.save(object) method. However, my requirement is to save bulk documents at a time. I am not able to find any methods related to saving bulk documents using the Lightcouch api. Please suggest any possible solution.
Thanks in advance!
I decided to give it a go. I have a database holding documents that describe a person.
Here is my Person class which extends Document LightCouch:
public class Person extends Document {
private String firstname = "";
private String lastname = "";
private int age = -1;
public Person(String firstname, String lastname, int age) {
super();
this.setFirstname(firstname);
this.setLastname(lastname);
this.setAge(age);
}
// setters and getters omitted for brevity
}
The algorithm is simple.
Create an array of type Document
Put your documents into the array
Create a HTTP POST request
Put the JSON converted array into the request body
Send it
Here is roughly what the code could look like.
Note: try/catch omitted for brevity! Of course you are expected to use them.
public static void main(String[] args) {
// You could also use a List and then convert it to an array
Document[] docs = new Document[2];
docs[0] = new Person("John", "Smith", 34);
docs[1] = new Person("Jane", "Smith", 30);
DefaultHttpClient httpClient = new DefaultHttpClient();
// Note the _bulk_docs
HttpPost post = new HttpPost("http://127.0.0.1:5984/persons/_bulk_docs");
Gson gson = new Gson();
StringEntity data =
new StringEntity("{ \"docs\": " + gson.toJson(docs) + "}");
data.setContentType("application/json");
post.setEntity(data);
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed. HTTP error code: "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
}
I'll describe the two noteworthy parts in this example.
First one is the collection of documents. In this case I used an array instead of a List for the example.
Document[] docs = new Document[2];
docs[0] = new Person("John", "Smith", 34);
docs[1] = new Person("Jane", "Smith", 30);
You could use a List as well and later convert it to an array using Java's utility methods.
Second one is the StringEntity. As per CouchDB's documentation on the HTTP Bulk Document API on modify multiple documents with a single request the JSON structure of your request body should look like this.
{
"docs": [
DOCUMENT,
DOCUMENT,
DOCUMENT
]
}
This is the reason for the somewhat ugly StringEntity definition.
StringEntity data = new StringEntity("{ \"docs\": " + gson.toJson(docs) + "}");
As a response you'll get a JSON array containing objects whose fields represent the *_id* and *_rev* of the inserted document along with a transaction status indicator.
I did the same thing but with spring Rest Template
I created a class which would hold the documents to be updated int he following way.
public class BulkUpdateDocument {
private List<Object> docs;
}
My Rest code looks like this.
BulkUpdateDocument doc = new BulkUpdateDocument(ListOfObjects);
Gson gson = new Gson();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<?> requestObject = new HttpEntity<Object>(gson.toJson(doc), header);
ResponseEntity<Object> postForEntity = restTemplate.postForEntity(path + "/_bulk_docs", requestObject, Object.class);

Categories

Resources