Am I not sending an array of commands, "hello world ", to exec() correctly?
correct output, hello world:
thufir#mordor:~$
thufir#mordor:~$ java -jar NetBeansProjects/HelloExec/dist/HelloExec.jar
Apr 05, 2016 7:11:23 AM net.bounceme.mordor.telnet.Main run
INFO: starting..
Apr 05, 2016 7:11:23 AM net.bounceme.mordor.telnet.Telnet <init>
INFO: connecting..
Apr 05, 2016 7:11:23 AM net.bounceme.mordor.telnet.Telnet connect
INFO: connect..
Apr 05, 2016 7:11:23 AM net.bounceme.mordor.telnet.Telnet connect
INFO: [echo hello 1, echo hello 2, echo hello 3]
Apr 05, 2016 7:11:24 AM net.bounceme.mordor.telnet.Telnet connect
INFO: did process..
Apr 05, 2016 7:11:24 AM net.bounceme.mordor.telnet.Telnet connect
INFO: trying..
hello 1
Apr 05, 2016 7:11:24 AM net.bounceme.mordor.telnet.Telnet read
SEVERE: exiting.. 0
thufir#mordor:~$
code:
package net.bounceme.mordor.telnet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.lang.System.out;
public class Telnet {
private final static Logger LOG = Logger.getLogger(Telnet.class.getName());
public Telnet() {
LOG.info("connecting..");
}
private List<String> getCommand() {
List<String> commands = new ArrayList<>();
commands.add("echo hello 1");
commands.add("echo hello 2");
commands.add("echo hello 3");
return commands;
}
private void read(Process process) throws IOException, InterruptedException {
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
out.println(line);
}
int exitVal = process.waitFor();
LOG.log(Level.SEVERE, "exiting.. {0}", exitVal);
}
private void connect() {
LOG.info("connect..");
Runtime runtime = Runtime.getRuntime();
List<String> cmds = getCommand();
String[] cmdArray = cmds.toArray(new String[cmds.size()]);
String command = cmdArray[0];
LOG.info(cmds.toString());
Process process = null;
try {
process = runtime.exec(command);
} catch (IOException ex) {
LOG.severe("process wrong");
Logger.getLogger(Telnet.class.getName()).log(Level.SEVERE, null, ex);
}
LOG.info("did process..");
LOG.info("trying..");
try {
read(process);
} catch (IOException | InterruptedException ex) {
LOG.severe("read wrong");
Logger.getLogger(Telnet.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void tryConnect() {
connect();
}
}
crash:
thufir#mordor:~$
thufir#mordor:~$ java -jar NetBeansProjects/HelloExec/dist/HelloExec.jar
Apr 05, 2016 7:12:32 AM net.bounceme.mordor.telnet.Main run
INFO: starting..
Apr 05, 2016 7:12:32 AM net.bounceme.mordor.telnet.Telnet <init>
INFO: connecting..
Apr 05, 2016 7:12:32 AM net.bounceme.mordor.telnet.Telnet connect
INFO: connect..
Apr 05, 2016 7:12:32 AM net.bounceme.mordor.telnet.Telnet connect
INFO: [echo hello 1, echo hello 2, echo hello 3]
Apr 05, 2016 7:12:32 AM net.bounceme.mordor.telnet.Telnet connect
SEVERE: process wrong
Apr 05, 2016 7:12:32 AM net.bounceme.mordor.telnet.Telnet connect
SEVERE: null
java.io.IOException: Cannot run program "echo hello 1": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at java.lang.Runtime.exec(Runtime.java:620)
at java.lang.Runtime.exec(Runtime.java:485)
at net.bounceme.mordor.telnet.Telnet.connect(Telnet.java:48)
at net.bounceme.mordor.telnet.Telnet.tryConnect(Telnet.java:66)
at net.bounceme.mordor.telnet.Main.run(Main.java:17)
at net.bounceme.mordor.telnet.Main.main(Main.java:11)
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:248)
at java.lang.ProcessImpl.start(ProcessImpl.java:134)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 6 more
Apr 05, 2016 7:12:32 AM net.bounceme.mordor.telnet.Telnet connect
INFO: did process..
Apr 05, 2016 7:12:32 AM net.bounceme.mordor.telnet.Telnet connect
INFO: trying..
Exception in thread "main" java.lang.NullPointerException
at net.bounceme.mordor.telnet.Telnet.read(Telnet.java:30)
at net.bounceme.mordor.telnet.Telnet.connect(Telnet.java:57)
at net.bounceme.mordor.telnet.Telnet.tryConnect(Telnet.java:66)
at net.bounceme.mordor.telnet.Main.run(Main.java:17)
at net.bounceme.mordor.telnet.Main.main(Main.java:11)
thufir#mordor:~$
when trying to use cmdArray:
process = runtime.exec(cmdArray);
The reasoning:
...it's because when exec is given a single string, it parses it first
(in a way that we don't like). In contrast, when exec is given a
string array, it simply passes it on to the operating system without
parsing it.
https://stackoverflow.com/a/19383655/262852
Related
I have a Vaadin web application, that is deploying OK.
BUT when I add a FolderWatcher service as a Listener using
#WebListener
The application fails to deploy, but it starts the thread if I disable the annotation #WebListener the application does deploy.
Folder watcher class
public class FolderWatchService {
private final WatchService watcher;
private final Map<WatchKey, Path> keys;
private static final Logger LOGGER = Logger.getLogger( FolderWatchService.class.getName() );
/**
* Creates a WatchService and registers the given directory
*/
public FolderWatchService(Path dir) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey, Path>();
walkAndRegisterDirectories(dir);
}
/**
* Register the given directory with the WatchService; This function will be called by FileVisitor
*/
private void registerDirectory(Path dir) throws IOException
{
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
keys.put(key, dir);
}
/**
* Register the given directory, and all its sub-directories, with the WatchService.
*/
private void walkAndRegisterDirectories(final Path start) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
registerDirectory(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* Process all events for keys queued to the watcher
*/
public void processEvents() {
for (;;) {
// wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
LOGGER.log( Level.FINE, "WatchKey not recognized!!", "" );
System.err.println("WatchKey not recognized!!");
continue;
}
for (WatchEvent<?> event : key.pollEvents()) {
#SuppressWarnings("rawtypes")
WatchEvent.Kind kind = event.kind();
// Context for directory entry event is the file name of entry
#SuppressWarnings("unchecked")
Path name = ((WatchEvent<Path>)event).context();
Path child = dir.resolve(name);
String fileContent;
// if directory is created, and watching recursively, then register it and its sub-directories
if (kind == ENTRY_CREATE) {
System.out.println("File created");
LOGGER.log( Level.FINER, "New File created", "" );
readFile(child.toString());
}
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}
private static void readFile(String pathname){
try {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
String fileContent = fileContents.toString();
System.out.println("File name: "+FilenameUtils.getBaseName(pathname));
LOGGER.log( Level.FINER, "File name: "+FilenameUtils.getBaseName(pathname), "" );
String title = "File Title: "+fileContent.substring(0, 64).trim().lastIndexOf(System.getProperty("line.separator"))+"...";
} finally {
scanner.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ContextLister class
#WebListener
public class ContextListener implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("#### Folder watcher service destroyed");
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("#### Folder watcher service initialized");
Path dir = Paths.get(PropertiesCache.getInstance().getProperty("file_input_location"));
try {
new FolderWatchService(dir).processEvents();
System.out.println("#### Folder watcher service started");
} catch (IOException e) {
System.out.println("#### Folder watcher Problem");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT: Added what is printed out by logs
Jun 26, 2017 10:56:31 PM org.apache.catalina.core.AprLifecycleListener
lifecycleEvent
INFO: Loaded APR based Apache Tomcat Native library 1.2.12 using APR version
1.5.2.
Jun 26, 2017 10:56:31 PM org.apache.catalina.core.AprLifecycleListener
lifecycleEvent
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters
[false], random [true].
Jun 26, 2017 10:56:31 PM org.apache.catalina.core.AprLifecycleListener
lifecycleEvent
INFO: APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
Jun 26, 2017 10:56:31 PM org.apache.catalina.core.AprLifecycleListener
initializeSSL
INFO: OpenSSL successfully initialized (OpenSSL 1.0.2k 26 Jan 2017)
Jun 26, 2017 10:56:31 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jun 26, 2017 10:56:31 PM org.apache.tomcat.util.net.NioSelectorPool
getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 26, 2017 10:56:31 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Jun 26, 2017 10:56:31 PM org.apache.tomcat.util.net.NioSelectorPool
getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 26, 2017 10:56:31 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1392 ms
Jun 26, 2017 10:56:31 PM org.apache.catalina.core.StandardService
startInternal
INFO: Starting service Catalina
Jun 26, 2017 10:56:31 PM org.apache.catalina.core.StandardEngine
startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.5.12
Jun 26, 2017 10:56:32 PM org.apache.catalina.util.SessionIdGeneratorBase
createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using
[SHA1PRNG] took [126] milliseconds.
Jun 26, 2017 10:56:40 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable
debug logging for this logger for a complete list of JARs that were scanned
but no TLDs were found in them. Skipping unneeded JARs during scanning can
improve startup time and JSP compilation time.
#### Folder watcher service initialized
The last line here is println from ContextLister, and the applic
What am I doing wrong here?
It seems that the listener implementation is blocking at new FolderWatchService(dir).processEvents();. You should run event processing in another thread (ie using a ExecutorService to submit processEvents job and maybe cancel/shutdown in contextDestroyed)
I have done a video player using vlcj library of vlc media player.
When i run the code the frame open fine but the video dosen't play.
Here is my code to do that..
public class Test {
public static void main (String[] args) {
JFrame f = new JFrame();
f.setLocation(100,100);
f.setSize(1000,600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
Canvas c = new Canvas();
c.setBackground(Color.black);
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(c);
f.add(p);
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
MediaPlayerFactory mpf = new MediaPlayerFactory();
EmbeddedMediaPlayer emp = mpf.newEmbeddedMediaPlayer(new DefaultFullScreenStrategy(f));
emp.setVideoSurface(mpf.newVideoSurface(c));
//emp.toggleFullScreen();
emp.setEnableMouseInputHandling(false);
emp.setEnableKeyInputHandling(false);
String file= "C:\\!temp\\v.mp4";
emp.prepareMedia(file);
}
}
This is on my console:
nov. 03, 2015 12:04:40 DU uk.co.caprica.vlcj.Info <init>
INFO: vlcj: 3.8.0
nov. 03, 2015 12:04:40 DU uk.co.caprica.vlcj.Info <init>
INFO: java: 1.8.0_65 Oracle Corporation
nov. 03, 2015 12:04:40 DU uk.co.caprica.vlcj.Info <init>
INFO: java home: C:\Program Files\Java\jre1.8.0_65
nov. 03, 2015 12:04:40 DU uk.co.caprica.vlcj.Info <init>
INFO: os: Windows 8.1 6.3 amd64
nov. 03, 2015 12:04:40 DU uk.co.caprica.vlcj.binding.LibVlcFactory create
INFO: vlc: 2.2.1 Terry Pratchett (Weatherwax), changeset 2.2.1-0-ga425c42
nov. 03, 2015 12:04:40 DU uk.co.caprica.vlcj.binding.LibVlcFactory create
INFO: libvlc: C:\Program Files\VideoLAN\VLC\libvlc.dll
The prepareMedia() method just gets the media 'ready', it does not actually play it.
So use play() after you prepare it, or miss prepare out and just use playMedia(...) instead.
And as per the other comment, are you sure "!temp" is correct?
I would like to initiate a call from extension number to another in LAN network. I have done this task through FreePBX GUI. Now I am trying to execute this task by using Asterisk AMI with Java code. Below Java code shows some exception while in debugging.
import java.io.IOException;
import org.asteriskjava.manager.AuthenticationFailedException;
import org.asteriskjava.manager.ManagerConnection;
import org.asteriskjava.manager.ManagerConnectionFactory;
import org.asteriskjava.manager.TimeoutException;
import org.asteriskjava.manager.action.OriginateAction;
import org.asteriskjava.manager.response.ManagerResponse;
public class HelloManager
{
private ManagerConnection managerConnection;
public HelloManager() throws IOException
{
ManagerConnectionFactory factory = new ManagerConnectionFactory(
"192.168.68.173", "admin", "admin");
this.managerConnection = factory.createManagerConnection();
}
public void run() throws IOException, AuthenticationFailedException,
TimeoutException
{
OriginateAction originateAction;
ManagerResponse originateResponse;
originateAction = new OriginateAction();
originateAction.setChannel("SIP/1010");
originateAction.setContext("default");
originateAction.setExten("2020");
originateAction.setPriority(new Integer(1));
originateAction.setTimeout(new Integer(30000));
// connect to Asterisk and log in
managerConnection.login();
// send the originate action and wait for a maximum of 30 seconds for Asterisk
// to send a reply
originateResponse = managerConnection.sendAction(originateAction, 30000);
// print out whether the originate succeeded or not
System.out.println("Enter Response="+originateResponse.getResponse());
// and finally log off and disconnect
managerConnection.logoff();
}
public static void main(String[] args) throws Exception
{
HelloManager helloManager;
helloManager = new HelloManager();
helloManager.run();
}
}
Exception:
run:
Feb 06, 2014 4:04:16 PM org.asteriskjava.manager.internal.ManagerConnectionImpl connect
INFO: Connecting to 192.168.68.173:5038
Feb 06, 2014 4:04:17 PM org.asteriskjava.manager.internal.ManagerConnectionImpl setProtocolIdentifier
INFO: Connected via Asterisk Call Manager/1.3
Feb 06, 2014 4:04:17 PM org.asteriskjava.manager.internal.ManagerConnectionImpl setProtocolIdentifier
WARNING: Unsupported protocol version 'Asterisk Call Manager/1.3'. Use at your own risk.
Feb 06, 2014 4:04:18 PM org.asteriskjava.manager.internal.ManagerConnectionImpl disconnect
INFO: Closing socket.
Feb 06, 2014 4:04:18 PM org.asteriskjava.manager.internal.ManagerReaderImpl run
INFO: Terminating reader thread: No more lines available: null
Exception in thread "main" org.asteriskjava.manager.AuthenticationFailedException: Authentication failed
at org.asteriskjava.manager.internal.ManagerConnectionImpl.doLogin(ManagerConnectionImpl.java:578)
at org.asteriskjava.manager.internal.ManagerConnectionImpl.login(ManagerConnectionImpl.java:438)
at org.asteriskjava.manager.internal.ManagerConnectionImpl.login(ManagerConnectionImpl.java:423)
at org.asteriskjava.manager.DefaultManagerConnection.login(DefaultManagerConnection.java:294)
at asteriskjtapi.HelloManager.run(HelloManager.java:49)
at asteriskjtapi.HelloManager.main(HelloManager.java:67)
Note:
Here I am using the credentials in FreePBX. Is this right one to access ConnectionManager?
Kindly paste your asterisk log while executing your java program
For getting asterisk log
tail -f /var/log/asterisk/full
For checking the same from command line try this
telnet 192.168.68.173 5038
Action: Login
Username: admin
Secret: admin
if login sucessfull
Action: Originate
Channel: SIP/1010
Exten: 2020
Context: default
Priority: 1
Callerid: 1010
Async: yes
Try this and let me know your outputs
First of all, you have to try to connect with asterisk through telnet.
If you get 'Login success' message, you can proceed with your programming. Otherwise if you get an 'Authentication failed' message, add your ip to the permit setting in manager.conf. Then save the changes.
permit:[your static ip]
Try again with telnet
Have a Transaction Event Handler to do logging for changes made via the Embedded API.
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.event.TransactionData;
import org.neo4j.graphdb.event.TransactionEventHandler;
import org.neo4j.kernel.impl.util.StringLogger;
import org.neo4j.server.logging.Logger;
import java.util.logging.Level;
public class WarehouseTransactionEventHandler implements TransactionEventHandler<String> {
private static Logger log = Logger
.getLogger(WarehouseTransactionEventHandler.class);
public void afterCommit(TransactionData data, String state) {
Iterable<Node> createdNodes = data.createdNodes();
for(Node n: createdNodes) {
log.info("AfterCommit ########: created node:" + n.getId());
log.log(Level.ALL,"AfterCommit ########: created node:" + n.getId());
}
}
public void afterRollback(TransactionData data, String state) {
// TODO Auto-generated method stub
}
public String beforeCommit(TransactionData data) throws Exception {
Iterable<Node> createdNodes = data.createdNodes();
for(Node n: createdNodes) {
log.info("BeforeCommit ######: created node:" + n.getId());
log.log(Level.ALL,"BeforeCommit ######: created node:" + n.getId());
}
return null;
}
}
Then I register it in my code that does the writing
GraphDatabaseService graphDb = new EmbeddedGraphDatabase(DB_PATH)
graphDb.registerTransactionEventHandler(new WarehouseTransactionEventHandler())
// do stuff
graphDb.shutdown();
So when I run my code it seems to be working
INFO: AfterCommit ########: created node:14
Jun 26, 2013 12:24:22 PM org.neo4j.server.logging.Logger log
INFO: AfterCommit ########: created node:15
Jun 26, 2013 12:24:22 PM org.neo4j.server.logging.Logger log
INFO: AfterCommit ########: created node:17
Jun 26, 2013 12:24:22 PM org.neo4j.server.logging.Logger log
INFO: AfterCommit ########: created node:16
Jun 26, 2013 12:24:22 PM org.neo4j.server.logging.Logger log
INFO: AfterCommit ########: created node:19
Jun 26, 2013 12:24:22 PM org.neo4j.server.logging.Logger log
INFO: AfterCommit ########: created node:18
Jun 26, 2013 12:24:22 PM org.neo4j.server.logging.Logger log
INFO: AfterCommit ########: created node:21
Jun 26, 2013 12:24:22 PM org.neo4j.server.logging.Logger log
INFO: AfterCommit ########: created node:20
Jun 26, 2013 12:24:22 PM org.neo4j.server.logging.Logger log
INFO: AfterCommit ########: created node:22
However I have gone through the logs and can't find any of these AfterCommit messages. My log.properties hasn't been changed except for setting java.util.logging.FileHandler.limit=10000000
Any thoughts? Thanks!
Have you tried using log4j, it works fine with me.
Initializing the logger # the beginning of your app, it will log your messages wherever you want it to be.. like this:
static {
try {
String logFileName = "neo4j.log";
RollingFileAppender fa = new RollingFileAppender();
fa.setName("NEO4JLOGGER");
fa.setFile(logFileName);
fa.setLayout(new PatternLayout(
"[%d{dd.MM.yyyy HH:mm:ss.SSS}] %5p %c{1}:%L - %m%n"));
fa.setAppend(true);
fa.activateOptions();
Logger.getLogger("CLASSES NEEDED TO BE LOGGED").setLevel(Level.ALL);
Logger.getLogger("CLASSES NEEDED TO BE LOGGED").addAppender(fa);
} catch (Exception ex) {
logger.error("Intialize Logger :: Failed... \n ", ex);
}
}
isUnique should just check for the existence of a newsgroup and return a boolean reflecting that:
init:
Deleting: /home/thufir/NetBeansProjects/USENET/build/built-jar.properties
deps-jar:
Updating property file: /home/thufir/NetBeansProjects/USENET/build/built-jar.properties
compile:
run:
DEBUG: nntp: newsrc loading /home/thufir/.newsrc
DEBUG: nntp: newsrc load: 5 groups in 26ms
Jul 29, 2012 8:37:13 PM net.bounceme.dur.usenet.driver.Main getFolders
INFO: [gwene.com.androidcentral, gwene.com.blogspot.emacsworld, gwene.com.blogspot.googlecode, gwene.com.blogspot.googlereader, gwene.com.economist]
[EL Info]: 2012-07-29 20:37:17.607--ServerSession(20908501)--EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
[EL Info]: 2012-07-29 20:37:19.815--ServerSession(20908501)--file:/home/thufir/NetBeansProjects/USENET/build/classes/_USENETPU login successful
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main persist
INFO: gwene.com.androidcentral
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main isUnique
INFO: []
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main isUnique
INFO: gwene.com.androidcentral new
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main persist
INFO: gwene.com.blogspot.emacsworld
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main isUnique
INFO: [gwene.com.androidcentral]
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main isUnique
INFO: gwene.com.blogspot.emacsworld new
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main persist
INFO: gwene.com.blogspot.googlecode
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main isUnique
INFO: [gwene.com.androidcentral, gwene.com.blogspot.emacsworld]
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main isUnique
INFO: gwene.com.blogspot.googlecode new
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main persist
INFO: gwene.com.blogspot.googlereader
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main isUnique
INFO: [gwene.com.androidcentral, gwene.com.blogspot.emacsworld, gwene.com.blogspot.googlecode]
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main isUnique
INFO: gwene.com.blogspot.googlereader new
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main persist
INFO: gwene.com.economist
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main isUnique
INFO: [gwene.com.androidcentral, gwene.com.blogspot.emacsworld, gwene.com.blogspot.googlecode, gwene.com.blogspot.googlereader]
Jul 29, 2012 8:37:20 PM net.bounceme.dur.usenet.driver.Main isUnique
INFO: gwene.com.economist new
BUILD SUCCESSFUL (total time: 9 seconds)
From querying the database, this seems to work as advertised. However, it seems like the wrong type of query:
package net.bounceme.dur.usenet.driver;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.mail.Folder;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import net.bounceme.dur.usenet.model.Newsgroups;
import net.bounceme.dur.usenet.model.Usenet;
public class Main {
private static final Logger LOG = Logger.getLogger(Main.class.getName());
private Usenet u = Usenet.INSTANCE;
public static void main(String[] args) {
Main main = new Main();
}
public Main() {
List<Newsgroups> folderGroups = getFolders();
EntityManagerFactory emf;
EntityManager em;
emf = Persistence.createEntityManagerFactory("USENETPU");
em = emf.createEntityManager();
for (Newsgroups n : folderGroups) {
persist(em, n);
}
em.close();
}
private void persist(EntityManager em, Newsgroups newNewsgroup) {
LOG.info(newNewsgroup.toString());
TypedQuery<Newsgroups> query = em.createQuery("SELECT n FROM Newsgroups n", Newsgroups.class);
List<Newsgroups> results = query.getResultList();
if (isUnique(newNewsgroup, results)) {
em.getTransaction().begin();
em.persist(newNewsgroup);
em.getTransaction().commit();
}
}
private boolean isUnique(Newsgroups newNewsgroup, Iterable<Newsgroups> results) {
LOG.info(results.toString());
for (Newsgroups existingNewsgroup : results) {
if ((existingNewsgroup.getNewsgroup().equals(newNewsgroup.getNewsgroup()))) {
return false;
}
}
LOG.info(newNewsgroup + "\tnew");
return true;
}
private boolean queryDB2(EntityManager em, Newsgroups ng) {
String newsgroup = ng.getNewsgroup();
TypedQuery<Newsgroups> query = em.createQuery("SELECT n FROM Newsgroups n WHERE n.newsgroup = :newsgroup", Newsgroups.class);
Newsgroups result = query.getSingleResult();
LOG.info("query result:\n" + result + "\ncompared to\n" + ng);
return false;
}
private List<Newsgroups> getFolders() {
List<Folder> folders = u.getFolders();
List<Newsgroups> newsgroups = new ArrayList<>();
for (Folder folder : folders) {
Newsgroups newsgroup = new Newsgroups(folder);
newsgroups.add(newsgroup);
}
LOG.info(newsgroups.toString());
return newsgroups;
}
}
Where rather than using isUnique to iterate through the query result, what would be the syntax for a match?
I see that in SQL there's an EXISTS key word. How can I turn the isUnique method into just a query for existence?
You can try simple query as:
SELECT 1
FROM Newsgroups n
WHERE newNewsgroup = 'newNewsgroup'
LIMIT 1;