public JSONObject textToSpeech(Object input) {
    JSONObject args = (JSONObject) JSObjectConverter.scriptableToJSON((Scriptable) input);
    JSONObject theReturn = null;
    URL url = null;
    try {
      theReturn = new JSONObject();
      String host = (String) args.get(ATTConstant.ARG_URL);
      url = new URL(host);

      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

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

      conn.setRequestMethod("POST");
      conn.setRequestProperty("Authorization", (String) args.get(ATTConstant.ARG_TOKEN));

      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_TYPE)) {
        conn.setRequestProperty(
            "Content-Type", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_TYPE));
      } else {
        conn.setRequestProperty("Content-Type", "text/plain");
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_ACCEPT)) {
        conn.setRequestProperty(
            ATTConstant.ARG_HEADER_ACCEPT, (String) args.get(ATTConstant.ARG_HEADER_ACCEPT));
      } else {
        conn.setRequestProperty(ATTConstant.ARG_HEADER_ACCEPT, ATTConstant.VAL_CONTENT_TYPE_AMRWB);
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE)) {
        conn.setRequestProperty(
            "Content-Language", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE));
      } else {
        conn.setRequestProperty("Content-Language", ATTConstant.VAL_EN_US);
      }

      String body = (String) args.get(ATTConstant.ARG_BODY);
      conn.setRequestProperty("Content-Length", Integer.toString(body.length()));

      if (args.containsKey(ATTConstant.ARG_HEADER_XARG)) {
        conn.setRequestProperty("X-Arg", (String) args.get(ATTConstant.ARG_HEADER_XARG));
      }

      String clientSdk = "ClientSdk=att.worklight." + ATTConstant.ARG_HEADER_XARG_VERSION;
      if (args.containsKey(ATTConstant.ARG_HEADER_XARG)) {
        conn.setRequestProperty(
            "X-Arg", (String) args.get(ATTConstant.ARG_HEADER_XARG) + "," + clientSdk);
      } else {
        conn.setRequestProperty("X-Arg", clientSdk);
      }

      System.out.println("********* TextToSpeech JAVA ADAPTER LOGS ***********");

      OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream());
      outStream.write(body);
      outStream.flush();
      outStream.close();

      /*@SuppressWarnings("unchecked")
      Map<String,List<String>> header = conn.getHeaderFields();
      for (String key: header.keySet ())
         System.out.println (key+": "+conn.getHeaderField (key));
         */

      int responseCode = conn.getResponseCode();
      String responseCodeString = Integer.toString(responseCode);
      JSONObject response = new JSONObject();
      response.put("code", responseCodeString);

      if (responseCode < 400) { // Handle binary response
        // Get all the headers to pass through
        // Read the response and convert to base64
        BufferedInputStream inputStream = new BufferedInputStream(conn.getInputStream());

        int iContentLength = conn.getHeaderFieldInt("Content-Length", 0);
        int totalRead = 0;
        int currentRead = 0;
        byte[] binaryBody = new byte[iContentLength];
        do {
          currentRead = inputStream.read(binaryBody, totalRead, iContentLength - totalRead);
          totalRead += currentRead;
        } while (totalRead < iContentLength);

        String encodedBody = Base64.encode(binaryBody);
        Base64.encode(binaryBody, iContentLength);
        response.put("content", encodedBody.toString());
        response.put("contentType", conn.getHeaderField("Content-Type") + ";base64");
        response.put("contentLength", conn.getHeaderField("Content-Length"));
      } else { // handle html response
        StringBuffer errorString = new StringBuffer();
        BufferedReader is = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        String str;
        while (null != ((str = is.readLine()))) {
          errorString.append(str);
        }
        is.close();
        response.put("error", errorString.toString());
      }
      theReturn.put("message", response);
    } catch (Exception e) {
      e.printStackTrace();
      String message = null;
      String code = null;
      if (e.equals(ATTConstant.ERR_INV_STATUS_MSG)) {
        code = ATTConstant.ERR_INV_STATUS_CODE;
        message = ATTConstant.ERR_INV_STATUS_MSG;
      } else {
        code = ATTConstant.ERR_PROCESS_REQ_CODE;
        message = e.getLocalizedMessage(); // ATTConstant.ERR_PROCESS_REQ_MSG;
      }
      theReturn.put(code, message);
      return theReturn;
    } finally {
      args.clear();
      args = null;
    }
    return theReturn;
  }
  public JSONObject speechToText(Object input) {
    JSONObject args = (JSONObject) JSObjectConverter.scriptableToJSON((Scriptable) input);
    JSONObject theReturn = null;
    URL url = null;

    try {
      System.out.println("********* Speech JAVA ADAPTER LOGS ***********");
      theReturn = new JSONObject();
      String host = (String) args.get(ATTConstant.ARG_URL);
      url = new URL(host);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      // HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setRequestMethod("POST");
      // conn.setRequestMethod("GET");
      conn.setRequestProperty("Authorization", (String) args.get(ATTConstant.ARG_TOKEN));
      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_TYPE)) {
        conn.setRequestProperty(
            "Content-Type", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_TYPE));
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE)) {
        conn.setRequestProperty(
            "Content-Language", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE));
      } else {
        conn.setRequestProperty("Content-Language", ATTConstant.VAL_EN_US);
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_XSPEECH_CONTEXT)) {
        conn.setRequestProperty(
            "X-SpeechContext", (String) args.get(ATTConstant.ARG_HEADER_XSPEECH_CONTEXT));
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_XSPEECH_SUBCONTEXT)) {
        conn.setRequestProperty(
            "X-SpeechSubContext", (String) args.get(ATTConstant.ARG_HEADER_XSPEECH_SUBCONTEXT));
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_ACCEPT)) {
        conn.setRequestProperty("Accept", (String) args.get(ATTConstant.ARG_HEADER_ACCEPT));
      }

      String clientSdk =
          "ClientSdk=att_worklight-"
              + (String) args.get("platform")
              + "-"
              + ATTConstant.ARG_HEADER_XARG_VERSION;
      if (args.containsKey(ATTConstant.ARG_HEADER_XARG)) {
        conn.setRequestProperty(
            "X-Arg", (String) args.get(ATTConstant.ARG_HEADER_XARG) + "," + clientSdk);
      } else {
        conn.setRequestProperty("X-Arg", clientSdk);
      }

      String base64AudioString = (String) args.get(ATTConstant.ARG_FILEOBJECT);
      Logger logger = Logger.getLogger("Speech Adapter");
      logger.info("The received string is: " + base64AudioString);

      byte[] decoded = Base64.decode(base64AudioString);

      OutputStream wr = conn.getOutputStream();

      wr.write(decoded);
      wr.flush();
      wr.close();
      // System.out.println("********* Speech JAVA ADAPTER LOGS ***********");
      // System.out.println("Headers***********");
      // @SuppressWarnings("unchecked")
      // Map<String,List<String>> header = conn.getHeaderFields();
      // for (String key: header.keySet ())
      //   System.out.println (key+": "+conn.getHeaderField (key));

      JSONObject response = new JSONObject();
      if (conn.getResponseCode() < 400) {
        response = JSONObject.parse(conn.getInputStream());
      } else {
        StringBuffer errorString = new StringBuffer();
        BufferedReader is = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        String str;
        while (null != ((str = is.readLine()))) {
          errorString.append(str);
        }
        is.close();
        response.put("error", errorString.toString());
      }

      theReturn.put("message", response);
    } catch (Exception e) {
      e.printStackTrace();
      String message = null;
      String code = null;
      if (e.equals(ATTConstant.ERR_INV_STATUS_MSG)) {
        code = ATTConstant.ERR_INV_STATUS_CODE;
        message = ATTConstant.ERR_INV_STATUS_MSG;
      } else {
        code = ATTConstant.ERR_PROCESS_REQ_CODE;
        message =
            url.toString() + " " + e.getLocalizedMessage(); // ATTConstant.ERR_PROCESS_REQ_MSG;
      }

      theReturn.put(code, message);
      return theReturn;
    } finally {
      args.clear();
      args = null;
    }
    return theReturn;
  }
 /**
  * Creates a <code>DOMPGPData</code> from an element.
  *
  * @param pdElem a PGPData element
  */
 public DOMPGPData(Element pdElem) throws MarshalException {
   // get all children nodes
   byte[] keyId = null;
   byte[] keyPacket = null;
   NodeList nl = pdElem.getChildNodes();
   int length = nl.getLength();
   List other = new ArrayList(length);
   for (int x = 0; x < length; x++) {
     Node n = nl.item(x);
     if (n.getNodeType() == Node.ELEMENT_NODE) {
       Element childElem = (Element) n;
       String localName = childElem.getLocalName();
       try {
         if (localName.equals("PGPKeyID")) {
           keyId = Base64.decode(childElem);
         } else if (localName.equals("PGPKeyPacket")) {
           keyPacket = Base64.decode(childElem);
         } else {
           other.add(new javax.xml.crypto.dom.DOMStructure(childElem));
         }
       } catch (Base64DecodingException bde) {
         throw new MarshalException(bde);
       }
     }
   }
   this.keyId = keyId;
   this.keyPacket = keyPacket;
   this.externalElements = Collections.unmodifiableList(other);
 }
  public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
      throws MarshalException {
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element pdElem = DOMUtils.createElement(ownerDoc, "PGPData", XMLSignature.XMLNS, dsPrefix);

    // create and append PGPKeyID element
    if (keyId != null) {
      Element keyIdElem =
          DOMUtils.createElement(ownerDoc, "PGPKeyID", XMLSignature.XMLNS, dsPrefix);
      keyIdElem.appendChild(ownerDoc.createTextNode(Base64.encode(keyId)));
      pdElem.appendChild(keyIdElem);
    }

    // create and append PGPKeyPacket element
    if (keyPacket != null) {
      Element keyPktElem =
          DOMUtils.createElement(ownerDoc, "PGPKeyPacket", XMLSignature.XMLNS, dsPrefix);
      keyPktElem.appendChild(ownerDoc.createTextNode(Base64.encode(keyPacket)));
      pdElem.appendChild(keyPktElem);
    }

    // create and append any elements
    for (int i = 0, size = externalElements.size(); i < size; i++) {
      DOMUtils.appendChild(
          pdElem, ((javax.xml.crypto.dom.DOMStructure) externalElements.get(i)).getNode());
    }

    parent.appendChild(pdElem);
  }
示例#5
0
  public void onBtnDecrypt() {
    // Prompt for file name/location.
    File keyFile = Utils.pickFileRead("Public key");
    if (keyFile == null) {
      return;
    }
    File inputFile = Utils.pickFileRead("Input file");
    if (inputFile == null) {
      return;
    }
    File outputFile = Utils.pickFileWrite("Decrypted file", "decrypted.txt");
    if (outputFile == null) {
      return;
    }

    // Encrypt the file.
    try {
      // Read the public key.
      X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decode(Utils.readFromFile(keyFile)));
      PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);

      // Read the input file.
      byte[] input = Base64.decode(Utils.readFromFile(inputFile));
      int signatureLength = (int) (input[0] & (0xff));
      byte[] signature = new byte[signatureLength];
      byte[] ciphered = new byte[input.length - signatureLength - 1];
      System.arraycopy(input, 1, signature, 0, signature.length);
      System.arraycopy(input, signature.length + 1, ciphered, 0, ciphered.length);

      // Decrypt the file.
      Cipher cipher = Cipher.getInstance("RSA");
      cipher.init(Cipher.DECRYPT_MODE, publicKey);
      byte[] output = cipher.doFinal(ciphered);

      // Verify the signature of the document using the Signature class
      Signature s = Signature.getInstance("SHA1withRSA");
      s.initVerify(publicKey);
      s.update(output);
      if (s.verify(signature)) {
        Dialogs.create()
            .title("Signature is valid")
            .message("The signature of the file is valid.")
            .showInformation();
      } else {
        Dialogs.create()
            .title("Signature is invalid")
            .message("The signature of the file is not valid.")
            .showError();
        return;
      }

      // Write the file.
      Utils.writeToFile(outputFile, new String(output, "UTF-8"));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#6
0
 public static boolean check() {
   /** 读取WEB-INF/SN */
   try {
     String path = FileUtil.classPath().replace("classes/", "");
     File file = new File(path + "SN");
     if (new File(path + "PRODUCTID").exists() == false) {
       FileWriter fr = new FileWriter(path + "PRODUCTID");
       String sequence = WindowsSequenceService.me.getSequence();
       fr.write(sequence);
       fr.flush();
       return false;
     }
     BufferedReader br = new BufferedReader(new FileReader(file));
     String sn = br.readLine();
     br.close();
     sn = new String(Base64.decode(sn)); // 64位解码
     sn = CipherUtil.decryptData(sn); // 加密解密
     String[] s = sn.split("@"); // sn@sn加密
     String t = CipherUtil.decryptData(s[1], s[0] + "loyin");
     if (!s[0].equals(t)) {
       return false;
     } else {
       String sequence = WindowsSequenceService.me.getSequence();
       return s[0].equals(sequence);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return false;
 }
  public void digest(XMLSignContext signContext) throws XMLSignatureException {
    Data data = null;
    if (appliedTransformData == null) {
      data = dereference(signContext);
    } else {
      data = appliedTransformData;
    }
    digestValue = transform(data, signContext);

    // insert digestValue into DigestValue element
    String encodedDV = Base64.encode(digestValue);
    if (log.isLoggable(Level.FINE)) {
      log.log(Level.FINE, "Reference object uri = " + uri);
    }
    Element digestElem = DOMUtils.getLastChildElement(refElem);
    if (digestElem == null) {
      throw new XMLSignatureException("DigestValue element expected");
    }
    DOMUtils.removeAllChildren(digestElem);
    digestElem.appendChild(refElem.getOwnerDocument().createTextNode(encodedDV));

    digested = true;
    if (log.isLoggable(Level.FINE)) {
      log.log(Level.FINE, "Reference digesting completed");
    }
  }
示例#8
0
 public static ValueResult fromJSON(JSONObject result) throws RPCException {
   try {
     return new ValueResult(Base64.decode(result.getString("result")));
   } catch (Base64DecodingException e) {
     throw new RPCException(JSONRPCError.INVALID_BASE64);
   } catch (JSONException e) {
     throw new RPCException(JSONRPCError.INVALID_RESULT);
   }
 }
示例#9
0
 public static String createSn() {
   String sn = "0727-c5a6-29a4-1b81-6512-e5ad-1905-30f8";
   StringBuffer sb = new StringBuffer(sn);
   sb.append("@");
   sb.append(CipherUtil.encryptData(sn, sn + "loyin"));
   sb.append("@");
   sb.append((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
   return Base64.encode(CipherUtil.encryptData(sb.toString()).getBytes());
 }
示例#10
0
  public boolean validate(XMLValidateContext validateContext) throws XMLSignatureException {
    if (validateContext == null) {
      throw new NullPointerException("validateContext cannot be null");
    }
    if (validated) {
      return validationStatus;
    }
    Data data = dereference(validateContext);
    calcDigestValue = transform(data, validateContext);

    if (log.isLoggable(Level.FINE)) {
      log.log(Level.FINE, "Expected digest: " + Base64.encode(digestValue));
      log.log(Level.FINE, "Actual digest: " + Base64.encode(calcDigestValue));
    }

    validationStatus = Arrays.equals(digestValue, calcDigestValue);
    validated = true;
    return validationStatus;
  }
示例#11
0
  /** @inheritDoc */
  protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
    try {
      if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature));
      }

      byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature);

      return this.signatureAlgorithm.verify(jcebytes);
    } catch (SignatureException ex) {
      throw new XMLSignatureException("empty", ex);
    } catch (IOException ex) {
      throw new XMLSignatureException("empty", ex);
    }
  }
示例#12
0
  /**
   * @param args
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeyException
   */
  public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {

    byte[] input = "MAC".getBytes();

    // Jdk6支持的算法:HmacMD5、HmacSHA1、HmacSHA256、HmacSHA384、HmacSHA512
    // 秘密密钥生成器,可以依赖于具体的算法;或是于算法无关;
    KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");

    // 生成保密密钥
    SecretKey secretKey = keyGenerator.generateKey();

    // 构建Mac对象
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());

    // 初始化Mac对象
    mac.init(secretKey);

    // 获得安全信息摘要信息
    byte[] outPut = mac.doFinal(input);

    System.out.println("加密算法:" + secretKey.getAlgorithm());
    System.out.println("保密密钥:" + new String(Base64.encode(secretKey.getEncoded())));
    System.out.println("摘要信息:" + new String(Base64.encode(outPut)));
  }
示例#13
0
  public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
      throws MarshalException {
    if (log.isLoggable(Level.FINE)) {
      log.log(Level.FINE, "Marshalling Reference");
    }
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    refElem = DOMUtils.createElement(ownerDoc, "Reference", XMLSignature.XMLNS, dsPrefix);

    // set attributes
    DOMUtils.setAttributeID(refElem, "Id", id);
    DOMUtils.setAttribute(refElem, "URI", uri);
    DOMUtils.setAttribute(refElem, "Type", type);

    // create and append Transforms element
    if (!transforms.isEmpty() || !appliedTransforms.isEmpty()) {
      Element transformsElem =
          DOMUtils.createElement(ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix);
      refElem.appendChild(transformsElem);
      for (int i = 0, size = appliedTransforms.size(); i < size; i++) {
        DOMStructure transform = (DOMStructure) appliedTransforms.get(i);
        transform.marshal(transformsElem, dsPrefix, context);
      }
      for (int i = 0, size = transforms.size(); i < size; i++) {
        DOMStructure transform = (DOMStructure) transforms.get(i);
        transform.marshal(transformsElem, dsPrefix, context);
      }
    }

    // create and append DigestMethod element
    ((DOMDigestMethod) digestMethod).marshal(refElem, dsPrefix, context);

    // create and append DigestValue element
    if (log.isLoggable(Level.FINE)) {
      log.log(Level.FINE, "Adding digestValueElem");
    }
    Element digestValueElem =
        DOMUtils.createElement(ownerDoc, "DigestValue", XMLSignature.XMLNS, dsPrefix);
    if (digestValue != null) {
      digestValueElem.appendChild(ownerDoc.createTextNode(Base64.encode(digestValue)));
    }
    refElem.appendChild(digestValueElem);

    parent.appendChild(refElem);
    here = refElem.getAttributeNodeNS(null, "URI");
  }
示例#14
0
  /**
   * Creates a <code>DOMReference</code> from an element.
   *
   * @param refElem a Reference element
   */
  public DOMReference(Element refElem, XMLCryptoContext context) throws MarshalException {
    // unmarshal Transforms, if specified
    Element nextSibling = DOMUtils.getFirstChildElement(refElem);
    List transforms = new ArrayList(5);
    if (nextSibling.getLocalName().equals("Transforms")) {
      Element transformElem = DOMUtils.getFirstChildElement(nextSibling);
      while (transformElem != null) {
        transforms.add(new DOMTransform(transformElem, context));
        transformElem = DOMUtils.getNextSiblingElement(transformElem);
      }
      nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
    }

    // unmarshal DigestMethod
    Element dmElem = nextSibling;
    this.digestMethod = DOMDigestMethod.unmarshal(dmElem);

    // unmarshal DigestValue
    try {
      Element dvElem = DOMUtils.getNextSiblingElement(dmElem);
      this.digestValue = Base64.decode(dvElem);
    } catch (Base64DecodingException bde) {
      throw new MarshalException(bde);
    }

    // unmarshal attributes
    this.uri = DOMUtils.getAttributeValue(refElem, "URI");
    this.id = DOMUtils.getAttributeValue(refElem, "Id");

    this.type = DOMUtils.getAttributeValue(refElem, "Type");
    this.here = refElem.getAttributeNodeNS(null, "URI");
    this.refElem = refElem;

    if (transforms.isEmpty()) {
      this.transforms = Collections.EMPTY_LIST;
    } else {
      this.transforms = Collections.unmodifiableList(transforms);
    }
    this.appliedTransforms = Collections.EMPTY_LIST;
    this.allTransforms = transforms;
    this.appliedTransformData = null;
  }
示例#15
0
 private static String getFormattedText(byte[] bytes) {
   String result = Base64.encode(bytes);
   return result;
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    try {
      if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(fif);
        List items = sfu.parseRequest(request);
        Iterator itr = items.iterator();
        FileItem image1 = null, image2 = null;
        if (itr.hasNext()) image1 = (FileItem) itr.next();
        if (itr.hasNext()) image2 = (FileItem) itr.next();
        byte[] bimage1 = new byte[(int) image1.getSize()];
        byte[] bimage2 = new byte[(int) image2.getSize()];

        InputStream in = image1.getInputStream();
        in.read(bimage1);
        in.close();
        in = image2.getInputStream();
        in.read(bimage2);
        byte[] img1 = new byte[bimage1.length];
        for (int i = 0; i < bimage1.length; ++i) img1[i] = bimage1[i];
        ByteArrayInputStream bais = new ByteArrayInputStream(img1);
        BufferedImage bufimg1 = ImageIO.read(bais);
        byte[] img2 = new byte[bimage2.length];
        for (int i = 0; i < bimage2.length; ++i) img2[i] = bimage2[i];
        ByteArrayInputStream bais1 = new ByteArrayInputStream(img2);
        BufferedImage bufimg2 = ImageIO.read(bais1);
        ProgressListener progressListener =
            new ProgressListener() {
              public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("We are currently reading item " + pItems);
                if (pContentLength == -1) {
                  System.out.println("So far, " + pBytesRead + " bytes have been read.");
                } else {
                  System.out.println(
                      "So far, " + pBytesRead + " of " + pContentLength + " bytes have been read.");
                }
              }
            };
        sfu.setProgressListener(progressListener);
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection wsdircon =
            DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:XE", "system", "imbagaming");
        PreparedStatement st =
            wsdircon.prepareStatement(
                "SELECT wsdl,count FROM WEBSERVICEDATABASE WHERE panorama='yes' and status='up' ORDER BY count");
        ResultSet rs = st.executeQuery();
        String wsdlString = "";
        int count = 0;
        if (rs.next()) {
          System.out.println(wsdlString = rs.getString(1));
          count = rs.getInt(2);
        } else {
          response.sendRedirect("effectchoosere.htm");
        }
        PreparedStatement st1 =
            wsdircon.prepareStatement(
                "UPDATE WEBSERVICEDATABASE SET count="
                    + (count
                        + (bufimg1.getWidth() * bufimg1.getHeight()
                            + bufimg2.getWidth() * bufimg2.getHeight()))
                    + "WHERE wsdl=\'"
                    + wsdlString
                    + "\'");
        System.out.println(count);
        st1.execute();

        // parse the wsdl and get the details from it

        URL wsdl = new URL(wsdlString);
        // URL wsdl=new URL("http://localhost:8084/IPWebServices/ImageProcess?wsdl");
        URLConnection conn = wsdl.openConnection();
        InputStream wsdlin = conn.getInputStream();
        BufferedReader bin = new BufferedReader(new InputStreamReader(wsdlin));
        char[] asdf = new char[1024 * 100];
        bin.read(asdf);
        String ss = new String(asdf);
        bin.close();
        wsdlin.close();
        String[] info = new String[6];
        info[0] = ss.substring(ss.indexOf("targetNamespace=\"") + 17, ss.indexOf("\" name"));
        System.out.println(info[0]);
        info[1] = ss.substring(ss.indexOf("name=\"") + 6, ss.indexOf("\">"));
        System.out.println(info[1]);
        info[2] = ss.substring(ss.indexOf("port name=\"") + 11, ss.indexOf("\" binding=\""));
        System.out.println(info[2]);
        info[3] = ss.substring(ss.indexOf("<message name=\"") + 15, ss.indexOf("\">\n<part"));

        // DII

        String svcName = info[1];
        String ns = info[0];
        QName svcQname = new QName(ns, svcName);
        String portName = info[2];
        QName portQname = new QName(ns, portName);
        Service service = Service.create(wsdl, svcQname);
        Dispatch<SOAPMessage> dispatch =
            service.createDispatch(portQname, SOAPMessage.class, Service.Mode.MESSAGE);
        SOAPMessage soapMsg = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMsg.getSOAPPart();
        SOAPEnvelope soapEnv = soapPart.getEnvelope();
        SOAPBody soapBody = soapEnv.getBody();
        Name bodyName = SOAPFactory.newInstance().createName("gogogo_1", "m", ns);
        SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
        Name param1 = SOAPFactory.newInstance().createName("image1");
        Name param2 = SOAPFactory.newInstance().createName("image2");
        Name param3 = SOAPFactory.newInstance().createName("effect");
        SOAPElement seimage1 = bodyElement.addChildElement(param1);
        SOAPElement seimage2 = bodyElement.addChildElement(param2);
        SOAPElement effect = bodyElement.addChildElement(param3);
        seimage1.addTextNode(Base64.encode(bimage1));
        seimage2.addTextNode(Base64.encode(bimage2));
        effect.addTextNode("panorama");
        SOAPMessage resp = dispatch.invoke(soapMsg);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // handle the response from web service to obtain the processed image

        resp.writeTo(baos);
        String saveImg = new String(baos.toByteArray());
        int lastI = saveImg.lastIndexOf("<return>") + 8;
        int firstI = saveImg.indexOf("</return>");
        saveImg = saveImg.substring(lastI, firstI);
        byte[] dwnld = new byte[saveImg.length()];
        dwnld = Base64.decode(saveImg);
        // decrease the count in the service directory

        PreparedStatement stc =
            wsdircon.prepareStatement(
                "SELECT count FROM WEBSERVICEDATABASE WHERE wsdl='" + wsdlString + "'");
        rs = stc.executeQuery();
        if (rs.next()) count = rs.getInt(1);
        count -=
            (bufimg1.getWidth() * bufimg1.getHeight() + bufimg2.getWidth() * bufimg2.getHeight());
        if (count < 0) count = 0;
        PreparedStatement st2 =
            wsdircon.prepareStatement(
                "UPDATE WEBSERVICEDATABASE SET count="
                    + (count)
                    + "WHERE wsdl=\'"
                    + wsdlString
                    + "\'");
        System.out.println(count);
        st2.execute();
        wsdircon.close();
        // redirect user to the download page

        ServletOutputStream op = response.getOutputStream();
        ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType("application/octet-stream");
        response.setContentLength(dwnld.length);
        response.setHeader(
            "Content-Disposition", "attachment; filename=\"" + "processedImage.jpg" + "\"");
        int length = 0;
        byte[] bbuf = new byte[1000];
        ByteArrayInputStream iin = new ByteArrayInputStream(dwnld);
        while ((iin != null) && ((length = iin.read(bbuf)) != -1)) {
          op.write(bbuf, 0, length);
        }
        // in.close();
        iin.close();
        op.flush();
        op.close();
      }
    } catch (Exception e) {
      System.out.println(e);
    } finally {

    }
  }
示例#17
0
 @Override
 public JSONObject toJSON() {
   JSONObject result = shell();
   result.put("result", Base64.encode(value));
   return result;
 }
示例#18
0
 /**
  * Method decodeBigIntegerFromText
  *
  * @param text
  * @return the biginter obtained from the text node
  * @throws Base64DecodingException
  */
 public static final BigInteger decodeBigIntegerFromText(Text text)
     throws Base64DecodingException {
   return new BigInteger(1, Base64.decode(text.getData()));
 }
示例#19
0
 /**
  * Method decodeBigIntegerFromElement
  *
  * @param element
  * @return the biginteger obtained from the node
  * @throws Base64DecodingException
  */
 public static final BigInteger decodeBigIntegerFromElement(Element element)
     throws Base64DecodingException {
   return new BigInteger(1, Base64.decode(element));
 }