Example usage for org.apache.commons.httpclient HttpStatus SC_NOT_IMPLEMENTED

List of usage examples for org.apache.commons.httpclient HttpStatus SC_NOT_IMPLEMENTED

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_NOT_IMPLEMENTED.

Prototype

int SC_NOT_IMPLEMENTED

To view the source code for org.apache.commons.httpclient HttpStatus SC_NOT_IMPLEMENTED.

Click Source Link

Document

<tt>501 Not Implemented</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:gov.tva.sparky.hbase.RestProxy.java

public static boolean DeleteHbaseRow(String strTablename, String strRowKey) throws URIException {

    Configuration conf = new Configuration(false);
    conf.addResource("hadoop-default.xml");
    conf.addResource("sparky-site.xml");

    int port = conf.getInt("sparky.hbase.restPort", 8092);
    String uri = conf.get("sparky.hbase.restURI", "http://socdvmhbase");

    boolean bResult = false;

    BufferedReader br = null;/*from  w ww.  j  a  v a 2s .  c  o m*/
    HttpClient client = new HttpClient();

    String strRestPath = uri + ":" + port + "/" + strTablename + "/" + strRowKey;

    DeleteMethod delete_method = new DeleteMethod(strRestPath);

    try {

        int returnCode = client.executeMethod(delete_method);

        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {

            System.out.println("The Post method is not implemented by this URI");

        } else {

            bResult = true;

        }
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        delete_method.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
            }
    }

    return bResult;

}

From source file:gov.tva.sparky.hbase.RestProxy.java

/**
 * This method adds data to HBase./*from  w w  w.j  av a2 s  .  com*/
 * 
 * @param strTablename
 * @param strRowKey
 * @param strColumn
 * @param strQualifier
 * @param arBytesValue
 * @return
 * @throws URIException
 */
public static boolean InsertHbaseIndexBucket(String strTablename, String strRowKey, String strColumn,
        String strQualifier, byte[] arBytesValue) throws URIException {
    // Configuration
    Configuration conf = new Configuration(false);
    conf.addResource("hadoop-default.xml");
    conf.addResource("sparky-site.xml");
    int port = conf.getInt("sparky.hbase.restPort", 8092);
    String uri = conf.get("sparky.hbase.restURI", "http://socdvmhbase");

    boolean bResult = false;

    BufferedReader br = null;
    HttpClient client = new HttpClient();

    String strRestPath = uri + ":" + port + "/" + strTablename + "/" + strRowKey + "/" + strColumn + ":"
            + strQualifier;

    PostMethod post = new PostMethod(strRestPath);
    post.addRequestHeader("Content-Type", "application/octet-stream");

    RequestEntity entity = new ByteArrayRequestEntity(arBytesValue);
    post.setRequestEntity(entity);

    try {
        int returnCode = client.executeMethod(post);

        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.out.println("The Post method is not implemented by this URI");
            // still consume the response body
            post.getResponseBodyAsString();
        } else {
            br = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
            String readLine;
            while (((readLine = br.readLine()) != null)) {
                System.out.println(readLine);
            }

            bResult = true;

        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
        if (br != null) {
            try {
                br.close();
            } catch (Exception fe) {
                fe.printStackTrace();
            }
        }
    }

    return bResult;
}

From source file:gov.tva.sparky.util.indexer.HBaseRestInterface.java

public static void InsertDataIntoHBase(String str_REST_URL, byte[] arPayloadBytes) {

    BufferedReader br = null;/*from ww  w.ja  va2  s .c  o  m*/
    HttpClient client = new HttpClient();

    PostMethod post = new PostMethod(str_REST_URL);

    post.addRequestHeader("Content-Type", "application/octet-stream");
    RequestEntity entity = new ByteArrayRequestEntity(arPayloadBytes);
    post.setRequestEntity(entity);

    try {

        int returnCode = client.executeMethod(post);

        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {

            System.out.println("The Post method is not implemented by this URI");
            // still consume the response body
            post.getResponseBodyAsString();

        } else {

            br = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
            String readLine;

            while (((readLine = br.readLine()) != null)) {
                System.out.println(readLine);
            }

        }

    } catch (Exception e) {

        System.out.println(e);

    } finally {

        post.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
            }

    }

}

From source file:Interface.FramePrincipal.java

private void bt_uplActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_uplActionPerformed

    File diretorio = new File(dir_arq.getText());
    File file = new File(dir_arq.getText() + "/" + nom_arq.getText());

    if (!diretorio.exists()) {
        JOptionPane.showMessageDialog(null, "Informe um diretrio vlido!");
    } else if (!file.exists() || "".equals(nom_arq.getText())) {
        JOptionPane.showMessageDialog(null, "Informe um arquivo vlido!");
    } else {/*  w  w w  .  j  a  v  a  2  s.c o m*/
        try {
            //////////////////////////////////////// Validar tamanho de arquivo/////////////////////////////////////////////////               
            RandomAccessFile arquivo = new RandomAccessFile(dir_arq.getText() + "/" + nom_arq.getText(), "r");
            long tamanho = arquivo.length();

            if (tamanho >= 104857600) {
                JOptionPane.showMessageDialog(null, "Arquivo excedeu o tamanho mximo de 100 MB!");
                arquivo.close();
                return;
            }

            //////////////////////////////////////////// Carrega arquivo para o bucket /////////////////////////////////////////
            HttpClient client = new HttpClient();
            client.getParams().setParameter("http.useragent", "Test Client");

            BufferedReader br = null;
            String apikey = "AIzaSyAuKiAdUluAz4IEaOUoXldA8XuwEbty5V8";

            File input = new File(dir_arq.getText() + "/" + nom_arq.getText());

            PostMethod method = new PostMethod("https://www.googleapis.com/upload/storage/v1/b/" + bac.getNome()
                    + "/o?uploadType=media&name=" + nom_arq.getText());
            method.addParameter("uploadType", "media");
            method.addParameter("name", nom_arq.getText());
            method.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
            //       method.setRequestHeader("Content-type", "image/png; charset=ISO-8859-1");
            method.setRequestHeader("Content-type", "application/octet-stream");

            //       try{
            int returnCode = client.executeMethod(method);

            if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
                System.err.println("The Post method is not implemented by this URI");
                method.getResponseBodyAsString();
            } else {
                br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
                String readLine;
                while (((readLine = br.readLine()) != null)) {
                    System.err.println(readLine);
                }
                br.close();
            }

        } catch (Exception e) {
            System.err.println(e);

        }
        JOptionPane.showMessageDialog(null, "Arquivo carregado com sucesso!");
    }
}

From source file:com.thoughtworks.go.server.service.PipelineHistoryServiceTest.java

@Test
public void shouldFailWhenFeatureIsToggledOff_updateComment() {
    when(featureToggleService.isToggleOn(Toggles.PIPELINE_COMMENT_FEATURE_TOGGLE_KEY)).thenReturn(false);
    Toggles.initializeWith(featureToggleService);
    CaseInsensitiveString unauthorizedUser = new CaseInsensitiveString("cannot-access");
    String pipelineName = "pipeline_name";

    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    pipelineHistoryService.updateComment(pipelineName, 1, "test comment", new Username(unauthorizedUser),
            result);/* ww  w . j a v a 2  s.co m*/

    assertThat(result.httpCode(), is(HttpStatus.SC_NOT_IMPLEMENTED));
    assertThat((Localizable.CurryableLocalizable) result.localizable(),
            is(LocalizedMessage.string("FEATURE_NOT_AVAILABLE", "Pipeline Comment")));
    verify(pipelineDao, never()).updateComment(pipelineName, 1, "test comment");
}

From source file:org.bbaw.pdr.ae.view.identifiers.internal.ConcurrenceSearchController.java

private String requestWebService(URL url) throws URISyntaxException, UnsupportedEncodingException {
    String result = null;//from w  ww.ja v  a 2  s  .  co m
    if (url != null) {
        HttpClient client = new HttpClient();

        // System.out.println("url " + url.toString());
        // PostMethod method = null;
        HttpClient httpclient = null;
        httpclient = new HttpClient();

        String urlString = new String(url.toString());
        if (urlString.contains(" ")) {
            // System.out.println("containts ws");
            urlString.replace(" ", "%20");
        }
        Pattern p = Pattern.compile("\\s");
        Matcher m = p.matcher(urlString);
        // while (m.find())
        // {
        // // System.out.println("\\s");
        // }
        urlString = m.replaceAll("%20");
        // while (m.find())
        // {
        // System.out.println("2.\\s");
        // }
        // urlString = URLEncoder.encode(urlString, "UTF-8");
        // urlString.replace("\\s+", "%20");
        GetMethod get = new GetMethod(urlString);
        HostConfiguration hf = new HostConfiguration();
        hf.setHost(urlString, url.getPort());
        httpclient.setHostConfiguration(hf);
        // get = new PostMethod(theURL);
        // LogHelper.logMessage("Before sending SMS Message: "+message);
        int respCode;
        try {
            respCode = httpclient.executeMethod(get);
            log = new Status(IStatus.INFO, Activator.PLUGIN_ID, "Response code: " + respCode);
            iLogger.log(log);
            // successful.

            /* send request */
            final int status = client.executeMethod(get);
            // LOG.debug("http status #execute: " +
            // Integer.toString(status));
            switch (status) {
            case HttpStatus.SC_NOT_IMPLEMENTED:
                get.releaseConnection();
                // throw new IOException("Solr Query #GET (" +
                // get.getURI().toString() + ") returned 501");
            default:
                result = get.getResponseBodyAsString();
                get.releaseConnection();
            }
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return result;
}

From source file:org.craftercms.cstudio.share.service.impl.WcmWorkflowServiceImpl.java

private String callRESTService(final String targetURI, final String xmlString) throws Exception {
    String xmlResponseString = "";
    int result = -1;

    //TODO: Use Alfresco Endpoint instead of httpclient

    PostMethod postMethod = null;/* w ww  .  jav  a2  s.  c  o m*/
    BufferedReader br = null;
    HttpClient httpClient = new HttpClient();

    // PRECONDITIONS
    assert targetURI != null && targetURI.trim().length() > 0 : "path must not be null, empty or blank.";

    // Body
    postMethod = new PostMethod(targetURI);
    postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    // Get the Alfresco Ticket       
    SeamlessAppContext context = SeamlessAppContext.currentApplicationContext();
    String alfTicketCookie = (String) cookieManager.getCookieValue(context.getRequest(),
            this.COOKIE_ALFRESCO_TICKET);

    // Set the Parameter
    //getMethod.setQueryString(new NameValuePair[] {new NameValuePair("formId", formId)});
    postMethod.setQueryString("?xml=" + xmlString + "&" + COOKIE_ALFRESCO_TICKET + "=" + alfTicketCookie);

    try {
        result = httpClient.executeMethod(postMethod);

        if (result == HttpStatus.SC_NOT_IMPLEMENTED) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("The POST method is not implemented by this URI");
                throw new Exception("The POST method is not implemented by this URI");
            }
            // still consume the response body
            xmlResponseString = postMethod.getResponseBodyAsString();
        } else {
            if (result == HttpStatus.SC_OK) {
                br = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));

                String readLine;
                while (((readLine = br.readLine()) != null)) {
                    xmlResponseString = xmlString + readLine;
                }
            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Push to Alfresco Service Failed: " + HttpStatus.getStatusText(result));
                    throw new Exception("Push to Alfresco Service Failed: " + HttpStatus.getStatusText(result));
                }
            }
        }
    } catch (HttpException he) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Push to Alfresco Service Failed due to HttpException: " + he.getMessage(), he);
            throw he;
        }
    } catch (IOException ie) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Push to Alfresco Service Failed due to IOException: " + ie.getMessage(), ie);
        }
    } finally {
        postMethod.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
            }
    }

    return (xmlResponseString);
}

From source file:org.eclipse.lyo.samples.sharepoint.SharepointConnector.java

public int createDocument(HttpServletResponse response, String library, FileItem item)
        throws UnrecognizedValueTypeException, ShareServerException {
    //   System.out.println("createDocument: uri='" + uri + "'");
    //SharepointResource sharepointResource = new SharepointResource(uri);

    //       String filename = resource.getSource();
    //       //  w  w  w.j  av  a 2s  .co m
    //      OEntity newProduct = odatac.createEntity("Empire").properties(OProperties.int32("Id", 10))
    //                                                       .properties(OProperties.string("Name", filename))
    //                                                       .properties(OProperties.string("ContentType","Document"))
    //                                                       .properties(OProperties.string("Title","Architecture"))
    //                                                       .properties(OProperties.string("ApprovalStatus","2"))
    //                                                       .properties(OProperties.string("Path","/Empire"))   
    //                                                         .execute();  

    // no obvious API in odata4j to create a document, default apache http Create
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");

    BufferedReader br = null;
    int returnCode = 500;
    PostMethod method = null;
    try {
        client.setConnectionTimeout(8000);

        method = new PostMethod(SharepointInitializer.getSharepointUri() + "/" + library);
        String userPassword = SharepointInitializer.getUsername() + ":" + SharepointInitializer.getPassword();
        String encoding = Base64.encodeBase64String(userPassword.getBytes());
        encoding = encoding.replaceAll("\r\n?", "");
        method.setRequestHeader("Authorization", "Basic " + encoding);
        method.addRequestHeader("Content-type", item.getContentType());
        method.addRequestHeader(IConstants.HDR_SLUG, "/" + library + "/" + item.getName());

        //InputStream is =  new FileInputStream("E:\\odata\\sharepoint\\DeathStarTest.doc");

        RequestEntity entity = new InputStreamRequestEntity(item.getInputStream(), "application/msword");
        method.setRequestEntity(entity);
        method.setDoAuthentication(true);

        returnCode = client.executeMethod(method);

        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.err.println("The Post method is not implemented by this URI");
            // still consume the response body
            method.getResponseBodyAsString();
        } else {
            //br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            InputStream is = method.getResponseBodyAsStream();
            //br = new BufferedReader(new InputStreamReader(is));          
            //    String readLine;
            //    while(((readLine = br.readLine()) != null)) {
            //      System.out.println(readLine);
            //    }

            response.setContentType("text/html");
            //response.setContentType("application/atom+xml");
            //response.setContentLength(is.getBytes().length);
            response.setStatus(IConstants.SC_OK);
            //response.getWriter().write("<html><head><title>hello world</title></head><body><p>hello world!</p></body></html>");
            //response.getWriter().write(method.getResponseBodyAsString());

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder parser = factory.newDocumentBuilder();
            Document doc = parser.parse(is);
            Element root = doc.getDocumentElement();

            System.out.println("Root element of the doc is " + root.getNodeName());

            //         String msftdPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            //         String msftmPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

            String id = null;
            String name = null;
            NodeList nl = root.getElementsByTagName("d:Id");
            if (nl.getLength() > 0) {
                id = nl.item(0).getFirstChild().getNodeValue();
            }

            //nl = root.getElementsByTagName("d:ContentType");         
            //if (nl.getLength() > 0) {
            //   type = nl.item(0).getFirstChild().getNodeValue(); 
            //}

            nl = root.getElementsByTagName("d:Name");
            if (nl.getLength() > 0) {
                name = nl.item(0).getFirstChild().getNodeValue();
            }

            response.getWriter().write("<html>");
            response.getWriter().write("<head>");
            response.getWriter().write("</head>");
            response.getWriter().write("<body>");
            response.getWriter().write("<p>" + name + " was created with an Id =" + id + "</p>");
            response.getWriter().write("</body>");
            response.getWriter().write("</html>");

            //response.getWriter().write(is.content);
            //String readLine;
            //while(((readLine = br.readLine()) != null)) {
            //   response.getWriter().write(readLine);
            //}
            //response.setContentType(IConstants.CT_XML);
            //response.getWriter().write(is.toString()); 
            //response.setStatus(IConstants.SC_OK);
            //test 
            //   String readLine;
            //   while(((readLine = br.readLine()) != null)) {
            //     System.out.println(readLine);
            //   }
        }
    } catch (Exception e) {
        System.err.println(e);
        e.printStackTrace();
    } finally {
        if (method != null)
            method.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
            }
    }
    return returnCode;
}

From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java

private int computeStatus(int status) {
    switch (status) {
    case HttpStatus.SC_FORBIDDEN:
    case HttpStatus.SC_METHOD_NOT_ALLOWED:
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_NOT_FOUND:
    case HttpStatus.SC_NOT_ACCEPTABLE:
    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
    case HttpStatus.SC_REQUEST_TIMEOUT:
    case HttpStatus.SC_CONFLICT:
    case HttpStatus.SC_GONE:
    case HttpStatus.SC_LENGTH_REQUIRED:
    case HttpStatus.SC_PRECONDITION_FAILED:
    case HttpStatus.SC_REQUEST_TOO_LONG:
    case HttpStatus.SC_REQUEST_URI_TOO_LONG:
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
    case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
    case HttpStatus.SC_EXPECTATION_FAILED:
    case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
    case HttpStatus.SC_METHOD_FAILURE:
    case HttpStatus.SC_UNPROCESSABLE_ENTITY:
    case HttpStatus.SC_LOCKED:
    case HttpStatus.SC_FAILED_DEPENDENCY:
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
    case HttpStatus.SC_NOT_IMPLEMENTED:
    case HttpStatus.SC_BAD_GATEWAY:
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
    case HttpStatus.SC_GATEWAY_TIMEOUT:
    case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
    case HttpStatus.SC_INSUFFICIENT_STORAGE:
        return 0;
    case HttpStatus.SC_CONTINUE:
    case HttpStatus.SC_SWITCHING_PROTOCOLS:
    case HttpStatus.SC_PROCESSING:
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
    case HttpStatus.SC_NO_CONTENT:
    case HttpStatus.SC_RESET_CONTENT:
    case HttpStatus.SC_PARTIAL_CONTENT:
    case HttpStatus.SC_MULTI_STATUS:
    case HttpStatus.SC_MULTIPLE_CHOICES:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_NOT_MODIFIED:
    case HttpStatus.SC_USE_PROXY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        return 1;
    default://www .  j ava  2  s.c om
        return 1;
    }
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

@Path("/bulb/{state}")
@POST/*from w  ww.java 2s .  c o  m*/
public void switchBulb(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
        @HeaderParam("protocol") String protocol, @PathParam("state") String state,
        @Context HttpServletResponse response) {

    try {
        DeviceValidator deviceValidator = new DeviceValidator();
        if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, FireAlarmConstants.DEVICE_TYPE))) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
    } catch (DeviceManagementException e) {
        log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    String switchToState = state.toUpperCase();

    if (!switchToState.equals(FireAlarmConstants.STATE_ON)
            && !switchToState.equals(FireAlarmConstants.STATE_OFF)) {
        log.error("The requested state change shoud be either - 'ON' or 'OFF'");
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    String deviceIP = deviceToIpMap.get(deviceId);
    if (deviceIP == null) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
        return;
    }

    String protocolString = protocol.toUpperCase();
    String callUrlPattern = BULB_CONTEXT + switchToState;

    log.info("Sending command: '" + callUrlPattern + "' to firealarm at: " + deviceIP + " " + "via" + " "
            + protocol);

    try {
        switch (protocolString) {
        case HTTP_PROTOCOL:
            sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
            break;
        case MQTT_PROTOCOL:
            callUrlPattern = BULB_CONTEXT.replace("/", "");
            sendCommandViaMQTT(owner, deviceId, callUrlPattern, switchToState);
            break;
        default:
            if (protocolString == null) {
                sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
            } else {
                response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
                return;
            }
            break;
        }
    } catch (DeviceManagementException e) {
        log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" + " " + protocol);
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    response.setStatus(HttpStatus.SC_OK);
}