Example usage for org.apache.commons.httpclient.util URIUtil decode

List of usage examples for org.apache.commons.httpclient.util URIUtil decode

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.util URIUtil decode.

Prototype

public static String decode(String escaped) throws URIException 

Source Link

Document

Unescape and decode a given string regarded as an escaped string with the default protocol charset.

Usage

From source file:de.innovationgate.utils.CookieValueEncoder.java

/**
 * Decodes the value/* w w  w.j  av a  2s.c  om*/
 * @param value The encoded value
 * @return Decoded value or null if not decodeable
 */
public static String decode(String value) {
    try {
        return URIUtil.decode(value);
    } catch (URIException e) {
        return null;
    }
}

From source file:net.bioclipse.opentox.api.Dataset.java

@SuppressWarnings("serial")
public static StringMatrix listPredictedFeatures(String datasetURI) throws Exception {
    logger.debug("Listing features for: " + datasetURI);
    datasetURI = datasetURI.replaceAll("\n", "");
    if (datasetURI.contains("feature_uris[]=")) {
        String baseURI = datasetURI.substring(0, datasetURI.indexOf("feature_uris[]="));
        String featureURIs = datasetURI.substring(datasetURI.indexOf("feature_uris[]=") + 15);
        featureURIs = URIUtil.decode(featureURIs);
        String fullURI = baseURI + "feature_uris[]=" + featureURIs;
        datasetURI = URIUtil.encodeQuery(fullURI);
    }/*from   w ww.  j av a  2s.  c  o  m*/
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(datasetURI);
    HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() {
        {
            put("Accept", "application/rdf+xml");
        }
    });
    client.executeMethod(method);
    String result = method.getResponseBodyAsString(); // without this things will fail??
    IRDFStore store = rdf.createInMemoryStore();
    rdf.importFromStream(store, method.getResponseBodyAsStream(), "RDF/XML", null);
    method.releaseConnection();
    String dump = rdf.asRDFN3(store);
    StringMatrix matrix = rdf.sparql(store, QUERY_PREDICTED_FEATURES);
    return matrix;
}

From source file:davmail.caldav.CaldavConnection.java

@Override
public void run() {
    String line;//from  w  ww  . j a v  a  2  s . c om
    StringTokenizer tokens;

    try {
        while (!closed) {
            line = readClient();
            // unable to read line, connection closed ?
            if (line == null) {
                break;
            }
            tokens = new StringTokenizer(line);
            String command = tokens.nextToken();
            Map<String, String> headers = parseHeaders();
            String encodedPath = StringUtil.encodePlusSign(tokens.nextToken());
            String path = URIUtil.decode(encodedPath);
            String content = getContent(headers.get("content-length"));
            setSocketTimeout(headers.get("keep-alive"));
            // client requested connection close
            closed = "close".equals(headers.get("connection"));
            if ("OPTIONS".equals(command)) {
                sendOptions();
            } else if (!headers.containsKey("authorization")) {
                sendUnauthorized();
            } else {
                decodeCredentials(headers.get("authorization"));
                // need to check session on each request, credentials may have changed or session expired
                try {
                    session = ExchangeSessionFactory.getInstance(userName, password);
                    handleRequest(command, path, headers, content);
                } catch (DavMailAuthenticationException e) {
                    sendUnauthorized();
                }
            }

            os.flush();
            DavGatewayTray.resetIcon();
        }
    } catch (SocketTimeoutException e) {
        DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT"));
    } catch (SocketException e) {
        DavGatewayTray.debug(new BundleMessage("LOG_CONNECTION_CLOSED"));
    } catch (Exception e) {
        if (!(e instanceof HttpNotFoundException)) {
            DavGatewayTray.log(e);
        }
        try {
            sendErr(e);
        } catch (IOException e2) {
            DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2);
        }
    } finally {
        close();
    }
    DavGatewayTray.resetIcon();
}

From source file:davmail.caldav.CaldavConnection.java

protected void handlePrincipals(CaldavRequest request) throws IOException {
    if (request.isPath(2, "users")) {
        if (request.isPropFind() && request.isPathLength(4)) {
            sendPrincipal(request, "users", URIUtil.decode(request.getPathElement(3)));
            // send back principal on search
        } else if (request.isReport() && request.isPathLength(3)) {
            sendPrincipal(request, "users", session.getEmail());
            // iCal current-user-principal request
        } else if (request.isPropFind() && request.isPathLength(3)) {
            sendPrincipalsFolder(request);
        } else {//from  w w  w . j ava2 s.  co m
            sendUnsupported(request);
        }
    } else if (request.isPath(2, "public")) {
        StringBuilder prefixBuffer = new StringBuilder("public");
        for (int i = 3; i < request.getPathLength() - 1; i++) {
            prefixBuffer.append('/').append(request.getPathElement(i));
        }
        sendPrincipal(request, URIUtil.decode(prefixBuffer.toString()), URIUtil.decode(request.getLastPath()));
    } else {
        sendUnsupported(request);
    }
}

From source file:edu.unc.lib.dl.cdr.services.techmd.TechnicalMetadataEnhancement.java

/**
 * Executes fits extract irods script/*from www.  j  ava2s  .c  o m*/
 * 
 * @param dsIrodsPath
 * @return FITS output XML Document
 */
private Document runFITS(String dsIrodsPath, String altIds) throws Exception {
    Document result = null;

    // try to extract file name from ALT_ID
    String filename = null;
    if (altIds != null) {
        for (String altid : altIds.split(" ")) {
            if (altid.length() > 0) {
                String rawPath = altid;
                // Narrow file name down to after the last /
                int lastSlash = rawPath.lastIndexOf("/");
                if (lastSlash > 0)
                    rawPath = rawPath.substring(lastSlash + 1);
                int ind = rawPath.lastIndexOf(".");
                // Use text after last . as extension if its length is 0 > len >= MAX_EXTENSION_LENGTH
                if (ind > 0 && rawPath.length() - 1 > ind && (rawPath.length() - ind <= MAX_EXTENSION_LENGTH)) {
                    filename = rawPath.substring(ind + 1);
                    filename = URIUtil.decode("linkedfile." + filename);
                    break;
                }
            }
        }
    }

    // execute FITS
    LOG.debug("Run fits for {}", dsIrodsPath);
    BufferedReader reader = null;
    String xmlstr = null;
    String errstr = null;
    try {
        if (filename == null) {
            reader = new BufferedReader(new InputStreamReader(((AbstractIrodsObjectEnhancementService) service)
                    .remoteExecuteWithPhysicalLocation("fitsextract", dsIrodsPath)));
        } else {
            reader = new BufferedReader(new InputStreamReader(((AbstractIrodsObjectEnhancementService) service)
                    .remoteExecuteWithPhysicalLocation("fitsextract", "'" + filename + "'", dsIrodsPath)));
        }
        StringBuilder xml = new StringBuilder();
        StringBuilder err = new StringBuilder();
        boolean blankReached = false;
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            if (line.trim().length() == 0) {
                blankReached = true;
                continue;
            } else {
                if (blankReached) {
                    err.append(line).append("\n");
                } else {
                    xml.append(line).append("\n");
                }
            }
        }
        xmlstr = xml.toString();
        errstr = err.toString();
        if (errstr.length() > 0) {
            LOG.warn("FITS is warning for path: " + dsIrodsPath);
            LOG.info(errstr);
        }
        result = new SAXBuilder().build(new StringReader(xmlstr));
        return result;
    } catch (JDOMException e) {
        LOG.warn("Failed to parse FITS output for path: " + dsIrodsPath);
        LOG.info("FITS returned: \n" + xmlstr + "\n\n" + errstr);
        throw e;
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:davmail.caldav.CaldavConnection.java

protected void handleFolderOrItem(CaldavRequest request) throws IOException {
    String lastPath = StringUtil.xmlDecode(request.getLastPath());
    // folder requests
    if (request.isPropFind() && "inbox".equals(lastPath)) {
        sendInbox(request);/*from   w ww.j  a v a 2  s  . c  o  m*/
    } else if (request.isPropFind() && "outbox".equals(lastPath)) {
        sendOutbox(request);
    } else if (request.isPost() && "outbox".equals(lastPath)) {
        if (request.isFreeBusy()) {
            sendFreeBusy(request.getBody());
        } else {
            int status = session.sendEvent(request.getBody());
            // TODO: implement Itip response body
            sendHttpResponse(status);
        }
    } else if (request.isPropFind()) {
        sendFolderOrItem(request);
    } else if (request.isPropPatch()) {
        patchCalendar(request);
    } else if (request.isReport()) {
        reportItems(request);
        // event requests
    } else if (request.isPut()) {
        String etag = request.getHeader("if-match");
        String noneMatch = request.getHeader("if-none-match");
        ExchangeSession.ItemResult itemResult = session.createOrUpdateItem(request.getFolderPath(), lastPath,
                request.getBody(), etag, noneMatch);
        sendHttpResponse(itemResult.status, buildEtagHeader(itemResult.etag), null, "", true);

    } else if (request.isDelete()) {
        if (request.getFolderPath().endsWith("inbox")) {
            session.processItem(request.getFolderPath(), lastPath);
        } else {
            session.deleteItem(request.getFolderPath(), lastPath);
        }
        sendHttpResponse(HttpStatus.SC_OK);
    } else if (request.isGet()) {
        if (request.path.endsWith("/")) {
            // GET request on a folder => build ics content of all folder events
            String folderPath = request.getFolderPath();
            ExchangeSession.Folder folder = session.getFolder(folderPath);
            if (folder.isContact()) {
                List<ExchangeSession.Contact> contacts = session.getAllContacts(folderPath);
                ChunkedResponse response = new ChunkedResponse(HttpStatus.SC_OK, "text/vcard;charset=UTF-8");

                for (ExchangeSession.Contact contact : contacts) {
                    String contactBody = contact.getBody();
                    if (contactBody != null) {
                        response.append(contactBody);
                        response.append("\n");
                    }
                }
                response.close();

            } else if (folder.isCalendar() || folder.isTask()) {
                List<ExchangeSession.Event> events = session.getAllEvents(folderPath);
                ChunkedResponse response = new ChunkedResponse(HttpStatus.SC_OK, "text/calendar;charset=UTF-8");
                response.append("BEGIN:VCALENDAR\r\n");
                response.append("VERSION:2.0\r\n");
                response.append("PRODID:-//davmail.sf.net/NONSGML DavMail Calendar V1.1//EN\r\n");
                response.append("METHOD:PUBLISH\r\n");

                for (ExchangeSession.Event event : events) {
                    String icsContent = StringUtil.getToken(event.getBody(), "BEGIN:VTIMEZONE",
                            "END:VCALENDAR");
                    if (icsContent != null) {
                        response.append("BEGIN:VTIMEZONE");
                        response.append(icsContent);
                    } else {
                        icsContent = StringUtil.getToken(event.getBody(), "BEGIN:VEVENT", "END:VCALENDAR");
                        if (icsContent != null) {
                            response.append("BEGIN:VEVENT");
                            response.append(icsContent);
                        }
                    }
                }
                response.append("END:VCALENDAR");
                response.close();
            } else {
                sendHttpResponse(HttpStatus.SC_OK, buildEtagHeader(folder.etag), "text/html", (byte[]) null,
                        true);
            }
        } else {
            ExchangeSession.Item item = session.getItem(request.getFolderPath(), lastPath);
            sendHttpResponse(HttpStatus.SC_OK, buildEtagHeader(item.getEtag()), item.getContentType(),
                    item.getBody(), true);
        }
    } else if (request.isHead()) {
        // test event
        ExchangeSession.Item item = session.getItem(request.getFolderPath(), lastPath);
        sendHttpResponse(HttpStatus.SC_OK, buildEtagHeader(item.getEtag()), item.getContentType(),
                (byte[]) null, true);
    } else if (request.isMkCalendar()) {
        HashMap<String, String> properties = new HashMap<String, String>();
        //properties.put("displayname", request.getProperty("displayname"));
        int status = session.createCalendarFolder(request.getFolderPath(), properties);
        sendHttpResponse(status, null);
    } else if (request.isMove()) {
        String destinationUrl = request.getHeader("destination");
        session.moveItem(request.path, URIUtil.decode(new URL(destinationUrl).getPath()));
        sendHttpResponse(HttpStatus.SC_CREATED, null);
    } else {
        sendUnsupported(request);
    }

}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Exchange 2003: get mailPath from welcome page
 *
 * @param method current http method/*from  w ww . java 2s .com*/
 * @return mail path from body
 */
protected String getMailpathFromWelcomePage(HttpMethod method) {
    String welcomePageMailPath = null;
    // get user mail URL from html body (multi frame)
    BufferedReader mainPageReader = null;
    try {
        mainPageReader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        //noinspection StatementWithEmptyBody
        String line;
        while ((line = mainPageReader.readLine()) != null && line.toLowerCase().indexOf(BASE_HREF) == -1) {
        }
        if (line != null) {
            // Exchange 2003
            int start = line.toLowerCase().indexOf(BASE_HREF) + BASE_HREF.length();
            int end = line.indexOf('\"', start);
            String mailBoxBaseHref = line.substring(start, end);
            URL baseURL = new URL(mailBoxBaseHref);
            welcomePageMailPath = URIUtil.decode(baseURL.getPath());
            LOGGER.debug("Base href found in body, mailPath is " + welcomePageMailPath);
        }
    } catch (IOException e) {
        LOGGER.error("Error parsing main page at " + method.getPath(), e);
    } finally {
        if (mainPageReader != null) {
            try {
                mainPageReader.close();
            } catch (IOException e) {
                LOGGER.error("Error parsing main page at " + method.getPath());
            }
        }
        method.releaseConnection();
    }
    return welcomePageMailPath;
}

From source file:davmail.exchange.dav.DavExchangeSession.java

protected String getURIPropertyIfExists(DavPropertySet properties, String alias) throws URIException {
    DavProperty property = properties.get(Field.getPropertyName(alias));
    if (property == null) {
        return null;
    } else {//from ww w.ja v  a  2s.  co  m
        return URIUtil.decode((String) property.getValue());
    }
}

From source file:davmail.caldav.CaldavConnection.java

/**
 * Report items listed in request.// ww w.j  a va  2 s  .  c o  m
 *
 * @param request Caldav request
 * @throws IOException on error
 */
public void reportItems(CaldavRequest request) throws IOException {
    String folderPath = request.getFolderPath();
    List<ExchangeSession.Event> events;
    List<String> notFound = new ArrayList<String>();

    CaldavResponse response = new CaldavResponse(HttpStatus.SC_MULTI_STATUS);
    response.startMultistatus();
    if (request.isMultiGet()) {
        int count = 0;
        int total = request.getHrefs().size();
        for (String href : request.getHrefs()) {
            DavGatewayTray.debug(new BundleMessage("LOG_REPORT_ITEM", ++count, total));
            DavGatewayTray.switchIcon();
            String eventName = getEventFileNameFromPath(href);
            try {
                // ignore cases for Sunbird
                if (eventName != null && eventName.length() > 0 && !"inbox".equals(eventName)
                        && !"calendar".equals(eventName)) {
                    ExchangeSession.Item item;
                    try {
                        item = session.getItem(folderPath, eventName);
                    } catch (HttpNotFoundException e) {
                        // workaround for Lightning bug
                        if (request.isBrokenLightning() && eventName.indexOf('%') >= 0) {
                            item = session.getItem(folderPath,
                                    URIUtil.decode(StringUtil.encodePlusSign(eventName)));
                        } else {
                            throw e;
                        }

                    }
                    appendItemResponse(response, request, item);
                }
            } catch (SocketException e) {
                // rethrow SocketException (client closed connection)
                throw e;
            } catch (Exception e) {
                wireLogger.debug(e.getMessage(), e);
                DavGatewayTray.warn(new BundleMessage("LOG_ITEM_NOT_AVAILABLE", eventName, href));
                notFound.add(href);
            }
        }
    } else if (request.isPath(1, "users") && request.isPath(3, "inbox")) {
        events = session.getEventMessages(request.getFolderPath());
        appendEventsResponses(response, request, events);
    } else {
        // TODO: handle contacts ?
        if (request.vTodoOnly) {
            events = session.searchTasksOnly(request.getFolderPath());
        } else if (request.vEventOnly) {
            events = session.searchEventsOnly(request.getFolderPath(), request.timeRangeStart,
                    request.timeRangeEnd);
        } else {
            events = session.searchEvents(request.getFolderPath(), request.timeRangeStart,
                    request.timeRangeEnd);
        }
        appendEventsResponses(response, request, events);
    }

    // send not found events errors
    for (String href : notFound) {
        response.startResponse(encodePath(request, href));
        response.appendPropstatNotFound();
        response.endResponse();
    }
    response.endMultistatus();
    response.close();
}

From source file:davmail.exchange.dav.DavExchangeSession.java

protected Folder buildFolder(MultiStatusResponse entity) throws IOException {
    String href = URIUtil.decode(entity.getHref());
    Folder folder = new Folder();
    DavPropertySet properties = entity.getProperties(HttpStatus.SC_OK);
    folder.displayName = getPropertyIfExists(properties, "displayname");
    folder.folderClass = getPropertyIfExists(properties, "folderclass");
    folder.hasChildren = "1".equals(getPropertyIfExists(properties, "hassubs"));
    folder.noInferiors = "1".equals(getPropertyIfExists(properties, "nosubs"));
    folder.count = getIntPropertyIfExists(properties, "count");
    folder.unreadCount = getIntPropertyIfExists(properties, "unreadcount");
    // fake recent value
    folder.recent = folder.unreadCount;/*from  www  .j  a va2s . c  o  m*/
    folder.ctag = getPropertyIfExists(properties, "contenttag");
    folder.etag = getPropertyIfExists(properties, "lastmodified");

    folder.uidNext = getIntPropertyIfExists(properties, "uidNext");

    // replace well known folder names
    if (inboxUrl != null && href.startsWith(inboxUrl)) {
        folder.folderPath = href.replaceFirst(inboxUrl, INBOX);
    } else if (sentitemsUrl != null && href.startsWith(sentitemsUrl)) {
        folder.folderPath = href.replaceFirst(sentitemsUrl, SENT);
    } else if (draftsUrl != null && href.startsWith(draftsUrl)) {
        folder.folderPath = href.replaceFirst(draftsUrl, DRAFTS);
    } else if (deleteditemsUrl != null && href.startsWith(deleteditemsUrl)) {
        folder.folderPath = href.replaceFirst(deleteditemsUrl, TRASH);
    } else if (calendarUrl != null && href.startsWith(calendarUrl)) {
        folder.folderPath = href.replaceFirst(calendarUrl, CALENDAR);
    } else if (contactsUrl != null && href.startsWith(contactsUrl)) {
        folder.folderPath = href.replaceFirst(contactsUrl, CONTACTS);
    } else {
        int index = href.indexOf(mailPath.substring(0, mailPath.length() - 1));
        if (index >= 0) {
            if (index + mailPath.length() > href.length()) {
                folder.folderPath = "";
            } else {
                folder.folderPath = href.substring(index + mailPath.length());
            }
        } else {
            try {
                URI folderURI = new URI(href, false);
                folder.folderPath = folderURI.getPath();
            } catch (URIException e) {
                throw new DavMailException("EXCEPTION_INVALID_FOLDER_URL", href);
            }
        }
    }
    if (folder.folderPath.endsWith("/")) {
        folder.folderPath = folder.folderPath.substring(0, folder.folderPath.length() - 1);
    }
    return folder;
}