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:io.github.retz.web.JobRequestHandler.java

static String kill(Request req, spark.Response res) throws JsonProcessingException {
    LOG.debug("kill", req.params(":id"));
    res.type("application/json");
    int id = Integer.parseInt(req.params(":id"));

    Optional<Job> maybeJob;
    try {/* ww  w .  ja v a 2  s.  co m*/
        maybeJob = getJobAndVerify(req);
    } catch (IOException e) {
        return MAPPER.writeValueAsString(new ErrorResponse(e.toString()));
    }

    if (!maybeJob.isPresent()) {
        res.status(404);
        Response response = new ErrorResponse("No such job: " + id);
        response.status("No such job: " + id);
        return MAPPER.writeValueAsString(response);
    }

    Optional<Boolean> result = Stanchion.call(() -> {
        Optional<Job> maybeJob2 = JobQueue.cancel(id, "Canceled by user");

        if (maybeJob2.isPresent()) {
            Job job = maybeJob2.get();
            // There's a slight pitfall between cancel above and kill below where
            // no kill may be sent, RetzScheduler is exactly in resourceOffers and being scheduled.
            // Then this protocol returns false for sure.
            if (job.taskId() != null && !job.taskId().isEmpty() && driver.isPresent()) {
                Protos.TaskID taskId = Protos.TaskID.newBuilder().setValue(job.taskId()).build();
                Protos.Status status = driver.get().killTask(taskId);
                LOG.info("Job id={} was running and killed. status={}, taskId={}", job.id(), status,
                        job.taskId());
            }
            return job.state() == Job.JobState.KILLED;
        }
        // Job is already finished or killed, no more running nor runnable, or something is wrong
        return false;
    });

    Response response;
    if (result.isPresent() && result.get()) {
        response = new KillResponse();
        res.status(200);
        response.ok();
    } else {
        res.status(500);
        response = new ErrorResponse();
        response.status("Can't kill job - due to unknown reason");
    }

    return MAPPER.writeValueAsString(response);
}

From source file:com.example.android.wifidirect.DeviceDetailFragment.java

public static boolean copyFile(InputStream inputStream, OutputStream out) {
    byte buf[] = new byte[1024];
    int len;/*  w  ww  .j a v a  2 s.c  o m*/
    long startTime = System.currentTimeMillis();

    try {
        while ((len = inputStream.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        out.close();
        inputStream.close();
        long endTime = System.currentTimeMillis() - startTime;
        Log.v("", "Time taken to transfer all bytes is : " + endTime);

    } catch (IOException e) {
        Log.d(WiFiDirectActivity.TAG, e.toString());
        return false;
    }
    return true;
}

From source file:edu.wpi.margrave.SQSReader.java

protected static MPolicy loadSQS(String polId, String sFileName) throws MUserException {
    // Convert filename
    sFileName = MPolicy.convertSeparators(sFileName);

    // Read in the JSON text

    BufferedReader reader;//from  w w w  .ja  va  2 s .c  o  m
    try {
        reader = new BufferedReader(new FileReader(sFileName));
        StringBuffer target = new StringBuffer();
        while (reader.ready()) {
            String line = reader.readLine();
            target.append(line + "\n");
        }
        reader.close();

        JSONObject json = new JSONObject(target.toString());

        // Use provided policy ID
        //String polId;         
        //if(!json.isNull("Id"))
        //   polId = json.getString("Id");
        //else
        //   throw new MGEUnsupportedSQS("Id element must be present.");

        MVocab env = createSQSVocab(polId);
        MPolicyLeaf result = new MPolicyLeaf(polId, env);

        result.declareVariable("p", "Principal");
        result.declareVariable("a", "Action");
        result.declareVariable("r", "Resource");
        result.declareVariable("c", "Condition");

        // Get statements; may be an array or a single statement object.
        Object statement_s = json.get("Statement");
        if (statement_s instanceof JSONArray) {
            JSONArray statements = json.getJSONArray("Statement");

            for (int ii = 0; ii < statements.length(); ii++) {
                JSONObject thisStatement = statements.getJSONObject(ii);
                handleSQSStatement(thisStatement, result, ii);
            }
        } else
            handleSQSStatement((JSONObject) statement_s, result, 0);

        // "Allow overrides a `default deny' but never an explicit deny."
        // Default deny is N/a.
        Set<String> denySet = new HashSet<String>();
        denySet.add("Deny");
        result.rCombineWhatOverrides.put("Allow", denySet); // Allow < {Deny}

        result.initIDBs();

        return result;

    } catch (IOException e) {
        throw new MGEUnsupportedSQS(e.toString());
    } catch (JSONException e) {
        throw new MGEUnsupportedSQS(e.toString());
    }

}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Save data to a file.
 * @param dirName The full directory name
 * @param fileName The base name of the file to create
 * @param format The format to use; a key in
 *  ToolkitConfig.FORMAT_TO_FILEEXT_MAP.
 * @param data The data to be written//from ww  w  .j  av  a  2  s  .c  o m
 * @return The complete, full path to the file.
 */
public static String saveFile(final String dirName, final String fileName, final String format,
        final String data) {
    String fileExtension = ToolkitConfig.FORMAT_TO_FILEEXT_MAP.get(format.toLowerCase());
    String filePath = dirName + File.separator + fileName + fileExtension;
    FileWriter writer = null;
    try {
        requireDirectory(dirName);
        File oFile = new File(filePath);
        writer = new FileWriter(oFile);
        writer.write(data);
        writer.close();
    } catch (IOException e) {
        return "Exception: " + e.toString();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                return "Exception: " + e.toString();
            }
        }
    }
    return filePath;
}

From source file:io.github.retz.mesosc.MesosHTTPFetcher.java

public static boolean statHTTPFile(String url, String name) {
    String addr = url.replace("files/browse", "files/download") + "%2F" + maybeURLEncode(name);
    try (UrlConnector conn = new UrlConnector(addr, "HEAD", false)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(conn.getResponseMessage());
        }/*from w w w.  jav  a 2 s.  co  m*/
        int statusCode = conn.getResponseCode();
        return statusCode == 200 || statusCode == 204;
    } catch (IOException e) {
        LOG.error("Failed to fetch {}: {}", addr, e.toString(), e);
        return false;
    }
}

From source file:com.ushahidi.android.app.net.MainHttpClient.java

/**
 * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid
 * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no
 * data, 8 - api disabled, 9 - no task found, 10 - json is wrong
 *//*from w  w  w.j a  v a  2 s .c o  m*/
public static int PostFileUpload(String URL, HashMap<String, String> params) throws IOException {
    Log.d(CLASS_TAG, "PostFileUpload(): upload file to server.");

    entity = new MultipartEntity();
    // Dipo Fix
    try {
        // wrap try around because this constructor can throw Error
        final HttpPost httpost = new HttpPost(URL);

        if (params != null) {

            entity.addPart("task", new StringBody(params.get("task")));
            entity.addPart("incident_title",
                    new StringBody(params.get("incident_title"), Charset.forName("UTF-8")));
            entity.addPart("incident_description",
                    new StringBody(params.get("incident_description"), Charset.forName("UTF-8")));
            entity.addPart("incident_date", new StringBody(params.get("incident_date")));
            entity.addPart("incident_hour", new StringBody(params.get("incident_hour")));
            entity.addPart("incident_minute", new StringBody(params.get("incident_minute")));
            entity.addPart("incident_ampm", new StringBody(params.get("incident_ampm")));
            entity.addPart("incident_category", new StringBody(params.get("incident_category")));
            entity.addPart("latitude", new StringBody(params.get("latitude")));
            entity.addPart("longitude", new StringBody(params.get("longitude")));
            entity.addPart("location_name",
                    new StringBody(params.get("location_name"), Charset.forName("UTF-8")));
            entity.addPart("person_first",
                    new StringBody(params.get("person_first"), Charset.forName("UTF-8")));
            entity.addPart("person_last", new StringBody(params.get("person_last"), Charset.forName("UTF-8")));
            entity.addPart("person_email",
                    new StringBody(params.get("person_email"), Charset.forName("UTF-8")));

            if (!TextUtils.isEmpty(params.get("filename"))) {
                File file = new File(params.get("filename"));
                if (file.exists()) {
                    entity.addPart("incident_photo[]", new FileBody(new File(params.get("filename"))));
                }
            }

            // NEED THIS NOW TO FIX ERROR 417
            httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
            httpost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpost);
            Preferences.httpRunning = false;

            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                InputStream serverInput = respEntity.getContent();
                return Util.extractPayloadJSON(GetText(serverInput));

            }
        }

    } catch (MalformedURLException ex) {
        Log.d(CLASS_TAG, "PostFileUpload(): MalformedURLException");
        ex.printStackTrace();
        return 11;
        // fall through and return false
    } catch (IllegalArgumentException ex) {
        Log.e(CLASS_TAG, ex.toString());
        //invalid URI
        return 12;
    } catch (IOException e) {
        Log.e(CLASS_TAG, e.toString());
        //timeout
        return 13;
    }
    return 10;
}

From source file:org.cerberus.engine.execution.impl.SeleniumServerService.java

private static void getIPOfNode(TestCaseExecution tCExecution) {
    try {/*from w  ww.  j  av a  2 s. c o m*/
        Session session = tCExecution.getSession();
        HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver())
                .getCommandExecutor();
        SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId();
        String hostName = ce.getAddressOfRemoteServer().getHost();
        int port = ce.getAddressOfRemoteServer().getPort();
        HttpHost host = new HttpHost(hostName, port);
        HttpClient client = HttpClientBuilder.create().build();
        URL sessionURL = new URL("http://" + session.getHost() + ":" + session.getPort()
                + "/grid/api/testsession?session=" + sessionId);
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
                sessionURL.toExternalForm());
        HttpResponse response = client.execute(host, r);
        if (!response.getStatusLine().toString().contains("403")) {
            InputStream contents = response.getEntity().getContent();
            StringWriter writer = new StringWriter();
            IOUtils.copy(contents, writer, "UTF8");
            JSONObject object = new JSONObject(writer.toString());
            URL myURL = new URL(object.getString("proxyId"));
            if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
                tCExecution.setIp(myURL.getHost());
                tCExecution.setPort(String.valueOf(myURL.getPort()));
            }
        }

    } catch (IOException ex) {
        LOG.error(ex.toString());
    } catch (JSONException ex) {
        LOG.error(ex.toString());
    }
}

From source file:com.google.android.apps.body.LayersLoader.java

/**
 * Loads a resource containing json text into a {@code JSONObject}.
 * @param context The context to load the resource from.
 * @param resource Resource identifier.//from w  w  w. j av a  2  s. c  o m
 * @return The result of loading and parsing the resource.
 *     {@code null} on error.
 */
public static JSONObject loadJsonResource(Context context, int resource) {
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(context.getResources().openRawResource(resource)));
    StringBuffer stringBuffer = new StringBuffer();
    try {
        // TODO(thakis): This is sad.
        String s;
        while ((s = reader.readLine()) != null)
            stringBuffer.append(s);
    } catch (IOException e) {
        Log.e("Body", e.toString());
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            Log.e("Body", e.toString());
        }
    }
    JSONObject object;
    try {
        object = new JSONObject(stringBuffer.toString());
    } catch (JSONException e) {
        Log.e("Body", e.toString());
        return null;
    }
    return object;
}

From source file:frequencyanalysis.FrequencyAnalysis.java

public static String getCleansedStringFromWarAndPeace() {
    String sampleTextString;//from w  w w  . j a v  a 2  s .  c  om

    try {
        sampleTextString = readFile(Paths.get("WarAndPeace.txt").toAbsolutePath().toString(),
                Charset.defaultCharset());

        //Remove all punctuation
        sampleTextString = sampleTextString.replaceAll("\\W", "");

        //Remove all numbers
        sampleTextString = sampleTextString.replaceAll("\\d", "");

        //All uppercase
        sampleTextString = sampleTextString.toUpperCase();

        return sampleTextString;
    } catch (IOException e) {
        System.out.println(e.toString());
    }

    return null;
}

From source file:com.bonsai.btcreceive.HDReceiver.java

public static JSONObject deserialize(File dir, String prefix) throws IOException, JSONException {

    String path = persistPath(prefix);
    mLogger.info("restoring HDReceiver from " + path);
    try {/*from   w  w w .  j ava2s  . co m*/
        File file = new File(dir, path);
        int len = (int) file.length();

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            String currentLine;
            br = new BufferedReader(new FileReader(file));
            while ((currentLine = br.readLine()) != null)
                sb.append(currentLine);
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException ex) {
                String msg = "problem closing file: " + ex.toString();
                mLogger.error(msg);
                throw new RuntimeException(msg);
            }
        }

        String jsonstr = sb.toString();

        /*
        String msg = jsonstr;
        while (msg.length() > 1024) {
        String chunk = msg.substring(0, 1024);
        mLogger.error(chunk);
        msg = msg.substring(1024);
        }
        mLogger.error(msg);
        */

        JSONObject node = new JSONObject(jsonstr);
        return node;

    } catch (IOException ex) {
        mLogger.warn("trouble reading " + path + ": " + ex.toString());
        throw ex;
    } catch (RuntimeException ex) {
        mLogger.warn("trouble restoring wallet: " + ex.toString());
        throw ex;
    }
}