Example usage for java.io IOException getCause

List of usage examples for java.io IOException getCause

Introduction

In this page you can find the example usage for java.io IOException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:csiro.pidsvc.mappingstore.Manager.java

@SuppressWarnings("unchecked")
protected String unwrapCompressedBackupFile(HttpServletRequest request, ICallback callback) {
    java.util.List<FileItem> fileList = null;
    GZIPInputStream gis = null;// ww w .j  ava  2  s  . c o  m
    String ret = null;

    try {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        // Set the size threshold, above which content will be stored on disk.
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
        //         fileItemFactory.setSizeThreshold(100 * 1024); // 100 KB

        // Set the temporary directory to store the uploaded files of size above threshold.
        fileItemFactory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

        fileList = uploadHandler.parseRequest(request);
        for (FileItem item : fileList) {
            if (item.isFormField())
                continue;

            try {
                // Try to restore the backup file as it was in binary format.
                gis = new GZIPInputStream(item.getInputStream());
                ret = callback.process(gis);
                gis.close();
            } catch (IOException ex) {
                String msg = ex.getMessage();
                if (msg != null && msg.equalsIgnoreCase("Not in GZIP format")) {
                    // Try to restore the backup file as it was unzipped.
                    ret = callback.process(item.getInputStream());
                } else
                    throw ex;
            }

            // Process the first uploaded file only.
            return ret;
        }
    } catch (Exception ex) {
        String msg = ex.getMessage();
        Throwable linkedException = ex.getCause();
        _logger.warn(msg);
        if (linkedException != null)
            _logger.warn(linkedException.getMessage());
        if (msg != null && msg.equalsIgnoreCase("Not in GZIP format"))
            return "ERROR: Unknown file format.";
        else
            return "ERROR: " + (msg == null ? "Something went wrong."
                    : msg + (linkedException == null ? "" : " " + linkedException.getMessage()));
    } finally {
        try {
            // Close the stream.
            gis.close();
        } catch (Exception ex) {
        }
        if (fileList != null) {
            // Delete all uploaded files.
            for (FileItem item : fileList) {
                if (!item.isFormField() && !item.isInMemory())
                    ((DiskFileItem) item).delete();
            }
        }
    }
    _logger.trace("No file found.");
    return "ERROR: No file.";
}

From source file:org.codice.ddf.endpoints.rest.RESTEndpoint.java

private Metacard generateMetacard(MimeType mimeType, String id, InputStream message)
        throws MetacardCreationException {

    List<InputTransformer> listOfCandidates = mimeTypeToTransformerMapper.findMatches(InputTransformer.class,
            mimeType);//from  w  w  w .j a va 2 s. co m

    LOGGER.trace("Entering generateMetacard.");
    LOGGER.debug("List of matches for mimeType [{}]: {}", mimeType, listOfCandidates);

    Metacard generatedMetacard = null;

    try (FileBackedOutputStream fileBackedOutputStream = new FileBackedOutputStream(1000000)) {

        try {
            if (null != message) {
                IOUtils.copy(message, fileBackedOutputStream);
            } else {
                throw new MetacardCreationException(
                        "Could not copy bytes of content message.  Message was NULL.");
            }
        } catch (IOException e) {
            throw new MetacardCreationException("Could not copy bytes of content message.", e);
        }

        Iterator<InputTransformer> it = listOfCandidates.iterator();

        StringBuilder causeMessage = new StringBuilder("Could not create metacard with mimeType ");
        causeMessage.append(mimeType);
        causeMessage.append(". Reason: ");
        while (it.hasNext()) {
            InputTransformer transformer = it.next();

            try (InputStream inputStreamMessageCopy = fileBackedOutputStream.asByteSource().openStream()) {
                generatedMetacard = transformer.transform(inputStreamMessageCopy);
            } catch (CatalogTransformerException | IOException e) {
                causeMessage.append(System.lineSeparator());
                causeMessage.append(e.getMessage());
                // The caught exception more than likely does not have the root cause message
                // that is needed to inform the caller as to why things have failed.  Therefore
                // we need to iterate through the chain of cause exceptions and gather up
                // all of their message details.
                Throwable cause = e.getCause();
                while (null != cause && cause != cause.getCause()) {
                    causeMessage.append(System.lineSeparator());
                    causeMessage.append(cause.getMessage());
                    cause = cause.getCause();
                }
                LOGGER.debug("Transformer [{}] could not create metacard.", transformer, e);
            }
            if (generatedMetacard != null) {
                break;
            }
        }

        if (generatedMetacard == null) {
            throw new MetacardCreationException(causeMessage.toString());
        }

        if (id != null) {
            generatedMetacard.setAttribute(new AttributeImpl(Metacard.ID, id));
        } else {
            LOGGER.debug("Metacard had a null id");
        }
    } catch (IOException e) {
        throw new MetacardCreationException("Could not create metacard.", e);
    }
    return generatedMetacard;

}

From source file:de.unirostock.sems.cbarchive.web.rest.ShareApi.java

@POST
@Path("/import")
@Produces(MediaType.TEXT_PLAIN)//from ww  w .ja  v a  2 s  . co m
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadArchive(@CookieParam(Fields.COOKIE_PATH) String userPath,
        @CookieParam(Fields.COOKIE_USER) String userJson, @Context HttpServletRequest requestContext,
        @FormDataParam("request") String serializedRequest,
        @FormDataParam("archive") FormDataBodyPart archiveFile,
        @FormDataParam("additionalFile") List<FormDataBodyPart> additionalFiles) {
    // user stuff
    UserManager user = null;
    try {
        user = new UserManager(userPath);
        if (userJson != null && !userJson.isEmpty())
            user.setData(UserData.fromJson(userJson));
    } catch (IOException e) {
        LOGGER.error(e, "Cannot create user");
        return buildTextErrorResponse(500, null, "user not creatable!", e.getMessage());
    }

    ImportRequest request = null;
    ObjectMapper mapper = null;
    try {

        mapper = ((ObjectMapperProvider) providers.getContextResolver(ObjectMapper.class,
                MediaType.WILDCARD_TYPE)).getContext(null);
        request = mapper.readValue(serializedRequest, ImportRequest.class);

        if (request == null) {
            LOGGER.error("Cannot deserialize import request");
            return buildTextErrorResponse(500, user, "Cannot deserialize import request");
        } else if (request.isValid() == false)
            return buildTextErrorResponse(400, user, "import request is not set properly");

    } catch (IOException e) {
        LOGGER.error(e, "Cannot deserialize import request");
        return buildTextErrorResponse(500, user, "Cannot deserialize import request", e.getMessage());
    }

    // check maximum archives
    if (Tools.checkQuota(user.getWorkspace().getArchives().size(), Fields.QUOTA_ARCHIVE_LIMIT) == false) {
        LOGGER.warn("QUOTA_ARCHIVE_LIMIT reached in workspace ", user.getWorkspaceId());
        return buildTextErrorResponse(507, user, "Maximum number of archives in one workspace reached!");
    }

    String archiveId = null;
    try {
        archiveId = importOrCreateArchive(user, request, archiveFile);
    } catch (ImporterException e) {
        return buildTextErrorResponse(400, user, e.getMessage(), e.getCause().getMessage());
    }

    try (Archive archive = user.getArchive(archiveId)) {
        // set own VCard
        if (request.isOwnVCard())
            setOwnVCard(user, request, archive);

        try {
            // import additional files
            if (request.getAdditionalFiles() != null && request.getAdditionalFiles().size() > 0) {
                addAdditionalFiles(user, request, archive, additionalFiles);
            }
        } catch (ImporterException e) {
            // catch quota-exceeding-exception (Logging already done)
            user.deleteArchiveSilent(archiveId);
            return buildTextErrorResponse(507, user, e.getMessage(),
                    e.getCause() != null ? e.getCause().getMessage() : null);
        }

        archive.getArchive().pack();

    } catch (IOException | CombineArchiveWebException e) {
        LOGGER.error(e, "Cannot open/pack newly created archive");
        user.deleteArchiveSilent(archiveId);
        return buildTextErrorResponse(500, user, "Cannot open newly created archive: ", e.getMessage());
    } catch (ImporterException e) {
        LOGGER.error(e, "Something went wrong with the extended import");
        user.deleteArchiveSilent(archiveId);
        return buildTextErrorResponse(500, user, "Error while applying additional data to the archive");
    } catch (TransformerException e) {
        LOGGER.error(e, "Something went wrong while packing the archive");
        user.deleteArchiveSilent(archiveId);
        return buildTextErrorResponse(500, user, "Something went wrong while packing the archive");
    }

    // redirect to workspace
    return buildSuccesResponse(user, request, archiveId, requestContext);
}

From source file:net.pms.io.ThreadedProcessWrapper.java

/**
 * Runs a process with the given command {@link List}.
 *
 * @param command an array of {@link String} used to build the command line.
 * @param timeoutMS the process timeout in milliseconds after which the
 *            process is terminated. Use zero for no timeout, but be aware
 *            of the <a href=/*  w ww . j a va  2s  . c  om*/
 *            "https://web.archive.org/web/20121201070147/http://kylecartmell.com/?p=9"
 *            >pitfalls</a>
 * @param terminateTimeoutMS the timeout in milliseconds to wait for each
 *            termination attempt.
 * @return The {@link ProcessWrapperResult} from running the process.
 * @throws IllegalArgumentException If {@code command} is {@code null} or
 *             empty.
 */
@Nonnull
public Future<R> runProcess(@Nonnull final List<String> command, final long timeoutMS,
        final long terminateTimeoutMS) {
    if (command == null || command.isEmpty()) {
        throw new IllegalArgumentException("command can't be null or empty");
    }
    final String executableName;
    if (isNotBlank(command.get(0))) {
        Path executable = Paths.get(command.get(0)).getFileName();
        if (executable != null) {
            executableName = executable.toString();
        } else {
            executableName = command.get(0);
        }
    } else {
        executableName = command.get(0);
    }
    final int threadId = PROCESS_COUNTER.getAndIncrement();

    Callable<R> callable = new Callable<R>() {

        @Override
        public R call() throws InterruptedException {
            boolean manageProcess = timeoutMS > 0;
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            if (LOGGER.isTraceEnabled()) {
                //XXX: Replace with String.join() in Java 8
                LOGGER.trace("Executing \"{}\"", StringUtils.join(command, " "));
            }
            Process process;
            try {
                process = processBuilder.start();
            } catch (IOException e) {
                LOGGER.debug("IOException when trying to start \"{}\" process: {}", executableName,
                        e.getMessage());
                LOGGER.trace("", e);
                return consumer.createResult(null, Integer.MIN_VALUE, e);
            }
            Future<T> output = consumer.consume(process.getInputStream(),
                    "TPW \"" + executableName + "\" consumer " + threadId);
            if (manageProcess) {
                Services.processManager().addProcess(process, executableName, timeoutMS, terminateTimeoutMS);
            }
            int exitCode = Integer.MIN_VALUE;
            boolean interrupted = false;
            boolean shutdown = false;
            do {
                interrupted = false;
                try {
                    exitCode = process.waitFor();
                } catch (InterruptedException e) {
                    interrupted = Thread.interrupted();
                    if (!shutdown) {
                        if (manageProcess) {
                            Services.processManager().shutdownProcess(process, executableName);
                            manageProcess = false;
                        } else {
                            Services.processManager().addProcess(process, executableName, 0,
                                    terminateTimeoutMS);
                        }
                        shutdown = true;
                    }
                }
            } while (interrupted);
            if (manageProcess) {
                Services.processManager().removeProcess(process, executableName);
            }
            try {
                return consumer.createResult(output.get(), exitCode, null);
            } catch (ExecutionException e) {
                Throwable cause = e.getCause() != null ? e.getCause() : e;
                LOGGER.error("ExecutionException in \"{}\" consumer, no output will be returned: {}",
                        executableName, cause.getMessage());
                LOGGER.trace("", e);
                return consumer.createResult(null, exitCode, cause);
            }
        }
    };
    FutureTask<R> result = new FutureTask<R>(callable);
    Thread runner = new Thread(result, "TPW \"" + executableName + "\" " + threadId);
    runner.start();
    return result;
}

From source file:org.apache.stanbol.commons.opennlp.OpenNLP.java

private <T> T loadModel(String name, Class<T> modelType, Map<String, String> modelProperties)
        throws InvalidFormatException, IOException {
    if (modelProperties != null) { //copy the data to avoid external modifications
        modelProperties = new HashMap<String, String>(modelProperties);
    } else {//w w  w.j  a va  2s. c o  m
        modelProperties = new HashMap<String, String>();
    }
    if (!modelProperties.containsKey("Description")) {
        modelProperties.put("Description", "Statistical model for OpenNLP");
    }
    if (!modelProperties.containsKey("Model Type")) {
        modelProperties.put("Model Type", modelType.getSimpleName());
    }
    if (!modelProperties.containsKey("Download Location")) {
        modelProperties.put("Download Location", DOWNLOAD_ROOT + name);
    }
    InputStream modelDataStream;
    try {
        modelDataStream = lookupModelStream(name, modelProperties);
    } catch (IOException e) {
        log.debug("Unable to load Resource {} via the DataFileProvider", name);
        return null;
    }
    if (modelDataStream == null) {
        log.debug("Unable to load Resource {} via the DataFileProvider", name);
        return null;
    }
    T built;
    try {
        Constructor<T> constructor;
        constructor = modelType.getConstructor(InputStream.class);
        built = constructor.newInstance(modelDataStream);
    } catch (SecurityException e) {
        throw new IllegalStateException(
                String.format("Unable to create %s for %s!", modelType.getSimpleName(), name), e);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException(
                String.format("Unable to create %s for %s!", modelType.getSimpleName(), name), e);
    } catch (IllegalArgumentException e) {
        throw new IllegalStateException(
                String.format("Unable to create %s for %s!", modelType.getSimpleName(), name), e);
    } catch (InstantiationException e) {
        throw new IllegalStateException(
                String.format("Unable to create %s for %s!", modelType.getSimpleName(), name), e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(
                String.format("Unable to create %s for %s!", modelType.getSimpleName(), name), e);
    } catch (InvocationTargetException e) {
        //this indicates an exception while creating the instance
        //for InvalidFormatException and IO Exceptions we shall
        //directly throw the cause. for all others wrap the thrown one
        //in an IllegalStateException
        Throwable checked = e.getCause();
        if (checked instanceof InvalidFormatException) {
            throw (InvalidFormatException) checked;
        } else if (checked instanceof IOException) {
            throw (IOException) checked;
        } else {
            throw new IllegalStateException(
                    String.format("Unable to create %s for %s!", modelType.getSimpleName(), name), e);
        }
    } finally {
        IOUtils.closeQuietly(modelDataStream);
    }
    return built;
}

From source file:org.apache.hadoop.hdfs.server.datanode.FSDataset.java

/** Get the cause of an I/O exception if caused by a possible disk error
 * @param ioe an I/O exception//w w w. j  av a  2 s  .  co m
 * @return cause if the I/O exception is caused by a possible disk error;
 *         null otherwise.
 */
static IOException getCauseIfDiskError(IOException ioe) {
    if (ioe.getMessage() != null && ioe.getMessage().startsWith(DISK_ERROR)) {
        return (IOException) ioe.getCause();
    } else {
        return null;
    }
}

From source file:hu.sztaki.lpds.pgportal.services.asm.ASMService.java

/**
 * /*from   w  w w  . ja v  a2s  . com*/
 * It gets the file specified by the attributes (userID/workflowID/jobID/portID) and passes it back to the
 * outputstream of the specified response
 * 
 * @param userID
 *            - ID of the user
 * @param workflowID
 *            - Name of the workflow
 * @param jobID
 *            - Name of the job
 * @param fileName
 *            - Name of the file
 * @param response
 *            - response that should contain the file to download
 * @throws ASM_GeneralException
 */
public void getFileStream(String userID, String workflowID, String jobID, String fileName,
        HttpServletResponse response) throws Upload_GeneralException {
    InputStream is = null;
    try {

        is = getFileStreamFromStorage(userID, workflowID, DownloadTypeConstants.InstanceAll);
        this.convertOutputZip(userID, workflowID, jobID, fileName, is, response.getOutputStream());

    } catch (IOException ex) {
        throw new Download_GettingFileStreamException(ex.getCause(), userID, workflowID);
    }
}

From source file:hu.sztaki.lpds.pgportal.services.asm.ASMService.java

/**
 * /*from  ww  w.  j a  va  2 s  . c  o  m*/
 * It gets the file specified by the attributes (userID/workflowID/jobID/portID) and passes it back to the
 * outputstream of the specified ResourceResponse It can be used if file downloading should work using Ajax
 * technology
 * 
 * @param userID
 *            - ID of the user
 * @param workflowID
 *            - Name of the workflow
 * @param jobID
 *            - Name of the job
 * @param fileName
 *            - name of the file
 * @param response
 *            - response that should contain the file to download
 * @throws ASM_GeneralException
 */
public void getFileStream(String userID, String workflowID, String jobID, String fileName,
        ResourceResponse response) throws Download_GettingFileStreamException

{

    InputStream is = null;
    try {

        is = getFileStreamFromStorage(userID, workflowID, DownloadTypeConstants.InstanceAll);
        this.convertOutputZip(userID, workflowID, jobID, fileName, is, response.getPortletOutputStream());

    } catch (IOException ex) {
        throw new Download_GettingFileStreamException(ex.getCause(), userID, workflowID);
    }
}

From source file:hu.sztaki.lpds.pgportal.services.asm.ASMService.java

/**
 * /*from w  ww.jav  a  2s.co  m*/
 * It gets the file specified by the attributes (userID/workflowID/jobID/portID) and passes it back to the
 * outputstream of the specified response
 * 
 * @param userID
 *            - ID of the user
 * @param workflowID
 *            - Name of the workflow
 * @param jobID
 *            - Name of the job
 * @param portID
 *            - ID of the port (0..15)
 * 
 * @throws ASM_GeneralException
 * @return String - Path of the file stored on the portal server
 */
public String getFiletoPortalServer(String userID, String workflowID, String jobID, String portID)
        throws Download_GettingFileToPortalServiceException {
    String downloadfolder = PropertyLoader.getInstance().getProperty("prefix.dir") + "tmp/users/" + userID
            + "/workflow_outputs";

    if (!new File(downloadfolder).exists()) {
        File down_folder = new File(downloadfolder);
        down_folder.mkdirs();
    }
    String outputfile = downloadfolder + "/" + workflowID;
    File f = new File(outputfile);
    InputStream is = null;
    try {

        is = getFileStreamFromStorage(userID, workflowID, DownloadTypeConstants.InstanceAll);
        java.io.OutputStream out = new FileOutputStream(f);
        byte[] b = new byte[1024];
        int nm;
        while ((nm = is.read(b)) > (-1)) {

            out.write(b, 0, nm);
        }
        is.close();
        out.close();
        return outputfile;
    } catch (IOException ex) {
        throw new Download_GettingFileToPortalServiceException(ex.getCause(), userID, workflowID);
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

private EntityManagerFactory createFactory() {
    jqmlogger.debug("Creating connection pool to database");

    InputStream fis = null;//from ww  w.j av a 2s .c o m
    try {
        fis = this.getClass().getClassLoader().getResourceAsStream("META-INF/jqm.properties");
        if (fis == null) {
            jqmlogger.trace("No jqm.properties file found.");
        } else {
            p.load(fis);
            jqmlogger.trace("A jqm.properties file was found");
        }
    } catch (IOException e) {
        // We allow no configuration files, but not an unreadable configuration file.
        throw new JqmClientException("META-INF/jqm.properties file is invalid", e);
    } finally {
        closeQuietly(fis);
    }

    EntityManagerFactory newEmf = null;
    if (p.containsKey("javax.persistence.nonJtaDataSource")) {
        // This is a hack. Some containers will use root context as default for JNDI (WebSphere, Glassfish...), other will use
        // java:/comp/env/ (Tomcat...). So if we actually know the required alias, we try both, and the user only has to provide a
        // root JNDI alias that will work in both cases.
        try {
            newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p);
            // Do a stupid query to force EMF initialization
            EntityManager em = newEmf.createEntityManager();
            em.createQuery("SELECT n from Node n WHERE 1=0").getResultList().size();
            em.close();
        } catch (RuntimeException e) {
            if (e.getCause() != null && e.getCause().getCause() != null
                    && e.getCause().getCause() instanceof NameNotFoundException) {
                jqmlogger.debug("JNDI alias " + p.getProperty("javax.persistence.nonJtaDataSource")
                        + " was not found. Trying with java:/comp/env/ prefix");
                p.setProperty("javax.persistence.nonJtaDataSource",
                        "java:/comp/env/" + p.getProperty("javax.persistence.nonJtaDataSource"));
                newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p);
                // Do a stupid query to force EMF initialization
                EntityManager em = newEmf.createEntityManager();
                em.createQuery("SELECT n from Node n WHERE 1=3").getResultList().size();
                em.close();
            } else {
                throw e;
            }
        }
    } else {
        newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p);
    }
    return newEmf;
}