Beispiel #1
0
 static void writeAsBase64ToFile(Path filename, int numKeys, int numValuesPerKeys)
     throws IOException {
   BufferedWriter bw = Files.newBufferedWriter(filename, Charset.defaultCharset());
   for (int i = 0; i < numKeys; ++i) {
     bw.write(DatatypeConverter.printBase64Binary(makeKey(i)));
     for (int j = 0; j < numValuesPerKeys; ++j) {
       bw.append(' ').write(DatatypeConverter.printBase64Binary(makeValue(j)));
     }
     bw.newLine();
   }
   bw.close();
 }
 private static String getEncodedHistogram(Histogram combined) {
   ByteBuffer targetBuffer = ByteBuffer.allocate(combined.getNeededByteBufferCapacity());
   int compressedLength =
       combined.encodeIntoCompressedByteBuffer(targetBuffer, Deflater.BEST_COMPRESSION);
   byte[] compressedArray = Arrays.copyOf(targetBuffer.array(), compressedLength);
   return DatatypeConverter.printBase64Binary(compressedArray);
 }
  /**
   * Changes hexadecimal to base 64
   *
   * @param hex the hexadecimal value to convert
   * @return the base64 value
   */
  public String HexToBase64(String hex) {

    byte[] byteArray = DatatypeConverter.parseHexBinary(hex);
    String base64String = DatatypeConverter.printBase64Binary(byteArray);

    return base64String;
  }
  /**
   * Constructor. The raw message body will be Base64-encoded because some bytes are unsafe to use
   * with the IoT Hub HTTPS batch message format.
   *
   * @param body the raw message body.
   * @throws IllegalArgumentException if body is null.
   * @throws SizeLimitExceededException if body has a size of more than 255 kb.
   */
  public IotHubServiceboundMessage(byte[] body) throws SizeLimitExceededException {
    // Codes_SRS_IOTHUBSERVICEBOUNDMESSAGE_11_017: [If body is null, the constructor shall throw an
    // IllegalArgumentException.]
    if (body == null) {
      throw new IllegalArgumentException("Message body cannot be 'null'.");
    }
    // Codes_SRS_IOTHUBSERVICEBOUNDMESSAGE_11_001: [The constructor shall Base64-encode the
    // message.]
    byte[] base64EncodedBody =
        DatatypeConverter.printBase64Binary(body)
            .getBytes(IotHubMessage.IOTHUB_MESSAGE_DEFAULT_CHARSET);
    // Codes_SRS_IOTHUBSERVICEBOUNDMESSAGE_11_007: [If the body length is greater than 255 kb after
    // Base64-encoding it, the constructor shall throw a SizeLimitExceededException.]
    if (base64EncodedBody.length > SERVICEBOUND_MESSAGE_MAX_SIZE_BYTES) {
      String errMsg =
          String.format(
              "Service-bound message body "
                  + "cannot exceed %d bytes after being "
                  + "Base64-encoded.\n",
              SERVICEBOUND_MESSAGE_MAX_SIZE_BYTES);
      throw new SizeLimitExceededException(errMsg);
    }

    // Codes_SRS_IOTHUBSERVICEBOUNDMESSAGE_11_006: [The constructor shall save the content-type as
    // 'application/octet-stream'.]
    this.msg = new IotHubMessage(base64EncodedBody);
    this.base64Encoded = true;
  }
Beispiel #5
0
  public void recognizeFromFileExplicit() throws Exception {
    File pcmFile = new File(testFileName);
    HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection();

    // construct params
    JSONObject params = new JSONObject();
    params.put("format", "wav");
    params.put("rate", 16000);
    params.put("channel", "1");
    params.put("token", token);
    params.put("cuid", cuid);
    params.put("len", pcmFile.length());
    params.put("speech", DatatypeConverter.printBase64Binary(loadFile(pcmFile)));

    // add request header
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

    conn.setDoInput(true);
    conn.setDoOutput(true);

    // send request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(params.toString());
    wr.flush();
    wr.close();

    printResponse(conn);
  }
Beispiel #6
0
  /**
   * Returns the contents of an attachment
   *
   * @param assetId The ID of the asset owning the attachment
   * @param attachmentId The ID of the attachment
   * @return The input stream for the attachment
   * @throws IOException
   * @throws RequestFailureException
   */
  public InputStream getAttachment(String assetId, String attachmentId)
      throws IOException, BadVersionException, RequestFailureException {
    // Get the URL for the attachment
    Attachment attachment = getAttachmentMetaData(assetId, attachmentId);

    // accept license for type CONTENT
    HttpURLConnection connection;
    if (attachment.getType() == Attachment.Type.CONTENT) {
      connection = createHttpURLConnection(attachment.getUrl() + "?license=agree");
    } else {
      connection = createHttpURLConnection(attachment.getUrl());
    }

    // If the attachment was a link and we have a basic auth userid + password specified
    // we are attempting to access the files staged from a protected site so authorise for it
    if (attachment.getLinkType() == LinkType.DIRECT) {
      if ((loginInfo.getAttachmentBasicAuthUserId() != null)
          && (loginInfo.getAttachmentBasicAuthPassword() != null)) {
        String userpass =
            loginInfo.getAttachmentBasicAuthUserId()
                + ":"
                + loginInfo.getAttachmentBasicAuthPassword();
        String basicAuth =
            "Basic "
                + javax.xml.bind.DatatypeConverter.printBase64Binary(
                    userpass.getBytes(Charset.forName("UTF-8")));
        connection.setRequestProperty("Authorization", basicAuth);
      }
    }

    connection.setRequestMethod("GET");
    testResponseCode(connection);
    return connection.getInputStream();
  }
 private String getBasicAuthentication() {
   String token = this.user + ":" + this.password;
   try {
     return "Basic " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
   } catch (UnsupportedEncodingException ex) {
     throw new IllegalStateException("Cannot encode with UTF-8", ex);
   }
 }
Beispiel #8
0
  @Override
  public String text() {

    if (renderB64) {
      return "data:image/png;base64," + DatatypeConverter.printBase64Binary(fileBytes());
    } else {
      return url();
    }
  }
 @Override
 public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
   String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
   try {
     headerParams.put(
         "Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8")));
   } catch (UnsupportedEncodingException e) {
     throw new RuntimeException(e);
   }
 }
 private static String asString(final Object primitive) {
   // TODO: improve 'string' conversion; maybe consider only String properties
   if (primitive instanceof String) {
     return (String) primitive;
   } else if (primitive instanceof Calendar) {
     return DatatypeConverter.printDateTime((Calendar) primitive);
   } else if (primitive instanceof byte[]) {
     return DatatypeConverter.printBase64Binary((byte[]) primitive);
   } else {
     return primitive.toString();
   }
 }
Beispiel #11
0
  public static String getBase64FromNBT(NBTTagCompound compound) {
    byte[] worldDataByteArray;

    try {
      worldDataByteArray = CompressedStreamTools.compress(compound);
      return DatatypeConverter.printBase64Binary(worldDataByteArray);
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
Beispiel #12
0
 public static String safeBase64(String link) {
   try {
     String original =
         DatatypeConverter.printBase64Binary(
             MessageDigest.getInstance("SHA1").digest(link.getBytes()));
     String safe = original.replaceAll("\\+", "-");
     safe = safe.replaceAll("\\/", "_");
     return safe.replaceAll("=", ",");
   } catch (Exception e) {
     LOG.error("Unable to digest link for content type of url", e);
   }
   return null;
 }
  /**
   * Writes out the certificates of all the key store entries. For debugging purposes.
   *
   * @param certformat If "rawcert", writes out the text information (long) about the certificates.
   *     If "enccert" [default], writes out the certificates in base64 (short).
   */
  public void printKeyStoreCertificates(String certformat) {
    try {
      String alias = null;
      Certificate cert;

      for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
        alias = aliases.nextElement();
        System.out.println("");
        if (alias.startsWith(aliasPrefix)) {
          System.out.print(" * ===== ");
        } else {
          System.out.print("   ===== ");
        }
        System.out.println(alias);
        // entry = (TrustedCertificateEntry) keyStore.getEntry(alias, null);
        System.out.print("   Creation Date:    ");
        System.out.println(keyStore.getCreationDate(alias));
        System.out.print("   Certificate type: ");
        cert = keyStore.getCertificate(alias);
        System.out.print(cert.getType());
        if (keyStore.isKeyEntry(alias)) {
          System.out.println("                          (details hidden)");
          continue;
        } else {
          System.out.println("");
        }

        if (keyStore.isCertificateEntry(alias)) {
          if ((certformat != null) && (certformat.equals("rawcert"))) {
            System.out.println(cert.toString());
          } else // enccert, encoded certificate
          {
            // String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(data);
            // byte[] decoded = javax.xml.bind.DatatypeConverter.parseBase64Binary(encoded);
            System.out.println(DatatypeConverter.printBase64Binary(cert.getEncoded()));
          }
        }
        System.out.flush();
      } // end for

      System.out.println("");
      System.out.print("Number of entries in key store: ");
      System.out.println(keyStore.size());
      System.out.flush();

    } catch (Exception e) {
      System.err.println("ERROR: GFIPMKeystore.printKeyStoreContents failed: ");
      System.err.println(e.toString());
      System.err.flush();
    }
  } // end printKeyStoreCertificates
Beispiel #14
0
 /**
  * Do get.
  *
  * @param url the url
  * @param client the client
  * @return the http response
  */
 private HttpResponse doGet(String url, DefaultHttpClient client) {
   log.info("Doing GET request in RESTInvoker");
   HttpResponse response = null;
   try {
     HttpGet getRequest = new HttpGet("url");
     String encoding = DatatypeConverter.printBase64Binary("user:passwd".getBytes("UTF-8"));
     getRequest.addHeader("authorization", "Basic " + encoding);
     getRequest.addHeader("accept", "application/json");
     response = client.execute(getRequest);
   } catch (IOException e) {
     log.error("Exception in GET request of REST Invoker: ", e);
   }
   return response;
 }
  public static String generateHMacSHA256(final String key, final String data)
      throws InvalidKeyException, NoSuchAlgorithmException {
    Assert.notNull(key, "key is required");
    Assert.notNull(data, "data is required");

    final Mac hMacSHA256 = Mac.getInstance("HmacSHA256");
    byte[] hmacKeyBytes = key.getBytes(StandardCharsets.UTF_8);
    final SecretKeySpec secretKey = new SecretKeySpec(hmacKeyBytes, "HmacSHA256");
    hMacSHA256.init(secretKey);
    byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
    byte[] res = hMacSHA256.doFinal(dataBytes);

    return DatatypeConverter.printBase64Binary(res);
  }
Beispiel #16
0
  /**
   * Adds authentication credentials to the connection.
   *
   * <p>For basic auth credentials, both username *and* password must be set in order for this to
   * happen and it is an error for only one to be set.
   *
   * @throws AssertionError if precisely one of {username, password} is set.
   */
  private void addAuthToConnection(HttpURLConnection connection) {

    if (loginInfo.getUserId() != null && loginInfo.getPassword() == null) {
      throw new AssertionError(
          "userId is set but password is null. Either both or neither must be set.");
    }
    if (loginInfo.getUserId() == null && loginInfo.getPassword() != null) {
      throw new AssertionError(
          "password is set but userId is null. Either both or neither must be set.");
    }

    // The username and password are added to the connection as a basic auth
    // Authorization header
    if (loginInfo.getUserId() != null && loginInfo.getPassword() != null) {
      String userpass = loginInfo.getUserId() + ":" + loginInfo.getPassword();
      String basicAuth =
          "Basic "
              + javax.xml.bind.DatatypeConverter.printBase64Binary(
                  userpass.getBytes(Charset.forName("UTF-8")));
      connection.setRequestProperty("Authorization", basicAuth);
    }

    // If a proxy is defined and a userid and password are defined add the proxy
    // authorisation to the connection.
    if ((loginInfo.getProxy() != null)
        && (loginInfo.getProxy().getProxyUserid() != null)
        && (loginInfo.getProxy().getProxyPassword() != null)) {
      String proxyUser = loginInfo.getProxy().getProxyUserid();
      String proxyPwd = loginInfo.getProxy().getProxyPassword();
      String proxyUidAndPwd = proxyUser + ":" + proxyPwd;
      String proxyBasicAuth =
          "Basic "
              + javax.xml.bind.DatatypeConverter.printBase64Binary(
                  proxyUidAndPwd.getBytes(Charset.forName("UTF-8")));
      connection.setRequestProperty("Proxy-Authorization", proxyBasicAuth);
    }
  }
Beispiel #17
0
 private static String objectToString(Serializable o) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   try {
     ObjectOutputStream oos = new ObjectOutputStream(baos);
     try {
       oos.writeObject(o);
       return javax.xml.bind.DatatypeConverter.printBase64Binary(baos.toByteArray());
     } finally {
       baos.close();
       oos.close();
     }
   } catch (Exception e) {
     Logger.logError("Failed to write object to string" + o, e);
     return null;
   }
 }
  /**
   * Get base64 representation of selected hash algorithm of given file
   *
   * @param filepath
   * @param hashAlgo
   * @return calculated hash value
   */
  public String getBase64FileHash(String filepath, ImfHashAlgorithm hashAlgo) {
    try (FileInputStream inputStream = new FileInputStream(filepath)) {
      MessageDigest digest;
      if (hashAlgo == ImfHashAlgorithm.SHA256) digest = MessageDigest.getInstance("SHA-256");
      else digest = MessageDigest.getInstance("SHA-1");

      byte[] bytesBuffer = new byte[1024];
      int bytesRead = -1;
      while ((bytesRead = inputStream.read(bytesBuffer)) != -1) {
        digest.update(bytesBuffer, 0, bytesRead);
      }
      byte[] hashedBytes = digest.digest();
      return DatatypeConverter.printBase64Binary(hashedBytes);
    } catch (NoSuchAlgorithmException | IOException ex) {
      return null;
    }
  }
Beispiel #19
0
  public String encode(String password) {
    try {
      byte[] salt = props.getString("user.password.salt", "salt").getBytes();
      byte[] digest = password.getBytes();
      for (int i = 0; i < 25; i++) {
        byte[] source = new byte[digest.length + salt.length];
        System.arraycopy(digest, 0, source, 0, digest.length);
        System.arraycopy(salt, 0, source, digest.length, salt.length);

        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(source);
        digest = messageDigest.digest();
      }
      return DatatypeConverter.printBase64Binary(digest);
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException("error", e);
    }
  }
Beispiel #20
0
  public static void main(String[] args) {
    Map<String, String> environ = System.getenv();
    JSONObject json = new JSONObject();
    for (Map.Entry<String, String> entry : environ.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();
      System.out.println(key + '=' + value);
      json.put(key, value);
    }

    String json_string = json.toString();
    try {
      byte[] json_bytes = json_string.getBytes("UTF-8");
      String base64 = DatatypeConverter.printBase64Binary(json_bytes);
      System.out.println(base64);
    } catch (java.io.UnsupportedEncodingException exc) {
      exc.printStackTrace();
    }
  }
Beispiel #21
0
 /**
  * Do post.
  *
  * @param url the url
  * @param payload the payload
  * @param httpClient the http client
  * @return the http response
  */
 private HttpResponse doPost(String url, String payload, DefaultHttpClient httpClient) {
   log.info("\n Doing POST request in RESTInvoker for URL>>>>> " + url);
   log.info("\n Sending payload####### " + payload);
   HttpResponse response = null;
   try {
     HttpPost post = new HttpPost(url);
     String encoding =
         DatatypeConverter.printBase64Binary(WSConstants.AUTHENTICATION_WS.getBytes("UTF-8"));
     StringEntity input = new StringEntity(payload);
     input.setContentType("application/json");
     post.setEntity(input);
     post.addHeader("content-type", "application/json");
     post.addHeader("authorization", "Basic " + encoding);
     post.addHeader("accept", "application/json");
     response = httpClient.execute(post);
   } catch (IOException e) {
     log.error("Exception in POST request: ", e);
   }
   return response;
 }
  public Boolean setVariable(Integer variableId, Integer valueToSet)
      throws MalformedURLException, IOException {

    URL url =
        new URL(
            "http://"
                + this.address
                + "/rest/vars/set/2/"
                + variableId.toString()
                + "/"
                + valueToSet.toString());
    URLConnection connection = url.openConnection();
    String userpass = this.userName + ":" + this.password;
    String basicAuth =
        "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
    connection.setRequestProperty("Authorization", basicAuth);
    connection.setRequestProperty("Accept", "application/xml");
    InputStream response = connection.getInputStream();
    String responseContents = streamToString(response);
    return true;
  }
  public GHContentUpdateResponse createContent(
      String content, String commitMessage, String path, String branch) throws IOException {
    Requester requester =
        new Requester(root)
            .with("path", path)
            .with("message", commitMessage)
            .with("content", DatatypeConverter.printBase64Binary(content.getBytes()))
            .method("PUT");

    if (branch != null) {
      requester.with("branch", branch);
    }

    GHContentUpdateResponse response =
        requester.to(getApiTailUrl("contents/" + path), GHContentUpdateResponse.class);

    response.getContent().wrap(this);
    response.getCommit().wrapUp(this);

    return response;
  }
Beispiel #24
0
 @Override
 public void onNext(final SuspendedTask task) {
   checkMsgOrder(task);
   state = DriverState.RESUME;
   try {
     task.getActiveContext()
         .submitTask(
             TaskConfiguration.CONF
                 .set(TaskConfiguration.IDENTIFIER, task.getId() + "_RESUMED")
                 .set(TaskConfiguration.TASK, NoopTask.class)
                 .set(TaskConfiguration.ON_MESSAGE, NoopTask.DriverMessageHandler.class)
                 .set(TaskConfiguration.ON_SUSPEND, NoopTask.TaskSuspendHandler.class)
                 .set(TaskConfiguration.ON_CLOSE, NoopTask.TaskCloseHandler.class)
                 .set(TaskConfiguration.ON_TASK_STOP, NoopTask.TaskStopHandler.class)
                 .set(TaskConfiguration.ON_SEND_MESSAGE, NoopTask.class)
                 .set(TaskConfiguration.MEMENTO, DatatypeConverter.printBase64Binary(HELLO_STR))
                 .build());
   } catch (final BindException ex) {
     LOG.log(Level.SEVERE, "Task configuration error", ex);
     throw new DriverSideFailure("Task configuration error", ex);
   }
 }
 /**
  * 本方法可對字串message(Plaintext, 明文)加密,然後將加密後的字串 (Ciphertext, 密文)傳回。
  *
  * @param key : 加密金鑰
  * @param message : 明文,即要加密的字串
  * @return 加密後的
  * @throws NoSuchPaddingException
  * @throws NoSuchAlgorithmException
  * @throws InvalidKeyException
  * @throws BadPaddingException
  * @throws IllegalBlockSizeException
  * @throws Throwable
  */
 public static String encryptString(String message) {
   //  DES : Data Encryption Standard, 一種對稱式加密演算法。
   //           美國聯邦政府於1976年定為聯邦資料處理標準(FIPS),它的
   //           金鑰則必須是7個位元組、加密區塊(Cipher Block)固定為8個位元組。
   //           DES目前已被視為是一種不安全的演算法。
   //  AES : Advanced Encryption Standard, 一種對稱式加密演算法。
   //           (美國聯邦政府於2001年納入FIPS 140-2標準),此種演算法
   //           的Cipher Block固定為16個位元組。金鑰則必須是16個位元組、
   //           24個位元組或32個位元組(即128個位元、192個位元或256個位元)。
   //  ECB : Electronic CookBook, 一種資料的加密方式,這種加密方式採取
   //           每個區塊(如8個或16個位元組)獨立加密,即加密任ㄧ區塊時與其它區塊
   //           無關。獨立壓縮有優點也有缺點。
   //           優點為可以由多個處理器來平行處理ㄧ個很大的資料。缺點為如果資料
   //           的內容有重複出現的部分,而且重複資料的長度剛好與加密區塊等長,
   //           則這些重複出現的部分經過加密後會出現相同的結果。
   //  PKCS5Padding: 如果要加密的資料不是8個(如DES加密演算法)或
   //           16個(如AES加密演算法)位元組的整數倍,則必須在欲加密資料的
   //           尾端加入若干個位元組來湊成整數倍。PKCS5Padding是一種
   //           補足不足位元組的方法。
   String encryptedString = "";
   try {
     Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
     SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");
     cipher.init(Cipher.ENCRYPT_MODE, secretKey);
     encryptedString = DatatypeConverter.printBase64Binary(cipher.doFinal(message.getBytes()));
   } catch (InvalidKeyException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (NoSuchPaddingException e) {
     e.printStackTrace();
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   }
   return encryptedString;
 }
Beispiel #26
0
  public static String encrypt(final String secret, SecretKey secretKey) {

    String strCipherText = null;
    try {
      final byte[] plaintext = secret.getBytes();
      final byte[] nonceAndCiphertext = new byte[NONCE_SIZE + plaintext.length];

      Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
      int offset = generateRandomNonce(nonceAndCiphertext, 0, NONCE_SIZE);
      final IvParameterSpec nonceIV =
          generateIVFromNonce(nonceAndCiphertext, 0, NONCE_SIZE, cipher.getBlockSize());

      cipher.init(Cipher.ENCRYPT_MODE, secretKey, nonceIV);
      offset += cipher.doFinal(plaintext, 0, plaintext.length, nonceAndCiphertext, offset);
      if (offset != nonceAndCiphertext.length) {
        throw new IllegalStateException("Something wrong during encryption");
      }
      strCipherText = DatatypeConverter.printBase64Binary(nonceAndCiphertext);
    } catch (final GeneralSecurityException e) {
      throw new IllegalStateException("Missing basic functionality from Java runtime", e);
    }

    return strCipherText;
  }
  private String callNeo(String query) {
    ResteasyClient client = new ResteasyClientBuilder().build();
    ResteasyWebTarget target = client.target("http://" + getStrNeoHost() + ":7474/db/data/cypher");
    String token = "neo4j" + ":" + "neo4j";
    String base64Token = "";
    try {
      base64Token = DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Response response =
        target
            .request()
            .header("Authorization", "Basic " + base64Token)
            .header("Accept", "application/json; charset=UTF-8")
            .header("Content-Type", "application/json")
            .post(Entity.entity(query, "application/json"));

    String value = response.readEntity(String.class);
    response.close();

    return value;
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    response.setContentType("text/html;charset=UTF-8");

    final Part filePart = request.getPart("photo");
    InputStream is = filePart.getInputStream();

    BufferedImage bimg = ImageIO.read(new File("E:/mydoc/a.jpg"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(bimg, "jpg", baos);
    baos.flush();
    byte[] imageinByteArray = baos.toByteArray();
    baos.close();
    String b64 = DatatypeConverter.printBase64Binary(imageinByteArray);
    request.setAttribute("uploadImg", b64);
    request.setAttribute("message", "Uploading Image has been done successfully!");
    getServletContext().getRequestDispatcher("/jsp/welcome.jsp").forward(request, response);

    //	      NOTE----  This is put into the JSP page
    //	        <img border="0"
    // src="data:image/jpg;base64,<%=(String)request.getAttribute("uploadImg")%>"  height="200"
    // width="200">

  }
Beispiel #29
0
  @SuppressWarnings("unchecked")
  public Object request(String method, String resource, Object parameters)
      throws VingdTransportException, VingdOperationException, IOException {
    URL url = new URL(backendURL + resource);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    method = method.toUpperCase();
    if (method.equals("GET") || method.equals("POST") || method.equals("PUT")) {
      conn.setRequestMethod(method);
    } else {
      throw new VingdTransportException("Unsupported HTTP method.", "Request");
    }

    byte[] credBytes = (username + ":" + pwhash).getBytes("ASCII");
    String credentials = DatatypeConverter.printBase64Binary(credBytes);
    conn.setRequestProperty("Authorization", "Basic " + credentials);
    conn.setRequestProperty("User-Agent", userAgent);

    if (parameters != null) {
      conn.setDoOutput(true);
      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
      String parametersString = jsonStringify(parameters);
      writer.write(parametersString);
      writer.close();
    }

    int statusCode = 0;
    try {
      conn.connect();
      statusCode = conn.getResponseCode();
    } catch (IOException e) {
      throw new VingdTransportException("Connecting to Vingd Broker failed.", e);
    }

    StringBuffer response = new StringBuffer();
    String jsonContent;
    try {
      InputStreamReader reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
      BufferedReader in = new BufferedReader(reader);
      String line;
      while ((line = in.readLine()) != null) response.append(line);
      in.close();
      jsonContent = response.toString();
    } catch (IOException e) {
      throw new VingdTransportException("Communication with Vingd Broker failed.", e);
    } finally {
      conn.disconnect();
    }

    // return data response if request successful
    Map<String, Object> contentMap;
    try {
      contentMap = (Map<String, Object>) jsonParseMap(jsonContent);
    } catch (Exception e) {
      throw new VingdTransportException(
          "Non-JSON response or unexpected JSON structure.", "ParsingResponse", statusCode, e);
    }

    if (statusCode >= 200 && statusCode < 300) {
      Object data = contentMap.get("data");
      if (data == null) {
        throw new VingdTransportException("Invalid JSON error response.", "ParsingDataResponse");
      }
      return data;
    }

    // raise exception describing the vingd error condition
    String message, context;
    try {
      message = (String) contentMap.get("message");
      context = (String) contentMap.get("context");
    } catch (Exception e) {
      throw new VingdTransportException(
          "Invalid JSON error response.", "ParsingErrorResponse", statusCode, e);
    }
    throw new VingdOperationException(message, context, statusCode);
  }
  private void setGmailPassword(String password) {
    if (password == null) this.gmailPassword = null;

    this.gmailPassword =
        DatatypeConverter.printBase64Binary(password.getBytes(Charset.forName("UTF8")));
  }