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

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

Introduction

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

Prototype

int SC_MOVED_TEMPORARILY

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

Click Source Link

Document

<tt>302 Moved Temporarily</tt> (Sometimes <tt>Found</tt>) (HTTP/1.0 - RFC 1945)

Usage

From source file:com.jaspersoft.jasperserver.war.common.HeartbeatBean.java

private synchronized void httpCall(String url, HeartbeatContributor contributor) {
    if (log.isDebugEnabled())
        log.debug("Heartbeat calling: " + url);

    HttpClient httpClient = new HttpClient();

    PostMethod post = new PostMethod(url);

    try {/*w ww. j  a va  2s  . c om*/
        if (heartbeatId != null) {
            post.addParameter("id", heartbeatId);
        }

        if (contributor != null) {
            contributor.contributeToHttpCall(post);
        }

        int statusCode = httpClient.executeMethod(post);
        if (statusCode == HttpStatus.SC_OK) {
            if (heartbeatId == null) {
                heartbeatId = post.getResponseBodyAsString();
                heartbeatId = heartbeatId == null ? null : heartbeatId.trim();

                localIdProperties.setProperty(PROPERTY_HEARTBEAT_ID, heartbeatId);

                saveLocalIdProperties();
            }
        } else if (
        //supported types of redirect
        statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header header = post.getResponseHeader("location");
            if (header != null) {
                if (log.isDebugEnabled())
                    log.debug("Heartbeat listener redirected.");

                httpCall(header.getValue(), contributor);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Heartbeat listener redirected to unknown destination.");
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Connecting to heartbeat listener URL failed. Status code: " + statusCode);
        }
    } catch (IOException e) {
        if (log.isDebugEnabled())
            log.debug("Connecting to heartbeat listener URL failed.", e);
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();

        clearCache();
    }
}

From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java

/**
 * Look for a session and if it's completed or not found try 
 *                            re-validate existing security token
 *//* w  ww  . ja va 2s  . co m*/
@Override
public void validate(HttpServletRequest req, String stoken) throws WsSrvException {
    Session session = activeSessions.get(stoken);

    if (!(session == null || session.isFinished()))
        // Everything fine
        return;

    getLogger(req).debug("Local session validation faied." + " Sending POST request to validate SAML session");

    // Revalidate session
    PostMethod post = new PostMethod(_login);

    try {
        String ars = createAuthnRequest(getServiceLocation(req), getRefererUrl(req));
        post.setParameter("SAMLRequest", ars);
    } catch (MarshallingException | SignatureException | IOException e) {
        //-- 63
        throw new WsSrvException(63, e);
    }

    HttpClient hc = (new HttpClientBuilder()).buildClient();
    post.setRequestHeader("Cookie",
            (String) req.getSession().getServletContext().getAttribute("scookie_name") + "=" + stoken);

    int result;
    try {
        result = hc.executeMethod(post);
    } catch (IOException e) {
        //-- 66
        throw new WsSrvException(66, e);
    }

    // Expecting 200 if cookie valid and 302 if not, rest are errors
    if (result == HttpStatus.SC_OK) {
        // Extract end process SAML response from form
        String rb;
        try {
            rb = new String(post.getResponseBody());
        } catch (IOException e) {
            //-- 67
            throw new WsSrvException(67, e);
        }

        Matcher m = SAML_RESP.matcher(rb);

        if (m.matches() && m.groupCount() == 1) {
            String gs = m.group(1);

            // Convert hex decoded javascript variable
            String msg = "";
            int start = 0;
            Matcher m1 = HP.matcher(gs);

            while (m1.find()) {
                String dc = m1.group(1);
                int i = Integer.decode("#" + dc);

                int st = m1.start();
                int ed = m1.end();

                msg += gs.substring(start, st) + (char) i;
                start = ed;
            }

            try {
                procAuthnResponse(req, msg, stoken);
            } catch (Exception e) {
                //-- 62
                throw new WsSrvException(62, e);
            }
        }
    } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
        //-- 64
        throw new WsSrvException(64, "Redirect received");
    } else {
        //-- 65
        throw new WsSrvException(65, "Unexpected http return code " + result);
    }
}

From source file:com.twinsoft.convertigo.eclipse.editors.connector.HtmlConnectorDesignComposite.java

public void modelChanged(HttpProxyEvent event) {
    if (!checkProxySource(event)) {
        return;//from w w w . jav a 2  s.  c o  m
    }

    String requestString = event.getRequest();
    String responseString = event.getResponse();
    boolean https = event.isHttps();
    int status = Integer.parseInt(event.getStatus());

    // do not record client redirection
    if ((status == HttpStatus.SC_MOVED_TEMPORARILY) || (status == HttpStatus.SC_MOVED_PERMANENTLY)
            || (status == HttpStatus.SC_SEE_OTHER) || (status == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        return;
    }

    /*if (requestString.indexOf(getServer()) == -1) {
       return;
    }*/

    Map<String, String> headers = parseResponseString(responseString);
    String contentType = headers.get(HeaderName.ContentType.value().toLowerCase());

    // record only text/html or null Content-Type ...
    if (contentType == null) {
        return;
    }

    if (MimeType.Html.is(contentType) && MimeType.Plain.is(contentType)) {
        return;
    }

    ConvertigoPlugin.logDebug2("(HtmlConnectorDesignComposite) Learning statement...");

    try {
        String url, method, handlerName, transactionName, statementName, scHandlerName;
        String normalizedScreenClassName, screenClassName;
        HtmlTransaction htmlTransaction = null;
        HTTPStatement httpStatement = null;
        HtmlScreenClass htmlScreenClass = null;
        HandlerStatement handlerStatement = null;
        ScHandlerStatement scHandlerStatement = null;
        //Document dom = null;
        //Log log = null;
        int size, index1;
        boolean bContinue;

        index1 = 0;
        bContinue = true;
        normalizedScreenClassName = "Unknown";

        htmlTransaction = (HtmlTransaction) htmlConnector.getLearningTransaction();

        synchronized (htmlConnector) {
            //dom = htmlConnector.getCurrentXmlDocument();
            htmlScreenClass = htmlConnector.getCurrentScreenClass();
        }

        screenClassName = htmlScreenClass.getName();
        normalizedScreenClassName = StringUtils.normalize(htmlScreenClass.getName());
        ConvertigoPlugin
                .logDebug2("(HtmlConnectorDesignComposite) current screen class is '" + screenClassName + "'");

        if (htmlTransaction != null) {
            transactionName = htmlTransaction.getName();

            ConvertigoPlugin.logDebug2("(HtmlConnectorDesignComposite) creating new HTTPStatement");
            ConvertigoPlugin.logDebug2(requestString);

            httpStatement = parseRequestString(requestString);
            httpStatement.setHttps(https);
            httpStatement.setPort(https ? 443 : 80);
            method = httpStatement.getMethod().toLowerCase();
            //size = httpStatement.getVariablesDefinitionSize();
            size = httpStatement.numberOfVariables();
            url = httpStatement.getUrl(htmlConnector.isHttps(), htmlConnector.getServer(),
                    htmlConnector.getPort());

            while (bContinue) {
                statementName = method + ((index1 == 0) ? " " : " " + index1) + " (" + url + " - " + size + ")";
                statementName = StringUtils.normalize(statementName);
                httpStatement.setName(statementName);
                httpStatement.hasChanged = true;
                httpStatement.bNew = true;

                if (htmlScreenClass == null) {
                    try {
                        httpStatement.priority = 0;
                        htmlTransaction.addStatement(httpStatement);
                        ConvertigoPlugin.logDebug2(
                                "(HtmlConnectorDesignComposite) added new HTTPStatement to default transaction '"
                                        + transactionName + "'");
                        fireObjectChanged(new CompositeEvent(htmlTransaction));
                        Engine.theApp.fireObjectDetected(new EngineEvent(httpStatement));

                        bContinue = false;
                    } catch (ObjectWithSameNameException owsne) {
                        index1++;
                    }
                } else {
                    if (htmlConnector.isAccumulating())
                        handlerName = "on" + normalizedScreenClassName + "Exit";
                    else
                        handlerName = "on" + normalizedScreenClassName + "Entry";

                    handlerStatement = htmlTransaction.getHandlerStatement(handlerName);
                    if (handlerStatement != null) {
                        try {
                            handlerStatement.addStatement(httpStatement);
                            ConvertigoPlugin.logDebug2(
                                    "(HtmlConnectorDesignComposite) added new HTTPStatement to handler '"
                                            + handlerName + "' of transaction '" + transactionName + "'");
                            fireObjectChanged(new CompositeEvent(handlerStatement));
                            Engine.theApp.fireObjectDetected(new EngineEvent(httpStatement));

                            bContinue = false;
                        } catch (ObjectWithSameNameException owsne) {
                            index1++;
                        }
                    } else {
                        try {
                            if (htmlConnector.isAccumulating())
                                scHandlerStatement = new ScExitHandlerStatement(normalizedScreenClassName);
                            else
                                scHandlerStatement = new ScEntryHandlerStatement(normalizedScreenClassName);
                            scHandlerName = scHandlerStatement.getName();
                            scHandlerStatement.setName(scHandlerName);
                            scHandlerStatement.hasChanged = true;
                            scHandlerStatement.bNew = true;

                            scHandlerStatement.priority = 0;
                            htmlTransaction.addStatement(scHandlerStatement);
                            ConvertigoPlugin.logDebug2(
                                    "(HtmlConnectorDesignComposite) added new ScExitHandlerStatement '"
                                            + handlerName + "' of transaction '" + transactionName + "'");

                            try {
                                scHandlerStatement.addStatement(httpStatement);
                                ConvertigoPlugin
                                        .logDebug2("(HtmlConnectorDesignComposite) added new HTTPStatement '"
                                                + statementName + "' to ScExitHandlerStatement '" + handlerName
                                                + "'");
                                fireObjectChanged(new CompositeEvent(htmlTransaction));
                                Engine.theApp.fireObjectDetected(new EngineEvent(httpStatement));

                                bContinue = false;
                            } catch (ObjectWithSameNameException owsne) {
                                index1++;
                            }
                        }
                        // Should not append
                        catch (ObjectWithSameNameException owsne) {
                            throw new EngineException(owsne.getMessage());
                        }
                    }
                }
            }
        } else {
            throw new EngineException("Found none learning transaction");
        }

    } catch (EngineException e) {
        ConvertigoPlugin.logException(e, "An exception occured while learning");
    }

}

From source file:com.zimbra.qa.unittest.TestCalDav.java

/**
 *  dav - sending http error 302 because: wrong url - redirecting to:
 *  http://pan.local:7070/dav/dav1@pan.local/Calendar/d123f102-42a7-4283-b025-3376dabe53b3.ics
 *  com.zimbra.cs.dav.DavException: wrong url - redirecting to:
 *  http://pan.local:7070/dav/dav1@pan.local/Calendar/d123f102-42a7-4283-b025-3376dabe53b3.ics
 *      at com.zimbra.cs.dav.resource.CalendarCollection.createItem(CalendarCollection.java:431)
 *      at com.zimbra.cs.dav.service.method.Put.handle(Put.java:49)
 *      at com.zimbra.cs.dav.service.DavServlet.service(DavServlet.java:322)
 *///from www  . j  a  va 2s  . c  om
@Test
public void testCreateUsingClientChosenName() throws ServiceException, IOException {
    Account dav1 = users[1].create();
    String davBaseName = "clientInvented.now";
    String calFolderUrl = getFolderUrl(dav1, "Calendar");
    String url = String.format("%s%s", calFolderUrl, davBaseName);
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(url);
    addBasicAuthHeaderForUser(putMethod, dav1);
    putMethod.addRequestHeader("Content-Type", "text/calendar");

    putMethod.setRequestEntity(new ByteArrayRequestEntity(simpleEvent(dav1), MimeConstants.CT_TEXT_CALENDAR));
    if (DebugConfig.enableDAVclientCanChooseResourceBaseName) {
        HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_CREATED);
    } else {
        HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_MOVED_TEMPORARILY);
        // Not testing much in this mode but...
        return;
    }

    doGetMethod(url, dav1, HttpStatus.SC_OK);

    PropFindMethod propFindMethod = new PropFindMethod(getFolderUrl(dav1, "Calendar"));
    addBasicAuthHeaderForUser(propFindMethod, dav1);
    TestCalDav.HttpMethodExecutor executor;
    String respBody;
    Element respElem;
    propFindMethod.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    propFindMethod.addRequestHeader("Depth", "1");
    propFindMethod.setRequestEntity(
            new ByteArrayRequestEntity(propFindEtagResType.getBytes(), MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, propFindMethod, HttpStatus.SC_MULTI_STATUS);
    respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    respElem = Element.XMLElement.parseXML(respBody);
    assertEquals("name of top element in propfind response", DavElements.P_MULTISTATUS, respElem.getName());
    assertTrue("propfind response should have child elements", respElem.hasChildren());
    Iterator<Element> iter = respElem.elementIterator();
    boolean hasCalendarHref = false;
    boolean hasCalItemHref = false;
    while (iter.hasNext()) {
        Element child = iter.next();
        if (DavElements.P_RESPONSE.equals(child.getName())) {
            Iterator<Element> hrefIter = child.elementIterator(DavElements.P_HREF);
            while (hrefIter.hasNext()) {
                Element href = hrefIter.next();
                calFolderUrl.endsWith(href.getText());
                hasCalendarHref = hasCalendarHref || calFolderUrl.endsWith(href.getText());
                hasCalItemHref = hasCalItemHref || url.endsWith(href.getText());
            }
        }
    }
    assertTrue("propfind response contained entry for calendar", hasCalendarHref);
    assertTrue("propfind response contained entry for calendar entry ", hasCalItemHref);
    doDeleteMethod(url, dav1, HttpStatus.SC_NO_CONTENT);
}

From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java

private byte[] executeMethod(HttpMethod method, final Context context)
        throws IOException, URIException, MalformedURLException, EngineException {
    Header[] requestHeaders, responseHeaders = null;
    byte[] result = null;
    String contents = null;/*from  w w w . ja  v  a  2  s  .co m*/
    int statuscode = -1;

    if (!context.requestedObject.runningThread.bContinue)
        return null;

    Engine.logBeans
            .debug("(HttpConnector) Executing method - " + method.getName() + "(" + method.getPath() + ")");

    try {
        requestHeaders = method.getRequestHeaders();
        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans
                    .trace("(HttpConnector) Request headers :\n" + Arrays.asList(requestHeaders).toString());

        statuscode = doExecuteMethod(method, context);

        Engine.logBeans.debug("(HttpConnector) Status: " + method.getStatusLine().toString());

        responseHeaders = method.getResponseHeaders();
        context.setResponseHeaders(responseHeaders);
        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans
                    .trace("(HttpConnector) Response headers:\n" + Arrays.asList(responseHeaders).toString());

        if (statuscode != -1) {
            InputStream in = method.getResponseBodyAsStream();
            if (in != null) {

                /**
                 * Retrieve response charset if available in responseHeaders
                 */
                charset = null;
                boolean checkGZip = false; // add GZip support #320

                for (int i = 0; i < responseHeaders.length && (charset == null || !checkGZip); i++) {
                    Header head = responseHeaders[i];
                    if (HeaderName.ContentType.is(head)) {
                        context.contentType = head.getValue();
                        HeaderElement[] els = head.getElements();
                        for (int j = 0; j < els.length && charset == null; j++) {
                            NameValuePair nvp = els[j].getParameterByName("charset");
                            if (nvp != null)
                                charset = nvp.getValue();
                        }
                    } else if (HeaderName.ContentEncoding.is(head)) {
                        checkGZip = true;
                        HeaderElement[] els = head.getElements();
                        for (int j = 0; j < els.length; j++)
                            if ("gzip".equals(els[j].getName())) {
                                Engine.logBeans.debug("(HttpConnector) Decode GZip stream");
                                in = new GZIPInputStream(in);
                            }
                    }
                }

                if (context.contentType != null && context.contentType.startsWith("multipart/")
                        && context.requestedObject instanceof AbstractHttpTransaction) {
                    Engine.logBeans.debug("(HttpConnector) Decoding multipart contentType");

                    try {
                        AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject;

                        BigMimeMultipart mp = new BigMimeMultipart(new BufferedInputStream(in),
                                context.contentType);

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        mp.nextPart(bos);
                        result = bos.toByteArray();

                        if (transaction.getAllowDownloadAttachment()) {
                            Document doc = context.outputDocument;
                            Element attInfo = null;

                            File file = File.createTempFile("c8o_", ".part");

                            for (MimePart bp = mp.nextPart(file); bp != null; bp = mp.nextPart(file)) {
                                try {
                                    file.deleteOnExit();

                                    if (attInfo == null) {
                                        Engine.logBeans.debug("(HttpConnector) Saving attachment(s)");

                                        attInfo = doc.createElement("AttachmentInfo");
                                        doc.getDocumentElement().appendChild(attInfo);
                                    }

                                    Element att = doc.createElement("attachment");
                                    attInfo.appendChild(att);

                                    String cid = bp.getContentID();

                                    if (cid != null) {
                                        cid = cid.replaceFirst("^<?(.*?)>?$", "$1");
                                        att.setAttribute("cid", "cid:" + cid);
                                    }

                                    Engine.logBeans.debug("(HttpConnector) Saving the attachment cid: " + cid
                                            + " in file: " + file.getAbsolutePath());

                                    att.setAttribute("filepath", file.getAbsolutePath());

                                    Enumeration<javax.mail.Header> headers = GenericUtils
                                            .cast(bp.getAllHeaders());
                                    while (headers.hasMoreElements()) {
                                        javax.mail.Header header = headers.nextElement();
                                        Element eHeader = doc.createElement("header");
                                        att.appendChild(eHeader);

                                        eHeader.setAttribute("name", header.getName());
                                        eHeader.setAttribute("value", header.getValue());
                                    }
                                } catch (Exception e1) {
                                    Engine.logBeans
                                            .error("(HttpConnector) Failed to retrieve the attachment in "
                                                    + file.getAbsolutePath(), e1);
                                }

                                file = File.createTempFile("c8o_", ".part");
                            }

                            file.delete();
                            in.close();
                        }
                    } catch (Exception e) {
                        Engine.logBeans.error("(HttpConnector) Failed to retrieve attachments", e);
                    }
                } else {
                    result = IOUtils.toByteArray(in);
                    in.close();
                }
            }

            if (Engine.logBeans.isTraceEnabled()) {
                contents = new String((result != null) ? result : new byte[] {});
                Engine.logBeans.trace("(HttpConnector) Response content:\n" + contents);
            }

            String redirectUrl, newuri;
            GetMethod redirectMethod = null;

            // Handles REDIRECTION through Location header
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

                Header location = method.getResponseHeader("Location");
                if (location != null) {
                    newuri = location.getValue();
                    if ((newuri == null) || (newuri.equals(""))) {
                        newuri = "/";
                    }

                    // ignore any data after the ";" character
                    int split = newuri.indexOf(';');
                    if (split != -1) {
                        newuri = newuri.substring(0, split);
                    }

                    redirectUrl = getAbsoluteUrl(method, newuri);
                    Engine.logBeans.debug("(HttpConnector) Redirecting to : " + redirectUrl);
                    redirectMethod = new GetMethod(redirectUrl);

                    // set headers
                    for (int i = 0; i < requestHeaders.length; i++)
                        redirectMethod.setRequestHeader(requestHeaders[i]);

                    referer = redirectUrl.startsWith("http") ? redirectUrl
                            : (hostConfiguration.getHostURL() + redirectUrl);

                    result = executeMethod(redirectMethod, context); // recurse
                } else {
                    Engine.logBeans.debug("(HttpConnector) Invalid redirect!");
                }
            } else {
                /*
                 * String lwContents = contents.toLowerCase(); int index, i,
                 * j, k, z; // Handles REDIRECTION through META Refresh if
                 * (((index = lwContents.indexOf("http-equiv='refresh'")) !=
                 * -1) || ((index =
                 * lwContents.indexOf("http-equiv=\"refresh\"")) != -1)) {
                 * if ((i = lwContents.indexOf("content=", index + 20)) !=
                 * -1) { char c = lwContents.charAt(i+8); if ((j =
                 * lwContents.indexOf("url=", i)) != -1) { if ((k =
                 * lwContents.indexOf(c, j + 1)) != -1) { newuri =
                 * lwContents.substring(j+4, k); redirectUrl =
                 * getAbsoluteUrl(method,newuri);
                 * Engine.logBeans.debug("(HttpConnector) Redirecting to : "
                 * + redirectUrl); redirectMethod = new
                 * GetMethod(redirectUrl);
                 * 
                 * // set headers for (z=0; z<requestHeaders.length; z++)
                 * redirectMethod.setRequestHeader(requestHeaders[z]);
                 * 
                 * referer = redirectUrl; result =
                 * executeMethod(redirectMethod, context); // recurse } } }
                 * } // Handles FRAMESET else if
                 * (lwContents.indexOf("frameset") != -1) {
                 * Engine.logBeans.debug
                 * ("(HttpConnector) Analyzing frameset...");
                 * StringTokenizer st = new StringTokenizer(lwContents);
                 * StringEx newcontents = new StringEx(lwContents); while
                 * (st.hasMoreTokens()) { String token = st.nextToken();
                 * String uri; if (token.startsWith("src=")) { if
                 * ((token.indexOf("\"") != -1) || (token.indexOf("'") !=
                 * -1)) { token = token.substring(5); uri =
                 * token.substring(0,token.length()-1); newuri =
                 * getAbsoluteUrl(method,uri);
                 * Engine.logBeans.trace("(HttpConnector) Replaced uri ("+
                 * uri +") with newuri("+ newuri +")");
                 * 
                 * newcontents.replaceAll(token,newuri); } } }
                 * Engine.logBeans
                 * .trace("(HttpConnector) New response content:\n"+
                 * newcontents); result = newcontents.toString().getBytes();
                 * }
                 */
            }
        }
        //Added by julienda - #3433 - 04/03/2013
        AbstractHttpTransaction abstractHttpTransaction = (AbstractHttpTransaction) context.transaction;

        if (abstractHttpTransaction.getHttpInfo()) {
            Document doc = context.outputDocument;

            //Remove the node HTTPInfo if we have a redirect
            NodeList nodeList = XMLUtils.findElements(context.outputDocument.getDocumentElement(),
                    abstractHttpTransaction.getHttpInfoTagName());
            if (nodeList != null) {
                XMLUtils.removeNodeListContent(nodeList);
            }

            //Parent Element
            httpInfoElement = doc.createElement(abstractHttpTransaction.getHttpInfoTagName());

            //Add requested URL
            Element urlElement = doc.createElement("url");
            urlElement.setTextContent(method.getURI().toString());
            httpInfoElement.appendChild(urlElement);

            //Add status code
            Element httpStatusElement = doc.createElement("status");

            httpStatusElement.setAttribute("code", Integer.toString(statuscode));
            httpStatusElement.setAttribute("text", method.getStatusText());
            httpInfoElement.appendChild(httpStatusElement);

            //We add headers informations

            List<Header> headers = Arrays.asList(requestHeaders);
            if (!headers.isEmpty()) {
                Element httpHeadersElement = doc.createElement("headers");

                for (int i = 0; i < headers.size(); i++) {
                    Element elt = doc.createElement("header");
                    elt.setAttribute("name", headers.get(i).getName());
                    elt.setAttribute("value", headers.get(i).getValue());
                    httpHeadersElement.appendChild(elt);
                }
                httpInfoElement.appendChild(httpHeadersElement);
            }

            // we add response header information
            if (responseHeaders.length != 0) {
                Element httpHeadersElement = doc.createElement("responseHeaders");

                for (int i = 0; i < responseHeaders.length; i++) {
                    Element elt = doc.createElement("header");
                    elt.setAttribute("name", responseHeaders[i].getName());
                    elt.setAttribute("value", responseHeaders[i].getValue());
                    httpHeadersElement.appendChild(elt);
                }
                httpInfoElement.appendChild(httpHeadersElement);
            }

            doc.getDocumentElement().appendChild(httpInfoElement);
        }
    } finally {
        method.releaseConnection();
    }

    return result;
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

/**
 * http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk/doc/Extensions/caldav-proxy.txt
 * This is an Apple standard implemented by Apple Mac OSX at least up to Yosemite and offers a fairly simple
 * sharing model for calendars.  The model is simpler than Zimbra's native model and there are mismatches,
 * for instance Zimbra requires the proposed delegate to accept shares.
 */// w  ww .j a va  2s.  c o  m
@Test
public void testAppleCaldavProxyFunctions() throws ServiceException, IOException {
    Account sharer = users[3].create();
    Account sharee1 = users[1].create();
    Account sharee2 = users[2].create();
    ZMailbox mboxSharer = TestUtil.getZMailbox(sharer.getName());
    ZMailbox mboxSharee1 = TestUtil.getZMailbox(sharee1.getName());
    ZMailbox mboxSharee2 = TestUtil.getZMailbox(sharee2.getName());
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharer, true);
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharee1, true);
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharee2, true);
    // Test PROPPATCH to "calendar-proxy-read" URL
    setGroupMemberSet(TestCalDav.getCalendarProxyReadUrl(sharer), sharer, sharee2);
    // Test PROPPATCH to "calendar-proxy-write" URL
    setGroupMemberSet(TestCalDav.getCalendarProxyWriteUrl(sharer), sharer, sharee1);

    // verify that adding new members to groups triggered notification messages
    List<ZMessage> msgs = TestUtil.waitForMessages(mboxSharee1,
            "in:inbox subject:\"Share Created: Calendar shared by \"", 1, 10000);
    assertNotNull(String.format("Notification msgs for %s", sharee1.getName()), msgs);
    assertEquals(String.format("num msgs for %s", sharee1.getName()), 1, msgs.size());

    msgs = TestUtil.waitForMessages(mboxSharee2, "in:inbox subject:\"Share Created: Calendar shared by \"", 1,
            10000);
    assertNotNull(String.format("Notification msgs for %s", sharee2.getName()), msgs);
    assertEquals(String.format("num msgs for %s", sharee2.getName()), 1, msgs.size());
    // Simulate acceptance of the shares (would normally need to be done in ZWC
    createCalendarMountPoint(mboxSharee1, sharer);
    createCalendarMountPoint(mboxSharee2, sharer);
    Document doc = delegateForExpandProperty(sharee1);
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV());
    XPathExpression xPathExpr;
    try {
        String xpathS = "/D:multistatus/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        NodeList result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
        assertEquals(String.format("num XPath nodes for %s for %s", xpathS, sharee1.getName()), 1,
                result.getLength());
        String text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for account owner", UrlNamespace.getPrincipalUrl(sharee1).replaceAll("@", "%40"),
                text);

        xpathS = "/D:multistatus/D:response/D:propstat/D:prop/CS:calendar-proxy-write-for/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
        assertEquals(String.format("num XPath nodes for %s for %s", xpathS, sharee1.getName()), 1,
                result.getLength());
        text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for sharer", UrlNamespace.getPrincipalUrl(sharer).replaceAll("@", "%40"), text);
    } catch (XPathExpressionException e1) {
        ZimbraLog.test.debug("xpath problem", e1);
    }
    // Check that proxy write has sharee1 in it
    doc = groupMemberSetExpandProperty(sharer, sharee1, true);
    // Check that proxy read has sharee2 in it
    doc = groupMemberSetExpandProperty(sharer, sharee2, false);
    String davBaseName = "notAllowed@There";
    String url = String.format("%s%s",
            getFolderUrl(sharee1, "Shared Calendar").replaceAll(" ", "%20").replaceAll("@", "%40"),
            davBaseName);
    HttpMethodExecutor exe = doIcalPut(url, sharee1, simpleEvent(sharer), HttpStatus.SC_MOVED_TEMPORARILY);
    String location = null;
    for (Header hdr : exe.respHeaders) {
        if ("Location".equals(hdr.getName())) {
            location = hdr.getValue();
        }
    }
    assertNotNull("Location Header not returned when creating", location);
    url = String.format("%s%s",
            getFolderUrl(sharee1, "Shared Calendar").replaceAll(" ", "%20").replaceAll("@", "%40"),
            location.substring(location.lastIndexOf('/') + 1));
    doIcalPut(url, sharee1, simpleEvent(sharer), HttpStatus.SC_CREATED);
}

From source file:orca.handlers.nlr.SherpaSession.java

Reader executeCommand(String wellFormedCmdURL) {

    if (debug)/* w  ww. j a  va  2  s.co  m*/
        System.out.println("Executing " + wellFormedCmdURL);
    try {

        GetMethod httpget = new GetMethod(wellFormedCmdURL);

        // disableRedirects();
        httpget.setFollowRedirects(false);

        dhc.executeMethod(httpget);

        if (httpget.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            // consume content and handle the login

            // get the redirected location
            Header location = httpget.getResponseHeader("location");

            handleLogin(httpget);

            // hit the redirected location again
            // enableRedirects();

            GetMethod httpget1 = new GetMethod(location.getValue());
            httpget1.setFollowRedirects(true);

            dhc.executeMethod(httpget1);
            InputStreamReader isr = new InputStreamReader(httpget1.getResponseBodyAsStream());
            return isr;
        }

        InputStreamReader isr = new InputStreamReader(httpget.getResponseBodyAsStream());

        return isr;

    } catch (IOException e2) {
        e2.printStackTrace(System.err);
    }
    return null;
}

From source file:org.alfresco.httpclient.AbstractHttpClient.java

private boolean isRedirect(HttpMethod method) {
    switch (method.getStatusCode()) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        if (method.getFollowRedirects()) {
            return true;
        } else {//from   w  w w  . j  a  v  a  2 s  .com
            return false;
        }
    default:
        return false;
    }
}

From source file:org.alfresco.repo.search.impl.solr.SolrAdminHTTPClient.java

public JSONObject execute(String relativeHandlerPath, HashMap<String, String> args) {
    ParameterCheck.mandatory("relativeHandlerPath", relativeHandlerPath);
    ParameterCheck.mandatory("args", args);

    String path = getPath(relativeHandlerPath);
    try {/*from   www  .j ava 2  s .  c  om*/
        URLCodec encoder = new URLCodec();
        StringBuilder url = new StringBuilder();

        for (String key : args.keySet()) {
            String value = args.get(key);
            if (url.length() == 0) {
                url.append(path);
                url.append("?");
                url.append(encoder.encode(key, "UTF-8"));
                url.append("=");
                url.append(encoder.encode(value, "UTF-8"));
            } else {
                url.append("&");
                url.append(encoder.encode(key, "UTF-8"));
                url.append("=");
                url.append(encoder.encode(value, "UTF-8"));
            }

        }

        // PostMethod post = new PostMethod(url.toString());
        GetMethod get = new GetMethod(url.toString());

        try {
            httpClient.executeMethod(get);

            if (get.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                    || get.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                Header locationHeader = get.getResponseHeader("location");
                if (locationHeader != null) {
                    String redirectLocation = locationHeader.getValue();
                    get.setURI(new URI(redirectLocation, true));
                    httpClient.executeMethod(get);
                }
            }

            if (get.getStatusCode() != HttpServletResponse.SC_OK) {
                throw new LuceneQueryParserException(
                        "Request failed " + get.getStatusCode() + " " + url.toString());
            }

            Reader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
            // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
            JSONObject json = new JSONObject(new JSONTokener(reader));
            return json;
        } finally {
            get.releaseConnection();
        }
    } catch (UnsupportedEncodingException e) {
        throw new LuceneQueryParserException("", e);
    } catch (HttpException e) {
        throw new LuceneQueryParserException("", e);
    } catch (IOException e) {
        throw new LuceneQueryParserException("", e);
    } catch (JSONException e) {
        throw new LuceneQueryParserException("", e);
    }
}

From source file:org.alfresco.repo.search.impl.solr.SolrQueryHTTPClient.java

protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body)
        throws UnsupportedEncodingException, IOException, HttpException, URIException, JSONException {
    PostMethod post = new PostMethod(url);
    if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER) {
        post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    }//from  ww w.j a  va2s  .  co  m
    post.setRequestEntity(new ByteArrayRequestEntity(body.toString().getBytes("UTF-8"), "application/json"));

    try {
        httpClient.executeMethod(post);

        if (post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null) {
                String redirectLocation = locationHeader.getValue();
                post.setURI(new URI(redirectLocation, true));
                httpClient.executeMethod(post);
            }
        }

        if (post.getStatusCode() != HttpServletResponse.SC_OK) {
            throw new LuceneQueryParserException(
                    "Request failed " + post.getStatusCode() + " " + url.toString());
        }

        Reader reader = new BufferedReader(
                new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
        // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
        JSONObject json = new JSONObject(new JSONTokener(reader));

        if (json.has("status")) {
            JSONObject status = json.getJSONObject("status");
            if (status.getInt("code") != HttpServletResponse.SC_OK) {
                throw new LuceneQueryParserException("SOLR side error: " + status.getString("message"));
            }
        }
        return json;
    } finally {
        post.releaseConnection();
    }
}