Creating new Signer throws XadesProfileResolutionException [Android Xades4j] - android

I have simple method getSigner which return new Signer (XadesSigner object).
The same method works on simple console java application but in Android throws XadesProfileResolutiionException.
Anyone help me?
private XadesSigner getSigner(String pfxPath, String password) throws SigningKeyException {
try {
KeyingDataProvider keyingProvider = getKeyingDataProvider(pfxPath, password);
XadesSigningProfile p = new XadesBesSigningProfile(keyingProvider);
return p.newSigner();
} catch (KeyStoreException ex) {
throw new SigningKeyException("Keystore Problem", ex);
} catch (SigningCertChainException ex) {
throw new SigningKeyException("Signer Cert Chain Problem", ex);
} catch (UnexpectedJCAException ex) {
throw new SigningKeyException("JCA Problem", ex);
} catch (XadesProfileResolutionException ex) {
throw new SigningKeyException("XadesProfileResolutionException Problem", ex);
}
}

Related

RFCOMM_CreateConnection - already opened state:2, RFC state:4, MCB state:5 - isConnected returns false and can't reconnect

I have the following code to connect to a Bluetooth device:
class BiSymConnectThread extends Thread {
BluetoothDevice mDevice;
public BiSymConnectThread(BluetoothDevice device) throws SecurityException, NoSuchMethodException {
mDevice = device;
UUID uuid = mDevice.getUuids()[0].getUuid();
try {
biSymSocket = mDevice.createInsecureRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e("Error", "Could not connect!");
}
}
public void cancel() {
interrupt();
try {
Log.i("Treadmill", "in connect thread cancellation");
if (biSymSocket != null) {
biSymSocket.close();
}
} catch (IOException localIOException) {
Log.e("Treadmill", "exception + " + localIOException.getMessage());
}
}
public void run() {
try {
if (biSymSocket.isConnected()) {
biSymSocket.close();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new IOException();
}
}
biSymSocket.connect();
eventHandler.obtainMessage(MESSAGE_CONNECT_BISYM, 0, 0, "").sendToTarget();
BluetoothConnectionService.setSocket(biSymSocket);
BluetoothConnectionService.sendMessage(biSymSocket, "S");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e("Error", "InterruptedException: " + e.getMessage(), e);
throw new IOException();
}
} catch (IOException e) {
Log.e("Error", "IOException: " + e.getMessage(), e);
eventHandler.obtainMessage(MESSAGE_ERRORCONNECT_BISYM, 0, 0, "").sendToTarget();
if (biSymSocket != null) {
try {
biSymSocket.close();
} catch (IOException e1) {
Log.e("Error", "Can't close socket!");
}
}
}
synchronized (this) {
biSymConnectThread = null;
}
}
}
If I attempt to reconnect to the device, I get the following error:
RFCOMM_CreateConnection - already opened state:2, RFC state:4, MCB state:5
In the other question asking about this error, someone mentions the isConnected() method. However, in my case, isConnected() returns false and the connection still fails.
Does anyone know what is the problem here? It appears this is some obscure error, since there doesn't seem to be anything on the web about this.

How to fix Not implemented error..(this code will be throw the error)

It's my code:
try {
System.out.println("Cloudinaryyyy 0000 :");
Map result = cloudinary.api().resources(ObjectUtils.asMap("resource_type","raw"));
System.out.println("Cloudinaryyyy :"+result);
}
catch (IOException e) {
Log.d("DownloadManager", "Error:" + e);
}
catch (NetworkOnMainThreadException e) {
System.out.println("Error 3" + e);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error 3" + e);
}
In the cloudinary it throws the exception.
Did you remember to configure the Cloudinary object?
Map config = new HashMap();
config.put("cloud_name", "n07t21i7");
config.put("api_key", "123456789012345");
config.put("api_secret", "abcdeghijklmnopqrstuvwxyz12");
Cloudinary cloudinary = new Cloudinary(config);
Also, you can try to run the sample projects on https://github.com/cloudinary/cloudinary_java

Override/Extend the default http protocol Handler on Android

I've used protocol handlers in the past overriding the default http handler and creating my own custom handlers and I was thinking the approach still works on Android. I am trying to override any http or https URL requested by my Android app and pass it to a custom handler under certain situations. However I still would like to access web resources in other cases. How do I retrieve the default http/https protocol handlers? I'm trying something like the following to load the default handler before putting my override in place:
static URLStreamHandler handler;
static {
Class<?> handlerClass;
try {
handlerClass = Class.forName("net.www.protocol.http.Handler");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Error loading clas for default http handler.", e);
}
Object handlerInstance;
try {
handlerInstance = handlerClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Error instantiating default http handler.", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Error accessing default http handler.", e);
}
if (! (handlerInstance instanceof URLStreamHandler)) {
throw new RuntimeException("Wrong class type, " + handlerInstance.getClass().getName());
} else {
handler = (URLStreamHandler) handlerInstance;
}
}
My override logic works as follows:
URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
public URLStreamHandler createURLStreamHandler(String protocol) {
URLStreamHandler urlStreamHandler = new URLStreamHandler() {
protected URLConnection openConnection(URL url) throws IOException {
return new URLConnection(url) {
public void connect() throws IOException {
Log.i(getClass().getName(), "Global URL override!!! URL load requested " + url);
}
};
}
};
return shouldHandleURL(url) ? urlStreamHandler : handler;
}
});
The override works but I cannot load the default in cases where I want normal URL connection behavior. Trying to clear my StreamHandlerFactory as follows:
URL.setURLStreamHandlerFactory(null);
Throws an error:
java.lang.Error: Factory already set
at java.net.URL.setURLStreamHandlerFactory(URL.java:112)
The only way I've been able to resolve my issue is by setting the streamHandler and StramHandler factory to null using reflection through the private fields. It's yucky but it works. This is my temporary solution (I was hoping for something less yucky):
private static class APIURLStreamHandlerFactory implements URLStreamHandlerFactory {
public URLStreamHandler createURLStreamHandler(String protocol) {
return new URLStreamHandler() {
protected URLConnection openConnection(URL url) throws IOException {
if (! shouldHandle(url)) {
Field streamHandlerMapField = getURLPrivateField("streamHandlers");
try { Map handlerMap = (Map) streamHandlerMapField.get(url); handlerMap.clear(); }
catch (IllegalAccessException e) { throw new Error("Could not access private field streamHandler",e); }
unregisterSelf();
invokeInstancePrivateMethod(url, "setupStreamHandler");
URLStreamHandler originalHandler = getPrivateUrlStreamHandler(url);
Method openConnectionMethod = getPrivateMethod(originalHandler, "openConnection", URL.class);
openConnectionMethod.setAccessible(true);
try { return (URLConnection) openConnectionMethod.invoke(originalHandler, url); }
catch (IllegalAccessException e) { throw new Error("Could not access openConnection on URL", e); }
catch (InvocationTargetException e) { throw new RuntimeException("Exception while invoking openConnection on URL", e); }
finally { registerSelf(); }
}
return new APIURLConnection(url, registeredServiceRouter);
}
};
}
private static Method getPrivateMethod(Object object, String methodName, Class... parameterTypes) {
try { return object.getClass().getDeclaredMethod(methodName, parameterTypes); }
catch (NoSuchMethodException e) { throw new Error("Could not find method " + methodName, e); }
}
private static boolean shouldHandle(URL url) {
//Logic to decide which requests to handle
}
private static URLStreamHandler getPrivateUrlStreamHandler(URL url) {
URLStreamHandler originalHandler;
try { originalHandler = (URLStreamHandler) getURLPrivateField("streamHandler").get(url); }
catch (IllegalAccessException e) { throw new Error("Could not access streamHandler field on URL",e); }
return originalHandler;
}
private static Object invokeInstancePrivateMethod(Object objectInstance, String methodName) {
try {
Method urlPrivateMethod = getURLPrivateMethod(methodName);
urlPrivateMethod.setAccessible(true);
return urlPrivateMethod.invoke(objectInstance);
}
catch (IllegalAccessException e) { throw new Error("Cannot access metehod " + methodName + " on instance type " + objectInstance.getClass().getName(), e); }
catch (InvocationTargetException e) { throw new RuntimeException("Exception while invoking method " + methodName + " on type " + objectInstance.getClass().getName(),e); }
}
private static Method getURLPrivateMethod(String methodName) {
try { return URL.class.getDeclaredMethod(methodName); }
catch (NoSuchMethodException e) { throw new Error("Method " + methodName + " not found on class URL"); }
}
#TargetApi(Build.VERSION_CODES.KITKAT)
private static void resetStreamHandlerFactory() {
try { getURLPrivateField("streamHandlerFactory").set(null, null); }
catch (IllegalAccessException e) { throw new Error("Could not access factory field on URL class: {}", e); }
}
#NonNull
private static Field getURLPrivateField(String field) {
final Field privateField;
try { privateField = URL.class.getDeclaredField(field); }
catch (NoSuchFieldException e) { throw new Error("No such field " + field + " in class URL"); }
privateField.setAccessible(true);
return privateField;
}
}
I found this in java.net.URL
else if (protocol.equals("http")) {
try {
String name = "com.android.okhttp.HttpHandler";
streamHandler = (URLStreamHandler) Class.forName(name).newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
}
It would appear com.android.okhttp.HttpHandler would be the stream handler you would want to return for default behaviour
Here are the other defaults:
if (protocol.equals("file")) {
streamHandler = new FileHandler();
} else if (protocol.equals("ftp")) {
streamHandler = new FtpHandler();
} else if (protocol.equals("http")) {
try {
String name = "com.android.okhttp.HttpHandler";
streamHandler = (URLStreamHandler) Class.forName(name).newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
} else if (protocol.equals("https")) {
try {
String name = "com.android.okhttp.HttpsHandler";
streamHandler = (URLStreamHandler) Class.forName(name).newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
} else if (protocol.equals("jar")) {
streamHandler = new JarHandler();
}
if (streamHandler != null) {
streamHandlers.put(protocol, streamHandler);
}
PS: I've been trying to solve this for the past couple hours and your post was the only one I could find wanting to do a similar thing. Hopefully this helps.

How to get message from Exception?

Following is my piece of code:\
public void LoadProjectFile(String Filename) throws Exception
{
// m_Renderer.m_Project=new Project();
refresh_project();
m_Renderer.m_SelectedProjectPath = Filename;
try {
m_Renderer.m_Project.load_file(Filename);
}
catch (Exception e)
{
//Exception a = e.getMessage();
String a= e.getMessage();
throw new Exception(a);
}
//AppFuncs.m_GisProject=m_Renderer.m_Project;
}
try
{
Map.this.mGLView.LoadProjectFile(AppFuncs.g_path);
Map.this.mGLView.requestRender();
}
catch (Exception e)
{
br=1;
b=e.getMessage();
}
Load project file throws an exception which i recieve in Map class. This exception contains message: Java.lang.exception: java.lang.exception: file not found.
I want to show only "File not found" message. so how should i get this message out from an exception?
Catch all types of exceptions instead of base Exception:
try {
m_Renderer.m_Project.load_file(Filename);
}
catch (FileNotFoundException e)
{
String a= "File not found"
throw new Exception(a);
}
catch (SomeOhterException e){
String a= "Some other message"
throw new Exception(a);
}
//at the end, but it shouldn't be necessary
catch (Exception e){
String a= "Something happend we don't know what"
throw new Exception(a);
}
Shortly: Use different class for different exception to show correct information rahter than using exception message.
Just catch the FileNotFoundException instead of an Exception.
For example:
try {
//whatever
} catch (FileNotFoundException e) {
System.out.println("File not found");
}

exception while trying to receive a file from server

i run some code to connect to a server, send it an Object and then receive another Object.
while running this on my Android enulator (v2.2) i get - java.net.SocketException: Socket is closed
the connection to the server is successful and i'm able to send the object but when i'm trying to do socket.getInputStream() it throws the exception
this is my connector class:
public class ConnectionToServer {
UserProblemRequest sentProblem;
Problem responseProblem;
Socket socket;
public ConnectionToServer(){
sentProblem = null;
responseProblem = null;
socket = null;
}
public void connect(){
try {
Log.d(TAG, "Connecting...");
socket = new Socket(Utils.SERVER_IP, Utils.SERVER_PORT);
Log.d(TAG, "SUCCESS: Connected!");
} catch (UnknownHostException e) {
Log.d(TAG, "ERROR: Falied to connect! (UnknownHostException)");
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "ERROR: Falied to connect! (IOException)");
e.printStackTrace();
}
}
public void setProblemFromByteArray(byte[] data, boolean isFile){
sentProblem = new UserProblemRequest();
sentProblem.fileBArray = data.clone();
if (isFile){
sentProblem.requestType = Utils.requestType_IMAGE;
}
else {
sentProblem.requestType = Utils.RequestType_STRING;
}
}
public void sendProblem(){
ObjectOutputStream os;
try {
os = new ObjectOutputStream(socket.getOutputStream());
Log.d(TAG, "Sending file to server...");
os.writeObject(sentProblem);
os.flush();
os.close();
} catch (IOException e) {
Log.d(TAG, "ERROR: Falied to send file to server!");
e.printStackTrace();
}
Log.d(TAG, "SUCCESS: File sent to server!");
}
public void closeConnection(){
try {
socket.close();
} catch (IOException e) {
Log.d(TAG, "failed to close socket");
e.printStackTrace();
}
}
public Problem reciveResponseFromServer(){
ObjectInputStream ois;
try {
ois = new ObjectInputStream(socket.getInputStream());
responseProblem = (Problem) ois.readObject();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return responseProblem;
}
}
and i use this code to run it:
ConnectionToServer serverConnection = new ConnectionToServer();
serverConnection.connect();
serverConnection.setProblemFromByteArray(temp_data, true);
serverConnection.sendProblem();
Problem responseProblem = serverConnection.reciveResponseFromServer();
serverConnection.closeConnection();
any ideas?
Does closing the ObjectOutputStream() in sendProblem() wind up closing the underlying socket so that when you getInputStream() in reciveResponseFromServer() the socket is already closed?

Categories

Resources