Example usage for java.io IOException toString

List of usage examples for java.io IOException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.example.soumya.feedthepanda.RegistrationIntentService.java

/**
 * Persist registration to third-party servers.
 *
 * Modify this method to associate the user's GCM registration token with any server-side account
 * maintained by your application.// w w  w.  j a v  a 2  s. co m
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token, String api) {
    final String API_URL = DataFetcher.API_URL + "register_gcm";

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(API_URL);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

        nameValuePairs.add(new BasicNameValuePair("gcm_token", token));
        nameValuePairs.add(new BasicNameValuePair("api_key", api));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
        HttpResponse response = httpclient.execute(httppost);

        Log.i("Extra", response.toString());
    } catch (IOException e) {
        Log.d(TAG, "Could not send token to server: " + e.toString());
    }
    Log.v(TAG, "Sent token " + token + " to server");
}

From source file:cn.webwheel.results.JsonResult.java

public String toString() {
    try {//from w w w .jav a  2  s .  co  m
        return objectMapper.writeValueAsString(json != null ? json : map);
    } catch (IOException e) {
        try {
            return "{\"msg\":" + objectMapper.writeValueAsString(e.toString()) + "}";
        } catch (IOException e1) {
            return e1.toString();
        }
    }
}

From source file:de.rrze.idmone.utils.jidgen.filter.ShellCmdFilter.java

public String apply(String id) {
    String cmd = this.cmdTemplate.replace("%s", id);

    logger.trace("Executing command: " + cmd);

    Runtime run = Runtime.getRuntime();
    try {//  w w w .j av  a  2 s. c  om
        Process proc = run.exec(cmd);

        /*      BufferedWriter commandLine = new BufferedWriter(
                    new OutputStreamWriter(proc.getOutputStream())
              );
              commandLine.write(cmd);
              commandLine.flush();
        */
        // read stdout and log it to the debug level
        BufferedReader stdOut = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String stdOutput = "";
        while ((stdOutput = stdOut.readLine()) != null) {
            logger.debug("STDOUT: " + stdOutput);
        }
        stdOut.close();

        // read stderr and log it to the error level
        BufferedReader stdErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String errOutput = "";
        while ((errOutput = stdErr.readLine()) != null) {
            logger.error("STDERR: " + errOutput);
        }
        stdErr.close();

        int exitCode = proc.waitFor();
        proc.destroy();

        if (exitCode == 0) {
            logger.trace("Filtered!");
            return null;
        } else {
            return id;
        }

    } catch (IOException e) {
        logger.fatal(e.toString());
        System.exit(120);
    } catch (InterruptedException e) {
        logger.fatal(e.toString());
        System.exit(121);
    }

    return null;
}

From source file:com.streamsets.pipeline.stage.destination.fifo.FifoTarget.java

@Override
public void destroy() {
    try {/*from w  w  w.  ja va 2  s.c  o  m*/
        if (fos != null) {
            fos.close();
            fos = null;
        }
    } catch (IOException ex) {
        LOG.error("destroy(): IOException closing connection: '{}' ", ex.toString(), ex);
    }
}

From source file:libra.preprocess.stage2.KmerIndexBuilderPartitioner.java

private void initializeSecond(int numReduceTasks) throws IOException {
    if (this.partitions == null) {
        KmerHistogram histogram = null;/* www .  j  a va 2  s . co m*/
        // search index file
        Path histogramPath = getHistogramPath(this.conf);
        FileSystem fs = histogramPath.getFileSystem(this.conf);
        if (fs.exists(histogramPath)) {
            histogram = KmerHistogram.createInstance(fs, histogramPath);
        } else {
            throw new IOException("k-mer histogram is not found in given paths");
        }

        KmerRangePartitioner partitioner = new KmerRangePartitioner(this.ppConfig.getKmerSize(),
                numReduceTasks);
        this.partitions = partitioner.getHistogramPartitions(histogram.getSortedRecord(),
                histogram.getTotalKmerCount());

        this.partitionEndKeys = new CompressedSequenceWritable[this.partitions.length];
        for (int i = 0; i < this.partitions.length; i++) {
            try {
                this.partitionEndKeys[i] = new CompressedSequenceWritable(
                        this.partitions[i].getPartitionEndKmer());
            } catch (IOException ex) {
                throw new RuntimeException(ex.toString());
            }
        }
    }
}

From source file:fr.esiea.esieaddress.controllers.importation.CSVImportCtrl.java

@RequestMapping(method = RequestMethod.POST)
@ResponseBody//  w ww  .  j a  va 2  s.c om
@Secured("ROLE_USER")
public void upload(MultipartHttpServletRequest files, final HttpServletRequest request)
        throws DaoException, ServiceException, FileNotFoundException {
    LOGGER.info("[IMPORT] Start to import contact");

    //TODO Make it less verbose and may use a buffer to make it safer
    Map<String, MultipartFile> multipartFileMap = files.getMultiFileMap().toSingleValueMap();
    Set<String> fileNames = multipartFileMap.keySet();

    for (String fileName : fileNames) {

        MultipartFile multipartFile = multipartFileMap.get(fileName);
        String originalFilename = multipartFile.getOriginalFilename();

        if (checkFileName(originalFilename) && multipartFile.getSize() < FILE_SIZE_MAX) {

            InputStream inputStream = null;

            try {
                inputStream = multipartFile.getInputStream();
            } catch (IOException e) {
                throw new FileNotFoundException(e.toString());
            }

            try (Reader contactsFile = new InputStreamReader(inputStream)) {
                Map<String, Object> modelErrors = new HashMap<>();
                LOGGER.debug("[IMPORT] File is reading");
                Collection<Contact> contacts = csvService.ReadContactCSV(contactsFile);
                for (Contact contact : contacts) {
                    try {
                        contactCrudService.insert(contact);
                    } catch (ValidationException e) {
                        Object modelError = e.getModel();
                        LOGGER.warn("found an error in contact " + modelError);
                        modelErrors.put(contact.getId(), (Map) modelError);
                    }
                }

                if (!modelErrors.isEmpty())
                    throw new ValidationException(modelErrors);
            } catch (IOException e) {
                throw new FileNotFoundException(e.toString());
            } finally {
                if (inputStream != null)
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        LOGGER.error("[IMPORT] Impossible to close the file " + inputStream.toString());
                    }
            }
        }
    }
}

From source file:eionet.webq.service.RemoteFileServiceImpl.java

/**
 * Read file content from file system. The fileUri has to start with "file://" prefix.
 *
 * @param fileUri file location in file system in form of URI.
 * @return file content as bytes.// ww w  .ja v a  2s .  c om
 * @throws FileNotAvailableException if file is not available as local resource or fileUri is not valid URI.
 */
private byte[] readFilesystemFile(String fileUri) throws FileNotAvailableException {
    try {
        return FileUtils.readFileToByteArray(new File(new URI(fileUri)));
    } catch (IOException e) {
        throw new FileNotAvailableException("The file is not available at: " + fileUri + "." + e.toString());
    } catch (URISyntaxException e) {
        throw new FileNotAvailableException("Incorrect file URI: " + fileUri + "." + e.toString());
    } catch (Exception e) {
        throw new FileNotAvailableException("Illegal file URI argument: " + fileUri + "." + e.toString());
    }
}

From source file:ws.util.AbstractJSONCoder.java

@Override
public String encode(T pojo) throws EncodeException {
    StringBuilder log = new StringBuilder().append(type).append("| [coder] encoding..").append(pojo);
    String json = null;/*from   ww w  .j  av  a 2s  .  com*/
    try {
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        // Jackson jr ??@JsonManagedReference, @JsonBackReference????
        //                  json = JSON.std.asString(pojo);
        json = ow.writeValueAsString(pojo);
        log.append(" DONE.");
    } catch (IOException e) {
        log.append(" **NG**.");
        logger.log(Level.SEVERE, e.toString());
        e.printStackTrace();
        throw new EncodeException(json, e.getMessage());
    } catch (Exception e) {
        log.append(" **NG**.");
        logger.log(Level.SEVERE, e.toString());
        e.printStackTrace();
        throw new EncodeException(json, e.getMessage());
    } finally {
        logger.log(Level.INFO, log.toString());
    }
    //            logger.log(Level.INFO, new StringBuilder()
    //                  .append("[coder] done: ")
    //                  .append(json)
    //                  .toString());
    return json;
}

From source file:beans.DecryptFileBean.java

public void decrypt() {
    if (getUser() != null) {
        try {/*from  w  w w .j  a  v a 2  s.c o  m*/
            if (encryptedFile != null) {
                byte[] encryptedFileContent = IOUtils.toByteArray(encryptedFile.getInputStream());
                if (encryptedSymmetricKey != null) {
                    byte[] encryptedSymmetricKeyContent = IOUtils
                            .toByteArray(encryptedSymmetricKey.getInputStream());
                    if (signedHash != null) {
                        byte[] signedHashContent = IOUtils.toByteArray(signedHash.getInputStream());
                        // Try to send the file to the email entered
                        status = PublicKeyCryptography.decryptFile(encryptedFileContent,
                                encryptedSymmetricKeyContent, signedHashContent);
                    } else {
                        status = "No signed hash was provided.";
                    }
                } else {
                    status = "No encrypted symmetric key was provided.";
                }
            } else {
                status = "No encrypted file was provided.";
            }
        } catch (IOException e) {
            status = "Error Uploading file: " + e.toString();
        }
    } else {
        status = "You are not logged in.";
    }
}

From source file:qhindex.servercomm.ServerDataCache.java

public JSONObject sendRequest(JSONObject data, String url, boolean sentAdminNotification) {
    JSONObject obj = new JSONObject();

    final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(AppHelper.connectionTimeOut)
            .setConnectionRequestTimeout(AppHelper.connectionTimeOut)
            .setSocketTimeout(AppHelper.connectionTimeOut).setStaleConnectionCheckEnabled(true).build();
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    HttpPost httpPost = new HttpPost(url);

    String dataStr = data.toJSONString();
    dataStr = dataStr.replaceAll("null", "\"\"");

    if (sentAdminNotification == true) {
        try {/*  w ww.j  a  v a2  s.  c  o  m*/
            AdminMail adminMail = new AdminMail();
            adminMail.sendMailToAdmin("Data to send to the server.", dataStr);
        } catch (Exception ex) { // Catch any problem during this step and continue 
            Debug.print("Could not send admin notification e-mail: " + ex);
        }
    }
    Debug.print("DATA REQUEST: " + dataStr);
    StringEntity jsonData = new StringEntity(dataStr, ContentType.create("plain/text", Consts.UTF_8));
    jsonData.setChunked(true);
    httpPost.addHeader("content-type", "application/json");
    httpPost.addHeader("accept", "application/json");
    httpPost.setEntity(jsonData);

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() >= 300) {
            Debug.print("Exception while sending http request: " + statusLine.getStatusCode() + " : "
                    + statusLine.getReasonPhrase());
            resultsMsg += "Exception while sending http request: " + statusLine.getStatusCode() + " : "
                    + statusLine.getReasonPhrase() + "\n";
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output = new String();
        String line;
        while ((line = br.readLine()) != null) {
            output += line;
        }
        output = output.substring(output.indexOf('{'));
        try {
            obj = (JSONObject) new JSONParser().parse(output);
        } catch (ParseException pEx) {
            Debug.print(
                    "Could not parse internet response. It is possible the cache server fail to deliver the content: "
                            + pEx.toString());
            resultsMsg += "Could not parse internet response. It is possible the cache server fail to deliver the content.\n";
        }
    } catch (IOException ioEx) {
        Debug.print("Could not handle the internet request: " + ioEx.toString());
        resultsMsg += "Could not handle the internet request.\n";
    }
    return obj;
}