Example usage for org.apache.commons.net.util Base64 encodeBase64

List of usage examples for org.apache.commons.net.util Base64 encodeBase64

Introduction

In this page you can find the example usage for org.apache.commons.net.util Base64 encodeBase64.

Prototype

public static byte[] encodeBase64(byte[] binaryData) 

Source Link

Document

Encodes binary data using the base64 algorithm but does not chunk the output.

Usage

From source file:de.burlov.ultracipher.core.mail.AuthenticatingSMTPClient.java

/**
 * Authenticate to the SMTP server by sending the AUTH command with the
 * selected mechanism, using the given username and the given password.
 * <p/>// w w w . ja va 2 s . c o  m
 *
 * @return True if successfully completed, false if not.
 * @throws SMTPConnectionClosedException              If the SMTP server prematurely closes the connection as a
 *                                                    result of the client being idle or some other reason
 *                                                    causing the server to send SMTP reply code 421. This
 *                                                    exception may be caught either as an IOException or
 *                                                    independently as itself.
 * @throws java.io.IOException                        If an I/O error occurs while either sending a command to
 *                                                    the server or receiving a reply from the server.
 * @throws java.security.NoSuchAlgorithmException     If the CRAM hash algorithm cannot be instantiated by the
 *                                                    Java runtime system.
 * @throws java.security.InvalidKeyException          If the CRAM hash algorithm failed to use the given
 *                                                    password.
 * @throws java.security.spec.InvalidKeySpecException If the CRAM hash algorithm failed to use the given
 *                                                    password.
 *                                                    *
 */
public boolean auth(AUTH_METHOD method, String username, String password)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    if (!SMTPReply.isPositiveIntermediate(sendCommand(SMTPCommand.AUTH, AUTH_METHOD.getAuthName(method)))) {
        return false;
    }

    if (method.equals(AUTH_METHOD.PLAIN)) {
        // the server sends an empty response ("334 "), so we don't have to
        // read it.
        return SMTPReply.isPositiveCompletion(sendCommand(
                new String(Base64.encodeBase64(("\000" + username + "\000" + password).getBytes()))));
    } else if (method.equals(AUTH_METHOD.CRAM_MD5)) {
        // get the CRAM challenge
        byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(4).trim());
        // get the Mac instance
        Mac hmac_md5 = Mac.getInstance("HmacMD5");
        hmac_md5.init(new SecretKeySpec(password.getBytes(), "HmacMD5"));
        // compute the result:
        byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes();
        // join the byte arrays to form the reply
        byte[] usernameBytes = username.getBytes();
        byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
        System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
        toEncode[usernameBytes.length] = ' ';
        System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length);
        // send the reply and read the server code:
        return SMTPReply.isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(toEncode))));
    } else if (method.equals(AUTH_METHOD.LOGIN)) {
        // the server sends fixed responses (base64("Username") and
        // base64("Password")), so we don't have to read them.
        if (!SMTPReply
                .isPositiveIntermediate(sendCommand(new String(Base64.encodeBase64(username.getBytes()))))) {
            return false;
        }
        return SMTPReply
                .isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(password.getBytes()))));
    } else {
        return false; // safety check
    }
}

From source file:com.adaptris.security.StdOutput.java

/**
 * Return the encrypted message ready for immediate writing to file.
 * /*from   w  w w  .  jav  a 2 s .  com*/
 * @return the bytes ready for writing.
 * @throws AdaptrisSecurityException if an error occurs
 */
private byte[] formatBase64() throws EncryptException {

    DataOutputStream out = null;
    ByteArrayOutputStream byteStream = null;
    byte[] returnBytes = null;
    try {
        byteStream = new ByteArrayOutputStream();
        out = new DataOutputStream(byteStream);
        write(out, getSessionVector());
        write(out, getSessionKey());
        write(out, getEncryptedData(false) == null ? getDecryptedData(false) : getEncryptedData(false));
        write(out, getSignature());
        returnBytes = Base64.encodeBase64(byteStream.toByteArray());
    } catch (Exception e) {
        throw new EncryptException(e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (byteStream != null) {
                byteStream.close();
            }
        } catch (Exception ignored) {
            ;
        }
    }
    return returnBytes;
}

From source file:edu.purdue.cybercenter.dm.web.GlobusControllerTest.java

@Test
@Ignore/*from www  . ja  va  2 s .c  o m*/
public void shouldBeAbleToRunWorkflowWithGlobusTransfer() throws Exception {

    useTestWorkspace("brouder_sylvie");
    login("george.washington", "1234");

    /*
     * upload the test workflow
     */
    MockMultipartFile mockMultipartFile = new MockMultipartFile(WORKFLOW_ZIP_FILE,
            new FileInputStream(WORKFLOW_FILES_DIR + WORKFLOW_ZIP_FILE));
    MockMultipartHttpServletRequestBuilder mockMultipartHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload(
            "/workflows/import").accept(MediaType.ALL).session(httpSession);
    mockMultipartHttpServletRequestBuilder.file(mockMultipartFile);

    ResultActions resultActions = mockMvc.perform(mockMultipartHttpServletRequestBuilder);

    resultActions.andExpect(status().isCreated());

    String content = extractTextarea(resultActions.andReturn().getResponse().getContentAsString());
    Map<String, Object> workflow = Helper.deserialize(content, Map.class);
    assertNotNull("workflow is null", workflow);
    Integer workflowId = (Integer) workflow.get("id");

    /*
     * create a project and an experiment to associate the job for the workflow with
     * while doing that, make sure we save all the IDs associated to post it with the job
     */
    MockHttpServletRequestBuilder mockHttpServletRequestBuilder = post("/projects")
            .content("{\"description\":\"This is a project\",\"name\":\"Project 1\"}")
            .accept(MediaType.APPLICATION_JSON).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
    resultActions.andExpect(status().isCreated());

    content = resultActions.andReturn().getResponse().getContentAsString();
    Map<String, Object> map = Helper.deserialize(content, Map.class);
    Integer projectId = (Integer) map.get("id");

    mockHttpServletRequestBuilder = post("/experiments")
            .content("{\"projectId\":{\"$ref\":\"/projects/" + projectId
                    + "\"},\"name\":\"Experiment 1\",\"description\":\"This is an experiment\"}")
            .accept(MediaType.APPLICATION_JSON).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
    resultActions.andExpect(status().isCreated());

    content = resultActions.andReturn().getResponse().getContentAsString();
    map = Helper.deserialize(content, Map.class);
    Integer experimentId = (Integer) map.get("id");

    /*
     * create a job associated with the project, experiment and workflow we just created
     */
    mockHttpServletRequestBuilder = post("/jobs").param("projectId", projectId.toString())
            .param("experimentId", experimentId.toString()).param("workflowId", workflowId.toString())
            .param("name", "Just a job").accept(MediaType.TEXT_HTML).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
    resultActions.andExpect(status().isOk());

    /*
     * forwarded to job/submit/jobId
     */
    String forwardedUrl = resultActions.andReturn().getResponse().getForwardedUrl();
    mockHttpServletRequestBuilder = post(forwardedUrl).accept(MediaType.TEXT_HTML_VALUE).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    /*
     * redirected to jobs/task/jobId
     */
    String redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();
    mockHttpServletRequestBuilder = get(redirectedUrl).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    /*
     * we're at UT1 in the workflow
     */
    String jobId = redirectedUrl.substring(redirectedUrl.lastIndexOf('/') + 1);
    TaskEntity task = (TaskEntity) resultActions.andReturn().getModelAndView().getModel().get("task");
    String taskId = task.getId();

    String templateId = "305b0f27-e829-424e-84eb-7a8a9ed93e28";
    String templateVersion = "db719406-f665-45cb-a8fb-985b6082b654";

    // For buttton 1
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile");
    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile1");
    uriBuilder.queryParam("multiple", false);

    System.out.println(uriBuilder.build(true).toUriString());

    mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    redirectedUrl = resultActions.andReturn().getResponse().getContentAsString();

    System.out.println("Redirected to: " + redirectedUrl);

    uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize");
    uriBuilder.queryParam("response_type", "code");
    //uriBuilder.queryParam("redirect_uri", "code");
    uriBuilder.queryParam("client_id", username);

    URL url = new URL(uriBuilder.build(true).toUriString());
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    String userpass = username + ":" + password;
    String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/json");
    String res = IOUtils.toString(connection.getInputStream());
    Map<String, Object> responseMap = Helper.deserialize(res, Map.class);
    String code = (String) responseMap.get("code");

    uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback");
    uriBuilder.queryParam("jobId", Integer.parseInt(jobId));
    uriBuilder.queryParam("alias", templateId + ".browsefile1");
    uriBuilder.queryParam("multiple", false);

    String uri = uriBuilder.build(true).toUriString() + "&code=" + code;
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().is3xxRedirection());

    redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();

    System.out.println("Redirected to: " + redirectedUrl);

    // For Button 2
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile");
    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile2");
    uriBuilder.queryParam("multiple", true);

    System.out.println(uriBuilder.build(true).toUriString());

    mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    redirectedUrl = resultActions.andReturn().getResponse().getContentAsString();

    System.out.println("Redirected to: " + redirectedUrl);

    uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize");
    uriBuilder.queryParam("response_type", "code");
    uriBuilder.queryParam("client_id", username);

    url = new URL(uriBuilder.build(true).toUriString());
    connection = (HttpsURLConnection) url.openConnection();
    userpass = username + ":" + password;
    basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/json");
    res = IOUtils.toString(connection.getInputStream());
    responseMap = Helper.deserialize(res, Map.class);
    code = (String) responseMap.get("code");

    // For button 2
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback");
    uriBuilder.queryParam("jobId", Integer.parseInt(jobId));
    uriBuilder.queryParam("alias", templateId + ".browsefile2");
    uriBuilder.queryParam("multiple", true);

    uri = uriBuilder.build(true).toUriString() + "&code=" + code;
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().is3xxRedirection());

    redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();

    System.out.println("Redirected to: " + redirectedUrl);

    // Getting accessToken only from one button
    String accessToken = "";
    String[] urlParts = redirectedUrl.split("&");
    for (String urlPart : urlParts) {
        if (urlPart.contains("accessToken")) {
            String[] accessTokenPair = urlPart.split("=");
            accessToken = accessTokenPair[1];
            break;
        }
    }

    //Button 1
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback");
    uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1);

    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile1");
    uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8")
    uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8"));

    uri = uriBuilder.build(true).toUriString();
    uri = URLDecoder.decode(uri);
    uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8");
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    //Button 2
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback");
    uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1);
    uriBuilder.queryParam(URLEncoder.encode("file[1]", "UTF-8"), FILE_TO_UPLOAD_2);

    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile2");
    uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8")
    uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8"));

    uri = uriBuilder.build(true).toUriString();
    uri = URLDecoder.decode(uri);
    uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8");
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    //For getting Storage Files (an abstract button called browsefile3)
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile");
    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile3");
    uriBuilder.queryParam("multiple", true);
    uriBuilder.queryParam("storageFile", "StorageFile:1");// This file has to be present in the storage file record and in memory

    System.out.println(uriBuilder.build(true).toUriString());

    mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    redirectedUrl = resultActions.andReturn().getResponse().getContentAsString();

    System.out.println("Redirected to: " + redirectedUrl);

    //FileSelect
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback");
    uriBuilder.queryParam("fileId", 1);
    uriBuilder.queryParam(URLEncoder.encode("folder[0]", "UTF-8"), "remote_endpoint/");

    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile3");
    uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8")
    uriBuilder.queryParam("path", URLEncoder.encode("/~/", "UTF-8"));

    uri = uriBuilder.build(true).toUriString();
    uri = URLDecoder.decode(uri, "UTF-8");
    uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8");
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    String multipartBoundary = "------WebKitFormBoundary3xeGH8uP6GWtBfd1";

    MultiPartFileContentBuilder multiPartFileContentBuilder = new MultiPartFileContentBuilder(
            multipartBoundary);
    multiPartFileContentBuilder.addField("autoGenerated", "true");
    multiPartFileContentBuilder.addField("jobId", jobId);
    multiPartFileContentBuilder.addField("taskId", taskId);
    multiPartFileContentBuilder.addField("jsonToServer", "{}");
    multiPartFileContentBuilder.addField("isIframe", "true");
    multiPartFileContentBuilder.addField("experimentId", "");
    multiPartFileContentBuilder.addField("projectId", "");
    multiPartFileContentBuilder
            .addField(templateId + ".name({%22_template_version:%22" + templateVersion + "%22})", "");
    multiPartFileContentBuilder
            .addField(templateId + ".browsefile1({%22_template_version:%22" + templateVersion + "%22})", "");
    multiPartFileContentBuilder
            .addField(templateId + ".browsefile2({%22_template_version:%22" + templateVersion + "%22})", "");
    String taskContent = multiPartFileContentBuilder.build();

    // /rest/objectus post call
    mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/rest/objectus/")
            .param("jobId", jobId).param("taskId", taskId).param(templateId + ".name", "")
            .param(templateId + ".browsefile1", "").param(templateId + ".browsefile2", "")
            .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession);
    mockHttpServletRequestBuilder.content(taskContent);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    multipartBoundary = "------WebKitFormBoundarybiQtLhfKnPwaMgsR";
    multiPartFileContentBuilder = new MultiPartFileContentBuilder(multipartBoundary);
    multiPartFileContentBuilder.addField("jobId", jobId);
    multiPartFileContentBuilder.addField("taskId", taskId);
    multiPartFileContentBuilder.addField("jsonToServer", "{}");
    taskContent = multiPartFileContentBuilder.build();

    // /jobs/task post call
    mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/jobs/task")
            .param("jobId", jobId).param("taskId", taskId).param("ignoreFormData", "true")
            .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession);
    mockHttpServletRequestBuilder.content(taskContent);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().is3xxRedirection());

    redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();

    System.out.println("Redirected to: " + redirectedUrl);

    deleteDatasetEntries(templateId);
}

From source file:com.kylinolap.metadata.model.cube.CubeDesc.java

public String calculateSignature() {
    MessageDigest md = null;//ww w . j  a v a 2s.  co m
    try {
        md = MessageDigest.getInstance("MD5");
        StringBuilder sigString = new StringBuilder();
        sigString.append(this.name).append("|").append(this.factTable).append("|")
                .append(JsonUtil.writeValueAsString(this.cubePartitionDesc)).append("|")
                .append(JsonUtil.writeValueAsString(this.dimensions)).append("|")
                .append(JsonUtil.writeValueAsString(this.measures)).append("|")
                .append(JsonUtil.writeValueAsString(this.rowkey)).append("|")
                .append(JsonUtil.writeValueAsString(this.hbaseMapping));

        byte[] signature = md.digest(sigString.toString().getBytes());
        return new String(Base64.encodeBase64(signature));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Failed to calculate signature");
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Failed to calculate signature");
    }
}

From source file:com.ibm.iotf.client.api.APIClient.java

private HttpResponse connect(String httpOperation, String url, String jsonPacket,
        List<NameValuePair> queryParameters) throws URISyntaxException, IOException {
    final String METHOD = "connect";

    StringEntity input = null;/*from w w w .  j a va  2s. c om*/
    if (jsonPacket != null) {
        input = new StringEntity(jsonPacket, StandardCharsets.UTF_8);
    }

    String encodedString = null;
    if (!isQuickstart) {
        byte[] encoding = Base64.encodeBase64(new String(authKey + ":" + authToken).getBytes());
        encodedString = new String(encoding);
    }
    switch (httpOperation) {
    case "post":
        return casePostFromConnect(queryParameters, url, METHOD, input, encodedString);
    case "put":
        return casePutFromConnect(queryParameters, url, METHOD, input, encodedString);
    case "get":
        return caseGetFromConnect(queryParameters, url, METHOD, input, encodedString);
    case "delete":
        return caseDeleteFromConnect(queryParameters, url, METHOD, input, encodedString);
    case "patch":
        return casePatchFromConnect(queryParameters, url, METHOD, input, encodedString);

    }
    return null;

}

From source file:com.ibm.iotf.client.AbstractClient.java

/**
 * @param organization  Organization ID (Either "quickstart" or the registered organization ID)
 * @param domain      Domain of the Watson IoT Platform, for example internetofthings.ibmcloud.com
 * @param deviceType   Device Type/*w  w  w.  j a va  2 s  . c o  m*/
 * @param deviceId      Device ID
 * @param eventName      Name of the Event
 * @param device       Boolean value indicating whether the request is originated from device or application
 * @param authKey      Authentication Method
 * @param authToken      Authentication Token to securely post this event (Can be null or empty if its quickstart)
 * @param payload      The message to be published
 * @return int         HTTP code indicating the status of the HTTP request
 * @throws Exception   throws exception when http post fails
 */
protected static int publishEventsThroughHttps(String organization, String domain, String deviceType,
        String deviceId, String eventName, boolean device, String authKey, String authToken, Object payload)
        throws Exception {

    final String METHOD = "publishEventsThroughHttps";

    validateNull("Organization ID", organization);
    validateNull("Domain", domain);
    validateNull("Device Type", deviceType);
    validateNull("Device ID", deviceId);
    validateNull("Event Name", eventName);
    if (QUICK_START.equalsIgnoreCase(organization) == false) {
        validateNull("Authentication Method", authKey);
        validateNull("Authentication Token", authToken);
    }

    StringBuilder sb = new StringBuilder();

    // Form the URL
    if (QUICK_START.equalsIgnoreCase(organization)) {
        sb.append("http://");
    } else {
        sb.append("https://");
    }
    sb.append(organization).append(".messaging.internetofthings.ibmcloud.com/api/v0002");

    if (device == true) {
        sb.append("/device");
    } else {
        sb.append("/application");
    }
    sb.append("/types/").append(deviceType).append("/devices/").append(deviceId).append("/events/")
            .append(eventName);

    LoggerUtility.fine(CLASS_NAME, METHOD, "ReST URL::" + sb.toString());
    BufferedReader br = null;

    // Create the payload message in Json format
    JsonObject message = (JsonObject) gson.toJsonTree(payload);
    StringEntity input = new StringEntity(message.toString(), StandardCharsets.UTF_8);

    // Create the Http post request
    HttpPost post = new HttpPost(sb.toString());
    post.setEntity(input);
    post.addHeader("Content-Type", "application/json");
    post.addHeader("Accept", "application/json");

    if (QUICK_START.equalsIgnoreCase(organization) == false) {
        byte[] encoding = Base64.encodeBase64(new String(authKey + ":" + authToken).getBytes());
        String encodedString = new String(encoding);
        post.addHeader("Authorization", "Basic " + encodedString);
    }

    try {

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);

        HttpClient client = HttpClientBuilder.create().setSSLContext(sslContext).build();

        HttpResponse response = client.execute(post);

        int httpCode = response.getStatusLine().getStatusCode();
        if (httpCode >= 200 && httpCode < 300) {
            return httpCode;
        }

        /**
         * Looks like some error so log the header and response
         */
        System.out.println("Looks like some error, so log the header and response");
        StringBuilder log = new StringBuilder("HTTP Code: " + httpCode);
        log.append("\nURL: ").append(sb.toString()).append("\nHeader:\n");
        Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            log.append(headers[i].getName()).append(' ').append(headers[i].getValue()).append('\n');
        }
        log.append("\nResponse \n");
        br = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
        log.append(br.readLine());
        LoggerUtility.severe(CLASS_NAME, METHOD, log.toString());

        return httpCode;
    } catch (IOException e) {
        LoggerUtility.severe(CLASS_NAME, METHOD, e.getMessage());
        throw e;
    } finally {
        if (br != null) {
            br.close();
        }
    }
}

From source file:com.znsx.cms.service.impl.DeviceManagerImpl.java

@Override
public List<PtsDvrVO> listDvrByCcs(String ccsId, int start, int limit) {
    List<Dvr> dvrs = dvrDAO.listDvrByCcs(ccsId, start, limit);
    // ?//w ww.  j a  v a 2  s.c o  m
    List<String> dvrIds = new ArrayList<String>();
    for (Dvr dvr : dvrs) {
        dvrIds.add(dvr.getId());
    }
    List<Camera> cameras = cameraDAO.listDvrsCamera(dvrIds);
    // ???
    List<Camera> removeList = new LinkedList<Camera>();
    // 
    List<PtsDvrVO> rtnList = new LinkedList<PtsDvrVO>();
    try {
        for (Dvr dvr : dvrs) {
            // ?
            PtsDvrVO dvrVO = new PtsDvrVO();
            VideoDeviceProperty property = dvr.getProperty();
            if (null == property) {
                throw new BusinessException(ErrorCode.RESOURCE_NOT_FOUND,
                        "DVR[" + dvr.getId() + "] property not found !");
            }
            if (null != property.getExpand()) {
                dvrVO.setExpand(new String(Base64.encodeBase64(property.getExpand().getBytes("utf8")), "utf8"));
            }
            dvrVO.setHeartCycle(property.getHeartCycle() != null ? property.getHeartCycle().toString() : "");
            dvrVO.setLanIp(dvr.getLanIp());
            dvrVO.setMaxConnect(dvr.getMaxConnect() != null ? dvr.getMaxConnect().toString() : "");
            dvrVO.setPassword(property.getPassword());
            dvrVO.setPort(dvr.getPort());
            dvrVO.setProtocol(property.getProtocol());
            dvrVO.setStandardNumber(dvr.getStandardNumber());
            dvrVO.setTransport(dvr.getTransport());
            dvrVO.setUserName(property.getUserName());

            // ?
            List<PtsCameraVO> cameraVOs = new LinkedList<PtsCameraVO>();
            for (Camera camera : cameras) {
                if (camera.getParent().getId().equals(dvr.getId())) {
                    PtsCameraVO cameraVO = new PtsCameraVO();
                    VideoDeviceProperty cameraProperty = camera.getProperty();
                    if (null == cameraProperty) {
                        throw new BusinessException(ErrorCode.RESOURCE_NOT_FOUND,
                                "Camera[" + camera.getId() + "] property not found !");
                    }
                    cameraVO.setChannelNumber(
                            camera.getChannelNumber() != null ? camera.getChannelNumber().toString() : "");
                    cameraVO.setCRSStandardNumber(
                            camera.getCrs() != null ? camera.getCrs().getStandardNumber() : "");
                    cameraVO.setStreamType(cameraProperty.getStreamType());
                    cameraVO.setMSSStandardNumber(
                            camera.getMss() != null ? camera.getMss().getStandardNumber() : "");
                    cameraVO.setRMSStandardNumber(
                            camera.getRms() != null ? camera.getRms().getStandardNumber() : "");
                    cameraVO.setStandardNumber(camera.getStandardNumber());
                    cameraVO.setStoreType(
                            cameraProperty.getStoreType() != null ? cameraProperty.getStoreType().toString()
                                    : "");
                    if (cameraProperty.getExpand() != null) {
                        String expend = cameraProperty.getExpand();
                        String encode = new String(Base64.encodeBase64(expend.getBytes("utf8")), "utf8");
                        cameraVO.setExpand(encode);

                    } else {
                        cameraVO.setExpand("");
                    }

                    cameraVOs.add(cameraVO);
                    // ???
                    removeList.add(camera);
                }
            }
            cameras.removeAll(removeList);
            removeList.clear();

            dvrVO.setCameras(cameraVOs);
            rtnList.add(dvrVO);
        }
    } catch (UnsupportedEncodingException e) {
        throw new BusinessException(ErrorCode.ENCODING_ERROR, e.getMessage());
    }
    return rtnList;
}

From source file:com.znsx.cms.web.controller.TmDeviceController.java

@InterfaceDescription(logon = false, method = "Get_Vms_Command", cmd = "3017")
@RequestMapping("/get_vms_command.xml")
public void getVmsCommand(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Document requestDoc = RequestUtil.parseRequest(request);
    Element reqRoot = requestDoc.getRootElement();
    Element e = reqRoot.getChild("CommandId");
    if (null == e) {
        throw new BusinessException(ErrorCode.PARAMETER_NOT_FOUND, "missing [CommandId]");
    }//from   www  .j  av  a 2 s .c  o  m

    String commandId = e.getText();
    if (StringUtils.isBlank(commandId)) {
        throw new BusinessException(ErrorCode.PARAMETER_NOT_FOUND, "missing [CommandId]");
    }

    CmsCommand command = tmDeviceManager.getCmsCommand(commandId);
    Blob blob = command.getContent();
    long length = blob.length();
    if (length >= Integer.MAX_VALUE) {
        throw new BusinessException(ErrorCode.ERROR,
                "Image length too long, can not encode by BASE64 encoding !");
    }
    int intLength = (int) length;

    BaseDTO dto = new BaseDTO();
    dto.setCmd("3017");
    dto.setMethod("Get_Vms_Command");
    Document doc = new Document();
    Element root = ElementUtil.createElement("Response", dto);
    doc.setRootElement(root);

    Element commandElement = new Element("Command");
    commandElement
            .setText(new String(Base64.encodeBase64(command.getContent().getBytes(1, intLength)), "utf8"));
    root.addContent(commandElement);

    writePageWithContentLength(response, doc);
}

From source file:com.ibm.iotf.client.api.APIClient.java

/**
 * Create a draft schema definition//from   w  w w . j  a v a  2s .c  om
 * 
 * @param schemaFile File containing the schema file
 *      
 * @param schemaName String containing the schema name
 *      
 * @param schemaDescription String containing the description of schema
 * 
 * @param schemaType String containing the schema type (like for e.g. json-schema)
 * 
 * @return If successful, JsonObject response from Watson IoT Platform.
 * 
 * @throws IoTFCReSTException Failure in creating a draft schema definition
 */
public JsonObject addDraftSchemaDefinition(File schemaFile, String schemaName, String schemaDescription,
        String schemaType) throws IoTFCReSTException {
    final String METHOD = "addDraftSchemaDefinition";
    HttpResponse response = null;
    JsonElement jsonResponse = null;
    int code = 0;
    String method = "post";
    try {
        StringBuilder sb = new StringBuilder("https://");
        sb.append(orgId).append('.').append(this.domain).append(BASIC_API_V0002_URL).append("/draft/schemas/");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        builder.addBinaryBody("schemaFile", new FileInputStream(schemaFile),
                org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM, schemaFile.getName());

        builder.addTextBody("description", schemaDescription);
        builder.addTextBody("name", schemaName);

        URIBuilder uri = new URIBuilder(sb.toString());

        HttpPost post = new HttpPost(uri.build());

        byte[] encoding = Base64.encodeBase64(new String(authKey + ":" + authToken).getBytes());
        String encodedString = new String(encoding);

        post.setHeader("Authorization", "Basic " + encodedString);

        HttpClient client = HttpClientBuilder.create().useSystemProperties().setSslcontext(sslContext).build();
        HttpEntity multipart = builder.build();
        post.setEntity(multipart);

        response = client.execute(post);
        code = response.getStatusLine().getStatusCode();
        String result = this.readContent(response, METHOD);
        jsonResponse = new JsonParser().parse(result);
        if (code == 201 || code == 400 || code == 401 || code == 403 || code == 404 || code == 500) {
            if (code == 201) {
                //Success
                return jsonResponse.getAsJsonObject();
            } else {
                String reason = null;
                switch (code) {
                case 400:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_400;
                    break;
                case 401:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_401;
                    break;
                case 403:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_403;
                    break;
                case 500:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_500;
                    break;
                }
                throw new IoTFCReSTException(method, sb.toString(), null, code, reason, jsonResponse);
            }
        } else {
            throw new IoTFCReSTException(code, "Unexpected error", jsonResponse);
        }
    } catch (IoTFCReSTException e) {
        throw e;
    } catch (Exception e) {
        // This includes JsonSyntaxException
        IoTFCReSTException ex = new IoTFCReSTException(
                "Failure in creating a draft schema definition " + "::" + e.getMessage());
        ex.initCause(e);
        throw ex;
    }
}

From source file:org.apache.giraph.comm.netty.SaslNettyServer.java

/**
 * Encode a byte[] identifier as a Base64-encoded string.
 *
 * @param identifier identifier to encode
 * @return Base64-encoded string//from ww  w.jav  a2s  .  com
 */
static String encodeIdentifier(byte[] identifier) {
    return new String(Base64.encodeBase64(identifier));
}