URI Schema: Infinite command prompts are opening - java

I went through the following doc center and tried to create my own URI schema myDocs:
https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
Following is my Java program. It takes a command line argument and returns the URL in the browser.
import java.awt.Desktop;
import java.io.IOException;
public class URIOpen {
public static void main(String args[]) {
if (args.length == 0) {
return;
}
String uri = args[0];
try {
Desktop.getDesktop().browse(java.net.URI.create(uri));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
I updated the (Default) value field of the command key like below.
"C:\Program Files (x86)\Java\jdk1.8.0_102\bin\java" -cp "C:\Users\Krishna\Documents\Study\Miscellaneous\examples" "URIOpen" "%1"
When I try to run the command myDocs:http://google.com, I end up opening infinite command prompts.
The following is my URI schema entry structure in the registry. Any help on this?

Your solution end up opening infinite command prompts because of:
you registered the execution of the custom URIOpen class to be activated by the system when it has to deal with myDocs:'s scheme based URI;
when custom URIOpen class executes the line Desktop.getDesktop().browse(java.net.URI.create(uri)); the system will receive again an URI based on the same scheme ( myDocs: ) and it will activate again a new command to execute your class again and again and again ...
Probably you would like to change your code in someway like that:
try {
java.net.URI theURI = java.net.URI.create(uri);
// System.out.println(theURI.getScheme()); => myDocs
String uriBrowsablePart = theURI.getRawSchemeSpecificPart();
// System.out.println(uriBrowsablePart); => http://google.com
Desktop.getDesktop().browse(java.net.URI.create(uriBrowsablePart));
// the above statement will open default browser on http://google.com
} catch (IOException e) {
System.out.println(e.getMessage());
}
try replacing your try-catch block with my suggestion and see if it works as required.

Related

Error running RMI application in Visual Studio Code [duplicate]

I'm programming a simple rmi application, and I have a problem.
If I run the registry in the same directory, it works; but if I change the directory from which I run the registry, it does not.
The registry would work generically from another host, but only the change of directory stop his functionality.
I'm working on this problem by 3 days without solution, I change also every possible configuration of the codebase parameter but nothing.
I describe the situation and code with the directory:
fileserver.java :
`package testrmi2;
import java.rmi.*;
public interface fileserver extends Remote {
public void scrivifile(String nomefile, String arg) throws RemoteException;
}
`
fileserverimpl.java:
package testrmi2;
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class fileserverimpl extends UnicastRemoteObject implements fileserver{
public fileserverimpl() throws RemoteException {
super();
}
public void scrivifile(String nomefile, String arg) throws RemoteException {
try {
FileWriter myfile = new FileWriter(nomefile);
myfile.write(arg);
myfile.close(); }
catch (Exception e) {System.out.println(e);}
}
public static void main (String arg[]) {
try {
fileserverimpl s = new fileserverimpl();
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
String codebase = System.getProperty("classpath");
System.out.println("Trying to access code base: " + codebase+"\n\nuse is "+System.getProperty("useCodebaseOnly"));
Naming.rebind("//127.0.0.1:2005/fileserverimpl", s);
System.out.println("Server attivato.");
} catch (Exception e) {System.out.println("errore inizializzazione server\n\n"+e.getMessage()+"\n\n\n");
}}}
client.java:
package testrmi2;
import java.rmi.*;
import java.io.*;
public class client {
public static void main (String arg[]) {
fileserver myserver;
String nomefile=" ";
String testo=" ";
System.out.println("Scrivi il nome del file");
nomefile=ReadString();
System.out.println("Scrivi il testo");
testo=ReadString();
try {
myserver = (fileserver) Naming.lookup("//127.0.0.1:2005/fileserverimpl");
myserver.scrivifile(nomefile, testo);
} catch (Exception e) {System.out.println(e);}
}
public static String ReadString() {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(System.in));
String s=" ";
try{
s=stdIn.readLine();
}
catch(IOException e) {System.out.println(e.getMessage()); }
return s;
}
}
and the policy file is:
grant {
// Allow everything for now
permission java.security.AllPermission;
};
all this files are on the directory:
/Users/franco/Desktop/prova
to compiling it I goes in the /Users/franco/Desktop/prova directory and do in terminal :
javac -cp . -d . *.java
rmic rmic testrmi2.fileserverimpl
jar cvf testrmi2.jar testrmi2/fileserver.class testrmi2/fileserverimpl_Stub.class
after I run registry in another terminal with the following commands but in another directory:
export classpath=""
rmiregistry 2005 &
Finally I would to run the filesereveimpl.class goes with terminal in the /Users/franco/Desktop/prova directory and write :
java -classpath /Users/franco/Desktop/prova/ -Djava.rmi.server.codebase=file:/Users/franco/Desktop/prova/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
But the results are:
Trying to access code base: null
use is null
errore inizializzazione server
RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: testrmi2.fileserverimpl_Stub
I also try to public he jar on a local webserver xampp and try to run with the following:
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2/ -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
or with :
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
but I have the same results.
Try to set the classpath var before to execute the rmregistry:
export classpath="/Users/franco/Desktop/prova/"
rmiregistry 2005 &
There are three cases.
You got that exception in the server when exporting/constructing the remote object. Solution: run rmic to generate the stub.
You got it in the server when binding/rebinding. Solution: make the stub class available to the Registry's CLASSPATH, or run the Registry in the server JVM via LocateRegistry.createRegistry().
You got it in the client, in lookup(). Solution: make the stub class available to the client's CLASSPATH.
These also apply to the remote interface itself, and any application classes it depends on, and so on recursively until closure.
Solution for stubs to all three: take the measures outlined in the Javadoc preamble to UnicastRemoteObject, so you don't need a stub at all.

Crawling GitHub with JGit

I'm trying to crawl a GitHub Wiki with JGit.
When I try it with one URL, it worked perfectly fine. Then I tried it with another random URL and got an error.
Please see the extract of my code:
import java.io.File;
import java.io.IOException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
public class Main {
// with this URL I get an error
String url = "https://github.com/radiant/radiant.wiki.git";
// this URL works
// String url = "https://github.com/WardCunningham/Smallest-Federated-Wiki.wiki.git";
public static void main(String[] args) {
Main m = new Main();
m.jgitTest();
System.out.println("Done!");
}
public void jgitTest() {
try {
File localPath = File.createTempFile("TestGitRepository", "");
localPath.delete();
Git.cloneRepository().setURI(url).setDirectory(localPath).call();
} catch (IOException | GitAPIException e) {
System.err.println("excepton: " + e.getMessage());
e.printStackTrace();
}
}
}
This is the stack trace:
Exception in thread "main" org.eclipse.jgit.dircache.InvalidPathException: Invalid path (contains separator ':'): How-To:-Create-an-Extension.textile
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPathSegment(DirCacheCheckout.java:1243)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPathSegment(DirCacheCheckout.java:1225)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPath(DirCacheCheckout.java:1185)
at org.eclipse.jgit.dircache.DirCacheCheckout.processEntry(DirCacheCheckout.java:311)
at org.eclipse.jgit.dircache.DirCacheCheckout.prescanOneTree(DirCacheCheckout.java:290)
at org.eclipse.jgit.dircache.DirCacheCheckout.doCheckout(DirCacheCheckout.java:408)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkout(DirCacheCheckout.java:393)
at org.eclipse.jgit.api.CloneCommand.checkout(CloneCommand.java:236)
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:127)
at Main.jgitTest(Main.java:21)
at Main.main(Main.java:13)
If you visit the wiki page of the URL that doesn't work (https://github.com/radiant/radiant/wiki), you will find this page: How To: Create an Extension.
The title of this page is the cause of the error: Invalid path (contains separator ':'): How-To:-Create-an-Extension.textile.
I assume I need to escape all output.
I suppose you are on windows. You can't create a file on windows having the ":" in the name. JGit should handle it somehow, so I suppose this is a bug in JGit.
I had the same problem with pure git, and this answer helped me:
git config core.protectNTFS false

rmi java.lang.ClassNotFoundException: testrmi2.fileserverimpl_Stub

I'm programming a simple rmi application, and I have a problem.
If I run the registry in the same directory, it works; but if I change the directory from which I run the registry, it does not.
The registry would work generically from another host, but only the change of directory stop his functionality.
I'm working on this problem by 3 days without solution, I change also every possible configuration of the codebase parameter but nothing.
I describe the situation and code with the directory:
fileserver.java :
`package testrmi2;
import java.rmi.*;
public interface fileserver extends Remote {
public void scrivifile(String nomefile, String arg) throws RemoteException;
}
`
fileserverimpl.java:
package testrmi2;
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class fileserverimpl extends UnicastRemoteObject implements fileserver{
public fileserverimpl() throws RemoteException {
super();
}
public void scrivifile(String nomefile, String arg) throws RemoteException {
try {
FileWriter myfile = new FileWriter(nomefile);
myfile.write(arg);
myfile.close(); }
catch (Exception e) {System.out.println(e);}
}
public static void main (String arg[]) {
try {
fileserverimpl s = new fileserverimpl();
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
String codebase = System.getProperty("classpath");
System.out.println("Trying to access code base: " + codebase+"\n\nuse is "+System.getProperty("useCodebaseOnly"));
Naming.rebind("//127.0.0.1:2005/fileserverimpl", s);
System.out.println("Server attivato.");
} catch (Exception e) {System.out.println("errore inizializzazione server\n\n"+e.getMessage()+"\n\n\n");
}}}
client.java:
package testrmi2;
import java.rmi.*;
import java.io.*;
public class client {
public static void main (String arg[]) {
fileserver myserver;
String nomefile=" ";
String testo=" ";
System.out.println("Scrivi il nome del file");
nomefile=ReadString();
System.out.println("Scrivi il testo");
testo=ReadString();
try {
myserver = (fileserver) Naming.lookup("//127.0.0.1:2005/fileserverimpl");
myserver.scrivifile(nomefile, testo);
} catch (Exception e) {System.out.println(e);}
}
public static String ReadString() {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(System.in));
String s=" ";
try{
s=stdIn.readLine();
}
catch(IOException e) {System.out.println(e.getMessage()); }
return s;
}
}
and the policy file is:
grant {
// Allow everything for now
permission java.security.AllPermission;
};
all this files are on the directory:
/Users/franco/Desktop/prova
to compiling it I goes in the /Users/franco/Desktop/prova directory and do in terminal :
javac -cp . -d . *.java
rmic rmic testrmi2.fileserverimpl
jar cvf testrmi2.jar testrmi2/fileserver.class testrmi2/fileserverimpl_Stub.class
after I run registry in another terminal with the following commands but in another directory:
export classpath=""
rmiregistry 2005 &
Finally I would to run the filesereveimpl.class goes with terminal in the /Users/franco/Desktop/prova directory and write :
java -classpath /Users/franco/Desktop/prova/ -Djava.rmi.server.codebase=file:/Users/franco/Desktop/prova/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
But the results are:
Trying to access code base: null
use is null
errore inizializzazione server
RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: testrmi2.fileserverimpl_Stub
I also try to public he jar on a local webserver xampp and try to run with the following:
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2/ -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
or with :
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
but I have the same results.
Try to set the classpath var before to execute the rmregistry:
export classpath="/Users/franco/Desktop/prova/"
rmiregistry 2005 &
There are three cases.
You got that exception in the server when exporting/constructing the remote object. Solution: run rmic to generate the stub.
You got it in the server when binding/rebinding. Solution: make the stub class available to the Registry's CLASSPATH, or run the Registry in the server JVM via LocateRegistry.createRegistry().
You got it in the client, in lookup(). Solution: make the stub class available to the client's CLASSPATH.
These also apply to the remote interface itself, and any application classes it depends on, and so on recursively until closure.
Solution for stubs to all three: take the measures outlined in the Javadoc preamble to UnicastRemoteObject, so you don't need a stub at all.

Javamail - Why can't I get it to work?

I stole this code to test about emailing using java. Javamail is required, obviously. For some reason, I can't get javax.mail to implement. I downloaded the most recent javamail and put them in the jdk and jre lib folders, yet nothing changes. Please and thank you!
//A class which uses this file to send an email :
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
/**
* Simple demonstration of using the javax.mail API.
*
* Run from the command line. Please edit the implementation
* to use correct email addresses and host name.
*/
public final class Emailer {
public static void main( String... aArguments ){
Emailer emailer = new Emailer();
//the domains of these email addresses should be valid,
//or the example will fail:
emailer.sendEmail(
"sean_chili#yahoo.com", "clevelanm#sou.edu",
"Testing 1-2-3", "blah blah blah"
);
}
/**
* Send a single email.
*/
public void sendEmail(
String aFromEmailAddr, String aToEmailAddr,
String aSubject, String aBody
){
//Here, no Authenticator argument is used (it is null).
//Authenticators are used to prompt the user for user
//name and password.
Session session = Session.getDefaultInstance( fMailServerConfig, null );
MimeMessage message = new MimeMessage( session );
try {
//the "from" address may be set in code, or set in the
//config file under "mail.from" ; here, the latter style is used
//message.setFrom( new InternetAddress(aFromEmailAddr) );
message.addRecipient(
Message.RecipientType.TO, new InternetAddress(aToEmailAddr)
);
message.setSubject( aSubject );
message.setText( aBody );
Transport.send( message );
}
catch (MessagingException ex){
System.err.println("Cannot send email. " + ex);
}
}
/**
* Allows the config to be refreshed at runtime, instead of
* requiring a restart.
*/
public static void refreshConfig() {
fMailServerConfig.clear();
fetchConfig();
}
// PRIVATE //
private static Properties fMailServerConfig = new Properties();
static {
fetchConfig();
}
/**
* Open a specific text file containing mail server
* parameters, and populate a corresponding Properties object.
*/
private static void fetchConfig() {
InputStream input = null;
try {
//If possible, one should try to avoid hard-coding a path in this
//manner; in a web application, one should place such a file in
//WEB-INF, and access it using ServletContext.getResourceAsStream.
//Another alternative is Class.getResourceAsStream.
//This file contains the javax.mail config properties mentioned above.
input = new FileInputStream( "C:\\Temp\\MyMailServer.txt" );
fMailServerConfig.load( input );
}
catch ( IOException ex ){
System.err.println("Cannot open and load mail server properties file.");
}
finally {
try {
if ( input != null ) input.close();
}
catch ( IOException ex ){
System.err.println( "Cannot close mail server properties file." );
}
}
}
}
Just for completeness, here's the answer.
Your Eclipse is telling you
<Some Class> cannot be resolved to a type
This is usually an indication that your classpath is not correct. You said
I downloaded the most recent javamail and put them in the jdk and jre
lib folders, yet nothing changes
Don't do this. Take the javamail.jar and use it on your application Build Path. To do so, drag and drop the jar into your project, right-click it and select Build Path > Add to build path.

Java running in Oracle - the imported jars

I am trying to get a small java class to load into Oracle 11g so I can run it and call it from PL/SQL. I coded and compiled the class on my local machine in eclipse and it compiles fine. I packaged it up into a jar (with the other jar files it depends on in the jar). They I tried loading my jar into Oracle 11g. Everything loads in, unfortunately when it loads my custom java class, it stays invalid and when I try to compile it within Oracle it says it can't find references to the classes (the ones I had packaged in my jar with my class).
Is there some other sort of setting I need to configure?
Here is what my custom classes code looks like:
import com.flashline.registry.openapi.base.OpenAPIException;
import com.flashline.registry.openapi.entity.*;
import com.flashline.registry.openapi.service.v300.FlashlineRegistry;
import com.flashline.registry.openapi.service.v300.FlashlineRegistryServiceLocator;
import javax.xml.rpc.ServiceException;
import java.net.URL;
import java.rmi.RemoteException;
import org.apache.log4j.Logger;
import java.net.MalformedURLException;
public class AssetExtractor {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
static Logger LOG;
static AuthToken authToken = null;
static FlashlineRegistry repository = null;
static URL repoURL;
public static FlashlineRegistry getRepository()
{
if(repository == null)
try
{
try{
repoURL = new URL("https://myserver/oer/services/FlashlineRegistry");
}catch(MalformedURLException mue)
{
LOG.error(mue);
}
repository = (new FlashlineRegistryServiceLocator()).getFlashlineRegistry(repoURL);
LOG.debug((new StringBuilder()).append("Created repository at URL=").append(repoURL.toString()).toString());
}
catch(ServiceException e)
{
LOG.error(e, e);
}
return repository;
}
public static AuthToken getAuthToken()
{
if(authToken == null)
try
{
authToken = getRepository().authTokenCreate("user", "password");
LOG.debug("Created auth token.");
}
catch(OpenAPIException e)
{
LOG.error(e, e);
}
catch(RemoteException e)
{
LOG.error(e, e);
}
else
try
{
getRepository().authTokenValidate(authToken);
}
catch(OpenAPIException e)
{
LOG.info("Auth token was invalid. Recreating auth token");
authToken = null;
return getAuthToken();
}
catch(RemoteException re)
{
LOG.error("Remote exception occured during creation of suth token after determined to be invalid", re);
re.printStackTrace();
authToken = null;
}
return authToken;
}
public static String getAssetXML(String strAssetID)
{
String strAsset = null;
try
{
strAsset = getRepository().assetReadXml(getAuthToken(), Long.parseLong(strAssetID));
}
catch(OpenAPIException e)
{
e.printStackTrace();
}
catch(RemoteException e)
{
e.printStackTrace();
}
return strAsset;
}
}
And all the *.jar files for the imports are inside my AssetExtractor.jar
The command I've been using to load the jar into oracle is:
loadjava -v -f -resolve -resolver "((* OER) (* PUBLIC))" -user oer/***** AssetExtractor.jar
Any ideas would be helpful!
So it appears that if I do the following it solves nearly all my problems:
Edit the Oracle users' .profile to SET and EXPORT the CLASSPATH, PATH, LD_LIBRARY_PATH, ORACLE_HOME, JAVA_HOME with the correct paths
SQLPlus as sys as sysdba
EXEC dbms_java.grant_permission( 'OER', 'SYS:java.util.PropertyPermission', 'java.class.path', 'write' );
OS Commandline as oracle user:
loadjava –v –grant PUBLIC <jar> -user oer/****** for all jars
SQLPlus as OER user
DECLARE
v_classpath VARCHAR2(4000);
v_path VARCHAR2(4000);
BEGIN
v_classpath := DBMS_JAVA.set_property('java.class.path', '/opt/oracle/102/jdk/lib:/mnt/hgfs/vmshare/rex_lib/aler-axis- 1.2.1.jar:/mnt/hgfs/vmshare/rex_lib/aler-axis-jaxrpc-1.2.1.jar:/mnt/hgfs/vmshare/rex_lib/client.rex- 11.1.1.5.0.jar:/mnt/hgfs/vmshare/rex_lib/commons-httpclient-3.0rc2- flashline.jar:/mnt/hgfs/vmshare/rex_lib/log4j-1.2.8.jar');
v_path := DBMS_JAVA.set_property('java.path', '/opt/oracle/102/jdk/bin');
END;
/
alter java source "AssetExtractor" compile;
show errors
The only outstanding issue is that for some reason it still can't locate/resolve some of the Oracle OER classes (which should all be in the client.rex*.jar, I opened and saw them there. If I can solve this part then I'm good to go.

Categories

Resources