Example usage for java.net HttpURLConnection HTTP_NO_CONTENT

List of usage examples for java.net HttpURLConnection HTTP_NO_CONTENT

Introduction

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

Prototype

int HTTP_NO_CONTENT

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

Click Source Link

Document

HTTP Status-Code 204: No Content.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL("http://www.google.coom").openConnection();
    con.setRequestMethod("HEAD");
    System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT);
}

From source file:bluevia.examples.MODemo.java

/**
 * @param args//from  ww w. j  ava 2 s. c  o m
 */
public static void main(String[] args) throws IOException {

    BufferedReader iReader = null;
    String apiDataFile = "API-AccessToken.ini";

    String consumer_key;
    String consumer_secret;
    String registrationId;

    OAuthConsumer apiConsumer = null;
    HttpURLConnection request = null;
    URL moAPIurl = null;

    Logger logger = Logger.getLogger("moSMSDemo.class");
    int i = 0;
    int rc = 0;

    Thread mThread = Thread.currentThread();

    try {
        System.setProperty("debug", "1");

        iReader = new BufferedReader(new FileReader(apiDataFile));

        // Private data: consumer info + access token info + phone info
        consumer_key = iReader.readLine();
        consumer_secret = iReader.readLine();
        registrationId = iReader.readLine();

        // Set up the oAuthConsumer
        while (true) {
            try {

                logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages..."));

                apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret);

                apiConsumer.setMessageSigner(new HmacSha1MessageSigner());

                moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId
                        + "/messages?version=v1&alt=json");

                request = (HttpURLConnection) moAPIurl.openConnection();
                request.setRequestMethod("GET");

                apiConsumer.sign(request);

                StringBuffer doc = new StringBuffer();
                BufferedReader br = null;

                rc = request.getResponseCode();
                if (rc == HttpURLConnection.HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line = br.readLine();
                    while (line != null) {
                        doc.append(line);
                        line = br.readLine();
                    }

                    System.out.printf("Output message: %s\n", doc.toString());
                    try {
                        JSONObject apiResponse1 = new JSONObject(doc.toString());
                        String aux = apiResponse1.getString("receivedSMS");
                        if (aux != null) {
                            String szMessage;
                            String szOrigin;
                            String szDate;

                            JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS");
                            JSONArray smsInfo = smsPool.optJSONArray("receivedSMS");
                            if (smsInfo != null) {
                                for (i = 0; i < smsInfo.length(); i++) {
                                    szMessage = smsInfo.getJSONObject(i).getString("message");
                                    szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress")
                                            .getString("phoneNumber");
                                    szDate = smsInfo.getJSONObject(i).getString("dateTime");
                                    System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate,
                                            szOrigin, szMessage);
                                }
                            } else {
                                JSONObject sms = smsPool.getJSONObject("receivedSMS");
                                szMessage = sms.getString("message");
                                szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber");
                                szDate = sms.getString("dateTime");
                                System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin,
                                        szMessage);
                            }
                        }
                    } catch (JSONException e) {
                        System.err.println("JSON error: " + e.getMessage());
                    }

                } else if (rc == HttpURLConnection.HTTP_NO_CONTENT)
                    System.out.printf("No content\n");
                else
                    System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage());

                request.disconnect();

            } catch (Exception e) {
                System.err.println("Exception: " + e.getMessage());
            }
            mThread.sleep(15000);
        }
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
}

From source file:org.eclipse.orion.server.tests.prefs.PreferenceTest.java

/**
 * Tests corruption of preference keys containing URLS.
 *//*from w ww  .  j  a va2  s . c o m*/
@Test
public void testBug409792() throws JSONException, IOException {
    String location = toAbsoluteURI("prefs/user/" + getTestUserId() + "/testBug409792");
    //put a value containing a URL in the key
    JSONObject prefs = new JSONObject();
    final String key = "http://127.0.0.2:8080/plugins/samplePlugin.html";
    prefs.put(key, true);
    WebRequest request = new PutMethodWebRequest(location, IOUtilities.toInputStream(prefs.toString()),
            "application/json");
    setAuthentication(request);
    WebResponse response = webConversation.getResource(request);
    assertEquals("1.1", HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());

    //attempt to retrieve the preference
    request = new GetMethodWebRequest(location);
    setAuthentication(request);
    response = webConversation.getResource(request);
    assertEquals("1.2", HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject result = new JSONObject(response.getText());
    assertTrue("1.3", result.optBoolean(key));
}

From source file:org.sonar.server.ws.DefaultLocalResponse.java

@Override
public Response noContent() {
    stream().setStatus(HttpURLConnection.HTTP_NO_CONTENT);
    IOUtils.closeQuietly(output);
    return this;
}

From source file:com.adaptris.http.legacy.HttpResponseService.java

/**
 * *//from   www .  j a v  a 2s  .  c o  m
 *
 * @see com.adaptris.core.Service#doService
 *      (com.adaptris.core.AdaptrisMessage)
 */
@Override
public void doService(AdaptrisMessage msg) throws ServiceException {
    try {
        HttpSession session = (HttpSession) msg.getObjectHeaders().get(CoreConstants.HTTP_SESSION_KEY);

        if (session != null) {
            if (msg.getSize() > 0) {
                InputStream in = msg.getInputStream();
                try {
                    StreamUtil.copyStream(in, session.getResponseMessage().getOutputStream());
                } finally {
                    IOUtils.closeQuietly(in);
                }
                handleMetadata(msg, session);
            } else {
                session.getResponseLine().setResponseCode(HttpURLConnection.HTTP_NO_CONTENT);
                session.getResponseLine().setResponseMessage("No Content");
            }
        } else {
            log.warn("HttpSession not set as metadata");
        }
    } catch (ClassCastException e) {
        log.error("ignoring [" + msg.getObjectHeaders().getClass().getName() + "] metadata");
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:org.eclipse.orion.server.tests.prefs.PreferenceTest.java

@Test
public void testGetSingle() throws IOException, JSONException {
    List<String> locations = getTestPreferenceNodes();
    for (String location : locations) {
        //unknown key should return 404
        WebRequest request = new GetMethodWebRequest(location + "?key=Name");
        setAuthentication(request);/*from  w w  w . java2  s .  c om*/
        WebResponse response = webConversation.getResource(request);
        assertEquals("1." + location, HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());

        //put a value
        request = createSetPreferenceRequest(location, "Name", "Frodo");
        setAuthentication(request);
        response = webConversation.getResource(request);
        assertEquals("2." + location, HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());

        //now doing a get should succeed
        request = new GetMethodWebRequest(location + "?key=Name");
        setAuthentication(request);
        response = webConversation.getResource(request);
        assertEquals("3." + location, HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject result = new JSONObject(response.getText());
        assertEquals("4." + location, "Frodo", result.optString("Name"));

        //getting another key on the same resource should still 404
        request = new GetMethodWebRequest(location + "?key=Address");
        setAuthentication(request);
        response = webConversation.getResource(request);
        assertEquals("5." + location, HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
    }
}

From source file:com.adaptris.http.HttpClientTransport.java

/**
 * Is the HTTP response code considered to be a success.
 * <p>//from  ww  w . j a  v a2s.c  om
 * There are 7 possible HTTP codes that signify success or partial success :-
 * <code>200,201,202,203,204,205,206</code>
 * </p>
 * 
 * @return true if the transaction was successful.
 */
private boolean wasSuccessful(HttpSession session) {

    boolean rc = false;
    switch (session.getResponseLine().getResponseCode()) {
    case HttpURLConnection.HTTP_ACCEPTED:
    case HttpURLConnection.HTTP_CREATED:
    case HttpURLConnection.HTTP_NO_CONTENT:
    case HttpURLConnection.HTTP_NOT_AUTHORITATIVE:
    case HttpURLConnection.HTTP_OK:
    case HttpURLConnection.HTTP_PARTIAL:
    case HttpURLConnection.HTTP_RESET: {
        rc = true;
        break;
    }
    default: {
        rc = false;
        break;
    }
    }
    return rc;
}

From source file:org.sonar.server.qualityprofile.ws.DeactivateRuleActionTest.java

@Test
public void deactivate_rule_in_default_organization() {
    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, defaultOrganization);
    QualityProfileDto qualityProfile = dbTester.qualityProfiles().insert(defaultOrganization);
    RuleKey ruleKey = RuleTesting.randomRuleKey();
    TestRequest request = wsActionTester.newRequest().setMethod("POST").setParam("rule_key", ruleKey.toString())
            .setParam("profile_key", qualityProfile.getKey());

    TestResponse response = request.execute();

    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
    ArgumentCaptor<ActiveRuleKey> captor = ArgumentCaptor.forClass(ActiveRuleKey.class);
    Mockito.verify(ruleActivator).deactivateAndUpdateIndex(any(DbSession.class), captor.capture());
    assertThat(captor.getValue().ruleKey()).isEqualTo(ruleKey);
    assertThat(captor.getValue().qProfile()).isEqualTo(qualityProfile.getKey());
}

From source file:com.nimbits.user.GoogleAuthentication.java

private Cookie getAuthCookie(final String gaeAppBaseUrl, final String gaeAppLoginUrl, final String authToken)
        throws NimbitsException {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    Cookie retObj = null;/*from   w ww .j  av a  2s  .c  o m*/
    final String cookieUrl;
    try {
        cookieUrl = gaeAppLoginUrl + "?continue=" + URLEncoder.encode(gaeAppBaseUrl, Const.CONST_ENCODING)
                + "&auth=" + URLEncoder.encode(authToken, Const.CONST_ENCODING);

        //
        //      String cookieUrl = gaeAppLoginUrl + "?continue="
        //      + URLEncoder.encode(gaeAppBaseUrl,Const.CONST_ENCODING) + "&auth=" + authToken;
        //httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
        final HttpGet httpget = new HttpGet(cookieUrl);
        final HttpResponse response = httpClient.execute(httpget);

        if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
                || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {

            for (final Cookie cookie : httpClient.getCookieStore().getCookies()) {
                if (cookie.getName().equals(Parameters.acsid.getText())) {
                    retObj = cookie;
                    break;
                }

            }
        } else if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            throw new NimbitsException("invalid token");

        } else {
            throw new NimbitsException(
                    "Error getting cookie: status code:" + response.getStatusLine().getStatusCode());
        }

        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    } catch (UnsupportedEncodingException e) {
        throw new NimbitsException(e.getMessage());
    } catch (ClientProtocolException e) {
        throw new NimbitsException(e.getMessage());
    } catch (IOException e) {
        throw new NimbitsException(e.getMessage());
    }

    return retObj;

}

From source file:io.joynr.messaging.bounceproxy.monitoring.BounceProxyShutdownReporter.java

protected void reportEventAsHttpRequest() throws IOException {

    final String url = bounceProxyControllerUrl.buildReportShutdownUrl();
    logger.debug("Using monitoring service URL: {}", url);

    HttpPut putReportShutdown = new HttpPut(url.trim());

    CloseableHttpResponse response = null;
    try {//from  w w w .  ja  v  a2  s.c om
        response = httpclient.execute(putReportShutdown);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode != HttpURLConnection.HTTP_NO_CONTENT) {
            // unexpected response
            logger.error("Failed to send shutdown notification: {}", response);
            throw new JoynrHttpException(statusCode,
                    "Failed to send shutdown notification. Bounce Proxy still registered at Monitoring Service.");
        } else {
            logger.debug("Successfully sent shutdown notification");
        }

    } finally {
        if (response != null) {
            response.close();
        }
    }
}