Detect Language of String with com.cybozu.labs.langdetect package - java

I am searching for a small example code to detect the language of a string in JAVA. For that i downloaded and imported the following GitHub Project: https://github.com/shuyo/language-detection
Unfortunately I am struggling reading the API and I don't know how to get my code to work. Help is very appreciated. Heres what i have so far. I get a NullPointerException because i dont know how to initialize the Detector properly. ny help is kindly appreciated.
import com.cybozu.labs.langdetect.*;
public class DetectLanguage {
public static void main(String[] args) throws LangDetectException {
String sample = "Comment vous appelez-vous?"; // french demo text
Detector d = new Detector(null); // initialize detector
d.append(sample);
System.out.println(d.detect());
}
}

The Detector constructor signature is:
public Detector(DetectorFactory factory)
So take a look to the DetectorFactory, is a singleton without getInstance() method:
You should create your Detector like this:
Detector d = DetectorFactory.create();
But if you just doing that, is not enough...
com.cybozu.labs.langdetect.LangDetectException: need to load profiles
So the minimal and complete work example is:
try {
String sample = "Comment vous appelez-vous?";
// Prepare the profile before
DetectorFactory.loadProfile("/language-detection/profiles");
// Create the Detector
Detector d = DetectorFactory.create();
d.append(sample);
System.out.println(d.detect()); // Ouput: "fr"
} catch (LangDetectException e) {
e.printStackTrace();
}
And when you test these strings:
String sample = "Comment vous appelez-vous ?"; // "fr"
String sample = "Buongiorno come stai ?"; // "it"
String sample = "Hello how are you ?"; // "en"

Related

PlantUML graph generation in java Illegal acces error

I'm trying to make a simple graph using java but keep getting error
Code:
public class PlantUMLDemoMain {
public static void main(String[] args) throws Exception {
generateFromStringSource(new File("from-string.png"));
generateFromApi(new File("from-api.png"));
}
private static void generateFromApi(File file) throws IOException {
// 1. setup:
SequenceDiagramFactory f = new SequenceDiagramFactory();
SequenceDiagram diagram = f.createEmptyDiagram();
// 2. Build the diagram:
// "Bob -> Alice : hello"
// See net.sourceforge.plantuml.sequencediagram.command.CommandArrow#executeArg
Display bobD = Display.getWithNewlines("Bob");
Participant bobP = diagram.getOrCreateParticipant("Bob", bobD);
Display aliceD = Display.getWithNewlines("Alice");
Participant aliceP = diagram.getOrCreateParticipant("Alice", aliceD);
Display label = Display.getWithNewlines("hello");
ArrowConfiguration config = ArrowConfiguration.withDirectionNormal();
Message msg = new Message(bobP, aliceP, label, config, diagram.getNextMessageNumber());
checkState(null == diagram.addMessage(msg));
// 3. Output the diagram
// See net.sourceforge.plantuml.SourceStringReader#generateImage
diagram.makeDiagramReady();
checkState(1 == diagram.getNbImages());
try (OutputStream os = new FileOutputStream(file)) {
ImageData imageData = diagram.exportDiagram(os, 0, new FileFormatOption(FileFormat.PNG));
System.out.println("generateFromApi: " + diagram.getDescription().getDescription());
}
}
private static void generateFromStringSource(File file) throws IOException {
String source = "#startuml\n";
source += "Bob -> Alice : hello\n";
source += "#enduml\n";
StringBuffer stringBuffer = new StringBuffer();
SourceStringReader reader = new SourceStringReader(source);
// Write the first image to "png"
String desc = reader.generateImage(file);
// Return a null string if no generation
System.out.println("generateFromStringSource: " + desc);
}
}
Error: Exception in thread "main" java.lang.IllegalAccessError: class net.sourceforge.plantuml.png.PngIOMetadata (in unnamed module #0x9597028) cannot access class com.sun.imageio.plugins.png.PNGMetadata (in module java.desktop) because module java.desktop does not export com.sun.imageio.plugins.png to unnamed module #0x9597028
at net.sourceforge.plantuml.png.PngIOMetadata.writeWithMetadata(PngIOMetadata.java:60)
at net.sourceforge.plantuml.png.PngIO.write(PngIO.java:86)
at net.sourceforge.plantuml.png.PngIO.write(PngIO.java:80)
at net.sourceforge.plantuml.ugraphic.g2d.UGraphicG2d.writeImageTOBEMOVED(UGraphicG2d.java:219)
at net.sourceforge.plantuml.ugraphic.ImageBuilder.writeImageInternal(ImageBuilder.java:249)
at net.sourceforge.plantuml.ugraphic.ImageBuilder.writeImageTOBEMOVED(ImageBuilder.java:171)
at net.sourceforge.plantuml.sequencediagram.graphic.SequenceDiagramFileMakerPuma2.createOne(SequenceDiagramFileMakerPuma2.java:234)
at net.sourceforge.plantuml.sequencediagram.SequenceDiagram.exportDiagramInternal(SequenceDiagram.java:222)
at net.sourceforge.plantuml.UmlDiagram.exportDiagramNow(UmlDiagram.java:236)
at net.sourceforge.plantuml.AbstractPSystem.exportDiagram(AbstractPSystem.java:127)
at net.sourceforge.plantuml.SourceStringReader.generateImage(SourceStringReader.java:124)
at net.sourceforge.plantuml.SourceStringReader.generateImage(SourceStringReader.java:111)
at net.sourceforge.plantuml.SourceStringReader.generateImage(SourceStringReader.java:101)
at scr.graphviz.sk.PlantUMLDemoMain.generateFromStringSource(PlantUMLDemoMain.java:66)
at scr.graphviz.sk.PlantUMLDemoMain.main(PlantUMLDemoMain.java:23)
I found someone with similar problem and older version of plantuml worked for him. I have jar file of the older version but I'm not sure how to apply it. I tried inspecting the file and find out versions of libraries used and added maven dependencies for them but it didnt seem to work.
This is similar problem i mentioned https://github.com/plantuml/plantuml/issues/69

JDeveloper don't find SignerEPES having xades4j.jar

Im using #lgoncalves code to sign an XML with XADES4J EPES. But however jdeveloper don't find (SignerEPES) when I have the xades4j.jar on my classpath. I let you the image of my library and the code:
Project Library
private static void signBes(Document doc) throws XadesProfileResolutionException, XAdES4jException,
KeyStoreException {
//Document doc = getTestDocument();
Element elemToSign = doc.getDocumentElement();
SignaturePolicyInfoProvider policyInfoProvider = new SignaturePolicyInfoProvider()
{
#Override
public SignaturePolicyBase getSignaturePolicy()
{
return new SignaturePolicyIdentifierProperty(
new ObjectIdentifier("oid:/1.2.4.0.9.4.5", IdentifierType.OIDAsURI, "Policy description"),
new ByteArrayInputStream("Test policy input stream".getBytes()))
.withLocationUrl(""); //<- I really don't know what to put right here.
}
};
KeyingDataProvider kdp = new FileSystemKeyStoreKeyingDataProvider("pkcs12","C:/****/****.pfx",new FirstCertificateSelector(),new DirectPasswordProvider("****"),new DirectPasswordProvider("****"),true);
SignerEPES signer = (SignerEPES) new XadesEpesSigningProfile(kdp, policyInfoProvider).newSigner();
new Enveloped(signer).sign(elemToSign);
}
Link to the sample code on GitHub: https://github.com/luisgoncalves/xades4j/blob/master/src/test/java/xades4j/production/SignerEPESTest.java
EDIT:
I tried to force the import like (import xades4j.production.SignerEPES) but IDE says "Cannot be accessed from outside package" but really don't know what that means
SignerEPES is a package-private class, so application code won't be able to import it. The tests use it just to be sure that the proper type is being returned.
In your code you can just use XadesSigner as the type of your variable.

(opendj-ldap-sdk-2.6.0) bind method parameter - password char [ ]

I'm using opendj-ldap-sdk-2.6.0 jar library to search LDAP entry.
I am following the guide.
(https://backstage.forgerock.com/docs/opendj/2.6/dev-guide/#chap-using-the-sdk)
source code :
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.SearchScope;
import org.forgerock.opendj.ldap.responses.SearchResultEntry;
import org.forgerock.opendj.ldap.responses.SearchResultReference;
import org.forgerock.opendj.ldif.ConnectionEntryReader;
import org.forgerock.opendj.ldif.LDIFEntryWriter;
public class Test {
public static void main(String[] args) {
final LDIFEntryWriter writer = new LDIFEntryWriter(System.out);
Connection connection = null;
try {
final LDAPConnectionFactory factory = new LDAPConnectionFactory("localhost",389);
connection = factory.getConnection();
connection.bind("cn = Directory Mangager", password );
// password is just an example of the password.
final ConnectionEntryReader reader = connection.search("dc=example,dc=com", SearchScope.WHOLE_SUBTREE,"(uid=bjensen)","*");
while (reader.hasNext()) {
if(reader.isEntry()) {
final SearchResultEntry entry = reader.readEntry();
writer.writeComment("Search result entry:" + entry.getName().toString());
writer.writeEntry(entry);
} else {
final SearchResultReference ref = reader.readReference();
writer.writeComment("Search result reference:" + ref.getURIs().toString());
}
}
writer.flush();
} catch (final Exception e) {
System.err.println(e.getMessage());
} finally {
if (connection !=null) {
connection.close();
}
}
}
connection.bind("cn = Directory Mangager", password );
I'm getting a red line at this line under password because the parameter has to be 'char []'.
I captured Bind method in the below.
If my password is 1234, how can I change that into char [] type?
You're missing a call from factory to obtain a connection.
connection = factory.getConnection();
connection.bind("cn = Directory Mangager", password );
I figured it out.
connection.bind("cn=Directory Manager", "yourpassword".toCharArray() );
You can use toCharArray()
Also, as Ludovic Poitou mentioned above, you need to use
connection = factory.getConnection(); with the bind method.
The guide says if you are not using anonymous search, use the bind method, but you gotta use them both. (I misunderstood the guide)

How do you load images in a simple Java Project?

I have this structure in my project:
and my code is simply this:
public class ChapterTwo {
public static void main( String[] args )
{
try {
//File imageFile = new File("../../../../resources/lena.jpg");
String image = ChapterTwo.class.getResource("resources/lena.jpg").toExternalForm();
System.out.println(image);
//MBFImage image = ImageUtilities.readMBF(imageFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now this has been driving me crazy. how hard is it to make java locate an image in a simple directory structure?
I tried:
resources/lena.jpg
/resources/lena.jpg
../resources/lena.jpg
../../../../../resources/lena.jpg
nothing works. When I load the File and call exists() it always returns false. How do I load this image?
PS: My code is just testing code, but you get the idea, I was trying various stuff.
And it is com.foo not com
EDIT:
From the answers:
String imagePath = ChapterTwo.class.getClassLoader().getResource("lena.jpg").toExternalForm();
File imageFile = new File(imagePath);
System.out.println(imageFile.exists());
I get false ....
String image = ChapterTwo.class.getClassLoader().getResource("lena.jpg").getPath();

Sikuli click. (ScreenCaptureImage) in java

I am new to Sikuli and I wanted to
1. click windows button, and
2. type "Helloworld"
3. press Enter.
I have coded this and working Successfully in Sikuli IDE
click("1391583846712.png")
type("helloWorld")
wait(2)
type(Key.ENTER)
I tried to move this to Java ,
From the sikuli javadocs I have seen the following code, However it is not working in java sikuli-api-1.0.2 and latest version
import org.sikuli.script.*;
public class TestSikuli {
public static void main(String[] args) {
Screen s = new Screen();
try{
s.click("imgs/win-start.png", 0);
s.wait("imgs/spotlight-input.png");
s.type(null, "hello world\n", 0);
}
catch(FindFailed e){
e.printStackTrace();
}
}
}
It tells that Screen is an interface . Please tell me how to make it working in latest java sikuli-api. Please see that I am very new to Sikuli . Any suggestions will be highly appreciated. Also Please point me to the right sikuli java for begineers
new org.sikuli.api.DesktopScreenRegion() creates a ScreenRegion on the base full screen where you can click and seek your images
Your best bet to find how the new API is built is to look at the sources. There aren't a lot of classes to understand, fortunately.
The following Sikuli Java code should work:
import org.sikuli.script.*;
public class HelloWorld {
public static void main(String[] args){
Screen screen = new Screen();
try{
screen.click("D:\\Sikuli\\WinStartButton.png");
//"WinStartButton.png" must exist on the desired location you are using
//OR, instead of above line you can use the following:
screen.type(Key.WIN);
}
catch(FindFailed e){
e.getStackTrace();
}
screen.type("Hello World");
screen.type(Key.ENTER);
}
}
Try to use image locator in your code,
import org.sikuli.script.*;
import org.sikuli.basics.ImageLocator;
public class AuthLogin {
public static void main(String[] args) {
Screen s = new Screen();
ImageLocator.setBundlePath("path to img directory");
try{
s.click("win-start.png", 0);
s.wait("spotlight-input.png");
s.type(null, "hello world\n", 0);
}
catch(FindFailed e){
e.printStackTrace();
}
}
I think you should not use the absolute image path directly in the code.
I would create a class which contains the absolute paths as static constants.
Example :
instead of :
screen.click( "D:\\Sikuli\\WinStartButton.png");
you can do it like this :
public static final String IMAGE = "D:\\Sikuli\\WinStartButton.png";
screen.click(IMAGE);
Use Keydown and Keyup method for Enter key pressed
I have tried to organize the entire code. please let me know if its working.
Screen sikuli = new Screen();
String message = "hello world";
Pattern imgLocator = "";
if(sikuli.exists(imgLocator)!=null) {
sikuli.find(imgLocator);
sikuli.click(imgLocator);
sikuli.wait(2);
sikuli.type(imgLocator, message);
}
sikuli.keyDown(Key.ENTER);
sikuli.keyUp(Key.ENTER);

Categories

Resources