Hot questions for Using Ubuntu in file

Question:

I just installed Ubuntu 15.10 and their openjdk-8-jdk (by apt-get).

Now I am missing the cacerts file.

There is a link at the usual location:

ls -l /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts
lrwxrwxrwx 1 root root 27 Oct 22 01:47 /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts -> /etc/ssl/certs/java/cacerts

but nothing at /etc/ssl/certs/java/cacerts:

stat /etc/ssl/certs/java/cacerts
stat: cannot stat ‘/etc/ssl/certs/java/cacerts’: No such file or directory

Answer:

This is due to a bug already reported here: Ubuntu bug ticket

The ticket above links another similar issue, which provides a workaround:

$ sudo dpkg --purge --force-depends ca-certificates-java
$ sudo apt-get install ca-certificates-java

Question:

In IntelliJ IDEA 13.1.5 on Ubuntu 14.04 LTS I see an occasional error in large projects that says "too many files open". Interestingly, this refuses to go away and freezes the IDE completely. I've tried the following things to fix it.

1) Modify my /etc/sysctl.conf to have this line as shown in this article here. Made the error less frequent:

fs.inotify.max_user_watches = 524288    
fs.file-max = 380180 

2) Raise the ulimit -n setting on the IntelliJ process to 64k. I don't notice any difference in performance with this, but the article that I mentioned above claims that it will help.

3) Add this to my idea64.vmoptions file (helps with speed of indexing, but not with this problem)

-Xms128m
-Xmx8192m
-XX:MaxPermSize=1024m

Has anyone else seen this error and do you have any other suggestions of what I can do to fix it?

I've considering asking IntelliJ support, but I've found I need to go back and forth with them a few times before I get a helpful answer. Any advice from the community on this would be appreciated.


Answer:

I spoke to IntelliJ support. They suggested that part 2 that I mentioned was not taking effect. I tried these steps:

1) sudo vi /etc/security/limits.conf and add these lines (take a backup too):

*       soft    nofile  380180
*       hard    nofile  380180

2) sudo vi /etc/pam.d/common-session add this line (take a backup too):

session required pam_limits.so

3) sudo vi /etc/pam.d/common-session-noninteractive add this line (take a backup too):

session required pam_limits.so

4) Reboot your machine

5) Confirm this took effect by running this command, you should see this result

~$ ulimit -n
380180

I reopened my large project after that and I haven't seen the "too many files open" message since then.

Question:

I have problem when loading shared libraries (JNI) from java class on Ubuntu operator system

Exception in thread "main" java.lang.UnsatisfiedLinkError: /opt/ETcpsdk/lib/linux-x86_64/libjcryptoki.so: libcryptoki.so: cannot open shared object file: No such file or directory
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary1(ClassLoader.java:1965)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1890)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1880)
    at java.lang.Runtime.loadLibrary0(Runtime.java:849)
    at java.lang.System.loadLibrary(System.java:1088)
    at tutorialjni.Test.<clinit>(Test.java:7)

- Test.java

package tutorialjni;

public class Test {

    // Load an external library, called "jcryptoki"
    static {
        System.loadLibrary("jcryptoki");
    }

    public static void main(String[] args) {
        System.out.println(System.getProperty("java.library.path"));
    }

}

- LD_LIBRARY_PATH was allocated in /etc/environment

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
JAVA_HOME="/opt/jdk1.7.0_75"
LD_LIBRARY_PATH="/opt/ETcpsdk/lib/linux-x86_64:/opt/ETcpsdk/lib/"

And I own ETcpsdk folder.

  • libcryptoki.so put in /opt/ETcpsdk/lib/linux-x86_64/libcryptoki.so

  • Run file libcryptoki.so command

    libjcryptoki.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped

- JDK version:

java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.75-b04, mixed mode)

- Ubuntu:

Distributor ID: Ubuntu
Description:    Ubuntu 14.04.2 LTS
Release:    14.04
Codename:   trusty

I added library directory to ldconfig cache

Can you help me?


Answer:

I got this problem because my shared libraries depends on another shared library which works improperly.

Question:

Ok. I have the following web app snippet (called in constructor - if that is important):

    private File[] logFiles;
    ...
    try {
        File directory = new File(auditDirectory);
        LOG.debug("Found directory: " + directory.getAbsolutePath());
        logFiles = directory.listFiles();           
        LOG.debug("Number of logFiles: " + logFiles.length);
    } catch (Exception e) {
        LOG.error("Exception: ", e);
        throw new RuntimeException("Failed to get list of audit files", e);
    }

In my windows environment (localhost) everything works like a charm. After deployment on linux (ubuntu) environment, seems that line

directory.listFiles();

returns null value. I have concluded that from the following linux deployment log:

c.a.s.a.a.AuditFileSource - Found directory: /home/myapp/myappfolder/logs
c.a.s.a.a.AuditFileSource - Exception: 
java.lang.NullPointerException: null
    at com.myapp.services.administration.audit.AuditFileSource.<init>(AuditFileSource.java:31) ~[com.myapp.services-2.2.2.jar:2.2.2]
    at... 

Log line AuditFileSource.java:31 is actually the line:

LOG.debug("Number of logFiles: " + logFiles.length);

and it is obvious that NullPointerException is raised as an attempt to access lenght on logFiles variable which is null.

My first try was to change permissions on relevant Linux folders but they already have read permissions. I'm completely puzzled. Any Idea?


Answer:

That's one of the numerous problems with File; its .listFiles() method is unreliable.

Try and use this instead:

final Path dir = Paths.get("path/to/directory");

final DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir);

// use the stream

If the fs entry is not a directory, you'll at least get a NotDirectoryException; if you don't have enough permissions, you'll get an AccessDeniedException; etc etc.

Drop File. This is 2015, after all. And the new file API (aka JSR 203, aka NIO2) has been there since 2011!


Since Java 8 you can also use Files.list(); DO NOTE however that you SHOULD use it in a try-with-resources block like this:

try (
    final Stream<Path> stream = Files.list(thedir);
) {
    // use the stream
}

It is a little known fact that Stream (well, BaseStream in fact) implements AutoCloseable!

Question:

I am trying to send a zip via tomcat server. But when I try to access http://localhost:8094/fetna-project-rest/webapi/retdoc/10 I got a permission error which I included in the bottom. I run the server on ubuntu. Can you please help me? My source codes are here:

public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {

    System.out.println("Writing '" + fileName + "' to zip file");

    File file = new File(fileName);
    if (!file.exists()) {
        file.createNewFile();
    }

    FileInputStream fis;
    fis = new FileInputStream(file);
    ZipEntry zipEntry = new ZipEntry(fileName);
    zos.putNextEntry(zipEntry);

    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
    }

    zos.closeEntry();
    fis.close();
}

@GET
@Path("retdoc/{id}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response retrieveDocument(@PathParam("id") String ID) throws IOException {

    FileOutputStream fos = new FileOutputStream("test.zip");
    ZipOutputStream zos = new ZipOutputStream(fos);

    String file1Name = "test.txt";

    addToZipFile(file1Name, zos);
    zos.close();
    fos.close();
    File zippedFile = new File("test.zip");
    return Response.ok(FileUtils.readFileToByteArray(zippedFile))
            .type("application/zip")
            .header("Content-Disposition", "attachment; filename=\"retrievedDocuments.zip\"")
            .build();
}

and my stacktrace:

message org.glassfish.jersey.server.ContainerException: java.io.FileNotFoundException: test.zip (Permission denied)

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.io.FileNotFoundException: test.zip (Permission denied)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:487)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

org.glassfish.jersey.server.ContainerException: java.io.FileNotFoundException: test.zip (Permission denied)
    org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:278)
    org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:260)
    org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:509)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:334)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

java.io.FileNotFoundException: test.zip (Permission denied)
    java.io.FileOutputStream.open(Native Method)
    java.io.FileOutputStream.<init>(FileOutputStream.java:221)
    java.io.FileOutputStream.<init>(FileOutputStream.java:110)
    org.eu.srdc.ehealth.MyResource.retrieveDocument(MyResource.java:78)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
    org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.30 logs.

Answer:

The user running tomcat doesn't have permission to write the file, just as the error says it. Would suggest you choose a specific folder where your uploaded files will be saved to and give the tomcat user write permissions to it (change username and path accordingly):

$ sudo mkdir /home/tomcat/uploads
$ sudo chown tomcat:tomcat /home/tomcat/uploads
$ sudo chmod u+wrx /home/tomcat/uploads

Then change your servlet code to use the upload path (modified line below):

FileOutputStream fos = new FileOutputStream("/home/tomcat/uploads/test.zip");

Question:

The code is libhdfs testing code.

 int main(int argc, char **argv)
{
    hdfsFS fs = hdfsConnect("hdfs://labossrv14", 9000);
    const char* writePath = "/libhdfs_test.txt";
    hdfsFile writeFile = hdfsOpenFile(fs, writePath, O_WRONLY|O_CREAT, 0, 0, 0);
    if(!writeFile)
    {
        fprintf(stderr, "Failed to open %s for writing!\n", writePath);
        exit(-1);
    }
    char* buffer = "Hello, libhdfs!";
    tSize num_written_bytes = hdfsWrite(fs, writeFile, (void*)buffer, strlen(buffer)+1);
    if (hdfsFlush(fs, writeFile))
    {
        fprintf(stderr, "Failed to 'flush' %s\n", writePath);
        exit(-1);
    }
    hdfsCloseFile(fs, writeFile);
}

I paid a lot of effort to compile this code successfully, but it doesn't work when I run the program. And the error message is below.

loadFileSystems error:
(unable to get stack trace for java.lang.NoClassDefFoundError exception: ExceptionUtils::getStackTrace error.)
hdfsBuilderConnect(forceNewInstance=0, nn=labossrv14, port=9000, kerbTicketCachePath=(NULL), userName=(NULL)) error:
(unable to get stack trace for java.lang.NoClassDefFoundError exception: ExceptionUtils::getStackTrace error.)
hdfsOpenFile(/libhdfs_test.txt): constructNewObjectOfPath error:
(unable to get stack trace for java.lang.NoClassDefFoundError exception: ExceptionUtils::getStackTrace error.)
Failed to open /libhdfs_test.txt for writing!

I play with this stuff according to the official document. And I find that the problem may be the incorrect CLASSPATH. My CLASSPATH is following, which is combined by the classpath generated from "hadoop classpath --glob" and the path of the lib of jdk and jre.

export CLASSPATH=/home/junzhao/hadoop/hadoop-2.5.2/etc/hadoop:/home/junzhao/hadoop/hadoop-2.5.2/share/hadoop/common/lib/*:/home/junzhao/hadoop/hadoop-2.5.2/share/hadoop/common/*:/home/junzhao/hadoop/hadoop-2.5.2/share/hadoop/hdfs:/home/junzhao/hadoop/hadoop-2.5.2/share/hadoop/hdfs/lib/*:/home/junzhao/hadoop/hadoop-2.5.2/share/hadoop/hdfs/*:/home/junzhao/hadoop/hadoop-2.5.2/share/hadoop/yarn/lib/*:/home/junzhao/hadoop/hadoop-2.5.2/share/hadoop/yarn/*:/home/junzhao/hadoop/hadoop-2.5.2/share/hadoop/mapreduce/lib/*:/home/junzhao/hadoop/hadoop-2.5.2/share/hadoop/mapreduce/*:/contrib/capacity-scheduler/*.jar:/usr/lib/jvm/java-8-oracle/lib:/usr/lib/jvm/java-8-oracle/jre/lib:$CLASSPATH

Does anyone have some good solutions? Thanks!


Answer:

I read again some information in the tutorials and some questions proposed before. Finally I find that the problem is caused by the fact that JNI doesn't expand the wildcards in CLASSPATH. So I just put all jars into CLASSPATH, and the problem is solved. Since this command "hadoop classpath --glob" also will generate wildcards, it explains that why the official document says this

It is not valid to use wildcard syntax for specifying multiple jars. It may be useful to run hadoop classpath --glob or hadoop classpath --jar to generate the correct classpath for your deployment.

I misunderstood this paragraph yesterday.

see also Hadoop C++ HDFS test running Exception and Can JNI be made to honour wildcard expansion in the classpath?

Question:


Answer:

you have installed the wrong architecture of java (32bit on top of a 64bit system or viceversa)

Question:

Environment: Java 7 on an Ubuntu 12 server.

I have a Java application that polls for incoming .zip files that are delivered via sftp. I have no control over the client that's delivering the files.

The files being delivered are quite large, and in some cases, the poll mechanism detects a file while it's still being written. In this situation, the Java application borks because it thinks the file is corrupt.

What's the most effective way of detecting when the local sftp server has finished writing the file?


Answer:

There are a number of approaches to dealing with this. You can choose one, but the more you implement the better:

  • The sender should upload as a .tmp file, then rename to .zip once done so that the watcher only sees the finished file.
  • The watcher should check the last modified time of the file, and if it was modified in the last 10 seconds (maybe 1 minute) then ignore the file and try again later.
  • If your OS supports it, try to get an exclusive lock on the file before reading it. This is not so easy in java, and depends on OS specifics.
  • Always send the file as a zip file, as if the file is incomplete of otherwise corrupted it will fail the CRC check. Also you get the added benefit for smaller transfers, smaller archive folder etc. (Of course you are already doing this, as mentioned in the question).

Look at the File2 component of camel and look at all the options it gives you. Make you want to use Camel, right?

Question:

I have installed Hadoop 2.6 on single machine using This Tutorial. I am using Ubuntu 12.04 machine and Java version 1.6.0_27.

I have created separate user as hduser for Hadoop operations. I have set HADOOP_HOME envrioment variable's value /usr/local/hadoop where I have extracted the Hadoop distribution.

Now I am following an example. But when I execute the command $HADOOP_HOME/bin/hdfs dfs -ls /home/hduser/input/ it gives following error -

15/01/02 18:32:38 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable ls: `/home/hduser/input/': No such file or directory

Also I have tried command- $HADOOP_HOME/bin/hdfs dfs -mkdir /home/hduser/input/ , but still getting same error.

When I run the command jps it shows - 16023 SecondaryNameNode 16200 ResourceManager 16432 NodeManager 18971 Jps 15503 NameNode

It is not showing any process for JobTracker and TaskTracker.

Can anybody please help me to resolve the issue of ls: `/home/hduser/input/': No such file or directory and to start/list the process for JobTracker and TaskTracker.

Thanks in Advance.


Answer:

You are trying to access you local directory using hdfs. Try following steps:

export PATH=$HADOOP_HOME/bin:$PATH ##Make this entry in your ~/.bashrc file
hdfs dfs -mkdir /user
hdfs dfs -mkdir /user/hduser
hdfs dfs -mkdir /user/hduser/input
hdfs dfs -ls /user/hduser/input
echo "Hello World" > file01
hadoop fs -copyFromLocal /user/hduser/input
hadoop fs -cat /user/hduser/input/file01

Question:

My Docker File

# Pull base image
  FROM tomcat:8-jre8

# Maintainer
  MAINTAINER "Ravindu <rav@info.com">

# Copy to images tomcat path
  ADD /mobile.war /usr/local/tomcat/webapps/

The docker image is built through running maven ant plugin, which successfully creates the image without any problem. But when I run the created image the tomcat server is starting as normal and throwing following errors on stack trace

19-Mar-2017 07:33:11.517 SEVERE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start: 
 org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/mobile]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:729)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:940)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1816)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@3ec80848]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4969)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5099)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    ... 10 more
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@1c19c6e4]
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:135)
    at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:707)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    ... 13 more
Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: zip file is empty
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:113)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    ... 16 more
Caused by: java.util.zip.ZipException: zip file is empty
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:219)
    at java.util.zip.ZipFile.<init>(ZipFile.java:149)
    at java.util.jar.JarFile.<init>(JarFile.java:166)
    at java.util.jar.JarFile.<init>(JarFile.java:103)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:110)
    ... 17 more

19-Mar-2017 07:33:11.519 SEVERE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive /usr/local/tomcat/webapps/mobile.war
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/mobile]]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:757)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:729)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:940)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1816)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Though I can access the tomcat server landing page via obtaining the docker container IP, even after these errors occur, my desired war file route which is the /mobile cannot be accessed and throws a 404.

N.B. - I have even tried to create a image directly using the docker file without using maven ant plugin, but the issue still remains same when running the created docker image.

N.B. - Though it throws a Zip file empty error, the mobile.war file is extracted completely without any error in my ubuntu machine.

N.B. - Also I tried doing this on my windows machine using docker toolbox command line tool, by creating an image based on the same Dockerfile and I was able to successfully deploy and access my war file via /mobile without any problem.

N.B. - mobile.war file is created with default maven war plugin and I'm using IntelliJ IDEA for my development.

EDIT - Adding the Full Stack Trace

WARNING: Error loading config file:/home/ravindu/.docker/config.json - stat /home/ravindu/.docker/config.json: permission denied
Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:        /usr/lib/jvm/java-8-openjdk-amd64/jre
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
22-Mar-2017 10:50:17.386 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.0.42
22-Mar-2017 10:50:17.395 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Mar 8 2017 19:58:16 UTC
22-Mar-2017 10:50:17.395 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:         8.0.42.0
22-Mar-2017 10:50:17.395 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Linux
22-Mar-2017 10:50:17.395 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            4.4.0-66-generic
22-Mar-2017 10:50:17.395 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          amd64
22-Mar-2017 10:50:17.395 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             /usr/lib/jvm/java-8-openjdk-amd64/jre
22-Mar-2017 10:50:17.395 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           1.8.0_121-8u121-b13-1~bpo8+1-b13
22-Mar-2017 10:50:17.396 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Oracle Corporation
22-Mar-2017 10:50:17.396 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         /usr/local/tomcat
22-Mar-2017 10:50:17.396 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         /usr/local/tomcat
22-Mar-2017 10:50:17.396 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/usr/local/tomcat/conf/logging.properties
22-Mar-2017 10:50:17.396 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
22-Mar-2017 10:50:17.396 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048
22-Mar-2017 10:50:17.396 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.protocol.handler.pkgs=org.apache.catalina.webresources
22-Mar-2017 10:50:17.396 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.endorsed.dirs=/usr/local/tomcat/endorsed
22-Mar-2017 10:50:17.396 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/usr/local/tomcat
22-Mar-2017 10:50:17.396 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/usr/local/tomcat
22-Mar-2017 10:50:17.397 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/usr/local/tomcat/temp
22-Mar-2017 10:50:17.397 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent Loaded APR based Apache Tomcat Native library 1.2.12 using APR version 1.5.1.
22-Mar-2017 10:50:17.397 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
22-Mar-2017 10:50:17.445 INFO [main] org.apache.catalina.core.AprLifecycleListener.initializeSSL OpenSSL successfully initialized (OpenSSL 1.1.0e  16 Feb 2017)
22-Mar-2017 10:50:17.915 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-apr-8080"]
22-Mar-2017 10:50:17.939 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-apr-8009"]
22-Mar-2017 10:50:17.940 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 2425 ms
22-Mar-2017 10:50:18.034 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service Catalina
22-Mar-2017 10:50:18.034 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.0.42
22-Mar-2017 10:50:18.131 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive /usr/local/tomcat/webapps/mobile.war
22-Mar-2017 10:50:19.556 SEVERE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start: 
 org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/mobile]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:729)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:940)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1816)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@3954f4bc]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4969)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5099)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    ... 10 more
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@3b4859b1]
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:135)
    at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:707)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    ... 13 more
Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: zip file is empty
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:113)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    ... 16 more
Caused by: java.util.zip.ZipException: zip file is empty
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:219)
    at java.util.zip.ZipFile.<init>(ZipFile.java:149)
    at java.util.jar.JarFile.<init>(JarFile.java:166)
    at java.util.jar.JarFile.<init>(JarFile.java:103)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:110)
    ... 17 more

22-Mar-2017 10:50:19.597 SEVERE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive /usr/local/tomcat/webapps/mobile.war
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/mobile]]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:757)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:729)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:940)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1816)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

22-Mar-2017 10:50:19.618 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /usr/local/tomcat/webapps/mobile.war has finished in 1,467 ms
22-Mar-2017 10:50:19.633 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/host-manager
22-Mar-2017 10:50:20.542 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/host-manager has finished in 909 ms
22-Mar-2017 10:50:20.543 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/docs
22-Mar-2017 10:50:20.595 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/docs has finished in 52 ms
22-Mar-2017 10:50:20.596 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/manager
22-Mar-2017 10:50:20.632 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/manager has finished in 36 ms
22-Mar-2017 10:50:20.636 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/ROOT
22-Mar-2017 10:50:20.697 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/ROOT has finished in 60 ms
22-Mar-2017 10:50:20.697 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/examples
22-Mar-2017 10:50:21.239 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/examples has finished in 542 ms
22-Mar-2017 10:50:21.245 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-apr-8080"]
22-Mar-2017 10:50:21.284 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-apr-8009"]
22-Mar-2017 10:50:21.292 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 3351 ms

Couldn't find any exact lead to solve this issue even after referring lots of SO questions.


Answer:

There may be two issues in this case :

  1. The best approach to copy files like *.war,*.zip,.*.tar.gz in container not with ADD but must use COPY because there is a little difference in COPY and ADD. When you use ADD it will put files in a extracted mode inside Images.if it is in any of these .war,.zip,.*.tar.gz, and if use COPY then it will simply just copy like cp command inside Images. So best practice is to use COPY for those kind of files and no worries of getting it corrupted.
  2. As you mentioned in comments "bash: jar: command not found" may be your java inside container is not set up in $PATH variable or JAVA_HOME don't have proper permission.

Hope this will help.Thank you!

Question:

I'm trying to implement file upload with play framework scala. This code works just fine in development(windows) but fails when deployed(Ubuntu).

     def upload = Action(parse.multipartFormData) { request =>
      request.body.file("torrentFile").map { picture =>
      import java.io.File
      val filename = picture.filename
      val contentType = picture.contentType
      println(filename)
      println(contentType)
      picture.ref.moveTo(new File("Files/ppp.rdf"))
      Ok("File uploaded")
    }.getOrElse {
      Redirect(routes.Application.index()).flashing(
        "error" -> "Missing file")
    }
}

This is the error I get when I try uploading a file

    play.api.UnexpectedException: Unexpected exception[NoSuchFileException: /tmp/playtemp5801072751187159177/multipartBody5640251320440161134asTemporaryFile -> Files/ppp.rdf]
        at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:289) ~[com.typesafe.play.play_2.11-2.5.10.jar:2.5.10]
        at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:220) ~[com.typesafe.play.play_2.11-2.5.10.jar:2.5.10]
        at play.api.GlobalSettings$class.onError(GlobalSettings.scala:160) [com.typesafe.play.play_2.11-2.5.10.jar:2.5.10]
        at play.core.j.JavaGlobalSettingsAdapter.play$core$j$JavaGlobalSettingsAdapter$$super$onError(JavaGlobalSettingsAdapter.scala:35) [com.typesafe.play.play_2.11-2.5.10.jar:2.5.10]
        at play.core.j.JavaGlobalSettingsAdapter$$anonfun$onError$2.apply(JavaGlobalSettingsAdapter.scala:35) [com.typesafe.play.play_2.11-2.5.10.jar:2.5.10]
        at play.core.j.JavaGlobalSettingsAdapter$$anonfun$onError$2.apply(JavaGlobalSettingsAdapter.scala:35) [com.typesafe.play.play_2.11-2.5.10.jar:2.5.10]
        at scala.Option.getOrElse(Option.scala:121) [org.scala-lang.scala-library-2.11.7.jar:na]
        at play.core.j.JavaGlobalSettingsAdapter.onError(JavaGlobalSettingsAdapter.scala:35) [com.typesafe.play.play_2.11-2.5.10.jar:2.5.10]
        at play.api.http.GlobalSettingsHttpErrorHandler.onServerError(HttpErrorHandler.scala:100) [com.typesafe.play.play_2.11-2.5.10.jar:2.5.10]
        at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:100) [com.typesafe.play.play-netty-server_2.11-2.5.10.jar:2.5.10]
Caused by: java.nio.file.NoSuchFileException: /tmp/playtemp5801072751187159177/multipartBody5640251320440161134asTemporaryFile -> Files/ppp.rdf
        at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86) ~[na:1.8.0_111]
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102) ~[na:1.8.0_111]
        at sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:457) ~[na:1.8.0_111]
        at sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:262) ~[na:1.8.0_111]
        at java.nio.file.Files.move(Files.java:1395) ~[na:1.8.0_111]
        at play.api.libs.Files$TemporaryFile.moveTo(Files.scala:102) ~[com.typesafe.play.play_2.11-2.5.10.jar:2.5.10]
        at controllers.Upload$$anonfun$upload$1$$anonfun$apply$1.apply(Upload.scala:74) ~[untitled10.untitled10-1.0-sans-externalized.jar:na]
        at controllers.Upload$$anonfun$upload$1$$anonfun$apply$1.apply(Upload.scala:68) ~[untitled10.untitled10-1.0-sans-externalized.jar:na]
        at scala.Option.map(Option.scala:146) [org.scala-lang.scala-library-2.11.7.jar:na]
        at controllers.Upload$$anonfun$upload$1.apply(Upload.scala:68) ~[untitled10.untitled10-1.0-sans-externalized.jar:na]

The applications creates some files and folders when running and this currently happens so I'm sure its not Linux file permission in the directory. when I go to /tmp directory I do not see the play temp files. I'm working with play 2.5 in intellij.


Answer:

First of all, try to give a full path instead of Files, like /var/webapps/your-app/files.

Run the app as root temporary (using sudo) and make sure that Files (/var/webapps/your-app/files) folder exists on the disk.

If the app worked as root it shows that there is something wrong about permissions. Make sure the user which the app is running by, have read/write access to /tmp and write access to Files.

Question:

I have two java application which works on some file exist check mechanism , where one application wait till file deletion occurs and create a file on deletion of file to manage concurrency. If the process are not process safe my application fails.


Answer:

The pseudocode:

if file exists:
   do something with it

It's not concurrent safe as nothing ensures the file does not get deleted between the first and the second line.

The safest way would be to use a FileLock. If you are planning to react to file creation/deletion events on Linux, I'd recommend to use some inotify based solution.

Question:

I came across a strange issue when writing unit tests for cross-platform Java applications, specifically using the FileInputStream. This test was originally written in Windows and passed

        FileInputStream inputStream = new FileInputStream(file.getAbsolutePath());
        FileOutputStream outputStream = FileUtils.getFileOutputStream(file.getAbsolutePath());

        outputStream.write('a');
        outputStream.close();


        Assert.assertEquals(inputStream.read(), 'a');

This works perfectly in Windows but fails in Ubuntu as inputStream returns -1 (which is EOF)

However if I reassign inputStream after I close outputStream like so,

        FileInputStream inputStream = new FileInputStream(file.getAbsolutePath());
        FileOutputStream outputStream = FileUtils.getFileOutputStream(file.getAbsolutePath());

        outputStream.write('a');
        outputStream.close();

        inputStream = new FileInputStream(file.getAbsolutePath());

        Assert.assertEquals(inputStream.read(), 'a');

everything works fine in Ubuntu and Windows.

My guess is that it has to do with the different file systems used by Windows and Ubuntu but I was hoping someone could elaborate further.

note: The FileUtils class is custom but works correctly. I checked that the file was being written to in both OS's manually


Answer:

On windows, while a file is opened it cannot be deleted, nor the directory it is in etc. The FileOutputStream can only truncate the file, it cannot delete and replace it. On Unix, the file lives independently of the directory structure. It can be open, read and written to even if it no longer appears in any directory. This means that FileOutputStream can delete the file and re-create it rather re-use the existing inode.

The difference is whether the file is truncated or replaced. On Linux a file can be replaced even if it is open, on Windows it cannot.

Question:

I want to handle mouse event in Linux terminal via java programming. I wrote two program via c++ and java that they do same process.

when i use c++ programming to open and read file ("/dev/input/event3"-mouse event file), there is no problem while running executable file. (Ubuntu 14.04 terminal and Ubuntu server 14.04 ---> no problem).

But when i used java programming to open and read the same file ,there is a problem while running executable result file "java -jar program.jar" in Ubuntu 14.04 "terminal". No error for opening file , but reading file make an error like this:

java.io.IOException: Invalid argument
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(Unknown Source)
    at eventfileopen.m.main(m.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)

But when i run the same jar file on Ubuntu server 14.04, there is no error and the program work perfectly. How can I resolve the problem?(Problem = run the java program on Ubuntu 14.04 with no error.) I guess the problem is related to Ubuntu GUI and JDK,but no idea for resolving that. My java program code:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

public class m {

    public static void main(String[] args) {

        File f = new File("/dev/input/event3");
        FileInputStream is = null;
        try {
            is = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] bytes = new byte[16];
        while(true){
            try 
            {
                is.read(bytes);
            } catch (IOException e) 
            {
                e.printStackTrace();   //-------> error while run on Ubuntu 14.04 and no error on Ubuntu server
            }
            System.out.println(Arrays.toString(bytes));
        }
    }
}


Answer:

Check that your buffer size is correct. In recent Linux kernels size of input_event structure is dependent on many things, but mainly on cpu architecture. Here's its declaration:

struct input_event {
      struct timeval time;
      __u16 type;
      __u16 code;
      __s32 value;
};

On 32-bit systems it's very likely that your buffer size is accepted(16 bytes).

On 64-bit systems it's very likely that the buffer should be no less than 24 bytes. The reason is that timeval struct takes twice as much space(8 bytes more) than on 32-bit systems.

I haven't found a reliable way to get input_event struct size from Java and personally I use JNI for that.

Question:

I'm new in java and Ubuntu. I want to know how can i write the right path of specific file in code as i got exception like that

/home/me/javaException in thread "main" java.io.FileNotFoundException: 
home/me/java/config.properites (No such file or directory)

Here is my code:

public static void main(String[] args) {
    Properties prop = new Properties();
    String queryFile = null;
    FileOutputStream fos = null;
    try {
        // load a properties file
        FileInputStream finputstream = new FileInputStream("config.properties");

Answer:

In ubuntu or any linux os your home folder is available in 'home/< username >'. You can check this from terminal or in gui. You can try some thing like,

File file = new File("/home/<your user name>/file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);

Question:

In Ubuntu 12.04 (Not Working)

I create a sh file and write the code.

  @echo off
  java -jar Program.jar

also allow the permission of execution. But no action performed. While in windows it works fine.

In Windows 7 (Working)

I create a batch file and write the code.

@echo off
java -jar Program.jar

Please help what i am doing wrong.


Answer:

Ubuntu shell scripts can't use @echo off that's for DOS command scripts. You need something like,

#!/bin/sh
java -jar Program.jar

The first line is known as the Shebang (the #! is a kind of magic number).

Question:

I am using docx4j to convert a docx file to html in my software. I am developing in a windows based system and my production is a Ubuntu Linux 14.04 in AWS. Everything works well in Windows, But when it comes to Ubuntu, it is throwing me an exception as follows.

2015-11-19 07:33:36 ERROR AbstractExporter:108 - Exception exporting package java.lang.NullPointerException at org.docx4j.openpackaging.parts.WordprocessingML.ObfuscatedFontPart.deleteEmbeddedFontTempFiles(ObfuscatedFontPart.java:263) at org.docx4j.openpackaging.parts.WordprocessingML.FontTablePart.deleteEmbeddedFontTempFiles(FontTablePart.java:161) at org.docx4j.convert.out.common.AbstractExporter.export(AbstractExporter.java:91) at org.docx4j.Docx4J.toHTML(Docx4J.java:511) at com.testbudha.document.impl.WordDocumentExtractor.toHtml(WordDocumentExtractor.java:31) at com.testbudha.document.impl.DocXExtractor.getText(DocXExtractor.java:31) at com.testbudha.document.impl.DocumentServiceImpl.getFileText(DocumentServiceImpl.java:18) at com.testbudha.server.controller.StudentHomeController.getResumeText(StudentHomeController.java:120)

I know it's a font related issue and I tried installing

ttf-mscorefonts-installer

But it doesn't change anything I also tried installing the vista fonts by using this script. Then also I am getting the same exception

Vista fonts installer

protected String toHtml(WordprocessingMLPackage wordMLPackage, String path, HttpServletRequest request)
            throws Docx4JException {
        try {

            HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
            htmlSettings.setImageDirPath(path + "/_files");
            htmlSettings.setImageTargetUri(request.getContextPath() + "/getfile/");
            htmlSettings.setWmlPackage(wordMLPackage);

            OutputStream os = new ByteArrayOutputStream();
            Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML", true);
            Docx4J.toHTML(htmlSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
            String outputHtml = ((ByteArrayOutputStream) os).toString().replaceAll("Â", "\n").replaceAll(" â€" ", "-")
                    .replaceAll("(?s)â€.\\s*", "").replaceAll("\\[(.*?)\\]","").replaceAll("#\\?", "")
                    .replaceAll("\\s*(?i)HYPERLINK\\s\\S\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))+\"", "($1)")
                    .replaceAll("(\\([^)]*\\))\\s?(\\w+)", "$2$1");
            return outputHtml;
        } finally {
            if (wordMLPackage.getMainDocumentPart().getFontTablePart() != null) {
                wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
            }
        }

it is throwing exception at

Docx4J.toHTML(htmlSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

Answer:

https://github.com/plutext/docx4j/blob/master/src/main/java/org/docx4j/openpackaging/parts/WordprocessingML/ObfuscatedFontPart.java#L263

tmpFontDir seems to be null, probably because System.getProperty("user.home") returns null

so set the property "docx4j.openpackaging.parts.WordprocessingML.ObfuscatedFontPart.tmpFontDir" in Docx4j.properties file added to your classpath.

Question:

I wanted to start an Android application project using Eclipse.

My OS is Ubuntu 14.04 and had already the Android SDK. So far, I was using the command line tools.

I downloaded and installed Eclipse Luna (the ADT bundle comes with an older version of Eclipse, so I did not want to use it). Then, using Help -> Install New Software, installed the Android Eclipse plug-in (the instructions are here.

As per the instructions on Android developer site, I created an application project and tried to run the app on an emulator instance.

But the app did not run, and the Error Log in Eclipse showed the error

 DDMS files not found:  /opt/android-sdk-linux/platform-tools/hprof-conv

The hprof-conv file exists in the shown location, and I was able to run it.

/opt/android-sdk-linux/platform-tools$ ./hprof-conv --help
Usage: hprof-conf infile outfile

Specify '-' for either or both to use stdin/stdout.

Copyright (C) 2009 The Android Open Source Project

This software is built from source code licensed under the Apache License,
Version 2.0 (the "License"). You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

See the associated NOTICE file for this software for further details.

After looking at different questions here (this, this, this, and this), I tried several things: restarting Eclipse, updating the SDK using the SDK manager, confirming that the settings at Window -> Preferences -> Android are correct, ensuring emulator screen is unlocked, etc.

All the settings everything is fine. But the problem persisted. Eclipse could not load the app on the emulator.

Another thing to note is that the posts on stack overflow and other sites that dealt with the similar problem were primarily on Windows.

I am puzzled. What am I missing or doing wrong?


Answer:

Looks like the problem occurred because adb server was not running. I ran the command

$ adb start-server
adb server is out of date.  killing...
* daemon started successfully *

And then ensured that the emulator is detected by adb:

$ adb devices
List of devices attached 
emulator-5554   device

Then I went to Eclipse again, and tried to run the app by using Run As -> Android Application

After a few seconds, voila, the emulator showed my app! :-) Problem solved. Hope this helps someone that has the same problem.

Question:

I'm trying to apply the next annotation to a the configuration class:

@Configuration
@EnableCaching
@ComponentScan({ "com.foo.*" })
@PropertySources({
    @PropertySource("classpath:foo.properties"),
    @PropertySource(value = "file:${catalina.home}/conf/foo.properties", ignoreResourceNotFound = true),
})

but I'm getting the following exception:

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.company.config.CoreConfig]; nested exception is java.io.FileNotFoundException: class path resource [foo.properties] cannot be opened because it does not exist

I've tried to look for this error on google and found many relevant things but nothing that could help me.

The file path is:

/home/me/apache-tomcat-8.0.36/conf


Answer:

I solved it by removing this line:

@PropertySource("classpath:foo.properties"),

Question:

Recently I tried to use add a picture to a label in my JavaFx Maven Project in Eclipse. If I run the application in Eclipse everything works fine and no error occurs.

This post is different to the: "Why relative path doesn't work in JAVA in JAR-file?" post! I tried the solution of this post, but it don't work for me. I described that below.

If I run the application from the Linux terminal like java -jar myapplication.jar the following error occurs:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$412(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.FileNotFoundException: src/pictures/forms_logo_2_1.png (Datei oder Verzeichnis nicht gefunden)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at de.elastic.client.Main.pane1(Main.java:193)
    at de.elastic.client.Main.start(Main.java:259)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$419(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$399(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$397(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$398(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$203(GtkApplication.java:139)
    ... 1 more
Exception running application de.elastic.client.Main

I localized the error at a file-import of a picture. For the import I used this code:

FileInputStream input = new FileInputStream("path/picture.png");
Image image = new Image(input);
Label img1 = new Label();
img1.setGraphic(new ImageView(image));

I also tried to give the imageUrl directly to the Image class like Image image = new Image(imageUrl);. This worked in previous projects for me.

I also tried Image image = new Image(getClass().getResourceAsStream(imageUrl)); but here eclipse throws the error Cannot make a static reference to the non-static method getClass() from the type Object.

Regarding this I also tried Image image = new Image(Main.class.getResource(imageUrl).toExternalForm();. For me it's only executable in this way without an error.

Update: I also tried this:

ClassLoader classLoader1 = Main.class.getClassLoader();
String ImgUrl1 = classLoader1.getResource("path/picture.png").toExternalForm();

Image image = new Image(ImgUrl1);
Label img1 = new Label();
img1.setGraphic(new ImageView(image));

It's throws the same error as above.

Update: Ok, it seems like the executable JAR-file don't match to find the picture and other data in itself. So for example a picture lies in the pictures folder and the application can't find it in the pictures folder. So it's a reference problem. Cause I converted it to a maven project maybe the structure is not right. I will try to create a new maven project and post the result here.

Because this are all common used ways I've found to import a picture into a label, I'm a bit frustrated. I hope someone have a solution for this tiny problem. Cheers!


Answer:

I find a solution on my own. There was a problem with the file system of the maven project and the arrangement of the code. The error occurred by using the eclipse feature in [right click] > configure > convert to maven project. This caused some missing folders in the file system of the program. Now it's possible to simply reference the files.

The solution is to create a new Maven Project and migrate everything from your old project. Than it worked for me. Cheers!

Question:

I am beginner to hadoop just practiced some of the tutorial projects. Initially did project in hadoop with python where i can able to specify mapper and reducer file separately hadoop jar /usr/local/hadoop/hadoop-2.8.0/share/hadoop/tools/lib/hadoop-streaming-2.8.0.jar -mapper mapper.py -reducer reducer.py -file mapper.py -file reducer.py -input input1 -output joboutput

But I want to do the same in java but where I found tutorials only by creating jar files. I didn't find any ways to debug java mapper and reducer code. Is there any ideas or possibilities to test our code by using some debug options.

Hereby i post screen shots where I am struck with.

Sample input file in csv

Mapper Code

    package SalesCountry;

import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;

public class SalesMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
    //private final static IntWritable one = new IntWritable(1);

    public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {

        String valueString = value.toString();
        String[] SingleCountryData = valueString.split(",");
        output.collect(new Text(SingleCountryData[7]), new IntWritable(Integer.parseInt(SingleCountryData[2])));
    }
}

Reducer Code

`package SalesCountry;

import java.io.IOException;
import java.util.*;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;

public class SalesCountryReducer extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {

    public void reduce(Text t_key, Iterator<IntWritable> values, OutputCollector<Text,IntWritable> output, Reporter reporter) throws IOException {
        Text key = t_key;
        int salesForCountry = 0;
        while (values.hasNext()) {
            // replace type of value with the actual type of our value
            IntWritable value = (IntWritable) values.next();
            salesForCountry += value.get();

        }
        output.collect(key, new IntWritable(salesForCountry));
    }
}
`

Terminal Output

$HADOOP_HOME/bin/hadoop jar TotalSalePerCountry.jar inputMapReduce mapreduce_output_sales
17/05/18 12:52:47 INFO Configuration.deprecation: session.id is deprecated. Instead, use dfs.metrics.session-id
17/05/18 12:52:47 INFO jvm.JvmMetrics: Initializing JVM Metrics with processName=JobTracker, sessionId=
17/05/18 12:52:47 INFO jvm.JvmMetrics: Cannot initialize JVM Metrics with processName=JobTracker, sessionId= - already initialized
17/05/18 12:52:47 WARN mapreduce.JobResourceUploader: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
17/05/18 12:52:47 INFO mapred.FileInputFormat: Total input files to process : 1
17/05/18 12:52:47 INFO mapreduce.JobSubmitter: number of splits:1
17/05/18 12:52:47 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_local1862814770_0001
17/05/18 12:52:47 INFO mapreduce.Job: The url to track the job: http://localhost:8080/
17/05/18 12:52:47 INFO mapred.LocalJobRunner: OutputCommitter set in config null
17/05/18 12:52:47 INFO mapreduce.Job: Running job: job_local1862814770_0001
17/05/18 12:52:47 INFO mapred.LocalJobRunner: OutputCommitter is org.apache.hadoop.mapred.FileOutputCommitter
17/05/18 12:52:47 INFO output.FileOutputCommitter: File Output Committer Algorithm version is 1
17/05/18 12:52:47 INFO output.FileOutputCommitter: FileOutputCommitter skip cleanup _temporary folders under output directory:false, ignore cleanup failures: false
17/05/18 12:52:47 INFO mapred.LocalJobRunner: Waiting for map tasks
17/05/18 12:52:47 INFO mapred.LocalJobRunner: Starting task: attempt_local1862814770_0001_m_000000_0
17/05/18 12:52:47 INFO output.FileOutputCommitter: File Output Committer Algorithm version is 1
17/05/18 12:52:47 INFO output.FileOutputCommitter: FileOutputCommitter skip cleanup _temporary folders under output directory:false, ignore cleanup failures: false
17/05/18 12:52:47 INFO mapred.Task:  Using ResourceCalculatorProcessTree : [ ]
17/05/18 12:52:47 INFO mapred.MapTask: Processing split: file:/home/deevita/MapReduceTutorial/inputMapReduce/SalesJan2009.csv:0+123638
17/05/18 12:52:47 INFO mapred.MapTask: numReduceTasks: 1
17/05/18 12:52:47 INFO mapred.MapTask: (EQUATOR) 0 kvi 26214396(104857584)
17/05/18 12:52:47 INFO mapred.MapTask: mapreduce.task.io.sort.mb: 100
17/05/18 12:52:47 INFO mapred.MapTask: soft limit at 83886080
17/05/18 12:52:47 INFO mapred.MapTask: bufstart = 0; bufvoid = 104857600
17/05/18 12:52:47 INFO mapred.MapTask: kvstart = 26214396; length = 6553600
17/05/18 12:52:47 INFO mapred.MapTask: Map output collector class = org.apache.hadoop.mapred.MapTask$MapOutputBuffer
17/05/18 12:52:47 INFO mapred.LocalJobRunner: map task executor complete.
17/05/18 12:52:47 WARN mapred.LocalJobRunner: job_local1862814770_0001
java.lang.Exception: java.lang.NumberFormatException: For input string: "Price"
    at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:489)
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:549)
Caused by: java.lang.NumberFormatException: For input string: "Price"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at SalesCountry.SalesMapper.map(SalesMapper.java:17)
    at SalesCountry.SalesMapper.map(SalesMapper.java:10)
    at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:54)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343)
    at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:270)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
17/05/18 12:52:48 INFO mapreduce.Job: Job job_local1862814770_0001 running in uber mode : false
17/05/18 12:52:48 INFO mapreduce.Job:  map 0% reduce 0%
17/05/18 12:52:48 INFO mapreduce.Job: Job job_local1862814770_0001 failed with state FAILED due to: NA
17/05/18 12:52:48 INFO mapreduce.Job: Counters: 0
java.io.IOException: Job failed!
    at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:873)
    at SalesCountry.SalesCountryDriver.main(SalesCountryDriver.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:234)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:148)
deevita@deevita-OptiPlex-7040:~/MapReduceTutorial$ $HADOOP_HOME/bin/hadoop jar TotalSalePerCountry.jar inputMapReduce mapreduce_output_sales
17/05/18 16:15:12 INFO Configuration.deprecation: session.id is deprecated. Instead, use dfs.metrics.session-id
17/05/18 16:15:12 INFO jvm.JvmMetrics: Initializing JVM Metrics with processName=JobTracker, sessionId=
17/05/18 16:15:12 INFO jvm.JvmMetrics: Cannot initialize JVM Metrics with processName=JobTracker, sessionId= - already initialized
org.apache.hadoop.mapred.FileAlreadyExistsException: Output directory file:/home/deevita/MapReduceTutorial/mapreduce_output_sales already exists
    at org.apache.hadoop.mapred.FileOutputFormat.checkOutputSpecs(FileOutputFormat.java:131)
    at org.apache.hadoop.mapreduce.JobSubmitter.checkSpecs(JobSubmitter.java:270)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:141)
    at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1341)
    at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1338)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1807)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1338)
    at org.apache.hadoop.mapred.JobClient$1.run(JobClient.java:575)
    at org.apache.hadoop.mapred.JobClient$1.run(JobClient.java:570)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1807)
    at org.apache.hadoop.mapred.JobClient.submitJobInternal(JobClient.java:570)
    at org.apache.hadoop.mapred.JobClient.submitJob(JobClient.java:561)
    at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:870)
    at SalesCountry.SalesCountryDriver.main(SalesCountryDriver.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:234)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:148)

I know it is Number format exception but to compile this I have to build jar file every time So Is there any way to execute mapreduce alone every time without building jar


Answer:

The NumberFormatException may come from a white space (need to be trimmed first).

I would suggest you to write unit test for your jobs that would allow you to debug them without doing the whole jar/deploy cycle.

Here is an example using mrunit.

<dependency>
<groupId>org.apache.mrunit</groupId>
<artifactId>mrunit</artifactId>
<version>1.0.0</version>
<classifier>hadoop1</classifier>
<scope>test</scope>
</dependency>

Test

public class HadoopTest {
MapDriver<LongWritable, Text, Text, IntWritable> mapDriver;

@Before
public void setUp() {
    SalesMapper mapper = new SalesMapper();
    mapDriver = new MapDriver<LongWritable, Text, Text, IntWritable>();
    mapDriver.setMapper(mapper);
}

@Test
public void testMapper() throws Exception {
    mapDriver.withInput(new LongWritable(1), new Text("date,product,1200,Visa,carolina,baslidoni,england,UK"));
    mapDriver.withOutput(new Text("UK"), new IntWritable(1200));
    mapDriver.runTest();
}
}

Question:

This is my build.gradle file. In eclipse, I run docker task via gradle in eclipse, there is no error and it generates dockerfile and image. But when I try to write gradle build in ubuntu terminal at project location, I get an error. I will try to run task to get dockerfile of project later by writing gradle distDucker.

build.gradle file:

buildscript {
repositories {
mavenCentral()
}
 dependencies {
  classpath "se.transmode.gradle:gradle-docker:1.2"
}
}

apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'docker'
apply plugin: 'eclipse'

repositories {
mavenCentral()
}

sourceCompatibility = 1.8

mainClassName = 'kafka.MyProducer'

applicationDefaultJvmArgs = ['-Xmx1g',
                         '-Xms1g']

dependencies {
compile group: 'org.apache.kafka', name: 'kafka_2.11',version: '0.10.0.0'    
 }

task copyConf(type: Copy) {
from System.getProperty('user.dir') + "/conf"
into "$buildDir/conf"
}

task createConf {
def conf = file("$buildDir/conf")
outputs.dir conf
doLast {
    conf.mkdirs()
    copyConf.execute()
}
}

distributions {
main {
    contents {
        from(createConf) { into "/conf" }
    }
}
}

docker {
baseImage = 'brscrt/java-8'
maintainer = 'Baris Cirit "brscrt@gmail.com"'
}

distDocker {
tag = 'brscrt/kafkaproducer'
  version = 'latest'

push = project.hasProperty('push') ? project.property('push') : false
} 


task wrapper(type: Wrapper) { gradleVersion = '2.14' }

This error on terminal:

baris@brscrt:~/workspace/KafkaProducer_Gr$ gradle build

FAILURE: Build failed with an exception.

* Where:
Build file '/home/baris/workspace/KafkaProducer_Gr/build.gradle' line: 12

* What went wrong:
A problem occurred evaluating root project 'KafkaProducer_Gr'.
    > Could not create task of type 'DockerTask'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 4.9 secs

Stacktrace is complicated. After typed gradle build --stacktrace :

baris@brscrt:~/workspace/KafkaProducer_Gr$ gradle build --stacktrace

FAILURE: Build failed with an exception.

* Where:
Build file '/home/baris/workspace/KafkaProducer_Gr/build.gradle' line: 12

* What went wrong:
A problem occurred evaluating root project 'KafkaProducer_Gr'.
 > Could not create task of type 'DockerTask'.

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project 'KafkaProducer_Gr'.
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:54)
at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:127)
at org.gradle.configuration.BuildScriptProcessor.evaluate(BuildScriptProcessor.java:38)
at org.gradle.configuration.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:43)
at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:466)
at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:77)
at org.gradle.configuration.ProjectEvaluationConfigurer.execute(ProjectEvaluationConfigurer.java:23)
at org.gradle.configuration.ProjectEvaluationConfigurer.execute(ProjectEvaluationConfigurer.java:21)
at org.gradle.api.internal.Actions$CompositeAction.execute(Actions.java:78)
at org.gradle.api.internal.Actions$TransformingActionAdapter.execute(Actions.java:130)
at org.gradle.api.internal.project.AbstractProject.configure(AbstractProject.java:442)
at org.gradle.api.internal.project.AbstractProject.allprojects(AbstractProject.java:437)
at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:40)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:142)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:113)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:81)
at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:38)
at org.gradle.launcher.exec.InProcessGradleLauncherActionExecuter.execute(InProcessGradleLauncherActionExecuter.java:39)
at org.gradle.launcher.exec.InProcessGradleLauncherActionExecuter.execute(InProcessGradleLauncherActionExecuter.java:25)
at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:50)
at org.gradle.api.internal.Actions$RunnableActionAdapter.execute(Actions.java:171)
at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:201)
at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:174)
at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:170)
at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:139)
at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
at org.gradle.launcher.Main.doAction(Main.java:48)
at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
at org.gradle.launcher.Main.main(Main.java:39)
at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:50)
at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:32)
at org.gradle.launcher.GradleMain.main(GradleMain.java:26)
Caused by: org.gradle.api.tasks.TaskInstantiationException: Could not create task of type 'DockerTask'.
at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:115)
at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:110)
at org.gradle.api.internal.AbstractTask.injectIntoNewInstance(AbstractTask.java:138)
at org.gradle.api.internal.project.taskfactory.TaskFactory.createTaskObject(TaskFactory.java:110)
at org.gradle.api.internal.project.taskfactory.TaskFactory.createTask(TaskFactory.java:70)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory.createTask(AnnotationProcessingTaskFactory.java:93)
at org.gradle.api.internal.project.taskfactory.DependencyAutoWireTaskFactory.createTask(DependencyAutoWireTaskFactory.java:39)
at org.gradle.api.internal.tasks.DefaultTaskContainer.add(DefaultTaskContainer.java:53)
at org.gradle.api.internal.project.AbstractProject.task(AbstractProject.java:929)
at org.gradle.api.Project$task.call(Unknown Source)
at se.transmode.gradle.plugins.docker.DockerPlugin.addDistDockerTask(DockerPlugin.groovy:48)
at se.transmode.gradle.plugins.docker.DockerPlugin.this$2$addDistDockerTask(DockerPlugin.groovy)
at se.transmode.gradle.plugins.docker.DockerPlugin$_apply_closure1.doCall(DockerPlugin.groovy:42)
at org.gradle.api.internal.ClosureBackedAction.execute(ClosureBackedAction.java:58)
at org.gradle.api.internal.Actions$FilteredAction.execute(Actions.java:203)
at org.gradle.api.internal.DefaultDomainObjectCollection.all(DefaultDomainObjectCollection.java:110)
at org.gradle.api.internal.DefaultDomainObjectCollection.all(DefaultDomainObjectCollection.java:115)
at org.gradle.api.DomainObjectCollection$all.call(Unknown Source)
at se.transmode.gradle.plugins.docker.DockerPlugin.apply(DockerPlugin.groovy:41)
at se.transmode.gradle.plugins.docker.DockerPlugin.apply(DockerPlugin.groovy)
at org.gradle.api.internal.plugins.DefaultProjectsPluginContainer.providePlugin(DefaultProjectsPluginContainer.java:107)
at org.gradle.api.internal.plugins.DefaultProjectsPluginContainer.addPluginInternal(DefaultProjectsPluginContainer.java:71)
at org.gradle.api.internal.plugins.DefaultProjectsPluginContainer.apply(DefaultProjectsPluginContainer.java:37)
at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyPlugin(DefaultObjectConfigurationAction.java:101)
at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:32)
at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:72)
at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:114)
at org.gradle.api.internal.project.AbstractProject.apply(AbstractProject.java:854)
at org.gradle.api.Project$apply.call(Unknown Source)
at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.groovy:34)
at org.gradle.api.Script$apply.callCurrent(Unknown Source)
at build_6evdo45vm72o57c2gvqaus0hpp.run(/home/baris/workspace/KafkaProducer_Gr/build.gradle:12)
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:52)
... 32 more
Caused by: java.lang.NoClassDefFoundError: org/codehaus/groovy/runtime/typehandling/ShortTypeHandling
at se.transmode.gradle.plugins.docker.DockerTask.<init>(DockerTask.groovy:104)
at se.transmode.gradle.plugins.docker.DockerTask_Decorated.<init>(Unknown Source)
at org.gradle.api.internal.DependencyInjectingInstantiator.newInstance(DependencyInjectingInstantiator.java:62)
at org.gradle.api.internal.ClassGeneratorBackedInstantiator.newInstance(ClassGeneratorBackedInstantiator.java:36)
at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:113)
... 64 more
Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.runtime.typehandling.ShortTypeHandling
... 69 more


BUILD FAILED

Total time: 4.897 secs

Line 12 in build.gradle : apply plugin: 'docker'


Answer:

It looks like you are using older version of gradle/groovy, because org.codehaus.groovy.runtime.typehandling.ShortTypeHandling was introduced in groovy 2.3 and according to the stack trace the class loader cannot find it while trying to apply docker plugin.

Question:

Ive been trying to test a simple project written by some students. Im testing it on Ubuntu and the project requires me to use ANTLR and a Makefile. It has been a nightmare to find a configuration of makefile, files and folders that compiles and executes successfully.

So basically this is the folder/file setup:

Makefile
test.txt
laboratorio/
  lab02/
    Main.java
    Lab02.g

The contents of Main.java are fairly simple. They just read the grammar token by token:

package laboratorios.lab02;
import org.antlr.v4.runtime.*;

public class Main{
    public static void main(String[] args) throws Exception{
        try{
            Lab02 lexer = new Lab02(new ANTLRFileStream(args[0]));
            while (lexer.nextToken().getType() != Token.EOF);
        }catch(ArrayIndexOutOfBoundsException aiobe){
            System.err.println("Must provide a valid path to the filename with the tokens");
            System.exit(1);
        }catch(Exception e){
            System.err.println("Must provide a valid path to the filename with the tokens");
            System.exit(1);
        }
    }
}

The contents of Lab02.g (the grammar) are irrelevant for the problem, but it produces a Lab02.java file (with package laboratorios.lab02) that must be compiled and referenced by the Main.java file.

The problem came when trying to test the makefile on Ubuntu. With every configuration I tried I kept getting errors (when compiling or running the Main java file) like:

  • java.lang.NoClassDefFoundError: org/antlr/v4/runtime/CharStream
  • Could not find or load main class org.antlr.v4.Tool
  • Error: Could not find or load main class

Ive followed the exact steps of this tutorial to set up antlr on my pc: Getting Started with ANTLR v4


Answer:

After many unsuccessful attempts I arrived at this magical configuration that made the whole project work nicely.

Makefile:

make:  gramatica main

gramatica: laboratorios/lab02/Lab02.g
    java org.antlr.v4.Tool laboratorios/lab02/Lab02.g

main: laboratorios/lab02/Lab02.java laboratorios/lab02/Main.java
    javac laboratorios/lab02/Lab02.java laboratorios/lab02/Main.java

run: laboratorios/lab02/Main.class
    java -cp ${CLASSPATH}:Lab02.class laboratorios/lab02/Main test.txt

clean:
    rm -rf laboratorios/lab02/*.tokens
    rm -rf laboratorios/lab02/*.class
    rm -rf laboratorios/lab02/Lab02.java
    rm -rf laboratorios/lab02/*~

I required me to set the CLASSPATH in the bashrc like this:

export CLASSPATH=.:~/your/path/to/antlr/antlr-4.2-complete.jar

As you would find in the tutorial I previously mentioned (Getting Started with ANTLR v4), it says you should write the Classpath using quotes. COMPLETELY IGNORE THAT ADVICE! Whenever I used quotes the main class wouldnt run as ANTLR was 'missing'. Also, the aliases in the tutorial are completely optional.

Some other things worth pointing out are that placing the Makefile inside the laboratorio/lab02/ folder was not helping either. Moving it out and referencing the java files from the outside helped A LOT. And the characters ".:" helped to execute the Main class as it would say it couldn't been found.

Question:

While trying to write file in specified directory i am getting exception.

Java code :-

public void jsonToYaml(JSONObject json, String studioName)
        throws JSONException, org.codehaus.jettison.json.JSONException,
        IOException {
    Yaml.dump(Yaml.dump(JsonToMap.jsonToMap(json)), new File("config.yml"));
    BufferedReader br = new BufferedReader(new FileReader("config.yml"));
    String line;
    studioName = studioName.toLowerCase();
    File writeFile = new File("sudo /var/iprotecs/idns2.0","" + studioName + ".yaml");
    FileOutputStream fos = new FileOutputStream(writeFile);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
    try {
        while ((line = br.readLine()) != null) {
            String line1 = line.replace("\"", "");
            String line2 = line1.replaceAll("!java.util.HashMap", "");
            String line3 = line2.replaceAll("---", "");
            String line4 = line3.replace("|", "");
            System.out.println(line4);
            bw.write(line4);
            bw.newLine();
        }
    } catch (FileNotFoundException e) {
        System.out.println(e);
    }
}

Exception :-

How to create file write content to it.

java.io.FileNotFoundException: sudo /var/iprotecs/idns2.0/asia.yaml (No such file or directory)

Answer:

Do not name the file sudo var/... but only /var/.... sudo is a shell command.

Question:

I have a iReport-5.6.0 file downloaded and after configuring the ireport.conf file as:

jdkhome="\usr\lib\jvm\java-7-openjdk-amd64"

When I try to run the iReport, it's showing as java.exe file not found in the above location. I am trying to run it in Ubuntu.


Answer:

Following below steps worked for me.

  1. There is a ireport file inside bin folder of the iReport package.
  2. Give it read-write permissions for all user groups.
  3. Open your terminal and go to the bin folder.
  4. Then type "./ireport".

Question:

I am new to java. I started installing oracle java in ubuntu 64 bit machine and I set the CLASS_PATH

export JAVA_HOME=/usr/lib/java/jdk1.8.0_40 set PATH="$PATH:$JAVA_HOME/bin"

If I put following command java -version in terminal it was saying 1.8 oracle java and javac -version javac 1.8.0_40

Then I created a java file and I was able to compile and execute the file. Now I installed tomcat7. now if I put java -version it is displaying

java version "1.7.0_55"
OpenJDK Runtime Environment (IcedTea 2.4.7) (7u55-2.4.7-1ubuntu1~0.13.10.1)
OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode)

and for javac -version

javac 1.8.0_40

But now I am able to compile the same java file which I compiled and run before but not I am not able to execute the file. it is saying following error ..

Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 791289926 in class file TestBean
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)

From this I can understand the javac is 1.8(oracle) and java is 1.7(openjdk). Now I need to configure to java 1.8(oracle). How will I do that? Also If I give the oracle jre full path (/usr/lib/java/jdk1.8.0_40/jre/bin/java) when executing java class file it is executing. If anyone know solutions please give me......


Answer:

Did you really set the CLASS_PATH variable? Unless you had a very specific reason you should unset that, it'll cause problems if you don't know what you are doing.

In order to configure which JDK is used on Ubuntu you should use:

sudo update-alternatives --config java

As documented in the Ubuntu help page for Java - https://help.ubuntu.com/community/Java

Question:

I'm trying to run jenkins war file, but I'm getting this error:

: Container startup failed
java.io.IOException: Failed to start Jetty

This is the command I'm running:

java -jar jenkins.war

This is the full error:

Mar 25, 2018 1:55:50 AM winstone.Logger logInternal
SEVERE: Container startup failed
java.io.IOException: Failed to start Jetty
    at winstone.Launcher.<init>(Launcher.java:154)
    at winstone.Launcher.main(Launcher.java:352)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at Main._main(Main.java:246)
    at Main.main(Main.java:91)
Caused by: java.net.BindException: Address already in use
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:433)
    at sun.nio.ch.Net.bind(Net.java:425)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:321)
    at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80)
    at org.eclipse.jetty.server.ServerConnector.doStart(ServerConnector.java:236)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.server.Server.doStart(Server.java:366)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at winstone.Launcher.<init>(Launcher.java:152)
    ... 7 more

Mar 25, 2018 1:55:51 AM hudson.util.BootFailure publish
SEVERE: Failed to initialize Jenkins
hudson.util.HudsonFailedToLoad: java.lang.InterruptedException
    at hudson.WebAppMain$3.run(WebAppMain.java:244)
Caused by: java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:502)
    at org.jvnet.hudson.reactor.Reactor.execute(Reactor.java:267)
    at jenkins.InitReactorRunner.run(InitReactorRunner.java:45)
    at jenkins.model.Jenkins.executeReactor(Jenkins.java:1009)
    at jenkins.model.Jenkins.<init>(Jenkins.java:877)
    at hudson.model.Hudson.<init>(Hudson.java:85)
    at hudson.model.Hudson.<init>(Hudson.java:81)
    at hudson.WebAppMain$3.run(WebAppMain.java:227)

I already checked port 8081 and it nothing is running on it. How to fix it?


Answer:

try on some other port using command

java -jar jenkins.war --httpPort=8089

for more info checkout this answer

Question:

I'm trying to run a simple java helloworld program with crontab. I made the following java code: helloworld.java:

class HelloWorld { 
     public static void main (String args[]) {
         System.out.println("Hello world");
   }
}

I then try to run this from a crontab in the following sequence:

  1. crontab -e
  2. At the end i insert this line 0,7,10,15,30,46,50,55,59 * * * * root /usr/bin/java /home/shivajividhale/cloudOccular/HelloWorld >/dev/null 2>&1

However, I am not able to see the helloworld putput in the syslog. Is everything correct? How do I check if the class file is being executed or not. I tried printing the output to a text file with the time on it as well. But nothing is being done on the file.

Running the file normally java HelloWorld yields proper output. I also made sure the crontab ends with a new line.

I just want to get started with having a class file run by the crontab. Oher posts discuss about crontab running bash scripts, I just want to run just this simple program. I just want to print out Hello World along with the time to ensure program execution at the defined intervals. Any help?


Answer:

You should not provide a full path when trying to execute a class with "java". The "java" command expects to receive just the class name as an argument.

That's why this works properly:

java HelloWorld

But this does not:

/usr/bin/java /home/shivajividhale/cloudOccular/HelloWorld

To make the latter work, you need to provide just the class name, and additionally a "classpath" so that Java knows where to find that class. You can use the "-cp" option to provide the classpath.

Try this:

/usr/bin/java -cp /home/shivajividhale/cloudOccular/ HelloWorld

Question:

I am using this method to generate some turtle files .ttl in a sub-directory of my project:

public static void write(int id, int depth){
        try {

            FileWriter fw = null;
            switch (getName()){
            case ("KG1"):
                fw = new FileWriter("WWW/KG1/" + depth + "/" + id + ".ttl");
            break;

            case ("KG2"):
                fw = new FileWriter("WWW/KG2/" + depth + "/" + id + ".ttl");
            }

        // Write something

        fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

But I am having this exception when I have put my project in Ubuntu (it is still working fine in Windows) in the java class FileWriter:

java.io.FileNotFoundException: /WWW/KG1/2/0.ttl (No such file or directory)

I am using Eclipse Neon for both OSs, but it seems that Ubuntu is not happy about it.

Here is what I have tried so far:

  1. Adding write permissons to ALL files and directories under the main project directory

  2. Using absolute path instead of relative path, by using System.getProperty("usr.dir"), and plotting all the path string I am giving to FileWriter, but it does not work.

Any advice?

Thanks!


Answer:

I would try using File.separator and make sure the parent directory exists. Here is an example (may have syntax issues).

final String WWW = "WWW";
final String KG1 = "KG1";
final String KG2 = "KG2";
final String extension = ".ttl";

int id = 1;
int depth = 1;

String filePath = "." // current dir
  + File.separator 
  + WWW 
  + File.separator 
  + KG1 
  + File.separator 
  + depth 
  + File.separator 
  + id 
  + extension;

File file = new File(filePath);
// make sure parent dir exists (else created)
file.getParentFile().mkdirs(); 
FileWriter writer = new FileWriter(file);

Question:

I have deployed my Java Rest Application in tomcat (ubuntu 18.04). Everything seems fine until this error shows :

java.io.FileNotFoundException: /opt/tomcat/webapps/botiv1/WEB-INF/lib/javax.inject-2.5.0-b42.jar (Too many open files)
    java.base/java.io.RandomAccessFile.open0(Native Method)
    java.base/java.io.RandomAccessFile.open(RandomAccessFile.java:345)
    java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:259)
    java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:214)
    java.base/java.util.zip.ZipFile$Source.<init>(ZipFile.java:1263)
    java.base/java.util.zip.ZipFile$Source.get(ZipFile.java:1229)
    java.base/java.util.zip.ZipFile$CleanableResource.<init>(ZipFile.java:727)
    java.base/java.util.zip.ZipFile$CleanableResource.get(ZipFile.java:845)
    java.base/java.util.zip.ZipFile.<init>(ZipFile.java:245)
    java.base/java.util.zip.ZipFile.<init>(ZipFile.java:175)
    java.base/java.util.jar.JarFile.<init>(JarFile.java:341)
    java.base/jdk.internal.reflect.GeneratedConstructorAccessor7.newInstance(Unknown Source)
    java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488)
    org.apache.tomcat.util.compat.Jre9Compat.jarFileNewInstance(Jre9Compat.java:209)
    org.apache.tomcat.util.compat.JreCompat.jarFileNewInstance(JreCompat.java:149)
    org.apache.catalina.webresources.AbstractArchiveResourceSet.openJarFile(AbstractArchiveResourceSet.java:307)
    org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.getArchiveEntry(AbstractSingleArchiveResourceSet.java:97)
    org.apache.catalina.webresources.AbstractArchiveResourceSet.getResource(AbstractArchiveResourceSet.java:256)
    org.apache.catalina.webresources.StandardRoot.getResourceInternal(StandardRoot.java:281)
    org.apache.catalina.webresources.Cache.getResource(Cache.java:62)
    org.apache.catalina.webresources.StandardRoot.getResource(StandardRoot.java:216)
    org.apache.catalina.webresources.StandardRoot.getClassLoaderResource(StandardRoot.java:225)
    org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2260)
    org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:834)
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1297)
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1157)
    org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:422)
    org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:285)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
    org.glassfish.jersey.internal.Errors.process(Errors.java:316)
    org.glassfish.jersey.internal.Errors.process(Errors.java:298)
    org.glassfish.jersey.internal.Errors.process(Errors.java:268)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    com.ritech.model.CORSFilter.doFilter(CORSFilter.java:59)

I have set the limits to 65000, but this error still shows up after a couple of hours.

/etc/security/limits.conf file

*soft nproc 65535

*hard nproc 65535

*soft nofile 65535

*hard nofile 65535 root soft nproc 65535

root hard nproc 65535

root soft nofile 65535

root hard nofile 65535

webuser hard nofile 64000

Note: This is not a database connections leak, because i have tracked the opened/active connecions, and there are not more than 4 active connections.


Answer:

I assume tomcat service is running under tomcat user. check open files with command lsof -u tomcat | wc -l check maximum number of file handles for the entire system with command: cat /proc/sys/fs/file-max

check the current usage of file handles with command: cat /proc/sys/fs/file-nr

to make the change permanent, add or change the following line in the file /etc/sysctl.conf. This file is used during the boot process. echo "fs.file-max=65536" >> /etc/sysctl.conf (values are valid after reboot)

run command ulimit -a and check number of open files( -n) and max user processes (-u) increase the values if necessary.

e.g. : in /etc/security/limits.conf file 
tomcat              hard    nofile          102400
tomcat              soft    nofile          102400

run command: systemctl status tomcat get tomcat pidand

check cat /proc/'tomcat pid'/limits, if limits are still at default values add below lines to /etc/init.d/tomcat file.

ulimit -Hn 16384

ulimit -Sn 16384

after changing /etc/init.d/tomcat file restart tomcat service toapply changes.

Question:

I'm using a ProcessBuilder to print the output of exiftool to a file. I'm trying to run this command on an .opus file: exiftool Aero.opus > Aero.txt. This runs just fine in terminal, but in the processbuilder it appears to have trouble parsing it.

Here is a simple program of it. Note that the directory is set to /home/sarah and the Aero.opus file exists in that directory.

Note also that the output prints to the console instead of to the file like it's supposed to, and that it says that it can't recognize the > operator.

@Test
public void testExifprocess() throws IOException {
    //File Located at /home/sarah/Aero.opus
    ProcessBuilder builder = new ProcessBuilder("exiftool", "Aero.opus", ">", "Aero.txt").directory(Paths.get("/home/sarah").toFile())
            .inheritIO();
    builder.start();
}

And here is the output:

Running com.protonmail.sarahszabo.stellaropusconverter.tests.StellarDiskManagerTest
File not found: >
File not found: Aero.txt
======== Aero.opus
ExifTool Version Number         : 10.80
File Name                       : Aero.opus
Directory                       : .
File Size                       : 13 MB
File Modification Date/Time     : 2018:06:29 19:19:08-04:00
File Access Date/Time           : 2018:07:16 23:20:27-04:00
File Inode Change Date/Time     : 2018:07:16 23:20:27-04:00
File Permissions                : rw-rw-r--
File Type                       : OPUS
File Type Extension             : opus
MIME Type                       : audio/ogg
Opus Version                    : 1
Audio Channels                  : 2
Sample Rate                     : 48000
Output Gain                     : 1
Vendor                          : Lavf58.17.100
Title                           : Aero
Artist                          : Daniel Deluxe
Picture Type                    : Front Cover
Picture MIME Type               : image/png
Picture Description             : Daniel Deluxe -- Aero.png
Picture Width                   : 1280
Picture Height                  : 720
Picture Bits Per Pixel          : 0
Picture Indexed Colors          : 0
Picture Length                  : 946992
Picture                         : (Binary data 946992 bytes, use -b     option to extract)
    1 image files read
    2 files could not be read

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

Home Folder:

My OS is Kubuntu 18.04, with Java 8_171.


Answer:

I assume it's just passing ">" as an argument to exiftool. I suggest you use https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#redirectOutput(java.io.File)

ProcessBuilder proc= new ProcessBuilder().command("exiftool", "Aero.opus");
proc.redirectErrorStream(true);
proc.redirectOutput(new File("Aero.txt"));
proc.start();

Question:

I am currently working on a project which requires a java program to run on the ubuntu server. This java file should be activated by php. The problem is that when I do that using this line of code:

shell_exec("java -jar /opt/lampp/htdocs/java/javafile.jar PARAMETERS");

It doesn't work and gives the error below. The weird thing is, it does work when I do it from my ubuntu terminal (without using php) or on Windows 10 (using php).

I've already tried adding this between 'java' and '-jar':

-Djava.awt.headless=true

but this gives the following error and therefor doesn't work:

Exception in thread "main" java.awt.HeadlessException at java.awt.Desktop.getDesktop(Desktop.java:142) at com.HotkeyCodeInc.Main.main(Main.java:56)

This is because I am using the Desktop function and that needs the X11 server.

The ERROR:

You can check the error yourself at: http://hotkeycode.biz.tm/java/executejava.php

No protocol specified Exception in thread "main" java.awt.AWTError: Can't 
connect to X11 window server using ':0' as the value of the DISPLAY 
variable. at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method) at         
sun.awt.X11GraphicsEnvironment.access$200(X11GraphicsEnvironment.java:65) at 
sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:115) at 
java.security.AccessController.doPrivileged(Native Method) at 
sun.awt.X11GraphicsEnvironment.(X11GraphicsEnvironment.java:74) at 
java.lang.Class.forName0(Native Method) at 
java.lang.Class.forName(Class.java:264) at 
java.awt.GraphicsEnvironment.createGE(GraphicsEnvironment.java:103) at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:82) at sun.awt.X11.XToolkit.(XToolkit.java:126) at 
java.lang.Class.forName0(Native Method) at 
java.lang.Class.forName(Class.java:264) at 
java.awt.Toolkit$2.run(Toolkit.java:860) at 
java.awt.Toolkit$2.run(Toolkit.java:855) at 
java.security.AccessController.doPrivileged(Native Method) at 
java.awt.Toolkit.getDefaultToolkit(Toolkit.java:854) at 
java.awt.Desktop.isDesktopSupported(Desktop.java:169) at 
java.awt.Desktop.getDesktop(Desktop.java:143) at 
com.HotkeyCodeInc.Main.main(Main.java:56)

PC Information

Ubuntu 17.04

XAMPP (as server)

Apache2

PHP 7.1.8


Answer:

The weird thing is, it does work when I do it from my ubuntu terminal (without using php) or on Windows 10 (using php).

I am new to Java, can you explain how to do that?

I think the most important thing is to understand the difference between the GUI in Windows and the GUI in Linux:

In Windows the GUI is part of the operating system. If some program (such as a text editor) creates a window the text editor tells Windows to open a window. If you use the mouse to click on the window Windows will tell the text editor that there was a mouse click on the window.

Linux does not have a built-in GUI. Instead there is a special program called "X server" or "X11 server" which provides the GUI: If the text editor creates a window it sends a message "create window" to the X11 server; if you press the mouse the X11 server sends a message "mouse pressed" back to the text editor.

Because Linux is a multi-user OS it distinguishes between the GUI you are using and the GUI used by Apache. Because Apache does not use a GUI the Java program (started indirectly by Apache) will fail because there is no GUI available.

This is because I am using the Desktop function ...

In both cases (Windows and Linux) your Java program will ONLY be able to interact with the GUI the web server is running on.

In other words:

When your web server is running on one PC and your web browser is running on another PC the Java program will access the GUI of the PC running the web server, not the GUI of the PC running the web browser!

Are you really sure that you want to do this?

Some explaination about alirabie's comment:

Is it possible for you to forward your X11 requests to your local desktop?

The X11 system allows you to run the "X11 server" on a computer that has display, keyboard and mouse connected while the text editor (or whatever) is running on some more powerful computer - such as a web server.

This concept is similar to web-browser based "cloud" text editors where the actual text editor is running on some web server and only the web browser is running on your local computer.

So you could install an X11 GUI on the computer which is running the web browser and configure Apache in a way that that GUI is "used by Apache"...

However I doubt that a person without a lot of X11 knowledge is able to do so...

Question:

I'm going to use web3j library inside servlet on Tomcat8 web-server on Linux server (Ubuntu 16.04).

I need to read the file from the servlet. The code in servlet is:

    Credentials credentials = null;
    String password = "secretPassword";
    String pathToWalletFile = "/home/ubuntu/.ethereum/testnet/keystore/UTC--2017-06-18T03-11-13.235052023Z--6c992fb9531c9285ca9aba80c32a63074b0acd00";
    File file = new File(pathToWalletFile);

    try {
        credentials = WalletUtils.loadCredentials(
                password,
                file
        );
    } catch (CipherException e) {
        e.printStackTrace();
    }

the file has permissions: 644 (-rw-r--r--) Tomcat8 installed with default settings using 'sudo apt install tomcat8' on Ubuntu 16.04 (user: tomcat8)

If I call servlet I get the following error:

HTTP Status 500 - /home/ubuntu/.ethereum/testnet/keystore/UTC--2017-06-18T03-11-13.235052023Z--6c992fb9531c9285ca9aba80c32a63074b0acd00 (Permission denied)

type Exception report

message /home/ubuntu/.ethereum/testnet/keystore/UTC--2017-06-18T03-11-13.235052023Z--6c992fb9531c9285ca9aba80c32a63074b0acd00 (Permission denied)

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.io.FileNotFoundException: /home/ubuntu/.ethereum/testnet/keystore/UTC--2017-06-18T03-11-13.235052023Z--6c992fb9531c9285ca9aba80c32a63074b0acd00 (Permission denied)
java.io.FileInputStream.open0(Native Method)
java.io.FileInputStream.open(FileInputStream.java:195)
java.io.FileInputStream.<init>(FileInputStream.java:138)
com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:756)
com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2740)
org.web3j.crypto.WalletUtils.loadCredentials(WalletUtils.java:76)
net.cryptonomica.tomcatweb3j.TestServlet.doGet(TestServlet.java:75)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

note The full stack trace of the root cause is available in the Apache Tomcat/8.0.32 (Ubuntu) logs.

Apache Tomcat/8.0.32 (Ubuntu)

If I put the file inside WEB-INF, it works. How to allow access to files outside WEB-INF in tomcat (or in jetty)?


UPD: User tomcat8 can read /home/ubuntu/.ethereum/ , but can not read /home/ubuntu/.ethereum/testnet/ directory

$ sudo -u tomcat8 ls /home/ubuntu/.ethereum/testnet/ 

returns:

ls: cannot access '/home/ubuntu/.ethereum/testnet/': Permission denied 

even if I add 'tomcat8' user to 'ubuntu' group

$members ubuntu 

now returns:

ubuntu tomcat8

and

$ ls -l /home/ubuntu/.ethereum/testnet/ 

returns:

total 8 
drwxr--r-- 5 ubuntu ubuntu 4096 Jun 17 17:33 geth 
srw------- 1 ubuntu ubuntu 0 Jun 18 14:08 geth.ipc 
drwxr--r-- 2 ubuntu ubuntu 4096 Jun 18 03:11 keystore 

But tomcat8 still don't have read access to /home/ubuntu/.ethereum/testnet/

Moving file to another directory (where user 'tomcat8' has access) solves problem. But I still not understand where the problem is. In general I'd like to have read access to file /home/ubuntu/.ethereum/testnet/ from servlets


Answer:

This a basic permission issue.

It looks though as if this file is under the home directory of the ubuntu user. It would be a bad idea to change permissions in that case. The better alternative would be to move the storage of these files outside any specific user's home directory or, better, move them to the tomcat user's home directory (if the directory is used just for things managed by your server)

Otherwise, what you need to do is find out which user the tomcat process is running as, then grant permissions accordingly:

sudo chown tomcat:tomcat /home/ubuntu/.ethereum/testnet/keystore/UTC--2017-06-18T03-11-13.235052023Z--6c992fb9531c9285ca9aba80c32a63074b0acd00
#OR
sudo chmod a+r /home/ubuntu/.ethereum/testnet/keystore/UTC--2017-06-18T03-11-13.235052023Z--6c992fb9531c9285ca9aba80c32a63074b0acd00
#OR grant folder access if files are dynamically generated
sudo chmod -R a+r /home/ubuntu/.ethereum/testnet/keystore/

The above code assumes the user running tomcat is named tomcat.

Question:

HTSJDK is a library for accessing common file formats, such as SAM and VCF. I want to build the HTSJDK jar. In the documentation page says that I have to use Ant for that. So I installed Ant and run the command:

ant htsjdk-jar

But I get this error:

compile-samtools:

[javac] /home/usr/Documents/samtools-htsjdk/build.xml:241: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds

[javac] Compiling 410 source files to /home/usr/Documents/samtools-htsjdk/classes

[javac] javac: invalid target release: 1.8

[javac] Usage: javac <options> <source files>

[javac] use -help for a list of possible options

BUILD FAILED

/home/usr/Documents/samtools-htsjdk/build.xml:96: The following error occurred while executing this line:

/home/usr/Documents/samtools-htsjdk/build.xml:241: Compile failed; see the compiler error output for details.

There is something wrong with the build.xml file. Here it is the beginning of the file:

<?xml version="1.0"?>

<project name="htsjdk" basedir="." default="all">

    <property name="src" value="src/java"/>
    <property name="src.test" value="src/tests"/>
    <property name="src.test.java" value="${src.test}/java"/>
    <property name="lib" value="lib"/>
    <property name="dist" value="dist"/>
    <property name="classes" value="classes"/>
    <property name="classes.test" value="testclasses"/>
    <property name="scripts" value="src/scripts"/>
    <property name="test.output" value="dist/test"/>

    <property name="javac.target" value="1.8"/>
    <property name="javac.debug" value="true"/>

    <!-- Get GIT hash, if available, otherwise leave it blank.  -->

    <property name="repository.revision" value=""/>
    <property name="htsjdk-version" value="2.0.1"/>
    <property name="htsjdk-version-file" value="htsjdk.version.properties"/>
    <property name="testng.verbosity" value="2"/>
    <property name="test.debug.port" value="5005" />  <!-- override on the command line if desired -->

Please, can someone tell me what to do to solve this problem?


Answer:

The javac task in the build.xml (which tells ant what to do) specifies a Java target version of 1.8 (which means Java 8). Seems like you are trying to compile with a lower Java version. You can check your installed Java version using javac -version.

Question:

I have an Environment Variable on an Ubuntu server, SDB_DOMAIN, that I'm trying to pass to this gradle properties file:

https://github.com/Netflix/SimianArmy/blob/master/src/main/resources/janitor.properties#L20

What's the syntax to pull environment variables into a properties file like this? I've tried a couple different ways, one example being: simianarmy.janitor.snapshots.ownerId = System.getenv("SIMIAN_OWNER_ID") but that just returns the literal value when I start the jetty server withgradlew jettRun and watch the logs.

19:55:53.957 [main] INFO  c.n.s.basic.BasicSimianArmyContext - using standard     class for simianarmy.client.recorder.class
19:55:54.060 [main] INFO  c.n.simianarmy.aws.SimpleDBRecorder - Creating SimpleDB domain: "System.getenv(SDB_DOMAIN)"
19:55:54.122 [main] WARN  c.n.simianarmy.aws.SimpleDBRecorder - Error while trying to auto-create SimpleDB domain
com.amazonaws.services.simpledb.model.InvalidParameterValueException: Value ("System.getenv(SDB_DOMAIN)") for parameter DomainName is invalid. (Service: AmazonSimpleDB; Status Code: 400; Error Code: InvalidParameterValue; Request ID: 4aabdeb2-68a5-0f49-dacd-17c96f375793)

Answer:

Here is what I did. I Wanted my Spring-Boot Application to show me $HOME variable.

My application.properties file:

variable.home = #{ systemEnvironment['HOME'] }

Class that is using it:

@Component
public class SomeName implements CommandLineRunner {

    @Value("${variable.home}" )
            String home;

    @Override
    public void run(String... args) throws Exception {
        System.out.println(home);
    }

    public String getHome() {
        return home;
    }

    public void setHome(String home) {
        this.home = home;
    }
}

Spring boot starting log:

2015-12-10 17:46:07.622  INFO 5710 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2015-12-10 17:46:07.652  INFO 5710 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
/home/dogbert
2015-12-10 17:46:07.655  INFO 5710 --- [           main] com.example.DemoApplication              : Started DemoApplication in 1.431 seconds (JVM running for 1.614)

and echo $HOME:

dogbert@borsuk:~$ echo $HOME
/home/dogbert
dogbert@borsuk:~$ 

I hope this helps.

Question:

I have a jar file , which when i execute by

 java -jar firstjar.jar

I get the following errors

Error: Invalid or corrupt jarfile firstjar.jar

Here is my manifest file

 Manifest-Version: 1.0
 Created-By: 1.7.0_79 (Oracle Corporation)
 Class-Path:mysql-connector-java-5.1.28.jar
 Main-Class:JavaApplication1

Contents of jar file

0 Wed May 13 14:09:06 IST 2015 META-INF/
140 Thu May 14 00:26:26 IST 2015 META-INF/MANIFEST.MF
2917 Wed May 13 13:16:02 IST 2015 JavaApplication1.class

Thanks in advance!


Answer:

Perhaps your jarfile is corrupted in some way, possibly due to how it was downloaded or installed.

this issue is caused by manifest file because you haven't added space after every colon in here, it should be:

Manifest-Version: 1.0 
Created-By: 1.7.0_79 (Oracle Corporation) 
Class-Path: mysql-connector-java-5.1.28.jar 
Main-Class: JavaApplication1 

after Main-Class there must be a Blank line see here https://docs.oracle.com/javase/tutorial/deployment/jar/modman.html.

Question:

Please note that I am very new to Ubuntu server and linux in general.

I have a java script that downloads an xml file from a url and imports it into my database. It works fine on my local machine, but after uploading it to my vps (which uses ubuntu 18.04 and Tomcat), I get the following error when running the script:

java.nio.file.AccessDeniedException: f1e4485c8f9fed7e4af0672c5f8bd0d0.xml
    at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:90) ~[na:na]
    at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111) ~[na:na]
    at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116) ~[na:na]
    at java.base/sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:219) ~[na:na]
    at java.base/java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:478) ~[na:na]
    at java.base/java.nio.file.Files.newOutputStream(Files.java:219) ~[na:na]
    at java.base/java.nio.file.Files.copy(Files.java:3066) ~[na:na]
    at com.keuzestress.api.keuzestressapi.resource.xml.CoolblueImport.doImport(CoolblueImport.java:53) ~[classes/:0.0.1-SNAPSHOT]
    at com.keuzestress.api.keuzestressapi.resource.xml.CoolblueImport$$FastClassBySpringCGLIB$$de9a1a6.invoke(<generated>) ~[classes/:0.0.1-SNAPSHOT]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
...

It is clear to me that there is some kind of permissions issue. What I don't know is where the file is saved. I tried checking the tomcat subfolders but I couldn't find out what folder I should give the appropriate permissions.

The java import script:

@Component
public class CoolblueImport implements importInterface{
    public List<CoolblueProduct> coolblueProductList = new ArrayList<>();
    public List<Product> productList = new ArrayList<>();
    String url = "http://feeds.performancehorizon.com/.../f1e4485c8f9fed7e4af0672c5f8bd0d0.xml";

    Logger logger = LoggerFactory.getLogger(CoolblueImport.class);

    @Autowired
    ProductRepository productRepository;

    @Transactional
    public List<Product> doImport() throws ParserConfigurationException, IOException, SAXException {
        coolblueProductList.clear();

        InputStream in = new URL(url).openStream();
        Files.copy(in, Paths.get("f1e4485c8f9fed7e4af0672c5f8bd0d0.xml"), StandardCopyOption.REPLACE_EXISTING);

        File file = new File("f1e4485c8f9fed7e4af0672c5f8bd0d0.xml");
...

Thanks in advance! Any help is welcome :)


Answer:

Ultimately your Tomcat process doesn't have the correct permission to write your .xml file to the current working directory in which Tomcat is running. When you try to run:

Files.copy(in, Paths.get("f1e4485c8f9fed7e4af0672c5f8bd0d0.xml"), StandardCopyOption.REPLACE_EXISTING); 

the Tomcat process isn't allowed to create the file.

One possibility is to create the file in a temporary directory. And one way to do that would be to change the code to be:

Files.copy(in,
    Paths.get(System.getProperty("java.io.tmpdir") + 
    System.getProperty("file.separator") + 
    "f1e4485c8f9fed7e4af0672c5f8bd0d0.xml"), StandardCopyOption.REPLACE_EXISTING);

This looks big but what it is doing is creating a file path, in an O/S independent way, to the Java temporary directory. This is a directory that virtually all processes should be able to write to in both Windows and Unix. There are other ways to do the same thing such as Files.createTempFile() that would work in a conceptually similar way.

Remember that if you use the file name again such as you have in the next line of code that you'll need to use the same path. You don't state what it is you want to do with the output file but please realize that the temporary directory is just that. In Unix a machine reboot clears it all out so if you need to keep the file you'll want a more permanent place.

Question:

So my Ubuntu terminal is claiming that the java file I'm trying to run does not exist. However, it clearly does, and it looks like I'm in the right directory. Here's what I'm trying to compile

And here's what happens

Can anybody help me with this?


Answer:

If you are sure that you are in the right directory, BE SURE that you write the filename Exactly as what it is. Because Linux is case sensitive and for example, if you have a file with name "Sample" and you try to open "sample" file, you will get the error.

if you type manually, try to use Tab button in your keyboard. it will auto-Complete the file/dir name for you. With this way, if you have typo or wrong spelling, Tab does not complete the name and you will know that there is something wrong with what you type in terminal.

Question:

I develop plug-in that works under Ubuntu. The plug-in is required to install a third party software with which it works. Installation directory is "user home" [System.getProperty("user.home")]

After installation, when I try to open the executable file from this third party software is throwing an exception -

java.io.IOException: Cannot run program >/home/mbaev/Tools/flasher/1.5.0/lua5.1.sh": error=13, Permission denied"

Where should be installed a third party software? Why this directory have permissions by default?


Answer:

There are probably two reasons:

  1. lua5.1.sh is not executable. You can make it executable by setting:

sudo chmod +x /home/mbaev/Tools/flasher/1.5.0/lua5.1.sh

And then run it:

./home/mbaev/Tools/flasher/1.5.0/lua5.1.sh

  1. If lua5.1.sh is executable but still says error=13, Permission denied. Maybe in this shell some of operations need root permission. Try to run it by sudo:

sudo ./home/mbaev/Tools/flasher/1.5.0/lua5.1.sh

Question:

I'm trying to convert an .mp4 to a .opus file using ffmpeg. I have a directory on my desktop called Indexing which has a test file called 40.mp4. I've tried using the command ffmpeg -i 40.mp4 -b:a 320k 40.opus which always works from a terminal set in the Indexing directory, but trying the same thing using Java always fails:

NOTE: I'm running on Kubuntu 17.10

private static final Path INDEXING_PATH = Paths.get("/home/sarah/Desktop/Indexing");

Process proc = new ProcessBuilder("ffmpeg -i 40.mp4 -b:a 320k 40.opus") .directory(INDEXING_PATH.toFile()).inheritIO().start();

Yields:

Exception in thread "main" java.io.IOException: Cannot run program "ffmpeg -i 40.mp4 -b:a 320k 40.opus" (in directory "/home/sarah/Desktop/Indexing"): error=2, No such file or directory at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)

Here's a snapshot of the folder:


Answer:

Java is looking for a program called ffmpeg -i 40.mp4 -b:a 320k 40.opus when in reality it should invoke ffmpeg with -i 40.mp4 -b:a 320k 40.opus as arguments

To fix this, change Process proc = new ProcessBuilder("ffmpeg -i 40.mp4 -b:a 320k 40.opus") .directory(INDEXING_PATH.toFile()).inheritIO().start();

to

Process proc = new ProcessBuilder("ffmpeg", "-i", "40.mp4", "-b:a", "320k", "40.opus") .directory(INDEXING_PATH.toFile()).inheritIO().start();

Look at This for more

Also, try adding the full path to ffmpeg in the ffmpeg portion of the command

Question:

Following is the code which I'm using to upload file:

java.io.IOException: Permission denied
    at java.io.UnixFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:1012)

Answer:

change permission of directory using command

chmod -R 777 <path>

if you want to change permission of subdirectories also

otherwise

chmod 777 <path>

Question:

I'm running a jar file but I get the following errors when I want to upload a file (which exists).

ufuoma@ufuoma-VirtualBox:~/ltserver$ java -jar lt4el-cmd.jar send -l en "file:Here.doc"
ERROR [Thread-1]: Error getting url: no protocol: Here.doc (AppInterface.java:140)

The part of the AppInterface.java file where the error is generated is (I commented line 140 for easy tracking):

public void run() {
        byte[] anaContent;
        byte[] ontContent;
        byte[] dceContent;
        Document doc = null;

        try {
        //create new Document object, initial status == FAILED
            DocumentStatus status = new DocumentStatus(DocumentStatus.Status.PROCESSING, "Preprocessing");
            doc = new Document(id, LangCode.toInt(lang), status, true, 0);
            doc.lockRW();

            //add the document and process it
            docControl.addDocument(doc);
        } catch (Exception e) {
            String error = "Error adding document: "+e.getMessage();
    /*Line 140*/ log.error(error);
            try {
                if (doc != null) {
                    docControl.setDocumentStatus(doc, DocumentStatus.Status.FAILED, error);
                    doc.unlockRW();
                }
                db.sync();    //FIXME
            } catch (Exception ex) {
                // ignore
            }
            return;
        }

        try {
            // save the document data
            log.debug("reading URL...");
            docControl.setDocumentStatus(doc, DocumentStatus.Status.PROCESSING, "Reading source document");
            readURL(url);
        } catch (Exception e) {
            String error = "Error getting url: "+e.getMessage();
            log.error(error);
            try {
                docControl.setDocumentStatus(doc, DocumentStatus.Status.FAILED, error);
                doc.unlockRW();
                db.sync();    //FIXME
            } catch (Exception ex) {
                // ignore
            }
            return;

The options for the send command are:

- send a LO (test.xml) into the LTserver, language is set to Czech. test.xml must reside in the Docs directory as specified in the property file.

    $ java -jar lt4el-cmd.jar send -l cs "test LO.xml"

By default, ID is a file name ("test LO.xml" in our example). To assign different ID, you can prepend it to the file name (separated by a colon). E.g. to give the learning object ID "lo1":

    $ java -jar lt4el-cmd.jar send -l cs "lo1:test LO.xml"

I've tried the following:

java -jar lt4el-cmd.jar send -l en "file:Here.doc"
java -jar lt4el-cmd.jar send -l en "Here.doc"
java -jar lt4el-cmd.jar send -l en "file:/path/to/Here.doc"
java -jar lt4el-cmd.jar send -l en "/path/to/Here.doc"

But it still gives the same error. I don't know where the problem is. Thanks


Answer:

The specifications actually required a HTTP url and I was giving it a file from my local system as file:/// which it couldn't resolve as FTP. Hence, I was getting: ERROR [Thread-1]: Error getting url: no protocol: . . .. To workaround it, I put the file on the XAMPP server - path/to/opt/lampp/htdocs/file - and could assess it through: http://localhost:file which was a valid HTTP url.

Question:

I want to execute a script file from Java , so i have used the following lines of code to execute the script file.

Runtime rt = Runtime.getRuntime();          

Process proc = rt.exec("/home/akshay/NetBeansProjects/testapplication/src/test_script");

But runtime.execute("path/to/file/") requires String as parameters which is path to the file , but i need to include the script file in the Jar.

So please help to how to include a script file inside the jar and also what parameters should i provide in the runtime.execute("please specify what parameters should i supply when i copy and paste the script files in the current pacakge")


Answer:

Runtime.exec requires a command name that can be interpreted by the operating system, and neither Windows, Linux or Mac OSX are capable of executing a command directly out of a JAR file (or a ZIP file or a TAR file, or ...)

You will need to extract the script file from your JAR file into the file system and then run the script from the file.


In theory, you could get the OS to mount the JAR file as a filesystem. However, this is liable to not work due to issues with file locking ... assuming that the JAR file is also on your application's classpath.

Question:

Getting errors in Ubuntu while running command ./run1.sh

javac: file not found: edge.java
Usage: javac <options> <source files>
use -help for a list of possible options
Error: Could not find or load main class median_degree

In run1.sh file

javac -cp .:libs/java-json.jar:./src edge.java ./src median_degree.java
java -cp .:libs/java-json.jar:./src median_degree

File Structure

Can anyone help on how to write script file for this? I have tried lots options but none of them is working. Thank you


Answer:

Try this:

javac -cp .:libs/java-json.jar ./src/edge.java ./src/median_degree.java

as the source files are not part of the class path and needs to be supplied as source files using the full path.

Question:

Suppose JNotify is listening to a folder named A and I copied a file f to A from folder B which is not part of a sub directory of A. At what exact point of time will JNotify notify.

1) Is it at the point when writing into the new file starts i.e when open() is called on the file to write into it?

OR

2) Is it at the point after the new file is written completely and closed i.e when close() is called on the file after completion of writing into it?

And I am not sure if copying a file involves writing into the file. But I guess it should do so.

I would like to know the scenario in ubuntu(Linux).Any reference is highly appreciated.


Answer:

JNotify does not make any guaranties as to exact timing of notification delivery. generally it depends on the operating system API, and those APIs can do their own buffering as well (Windows will behave differently than Linux or Mac).

in most non trivial file creation and writes you will be getting a series of events, not just one. you may want to have a timer on your side to get the point where the events for the file stops to determine that it's safe to operate on.

Question:

I am running a server with Ubuntu 12.04.5 and am trying to install java. I've tried a few different ways to install Java VM 7, including from WebUpd8. I've been running a Minecraft server on the machine and many plugins (made in Java) didn't function properly. Most threw errors or didn't run. So when I ran java -v in console, this error occoured:

*Unrecognized option: -v
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.*

Also, when I tried executing the same command on my Mac running OS X 10.11.2, the same error occurred.

What do you think is causing this?


Answer:

Execute the command

java -version

Question:

I'm having some trouble with saving a pic on the disk from my web server. It might be something about sufficient privileges to save a file on disk. At least I think that's what the error is about. I just switched to ubuntu so I'm a bit unfamiliar with how that works.

On windows I had :

    System.out.println("1");
    Path folder = Paths.get("/var/webapp/images"); // not null
    System.out.println("2");

    UploadedFile uploadedFile = e.getFile();
    String filename = "profile_pic";
    String extension = FilenameUtils.getExtension(uploadedFile
            .getFileName());
    System.out.println("3");

    Path file = Files.createTempFile(folder, filename + "-", "."
            + extension);
    System.out.println("4");
    //1,2,3,error

This gives me a NoSuchFileException on ubuntu. It's supposed to create a new file so sure there is no such file. Or maybe it means the parent? But it's not null. Or maybe it's that privilege thing ? I don't understand.

Caused by: java.nio.file.NoSuchFileException: /var/webapp/images/profile_pic-6949678835586050878.png
    at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
    at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
    at java.nio.file.Files.newByteChannel(Files.java:361)
    at java.nio.file.Files.createFile(Files.java:632)
    at java.nio.file.TempFileHelper.create(TempFileHelper.java:138)
    at java.nio.file.TempFileHelper.createTempFile(TempFileHelper.java:161)
    at java.nio.file.Files.createTempFile(Files.java:852)
    at main.java.managedbeans.UserProfileEdit.fileUploadListener(UserProfileEdit.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:292)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 42 more


    System.out.println("folder path : " + folder.toAbsolutePath().toString());

output : folder path : /var/webapp/images

I did try to see if that was a privilege thing but I'm not sure what I doing really.

ps aux | egrep '(wildfly)'
cedric   24184  3.5 14.2 4290528 870928 ?      Sl   20:04   3:03 /usr/lib/jvm/java-8-openjdk-amd64/bin/java -Dprogram.name=JBossTools: WildFly  9.x  -server -Xms64m -Xmx512m -Dorg.jboss.resolver.warning=true -Djava.net.preferIPv4Stack=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true -Dorg.jboss.boot.log.file=/home/cedric/Applications/wildfly-9.0.2.Final/standalone/log/boot.log -Dlogging.configuration=file:/home/cedric/Applications/wildfly-9.0.2.Final/standalone/configuration/logging.properties -Djboss.home.dir=/home/cedric/Applications/wildfly-9.0.2.Final -Dorg.jboss.logmanager.nocolor=true -Djboss.bind.address.management=localhost -Dfile.encoding=UTF-8 -classpath /home/cedric/Applications/wildfly-9.0.2.Final/jboss-modules.jar org.jboss.modules.Main -mp /home/cedric/Applications/wildfly-9.0.2.Final/modules -jaxpmodule javax.xml.jaxp-provider -jaxpmodule javax.xml.jaxp-provider org.jboss.as.standalone -b localhost --server-config=standalone.xml -Djboss.server.base.dir=/home/cedric/Applications/wildfly-9.0.2.Final/standalone
cedric   26485  0.0  0.0  13952  2468 pts/1    S+   21:30   0:00 grep -E --color=auto (wildfly)

Answer:

Check the permissions on /var/webapp/images to give cedric permission to write. The easiest way is probably to ls -l /var/webapp | grep images and get the group that owns images (and make sure images is group writable). Then add cedric to that group. Assuming it's www-data that might look something like

sudo usermod -a -G www-data cedric

The next easiest option would be to enable and add ACLs.

Question:

how to add path to File Scanner in Java? I use Ubuntu and Intellij. I think I do everythink ok, but it still doesn't work :(

Code:

 File file = new File("/abc/file.txt");

Error:

java.io.FileNotFoundException: /abc/file.txt (No such file or directory)


Answer:

Your abc folder is under src and you're using absolute pathing with the leading / which states it at the root of your file system.

Move the folder to the root folder of the project and then reference is as

File file = new File("abc/file.txt");

Question:

I'm trying to make the JavaFX application I made on Windows work for Ubuntu. I've made the .jar file and it works fine on Windows 10, but won't work on Ubuntu. Whether I double click it from the desktop (with running as executable enabled) or run it from the terminal, I keep getting these errors:

javac myApp.jar or javac myApp

error: Class names, 'myApp.jar', are only accepted if annotation processing is explicitly requested

javac -cp myApp.jar or javac -cp myApp

javac: no source files

This is the error I get on running java -jar myApp.jar:

Could not find or load main class Main
Caused by: java.lang.NoClassDefFoundError: javarx/application/Application

This is my MANIFEST file:

Manifest-Version: 1.0
Implementation-Title: 
Implementation-Version: 
Permissions: sandbox
JavaFX-Version: 8.0
Class-Path: 
Created-By: JavaFX Packager
Implementation-Vendor: 
Main-Class: Main

I have installed Java using the apt install default-jre command. I've also installed JavaFX.

I think it might be some issue with where the application tries to get its JavaFX library from, but I'm not sure whether this is it or how I'd fix it.


Answer:

default-jre package will install Open JDK 11 in Ubuntu Bionic. Java 11 removed JavaFX from the default distribution. This binaries are now shipped separately outside of the JDK, you can get them from Maven Central.

Either downgrade to a lower version of JRE/JDK or repackage the application to include the JavaFX binaries so it can work with Java 11.

Question:

This is a weird thing. I'm trying to playback some sounds via Java AudioSystem and AudioSystem.getClip(). The files are all "PCM_SIGNED, 22.050.0 Hz, 16 bit, mono, 2 bytes/frame, little endian".

On several Ubuntu 16.4 LTS Linux boxes this format is rejected by PulseAudio with an Invalid Format Exception, because the only accepted format is seemingly "PCM_SIGNED, unknown sample rate, 16 bit, stereo, 4 bytes/frame, big endian".

I already tried to re-sample my WAVs in order to match this strange constraint, to no avail. Those are not even accepted anymore by AudioSystem.getAudioInputStream()

Needless to say, that the same works fine on Mac OS and Windows. And there is also no problem to playback these files using the sox library and play file.wav


Answer:

OK, solved.

Usually if one asks, how to playback WAV using Java, this is the most common answer:

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(DragonflyApp.class.getResource("/resources/" + soundFile));
clip = AudioSystem.getClip();
clip.addLineListener(e -> {
    if (e.getType() == LineEvent.Type.STOP) {
        // Do something on end of playback
    }
});
clip.open(audioInputStream);
clip.start();

Unfortunately on some Linux systems this ends up in an "Invalid Format" exception, thrown by PulseAudio, which claims to be unable to playback the simplest WAV file (see above).

The workaround is to use this sequence under Linux instead. It generally does also work on MacOS, but the final "STOP" indication comes very late (roughly 5s after playback end), so I make a conditional execution here:

This works on Linux (at least on Ubunutu 16.04) with clips, which have formerly been rejected by PulseAudio:

DataPusher datapusher = null;
DataLine.Info lineinfo = null;
SourceDataLine sourcedataline = null;
lineinfo = new DataLine.Info(SourceDataLine.class, audioInputStream.getFormat());
if (!(AudioSystem.isLineSupported(lineinfo))) {
    return;
}
sourcedataline = (SourceDataLine) AudioSystem.getLine(lineinfo);
sourcedataline.addLineListener(e -> {
    if (e.getType() == LineEvent.Type.STOP) {
        // Do something on end of playback
    }
});
datapusher = new DataPusher(sourcedataline, audioInputStream);
datapusher.start();

Both code snippets are used conditionally:

if (System.getProperty("os.name").equals("Mac OS X")) {
    // The clip solution
}
else {
    // The datapusher solution
}

Hope, that helps others, who will also have this problem.

Question:

So I have a jar file that works perfectly fine on Windows and Mac, but not on Ubuntu (the only place where Openjdk is installed) This question hints at OpenJDK being the problem: Java Application main class not found on Ubuntu So: how do I show OpenJDK the correct Main Class? (Its Client.class in /chat in the jar file) I know it has something to do with the MetaINF File, but I cant guess the correct input there. This is what's currently in the MANIFEST.MF file:

Manifest-Version: 1.0

Main-Class: Chat.Client

I cant find anything anywhere on the topic, but I also cant install the proprietary java on the Ubuntu PC, as its the one where the jar HAS to run and the one where I m not admin at.


Answer:

Its Client.class in /chat in the jar file

Then Main-Class: Chat.Client is incorrect, it should be Main-Class: chat.Client (lower case chat).

So probably not an OpenJDK issue, just the fact that some file systems are case-insensitive and others are case-sensitive. You're almost certainly using a case-insensitive one on Windows. I guess you must be on Mac as well, though I find that surprising. You probably aren't on Ubuntu.

Question:

I have a simple Java application on my Ubuntu 16.04 Server. This application generates a prices.txt file. The File is generated if I start it directly with:

java -jar TankstellenLogger.jar

If I schedule it with cron it doesn´t create that file and I have no Idea why? The file is running because in cron I see the Log.txt which I want to have the other output, but thats not all.

crontab -e

# m h  dom mon dow   command
* * * * * /home/dominik/startLogger.sh > /home/dominik/Log.txt

StartLogger.sh

#!/bin/bash
java -jar /home/dominik/TankstellenLogger.jar

Answer:

"prices.txt" is possibly being written to a directory other than where you're expecting. Try adding this to the bottom of "startLogger.sh":

pwd
ls prices.txt 2>&1

That should print the working directory to "/home/dominik/Log.txt" as well as a check for whether "prices.txt" is there. If that info doesn't show up in "Log.txt", it may be a permissions problem.

Question:

my docker file:

FROM tomcat

MAINTAINER "Shan Khan <xxx@gmail.com">

RUN ["rm", "-rf", "/usr/local/tomcat/webapps/ROOT"]

COPY ROOT.war /usr/local/tomcat/webapps/

CMD ["/usr/local/tomcat/bin/catalina.sh", "run"]

running as:

sudo docker build -t webserver
sudo docker run -it --rm -p 8080:8080 webserver

tomcat is running but im unable to access in the localhost:8080 or localhost:8080/ROOT


Answer:

When I was doing this for a work project I seem to remember having to deploy the app to the Tomcat root.

Deploying my application at the root in Tomcat

So basically you would need to add some steps to your Dockerfile to accomplish this.

Question:


Answer:

Thats very possible - there seems to be plenty of stuff on google here's one example.

In answer to your second part: the trick is to run both the client and the server on your own computer, and the client connects (over the loopback ip address "localhost") to the same machine.

Question:

I have it like this:

file=new File(pathString+"/TileRecordings/",jTextField1.getText()+".txt");

and then after null checking etc...

file.createNewFile();

Thing is, if the texfield value was 'test' it would create 'text.txt' AS A FOLDER. Not an actual text file. Is this a Ubuntu only thing? How do I force it to literally create a text file, not a folder named 'test.txt'.


Answer:

Maybe try features from java.nio.file for example:

Path temp = Paths.get(pathString+"/TileRecordings/"+jTextField1.getText()+".txt");
Files.write(temp, contentToSave.toString().getBytes());

Question:

I am running tomcat7 inside of Eclipse on Ubuntu. When publishing to localhost, tomcat could not copy any of the files. They all showed as "No such file or directory". I have those files, I can see them in eclipse and local directory. Is there a file configures which directory tomcat will copy the files from? What am I missing?


Answer:

It's a permission thing. Also I recommend install tomcat manually instead of running apt-get. Either https://askubuntu.com/questions/17223/permissions-problem-when-copying-files-to-usr-share-tomcat6 or http://www.frattv.com/tomcat-can-t-start-from-ide-eclipse-luna-wtp-intellij-idea-in-ubuntu/ will work.

Question:

I have been trying to solve this for a few days now but I just can't seem to grasp why this isn't working properly. I am trying to launch a jar file from ProcessBuilder but it just says that the jar file isn't found. If I run the exact same command from the terminal then it runs like a charm. Any help would be greatly appreciated.

Note: The parameter s is the server file, I have already confirmed that the proper parameter is being passed down.

Here is a shortened version of the method (It errors on pb.start):

public static void startServer(String s){
    File server = new File(DataManager.getWorkingDirectory() + "/Servers/" + s + "/");
    if(server.exists()){
        if(serverProcess == null){
            try{
                String OS = System.getProperty("os.name").toLowerCase();
                boolean isLinux = (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0) ? true : false;
                //java -jar -XX:MaxPermSize=126M -Xmx1G -jar ...(PathToJar)/server.jar
                ProcessBuilder pb = new ProcessBuilder("java", "-jar", "-XX:MaxPermSize=" + permSize + "M", "-Xmx" + ramAmount + "G", "\"" + (!isLinux ? DataManager.getWorkingDirectory().replace("\\", "/") : "") + "Servers/" + s + "/server.jar\"", "nogui");
                if(!isLinux){
                    pb.directory(server);
                }else{
                    pb.directory(new File(DataManager.getWorkingDirectory()));
                }
                logger.info("Starting Server...");
                final Process p = pb.start();
                GUIMain.serverProcess  = p;

Here is the entire method:

public static void startServer(String s){
    File server = new File(DataManager.getWorkingDirectory() + "/Servers/" + s + "/");
    if(server.exists()){
        if(serverProcess == null){
            try{
                String OS = System.getProperty("os.name").toLowerCase();
                boolean isLinux = (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0) ? true : false;
                //java -jar -XX:MaxPermSize=126M -Xmx1G -jar ...(PathToJar)/server.jar
                ProcessBuilder pb = new ProcessBuilder("java", "-jar", "-XX:MaxPermSize=" + permSize + "M", "-Xmx" + ramAmount + "G", "\"" + (!isLinux ? DataManager.getWorkingDirectory().replace("\\", "/") : "") + "Servers/" + s + "/server.jar\"", "nogui");
                if(!isLinux){
                    pb.directory(server);
                }else{
                    pb.directory(new File(DataManager.getWorkingDirectory()));
                }
                logger.info("Starting Server...");
                final Process p = pb.start();
                GUIMain.serverProcess  = p;
                Thread thread = new Thread(){
                    public void run(){
                        try{
                            if(serverList != null){
                                serverList.setEnabled(false);
                            }
                            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                            String s = null;
                            while ((s = stdInput.readLine()) != null) {
                                if(s.toUpperCase().contains("EULA")){
                                    updateTextPane("<font color=\"red\">" + s.replace("Go to eula.txt for more info.", "Please press the <font color=\"green\">Agree to EULA</font> button to agree to the EULA.") + "</font>");
                                    runCommand("stop");
                                }else{
                                    updateTextPane(s);
                                }
                            }
                            while ((s = stdError.readLine()) != null) {
                                updateTextPane(s);
                            }
                            try{
                                Field field = p.getClass().getDeclaredField("hasExited");
                                field.setAccessible(true);
                                while (!(boolean) field.get(p)) {}
                            }catch(Exception e){
                                CrashReport.logStackTrace(e.getMessage(), e.getStackTrace());
                                updateTextPane("<font color=\"red\">Server is offline.</font>");
                                GUIMain.serverProcess = null;
                                if(serverList != null){
                                    serverList.setEnabled(true);
                                }
                            }
                        }catch(Exception e){
                            CrashReport.logStackTrace(e.getMessage(), e.getStackTrace());
                        }
                    }
                };
                thread.start();
            }catch(Exception e1){
                CrashReport.logStackTrace(e1.getMessage(), e1.getStackTrace());
            }
        }else{
            updateTextPane("<font color=\"red\">Server is already running!</font>");
        }
    }else{
        logger.error("The server " + server.toString() + " doesn't exist!");
    }
}

Answer:

Most likely this happens because you quote the path when passing it to the ProcessBuilder:

"\"" + (!isLinux ? DataManager.getWorkingDirectory().replace("\\", "/") : "") + "Servers/" + s + "/server.jar\""

ProcessBuilder takes care of quoting arguments, so you end up with double quoting. Try the following instead:

(!isLinux ? DataManager.getWorkingDirectory().replace("\\", "/") : "") + "Servers/" + s + "/server.jar"

Another thing that looks suspicious is that relative path is used under Linux. This might be a problem as well.

Question:

I took the following steps in making a JAR file with the audio file I found at: http://www.orangefreesounds.com/loud-alarm-clock-sound/

  1. Open Eclipse, create a new Java project.
  2. Download the audio file, place it in the src/sound-effects folder of the project.
  3. Copy and paste the code below into some class named Sandbox
  4. In the Project Explorer window (probably on the left-hand side of your screen), right-click on your project and click Export ... as a JAR file
  5. Run it in the terminal of a Windows or Linux system using java -jar.

The file structure should look like:

I have x64 Windows 8.1 and x64 Ubuntu 14.04 installed on my computer. My question is: why does this JAR program work in Windows but not Ubuntu?

import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.*;

public class Sandbox
{

    public static void main(String[] args)
            throws UnsupportedAudioFileException, IOException,
            LineUnavailableException
    {

        URL url = Sandbox.class
                .getResource("/sound-effects/Loud-alarm-clock-sound.wav");
        AudioInputStream ais = AudioSystem.getAudioInputStream(url);
        AudioFormat af = ais.getFormat();
        DataLine.Info info = new DataLine.Info(Clip.class, af);

        Clip clip = (Clip) AudioSystem.getLine(info);
        clip.open(ais);
        clip.start();
        System.out.println("Drain...");
        clip.drain();
        System.out.println("...Drained");
    }
}

Answer:

The problem here is that I had OpenJDK 1.7 (or IcedTea) installed on my Ubuntu system, and Oracle JDK 1.8 on my Windows system. As you know, OpenJDK is simply an open source version of Oracle's JVM and compiler. Sadly, this means that it has a few compatibility issues, such as not being able to play certain audio files.

I simply uninstalled OpenJDK 1.7 following the directions here: https://askubuntu.com/questions/335457/how-to-uninstall-openjdk

Then I installed Oracle JDK 1.8 using this link: http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html

Now my audio files are able to be played fine on both Ubuntu and Windows.

Question:

Hy. I'm trying to compile a .java file using docker. I read the files on docker's website, also I read these links:

docker's website

about volumes

and another question I had put up for gcc compiler

I understood the concept for the gcc compiler since it doesn't create any extra file for compiling. But the java one does. It creates a Main.class file on my /home directory if I use the following command and compile a file named Main.java

sudo docker run --rm -v "$PWD":/usr/src/myapp -w /usr/src/myapp java:7 javac Main.java

after learning from the above links I was able to successfully compile a java file with my own path using:

docker run --rm -v /mypathhere/mycode.java:/mycode.java: java:7 javac mycode.java"

if there is any error it shows an error but if there isn't it just compiles and gives me no output, and that's justified because it creates a Main.class file.

My problem is that I am unable to find that Main.class file. I don't know where docker is creating it and I have zero understanding for it. Please help me out.


Answer:

The .class file will be inside the container, under the root directory.

The best plan is to mount the whole source directory and have javac put the result to the same directory e.g:

docker run --rm -v /mypathhere:/mycode java:7 sh -c "cd mycode; javac mycode.java"

That way, you should get the class file written to the mypathhere directory.

Apologies if that doesn't quite work - it's off the top of my head. Hopefully you get the idea though.

Question:

This is one of a few Bash scripts I create in my pipeline. My Difficulty is I would like to make the created file executable without the user having to enter into the terminal "sudo chmod 777 /file/path/"

String Trans_ref = 
    "#!/bin/bash \n" +
    "mkdir -p "+Output+"/"+Sample+"_RSEM \n" +
    "cd "+Output+"/"+Sample+"_RSEM \n" +
    "PATH=$PATH:"+RSEMprep+" \n" +
    "export PATH=$PATH \n" + 
    ""+RSEMprep+"/rsem-prepare-reference --no-polyA --bowtie "+Output+"/Trans_CDHIT.fast Trans_CDHIT.RSEM \n" +    
    ""+RSEMprep+"/rsem-calculate-expression --paired-end -p "+CPU+" "+Output+"/SRR617145_1.fastq "+Output+"/SRR617145_2.fastq Trans_CDHIT.RSEM Trans_CDHIT.genes.results  \n"+
    ""+Trinprep+"/util/misc/count_features_given_MIN_FPKM_threshold.pl "+Output+"/"+Sample+"_RSEM/RSEM.genes.results > "+Output+"/"+Sample+"_RSEM/cumul_counts.txt \n"+
    ""+Trinprep+"/util/filter_fasta_by_rsem_values.pl --rsem_output= "+Output+"/"+Sample+"_RSEM/RSEM.isoforms.results --fasta="+Output+"/Trans_CDHIT.fasta -t 100 --output="+Output+"/"+Sample+"_RSEM/Trans_RSEMfilters.fasta \n" +
    ""+Trinprep+"/util/bowtie_PE_separate_then_join.pl --seqType fq --left "+Output+"/"+Sample+"_1.fasta --right "+Output+"/"+Sample+"_2.fasta --target "+Output+"/Trans_CDHIT.fasta --aligner bowtie --SS_lib_type FR -- -p 4 --all --best --strata -m 300 \n";  


        System.out.println(Trans_ref);

        FileUtils.writeStringToFile(new File(Output+"/TranRSEM"), Trans_ref);
        StringBuffer Trim = new StringBuffer();

        String cmd = (Output+"/TranRSEM");


    Process p;

    try{
        p = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c", cmd});

        p.waitFor();

        BufferedReader reader1 = 
                        new BufferedReader(new InputStreamReader(p.getInputStream()));

            System.out.println("Merg Finished");

        } catch (Exception e) {
        e.printStackTrace();


        }

many thanks


Answer:

There are a couple ways, but the best would be to use SetExecutable once you created the file. It would look something like this.

 if (file.exists()) {
            boolean bval = file.setExecutable(true);
            ..... set the owner's execute permission
        } else {
            ...... File does not exist;
        }


 if (file.exists()) {
            boolean bval = file.setExecutable(true, false);
            ..... set everybody's execute permission
        } else {
            ...... File does not exist;
        }

Hope this helps

Question:

I'm trying to write a parser to a file called "x". I want to use scanner. I tryied to follow actions from a tutorial: https://www.youtube.com/watch?v=3RNYUKxAgmw.

package q;

import java.io.File;
import java.util.Scanner;

public class Parser {
    public static void main(String [] args) {
        Scanner x = new Scanner(new File("/home/x/eclipse-workspace/q/src/q/x.txt"));
        String s=x.nextLine();
        System.out.print(s);
    }
}

The file that I want to open is called "x", its text file. We can see it in Package Explorer on left side. I clicked right on its properties. There is visible file locatization.

There appears FileNotFoundException as on the picture. I doesn't understand why this file cannot be opened.

[update] But I'm not sure if this is what


Answer:

There appears FileNotFoundException as on the picture. I doesn't understand why this file cannot be opened.

That's not what's happening. The error is in compilation time (the program has not executed, it doesn't know if the file -will- exist). The compiler is telling you "this method/constructor, according to its declaration, can throw an Exception (in this case: a FileNotFoundException ) at run time; you have not told me what to do in that case".

You really need to read about how Exceptions are treated in Java.

For a quick remedy, add a throws Exception to your main declaration. (Bear in mind: that is an awful thing to do if you don't really understand what are you doing)

Question:

javac: directory not found: bin
Usage: javac <options> <source files>
use -help for a list of possible options

when i try to run

javac -sourcepath src Downloads//Runner.java -d bin

i get error.

those are my paths

  vegan@vegan:~$ echo $PATH
/home/vegan/bin:/home/vegan/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin:/usr/lib/jvm/java-8-oracle/bin
vegan@vegan:~$ echo $JAVA_HOME
/usr/lib/jvm/java-8-oracle
vegan@vegan:~$ 

because in doc it says

ACME has a utility which generates audit reports - lists of files owned by

users. Substitute JAVA_HOME with your JVM installation and you can build & run the utility like this:

export JAVA_HOME=/usr/lib/jvm/java-7-oracle
$JAVA_HOME/bin/javac -sourcepath src src/com/reengen/utils/auditreporter/Runner.java -d bin

Answer:

Create the bin directory first. Run mkdir bin and try again.

Question:

I'm using IntelliJ and Spring and Java to locally develop an app on a Mac, and then deploy to a tomcat server on AWS, using Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-1048-aws x86_64). I'm having trouble specifying the file path so that it works in both environments.

My code is

        InputStream fileStream = new FileInputStream("src/main/resources/static/web/data/ReportDates.json");
        JsonReader reader = Json.createReader(fileStream);
        JsonObject reportDates = reader.readObject();
        reader.close();

When I run locally, the file is read in correctly. It is located in:

src/main/resources/static/web/data/ReportDates.json

But when I deploy, that code results in the error message:

java.io.FileNotFoundException: src/main/resources/static/web/data/ReportDates.json (No such file or directory)

The actual location of the file on that machine turns out to be:

/opt/tomcat/webapps/automentor/WEB-INF/classes/static/web/data/ReportDates.json

How can I specify the file path so that it works correctly in both environments?


Answer:

I have given up on using a single path. @Nicholas Pesa got me thinking -- since I use IDEA, I don't have a fixed WEB-INF folder, so it's easier for me to change the path that should be used than to move the file to a fixed location. My code now uses:

        String filepath = (new File("src/main/resources/static/web/data/ReportDates.json").exists()) ? "src/main/resources/static/web/data/ReportDates.json" : "/opt/tomcat/webapps/automentor/WEB-INF/classes/static/web/data/ReportDates.json";