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:net.modelbased.proasense.storage.fuseki.StorageRegistryFusekiService.java

@GET
@Path("/query/machine/list")
@Produces(MediaType.APPLICATION_JSON)//from  w  w w  .ja v  a 2s  .c om
public Response queryMachineList(@QueryParam("dataset") String dataset) {
    String FUSEKI_SPARQL_ENDPOINT_URL = getFusekiSparqlEndpointUrl(dataset);

    String SPARQL_MACHINE_LIST = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n"
            + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n"
            + "PREFIX ssn: <http://purl.oclc.org/NET/ssnx/ssn#>\n"
            + "PREFIX pssn: <http://www.sintef.no/pssn#>\n" + "\n" + "SELECT DISTINCT ?machineId\n"
            + "  WHERE {\n" + "    ?subject rdfs:subClassOf+ pssn:Machine .\n"
            + "    ?machineId rdf:type ?subject\n" + "  }\n" + "ORDER BY ASC (?machineId)";

    QueryExecution qe = QueryExecutionFactory.sparqlService(FUSEKI_SPARQL_ENDPOINT_URL, SPARQL_MACHINE_LIST);
    ResultSet results = qe.execSelect();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ResultSetFormatter.outputAsJSON(baos, results);

    String jsonResults = baos.toString();
    jsonResults = jsonResults.replaceAll("http://www.sintef.no/pssn#", "");

    qe.close();

    JSONObject jsonResponse = new JSONObject();
    JSONArray machineArray = new JSONArray();

    ObjectMapper mapper = new ObjectMapper();
    try {
        JsonNode rootNode = mapper.readTree(jsonResults);
        JsonNode resultsNode = rootNode.path("results");
        JsonNode bindingsNode = resultsNode.path("bindings");
        Iterator<JsonNode> iterator = bindingsNode.getElements();
        while (iterator.hasNext()) {
            JsonNode xNode = iterator.next();
            List<String> valueNode = xNode.findValuesAsText("value");

            machineArray.put(valueNode.get(0));
        }
    } catch (IOException e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    jsonResponse.put("machine", machineArray);

    String result = jsonResponse.toString(2);

    // Return HTTP response 200 in case of success
    return Response.status(200).entity(result).build();
}

From source file:net.modelbased.proasense.storage.fuseki.StorageRegistryFusekiService.java

@GET
@Path("/query/product/list")
@Produces(MediaType.APPLICATION_JSON)//w  ww .java  2s.  c  o m
public Response queryProductList(@QueryParam("dataset") String dataset) {
    String FUSEKI_SPARQL_ENDPOINT_URL = getFusekiSparqlEndpointUrl(dataset);

    String SPARQL_PRODUCT_LIST = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n"
            + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n"
            + "PREFIX ssn: <http://purl.oclc.org/NET/ssnx/ssn#>\n"
            + "PREFIX pssn: <http://www.sintef.no/pssn#>\n" + "\n" + "SELECT DISTINCT ?productId\n"
            + "  WHERE {\n" + "    ?productId rdf:type pssn:Product .\n" + "  }\n"
            + "ORDER BY ASC (?productId)";

    QueryExecution qe = QueryExecutionFactory.sparqlService(FUSEKI_SPARQL_ENDPOINT_URL, SPARQL_PRODUCT_LIST);
    ResultSet results = qe.execSelect();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ResultSetFormatter.outputAsJSON(baos, results);

    qe.close();

    String jsonResults = baos.toString();
    jsonResults = jsonResults.replaceAll("http://www.sintef.no/pssn#", "");

    JSONObject jsonResponse = new JSONObject();
    JSONArray productArray = new JSONArray();

    ObjectMapper mapper = new ObjectMapper();
    try {
        JsonNode rootNode = mapper.readTree(jsonResults);
        JsonNode resultsNode = rootNode.path("results");
        JsonNode bindingsNode = resultsNode.path("bindings");
        Iterator<JsonNode> iterator = bindingsNode.getElements();
        while (iterator.hasNext()) {
            JsonNode xNode = iterator.next();
            List<String> valueNode = xNode.findValuesAsText("value");

            productArray.put(valueNode.get(0));
        }
    } catch (IOException e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    jsonResponse.put("product", productArray);

    String result = jsonResponse.toString(2);

    // Return HTTP response 200 in case of success
    return Response.status(200).entity(result).build();
}

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

/**
 * manages interactions with comments based on method
 * //from   w w  w .  jav a  2  s  .  co  m
 * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void run(HttpServletRequest request, HttpServletResponse response) {
    // HTTP Method that the request was made with:
    String method = request.getMethod();

    /**
     * get the users bearer token
     */
    HttpSession session = request.getSession(false);
    Object o = session.getAttribute(OAuth20Handler.CREDENTIALS);
    if (o == null) {
        logger.warning("Credential Object is not present");
    } else {
        OAuth20Data data = (OAuth20Data) o;
        String bearer = data.getAccessToken();

        // Create a Comment
        if (method.compareTo("POST") == 0) {
            // Extract the URL parameters from the request
            String pid = request.getParameter("pid");
            String uid = request.getParameter("uid");

            try {
                String body = IOUtils.toString(request.getInputStream());

                // Checks the State of the URL parameters
                if (pid == null || uid == null || body == null || body.isEmpty() || pid.isEmpty()
                        || uid.isEmpty()) {
                    response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
                } else {
                    String nonce = getNonce(bearer, response);
                    if (!nonce.isEmpty()) {
                        createComment(bearer, pid, uid, body, nonce, response);
                    }
                }

            } catch (IOException e) {
                response.setHeader("X-Application-Error", e.getClass().getName());
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                logger.severe("Issue with POST comment" + e.toString());
            }
        }
        // Update a Comment
        else if (method.compareTo("PUT") == 0) {
            // Extract the URL parameters from the request
            String cid = request.getParameter("cid");
            String pid = request.getParameter("pid");
            String uid = request.getParameter("uid");

            try {
                String body = IOUtils.toString(request.getInputStream());

                // Checks the State of the URL parameters
                if (cid == null || pid == null || uid == null || body == null || body.isEmpty() || cid.isEmpty()
                        || pid.isEmpty() || uid.isEmpty()) {
                    response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
                } else {
                    String nonce = getNonce(bearer, response);
                    if (!nonce.isEmpty()) {
                        updateComment(bearer, cid, pid, uid, body, nonce, response);
                    }
                }

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

        }
        // Delete a Comment
        else if (method.compareTo("DELETE") == 0) {
            // Extract the URL parameters from the request
            String cid = request.getParameter("cid");
            String pid = request.getParameter("pid");
            String uid = request.getParameter("uid");

            // Checks the State of the URL parameters
            if (cid == null || pid == null || uid == null || cid.isEmpty() || pid.isEmpty() || uid.isEmpty()) {
                response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
            } else {
                String nonce = getNonce(bearer, response);

                if (!nonce.isEmpty()) {
                    deleteComment(bearer, cid, pid, uid, response, nonce);
                }
            }

        }
        // Read a Comment and default to a GET
        else {
            // Extract the URL parameters from the request
            String pid = request.getParameter("pid");
            String uid = request.getParameter("uid");

            if (pid == null || uid == null || pid.isEmpty() || uid.isEmpty()) {
                response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
            } else {
                readComments(bearer, pid, uid, response);
            }

        }

    }

}

From source file:com.searchcode.app.jobs.IndexSvnRepoJob.java

public RepositoryChanged checkoutSvnRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, boolean useCredentials) {
    boolean successful = false;
    Singleton.getLogger().info("Attempting to checkout " + repoRemoteLocation);

    try {/*  w w  w  .j av  a 2s  . c  o  m*/
        File f = new File(repoLocations);
        if (!f.exists()) {
            f.mkdir();
        }

        ProcessBuilder processBuilder;

        // http://serverfault.com/questions/158349/how-to-stop-subversion-from-prompting-about-server-certificate-verification-fai
        // http://stackoverflow.com/questions/34687/subversion-ignoring-password-and-username-options#38386
        if (useCredentials) {
            processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "checkout", "--no-auth-cache",
                    "--non-interactive", repoRemoteLocation, repoName);
        } else {
            processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "checkout", "--no-auth-cache",
                    "--non-interactive", "--username", repoUserName, "--password", repoPassword,
                    repoRemoteLocation, repoName);
        }

        processBuilder.directory(new File(repoLocations));

        Process process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;

        while ((line = br.readLine()) != null) {
            Singleton.getLogger().info(line);
        }

        successful = true;

    } catch (IOException ex) {
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    RepositoryChanged repositoryChanged = new RepositoryChanged(successful);
    repositoryChanged.setClone(true);

    return repositoryChanged;
}

From source file:com.searchcode.app.jobs.repository.IndexBaseRepoJob.java

public CodeLinesReturn getCodeLines(String changedFile, List<String[]> reportList) {
    List<String> codeLines = new ArrayList<>();
    boolean error = false;

    try {/*from   w ww  . jav  a 2s .  c o m*/
        codeLines = Singleton.getHelpers().readFileLinesGuessEncoding(changedFile, this.MAXFILELINEDEPTH);
    } catch (IOException ex) {
        error = true;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
        if (this.LOGINDEXED) {
            reportList.add(new String[] { changedFile, "excluded", "unable to guess guess file encoding" });
        }
    }

    return new CodeLinesReturn(codeLines, reportList, error);
}

From source file:org.apache.pig.test.TestLocalPOSplit.java

public LogicalPlan buildPlan(String query, ClassLoader cldr) {
    LogicalPlanBuilder.classloader = cldr;

    LogicalPlanBuilder builder = new LogicalPlanBuilder(pigContext); //

    try {/*  w w  w  .  ja  v  a2s  .  c  o  m*/
        String[] qs = query.split(";");
        LogicalPlan lp = null;
        for (String q : qs) {
            q = q.trim();
            if (q.equals(""))
                continue;
            q += ";";
            System.out.println(q);
            lp = builder.parse("Test-Plan-Builder", q, aliases, logicalOpTable, aliasOp, fileNameMap);
        }

        List<LogicalOperator> roots = lp.getRoots();

        if (roots.size() > 0) {
            for (LogicalOperator op : roots) {
                if (!(op instanceof LOLoad) && !(op instanceof LODefine)) {
                    throw new Exception("Cannot have a root that is not the load or define operator. Found "
                            + op.getClass().getName());
                }
            }
        }

        System.err.println("Query: " + query);

        // Just the top level roots and their children
        // Need a recursive one to travel down the tree

        for (LogicalOperator op : lp.getRoots()) {
            System.err.println("Logical Plan Root: " + op.getClass().getName() + " object " + op);

            List<LogicalOperator> listOp = lp.getSuccessors(op);

            if (null != listOp) {
                Iterator<LogicalOperator> iter = listOp.iterator();
                while (iter.hasNext()) {
                    LogicalOperator lop = iter.next();
                    System.err.println("Successor: " + lop.getClass().getName() + " object " + lop);
                }
            }
        }
        lp = refineLogicalPlan(lp);
        assertTrue(lp != null);
        return lp;
    } catch (IOException e) {
        // log.error(e);
        // System.err.println("IOException Stack trace for query: " +
        // query);
        // e.printStackTrace();
        fail("IOException: " + e.getMessage());
    } catch (Exception e) {
        log.error(e);
        // System.err.println("Exception Stack trace for query: " + query);
        // e.printStackTrace();
        fail(e.getClass().getName() + ": " + e.getMessage() + " -- " + query);
    }
    return null;
}

From source file:org.robam.xutils.http.client.RetryHandler.java

/**
 * @param exception/*from w ww.j  a  va 2  s. c  o m*/
 * @param retriedTimes
 * @param context      HTTP,??,ActivityContext
 * @return
 */
@Override
public boolean retryRequest(IOException exception, int retriedTimes, HttpContext context) {
    boolean retry = true;

    if (exception == null || context == null) {
        return false;
    }

    // ?????,?,True
    Object isReqSent = context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = isReqSent == null ? false : (Boolean) isReqSent;

    // ???
    if (retriedTimes > maxRetries) {
        // ??,
        retry = false;
    } else if (exceptionBlackList.contains(exception.getClass())) {
        // ?BlackList???.
        retry = false;
    } else if (exceptionWhiteList.contains(exception.getClass())) {
        // ?????.
        retry = true;
    } else if (!sent) {
        // ??
        retry = true;
    }

    if (retry) {
        try {
            Object currRequest = context.getAttribute(ExecutionContext.HTTP_REQUEST);
            if (currRequest != null) {
                if (currRequest instanceof HttpRequestBase) {
                    // ???GET?retry,?GET,??
                    HttpRequestBase requestBase = (HttpRequestBase) currRequest;
                    retry = "GET".equals(requestBase.getMethod());
                } else if (currRequest instanceof RequestWrapper) {
                    RequestWrapper requestWrapper = (RequestWrapper) currRequest;
                    retry = "GET".equals(requestWrapper.getMethod());
                }
            } else {
                retry = false;
                LogUtils.e("retry error, curr request is null");
            }
        } catch (Throwable e) {
            retry = false;
            LogUtils.e("retry error", e);
        }
    }

    if (retry) {
        // sleep a while and retry http request again.
        SystemClock.sleep(RETRY_SLEEP_INTERVAL);
    }

    return retry;
}

From source file:net.modelbased.proasense.storage.fuseki.StorageRegistryFusekiService.java

@GET
@Path("/query/sensor/properties")
@Produces(MediaType.APPLICATION_JSON)/*  w  w w . j  a  v a  2s .  com*/
public Response querySensorProperties(@QueryParam("dataset") String dataset,
        @QueryParam("sensorId") String sensorId) {
    String FUSEKI_SPARQL_ENDPOINT_URL = getFusekiSparqlEndpointUrl(dataset);

    String SPARQL_SENSOR_PROPERTIES = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n"
            + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n"
            + "PREFIX ssn: <http://purl.oclc.org/NET/ssnx/ssn#>\n"
            + "PREFIX pssn: <http://www.sintef.no/pssn#>\n" + "\n" + "SELECT DISTINCT ?property ?value\n"
            + "  WHERE {\n" + "    pssn:SENSORID ?property ?value .\n" + "}";

    SPARQL_SENSOR_PROPERTIES = SPARQL_SENSOR_PROPERTIES.replaceAll("SENSORID", sensorId);

    QueryExecution qe = QueryExecutionFactory.sparqlService(FUSEKI_SPARQL_ENDPOINT_URL,
            SPARQL_SENSOR_PROPERTIES);
    ResultSet results = qe.execSelect();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ResultSetFormatter.outputAsJSON(baos, results);

    qe.close();

    String jsonResults = baos.toString();
    jsonResults = jsonResults.replaceAll("http://www.sintef.no/pssn#", "");

    JSONObject jsonResponse = new JSONObject();
    JSONObject eventPropertiesNode = new JSONObject();
    JSONArray eventPropertiesArray = new JSONArray();

    ObjectMapper mapper = new ObjectMapper();
    try {
        JsonNode rootNode = mapper.readTree(jsonResults);
        JsonNode resultsNode = rootNode.path("results");
        JsonNode bindingsNode = resultsNode.path("bindings");

        Iterator<JsonNode> iterator = bindingsNode.getElements();
        while (iterator.hasNext()) {
            JsonNode propertyNode = iterator.next();
            JsonNode nameNode = propertyNode.get("property");
            JsonNode valueNode = propertyNode.get("value");

            String propertyName = nameNode.findValuesAsText("value").get(0);
            String propertyValue = valueNode.findValuesAsText("value").get(0);

            if (propertyName.equals("eventProperty")) {
                JSONObject eventPropertyNode = parseEventProperty(propertyValue);
                eventPropertiesNode.put("eventProperty", eventPropertyNode);
                eventPropertiesArray.put(eventPropertiesNode);
            } else if (propertyName.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")) {
                // Ignore
            } else
                jsonResponse.put(propertyName, propertyValue);
        }
    } catch (IOException e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    jsonResponse.put("eventProperties", eventPropertiesArray);

    String result = jsonResponse.toString(2);

    // Return HTTP response 200 in case of success
    return Response.status(200).entity(result).build();
}

From source file:grakn.core.console.ConsoleSession.java

private void executeQuery(String queryString, boolean catchRuntimeException) throws IOException {
    // We'll use streams so we can print the answer out much faster and smoother
    try {/*from ww w. jav  a  2 s  . c  om*/
        // Parse the string to get a stream of Graql Queries
        Stream<GraqlQuery> queries = Graql.parseList(queryString);

        // Get the stream of answers for each query (query.stream())
        // Get the  stream of printed answers (printer.toStream(..))
        // Combine the stream of printed answers into one stream (queries.flatMap(..))
        Stream<String> answers = queries.flatMap(query -> printer.toStream(tx.stream(query, infer)));

        // For each printed answer, print them on one line
        answers.forEach(answer -> {
            try {
                consoleReader.println(answer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    } catch (RuntimeException e) {
        // Flush out all answers from previous iterators in the stream
        consoleReader.flush();

        if (catchRuntimeException) {
            if (!e.getMessage().isEmpty()) {
                printErr.println("Error: " + e.getMessage());
            } else {
                printErr.println("Error: " + e.getClass().getName());
            }
            printErr.println("All uncommitted data is cleared");
            //If console session was terminated by shutdown hook thread, do not try to reopen transaction
            if (terminated.get())
                return;
            reopenTransaction();
        } else {
            throw e;
        }
    }

    consoleReader.flush(); // Flush the ConsoleReader before the next command

    // It is important that we DO NOT close the transaction at the end of a query
    // The user may want to do consecutive operations onto the database
    // The transaction will only close once the user decides to COMMIT or ROLLBACK
}

From source file:com.zenesis.qx.remote.ProxySessionTracker.java

/**
 * Parses JSON and returns a suitable object
 * @param str/*from  w w w . ja va 2  s . c  o m*/
 * @return
 */
public Object fromJSON(String str) {
    try {
        return fromJSON(new StringReader(str));
    } catch (IOException e) {
        log.error("Error while parsing: " + e.getClass() + ": " + e.getMessage() + "; code was: " + str + "\n");
        throw new IllegalArgumentException(e);
    }
}