Example usage for org.apache.commons.httpclient.methods GetMethod GetMethod

List of usage examples for org.apache.commons.httpclient.methods GetMethod GetMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods GetMethod GetMethod.

Prototype

public GetMethod(String uri) 

Source Link

Usage

From source file:eu.learnpad.core.impl.mv.XwikiBridgeInterfaceRestResource.java

@Override
public VerificationId startVerification(String modelSetId, String verificationType) throws LpRestException {
    HttpClient httpClient = this.getHttpClient();
    String uri = String.format("%s/learnpad/mv/bridge/startverification", this.restPrefix);
    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader("Accept", "application/xml");

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("modelsetid", modelSetId);
    queryString[1] = new NameValuePair("verificationtype", verificationType);

    getMethod.setQueryString(queryString);

    try {//from  ww  w. j  a v  a 2s .  c  om
        httpClient.executeMethod(getMethod);
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }

    VerificationId verificationId = null;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(VerificationId.class);
        InputStream retIs = getMethod.getResponseBodyAsStream();
        verificationId = (VerificationId) jaxbContext.createUnmarshaller().unmarshal(retIs);
    } catch (Exception e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }

    return verificationId;
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public SaxonDocument delete(String id)
        throws UnsupportedEncodingException, IOException, SaxonApiException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;//from  w w  w.j a  va  2 s.c  o  m

    String urlStr = this.solrHost + "/update?stream.body="
            + URLEncoder.encode("<delete><query>id:" + id + "</query></delete>") + "&commit=true";

    Log.debug("The " + id + " item is going to be deleted");
    // Create a method instance.
    method = new GetMethod(urlStr);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString());
    //Log.debug(solrResponse.getXMLDocumentString());

    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()",
                XPathConstants.STRING);
        throw new Exception(errorMessage);
    }

    return solrResponse;
}

From source file:edu.unc.lib.dl.cdr.sword.server.managers.MediaResourceManagerImpl.java

@Override
public MediaResource getMediaResourceRepresentation(String uri, Map<String, String> accept,
        AuthCredentials auth, SwordConfiguration config)
        throws SwordError, SwordServerException, SwordAuthException {

    log.debug("Retrieving media resource representation for " + uri);

    DatastreamPID targetPID = (DatastreamPID) extractPID(uri, SwordConfigurationImpl.EDIT_MEDIA_PATH + "/");

    Datastream datastream = Datastream.getDatastream(targetPID.getDatastream());
    if (datastream == null)
        datastream = virtualDatastreamMap.get(targetPID.getDatastream());

    if (datastream == null)
        throw new SwordError(ErrorURIRegistry.RESOURCE_NOT_FOUND, 404,
                "Media representations other than those of datastreams are not currently supported");

    HttpClient client = new HttpClient();

    UsernamePasswordCredentials cred = new UsernamePasswordCredentials(accessClient.getUsername(),
            accessClient.getPassword());
    client.getState().setCredentials(new AuthScope(null, 443), cred);
    client.getState().setCredentials(new AuthScope(null, 80), cred);

    GetMethod method = new GetMethod(fedoraPath + "/objects/" + targetPID.getPid() + "/datastreams/"
            + datastream.getName() + "/content");

    InputStream inputStream = null;
    String mimeType = null;/*w  ww .  j  av  a2 s. c o m*/
    String lastModified = null;

    try {
        method.setDoAuthentication(true);
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            StringBuffer query = new StringBuffer();
            query.append("select $mimeType $lastModified from <%1$s>")
                    .append(" where <%2$s> <%3$s> $mimeType and <%2$s> <%4$s> $lastModified").append(";");
            String formatted = String.format(query.toString(),
                    tripleStoreQueryService.getResourceIndexModelUri(),
                    targetPID.getURI() + "/" + datastream.getName(),
                    ContentModelHelper.FedoraProperty.mimeType.getURI().toString(),
                    ContentModelHelper.FedoraProperty.lastModifiedDate.getURI().toString());
            List<List<String>> datastreamResults = tripleStoreQueryService.queryResourceIndex(formatted);
            if (datastreamResults.size() > 0) {
                mimeType = datastreamResults.get(0).get(0);
                lastModified = datastreamResults.get(0).get(1);
            }
            inputStream = new MethodAwareInputStream(method);
        } else if (method.getStatusCode() >= 500) {
            throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, method.getStatusCode(),
                    "Failed to retrieve " + targetPID.getPid() + ": " + method.getStatusLine().toString());
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new SwordError(ErrorURIRegistry.RESOURCE_NOT_FOUND, 404,
                    "Object " + targetPID.getPid() + " could not be found.");
        }
    } catch (HttpException e) {
        throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION,
                "An exception occurred while attempting to retrieve " + targetPID.getPid());
    } catch (IOException e) {
        throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION,
                "An exception occurred while attempting to retrieve " + targetPID.getPid());
    }

    // For the ACL virtual datastream, transform RELS-EXT into accessControl tag
    if ("ACL".equals(targetPID.getDatastream())) {
        try {
            log.debug("Converting response XML to ACL format");
            SAXBuilder saxBuilder = new SAXBuilder();
            Document relsExt = saxBuilder.build(inputStream);
            XMLOutputter outputter = new XMLOutputter();
            Element accessElement = AccessControlTransformationUtil.rdfToACL(relsExt.getRootElement());
            inputStream.close();
            inputStream = new ByteArrayInputStream(outputter.outputString(accessElement).getBytes());
        } catch (Exception e) {
            log.debug("Failed to parse response from " + targetPID.getDatastreamURI() + " into ACL format", e);
            throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION,
                    "An exception occurred while attempting to retrieve " + targetPID.getPid());
        }
    }

    MediaResource resource = new MediaResource(inputStream, mimeType, null, true);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Date lastModifiedDate;
    try {
        lastModifiedDate = formatter.parse(lastModified);
        resource.setLastModified(lastModifiedDate);
    } catch (ParseException e) {
        log.error("Unable to set last modified date for " + uri, e);
    }

    return resource;
}

From source file:at.ait.dme.yuma.server.image.ImageTilesetGenerator.java

private String storeImage(String dir, String url) throws TilesetGenerationException {
    InputStream is = null;/* w w w. ja v  a  2s.c o m*/
    OutputStream os = null;
    try {
        GetMethod getImageMethod = new GetMethod(url);
        int statusCode = new HttpClient().executeMethod(getImageMethod);
        if (statusCode != HttpStatus.SC_OK)
            throw new TilesetGenerationException("GET " + url + " returned status code:" + statusCode);

        is = getImageMethod.getResponseBodyAsStream();
        File imageFile = new File(dir + "/" + url.substring(url.lastIndexOf("/")));
        os = new FileOutputStream(imageFile);

        byte buf[] = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0)
            os.write(buf, 0, len);

        return imageFile.getAbsolutePath();
    } catch (Throwable t) {
        logger.error("failed to store image from url:" + url, t);
        throw new TilesetGenerationException(t);
    } finally {
        try {
            if (os != null)
                os.close();
            if (is != null)
                is.close();
        } catch (IOException e) {
            logger.error("failed to close streams");
        }

    }
}

From source file:com.apatar.flickr.function.DownloadPhotoFlickrTable.java

public List<KeyInsensitiveMap> execute(FlickrNode node, Hashtable<String, Object> values, String strApi,
        String strSecret) throws IOException, XmlRpcException {
    FlickrTable table = FlickrTableList.getTableByName("flickr.photos.getSizes");
    if (table == null)
        return null;

    List<KeyInsensitiveMap> list = new ArrayList<KeyInsensitiveMap>();
    KeyInsensitiveMap map = new KeyInsensitiveMap();
    list.add(map);//from  w w  w.j  av  a2s.co m
    try {
        Element element = table.getResponse(node, values, strApi, strSecret);
        for (Object obj : element.getChild("sizes").getChildren("size")) {
            Element child = (Element) obj;
            if (child.getAttributeValue("label").equalsIgnoreCase("Medium")) {
                GetMethod getMethod = new GetMethod(child.getAttributeValue("source"));
                HttpClient client = new HttpClient();
                client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                client.executeMethod(getMethod);
                map.put("photo", getMethod.getResponseBody());
                map.put("photo_id", values.get("photo_id"));
            }
        }
    } catch (JDOMException e) {
        e.printStackTrace();
    }

    return list;
}

From source file:com.criticalsoftware.mobics.presentation.util.GeolocationUtil.java

public static List<PlaceDTO> getAddressFromText(String address) throws UnsupportedEncodingException {

    List<PlaceDTO> results = new ArrayList<PlaceDTO>();

    address = URLEncoder.encode(address, Configuration.INSTANCE.getUriEnconding());

    String url = MessageFormat.format(SEARCH_URL, Configuration.INSTANCE.getGeolocationServer(), address,
            Configuration.INSTANCE.getGeolocationServerAllowedCountries(),
            Configuration.INSTANCE.getMaxResults());
    HttpMethod method = new GetMethod(url);
    try {/*www .jav  a  2s.c  om*/
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Making search location call to: {}", url);
        }
        int statusCode = new HttpClient().executeMethod(method);

        if (statusCode == HttpStatus.SC_OK) {
            byte[] responseBody = readResponse(method);
            JSONArray jsonArray = (JSONArray) new JSONParser().parse(new String(responseBody));
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace(jsonArray.toJSONString());
            }

            @SuppressWarnings("unchecked")
            Iterator<JSONObject> it = jsonArray.iterator();
            while (it.hasNext()) {
                JSONObject place = it.next();
                results.add(new PlaceDTO((String) place.get(DISPLAY_NAME), (String) place.get(LATITUDE_NAME),
                        (String) place.get(LONGITUDE_NAME)));
            }

        } else {
            LOGGER.warn("Recived a HTTP status {}. Response was not good from {}", statusCode, url);
        }
    } catch (HttpException e) {
        LOGGER.error("Error while making call.", e);
    } catch (IOException e) {
        LOGGER.error("Error while reading the response.", e);
    } catch (ParseException e) {
        LOGGER.error("Error while parsing json response.", e);
    }

    return results;
}

From source file:com.rometools.propono.atom.client.ClientCollection.java

/**
 * Get full entry specified by entry edit URI. Note that entry may or may not be associated with
 * this collection./* w w w  . ja  v a 2s.co m*/
 *
 * @return ClientEntry or ClientMediaEntry specified by URI.
 */
public ClientEntry getEntry(final String uri) throws ProponoException {
    final GetMethod method = new GetMethod(uri);
    authStrategy.addAuthentication(httpClient, method);
    try {
        httpClient.executeMethod(method);
        if (method.getStatusCode() != 200) {
            throw new ProponoException("ERROR HTTP status code=" + method.getStatusCode());
        }
        final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(method.getResponseBodyAsStream()),
                uri, Locale.US);
        if (!romeEntry.isMediaEntry()) {
            return new ClientEntry(service, this, romeEntry, false);
        } else {
            return new ClientMediaEntry(service, this, romeEntry, false);
        }
    } catch (final Exception e) {
        throw new ProponoException("ERROR: getting or parsing entry/media, HTTP code: ", e);
    } finally {
        method.releaseConnection();
    }
}

From source file:att.jaxrs.client.Webinar.java

public static Webinar[] getWebinar() {
    // Sent HTTP GET request to query Webinar table
    GetMethod get = new GetMethod(Constants.SELECT_ALL_WEBINAR_OPERATION);
    WebinarCollection collection = new WebinarCollection();

    HttpClient httpClient = new HttpClient();
    try {/*from ww w . j  a  v a  2s  .co  m*/
        int result = httpClient.executeMethod(get);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        collection = Marshal.unmarshal(WebinarCollection.class, get.getResponseBodyAsStream());

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        get.releaseConnection();

    }
    if (null != collection.getWebinar() && collection.getWebinar().length > 0) {
        return collection.getWebinar();
    } else {
        System.out.println("unmarshalling returned empty collection");
    }
    return null;
}

From source file:com.github.jobs.api.GithubJobsApi.java

private static String createUrl(String url, List<NameValuePair> pairs) throws URIException {
    HttpMethod method = new GetMethod(url);
    NameValuePair[] nameValuePairs = pairs.toArray(new NameValuePair[pairs.size()]);
    method.setQueryString(nameValuePairs);
    return method.getURI().getEscapedURI();
}

From source file:com.owncloud.android.lib.resources.notifications.GetRemoteNotificationsOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;
    GetMethod get = null;/*ww  w.j  a  va 2 s.  c o m*/
    List<Notification> notifications;
    String url;
    if (client.getOwnCloudVersion().compareTo(OwnCloudVersion.nextcloud_12) >= 0) {
        url = client.getBaseUri() + OCS_ROUTE_LIST_V12_AND_UP;
    } else {
        url = client.getBaseUri() + OCS_ROUTE_LIST_V9_AND_UP;
    }

    // get the notifications
    try {
        get = new GetMethod(url);
        get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

        status = client.executeMethod(get);
        String response = get.getResponseBodyAsString();

        if (isSuccess(status)) {
            result = new RemoteOperationResult(true, status, get.getResponseHeaders());
            Log_OC.d(TAG, "Successful response: " + response);

            // Parse the response
            notifications = parseResult(response);
            result.setNotificationData(notifications);
        } else {
            result = new RemoteOperationResult(false, status, get.getResponseHeaders());
            Log_OC.e(TAG, "Failed response while getting user notifications ");
            if (response != null) {
                Log_OC.e(TAG, "*** status code: " + status + " ; response message: " + response);
            } else {
                Log_OC.e(TAG, "*** status code: " + status);
            }
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while getting remote notifications", e);
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

    return result;
}