Example usage for java.io FileNotFoundException getLocalizedMessage

List of usage examples for java.io FileNotFoundException getLocalizedMessage

Introduction

In this page you can find the example usage for java.io FileNotFoundException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:com.photon.phresco.service.util.DependencyUtils.java

/**
 * Extracts the given compressed file (of type tar, targz, and zip) into given location.
 * See also/*from w  w w .  j  a  v a 2s .  c  om*/
 * {@link ArchiveType} and {@link ArchiveUtil}
 * @param contentURL
 * @param path
 * @throws PhrescoException
 */
public static void extractFiles(String contentURL, String folderName, File path, String customerId)
        throws PhrescoException {
    if (isDebugEnabled) {
        LOGGER.debug("DependencyUtils.extractFiles:Entry");
        LOGGER.info(ServiceConstants.DEPENDENCY_UTIL_EXTRACT_FILES, "contentURL=\"" + contentURL + "\"",
                "folderName=\"" + folderName + "\"", ServiceConstants.PATH_EQUALS_SLASH + path.getName() + "\"",
                ServiceConstants.CUSTOMER_ID_EQUALS_SLASH + customerId + "\"");
    }
    assert !StringUtils.isEmpty(contentURL);

    PhrescoServerFactory.initialize();
    String extension = getExtension(contentURL);
    File archive = new File(Utility.getPhrescoTemp(), UUID.randomUUID().toString() + extension);
    FileOutputStream fos = null;
    OutputStream out = null;
    try {
        InputStream inputStream = PhrescoServerFactory.getRepositoryManager().getArtifactAsStream(contentURL,
                customerId);
        fos = new FileOutputStream(archive);
        out = new BufferedOutputStream(fos);

        IOUtils.copy(inputStream, out);

        out.flush();
        out.close();
        fos.close();
        ArchiveType archiveType = getArchiveType(extension);
        if (isDebugEnabled) {
            LOGGER.debug("extractFiles() path=" + path.getPath());
        }
        ArchiveUtil.extractArchive(archive.toString(), path.getAbsolutePath(), folderName, archiveType);
        archive.delete();
        if (isDebugEnabled) {
            LOGGER.debug("DependencyUtils.extractFiles:Exit");
        }
    } catch (FileNotFoundException e) {
        LOGGER.error(ServiceConstants.DEPENDENCY_UTIL_EXTRACT_FILES, ServiceConstants.STATUS_FAILURE,
                "message=\"" + e.getLocalizedMessage() + "\"");
        return;
    }

    catch (IOException e) {
        LOGGER.error(ServiceConstants.DEPENDENCY_UTIL_EXTRACT_FILES, ServiceConstants.STATUS_FAILURE,
                "message=\"" + e.getLocalizedMessage() + "\"");
        throw new PhrescoException(e);
    } catch (PhrescoException pe) {
        LOGGER.error(ServiceConstants.DEPENDENCY_UTIL_EXTRACT_FILES, ServiceConstants.STATUS_FAILURE,
                "message=\"" + pe.getLocalizedMessage() + "\"");
        if (pe.getCause() instanceof FileNotFoundException) {
            return;
        }
        throw pe;
    } finally {
        Utility.closeStream(fos);
        Utility.closeStream(out);
    }
}

From source file:com.nextgis.mobile.map.LocalTMSLayer.java

protected static void create(final MapBase map, String layerName, int tmsType, Uri uri) {
    String sErr = map.getContext().getString(R.string.error_occurred);
    try {//from  ww w . j  a v  a2s . co m
        InputStream inputStream = map.getContext().getContentResolver().openInputStream(uri);
        if (inputStream != null) {
            ProgressDialog progressDialog = new ProgressDialog(map.getContext());
            progressDialog.setMessage(map.getContext().getString(R.string.message_zip_extract_progress));
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCancelable(true);
            progressDialog.show();

            File outputPath = map.cretateLayerStorage();
            //create layer description file
            JSONObject oJSONRoot = new JSONObject();
            oJSONRoot.put(JSON_NAME_KEY, layerName);
            oJSONRoot.put(JSON_VISIBILITY_KEY, true);
            oJSONRoot.put(JSON_TYPE_KEY, LAYERTYPE_LOCAL_TMS);
            oJSONRoot.put(JSON_TMSTYPE_KEY, tmsType);

            new UnZipTask(map.getMapEventsHandler(), inputStream, outputPath, oJSONRoot, progressDialog)
                    .execute();
            return;
        }
    } catch (FileNotFoundException e) {
        Log.d(TAG, "Exception: " + e.getLocalizedMessage());
        sErr += ": " + e.getLocalizedMessage();
    } catch (JSONException e) {
        Log.d(TAG, "Exception: " + e.getLocalizedMessage());
        sErr += ": " + e.getLocalizedMessage();
    }
    //if we here something wrong occurred
    Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
}

From source file:jmupen.JMupenUpdater.java

public static void installUpdate() {
    try {/*from   w w  w.  java 2 s. c o m*/
        String digest = MD5ForFile.getDigest(new FileInputStream(updatePackage), 2048);
        System.out.println("DIGEST UPDATED PACK: " + digest);
        System.out.println("DIGEST ONLINE: " + MD5ForFile.getMd5FromUrl(new URL(Md5URL).openConnection()));
        if (!digest.trim().equals(MD5ForFile.getMd5FromUrl(new URL(Md5URL).openConnection()).trim())) {
            System.err.println("Download failed, removing update file.");
            JMupenGUI.getInstance().showError("Download failed - MD5 Check",
                    "MD5 Check failed, not installing the update.");
            boolean isDeleted = updatePackage.delete();
            if (!isDeleted) {
                JMupenGUI.getInstance().showError("Can't delete temp file",
                        "Please manually delete file at " + updatePackage.getAbsolutePath());
            }
            return;
        }
    } catch (FileNotFoundException e) {
        System.err.println("File not found. Nothing to install.");
        return;
    } catch (Exception e) {
        System.err.println(
                "Almost impossible error (malformed MD5 url or IO problem). " + e.getLocalizedMessage());
    }
    boolean deleted = jarFile.delete();
    System.out.println("Deleted jar? " + deleted);

    if (!deleted) {

        JMupenUtils.extractJar(jarFile, tmpDir);
        JMupenUpdater.startWinUpdaterApplication();

    }
    try {
        FileUtils.moveFile(updatePackage, jarFile);
        JMupenUpdater.restartApplication();
    } catch (IOException ex) {
        System.err.println("Error moving file. You can find updated file at " + JMupenUtils.getConfigDir()
                + " Full mess: " + ex.getLocalizedMessage());
        JMupenGUI.getInstance().showError("Error updating JMupen.",
                "I couldn't move update file in place. You can find the app file in "
                        + JMupenUtils.getConfigDir() + " folder.");
    }
}

From source file:org.geotools.gce.imagemosaic.catalog.oracle.DataStoreWrapper.java

/**
 * Utility method which load mapping properties from a propertiesFile.
 * @param propertiesFile/*from w  w  w .j ava 2 s .  co  m*/
 * @return
 */
private static Properties loadProperties(final String propertiesFile) {
    InputStream inStream = null;
    Properties properties = new Properties();
    try {
        File propertiesFileP = new File(propertiesFile);
        inStream = new BufferedInputStream(new FileInputStream(propertiesFileP));
        properties.load(inStream);
    } catch (FileNotFoundException e) {
        if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.warning("Unable to store the mapping " + e.getLocalizedMessage());
        }
    } catch (IOException e) {
        if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.warning("Unable to store the mapping " + e.getLocalizedMessage());
        }

    } finally {
        if (inStream != null) {
            IOUtils.closeQuietly(inStream);
        }
    }
    return properties;
}

From source file:com.jkoolcloud.tnt4j.streams.StreamsAgent.java

private static void loadConfigAndRun(File cfgFile, InputStreamListener streamListener,
        StreamTasksListener streamTasksListener) {
    LOGGER.log(OpLevel.INFO,/*from  w  w w . j a va2s  .co  m*/
            StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                    "StreamsAgent.loading.config.file"),
            cfgFile == null ? StreamsConfigLoader.getDefaultFile() : cfgFile);
    try {
        loadConfigAndRun(cfgFile == null ? null : new FileReader(cfgFile), streamListener, streamTasksListener);
    } catch (FileNotFoundException e) {
        LOGGER.log(OpLevel.ERROR, String.valueOf(e.getLocalizedMessage()), e);
    }
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call to the OCC web services
 * //from   w w w . j ava 2  s  .  co m
 * @param url
 *           The url
 * @param isAuthorizedRequest
 *           Whether this request requires the authorization token sending
 * @param httpMethod
 *           method type (GET, PUT, POST, DELETE)
 * @param httpBody
 *           Data to be sent in the body (Can be empty)
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws ProtocolException
 */
public static String getResponse(Context context, String url, Boolean isAuthorizedRequest, String httpMethod,
        Bundle httpBody) throws MalformedURLException, IOException, ProtocolException, JSONException {
    // Refresh if necessary
    if (isAuthorizedRequest && WebServiceAuthProvider.tokenExpiredHint(context)) {
        WebServiceAuthProvider.refreshAccessToken(context);
    }

    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
        // If we have refreshed max number of times, we will not do so again
        if (refreshed == 1) {
            refreshLimitReached = true;
        }

        // Make the connection and get the response
        OutputStream os;
        HttpURLConnection connection;

        if (httpMethod.equals("GET") && httpBody != null && !httpBody.isEmpty()) {
            url = url + "?" + encodePostBody(httpBody);
        }
        URL requestURL = new URL(addParameters(context, url));

        if (StringUtils.equalsIgnoreCase(requestURL.getProtocol(), "https")) {
            trustAllHosts();
            HttpsURLConnection https = createSecureConnection(requestURL);
            https.setHostnameVerifier(DO_NOT_VERIFY);
            if (isAuthorizedRequest) {
                String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token");
                https.setRequestProperty("Authorization", authValue);
            }
            connection = https;
        } else {
            connection = createConnection(requestURL);
        }
        connection.setRequestMethod(httpMethod);

        if (!httpMethod.equals("GET") && !httpMethod.equals("DELETE")) {
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();

            if (httpBody != null && !httpBody.isEmpty()) {
                os = new BufferedOutputStream(connection.getOutputStream());
                os.write(encodePostBody(httpBody).getBytes());
                os.flush();
            }
        }

        response = "";
        try {
            LoggingUtils.d(LOG_TAG, connection.toString());
            response = readFromStream(connection.getInputStream());
        } catch (FileNotFoundException e) {
            LoggingUtils.e(LOG_TAG,
                    "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                    context);
            response = readFromStream(connection.getErrorStream());
        } finally {
            connection.disconnect();
        }

        // Allow for calls to return nothing
        if (response.length() == 0) {
            return "";
        }

        // Check for JSON parsing errors (will throw JSONException is can't be parsed)
        JSONObject object = new JSONObject(response);

        // If no error, return response
        if (!object.has("error")) {
            return response;
        }
        // If there is a refresh token error, refresh the token
        else if (object.getString("error").equals("invalid_token")) {
            if (refreshLimitReached) {
                // Give up
                return response;
            } else {
                // Refresh the token
                WebServiceAuthProvider.refreshAccessToken(context);
                refreshed++;
            }
        }
    } // while(!refreshLimitReached)

    // There is an error other than a refresh error, so return the response
    return response;
}

From source file:br.com.nordestefomento.jrimum.bopepo.view.guia.ViewerPDF.java

/**
 * <p>/*w  ww .  j  a  va2s  . com*/
 * SOBRE O MTODO
 * </p>
 * 
 * @param pathName
 *            arquivo de destino
 * @param guias
 *            a serem agrupados
 * @param guiaViewer
 *            visualizador
 *            
 * @return File contendo guias geradas.
 * 
 * @throws JRimumException
 *             Quando ocorrer um problema na gerao do PDF que est fora do
 *             controle da biblioteca.
 * 
 * @since 0.3
 */
protected static File groupInOnePDF(String pathName, List<Guia> guias, GuiaViewer guiaViewer) {

    File arq = null;

    List<byte[]> guiasEmBytes = new ArrayList<byte[]>(guias.size());

    for (Guia guia : guias) {
        guiasEmBytes.add(guiaViewer.setGuia(guia).getPdfAsByteArray());
    }

    try {

        arq = FileUtil.bytes2File(pathName, PDFUtil.mergeFiles(guiasEmBytes));

    } catch (FileNotFoundException e) {

        log.error("Erro durante gerao do PDF." + e.getLocalizedMessage(), e);
        throw new JRimumException("Erro durante gerao do PDF. Causado por " + e.getLocalizedMessage(), e);

    } catch (IOException e) {

        log.error("Erro durante gerao do PDF." + e.getLocalizedMessage(), e);
        throw new JRimumException("Erro durante gerao do PDF. Causado por " + e.getLocalizedMessage(), e);
    }

    return arq;
}

From source file:br.com.nordestefomento.jrimum.bopepo.view.ViewerPDF.java

/**
 * <p>/*from   w w  w .jav  a2  s  . co  m*/
 * SOBRE O MTODO
 * </p>
 * 
 * @param pathName arquivo de destino
 * @param boletos a serem agrupados
 * @param boletoViewer visualizador
 * @return File contendo boletos gerados
 * 
 * @throws JRimumException Quando ocorrer um problema na gerao do PDF que est fora do controle
 * da biblioteca.
 * 
 * @since 0.2
 */
protected static File groupInOnePDF(String pathName, List<Boleto> boletos, BoletoViewer boletoViewer) {

    File arq = null;

    List<byte[]> boletosEmBytes = new ArrayList<byte[]>(boletos.size());

    for (Boleto bop : boletos) {
        boletosEmBytes.add(boletoViewer.setBoleto(bop).getPdfAsByteArray());
    }

    try {

        arq = FileUtil.bytes2File(pathName, PDFUtil.mergeFiles(boletosEmBytes));

    } catch (FileNotFoundException e) {

        log.error("Erro durante gerao do PDF." + e.getLocalizedMessage(), e);
        throw new JRimumException("Erro durante gerao do PDF. Causado por " + e.getLocalizedMessage(),
                e);

    } catch (IOException e) {

        log.error("Erro durante gerao do PDF." + e.getLocalizedMessage(), e);
        throw new JRimumException("Erro durante gerao do PDF. Causado por " + e.getLocalizedMessage(),
                e);
    }

    return arq;
}

From source file:com.yoctopuce.YoctoAPI.YFirmwareUpdate.java

private static YFirmwareFile _loadFirmwareFile(File file) throws YAPI_Exception {
    FileInputStream in = null;//from  w  w  w  .  jav a2 s. c  o m
    try {
        in = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        throw new YAPI_Exception(YAPI.FILE_NOT_FOUND, "File not found");
    }
    ByteArrayOutputStream result = new ByteArrayOutputStream(1024);

    try {
        byte[] buffer = new byte[1024];
        int readed = 0;
        while (readed >= 0) {
            readed = in.read(buffer, 0, buffer.length);
            if (readed < 0) {
                // end of connection
                break;
            } else {
                result.write(buffer, 0, readed);
            }
        }

    } catch (IOException e) {
        throw new YAPI_Exception(YAPI.IO_ERROR, "unable to load file :" + e.getLocalizedMessage());
    } finally {
        try {
            in.close();
        } catch (IOException ignore) {
        }
    }

    return YFirmwareFile.Parse(file.getPath(), result.toByteArray());
}

From source file:au.edu.uq.cmm.paul.servlet.FileView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    File file = (File) model.get("file");
    String contentType = (String) model.get("contentType");
    try (FileInputStream fis = new FileInputStream(file)) {
        response.setContentType(contentType);
        long length = file.length();
        if (length <= Integer.MAX_VALUE) {
            response.setContentLength((int) length);
        }//from w w  w  .ja  va 2 s  .  co  m
        response.setStatus(HttpServletResponse.SC_OK);
        try (OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[8192];
            int nosRead;
            while ((nosRead = fis.read(buffer)) > 0) {
                os.write(buffer, 0, nosRead);
            }
        }
    } catch (FileNotFoundException ex) {
        LOG.info("Cannot access file: " + ex.getLocalizedMessage());
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}