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:org.tangram.spring.StreamingMultipartResolver.java

@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);
    String encoding = determineEncoding(request);
    Map<String, String[]> multipartParameters = new HashMap<>();
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>();
    Map<String, String> multipartFileContentTypes = new HashMap<>();

    try {//from ww  w. j ava 2  s  . co m
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(stream, encoding);
                String[] curParam = multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }
            } else {
                try {
                    MultipartFile file = new StreamingMultipartFile(item);
                    multipartFiles.add(name, file);
                    multipartFileContentTypes.put(name, file.getContentType());
                } catch (final IOException e) {
                    LOG.warn("({})", e.getCause().getMessage(), e);
                    MultipartFile file = new MultipartFile() {

                        @Override
                        public String getName() {
                            return "";
                        }

                        @Override
                        public String getOriginalFilename() {
                            return e.getCause().getMessage();
                        }

                        @Override
                        public String getContentType() {
                            return ERROR;
                        }

                        @Override
                        public boolean isEmpty() {
                            return true;
                        }

                        @Override
                        public long getSize() {
                            return 0L;
                        }

                        @Override
                        public byte[] getBytes() throws IOException {
                            return new byte[0];
                        }

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return null;
                        }

                        @Override
                        public void transferTo(File file) throws IOException, IllegalStateException {
                            throw new UnsupportedOperationException("NYI", e);
                        }
                    };
                    multipartFiles.add(name, file);
                    multipartFileContentTypes.put(name, file.getContentType());
                } // try/catch
            } // if
        } // while
    } catch (IOException | FileUploadException e) {
        throw new MultipartException("Error uploading a file", e);
    } // try/catch

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters,
            multipartFileContentTypes);
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Check if file exists at the give string path, if it does not, creates a new file and returns that.
 *
 * @param file the file//from ww w . j  a va2s.co  m
 * @return the file
 * @throws java.io.IOException the iO exception
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
default File checkFile(String file) throws IOException {
    Logger.getLogger("minecraft").info("The path tried is " + file);
    File tmp = new File(file);
    try {
        tmp.createNewFile();
    } catch (IOException e) {
        Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e.getCause());
        throw e;
    }

    return tmp;
}

From source file:org.nuxeo.ecm.liveconnect.box.BoxBlobUploader.java

private boolean isCausedByUnauthorized(IOException ioe) {
    return ioe.getCause() instanceof BoxAPIException
            && ((BoxAPIException) ioe.getCause()).getResponseCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED;
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Write the properties object to the specified string file path.
 *
 * @param properties an instance of a {@link java.util.Properties} object.
 * @param path       the  {@link java.nio.file.Path} that the properties will be written to.
 * @param message    the message that is included in the header of properties files.
 * @throws IOException an {@link java.io.IOException} if their was a problem writing to the file.
 *//*from  w  w  w. ja  va2  s .c  om*/
default void writeToFile(Properties properties, Path path, String message) throws IOException {
    Validate.notNull(properties);
    Validate.notNull(path);
    Validate.notNull(message);
    System.out.println(path);

    Files.deleteIfExists(path);

    try {

        properties.store(Files.newBufferedWriter(path, Charset.defaultCharset()), message);
    } catch (IOException e) {
        Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e.getCause());
        throw e;
    }

}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Return a {@link java.util.Properties} read from the specified string file path.
 *
 * @param file the {@link java.nio.file.Path } name of the file to read the properties from.
 * @return the {@link java.util.Properties} instance.
 * @throws IOException the {@link java.io.IOException} if the file was not found or there were problems reading from it.
 *///from   ww w  . j  a  v  a 2 s .c  o  m
default Properties readFromFile(File file) throws IOException {

    Validate.notNull(file);

    if (Files.exists(file.toPath()))
        throw new FileNotFoundException("File at " + file.getPath() + " was not found");

    Properties properties = new Properties();
    try {

        properties.load(Files.newBufferedReader(file.toPath(), Charset.defaultCharset()));
    } catch (IOException e) {
        Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e.getCause());
        throw e;
    }

    return properties;
}

From source file:eu.learnpad.core.impl.cw.XwikiBridgeInterfaceRestResource.java

@Override
public void deleteRecommendations(String modelSetId, String simulationid, String userId)
        throws LpRestException {
    String contentType = "application/xml";

    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/bridge/notify/deleterecs/%s", DefaultRestResource.REST_URI,
            modelSetId);// w ww . j a  va 2 s.c om

    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", contentType);

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("simulationid", simulationid);
    queryString[1] = new NameValuePair("userid", userId);
    putMethod.setQueryString(queryString);

    try {
        httpClient.executeMethod(putMethod);
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:com.myjeeva.poi.ExcelReader.java

private void read(int sheetNumber) throws RuntimeException {
    ReadOnlySharedStringsTable strings;/*w  w  w .  j a v a2  s.  co m*/
    try {
        strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
        XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
        StylesTable styles = xssfReader.getStylesTable();
        XSSFReader.SheetIterator worksheets = (XSSFReader.SheetIterator) xssfReader.getSheetsData();

        for (int sheetIndex = 0; worksheets.hasNext(); sheetIndex++) {
            InputStream stream = worksheets.next();
            if (null != sheetCallback)
                this.sheetCallback.startSheet(sheetIndex, worksheets.getSheetName());

            if ((READ_ALL == sheetNumber) || (sheetIndex == sheetNumber)) {
                readSheet(styles, strings, stream);
            }
            IOUtils.closeQuietly(stream);

            if (null != sheetCallback)
                this.sheetCallback.endSheet();
        }
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } catch (SAXException se) {
        LOG.error(se.getMessage(), se.getCause());
    } catch (OpenXML4JException oxe) {
        LOG.error(oxe.getMessage(), oxe.getCause());
    } catch (ParserConfigurationException pce) {
        LOG.error(pce.getMessage(), pce.getCause());
    }
}

From source file:com.myjeeva.poi.ExcelReader.java

private void read(String sheetName) throws RuntimeException {
    ReadOnlySharedStringsTable strings;//from  w  ww.j  a va  2 s  .  c  o  m
    try {
        strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
        XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
        StylesTable styles = xssfReader.getStylesTable();
        XSSFReader.SheetIterator worksheets = (XSSFReader.SheetIterator) xssfReader.getSheetsData();

        for (int sheetIndex = 0; worksheets.hasNext(); sheetIndex++) {
            InputStream stream = worksheets.next();
            if (null != sheetCallback)
                this.sheetCallback.startSheet(sheetIndex, worksheets.getSheetName());

            if (sheetName.equals(worksheets.getSheetName())) {
                readSheet(styles, strings, stream);
            }
            IOUtils.closeQuietly(stream);

            if (null != sheetCallback)
                this.sheetCallback.endSheet();
        }
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } catch (SAXException se) {
        LOG.error(se.getMessage(), se.getCause());
    } catch (OpenXML4JException oxe) {
        LOG.error(oxe.getMessage(), oxe.getCause());
    } catch (ParserConfigurationException pce) {
        LOG.error(pce.getMessage(), pce.getCause());
    }
}

From source file:uk.ac.ebi.intact.editor.controller.dbmanager.DbImportController.java

private File[] saveUploadedFileTemporarily() {
    try {//  w ww .  j a  v  a 2  s  .c o m
        String fileName = System.currentTimeMillis() + "_" + this.uploadedFile.getFileName();
        String errorFileName = fileName + "_errors";
        File file = MIFileUtils.storeAsTemporaryFile(this.uploadedFile.getInputstream(), fileName, null);
        File errorFile = File.createTempFile(errorFileName, "txt");
        return new File[] { file, errorFile };
    } catch (IOException e) {
        addErrorMessage("Cannot upload file " + this.uploadedFile.getFileName(),
                e.getCause() + ": " + e.getMessage());
    }
    return null;
}

From source file:com.google.api.ads.adwords.awalerting.authentication.InstalledOAuth2Authenticator.java

/**
 * Get New Credentials from the user from the command line OAuth2 dance.
 *//*from   ww w  .ja v  a  2s  .co  m*/
private Credential getNewOAuth2Credential() throws OAuthException {
    GoogleAuthorizationCodeFlow authorizationFlow = getAuthorizationFlow();
    String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();

    System.out.println("\n**ACTION REQUIRED** Paste this url in your browser"
            + " and authenticate using your **AdWords Admin Email**: \n" + authorizeUrl);

    // Wait for the authorization code.
    System.out.println("\nType the code you received on the web page here: ");
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String authorizationCode = reader.readLine();

        // Authorize the OAuth2 token.
        GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationFlow.newTokenRequest(authorizationCode);
        tokenRequest.setRedirectUri(CALLBACK_URL);
        GoogleTokenResponse tokenResponse = tokenRequest.execute();

        //  Create the credential.
        Credential credential = new GoogleCredential.Builder().setClientSecrets(clientId, clientSecret)
                .setJsonFactory(new JacksonFactory()).setTransport(new NetHttpTransport()).build()
                .setFromTokenResponse(tokenResponse);

        // Get refresh token and prompt to save in properties file
        refreshToken = credential.getRefreshToken();
        System.out.println("\n**ACTION REQUIRED** Put the following line in your properties file to"
                + " avoid OAuth authentication next time.");
        System.out.printf("refreshToken=%s\n\n", refreshToken);

        System.out.println("Then press enter to continue...");
        reader.readLine();

        return credential;
    } catch (IOException e) {
        throw new OAuthException("An error occured obtaining the OAuth2Credential", e.getCause());
    }
}