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) 

Source Link

Usage

From source file:com.seleniumtests.browserfactory.SauceLabsDriverFactory.java

/**
 * Upload application to saucelabs server
 * @param targetAppPath/*from www.  j a va2  s.co m*/
 * @param serverURL
 * @return
 * @throws IOException
 * @throws AuthenticationException 
 */
protected static boolean uploadFile(String targetAppPath) throws IOException, AuthenticationException {

    // extract user name and password from getWebDriverGrid
    Matcher matcher = REG_USER_PASSWORD
            .matcher(SeleniumTestsContextManager.getThreadContext().getWebDriverGrid().get(0));
    String user;
    String password;
    if (matcher.matches()) {
        user = matcher.group(1);
        password = matcher.group(2);
    } else {
        throw new ConfigurationException(
                "getWebDriverGrid variable does not have the right format for connecting to sauceLabs");
    }

    FileEntity entity = new FileEntity(new File(targetAppPath));
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);

    HttpPost request = new HttpPost(String.format(SAUCE_UPLOAD_URL, user, new File(targetAppPath).getName()));
    request.setEntity(entity);
    request.addHeader(new BasicScheme().authenticate(creds, request, null));
    request.addHeader("Content-Type", "application/octet-stream");

    try (CloseableHttpClient client = HttpClients.createDefault();) {
        CloseableHttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            client.close();
            throw new ConfigurationException(
                    "Application file upload failed: " + response.getStatusLine().getReasonPhrase());
        }
    }

    return true;
}

From source file:org.fcrepo.examples.models.integration.ExampleNodeTypesIT.java

/**
 * curl -X POST -H "Content-Type: text/cnd" -d "@cnd.txt"
 * "http://localhost:8080/rest/fcr:nodetypes"
 *
 * @param cndFile/*from   w ww .j  a  v a2 s  .co  m*/
 * @throws Exception
 */
private void ingestNodeTypes(final File cndFile) throws Exception {
    final HttpPost post = new HttpPost(serverAddress + "/fcr:nodetypes");
    post.setHeader("Content-Type", "text/cnd");
    logger.debug("POST: {}", post.getURI());
    post.setEntity(new FileEntity(cndFile));
    final HttpResponse response = client.execute(post);
    final int status = response.getStatusLine().getStatusCode();
    assertEquals("Expected NO CONTENT response.", NO_CONTENT.getStatusCode(), status);
}

From source file:com.platts.portlet.documentlibrary.DLSetSeoUrl.java

@Override
public void processAction(StrutsPortletAction originalStrutsPortletAction, PortletConfig portletConfig,
        ActionRequest actionRequest, ActionResponse actionResponse)
        throws PortalException, SystemException, IOException {
    LOGGER.info("the process action for struts action DLSetSeoUrl is getting called");
    String uri = ParamUtil.getString(actionRequest, "uri", null);
    String seoURL = ParamUtil.getString(actionRequest, "seoURL", null);
    Long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
    LOGGER.info("uri is " + uri + " seourl is " + seoURL + " fileEntryId " + fileEntryId);
    FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(fileEntryId);
    // sample url http://10.206.111.1:8030/v1/resources/content?uri=/test/holiday.xml&seoUrl=/EditorBios/regina1233johnson.xml
    StringBuilder url = new StringBuilder("http://10.206.111.1:8030/v1/resources/content?uri=");
    url.append(uri).append(StringPool.SLASH).append(fileEntry.getTitle()).append("&seoUrl=").append(seoURL);
    LOGGER.info("the url is " + url.toString());
    PlattsExportUtil exportUtil = new PlattsExportUtil();
    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    File file = exportUtil.getFileFromDLFile(themeDisplay.getUserId(), fileEntry.getFileEntryId(),
            fileEntry.getLatestFileVersion().getVersion());
    //LOGGER.info("the file is " + FileUtils.readFileToString(file));
    FileEntity fileEntity = new FileEntity(file);
    fileEntity.setContentType("application/xml");
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("CPUser", "CPUser22");
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider).build();
    HttpPost postRequest = new HttpPost(url.toString());
    postRequest.setEntity(fileEntity);/*from ww  w. jav  a  2 s  .  c o m*/
    try {
        CloseableHttpResponse response = httpClient.execute(postRequest);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity);
        Document document = SAXReaderUtil.read(responseString);
        String responseText = document.getRootElement().selectSingleNode("/response").getText();
        if (responseText.equalsIgnoreCase("ok")) {
            SessionMessages.add(actionRequest, "seoURLActionSuccess");
            hideDefaultSuccessMessage(actionRequest);
            String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));
            try {
                actionResponse.sendRedirect(redirect);
            } catch (IOException e) {
                LOGGER.error("error redirecting ", e);
            }
        } else {
            SessionErrors.add(actionRequest, "seoURLActionFailure");
            LOGGER.info("the error text is " + responseText);
            actionResponse.setRenderParameter("errorMessage", responseText);
        }
        response.close();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:com.glodon.paas.document.api.FileRestAPITest.java

@Test
public void testUploadFileForOctet() throws IOException {
    java.io.File file = new ClassPathResource("file/testupload.file").getFile();
    String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path";
    HttpPost post = createPost(uploadUrl);
    post.setHeader("content-type", "application/octet-stream");
    FileEntity entity = new FileEntity(file);
    post.setEntity(entity);/*w  ww. j  a va 2 s  .c  o  m*/
    String response = simpleCall(post);
    assertNotNull(response);
    File resultFile = convertString2Obj(response, new TypeReference<File>() {
    });
    assertEquals(file.getName(), resultFile.getFullName());
    assertTrue(file.length() == resultFile.getSize());
}

From source file:com.adobe.ags.curly.controller.ActionRunner.java

@Override
public void run() {
    if (!ApplicationState.getInstance().runningProperty().get()) {
        response.setException(new Exception(ApplicationState.getMessage(ACTIVITY_TERMINATED)));
        return;//from   w w w. j a  v a  2  s .c o m
    }
    response.started().set(true);
    response.updateProgress(0.5);

    if (action.getDelay() > 0) {
        try {
            Thread.sleep(action.getDelay());
        } catch (InterruptedException ex) {
            response.setException(ex);
            return;
        }
    }

    HttpUriRequest request;
    try {
        switch (httpMethod) {
        case GET:
            request = new HttpGet(getURL());
            break;
        case HEAD:
            request = new HttpHead(getURL());
            break;
        case DELETE:
            request = new HttpDelete(getURL());
            break;
        case POST:
            request = new HttpPost(getURL());
            addPostParams((HttpPost) request);
            break;
        case PUT:
            request = new HttpPut(getURL());
            ((HttpPut) request).setEntity(new FileEntity(new File(putFile)));
            break;
        default:
            throw new UnsupportedOperationException(
                    ApplicationState.getMessage(UNSUPPORTED_METHOD_ERROR) + ": " + httpMethod.name());
        }

        addHeaders(request);
        Optional<Exception> ex = processor.apply((CloseableHttpClient client) -> {
            try (CloseableHttpResponse httpResponse = client.execute(request, ConnectionManager.getContext())) {
                response.processHttpResponse(httpResponse, action.getResultType());
                EntityUtils.consume(httpResponse.getEntity());
                return Optional.empty();
            } catch (Exception e) {
                return Optional.of(e);
            }
        });
        if (ex.isPresent()) {
            throw ex.get();
        }
    } catch (Exception ex) {
        Logger.getLogger(ActionRunner.class.getName()).log(Level.SEVERE, null, ex);
        response.setException(ex);
    } finally {
        response.updateProgress(1);
    }
}

From source file:com.glodon.paas.document.api.PerformanceRestAPITest.java

/**
 * octet-stream//from   ww  w .  j  a va  2  s  .c o m
 */
@Test
public void testUploadFileForOctet() throws IOException {
    //        File tempFile=createFile("testUpload");
    java.io.File file = new java.io.File("src/test/resources/file/testupload.file");
    if (!file.exists()) {
        file = new java.io.File(tempUploadFile);
    }
    String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path";
    HttpPost post = createPost(uploadUrl);
    post.setHeader("content-type", "application/octet-stream");
    FileEntity entity = new FileEntity(file);
    post.setEntity(entity);
    String response = simpleCall(post);
    assertNotNull(response);
    File resultFile = convertString2Obj(response, new TypeReference<File>() {
    });
    assertEquals(file.getName(), resultFile.getFullName());
    assertTrue(file.length() == resultFile.getSize());
}

From source file:org.eclipse.packagedrone.testing.server.channel.UploadApiV3Test.java

protected CloseableHttpResponse upload(final URIBuilder uri, final File file)
        throws IOException, URISyntaxException {
    final HttpPut http = new HttpPut(uri.build());

    final String encodedAuth = Base64.getEncoder()
            .encodeToString(uri.getUserInfo().getBytes(StandardCharsets.ISO_8859_1));

    http.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);

    http.setEntity(new FileEntity(file));
    return httpclient.execute(http);
}

From source file:org.metaeffekt.dcc.agent.DccAgentTest.java

@Test
public void cleanInitializeInstallAndConfigure() throws URISyntaxException, IOException, InterruptedException {

    HttpResponse response = httpClient/*from   w w w .j ava 2 s  .co  m*/
            .execute(deploymentBasedEndpointUriBuilder.buildHttpUriRequest(STATE, DEPLOYMENT_ID));
    assertEquals("GET STATE failed", 200, response.getStatusLine().getStatusCode());
    assertEquals(0, getStates(response).size());

    response = httpClient.execute(deploymentBasedEndpointUriBuilder.buildHttpUriRequest(CLEAN, DEPLOYMENT_ID));
    assertEquals("CLEAN failed", 200, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    response = httpClient.execute(deploymentBasedEndpointUriBuilder.buildHttpUriRequest(INITIALIZE,
            DEPLOYMENT_ID, new FileEntity(new File("src/test/resources/test.zip"))));
    assertEquals("INITIALIZE failed", 200, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    response = httpClient.execute(unitBasedEndpointUriBuilder.buildHttpUriRequest(INSTALL, DEPLOYMENT_ID,
            UNIT_ID, PACKAGE_ID, properties));
    assertEquals("INSTALL failed", 200, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    response = httpClient.execute(unitBasedEndpointUriBuilder.buildHttpUriRequest(CONFIGURE, DEPLOYMENT_ID,
            UNIT_ID, PACKAGE_ID, properties));
    assertEquals("CONFIGURE failed", 200, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    response = httpClient.execute(deploymentBasedEndpointUriBuilder.buildHttpUriRequest(STATE, DEPLOYMENT_ID));
    assertEquals("GET STATE failed", 200, response.getStatusLine().getStatusCode());
    Set<String> states = getStates(response);
    assertEquals(3, states.size());
    assertTrue("Does not contain " + INITIALIZE.toString(), states.contains(INITIALIZE.toString()));
    assertTrue("Does not contain " + UNIT_ID + "/" + INSTALL.toString(),
            states.contains(UNIT_ID + "/" + INSTALL.toString()));
    assertTrue("Does not contain " + UNIT_ID + "/" + CONFIGURE.toString(),
            states.contains(UNIT_ID + "/" + CONFIGURE.toString()));

}

From source file:org.talend.librariesmanager.deploy.ArtifactsDeployer.java

protected void installToRemote(File content, MavenArtifact artifact, String type) throws BusinessException {
    URL targetURL;//from  ww w  .j a  v  a 2  s .  c o m
    try {
        String artifactPath = PomUtil.getArtifactPath(artifact);
        if (!artifactPath.endsWith(type)) {
            if (artifactPath.lastIndexOf(".") != -1) {
                artifactPath = artifactPath.substring(0, artifactPath.lastIndexOf(".") + 1) + type;
            } else {
                artifactPath = artifactPath + "." + type;
            }
        }
        String target = repositoryUrl + artifactPath;
        targetURL = new URL(target);
        installToRemote(new FileEntity(content), targetURL);
    } catch (MalformedURLException e) {
        ExceptionHandler.process(e);
    }
}