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

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

Introduction

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

Prototype

int SC_OK

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

Click Source Link

Document

<tt>200 OK</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:mercury.UploadController.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        try {//from  w w  w  .  j av a 2  s .  co m
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String targetUrl = Config.getConfigProperty(ConfigurationEnum.DIGITAL_MEDIA);
                    if (StringUtils.isBlank(targetUrl)) {
                        targetUrl = request.getRequestURL().toString();
                        targetUrl = targetUrl.substring(0, targetUrl.lastIndexOf('/'));
                    }
                    targetUrl += "/DigitalMediaController";
                    PostMethod filePost = new PostMethod(targetUrl);
                    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
                    UploadPartSource src = new UploadPartSource(item.getName(), item.getSize(),
                            item.getInputStream());
                    Part[] parts = new Part[1];
                    parts[0] = new FilePart(item.getName(), src, item.getContentType(), null);
                    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                    HttpClient client = new HttpClient();
                    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                    int status = client.executeMethod(filePost);
                    if (status == HttpStatus.SC_OK) {
                        String data = filePost.getResponseBodyAsString();
                        JSONObject json = new JSONObject(data);
                        if (json.has("id")) {
                            JSONObject responseJson = new JSONObject();
                            responseJson.put("success", true);
                            responseJson.put("id", json.getString("id"));
                            responseJson.put("uri", targetUrl + "?id=" + json.getString("id"));
                            response.getWriter().write(responseJson.toString());
                        }
                    }
                    filePost.releaseConnection();
                    return;
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (JSONException je) {
            je.printStackTrace();
        }
    }
    response.getWriter().write("{success: false}");
}

From source file:com.hp.mercury.ci.jenkins.plugins.oo.core.OOAccessibilityLayer.java

public static OOListResponse listFlows(OOServer s, String... folders) throws IOException {

    String foldersPath = "";

    for (String folder : folders) {
        foldersPath += folder + "/";
    }/*w ww  .  java 2  s.  co  m*/

    String url = StringUtils.slashify(s.getUrl()) + REST_SERVICES_URL_PATH + LIST_OPERATION_URL_PATH
            + foldersPath;

    final HttpResponse response = OOBuildStep.getHttpClient().execute(new HttpGet(OOBuildStep.URI(url)));

    final int statusCode = response.getStatusLine().getStatusCode();

    final HttpEntity entity = response.getEntity();

    try {

        if (statusCode == HttpStatus.SC_OK) {

            return JAXB.unmarshal(entity.getContent(), OOListResponse.class);
        } else {

            throw new RuntimeException("unable to get list of flows from " + url + ", response code: "
                    + statusCode + "(" + HttpStatus.getStatusText(statusCode) + ")");
        }
    } finally {
        EntityUtils.consume(entity);
    }
}

From source file:com.kagilum.intellij.icescrum.IceScrumRepository.java

@Override
public CancellableConnection createCancellableConnection() {
    extractSettings(getUrl());//from  w w w.  j  ava 2 s  . c  om
    GetMethod method = new GetMethod(createCompleteUrl());
    return new HttpTestConnection<GetMethod>(method) {
        @Override
        public void doTest(GetMethod method) throws Exception {
            if (!isConfigured()) {
                throw new IOException("Setting missing...");
            }
            method.setRequestHeader("Content-type", "text/json");
            HttpClient client = getHttpClient();
            client.executeMethod(method);
            int statusCode = method.getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                checkServerStatus(statusCode);
            }
            Task[] results = getIssues(null, 1, 0);
            if (results.length < 1)
                throw new IOException("No results fetched, sure this is correct settings?");
        }
    };
}

From source file:net.sf.sail.webapp.dao.sds.impl.SdsWorkgroupGetCommandHttpRestImpl.java

/**
 * @see net.sf.sail.webapp.dao.sds.SdsCommand#generateRequest()
 *//*  w  w  w  .ja v  a  2  s .co  m*/
public HttpGetRequest generateRequest() {
    final SdsWorkgroup sdsWorkgroup = this.getSdsWorkgroup();
    final String url = "/workgroup/" + sdsWorkgroup.getSdsObjectId();
    return new HttpGetRequest(REQUEST_HEADERS_ACCEPT, EMPTY_STRING_MAP, url, HttpStatus.SC_OK);
}

From source file:de.extra.client.plugins.outputplugin.transport.ExtraTransportHttp.java

/**
 * ExtrasTransportHttp is an implementation of IExtraTransport and provides
 * Communication via http(s) protocol./*from  ww  w. j  a  v a2  s  .  c  o m*/
 * 
 * @see de.extra.client.transport.IExtraTransport#senden(java.lang.String)
 */
@Override
public InputStream senden(final InputStream extraRequest) throws ExtraTransportException {

    if (client != null) {

        // Init response
        InputStream extraResponse = null;

        // Build url String and create post request
        PostMethod method = new PostMethod(requestURL);

        try {

            RequestEntity entity = new InputStreamRequestEntity(extraRequest);
            method.setRequestEntity(entity);

            // Execute the method - send it
            int statusCode = client.executeMethod(method);

            // Something goes wrong
            if (statusCode != HttpStatus.SC_OK) {
                throw new ExtraTransportException(
                        "Versand von Request fehlgeschlagen: " + method.getStatusLine());
            } else {

                // Read the response body and save it

                extraResponse = method.getResponseBodyAsStream();
            }

        } catch (HttpException e) {
            throw new ExtraTransportException("Schwere Protokollverletzung: " + e.getMessage(), e);
        } catch (IOException e) {
            throw new ExtraTransportException("Schwerer Transportfehler: " + e.getMessage(), e);
        } finally {

            // Release the connection.
            method.releaseConnection();
        }
        return extraResponse;
    } else {
        throw new ExtraTransportException("Http Client nicht initialisiert!");
    }
}

From source file:net.sf.xmm.moviemanager.http.HttpUtil.java

public boolean setUpIMDbAuthentication() {

    if (httpSettings == null) {
        log.warn("Authentication could not be set. Missing authentication settings.");
        return false;
    }// ww w  .j a  v  a2s .c  om

    if (httpSettings.getIMDbAuthenticationEnabled()) {

        try {

            if (!isSetup())
                setup();

            client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

            PostMethod postMethod = new PostMethod(("https://secure.imdb.com/register-imdb/login"));

            NameValuePair[] postData = new NameValuePair[2];
            postData[0] = new NameValuePair("login", httpSettings.getIMDbAuthenticationUser());
            postData[1] = new NameValuePair("password", httpSettings.getIMDbAuthenticationPassword());

            postMethod.setRequestBody(postData);

            int statusCode = client.executeMethod(postMethod);

            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                imdbAuthenticationSetUp = true;
            else
                imdbAuthenticationSetUp = false;

        } catch (Exception e) {
            log.warn("error:" + e.getMessage());
        }
    } else
        imdbAuthenticationSetUp = false;

    return imdbAuthenticationSetUp;
}

From source file:com.myGengo.alfresco.webscripts.NodeContentGet.java

public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    ContentReader textReader = null;/*from  w ww . j av a2 s  .  c om*/
    Exception transformException = null;

    String nodeRef = req.getParameter("nodeRef");
    if (nodeRef == null) {
        throw new WebScriptException("nodeRef parameter is required for GetNodeContent");
    }

    ContentReader reader = contentService.getReader(new NodeRef(nodeRef), ContentModel.PROP_CONTENT);
    if (reader == null) {
        res.setStatus(HttpStatus.SC_NO_CONTENT);
        return;
    }

    // Perform transformation catering for mimetype AND encoding
    ContentWriter writer = contentService.getTempWriter();
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8"); // Expect transformers to produce UTF-8

    ContentTransformer transformer = contentService.getTransformer(reader.getMimetype(),
            MimetypeMap.MIMETYPE_TEXT_PLAIN);
    if (transformer == null) {
        res.setStatus(HttpStatus.SC_NO_CONTENT);
        return;
    }

    try {
        transformer.transform(reader, writer);
    } catch (ContentIOException e) {
        transformException = e;
    }

    if (transformException == null) {
        // point the reader to the new-written content
        textReader = writer.getReader();
        // Check that the reader is a view onto something concrete
        if (textReader == null || !textReader.exists()) {
            transformException = new ContentIOException("The transformation did not write any content, yet: \n"
                    + "   transformer:     " + transformer + "\n" + "   temp writer:     " + writer);
        }
    }

    if (transformException != null) {
        res.setStatus(HttpStatus.SC_NO_CONTENT);
    } else {
        res.setStatus(HttpStatus.SC_OK);
        Date modified = new Date();
        streamContentImpl(req, res, textReader, false, modified, String.valueOf(modified.getTime()), null);
    }
}

From source file:com.sdm.core.resource.RestResource.java

@Override
public IBaseResponse postQuery(String queryName, Map<String, Object> params) {
    DefaultResponse response = this.validateCache();
    // Cache validation
    if (response != null) {
        return response;
    }/*  w ww  .  ja  v  a2  s  . co m*/

    String entityName = getEntityClass().getName();
    Entity entityAnno = getEntityClass().getAnnotation(Entity.class);
    if (entityAnno != null) {
        entityName = entityAnno.name();
    }

    queryName = entityName + "." + queryName.toUpperCase();

    List<HashMap<String, Object>> data = (List<HashMap<String, Object>>) getDAO().fetchByNamedQuery(queryName,
            params);
    ListModel content = new ListModel<>(data);
    response = new DefaultResponse<>(HttpStatus.SC_OK, ResponseType.SUCCESS, content);

    response.setHeaders(this.buildCache());
    return response;
}

From source file:com.datatorrent.demos.yahoofinance.YahooFinanceCSVInputOperator.java

@Override
public void run() {
    while (true) {
        try {//from  ww  w.  j a v a2s.c o  m
            int statusCode = client.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + method.getStatusLine());
            } else {
                InputStream istream;
                istream = method.getResponseBodyAsStream();
                // Process response
                InputStreamReader isr = new InputStreamReader(istream);
                CSVReader reader = new CSVReader(isr);
                List<String[]> myEntries;
                myEntries = reader.readAll();
                for (String[] stringArr : myEntries) {
                    HashMap<String, Object> hm = new HashMap<String, Object>();
                    for (int i = 0; i < parameterList.size(); i++) {
                        hm.put(parameterList.get(i), stringArr[i]);
                    }
                    outputPort.emit(hm); // send out one symbol at a time
                }
            }
            Thread.sleep(readIntervalMillis);
        } catch (InterruptedException ex) {
            logger.debug(ex.toString());
        } catch (IOException ex) {
            logger.debug(ex.toString());
        }
    }
}

From source file:edu.umd.cs.buildServer.util.ServletAppender.java

@Override
protected void append(LoggingEvent event) {
    if (!APPEND_TO_SUBMIT_SERVER)
        return;//w  w  w .ja  v  a  2s  .c o  m
    try {
        Throwable throwable = null;
        if (event.getThrowableInformation() != null) {
            String[] throwableStringRep = event.getThrowableStrRep();
            StringBuffer stackTrace = new StringBuffer();
            for (String stackTraceString : throwableStringRep) {
                stackTrace.append(stackTraceString);
            }
            throwable = new Throwable(stackTrace.toString());
        }

        LoggingEvent newLoggingEvent = new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(),
                event.getLevel(), getConfig().getHostname() + ": " + event.getMessage(), throwable);

        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);

        String logURL = config.getServletURL(SUBMIT_SERVER_HANDLEBUILDSERVERLOGMESSAGE_PATH);

        MultipartPostMethod post = new MultipartPostMethod(logURL);
        // add password

        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(sink);

        out.writeObject(newLoggingEvent);
        out.flush();
        // add serialized logging event object
        post.addPart(new FilePart("event", new ByteArrayPartSource("event.out", sink.toByteArray())));

        int status = client.executeMethod(post);
        if (status != HttpStatus.SC_OK) {
            throw new IOException("Couldn't contact server: " + status);
        }
    } catch (IOException e) {
        // TODO any way to log these without an infinite loop?
        System.err.println(e.getMessage());
        e.printStackTrace(System.err);
    }
}