Example usage for java.io IOException getClass

List of usage examples for java.io IOException getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.idean.atthack.network.RequestHelper.java

private Result sendHttpGet(String urlStr) {
    HttpURLConnection conn = null;
    try {//  w  w  w . jav a2 s  .c o m
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(HttpVerb.GET.name());
        setBasicAuth(conn);
        conn.connect();
        Log.d(TAG, "[" + conn.getRequestMethod() + "] to " + url.toString());

        String body = readStream(conn.getInputStream());
        return new Result(conn.getResponseCode(), body);
    } catch (IOException e) {
        return new Result(e.getClass() + ": " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:photosharing.api.conx.CommentsDefinition.java

/**
 * deletes a comment with the given comments api url uses the HTTP method
 * delete/*  ww  w  . ja va  2s.  c  o m*/
 * 
 * Method: DELETE URL:
 * http://localhost:9080/photoSharing/api/comments?uid=20514318
 * &pid=bf33a9b5-
 * 3042-46f0-a96e-b8742fced7a4&cid=4ec9c9c2-6e21-4815-bd42-91d502d2d427
 * 
 * @param bearer
 *            token
 * @param cid
 *            comment id
 * @param pid
 *            document id
 * @param uid
 *            user id
 * @param response
 * @param nonce
 */
public void deleteComment(String bearer, String cid, String pid, String uid, HttpServletResponse response,
        String nonce) {
    String apiUrl = getApiUrl() + "/userlibrary/" + uid + "/document/" + pid + "/comment/" + cid + "/entry";

    Request delete = Request.Delete(apiUrl);
    delete.addHeader("Authorization", "Bearer " + bearer);
    delete.addHeader("X-Update-Nonce", nonce);

    try {
        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(delete);

        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes
         */
        int code = hr.getStatusLine().getStatusCode();

        // Checks the Status Code
        if (code == HttpStatus.SC_FORBIDDEN) {
            // Session is no longer valid or access token is expired
            response.setStatus(HttpStatus.SC_FORBIDDEN);
        } else if (code == HttpStatus.SC_UNAUTHORIZED) {
            // User is not authorized
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        } else {
            // Default to SC_NO_CONTENT(204)
            response.setStatus(HttpStatus.SC_NO_CONTENT);
        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("Issue with delete comment" + e.toString());
    }

}

From source file:edu.fullerton.ldvplugin.ExternalPlotManager.java

public double[][] rdBinXYFile(File in) throws FileNotFoundException, IOException, WebUtilException {
    ArrayList<double[]> data = new ArrayList<>();
    DataInputStream input = new DataInputStream(new FileInputStream(in));

    try {//from  w  ww  . j  a  v a  2  s.c  om
        while (true) {
            double[] it = new double[2];
            it[0] = input.readDouble();
            it[1] = input.readDouble();
            data.add(it);
        }
    } catch (EOFException eof) {
        // we're good
    } catch (IOException ex) {
        String ermsg = "Reading binary xy data from file: " + ex.getClass().getSimpleName();
        ermsg += " - " + ex.getLocalizedMessage();
        throw new WebUtilException(ermsg);
    }
    // return as array
    double[][] ret = new double[1][2];
    ret = data.toArray(ret);
    return ret;
}

From source file:photosharing.api.conx.CommentsDefinition.java

/**
 * get nonce as described with nonce <a href="http://ibm.co/1fG83gY">Get a
 * Cryptographic Key</a>/*from   w w w .  j a v a 2s  .co m*/
 * 
 * @param bearer
 *            the access token
 * @return {String} the nonce
 */
private String getNonce(String bearer, HttpServletResponse response) {
    String nonce = "";

    // Build the Request
    Request get = Request.Get(getNonceUrl());
    get.addHeader("Authorization", "Bearer " + bearer);

    try {
        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(get);
        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes and if 200, convert to String
         */
        int code = hr.getStatusLine().getStatusCode();

        // Checks the Status Code
        if (code == HttpStatus.SC_FORBIDDEN) {
            // Session is no longer valid or access token is expired
            response.setStatus(HttpStatus.SC_FORBIDDEN);
        } else if (code == HttpStatus.SC_UNAUTHORIZED) {
            // User is not authorized
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        } else if (code == HttpStatus.SC_OK) {
            // Default to 200
            InputStream in = hr.getEntity().getContent();
            nonce = IOUtils.toString(in);
        } else {
            // SC_BAD_GATEWAY (503)
            response.setStatus(HttpStatus.SC_BAD_GATEWAY);
        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("Issue with get nonce " + e.toString());
    }

    return nonce;
}

From source file:com.idean.atthack.network.RequestHelper.java

/**
 * Send secured HTTP Post to argument URL. Secured with basic http
 * authentication//from www.j  a v  a 2s . co m
 */
private Result sendHttpPost(JSONObject obj, String urlStr) {
    HttpURLConnection conn = null;
    try {
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(HttpVerb.POST.name());
        conn.setRequestProperty("Content-Type", "application/json");
        setBasicAuth(conn);
        conn.setDoOutput(true);
        writeBody(conn, obj);
        conn.connect();
        Log.d(TAG, "[" + conn.getRequestMethod() + "] to " + url.toString());

        String body = readStream(conn.getInputStream());
        return new Result(conn.getResponseCode(), body);
    } catch (IOException e) {
        return new Result(e.getClass() + ": " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:photosharing.api.conx.CommentsDefinition.java

/**
 * updates a given comment//  w  w w.  j a v  a2s .  co  m
 * 
 * @param bearer
 *            the accessToken
 * @param cid
 *            the comment id
 * @param pid
 *            the file id
 * @param uid
 *            the library id
 * @param body
 *            the text body
 * @param nonce
 *            the nonce value
 * @param response
 *            the response that is going to get the response
 */
public void updateComment(String bearer, String cid, String pid, String uid, String body, String nonce,
        HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/userlibrary/" + uid + "/document/" + pid + "/comment/" + cid + "/entry";
    try {
        JSONObject obj = new JSONObject(body);

        String comment = generateComment(obj.getString("comment"));

        // Generate the
        Request put = Request.Put(apiUrl);
        put.addHeader("Authorization", "Bearer " + bearer);
        put.addHeader("X-Update-Nonce", nonce);
        put.addHeader("Content-Type", "application/atom+xml");

        ByteArrayEntity entity = new ByteArrayEntity(comment.getBytes("UTF-8"));
        put.body(entity);

        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(put);
        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes
         */
        int code = hr.getStatusLine().getStatusCode();

        // Checks the status code for the response
        if (code == HttpStatus.SC_FORBIDDEN) {
            // Session is no longer valid or access token is expired
            response.setStatus(HttpStatus.SC_FORBIDDEN);
        } else if (code == HttpStatus.SC_UNAUTHORIZED) {
            // User is not authorized
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        } else {
            // Default to 200
            response.setStatus(HttpStatus.SC_OK);
        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("Issue with update comment" + e.toString());
    } catch (JSONException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("Issue with update comments " + e.toString());
        e.printStackTrace();
    }

}

From source file:it.newfammulfin.api.EntryResource.java

@POST
@Consumes("text/csv")
@Produces(MediaType.TEXT_PLAIN)/*from ww  w .  j a va2  s  . c  om*/
public Response importFromCsv(String csvData,
        @DefaultValue("false") @QueryParam("invertSign") final boolean invertSign) {
    final Group group = (Group) requestContext.getProperty(GroupRetrieverRequestFilter.GROUP);
    final Map<String, Key<Chapter>> chapterStringsMap = new HashMap<>();
    final List<CSVRecord> records;
    try {
        records = CSVParser.parse(csvData, CSVFormat.DEFAULT.withHeader()).getRecords();
    } catch (IOException e) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(String.format("Unexpected %s: %s.", e.getClass().getSimpleName(), e.getMessage()))
                .build();
    }
    //check users
    final Set<String> userIds = new HashSet<>();
    for (String columnName : records.get(0).toMap().keySet()) {
        if (columnName.startsWith("by:")) {
            String userId = columnName.replaceFirst("by:", "");
            if (!group.getUsersMap().keySet().contains(Key.create(RegisteredUser.class, userId))) {
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                        .entity(String.format("User %s not found in this group.", userId)).build();
            }
            userIds.add(userId);
        }
    }
    //build chapters
    final Set<String> chapterStringsSet = new HashSet<>();
    for (CSVRecord record : records) {
        chapterStringsSet.add(record.get("chapters"));
    }
    final List<Key<?>> createdKeys = new ArrayList<>();
    try {
        OfyService.ofy().transact(new Work<List<Key<?>>>() {
            @Override
            public List<Key<?>> run() {
                for (String chapterStrings : chapterStringsSet) {
                    List<String> pieces = Arrays.asList(chapterStrings.split(CSV_CHAPTERS_SEPARATOR));
                    Key<Chapter> parentChapterKey = null;
                    for (int i = 0; i < pieces.size(); i++) {
                        String partialChapterString = Joiner.on(CSV_CHAPTERS_SEPARATOR)
                                .join(pieces.subList(0, i + 1));
                        Key<Chapter> chapterKey = chapterStringsMap.get(partialChapterString);
                        if (chapterKey == null) {
                            chapterKey = OfyService.ofy().load().type(Chapter.class).ancestor(group)
                                    .filter("name", pieces.get(i)).filter("parentChapterKey", parentChapterKey)
                                    .keys().first().now();
                            chapterStringsMap.put(partialChapterString, chapterKey);
                        }
                        if (chapterKey == null) {
                            Chapter chapter = new Chapter(pieces.get(i), Key.create(group), parentChapterKey);
                            OfyService.ofy().save().entity(chapter).now();
                            chapterKey = Key.create(chapter);
                            createdKeys.add(chapterKey);
                            LOG.info(String.format("%s created.", chapter));
                        }
                        chapterStringsMap.put(partialChapterString, chapterKey);
                        parentChapterKey = chapterKey;
                    }
                }
                //build entries
                DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/YY");
                Key<Group> groupKey = Key.create(group);
                for (CSVRecord record : records) {
                    Entry entry = new Entry();
                    entry.setGroupKey(groupKey);
                    entry.setDate(LocalDate.parse(record.get("date"), formatter));
                    entry.setAmount(Money.of(CurrencyUnit.of(record.get("currency").toUpperCase()),
                            (invertSign ? -1 : 1) * Double.parseDouble(record.get("value"))));
                    if (!record.get("chapters").isEmpty()) {
                        entry.setChapterKey(chapterStringsMap.get(record.get("chapters")));
                    }
                    entry.setPayee(record.get("payee"));
                    for (String tag : record.get("tags").split(CSV_TAGS_SEPARATOR)) {
                        if (!tag.trim().isEmpty()) {
                            entry.getTags().add(tag);
                        }
                    }
                    entry.setDescription(record.get("description"));
                    entry.setNote(record.get("notes"));
                    int scale = Math.max(DEFAULT_SHARE_SCALE, entry.getAmount().getScale());
                    //by shares
                    for (String userId : userIds) {
                        String share = record.get("by:" + userId);
                        double value;
                        if (share.contains("%")) {
                            entry.setByPercentage(true);
                            value = Double.parseDouble(share.replace("%", ""));
                            value = entry.getAmount().getAmount().doubleValue() * value / 100d;
                        } else {
                            value = (invertSign ? -1 : 1) * Double.parseDouble(share);
                        }
                        entry.getByShares().put(Key.create(RegisteredUser.class, userId),
                                BigDecimal.valueOf(value).setScale(scale, RoundingMode.DOWN));
                    }
                    boolean equalByShares = checkAndBalanceZeroShares(entry.getByShares(),
                            entry.getAmount().getAmount());
                    entry.setByPercentage(entry.isByPercentage() || equalByShares);
                    //for shares
                    for (String userId : userIds) {
                        String share = record.get("for:" + userId);
                        double value;
                        if (share.contains("%")) {
                            entry.setForPercentage(true);
                            value = Double.parseDouble(share.replace("%", ""));
                            value = entry.getAmount().getAmount().doubleValue() * value / 100d;
                        } else {
                            value = (invertSign ? -1 : 1) * Double.parseDouble(share);
                        }
                        entry.getForShares().put(Key.create(RegisteredUser.class, userId),
                                BigDecimal.valueOf(value).setScale(scale, RoundingMode.DOWN));
                    }
                    boolean equalForShares = checkAndBalanceZeroShares(entry.getForShares(),
                            entry.getAmount().getAmount());
                    entry.setForPercentage(entry.isForPercentage() || equalForShares);
                    OfyService.ofy().save().entity(entry).now();
                    createdKeys.add(Key.create(entry));
                    EntryOperation operation = new EntryOperation(Key.create(group), Key.create(entry),
                            new Date(),
                            Key.create(RegisteredUser.class, securityContext.getUserPrincipal().getName()),
                            EntryOperation.Type.IMPORT);
                    OfyService.ofy().save().entity(operation).now();
                    LOG.info(String.format("%s created.", entry));
                }
                return createdKeys;
            }
        });
        //count keys
        int numberOfCreatedChapters = 0;
        int numberOfCreatedEntries = 0;
        for (Key<?> key : createdKeys) {
            if (key.getKind().equals(Entry.class.getSimpleName())) {
                numberOfCreatedEntries = numberOfCreatedEntries + 1;
            } else if (key.getKind().equals(Chapter.class.getSimpleName())) {
                numberOfCreatedChapters = numberOfCreatedChapters + 1;
            }
        }
        return Response.ok(String.format("Done: %d chapters and %d entries created.", numberOfCreatedChapters,
                numberOfCreatedEntries)).build();
    } catch (RuntimeException e) {
        LOG.warning(String.format("Unexpected %s: %s.", e.getClass().getSimpleName(), e.getMessage()));
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(String.format("Unexpected %s: %s.", e.getClass().getSimpleName(), e.getMessage()))
                .build();
    }
}

From source file:com.github.vatbub.vatbubgitreports.Main.java

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("application/json");
    PrintWriter writer;//from ww w.j  av a 2 s .  c om
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    StringBuilder requestBody = new StringBuilder();
    String line;

    try {
        writer = response.getWriter();
    } catch (IOException e) {
        Internet.sendErrorMail("getWriter", "Unable not read request", e, gMailUsername, gMailPassword);
        e.printStackTrace();
        response.setStatus(500);
        return;
    }

    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            requestBody.append(line);
        }
    } catch (IOException e) {
        Error error = new Error(e.getClass().getName() + " occurred while reading the request",
                ExceptionUtils.getFullStackTrace(e));
        writer.write(gson.toJson(error));
        response.setStatus(500);
        Internet.sendErrorMail("ReadRequestBody", requestBody.toString(), e, gMailUsername, gMailPassword);
        return;
    }

    // parse the request
    if (!request.getContentType().equals("application/json")) {
        // bad content type
        Error error = new Error("content type must be application/json");
        writer.write(gson.toJson(error));
    }

    GitHubIssue gitHubIssue;

    try {
        System.out.println("Received request:");
        System.out.println(requestBody.toString());
        System.out.println("Request encoding is: " + request.getCharacterEncoding());
        gitHubIssue = gson.fromJson(requestBody.toString(), GitHubIssue.class);
    } catch (Exception e) {
        Internet.sendErrorMail("ParseJSON", requestBody.toString(), e, gMailUsername, gMailPassword);
        Error error = new Error(e.getClass().getName() + " occurred while parsing the request",
                ExceptionUtils.getFullStackTrace(e));
        writer.write(gson.toJson(error));
        response.setStatus(500);
        return;
    }

    // Authenticate on GitHub
    GitHubClient client = new GitHubClient();
    client.setOAuth2Token(System.getenv("GITHUB_ACCESS_TOKEN"));

    // Convert the issue object
    Issue issue = new Issue();
    issue.setTitle(gitHubIssue.getTitle());
    String body = "";
    boolean metadataGiven = false;
    if (!gitHubIssue.getReporterName().equals("")) {
        body = "Reporter name: " + gitHubIssue.getReporterName() + "\n";
        metadataGiven = true;
    }
    if (!gitHubIssue.getReporterEmail().equals("")) {
        body = body + "Reporter email: " + gitHubIssue.getReporterEmail() + "\n";
        metadataGiven = true;
    }
    if (gitHubIssue.getLogLocation() != null) {
        body = body + "Log location: " + gitHubIssue.getLogLocation() + "\n";
        metadataGiven = true;
    }
    if (gitHubIssue.getScreenshotLocation() != null) {
        body = body + "Screenshot location: " + gitHubIssue.getScreenshotLocation() + "\n";
        metadataGiven = true;
    }
    if (gitHubIssue.getThrowable() != null) {
        body = body + "Exception stacktrace:\n" + ExceptionUtils.getFullStackTrace(gitHubIssue.getThrowable())
                + "\n";
        metadataGiven = true;
    }
    if (metadataGiven) {
        body = body + "----------------------------------" + "\n\nDESCRIPTION:\n";
    }
    body = body + gitHubIssue.getBody();

    issue.setBody(body);

    // send the issue to GitHub
    try {
        new IssueService(client).createIssue(gitHubIssue.getToRepo_Owner(), gitHubIssue.getToRepo_RepoName(),
                issue);
    } catch (IOException e) {
        e.printStackTrace();
        Error error = new Error(e.getClass().getName() + " occurred while parsing the request",
                ExceptionUtils.getFullStackTrace(e));
        writer.write(gson.toJson(error));
        response.setStatus(500);
        Internet.sendErrorMail("ForwardToGitHub", requestBody.toString(), e, gMailUsername, gMailPassword);
        return;
    }

    writer.write(gson.toJson(issue));
}

From source file:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java

private SampleResult sampleConnect(SampleResult sr) {
    IMAPClient client;//from  w  w w  . j av a 2s. c o m
    if (getUseSSL()) {
        client = new IMAPSClient(true);
    } else {
        client = new IMAPClient();
    }
    try {
        String request = "CONNECT \n";
        request += "Host : " + getHostname() + ":" + getPort() + "\n";
        request += "Default Timeout : " + getDefaultTimeout() + "\n";
        request += "Connect Timeout : " + getConnectionTimeout() + "\n";
        request += "So Timeout : " + getSoTimeout() + "\n";
        request += "Client : " + getClient() + "\n";

        sr.setRequestHeaders(request);
        sr.sampleStart();
        client.setDefaultTimeout(getDefaultTimeout());
        client.setConnectTimeout(getConnectionTimeout());
        if (getLocalAddr().isEmpty())
            client.connect(getHostname(), getPort());
        else
            client.connect(getHostname(), getPort(), InetAddress.getByName(getLocalAddr()), 0);
        if (client.isConnected()) {
            log.info("imap client " + getClient() + " connected from " + client.getLocalAddress() + ":"
                    + client.getLocalPort());
            SessionStorage.proto_type protoType = SessionStorage.proto_type.PLAIN;
            if (getUseSSL())
                protoType = SessionStorage.proto_type.SSL;
            SessionStorage.getInstance().putClient(getSOClient(), client, protoType);
            client.setSoTimeout(getSoTimeout());
            sr.setSuccessful(true);
            sr.setResponseCodeOK();
            sr.setResponseData(client.getReplyString().getBytes());
        } else {
            client.close();
            sr.setSuccessful(false);
            sr.setResponseCode("java.net.ConnectException");
            sr.setResponseMessage("Not connected");
        }
    } catch (SocketException se) {
        sr.setResponseMessage(se.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(se.getClass().getName());
        log.error("client `" + getClient() + "` ", se);
        removeClient();
    } catch (IOException ioe) {
        sr.setResponseMessage(ioe.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(ioe.getClass().getName());
        log.error("client `" + getClient() + "` ", ioe);
        removeClient();
    } finally {
        sr.sampleEnd();
    }
    return sr;
}

From source file:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java

private SampleResult sampleDisconnect(SampleResult sr) {
    SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient());
    IMAPClient client = null;//w w  w .  j a  v  a  2  s  .c  om
    if (soclient instanceof IMAPClient)
        client = (IMAPClient) soclient;

    String request = "DISCONNECT \n";
    request += "Client : " + getClient() + "\n";
    sr.setRequestHeaders(request);
    if (client == null) {
        clientNotFound(sr);
        return sr;
    } else {
        synchronized (client) {
            sr.sampleStart();
            try {
                client.disconnect();
                SessionStorage.getInstance().removeClient(getSOClient());
                sr.setSuccessful(true);
                sr.setResponseCodeOK();
                sr.setResponseData(client.getReplyString().getBytes());
            } catch (IOException e) {
                sr.setSuccessful(false);
                sr.setResponseData(e.toString().getBytes());
                sr.setResponseCode(e.getClass().getName());
                log.error("client `" + getClient() + "` ", e);
                removeClient();
            } finally {
                sr.sampleEnd();
            }
        }
    }
    return sr;
}