I want to upload txt file from java application(software) to restful web-service , Because inside txt file i have list of sql query to execute. So , I want to upload file into web-service first then execute query line by line to database.
I converted txt file into List object then again into string and passed it but could not get success.
Here is Webservice code
package com.java.webservice;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.api.client.WebResource;
#Path("UploadFile")
public class UploadFile {
private List<String> storedQueries = new ArrayList<String>();
private Connection conn = null;
// private PreparedStatement pstm = null;
private Statement pstm = null;
private ResultSet rs = null;
private String q = "";
// #GET here defines, this method will method will process HTTP GET
// requests.
#GET
// #Path here defines method level path. Identifies the URI path that a
// resource class method will serve requests for.
#Path("/getTest")
// #Produces here defines the media type(s) that the methods
// of a resource class can produce.
#Produces(MediaType.APPLICATION_JSON)
// #PathParam injects the value of URI parameter that defined in #Path
// expression, into the method.
public Response getTest(#QueryParam("name") String name) {
// String name = "Lokendra Pun ,Java Engineer";
System.out.println("Your Name IS: " + name);
java.util.StringTokenizer st = new java.util.StringTokenizer(name, ",");
java.util.ArrayList newArrayList = new java.util.ArrayList();
while (st.hasMoreTokens()) {
// the trim() below may not always be desired or necessary
newArrayList.add(st.nextToken().trim());
}
// this if statement only necessary because a String created from
// ArrayList.toString() ends up as "[1, 2, 3, 4]" not, "1, 2, 3, 4"
if (newArrayList.size() == 1) {
// remove [] around item
int length = ((String) newArrayList.get(0)).length();
newArrayList.set(0, ((String) newArrayList.get(0)).substring(1, length - 1));
} else if (newArrayList.size() > 1) {
// remove '[' in first item and ']' in last
int lastIndex = newArrayList.size() - 1;
String oldString = (String) newArrayList.get(0);
String newString = oldString.substring(1, oldString.length());
newArrayList.set(0, newString);
oldString = (String) newArrayList.get(lastIndex);
newString = oldString.substring(0, oldString.length() - 1);
newArrayList.set(newArrayList.size() - 1, newString);
}
System.out.println("newArrayList->" + newArrayList.toString());
System.out.println("==================");
for (int i = 0; i < newArrayList.size(); i++) {
System.out.println("Name" + i + " :" + newArrayList.get(i));
}
System.out.println("==================");
return Response.status(200).entity(name).build();
}
/**
*
*
* method to get file name from remote server and process query into
* database
*
*
*
*/
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/getUploadQuery")
public Response getUploadQuery(#QueryParam("file_name") String file_name,
#QueryParam("database_name") String database_name) {
System.out.println("I am inside getTeacher Method");
String list = null;
try {
conn = getConnection(database_name);
if (conn != null) {
try {
for (String line : Files.readAllLines(Paths.get(file_name))) {
storedQueries.add(line);
System.out.println(line);
}
for (int i = 0; i < storedQueries.size(); i++) {
System.out.println("Looping Query Length is: " + storedQueries.size());
System.out.println("Connection Object Inside Loop : " + conn);
pstm = conn.createStatement();
System.out.println("Looping Size now : " + i);
if (!storedQueries.get(i).equals("")) {
System.out.println("Query Before Executed is: " + storedQueries.get(i));
// pstm =
// conn.prepareStatement(storedQueries.get(i));
// pstm.executeUpdate();
pstm.addBatch(storedQueries.get(i));
pstm.executeBatch();
}
}
pstm.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
list = "true";
} else {
list = "false";
}
} catch (Exception e) {
e.printStackTrace();
}
return Response.status(200).entity(list).build();
}
/**
*
* method to connect to remote server database according to db and school
* name
*
* #param database_name
* #return
*/
public Connection getConnection(String database_name) {
System.out.println("Database Name before Connection: " + database_name);
try {
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
conn = DriverManager.getConnection(
"jdbc:mysql://localhost/" + database_name + "?" + "user=root&password=java#android2016");
System.out.println(conn);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
And here is code for service calling from java application
package WSserviceCall;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TestMain {
public static final String BASE_URI = "http://localhost:8080/MovieGalaxyService";
public static final String PATH_TEST = "/UploadFile/getTest";
public static final String PATH_LOAD_FILE = "/UploadFile/getUploadQuery";
public static final String PATH_AGE = "/UploadFile/age/";
public static void main(String[] args) {
try {
// TODO Auto-generated method stub
List<String> storedQueries = new ArrayList<String>();
String currentDirectory = System.getProperty("user.dir");
String file_name = currentDirectory + "/databaseBackupScript.txt";
String name = "Lokendra Pun Param";
String age ="26";
try{
for (String line : Files.readAllLines(Paths.get(file_name))) {
storedQueries.add(line);
System.out.println(line);
}
}catch(Exception e){
e.printStackTrace();
}
// String names = ""+aa;
//System.out.println("Array Objec is: "+aa);
//System.out.println("String Objects is: "+aa.toString());
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource resource = client.resource(BASE_URI);
String param = storedQueries.toString();
String temp_uri = URLEncoder.encode(param, "UTF-8");
WebResource testResource = resource.path(PATH_TEST).
queryParam("name",temp_uri);
//WebResource testResource = resource.path(PATH_TEST);
// System.out.println("Client Response \n"
// + getClientResponse(testResource));
// System.out.println("Response \n" + getResponse(testResource) + "\n\n");
String testValue = getResponse(testResource);
System.out.println("Test Resource Value is : "+testValue);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(TestMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns client response.
* e.g :
* GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra
* returned a response status of 200 OK
*
* #param service
* #return
*/
private static String getClientResponse(WebResource resource) {
return resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class).toString();
}
/**
* Returns the response as JSON data
* e.g : status : true or false
*
* #param service
* #return
*/
private static String getResponse(WebResource resource) {
return resource.accept(MediaType.APPLICATION_JSON).get(String.class);
}
}
Related
I created a java application which is connected to a database. The regular java console application part of it works just fine. Now I want to display my Result Set on an HTML web page. BUT I keep getting a 404 error from Ajax via the console on Chrome. Here is my Java code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.fasterxml.jackson.databind.ObjectMapper;
public class EmployeeDao
{
/* Database Parameters */
public List<tickets> viewMyTickets(HttpServletRequest req, HttpServletResponse resp)
{
HttpSession appSession = req.getSession(false);
PreparedStatement myStatement = null;
String userUsername = req.getParameter("username");
String userPassword = req.getParameter("password");
String userEmployeeID = req.getParameter("employeeID");
int userEmployeeID2 = Integer.parseInt(userEmployeeID);
String usernameSession = appSession.getAttribute("username").toString();
String userPasswordSession = appSession.getAttribute("password").toString();
ResultSet myRs;
tickets activeTickets;
int userTicketNumber = 0;
String userTicketsDescription = " ";
String userTicketsStatus = " ";
Double userReimbursementAmount = 0.0;
Timestamp userDateSubmitted = null;
Timestamp userDateResolved = null;
String userReimbursementType = " ";
if(userUsername.equals(usernameSession ) && userPassword.equals(userPasswordSession) )
{
String selectAllEmployeeRequests = "SELECT * FROM tickets WHERE employeeID = ?";
try
{
myStatement = AndreConnection.prepareStatement(selectAllEmployeeRequests);
myStatement.setInt(1, userEmployeeID2);
myRs = myStatement.executeQuery();
List<tickets> employeeTicketsList = new ArrayList<tickets>();
while (myRs.next())
{
userTicketNumber = myRs.getInt("ticketNumber");
userTicketsDescription = myRs.getString("ticketsDescription");
userTicketsStatus = myRs.getString("ticketsStatus");
userReimbursementAmount = myRs.getDouble("reimbursementAmount");
userDateSubmitted = myRs.getTimestamp("dateSubmitted");
userDateResolved = myRs.getTimestamp("dateResolved");
userReimbursementType = myRs.getString("reimbursementType");
userEmployeeID2 = myRs.getInt("employeeID");
activeTickets = new tickets(userTicketsDescription, userTicketsStatus, userReimbursementAmount, userDateSubmitted, userReimbursementType, userEmployeeID2);
employeeTicketsList.add(activeTickets);
}
PrintWriter printer = resp.getWriter();
printer.write(new ObjectMapper().writeValueAsString(employeeTicketsList));
return employeeTicketsList;
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try
{
PrintWriter out = resp.getWriter();
out.println("<html><head><title>Bad Login</title></head><body><h1> Go back and login </h1></body></html>");
resp.sendRedirect("ERS/index.html");
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
Here is my Ajax code:
window.onload = main;
function main()
{
ether();
getInfo();
}
function ether()
{
queryString = document.location.search;
let params = new URLSearchParams(queryString);
let username = params.get("username");
document.getElementById("welcome").innerText = "Welcome " + username;
}
function AndreAjax()
{
document.getElementById('Display').addEventListener('load', getInfo() );
}
function getInfo()
{
getRequest();
return false;
}//end of getNewFile function
function getRequest()
{
try
{
xhttp = new XMLHttpRequest();
}
catch(err1)
{
try
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(err2)
{
try
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(err3)
{
xhttp = false;
}
}
}
if(xhttp)
{
xhttp.onreadystatechange = getServerData;
xhttp.open(`GET`, `http://localhost:9001/ERS/employeeTicketsList` );
xhttp.send();
setTimeout("getRequest()", 5*1000);
}
else
{
document.getElementById("Display").innerHTML = "Sorry I could not creat an XMLHttpRequest";
}
}//end of getRequest function
function getServerData()
{
if(xhttp.readyState==4)
{
alert("xhttp.status = " + xhttp.status);
}
if(xhttp.readyState==4 && xhttp.status==200)
{
var displayContent = JSON.parse(xhttp.responseText);
document.getElementById("Display").innerHTML = displayContent;
alert(displayContent);
}
else
{
document.getElementById("Display").innerHTML = " waiting Andre";
}
}
Question: Why can't Ajax find http://localhost:9001/ERS/employeeTicketsList (this is the source of the 404 error in the console in Google Chrome and Firefox) Login for user works just fine, username displays at top of webpage
Here, You can see the program which fetch the Leaked Connection count from weblogic. But, I always get it as zero. I have set maximum connection count to 10 from my data source and I run some code which not closes the connection so, Connection Unavailable count is increases to 10 but Liked Connection count is still 0.
So, What to do to increase the count of it because there are liked connections are there by application.
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class Test {
private static final Logger logger = Logger.getLogger(Test.class.getName());
private static final String PROTOCOL = "admin.server.protocol";
private static final String HOST = "admin.server.host";
private static final String PORT = "admin.server.port";
private static final String USERNAME = "admin.server.username";
private static final String PASSWORD = "admin.server.password";
private static final String JNDI_ROOT = "jndi.root";
private static final String DATA_SOURCE = "DataSourceName";
private static final String DATASOURCE_ORACLEDS_JTA = "dataSource-OracleDS_jta";
private static MBeanServerConnection connection;
private static JMXConnector connector;
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
System.out.println(test.isConnectionLeaked());
}
public List<String> getDataSourceNames(){
return Arrays.asList(DATA_SOURCE,DATASOURCE_ORACLEDS_JTA);
}
/*
* Initialize connection to the Domain Runtime MBean Server.
*/
public static void initConnection() throws IOException,
MalformedURLException {
logger.info("Inside initConnection");
InputStream is = ClassLoader.getSystemResourceAsStream("jmx.properties");
Properties props = new Properties();
props.load(is);
String protocol = (String) props.get(PROTOCOL);
Integer portInteger = Integer.valueOf((String) props.get(PORT));
int port = portInteger.intValue();
String jndiroot = (String) props.get(JNDI_ROOT);
String hostname = (String) props.get(HOST);
JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostname, port, jndiroot);
Hashtable<String, Object> h = new Hashtable<>();
h.put(Context.SECURITY_PRINCIPAL, (String) props.get(USERNAME));
h.put(Context.SECURITY_CREDENTIALS, (String) props.get(PASSWORD));
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
h.put("jmx.remote.x.request.waiting.timeout", new Long(10000));
connector = JMXConnectorFactory.connect(serviceURL, h);
connection = connector.getMBeanServerConnection();
logger.info("End initConnection");
}
public boolean isConnectionLeaked() {
List<String> dataPoolNames = getDataSourceNames();
boolean isLeaked = false;
try {
initConnection();
ObjectName service = new ObjectName("com.bea:Name=DomainRuntimeService,"
+ "Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");
ObjectName[] number_of_servers = (ObjectName[]) connection.getAttribute(service, "ServerRuntimes");
int length = (int) number_of_servers.length;
for (int i = 0; i < length; i++) {
logger.info("Server Instance=" + number_of_servers[i]);
String name = (String) connection.getAttribute(number_of_servers[i], "Name");
ObjectName[] number_of_dbpools = (ObjectName[]) connection.getAttribute(new ObjectName("com.bea:Name="
+ name + ",ServerRuntime=" + name + ",Location=" + name + ",Type=JDBCServiceRuntime"),
"JDBCDataSourceRuntimeMBeans");
int pool_length = (int) number_of_dbpools.length;
for (int x = 0; x < pool_length; x++) {
String poolName = (String) connection.getAttribute(number_of_dbpools[x], "Name");
logger.info("********* PoolName=" + poolName + " ******");
int leakedConnectionCount = (Integer) connection.getAttribute(number_of_dbpools[x],
"LeakedConnectionCount");
logger.info("leakedConnectionCount : " + leakedConnectionCount);
if (leakedConnectionCount > 0) { // Send email alert
isLeaked = true;
}
}
}
} catch (Exception e) {
logger.severe("Exception in isConnectionLeaked method");
logger.severe("Message = " + e.getMessage());
} finally {
try {
if (connector != null) {
logger.info("Connectors JMXConnector.");
connector.close();
}
} catch (IOException e) {
logger.severe(e.getMessage());
}
}
logger.info("End isConnectionLeaked. isLeaked = "+isLeaked);
return isLeaked;
}
}
The Inactive Connection Timeout is set to 0?
This is the main class in which query is being fired
package extractKeyword;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.methods.GetMethod;
import org.dbpedia.spotlight.exceptions.AnnotationException;
import org.dbpedia.spotlight.model.DBpediaResource;
import org.dbpedia.spotlight.model.Text;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
public class db extends AnnotationClient {
//private final static String API_URL = "http://jodaiber.dyndns.org:2222/";
private static String API_URL = "http://spotlight.dbpedia.org/";
private static double CONFIDENCE = 0.0;
private static int SUPPORT = 0;
// private static String powered_by ="non";
// private static String spotter ="CoOccurrenceBasedSelector";//"LingPipeSpotter"=Annotate all spots
//AtLeastOneNounSelector"=No verbs and adjs.
//"CoOccurrenceBasedSelector" =No 'common words'
//"NESpotter"=Only Per.,Org.,Loc.
//private static String disambiguator ="Default";//Default ;Occurrences=Occurrence-centric;Document=Document-centric
//private static String showScores ="yes";
#SuppressWarnings("static-access")
public void configiration(double CONFIDENCE,int SUPPORT)
//, String powered_by,String spotter,String disambiguator,String showScores)
{
this.CONFIDENCE=CONFIDENCE;
this.SUPPORT=SUPPORT;
// this.powered_by=powered_by;
//this.spotter=spotter;
//this.disambiguator=disambiguator;
//showScores=showScores;
}
public List<DBpediaResource> extract(Text text) throws AnnotationException {
// LOG.info("Querying API.");
String spotlightResponse;
try {
String Query=API_URL + "rest/annotate/?" +
"confidence=" + CONFIDENCE
+ "&support=" + SUPPORT
// + "&spotter=" + spotter
// + "&disambiguator=" + disambiguator
// + "&showScores=" + showScores
// + "&powered_by=" + powered_by
+ "&text=" + URLEncoder.encode(text.text(), "utf-8");
//LOG.info(Query);
GetMethod getMethod = new GetMethod(Query);
getMethod.addRequestHeader(new Header("Accept", "application/json"));
spotlightResponse = request(getMethod);
} catch (UnsupportedEncodingException e) {
throw new AnnotationException("Could not encode text.", e);
}
assert spotlightResponse != null;
JSONObject resultJSON = null;
JSONArray entities = null;
try {
resultJSON = new JSONObject(spotlightResponse);
entities = resultJSON.getJSONArray("Resources");
} catch (JSONException e) {
//throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
}
LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
if(entities!=null)
for(int i = 0; i < entities.length(); i++) {
try {
JSONObject entity = entities.getJSONObject(i);
resources.add(
new DBpediaResource(entity.getString("#URI"),
Integer.parseInt(entity.getString("#support"))));
} catch (JSONException e) {
//((Object) LOG).error("JSON exception "+e);
}
}
return resources;
}
}
The extended class
package extractKeyword;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dbpedia.spotlight.exceptions.AnnotationException;
import org.dbpedia.spotlight.model.DBpediaResource;
import org.dbpedia.spotlight.model.Text;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import javax.ws.rs.HttpMethod;
/**
* #author pablomendes
*/
public abstract class AnnotationClient {
//public Logger LOG = Logger.getLogger(this.getClass());
private List<String> RES = new ArrayList<String>();
// Create an instance of HttpClient.
private static HttpClient client = new HttpClient();
public List<String> getResu(){
return RES;
}
public String request(GetMethod getMethod) throws AnnotationException {
String response = null;
// Provide custom retry handler is necessary
( getMethod).getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod((org.apache.commons.httpclient.HttpMethod) getMethod);
if (statusCode != HttpStatus.SC_OK) {
// LOG.error("Method failed: " + ((HttpMethodBase) method).getStatusLine());
}
// Read the response body.
byte[] responseBody = ((HttpMethodBase) getMethod).getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
} catch (HttpException e) {
// LOG.error("Fatal protocol violation: " + e.getMessage());
throw new AnnotationException("Protocol error executing HTTP request.",e);
} catch (IOException e) {
//((Object) LOG).error("Fatal transport error: " + e.getMessage());
//((Object) LOG).error(((HttpMethodBase) method).getQueryString());
throw new AnnotationException("Transport error executing HTTP request.",e);
} finally {
// Release the connection.
((HttpMethodBase) getMethod).releaseConnection();
}
return response;
}
protected static String readFileAsString(String filePath) throws java.io.IOException{
return readFileAsString(new File(filePath));
}
protected static String readFileAsString(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
#SuppressWarnings("resource")
BufferedInputStream f = new BufferedInputStream(new FileInputStream(file));
f.read(buffer);
return new String(buffer);
}
static abstract class LineParser {
public abstract String parse(String s) throws ParseException;
static class ManualDatasetLineParser extends LineParser {
public String parse(String s) throws ParseException {
return s.trim();
}
}
static class OccTSVLineParser extends LineParser {
public String parse(String s) throws ParseException {
String result = s;
try {
result = s.trim().split("\t")[3];
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException(e.getMessage(), 3);
}
return result;
}
}
}
public void saveExtractedEntitiesSet(String Question, LineParser parser, int restartFrom) throws Exception {
String text = Question;
int i=0;
//int correct =0 ; int error = 0;int sum = 0;
for (String snippet: text.split("\n")) {
String s = parser.parse(snippet);
if (s!= null && !s.equals("")) {
i++;
if (i<restartFrom) continue;
List<DBpediaResource> entities = new ArrayList<DBpediaResource>();
try {
entities = extract(new Text(snippet.replaceAll("\\s+"," ")));
System.out.println(entities.get(0).getFullUri());
} catch (AnnotationException e) {
// error++;
//LOG.error(e);
e.printStackTrace();
}
for (DBpediaResource e: entities) {
RES.add(e.uri());
}
}
}
}
public abstract List<DBpediaResource> extract(Text text) throws AnnotationException;
public void evaluate(String Question) throws Exception {
evaluateManual(Question,0);
}
public void evaluateManual(String Question, int restartFrom) throws Exception {
saveExtractedEntitiesSet(Question,new LineParser.ManualDatasetLineParser(), restartFrom);
}
}
The Main Class
package extractKeyword;
public class startAnnonation {
public static void main(String[] args) throws Exception {
String question = "What is the winning chances of BJP in New Delhi elections?";
db c = new db ();
c.configiration(0.25,0);
//, 0, "non", "AtLeastOneNounSelector", "Default", "yes");
c.evaluate(question);
System.out.println("resource : "+c.getResu());
}
}
The main problem is here when I am using DBPedia spotlight using spotlight jar (above code)then i am getting different result as compared to the dbpedia spotlight endpoint(dbpedia-spotlight.github.io/demo/)
Result using the above code:-
Text :-What is the winning chances of BJP in New Delhi elections?
Confidence level:-0.35
resource : [Election]
Result on DBPedia Spotlight endpoint(//dbpedia-spotlight.github.io/demo/)
Text:-What is the winning chances of BJP in New Delhi elections?
Confidence level:-0.35
resource : [Bharatiya_Janata_Party, New_Delhi, Election]
Why also the spotlight now don't have support as a parameter?
I have written a code in java for web services of crm on demand. The code reads the 1st column (id) from excel and queries it in the crm and inserts the values accordingly. If the 'id' is found it inserts the other values, but when the 'id' is not found in the crm the code is terminated with error message. I want the code to query for a record and if found insert the other values, but if the record is not found it should skip that record and query for the next id without it being terminated in between.
Please help...
and also how to skip cells with no value(null)??
import crmondemand.ws.account.AccountWS_AccountInsertChild_Input;
import crmondemand.ws.account.AccountWS_AccountInsertChild_Output;
import crmondemand.ws.account.AccountWS_AccountUpdate_Input;
import crmondemand.ws.account.AccountWS_AccountUpdate_Output;
import crmondemand.ws.account.Default_BindingStub;
import crmondemand.xml.account.Account;
import crmondemand.xml.account.RelatedAccount;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.TimeZone;
import javax.xml.rpc.ServiceException;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.axis.AxisProperties;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class accrel1 {
private String inputFile;
public static int length;
public void setInputFile(String inputFile) {
this.inputFile = inputFile;
}
static Logger logger = Logger.getLogger(accrel1.class);
public static URL reauthentication(Properties properties) throws MalformedURLException {
// System.setProperty("https.proxyHost", "172.17.24.24");
// System.setProperty("https.proxyPort", "8003");
//System.setProperty("https.proxyHost", "145.247.13.164");
// System.setProperty("https.proxyPort", "3128");
// System.setProperty("javax.net.ssl.trustStore","C:\\ProgramFiles\\Java\\jdk1.6.0_31\\jre\\lib\\cacerts");
System.out.println("Loggin In");
String jsessionid_full =
logon("https://secure-ausomxapa.crmondemand.com/Services/Integration",
"################", "##########", properties);
System.out.println("Connecting to CRM..." + jsessionid_full);
String jsessionid = getSessionId(jsessionid_full);
System.out.println("JSessionid: " + jsessionid);
String endpoint =
"https://secure-ausomxapa.crmondemand.com/Services/Integration" +
";jsessionid=" + jsessionid;
URL urlAddr = new java.net.URL(endpoint);
System.out.println("Establishing Connection...");
return urlAddr;
}
public static void urlqueryWS1(URL urlAddr, List cellDataList,
Properties properties) throws RemoteException,
ServiceException,
MalformedURLException {
AxisProperties.setProperty("https.proxyHost",
properties.getProperty("proxyhost"));
AxisProperties.setProperty("https.proxyPort",
properties.getProperty("proxyport"));
// AxisProperties.setProperty("http.nonProxyHosts", "secure-ausomxapa.crmondemand.com");
crmondemand.ws.account.AccountWS_AccountQueryPage_Input accountlist =
new crmondemand.ws.account.AccountWS_AccountQueryPage_Input();
crmondemand.ws.account.AccountWS_AccountQueryPage_Output outlist =
new crmondemand.ws.account.AccountWS_AccountQueryPage_Output();
crmondemand.xml.account.Account[] accounts =
new crmondemand.xml.account.Account[1];
crmondemand.xml.account.Account account =
new crmondemand.xml.account.Account();
String stringCellValue[] = new String[6000];
int k = 0;
int flag = 0, notflag = 0, noparentflag = 0;
System.out.println("CellDatasize:" + cellDataList.size());
for (int i = 1; i < cellDataList.size(); i++) {
crmondemand.ws.account.Account service =
new crmondemand.ws.account.AccountLocator();
Default_BindingStub stub =
(Default_BindingStub)service.getDefault(urlAddr);
List cellTempList = (List)cellDataList.get(i);
for (int j = 0; j < cellTempList.size(); j++) {
HSSFCell hssfCell = (HSSFCell)cellTempList.get(j);
//System.out.println("Cell Type:" + i + "," + j + " " + hssfCell.getCellType());
if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
stringCellValue[j] = hssfCell.getStringCellValue();
// logger.info(i + "," + j + "\t" + stringCellValue[j] + "\t");
} else if (hssfCell.getCellType() ==
HSSFCell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(hssfCell)) {
System.out.println(hssfCell.getDateCellValue());
Date date = new Date();
date = hssfCell.getDateCellValue();
SimpleDateFormat df =
new SimpleDateFormat("MM/dd/yyyy");
stringCellValue[j] = df.format(date);
} else {
stringCellValue[j] = new BigDecimal(hssfCell.getNumericCellValue()).toPlainString();
//logger.info("Number"+i+","+j+ "\t"+stringCellValue[j] + "\t");
}
}
}
AccountWS_AccountInsertChild_Input child =
new AccountWS_AccountInsertChild_Input();
AccountWS_AccountInsertChild_Output childs =
new AccountWS_AccountInsertChild_Output();
crmondemand.xml.account.Account[] accrels =
new crmondemand.xml.account.Account[1];
crmondemand.xml.account.Account accrel =
new crmondemand.xml.account.Account();
RelatedAccount[] relaccounts = new RelatedAccount[1];
RelatedAccount relaccount = new RelatedAccount();
logger.info("Inserting " + i + "Record: "+stringCellValue[0]);
relaccount.setRelationshipRole(stringCellValue[1]);
relaccount.setRelatedAccountId(stringCellValue[2]);
relaccount.setStartDate(stringCellValue[6]);
relaccount.setEndDate(stringCellValue[7]);
relaccount.setReverseRelationshipRole(stringCellValue[3]);
relaccount.setComments(stringCellValue[4]);
relaccount.setRelationshipStatus(stringCellValue[5]);
relaccounts[0] = relaccount;
accrel.setAccountId(stringCellValue[0]); //JDE Account ID
accrel.setListOfRelatedAccount(relaccounts);
accrels[0] = accrel;
child.setListOfAccount(accrels);
try {
childs = stub.accountInsertChild(child);
logger.info(i + "th Record Inserted");
++flag;
} catch (Exception e) {
logger.info("Network Error: Re-Authenticating" + e);
urlAddr = reauthentication(properties);
stub = (Default_BindingStub)service.getDefault(urlAddr);
childs = stub.accountInsertChild(child);
logger.info(i + "th Record Inserted in 2nd Attempt");
++flag;
}
//logger.info("Total No. Of Records Processed"+flag);
}
logger.info("Total No. Of Records Processed"+flag);
}
private void readExcelFile(URL urlAddr, String fileName,
Properties properties) throws ServiceException,
RemoteException,
MalformedURLException {
System.out.println("Reading Excel File");
/**
* Create a new instance for cellDataList
*/
List cellDataList = new ArrayList();
try {
/**
* Create a new instance for FileInputStream class
*/
FileInputStream fileInputStream = new FileInputStream(fileName);
/**
* Create a new instance for POIFSFileSystem class
*/
POIFSFileSystem fsFileSystem =
new POIFSFileSystem(fileInputStream);
/*
* Create a new instance for HSSFWorkBook Class
*/
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
HSSFSheet hssfSheet = workBook.getSheetAt(0);
/**
* Iterate the rows and cells of the spreadsheet
* to get all the datas.
*/
Iterator rowIterator = hssfSheet.rowIterator();
while (rowIterator.hasNext()) {
HSSFRow hssfRow = (HSSFRow)rowIterator.next();
Iterator iterator = hssfRow.cellIterator();
List cellTempList = new ArrayList();
while (iterator.hasNext()) {
HSSFCell hssfCell = (HSSFCell)iterator.next();
cellTempList.add(hssfCell);
}
cellDataList.add(cellTempList);
}
} catch (Exception e) {
e.printStackTrace();
}
/**
* Call the printToConsole method to print the cell data in the
* console.
*/
urlqueryWS1(urlAddr, cellDataList, properties);
}
private static String logon(String wsLocation, String userName,
String password, Properties properties) {
String sessionString = "FAIL";
int port =
Integer.parseInt(properties.getProperty("proxyport")); //Converting String Port Number to Integer.
try {
Proxy proxy =
new Proxy(Proxy.Type.HTTP, new InetSocketAddress(properties.getProperty("proxyhost"),
port));
// create an HTTPS connection to the On Demand webservices
URL wsURL = new URL(wsLocation + "?command=login");
HttpURLConnection wsConnection =
(HttpURLConnection)wsURL.openConnection(proxy);
// we don't want any caching to occur
wsConnection.setUseCaches(false);
// we want to send data to the server
// wsConnection.setDoOutput(true);
// set some http headers to indicate the username and passwod we are using to logon
wsConnection.setRequestProperty("UserName", userName);
wsConnection.setRequestProperty("Password", password);
wsConnection.setRequestMethod("GET");
// see if we got a successful response
if (wsConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// get the session id from the cookie setting
sessionString = getCookieFromHeaders(wsConnection);
}
} catch (Exception e) {
System.out.println("Logon Exception generated :: " + e);
}
return sessionString;
}
private static String getCookieFromHeaders(HttpURLConnection wsConnection) {
// debug code - display all the returned headers
String headerName;
String headerValue = "FAIL";
for (int i = 0; ; i++) {
headerName = wsConnection.getHeaderFieldKey(i);
if (headerName != null && headerName.equals("Set-Cookie")) {
// found the Set-Cookie header (code assumes only one cookie is being set)
headerValue = wsConnection.getHeaderField(i);
break;
}
}
// return the header value (FAIL string for not found)
return headerValue;
}
private static String getSessionId(String cookie) {
StringTokenizer st = new StringTokenizer(cookie, ";");
String jsessionid = st.nextToken();
st = new StringTokenizer(jsessionid, "=");
st.nextToken();
return st.nextToken();
}
public static void main(String[] args) throws IOException,
ServiceException {
String jsessionid, jsessionid_full;
String endpoint;
AxisProperties.setProperty("https.proxyHost", "172.25.9.240");
AxisProperties.setProperty("https.proxyPort", "2006");
System.setProperty("https.proxyHost", "172.25.9.240");
System.setProperty("https.proxyPort", "2006");
// System.setProperty("https.proxyHost", "145.247.13.164");
// System.setProperty("https.proxyPort", "3128");
Properties properties = new Properties();
properties.load(new FileInputStream("C:\\Users\\10608011\\Documents\\Account_Config.properties")); //Windows Path
System.setProperty("javax.net.ssl.trustStore","C:\\Oracle\\Middleware3\\jdk160_24\\jre\\lib\\security\\cacerts");
System.out.println("Logging In");
jsessionid_full =
logon("https://secure-ausomxapa.crmondemand.com/Services/Integration",
"############", "###########", properties);
System.out.println("Establishing " + jsessionid_full);
jsessionid = getSessionId(jsessionid_full);
System.out.println("Jsessionid: " + jsessionid);
endpoint =
"https://secure-ausomxapa.crmondemand.com/Services/Integration" +
";jsessionid=" + jsessionid;
URL urlAddr = new java.net.URL(endpoint);
String fileName =
"D:" + File.separator + "Test2.xls"; // Windows Path
// String fileName =File.separator + "u01"+File.separator +"CRM_DEV"+File.separator +
// "sofwaredepot"+File.separator +"PALS_200_11Feb2013.xls"; //Linux Path /u01/CRM_DEV/softwaredepot
// String fileName="PALS_200_11Feb2013.xls";
final long start = System.currentTimeMillis();
logger.info("Start Time:" + start);
new accrel1().readExcelFile(urlAddr, fileName, properties);
final long durationInMilliseconds = System.currentTimeMillis() - start;
System.out.println("Time(Min) for Data Upload: " +
durationInMilliseconds / 60000 + "mins.");
logger.info("Duration for Data Upload: " +
durationInMilliseconds / 60000 + "mins.");
}
}
Below is the code which i want to get the output of the names of the particular administrator number , administrator Emailid , but insted of that i am getting the output as : List of ---> com.demo.model.Administrator#91e143 with different numbers , basically i am new to java .Would you please help me in the Loop Iteration .
package com.demo.action;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.demo.model.Administrator;
import com.demo.model.AdministratorDAO;
import com.demo.model.AdministratorDemo;
import com.demo.model.JQueryDataTableParam;
import com.demo.model.JqueryDatatablesParamUtil;
public class AdministratorAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("in execute..");
JQueryDataTableParam param = JqueryDatatablesParamUtil
.getParam(request);
String txt2=request.getParameter("txt1");
//String select2=request.getParameter("select1");
//request.setAttribute("e", "select2");
//String select3=request.getParameter("select2");
//System.out.println("txtValue->"+e);
//System.out.println("txtValue->"+select2);
System.out.println("txtValue->"+txt2);
//String var = Administrator.isValidname(sData);
String sEcho = param.sEcho;
int iTotalRecords;
int iTotalDisplayRecords;
int start = param.iDisplayStart;
System.out.println("start" + start);
int last = param.iDisplayLength +param.iDisplayStart;
System.out.println("last" + last);
int sortColumnIndex = param.iSortColumnIndex;
System.out.println("sortColumnIndex" + sortColumnIndex);
String sortDirection = param.sSortDirection;
System.out.println("sortDirection" + sortDirection);
JSONArray data = new JSONArray();
iTotalRecords = AdministratorDemo.getAdminCount();
List<Administrator> Administrators = new LinkedList<Administrator>();
for (Administrator a : AdministratorDemo.getAdimistrators()) {
if (a.getAdministrator_nm() != null
&& a.getAdministrator_nm().toLowerCase()
.contains(param.sSearch.toLowerCase())
|| a.getAdmin_Email_ID() != null
&& a.getAdmin_Email_ID().toLowerCase()
.contains(param.sSearch.toLowerCase())
|| a.getAdmin_Fax_Phone_Num_Tx() != null
&& a.getAdmin_Fax_Phone_Num_Tx().toLowerCase()
.contains(param.sSearch.toLowerCase())) {
Administrators.add(a);
}
}
iTotalDisplayRecords = iTotalRecords;
if (Administrators.size() < param.iDisplayStart + param.iDisplayLength)
Administrators = Administrators.subList(param.iDisplayLength,
Administrators.size());
else
Administrators = Administrators.subList(param.iDisplayStart,
param.iDisplayStart + param.iDisplayLength);
System.out.println("End of the operations");
try {
JSONObject jsonresponse = new JSONObject();
jsonresponse.put("sEcho", sEcho);
jsonresponse.put("iTotalRecords", iTotalRecords);
jsonresponse.put("iTotalDisplayRecords", iTotalDisplayRecords);
JSONArray row = new JSONArray();
for(Iterator<Administrator> i = AdministratorDemo.getAdimistrators().iterator();i.hasNext();)
{
System.out.println(i.next());
}
jsonresponse.put("aaData", data);
response.setContentType("application/json");
response.getWriter().print(jsonresponse.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
response.setContentType("text/html");
response.getWriter().print(e1.getMessage());
}
System.out.println("In execute method.");
return null;
}
public String getXMLObject(HttpServletRequest request) {
return new java.util.Date().toString()
+ " sent by vasu from Date Action";
}
}
The result that you are seeing (com.demo.model.Administrator#91e143) is the default string representation of the Administrator object, more specifically, it's what is returned by the default toString() method inherited from Object
To print useful information, override public String toString() of Administrator
You need to override Object#toString() in your Administrator class.
This method can return any meaningful representation of the object you want, e.g:
#Override
public String toString() {
return "id = " + id + "email = " + email;
}
You're making a list of Administrators, where you want to make a list of Strings.
Alternatively (and probably better), if you can change the Administrator class, just implement the toString method in it, that will return the string you want to see on the screen.