Example usage for org.apache.http.entity FileEntity FileEntity

List of usage examples for org.apache.http.entity FileEntity FileEntity

Introduction

In this page you can find the example usage for org.apache.http.entity FileEntity FileEntity.

Prototype

public FileEntity(File file, ContentType contentType) 

Source Link

Usage

From source file:ee.ioc.phon.netspeechapi.Recognizer.java

private String postFile(File file, String mime, int rate) throws ClientProtocolException, IOException {
    HttpPost post = new HttpPost(mWsUrl);
    setUserAgent(post);/*from   w  w w  .  j  a v a  2 s.c om*/

    HttpEntity entity = new FileEntity(file, mime + "; rate=" + rate);
    post.setEntity(entity);

    return Utils.getResponseEntityAsString(post);
}

From source file:com.intel.cosbench.client.amplistor.AmpliClient.java

public String StoreObject(String sourceFilename, String ampliNamespace, String ampliFilename)
        throws IOException, HttpException, AmpliException {
    File file = new File(sourceFilename);

    HttpPut method = null;//www.j  a va  2  s . c  o m
    HttpResponse response = null;
    try {
        String storageUrl = "http://" + this.host + ":" + this.port + nsRoot;
        method = HttpClientUtil.makeHttpPut(storageUrl + "/" + HttpClientUtil.encodeURL(ampliNamespace) + "/"
                + HttpClientUtil.encodeURL(ampliFilename));

        method.setEntity(new FileEntity(file, "application/octet-stream"));

        response = client.execute(method);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return response.getFirstHeader("ETag").getValue();
        }

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return response.getFirstHeader("ETag").getValue();
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED) {
            throw new AmpliException("Etag missmatch", response.getAllHeaders(), response.getStatusLine());
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_LENGTH_REQUIRED) {
            throw new AmpliException("Length miss-match", response.getAllHeaders(), response.getStatusLine());
        } else {
            throw new AmpliException("Unexpected Server Response: " + response.getStatusLine(),
                    response.getAllHeaders(), response.getStatusLine());
        }
    } finally {
        if (response != null)
            EntityUtils.consume(response.getEntity());
    }
}

From source file:com.jaeksoft.searchlib.test.legacy.CommonTestCase.java

@SuppressWarnings("deprecation")
public int postFile(File file, String contentType, String api) throws IllegalStateException, IOException {
    String url = SERVER_URL + "/" + api + "?use=" + INDEX_NAME + "&login=" + USER_NAME + "&key=" + API_KEY;
    HttpPut put = new HttpPut(url);
    put.setEntity(new FileEntity(file, contentType));
    DefaultHttpClient httpClient = new DefaultHttpClient();
    return httpClient.execute(put).getStatusLine().getStatusCode();
}

From source file:com.ibm.xsp.extlib.sbt.services.client.SmartCloudService.java

@Override
protected void prepareRequest(HttpClient httpClient, HttpRequestBase httpRequestBase, Args args,
        Content content) throws ClientServicesException {

    Object contents = args.getHandler();
    if (contents instanceof File) {
        String name = args.getParameters().get("file");
        FileEntity fileEnt = new FileEntity((File) contents, getMimeForUpload());
        //fileEnt.setContentEncoding(FORMAT_BINARY);
        httpRequestBase.setHeader("slug", name);
        httpRequestBase.setHeader("Content-type", getMimeForUpload());
        if (fileEnt != null && (httpRequestBase instanceof HttpEntityEnclosingRequestBase)) {
            ((HttpEntityEnclosingRequestBase) httpRequestBase).setEntity(fileEnt);
        }/* w ww .  ja va 2  s .com*/
    }
    // TODO Auto-generated method stub
    super.prepareRequest(httpClient, httpRequestBase, args, content);
}

From source file:com.marklogic.client.test.util.TestServerBootstrapper.java

private void installBootstrapExtension() throws IOException {

    DefaultHttpClient client = new DefaultHttpClient();

    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", port),
            new UsernamePasswordCredentials(username, password));

    HttpPut put = new HttpPut("http://" + host + ":" + port + "/v1/config/resources/bootstrap?method=POST");

    put.setEntity(new FileEntity(new File("src/test/resources/bootstrap.xqy"), "application/xquery"));
    HttpResponse response = client.execute(put);
    @SuppressWarnings("unused")
    HttpEntity entity = response.getEntity();
    System.out.println("Installed bootstrap extension.  Response is " + response.toString());

}

From source file:com.personalserver.DirCommandHandler.java

private HttpEntity getEntityFromUri(String uri, HttpResponse response) {
    String contentType = "text/html";
    String filepath = FOLDER_SHARE_PATH;

    if (uri.equalsIgnoreCase("/") || uri.length() <= 0) {
        filepath = FOLDER_SHARE_PATH + "/";
    } else {/*from  w  w  w  .j  a v a 2  s  .c o m*/
        filepath = FOLDER_SHARE_PATH + "/" + URLDecoder.decode(uri);
    }

    System.out.println("request uri : " + uri);
    System.out.println("FOLDER SHARE PATH : " + FOLDER_SHARE_PATH);
    System.out.println("filepath : " + filepath);

    final File file = new File(filepath);

    HttpEntity entity = null;

    if (file.isDirectory()) {
        entity = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                String resp = getDirListingHTML(file);

                writer.write(resp);
                writer.flush();
            }
        });

        response.setHeader("Content-Type", contentType);
    } else if (file.exists()) {
        contentType = URLConnection.guessContentTypeFromName(file.getAbsolutePath());

        entity = new FileEntity(file, contentType);

        response.setHeader("Content-Type", contentType);
    } else {
        entity = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                String resp = "<html>" + "<head><title>ERROR : NOT FOUND</title></head>" + "<body>"
                        + "<center><h1>FILE OR DIRECTORY NOT FOUND !</h1></center>"
                        + "<p>Sorry, file or directory you request not available<br />"
                        + "Contact your administrator<br />" + "</p>" + "</body></html>";

                writer.write(resp);
                writer.flush();
            }
        });
        response.setHeader("Content-Type", "text/html");
    }

    return entity;
}

From source file:org.mobicents.servlet.restcomm.fax.InterfaxService.java

private URI send(final Object message) throws Exception {
    final FaxRequest request = (FaxRequest) message;
    final String to = request.to();
    final File file = request.file();
    // Prepare the request.
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpContext context = new BasicHttpContext();
    final SSLSocketFactory sockets = new SSLSocketFactory(strategy);
    final Scheme scheme = new Scheme("https", 443, sockets);
    client.getConnectionManager().getSchemeRegistry().register(scheme);
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);
    final HttpPost post = new HttpPost(url + to);
    final String mime = URLConnection.guessContentTypeFromName(file.getName());
    final FileEntity entity = new FileEntity(file, mime);
    post.addHeader(new BasicScheme().authenticate(credentials, post, context));
    post.setEntity(entity);//from w  ww  . j a va 2 s.  c om
    // Handle the response.
    final HttpResponse response = client.execute(post, context);
    final StatusLine status = response.getStatusLine();
    final int code = status.getStatusCode();
    if (HttpStatus.SC_CREATED == code) {
        EntityUtils.consume(response.getEntity());
        final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
        final Header location = headers[0];
        final String resource = location.getValue();
        return URI.create(resource);
    } else {
        final StringBuilder buffer = new StringBuilder();
        buffer.append(code).append(" ").append(status.getReasonPhrase());
        throw new FaxServiceException(buffer.toString());
    }
}

From source file:com.hp.mqm.clt.RestClientTest.java

@Test
public void testPostTestResult()
        throws IOException, URISyntaxException, InterruptedException, ValidationException {
    RestClient client = new RestClient(testClientSettings);
    long timestamp = System.currentTimeMillis();

    // invalid payload
    final File testResultsInvalidPayload = new File(this.getClass().getResource("TestResult.xmlx").toURI());
    try {//w  w w . j  ava2  s.  c o m
        client.postTestResult(new FileEntity(testResultsInvalidPayload, ContentType.APPLICATION_XML));
        Assert.fail();
    } catch (RuntimeException e) {
        Assert.assertNotNull(e);
    } finally {
        client.release();
    }

    // test "file does not exist"
    final File nonExistingFile = new File("abcdefghchijklmn.xml");
    try {
        client.postTestResult(new FileEntity(nonExistingFile, ContentType.APPLICATION_XML));
        Assert.fail();
    } catch (FileNotFoundException e) {
        Assert.assertNotNull(e);
    } finally {
        client.release();
    }

    String testResultXml = ResourceUtils.readContent("TestResult.xml").replaceAll("%%%TIMESTAMP%%%",
            String.valueOf(timestamp));
    final File testResult = temporaryFolder.newFile();
    FileUtils.write(testResult, testResultXml);
    try {
        long id = client.postTestResult(new FileEntity(testResult, ContentType.APPLICATION_XML));
        assertPublishResult(id, "success");
    } finally {
        client.release();
    }
    PagedList<TestRun> pagedList = testSupportClient.queryTestRuns("testOne" + timestamp, 0, 50);
    Assert.assertEquals(1, pagedList.getItems().size());
    Assert.assertEquals("testOne" + timestamp, pagedList.getItems().get(0).getName());
}

From source file:org.deegree.maven.WorkspaceITMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Set<?> artifacts = project.getDependencyArtifacts();
    Set<Artifact> workspaces = new HashSet<Artifact>();
    for (Object o : artifacts) {
        Artifact a = (Artifact) o;/*ww w  . j  av  a 2  s .  c  o m*/
        if (a.getType() != null && a.getType().equals("deegree-workspace")) {
            workspaces.add(a);
        }
    }

    ServiceIntegrationTestHelper helper = new ServiceIntegrationTestHelper(project, getLog());
    for (Artifact a : workspaces) {
        getLog().info("Testing workspace " + a.getArtifactId());

        String url = helper.createBaseURL() + "config/upload/iut.zip";
        File file = a.getFile();
        try {
            HttpClient client = HttpUtils.getAuthenticatedHttpClient(helper);

            getLog().info("Sending against: " + helper.createBaseURL() + "config/delete/iut");
            HttpGet get = new HttpGet(helper.createBaseURL() + "config/delete/iut");
            HttpResponse resp = client.execute(get);
            String response = EntityUtils.toString(resp.getEntity(), "UTF-8").trim();
            getLog().info("Response after initially deleting iut was: " + response);

            getLog().info("Sending against: " + helper.createBaseURL() + "config/restart");
            get = new HttpGet(helper.createBaseURL() + "config/restart");
            resp = client.execute(get);
            response = EntityUtils.toString(resp.getEntity(), "UTF-8").trim();
            getLog().info("Response after initial restart was: " + response);

            getLog().info("Sending against: " + url);
            HttpPost post = new HttpPost(url);
            post.setEntity(new FileEntity(file, null));
            resp = client.execute(post);
            response = EntityUtils.toString(resp.getEntity()).trim();
            getLog().info("Response after uploading was: " + response);

            getLog().info("Sending against: " + helper.createBaseURL() + "config/restart/iut");
            get = new HttpGet(helper.createBaseURL() + "config/restart/iut");
            resp = client.execute(get);
            response = EntityUtils.toString(resp.getEntity(), "UTF-8").trim();
            getLog().info("Response after starting workspace was: " + response);
        } catch (IOException e) {
            throw new MojoFailureException(
                    "Could not test workspace " + a.getArtifactId() + ": " + e.getLocalizedMessage(), e);
        }

        try {
            String s = get(UTF8STRING, helper.createBaseURL() + "config/list/iut/services/", null, "deegree",
                    "deegree");
            String[] services = s.split("\\s");

            for (String srv : services) {
                String nm = new File(srv).getName().toLowerCase();
                if (nm.length() != 7) {
                    continue;
                }
                String service = nm.substring(0, 3).toUpperCase();
                helper.testCapabilities(service);
                helper.testLayers(service);
                getLog().info("All maps can be requested.");
            }
            String response = get(UTF8STRING, helper.createBaseURL() + "config/delete/iut", null, "deegree",
                    "deegree").trim();
            getLog().info("Response after finally deleting iut was: " + response);
        } catch (IOException e) {
            getLog().debug(e);
            throw new MojoFailureException(
                    "Could not test workspace " + a.getArtifactId() + ": " + e.getLocalizedMessage(), e);
        }
    }
}