Here there is pseudocode about how to handle BLOB and CLOB in olingo jpa. I added the needed imports to the pseudocode:
package me;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import javax.sql.rowset.serial.SerialException;
import org.apache.olingo.odata2.jpa.processor.api.OnJPAWriteContent;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
public class OnDBWriteContent implements OnJPAWriteContent {
#Override
public Blob getJPABlob(byte[] binaryData) throws ODataJPARuntimeException {
try {
return new JDBCBlob(binaryData);
} catch (SerialException e) {
ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
} catch (SQLException e) {
ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return null;
}
#Override
public Clob getJPAClob(char[] characterData) throws ODataJPARuntimeException {
try {
return new JDBCClob(new String(characterData));
} catch (SQLException e) {
ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return null;
}
}
the only problem is I couldn't find any implementation for JDBCBlob and JDBCClob. Any suggestion about how can I implement them or use some classes?
If You are using MySQL it requires an additional ExceptionInterceptor along with the Blob Implementation. You can have a custom implementation of ExceptionInterceptor and use it to initialise the Blob field.
The code to achieve it would be as follows
import java.sql.Blob;
import java.sql.Clob;
import java.util.Properties;
import org.apache.olingo.odata2.jpa.processor.api.OnJPAWriteContent;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
import com.mysql.cj.exceptions.ExceptionInterceptor;
import com.mysql.cj.log.Log;
public class CustomOnJPAWriteContent implements OnJPAWriteContent {
#Override
public Blob getJPABlob(byte[] binaryData) throws ODataJPARuntimeException {
return new com.mysql.cj.jdbc.Blob(binaryData, exceptionInterceptor);
}
#Override
public Clob getJPAClob(char[] characterData) throws ODataJPARuntimeException {
return new com.mysql.cj.jdbc.Clob(new String(characterData), exceptionInterceptor);
}
ExceptionInterceptor exceptionInterceptor = new ExceptionInterceptor() {
#Override
public Exception interceptException(Exception sqlEx) {
// TODO Auto-generated method stub
return null;
}
#Override
public ExceptionInterceptor init(Properties props, Log log) {
// TODO Auto-generated method stub
return null;
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
};
}
Related
I need to create a TrxPlugin to verify if my Claim Line has a valid Product.
This is what I am trying to do:
import java.util.List;
import com.kernelsol.common.engine.Row;
import com.kernelsol.common.plugins.TrxPlugin;
public class MyTrxPlugin extends TrxPlugin {
#Override
public List<String> fields() throws Exception {
// TODO Auto-generated method stub
return null;
}
#Override
public Row augment(Row row) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
I get an unknown host error when I try to start an RMI server
here. The error is unknown host. Actually, I'm just a beginner in RMI and sockets programming in JAVA. Can you please provide me with some tutorials
concerning my problem.
My interface code:
package ApplicationServer;
import java.io.File;
import java.rmi.RemoteException;
import java.sql.ResultSet;
public interface Méthodes {
public String authentification(String login, String mdp) throws RemoteException;
public ResultSet selection(String requete) throws RemoteException;
public int miseAjour(String requete) throws RemoteException;
public String envoyerFichier(File fichier) throws RemoteException;
}
In this class I have all the methods that I need in my program:
package ApplicationServer;
import java.io.File;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Traitements extends UnicastRemoteObject implements Méthodes {
private Connection cnx;
private Statement stm;
private ResultSet rst;
private int rs;
public void setCnx(Connection cnx) {
this.cnx = cnx;
}
public void setStm(Statement stm) {
this.stm = stm;
}
public void setRst(ResultSet rst) {
this.rst = rst;
}
public void setRs(int rs) {
this.rs = rs;
}
protected Traitements() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
#Override
public String authentification(String login, String mdp) throws RemoteException {
// TODO Auto-generated method stub
try {
setCnx(null);
setStm(null);
setRst(null);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rst=stm.executeQuery("select md5('"+mdp+"');");
while(rst.next()){
mdp=rst.getString(1);
}
stm.clearBatch();
stm=cnx.createStatement();
setRst(null);
String Query = "select * from utilisateurs where login like '"+login+"' and motdepasse like '"+mdp+"';";
rst=stm.executeQuery(Query);
int id = 0;
String nm = null;
String prm = null;
while(rst.next()){
id = rst.getInt("id");
nm = rst.getString("nom");
prm = rst.getString("prenom");
}
if(id>0 && nm!=null && prm!=null){
return id+" "+nm+" "+prm;
}
}catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public ResultSet selection(String requete) throws RemoteException {
try{
setCnx(null);
setStm(null);
setRst(null);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rst=stm.executeQuery(requete);
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rst;
}
#Override
public int miseAjour(String requete) throws RemoteException {
try{
setCnx(null);
setStm(null);
setRs(0);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rs=stm.executeUpdate(requete);
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
#Override
public String envoyerFichier(File fichier) throws RemoteException {
// TODO Auto-generated method stub
return null;
}
}
This is the main class that runs the server:
package ApplicationServer;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int port=12345;
String url="rmi://serveur:"+port+"/reference";
LocateRegistry.createRegistry(port);
Traitements srv = new Traitements();
Naming.rebind(url, srv);
JOptionPane.showMessageDialog(null, "Serveur Lance :");
} catch (RemoteException | MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are supposed to replace serveur with a real hostname in that code.
However it's far better to use localhost in the RMI URL when binding. The Registry has to be local to the host anyway so there's no point in using anything else.
I'm trying Tomcat server with websocket. This is what I do:
I created 3 java files, copied from Tomcat examples. Please see the code below.
Then I build a war file and put it in webapps. But then I got this error message:
Info: WebSocket connection closed, Code: 1006
Do I miss any step to make a websocket on Tomcat?
Thanks.
1. ExamplesConfig.java
import java.util.HashSet;
import java.util.Set;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerApplicationConfig;
import javax.websocket.server.ServerEndpointConfig;
public class ExamplesConfig implements ServerApplicationConfig
{
#Override
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> scanned)
{
Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>();
System.out.println("ExamplesConfig ==========> getEndpointConfigs");
if (scanned.contains(EchoEndpoint.class))
{
result.add(ServerEndpointConfig.Builder.create(EchoEndpoint.class, "/websocket/echoProgrammatic").build());
}
return result;
}
#Override
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned)
{
// Deploy all WebSocket endpoints defined by annotations in the examples
// web application. Filter out all others to avoid issues when running
// tests on Gump
Set<Class<?>> results = new HashSet<Class<?>>();
for (Class<?> clazz : scanned)
{
if (clazz.getPackage().getName().startsWith("websocket."))
{
System.out.println("getAnnotatedEndpointClasses ===========>" + clazz);
results.add(clazz);
}
}
return results;
}
}
2. EchoEndpoint.java
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
public class EchoEndpoint extends Endpoint
{
#Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
RemoteEndpoint.Basic remoteEndpointBasic = session.getBasicRemote();
session.addMessageHandler(new EchoMessageHandlerText(remoteEndpointBasic));
session.addMessageHandler(new EchoMessageHandlerBinary(remoteEndpointBasic));
}
private static class EchoMessageHandlerText
implements MessageHandler.Partial<String> {
private final RemoteEndpoint.Basic remoteEndpointBasic;
private EchoMessageHandlerText(RemoteEndpoint.Basic remoteEndpointBasic) {
this.remoteEndpointBasic = remoteEndpointBasic;
}
#Override
public void onMessage(String message, boolean last) {
try {
if (remoteEndpointBasic != null) {
remoteEndpointBasic.sendText(message, last);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static class EchoMessageHandlerBinary
implements MessageHandler.Partial<ByteBuffer> {
private final RemoteEndpoint.Basic remoteEndpointBasic;
private EchoMessageHandlerBinary(RemoteEndpoint.Basic remoteEndpointBasic) {
this.remoteEndpointBasic = remoteEndpointBasic;
}
#Override
public void onMessage(ByteBuffer message, boolean last) {
try {
if (remoteEndpointBasic != null) {
remoteEndpointBasic.sendBinary(message, last);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
3. EchoAnnotation.java
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.websocket.OnMessage;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/websocket/echoAnnotation")
public class EchoAnnotation
{
#OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
try {
if (session.isOpen()) {
System.out.println("==========> this is my code");
session.getBasicRemote().sendText(msg, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
#OnMessage
public void echoBinaryMessage(Session session, ByteBuffer bb,
boolean last) {
try {
if (session.isOpen()) {
session.getBasicRemote().sendBinary(bb, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
/**
* Process a received pong. This is a NO-OP.
*
* #param pm Ignored.
*/
#OnMessage
public void echoPongMessage(PongMessage pm) {
// NO-OP
}
}
This example work's fine with Tomcat 7.0.x if you are running JVM version 1.7 and your web.xml use Servlet Specification version 3.0 according to Tomcat documentation.
You web.xml file should look like this :
<web-app version="3.0" ... >
I've just created my first library for an Android app I've built (I have code I need to reuse in the future across different apps) and I need to start a method I have in the main project from the library - however when I attempt to do so using the line:
com.project.sample.datasettings.UpdateActivity.success();
I'm getting a compiler error stating:
com.project.sample.UpdateActivity Cannot Be Resolved To A Type
SOURCE:
package com.project.sample.networktasklibrary;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import com.project.sample.networktasklibrary.XmlParserHandlerFinal;
import com.project.sample*;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
// this class performs the call to webservice in the background
public class NetworkTask extends AsyncTask<String, String, InputStream> {
private static final String LOG_TAG = "STDataSettings";
private static final String TAG_RESULT = "success";
private static InputStream stream;
#Override
protected InputStream doInBackground(String... params) {
try {
stream = getQueryResults("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stream;
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected static synchronized InputStream getQueryResults(
String urlQueryString) throws IOException, SAXException,
SSLException, SocketTimeoutException, Exception {
Bundle queryResults = new Bundle();
HttpsURLConnection https = null;
String uri = urlQueryString;
URL urlo = new URL(uri);
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(50000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
try {
https = (HttpsURLConnection) urlo.openConnection();
if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();
} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} finally {
}
String queryResult = null;
queryResults.putString(TAG_RESULT, queryResult);
return stream;
}
public InputStream getInputStream() {
return stream;
}
protected void onPostExecute(InputStream queryResults) {
// TODO Auto-generated method stub
super.onPostExecute(queryResults);
com.project.sample.datasettings.UpdateActivity.success();
}
}
UPDATE ACTIVITY CODE SAMPLE:
public void success() {
// to parse the response
try {
handler.getQueryResponse(stream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// to set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
}
Have you ever tried to add the library to the main project?
Right click the Project name -> Property -> Android -> Add. Then choose the library project.
I'm currently developing a system that loads classes via rmi. This system uses a classloader that communicates with the server in order to get the classes. The code is as follows.
Server:
import rocks.squareRock;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server extends UnicastRemoteObject
implements RemInterface {
public Server() throws RemoteException {
super();
}
public static void main(String argv[]) {
try {
Server serv = new Server();
Naming.rebind("RockServer", serv);
} catch (Throwable t) {
t.printStackTrace();
}
}
public Class<?> getRockClass(String type) {
if (type.equals("squareRock"))
return squareRock.class;
else
return null;
}
}
Client:
import rocks.Rock;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class Client {
RemInterface reminterface = null;
RockLoader rl = null;
public Client() {
String strName = "rmi://127.0.0.1/RockServer";
try {
reminterface = (RemInterface) Naming.lookup(strName);
rl = new RockLoader(reminterface);
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
loadRock("squareRock");
}
public Rock loadRock(String rock) {
try {
return (Rock) rl.loadClass(rock, false).newInstance();
} catch (Throwable t) {
return null;
}
}
}
Interface:
public interface RemInterface {
public Class<?> getRockClass(String type) throws RemoteException;
}
RockLoader:
import java.io.Serializable;
public class RockLoader extends ClassLoader implements Serializable {
private RemInterface reminterface = null;
public RockLoader(RemInterface reminterface) {
super();
this.reminterface = reminterface;
}
#Override
protected synchronized Class<?> loadClass(String className, boolean resolve)
throws ClassNotFoundException {
try {
return reminterface.getRockClass(className);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
The error I'm getting with this is (client-side):
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: SquareRock
This confuses me, as I'm not unmarshalling a SquareRock instance, but a Class. The only thought I have is that my classloader might be wrong.
It doesn't matter whether it's a Class or an object. The receiving JVM must have that class in its classpath, unless you are using the RMI codebase feature. What you are doing is basically trying to implement the codebase feature yourself. You can't do that.