Example usage for java.net HttpURLConnection HTTP_OK

List of usage examples for java.net HttpURLConnection HTTP_OK

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_OK.

Prototype

int HTTP_OK

To view the source code for java.net HttpURLConnection HTTP_OK.

Click Source Link

Document

HTTP Status-Code 200: OK.

Usage

From source file:com.googlecode.fascinator.portal.quartz.ExternalJob.java

/**
 * The real work happens here/*from  w w w  .ja  va  2 s .c om*/
 *
 */
private void runJob() {
    HttpURLConnection conn = null;
    log.debug("Job firing: '{}'", name);

    try {
        // Open tasks... much simpler
        if (token == null) {
            conn = (HttpURLConnection) url.openConnection();

            // Secure tasks
        } else {
            String param = "token=" + URLEncoder.encode(token, "UTF-8");

            // Prepare our request
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", "" + Integer.toString(param.getBytes().length));
            conn.setUseCaches(false);
            conn.setDoOutput(true);

            // Send request
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(param);
            wr.flush();
            wr.close();
        }

        // Get Response
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            log.error("Error hitting external script: {}", conn.getResponseMessage());
        }
    } catch (IOException ex) {
        log.error("Error connecting to URL: ", ex);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:org.jboss.as.test.integration.web.cookie.CookieUnitTestCase.java

@Test
public void testCookieRetrievedCorrectly() throws Exception {
    log.info("testCookieRetrievedCorrectly()");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieServlet"));

    // assert that we are able to hit servlet successfully
    int postStatusCode = response.getStatusLine().getStatusCode();
    Header[] postErrorHeaders = response.getHeaders("X-Exception");
    assertTrue("Wrong response code: " + postStatusCode, postStatusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-Exception(" + Arrays.toString(postErrorHeaders) + ") is null", postErrorHeaders.length == 0);

    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    assertTrue("Sever did not set expired cookie on client", checkNoExpiredCookie(cookies));

    for (Cookie cookie : cookies) {
        log.info("Cookie : " + cookie);
        String cookieName = cookie.getName();
        String cookieValue = cookie.getValue();

        if (cookieName.equals("simpleCookie")) {
            assertTrue("cookie value should be jboss", cookieValue.equals("jboss"));
            assertEquals("cookie path", "/jbosstest-cookie", cookie.getPath());
            assertEquals("cookie persistence", false, cookie.isPersistent());
        } else if (cookieName.equals("withSpace")) {
            assertEquals("should be no quote in cookie with space", cookieValue.indexOf("\""), -1);
        } else if (cookieName.equals("comment")) {
            log.info("comment in cookie: " + cookie.getComment());
            // RFC2109:Note that there is no Comment attribute in the Cookie request header
            // corresponding to the one in the Set-Cookie response header. The user
            // agent does not return the comment information to the origin server.

            assertTrue(cookie.getComment() == null);
        } else if (cookieName.equals("withComma")) {
            assertTrue("should contain a comma", cookieValue.indexOf(",") != -1);
        } else if (cookieName.equals("expireIn10Sec")) {
            Date now = new Date();
            log.info("will sleep for 5 seconds to see if cookie expires");
            assertTrue("cookies should not be expired by now",
                    !cookie.isExpired(new Date(now.getTime() + fiveSeconds)));
            log.info("will sleep for 5 more secs and it should expire");
            assertTrue("cookies should be expired by now",
                    cookie.isExpired(new Date(now.getTime() + 2 * fiveSeconds)));
        }/*from w  w w. j a va  2 s  .c  om*/
    }
}

From source file:com.cydroid.coreframe.web.img.fetcher.ImageFetcher.java

public Bitmap getImage(String path) throws Exception {
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10 * 1000);//from   ww w . ja v  a2 s. co m
    conn.setConnectTimeout(10 * 1000);
    conn.setRequestMethod("GET");
    InputStream is = null;
    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        is = conn.getInputStream();
    } else {
        is = null;
    }
    if (is == null) {
        throw new RuntimeException("stream is null");
    } else {
        try {
            byte[] data = readStream(is);
            if (data != null) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                return bitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        is.close();
        return null;
    }
}

From source file:com.streamsets.pipeline.stage.origin.httpserver.TestHttpServerPushSource.java

@Test
public void testSource() throws Exception {
    RawHttpConfigs httpConfigs = new RawHttpConfigs();
    httpConfigs.appId = () -> "id";
    httpConfigs.port = NetworkUtils.getRandomPort();
    httpConfigs.maxConcurrentRequests = 1;
    httpConfigs.tlsConfigBean.tlsEnabled = false;
    HttpServerPushSource source = new HttpServerPushSource(httpConfigs, 1, DataFormat.TEXT,
            new DataParserFormatConfig());
    final PushSourceRunner runner = new PushSourceRunner.Builder(HttpServerDPushSource.class, source)
            .addOutputLane("a").build();
    runner.runInit();//www  . j  a  v a2s  .c  om
    try {
        final List<Record> records = new ArrayList<>();
        runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
            @Override
            public void processBatch(StageRunner.Output output) {
                records.clear();
                records.addAll(output.getRecords().get("a"));
            }
        });

        // wait for the HTTP server up and running
        HttpReceiverServer httpServer = (HttpReceiverServer) Whitebox.getInternalState(source, "server");
        await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer));

        HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:" + httpConfigs.getPort())
                .openConnection();
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty(Constants.X_SDC_APPLICATION_ID_HEADER, "id");
        connection.setRequestProperty("customHeader", "customHeaderValue");
        connection.getOutputStream().write("Hello".getBytes());
        Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
        Assert.assertEquals(1, records.size());
        Assert.assertEquals("Hello", records.get(0).get("/text").getValue());
        Assert.assertEquals("id",
                records.get(0).getHeader().getAttribute(Constants.X_SDC_APPLICATION_ID_HEADER));
        Assert.assertEquals("customHeaderValue", records.get(0).getHeader().getAttribute("customHeader"));

        // passing App Id via query param should fail when appIdViaQueryParamAllowed is false
        String url = "http://localhost:" + httpConfigs.getPort() + "?"
                + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM + "=id";
        Response response = ClientBuilder.newClient().target(url).request().post(Entity.json("Hello"));
        Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getStatus());

        runner.setStop();
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        runner.runDestroy();
    }
}

From source file:com.scvngr.levelup.core.net.LevelUpResponseTest.java

/**
 * Tests {@link com.scvngr.levelup.core.net.LevelUpResponse#mapStatus(int, String)}.
 *//*from   w w  w. j  a  v  a  2s .  co  m*/
@SmallTest
public void testMapStatusHttp_okCode() {
    assertEquals(LevelUpStatus.OK,
            LevelUpResponse.mapStatus(HttpURLConnection.HTTP_OK, SERVER_LEVELUP_PLATFORM));
}

From source file:com.stackmob.example.CRUD.CreateObject.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    String model = "";
    String make = "";
    String year = "";

    LoggerService logger = serviceProvider.getLoggerService(CreateObject.class);
    // JSON object gets passed into the StackMob Logs
    logger.debug(request.getBody());//from   w ww  .ja v a2  s.  c  om

    // I'll be using these maps to print messages to console as feedback to the operation
    Map<String, SMValue> feedback = new HashMap<String, SMValue>();
    Map<String, String> errMap = new HashMap<String, String>();

    /* The following try/catch block shows how to properly fetch parameters for PUT/POST operations
     * from the JSON request body
     */
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;

        // Fetch the values passed in by the user from the body of JSON
        model = (String) jsonObject.get("model");
        make = (String) jsonObject.get("make");
        year = (String) jsonObject.get("year");
    } catch (ParseException pe) {
        logger.error(pe.getMessage(), pe);
        return Util.badRequestResponse(errMap);
    }

    if (Util.hasNulls(model, make, year)) {
        return Util.badRequestResponse(errMap);
    }

    feedback.put("model", new SMString(model));
    feedback.put("make", new SMString(make));
    feedback.put("year", new SMInt(Long.parseLong(year)));

    DataService ds = serviceProvider.getDataService();
    try {
        // This is how you create an object in the `car` schema
        ds.createObject("car", new SMObject(feedback));
    } catch (InvalidSchemaException ise) {
        return Util.internalErrorResponse("invalid_schema", ise, errMap); // http 500 - internal server error
    } catch (DatastoreException dse) {
        return Util.internalErrorResponse("datastore_exception", dse, errMap); // http 500 - internal server error
    }

    return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback);
}

From source file:org.sasabus.export2Freegis.network.DataReadyManager.java

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    long start = System.currentTimeMillis();
    BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "UTF-8"));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpExchange.getResponseBody()));
    try {//from  ww w. j a va 2 s.c  o m
        StringBuilder requestStringBuff = new StringBuilder();
        int b;
        while ((b = in.read()) != -1) {
            requestStringBuff.append((char) b);
        }
        Scanner sc = new Scanner(new File(DATAACKNOWLEDGE));
        String rdyackstring = "";
        while (sc.hasNextLine()) {
            rdyackstring += sc.nextLine();
        }
        sc.close();
        SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ");

        Date d = new Date();
        String timestamp = date_date.format(d) + "T" + date_time.format(d);
        timestamp = timestamp.substring(0, timestamp.length() - 2) + ":"
                + timestamp.substring(timestamp.length() - 2);

        rdyackstring = rdyackstring.replaceAll(":timestamp", timestamp);

        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, rdyackstring.length());
        out.write(rdyackstring);
        out.flush();
        long before_elab = System.currentTimeMillis() - start;
        DataRequestManager teqrequest = new DataRequestManager(this.hostname, this.portnumber);
        String datarequest = teqrequest.datarequest();
        ArrayList<TeqObjects> requestelements = TeqXMLUtils.extractFromXML(datarequest);
        int vtcounter = 0;
        if (!requestelements.isEmpty()) {
            Iterator<TeqObjects> iterator = requestelements.iterator();
            System.out.println("Sending List of Elements!");
            String geoJson = "{\"type\":\"FeatureCollection\",\"features\":[";
            while (iterator.hasNext()) {
                TeqObjects object = iterator.next();
                if (object instanceof VehicleTracking) {
                    geoJson += ((VehicleTracking) object).toGeoJson() + ",";
                    ++vtcounter;
                }
            }
            if (geoJson.charAt(geoJson.length() - 1) == ',') {
                geoJson = geoJson.substring(0, geoJson.length() - 1);
            }
            geoJson += "]}";
            System.out.println(
                    "GeoJson sent! (Nr of elements: " + vtcounter + "/" + requestelements.size() + " )");
            HttpPost subrequest = new HttpPost(DATASEND);

            StringEntity requestEntity = new StringEntity(geoJson,
                    ContentType.create("application/json", "UTF-8"));

            CloseableHttpClient httpClient = HttpClients.createDefault();

            subrequest.setEntity(requestEntity);
            long after_elab = System.currentTimeMillis() - start;
            CloseableHttpResponse response = httpClient.execute(subrequest);
            //System.out.println("Stauts JsonSend Response: " + response.getStatusLine().getStatusCode());
            //System.out.println("Status JsonSend Phrase: " + response.getStatusLine().getReasonPhrase());
            httpClient.close();
            long before_db = System.currentTimeMillis() - start;
            dbmanager.insertIntoDatabase(requestelements);
            System.out.format(
                    "Thread time (ms) : Before elab: %d, After Elab (before http sending): %d, Before db: %d, Total: %d, Thread name: %s, Objects elaborated: %d",
                    before_elab, after_elab, before_db, (System.currentTimeMillis() - start),
                    Thread.currentThread().getName(), requestelements.size());
            System.out.println("");
        }

    } catch (IOException e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        System.exit(-1);
        return;
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
        if (httpExchange != null)
            httpExchange.close();
    }
}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.connotea.ConnoteaUtils.java

/** send a POST Request and return the response as string */
String sendPostRequest(String url, String bodytext) throws Exception {
    String sresponse;/* w  w  w.  jav  a 2 s. c om*/

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    // set authentication header
    httppost.addHeader("Authorization", authHeader);

    // very important. otherwise there comes a invalid request error
    httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    StringEntity body = new StringEntity(bodytext);
    body.setContentType("application/x-www-form-urlencoded");

    httppost.setEntity(body);

    HttpResponse response = httpclient.execute(httppost);

    // check status code.
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
        // Not found too. no exception should be thrown.
        HttpEntity entity = response.getEntity();

        sresponse = readResponseStream(entity.getContent());
        httpclient.getConnectionManager().shutdown();
    } else {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        String httpcode = Integer.toString(response.getStatusLine().getStatusCode());
        httpclient.getConnectionManager().shutdown();
        throw new ReferenceSystemException(httpcode, "Connotea Error", RDFUtils.parseError(sresponse));
    }
    return sresponse;

}

From source file:net.andylizi.colormotd.Updater.java

private boolean checkUpdate() {
    if (file != null && file.exists()) {
        cancel();/* w  w w.j  ava2  s. com*/
    }
    URL url;
    try {
        url = new URL(UPDATE_URL);
    } catch (MalformedURLException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        return false;
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("User-Agent", userAgent);
        if (etag != null) {
            conn.addRequestProperty("If-None-Match", etag);
        }
        conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8");
        conn.addRequestProperty("Accept-Encoding", "gzip");
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("Date", new Date().toString());
        conn.addRequestProperty("Connection", "close");

        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();

        if (conn.getHeaderField("ETag") != null) {
            etag = conn.getHeaderField("ETag");
        }
        if (DEBUG) {
            logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode());
            logger.log(Level.INFO, "DEBUG ETag: {0}", etag);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return false;
        } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }

        BufferedReader input = null;
        if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) {
            input = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1);
        } else {
            input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1);
        }

        StringBuilder builder = new StringBuilder();
        String buffer = null;
        while ((buffer = input.readLine()) != null) {
            builder.append(buffer);
        }
        try {
            JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString());
            int build = ((Number) jsonObj.get("build")).intValue();
            if (build <= ColorMOTD.buildVersion) {
                return false;
            }
            String version = (String) jsonObj.get("version");
            String msg = (String) jsonObj.get("msg");
            String download_url = (String) jsonObj.get("url");
            newVersion = new NewVersion(version, build, msg, download_url);
            return true;
        } catch (ParseException ex) {
            if (DEBUG) {
                ex.printStackTrace();
            }
            exception = ex;
            return false;
        }
    } catch (SocketTimeoutException ex) {
        return false;
    } catch (IOException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        exception = ex;
        return false;
    }
}

From source file:de.egore911.versioning.deployer.performer.PerformExtraction.java

private static boolean extract(String uri, List<ExtractionPair> extractions) {
    URL url;//from   w ww.j  ava2 s  .  c  o m
    try {
        url = new URL(uri);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        return false;
    }
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();

        int lastSlash = uri.lastIndexOf('/');
        if (lastSlash < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        int lastDot = uri.lastIndexOf('.');
        if (lastDot < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        File downloadFile = File.createTempFile(uri.substring(lastSlash + 1), uri.substring(lastDot + 1));
        downloadFile.deleteOnExit();

        if (response == HttpURLConnection.HTTP_OK) {
            try (InputStream in = connection.getInputStream();
                    FileOutputStream out = new FileOutputStream(downloadFile)) {
                IOUtils.copy(in, out);
            }
            LOG.debug("Downloaded {} to {}", url, downloadFile.getAbsolutePath());

            Set<ExtractionPair> usedExtractions = new HashSet<>();

            // Perform extractions
            try (ZipFile zipFile = new ZipFile(downloadFile)) {
                Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();

                    // Only extract files
                    if (entry.isDirectory()) {
                        continue;
                    }

                    for (ExtractionPair extraction : extractions) {
                        String sourcePattern = extraction.source;
                        if (FilenameUtils.wildcardMatch(entry.getName(), sourcePattern)) {
                            usedExtractions.add(extraction);
                            LOG.debug("Found matching file {} for source pattern {}", entry.getName(),
                                    sourcePattern);
                            String filename = getSourcePatternMatch(entry.getName(), sourcePattern);
                            // Workaround: If there is no matcher in 'sourcePattern' it will return the
                            // complete path. Strip it down to the filename
                            if (filename.equals(entry.getName())) {
                                int lastIndexOf = filename.lastIndexOf('/');
                                if (lastIndexOf >= 0) {
                                    filename = filename.substring(lastIndexOf + 1);
                                }
                            }
                            String name = UrlUtil.concatenateUrlWithSlashes(extraction.destination, filename);
                            FileUtils.forceMkdir(new File(name).getParentFile());
                            try (InputStream in = zipFile.getInputStream(entry);
                                    FileOutputStream out = new FileOutputStream(name)) {
                                IOUtils.copy(in, out);
                            }
                            LOG.debug("Extracted {} to {} from {}", entry.getName(), name, uri);
                        }
                    }
                }
            }

            for (ExtractionPair extraction : extractions) {
                if (!usedExtractions.contains(extraction)) {
                    LOG.debug("Extraction {} to {} not used on {}", extraction.source, extraction.destination,
                            uri);
                }
            }

            return true;
        } else {
            LOG.error("Could not download file: {}", uri);
            return false;
        }
    } catch (IOException e) {
        LOG.error("Could not download file: {}", e.getMessage(), e);
        return false;
    }
}