public static void main(String[] args) {
   try {
     fileConfig = Utils.loadStatusData(LOGFILE_PATH);
     config = fileConfig.getOrDefault("progress", new HashMap<>());
     String API_SNIPPETS_PATH;
     if (args.length == 0) {
       API_SNIPPETS_PATH =
           Utils.getenv("API_SNIPPETS_PATH").orElse("/home/ehernandez/twilio/markdown");
     } else {
       API_SNIPPETS_PATH = args[0];
     }
     printStatus = PrintStatus.fromParam((args.length > 0) ? args[1] : "");
     PagesScanner scanner =
         new PagesScanner(
             SearchForMissingPages::checkPageStatus,
             BASE_REPOSITORY_URL,
             API_SNIPPETS_PATH,
             new String[] {"md"});
     scanner.test("/docs/api");
     scanner.test("/docs/quickstart");
     Utils.saveStatusData(fileConfig, new File(LOGFILE_PATH));
   } catch (ParsingFileException ex) {
     System.err.println("Error parsing " + LOGFILE_PATH);
   }
 }
예제 #2
0
  public static void main(String args[]) {

    try {
      // 读配置
      FileReader fr = new FileReader("/data/service/service.conf");
      BufferedReader br = new BufferedReader(fr);
      String ip = null;
      if ((ip = br.readLine()) != null) {
        String ans[] = ip.split(":");
        if (ans.length == 2) {
          Config.HOST_IP = ans[0];
          Config.HOST_PORT = Integer.parseInt(ans[1]);
          Config.REQUEST_URI_PRE =
              "http://" + Config.HOST_IP + ":" + Config.HOST_PORT + "/ebox/api/v1";
          Config.PAK_EXPRESS_QUERY_URL = Config.REQUEST_URI_PRE + "/express/query";
          Utils.log(Config.HOST_IP);
          Utils.log(Config.HOST_PORT + "");
          Utils.log(Config.REQUEST_URI_PRE);
          Utils.log(Config.PAK_EXPRESS_QUERY_URL);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    // 初始化文件删除定时器
    FileDelTimer fileDelTimer = new FileDelTimer();
    fileDelTimer.schedule(
        new TimerTask() {
          @Override
          public void run() {

            FileDelModel fileDelModel = null;
            Utils.log("Delete Task Start");

            while ((fileDelModel = FileCleanService.getInstance().get()) != null) {
              Utils.log("ready path = " + fileDelModel.filePath + " time = " + fileDelModel.time);
              if (fileDelModel.time + Config.TIME_FILE_TO_DEL > System.currentTimeMillis()) break;
              FileCleanService.getInstance().poll();
              File file = new File(fileDelModel.filePath);
              if (file.exists()) {
                Utils.log("del file path = " + file.getAbsolutePath());
                file.delete();
              }
            }
          }
        },
        0,
        60 * 1000);

    Utils.log("start time ok");

    // 初始化httpsever
    try {
      new ReportFormHttpServer(Config.SERVER_PORT).start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #3
0
 public void showKeyboard(KeyboardState keyboardState) {
   Utils.setVisible(this, R.id.keyboard, keyboardState == KeyboardState.KEYBOARD);
   Utils.setVisible(this, R.id.controller, keyboardState == KeyboardState.CONTROLLER);
   final ImageView btnInput = (ImageView) findViewById(R.id.btnInput);
   if (btnInput != null) {
     btnInput.setImageResource(
         keyboardState == KeyboardState.KEYBOARD
             ? (isXperiaPlay ? R.drawable.keyboard_cancel : R.drawable.controller)
             : R.drawable.keyboard);
   }
   keyboardShowing = keyboardState;
 }
 // ===========================================================================
 @Override
 public boolean onKeyDown(int keycode, KeyEvent event) {
   if (readKeyStateNow) {
     Toast.makeText(EditGameKeyActivity.this, "Got [" + keycode + "]", Toast.LENGTH_SHORT).show();
     androidKey = keycode;
     String s = BeebKeys.getKeyEventNameFromInt(keycode);
     int i = BeebKeys.parseKeyEventIntFromString(s);
     Utils.writeLog("onKeyDown KeyCode [" + keycode + "] Int [" + i + "] Key [" + s + "]");
     LBandroidKey.setText("Set [" + androidKey + "]");
     return true; // stop this event here, don't process this keypress any further
   }
   return super.onKeyDown(keycode, event);
 }
예제 #5
0
 public static void main(String[] args) {
   int[] factorials = new int[10];
   factorials[0] = 1;
   for (int i = 1; i < 10; i++) {
     factorials[i] = i * factorials[i - 1];
   }
   int count = 0;
   for (int i = 1; i < 1_000_000; i++) {
     Set<Long> set = new HashSet<>();
     long start = i;
     int chainCount = 0;
     while (!set.contains(start)) {
       set.add(start);
       chainCount++;
       int[] digits = Utils.digitsOf(start);
       start = sumOfFactorials(digits, factorials);
     }
     if (chainCount == 60) {
       count++;
     }
   }
   System.out.println(count);
 }
예제 #6
0
    @Override
    public void close() throws IOException {
      if (tmp_out != null) {
        Utils.closeQuietly(tmp_out);
        tmp_out = null;

        // Rename the file to the permanent name
        if (!errord) {
          File newtmpfile = new File(cachedir, urlToCacheFilename(url));
          errord = !tmpfile.renameTo(newtmpfile);
          if (!errord) {
            tmpfile = newtmpfile;
          }
        }

        // Add to cache
        if (errord) {
          tmpfile.delete();
        } else {
          synchronized (ImageCache.this) {
            Log.d(TAG, "adding " + url);
            filecachelist.add(tmpfile);
            filecachemap.put(url, tmpfile);
            filecachesize += tmpfile.length();
            // Trim cache
            while (filecachesize > MAX_FILECACHE_SIZE) {
              File trimfile = filecachelist.remove(0); // oldest
              Log.d(TAG, "trimming " + trimfile.getName());
              filecachemap.remove(trimfile.getName());
              filecachesize -= trimfile.length();
              trimfile.delete();
            }
          }
        }
      }
      super.close();
    }
예제 #7
0
파일: Event.java 프로젝트: smandreev/jetmbt
 /** Just a constructor. Fills hash field. */
 private Event(WebHandle handle, String context) {
   this.handle = handle;
   this.context = context;
   hash = handle.hashCode() + Utils.hashString(context) * 239;
 }
  public static Result index() {

    if (Utils.isPOST(request())) {
      form = Form.form(Credentials.class).bindFromRequest();
      // Check errors
      if (form.hasErrors()) {
        return badRequest(views.html.sample44.render(false, null, null, form));
      }
      // Save credentials to session
      Credentials credentials = form.get();
      session().put("clientId", credentials.getClientId());
      session().put("privateKey", credentials.getPrivateKey());
      session().put("basePath", credentials.getBasePath());
      credentials.normalizeBasePath("https://api.groupdocs.com/v2.0");
      // Get request parameters
      Http.MultipartFormData body = request().body().asMultipartFormData();

      String name = Utils.getFormValue(body, "firstName");
      String lastName = Utils.getFormValue(body, "lastName");
      String firstEmail = Utils.getFormValue(body, "firstEmail");
      String secondEmail = Utils.getFormValue(body, "secondEmail");
      String gender = Utils.getFormValue(body, "gender");
      String basePath = credentials.getBasePath();

      ApiInvoker.getInstance()
          .setRequestSigner(new GroupDocsRequestSigner(credentials.getPrivateKey()));

      try {
        //
        String guid = null;
        //
        Http.MultipartFormData.FilePart file = body.getFile("file");
        StorageApi storageApi = new StorageApi();
        // Initialize API with base path
        storageApi.setBasePath(credentials.getBasePath());
        FileInputStream is = new FileInputStream(file.getFile());
        UploadResponse uploadResponse =
            storageApi.Upload(
                credentials.getClientId(),
                file.getFilename(),
                "uploaded",
                "",
                1,
                new FileStream(is));
        // Check response status
        uploadResponse = Utils.assertResponse(uploadResponse);
        guid = uploadResponse.getResult().getGuid();
        guid = Utils.assertNotNull(guid);
        //
        MergeApi mergeApi = new MergeApi();
        // Initialize API with base path
        mergeApi.setBasePath(credentials.getBasePath());

        Datasource datasource = new Datasource();
        datasource.setFields(new ArrayList<DatasourceField>());

        DatasourceField datasourceField = null;

        datasourceField = new DatasourceField();
        datasourceField.setName("gender");
        datasourceField.setType("text");
        datasourceField.setValues(new ArrayList<String>());
        datasourceField.getValues().add(gender);
        datasource.getFields().add(datasourceField);

        datasourceField = new DatasourceField();
        datasourceField.setName("name");
        datasourceField.setType("text");
        datasourceField.setValues(new ArrayList<String>());
        datasourceField.getValues().add(name);
        datasource.getFields().add(datasourceField);

        AddDatasourceResponse datasourceResponse =
            mergeApi.AddDataSource(credentials.getClientId(), datasource);
        // Check response status
        datasourceResponse = Utils.assertResponse(datasourceResponse);

        MergeTemplateResponse mergeTemplateResponse =
            mergeApi.MergeDatasource(
                credentials.getClientId(),
                guid,
                Double.toString(datasourceResponse.getResult().getDatasource_id()),
                "pdf",
                null);
        // Check response status
        mergeTemplateResponse = Utils.assertResponse(mergeTemplateResponse);

        Thread.sleep(8000);

        AsyncApi asyncApi = new AsyncApi();
        // Initialize API with base path
        asyncApi.setBasePath(credentials.getBasePath());

        GetJobDocumentsResponse jobDocumentsResponse =
            asyncApi.GetJobDocuments(
                credentials.getClientId(),
                Double.toString(mergeTemplateResponse.getResult().getJob_id()),
                null);
        // Check response status
        jobDocumentsResponse = Utils.assertResponse(jobDocumentsResponse);

        if ("Postponed".equalsIgnoreCase(jobDocumentsResponse.getResult().getJob_status())) {
          throw new Exception("Job is failed");
        }

        if ("Pending".equalsIgnoreCase(jobDocumentsResponse.getResult().getJob_status())) {
          throw new Exception("Job is pending");
        }

        String resultGuid =
            jobDocumentsResponse.getResult().getInputs().get(0).getOutputs().get(0).getGuid();
        String resultName =
            jobDocumentsResponse.getResult().getInputs().get(0).getOutputs().get(0).getName();

        // Create Signature api object
        SignatureApi signatureApi = new SignatureApi();
        // Initialize API with base path
        signatureApi.setBasePath(basePath);
        // Make a requests to Signature Api to create an envelope
        SignatureEnvelopeSettingsInfo env = new SignatureEnvelopeSettingsInfo();
        env.setEmailSubject("Sign this!");
        SignatureEnvelopeResponse envelopeResponse =
            signatureApi.CreateSignatureEnvelope(
                credentials.getClientId(), resultName, null, null, resultGuid, true, env);
        envelopeResponse = Utils.assertResponse(envelopeResponse);
        // Get an ID of created envelope
        final String envelopeGuid = envelopeResponse.getResult().getEnvelope().getId();

        // Make a request to Signature Api to get all available roles
        SignatureRolesResponse signatureRolesResponse =
            signatureApi.GetRolesList(credentials.getClientId(), null);
        // Check response status
        signatureRolesResponse = Utils.assertResponse(signatureRolesResponse);
        List<SignatureRoleInfo> roles = signatureRolesResponse.getResult().getRoles();
        String roleGuid = null;
        for (SignatureRoleInfo role : roles) {
          // Get an ID of Signer role
          if ("Signer".equalsIgnoreCase(role.getName())) {
            roleGuid = role.getId();
            break;
          }
        }

        // Check emptiness lastName string
        if (Strings.isNullOrEmpty(lastName)) {
          lastName = name;
        }
        // Make a request to Signature Api to add new first recipient to envelope
        SignatureEnvelopeRecipientResponse signatureEnvelopeRecipientResponse =
            signatureApi.AddSignatureEnvelopeRecipient(
                credentials.getClientId(),
                envelopeGuid,
                firstEmail,
                name,
                lastName,
                roleGuid,
                null);
        // Check response status
        signatureEnvelopeRecipientResponse =
            Utils.assertResponse(signatureEnvelopeRecipientResponse);
        String recipientGuid =
            signatureEnvelopeRecipientResponse.getResult().getRecipient().getId();

        // Make a request to Signature Api to add new second recipient to envelope
        SignatureEnvelopeRecipientResponse signatureEnvelopeSecondRecipientResponse =
            signatureApi.AddSignatureEnvelopeRecipient(
                credentials.getClientId(),
                envelopeGuid,
                secondEmail,
                name + "2",
                lastName + "2",
                roleGuid,
                null);
        // Check response status
        signatureEnvelopeSecondRecipientResponse =
            Utils.assertResponse(signatureEnvelopeSecondRecipientResponse);
        String recipientSecondGuid =
            signatureEnvelopeSecondRecipientResponse.getResult().getRecipient().getId();

        // Make a request to Signature Api to get all available fields
        SignatureEnvelopeDocumentsResponse getEnvelopDocument =
            signatureApi.GetSignatureEnvelopeDocuments(credentials.getClientId(), envelopeGuid);
        // Check response status
        getEnvelopDocument = Utils.assertResponse(getEnvelopDocument);
        // Create new first field called singlIndex1
        SignatureEnvelopeFieldSettingsInfo envField1 = new SignatureEnvelopeFieldSettingsInfo();
        envField1.setName("singlIndex1");
        envField1.setLocationX(0.15);
        envField1.setLocationY(0.23);
        envField1.setLocationWidth(150.0);
        envField1.setLocationHeight(50.0);
        envField1.setForceNewField(true);
        envField1.setPage(1);

        // Make a request to Signature Api to add city field to envelope
        SignatureEnvelopeFieldsResponse signatureEnvelopeFieldsResponse =
            signatureApi.AddSignatureEnvelopeField(
                credentials.getClientId(),
                envelopeGuid,
                getEnvelopDocument.getResult().getDocuments().get(0).getDocumentId(),
                recipientGuid,
                "0545e589fb3e27c9bb7a1f59d0e3fcb9",
                envField1);

        // Create new second field called singlIndex2
        SignatureEnvelopeFieldSettingsInfo envField2 = new SignatureEnvelopeFieldSettingsInfo();
        envField2.setName("singlIndex2");
        envField2.setLocationX(0.35);
        envField2.setLocationY(0.23);
        envField2.setLocationWidth(150.0);
        envField2.setLocationHeight(50.0);
        envField2.setForceNewField(true);
        envField2.setPage(1);

        // Make a request to Signature Api to add city field to envelope
        SignatureEnvelopeFieldsResponse signatureEnvelopeSecondFieldsResponse =
            signatureApi.AddSignatureEnvelopeField(
                credentials.getClientId(),
                envelopeGuid,
                getEnvelopDocument.getResult().getDocuments().get(0).getDocumentId(),
                recipientSecondGuid,
                "0545e589fb3e27c9bb7a1f59d0e3fcb9",
                envField2);

        // Check response status
        Utils.assertNotNull(signatureEnvelopeFieldsResponse);
        SignatureEnvelopeSendResponse signatureEnvelopeSendResponse =
            signatureApi.SignatureEnvelopeSend(credentials.getClientId(), envelopeGuid, null);
        Utils.assertResponse(signatureEnvelopeSendResponse);

        String server =
            credentials
                .getBasePath()
                .substring(0, credentials.getBasePath().indexOf(".com") + 4)
                .replace("api", "apps");
        String embedUrl = server + "/signature2/signembed/" + envelopeGuid + "/" + recipientGuid;
        String embedUrl2 =
            server + "/signature2/signembed/" + envelopeGuid + "/" + recipientSecondGuid;

        // Render view
        return ok(views.html.sample44.render(true, embedUrl, embedUrl2, form));
      } catch (Exception e) {
        return badRequest(views.html.sample44.render(false, null, null, form));
      }
    } else if (Utils.isGET(request())) {
      form = form.bind(session());
    }
    return ok(views.html.sample44.render(false, null, null, form));
  }
  public static Result index() {

    if (Utils.isPOST(request())) {
      form = Form.form(Credentials.class).bindFromRequest();
      // Check errors
      if (form.hasErrors()) {
        return badRequest(views.html.sample18.render(false, null, form));
      }
      // Save credentials to session
      Credentials credentials = form.get();
      session().put("clientId", credentials.getClientId());
      session().put("privateKey", credentials.getPrivateKey());
      session().put("basePath", credentials.getBasePath());
      credentials.normalizeBasePath("https://api.groupdocs.com/v2.0");
      // Get request parameters
      Http.MultipartFormData body = request().body().asMultipartFormData();
      String sourse = Utils.getFormValue(body, "sourse");
      String convertType = Utils.getFormValue(body, "convertType");
      String callbackUrl = Utils.getFormValue(body, "callbackUrl");
      callbackUrl = (callbackUrl == null) ? "" : callbackUrl;
      // Initialize SDK with private key
      ApiInvoker.getInstance()
          .setRequestSigner(new GroupDocsRequestSigner(credentials.getPrivateKey()));

      try {
        //
        String guid = null;
        //
        if ("guid".equals(sourse)) { // File GUID
          guid = Utils.getFormValue(body, "fileId");
        } else if ("url".equals(sourse)) { // Upload file fron URL
          String url = Utils.getFormValue(body, "url");
          StorageApi storageApi = new StorageApi();
          // Initialize API with base path
          storageApi.setBasePath(credentials.getBasePath());
          UploadResponse uploadResponse = storageApi.UploadWeb(credentials.getClientId(), url);
          // Check response status
          uploadResponse = Utils.assertResponse(uploadResponse);
          guid = uploadResponse.getResult().getGuid();
        } else if ("local".equals(sourse)) { // Upload local file
          Http.MultipartFormData.FilePart file = body.getFile("file");
          StorageApi storageApi = new StorageApi();
          // Initialize API with base path
          storageApi.setBasePath(credentials.getBasePath());
          FileInputStream is = new FileInputStream(file.getFile());
          UploadResponse uploadResponse =
              storageApi.Upload(
                  credentials.getClientId(),
                  file.getFilename(),
                  "uploaded",
                  "",
                  1,
                  new FileStream(is));
          // Check response status
          uploadResponse = Utils.assertResponse(uploadResponse);
          guid = uploadResponse.getResult().getGuid();
        }
        guid = Utils.assertNotNull(guid);
        // Render view
        AsyncApi api = new AsyncApi();
        // Initialize API with base path
        api.setBasePath(credentials.getBasePath());
        ConvertResponse response =
            api.Convert(
                credentials.getClientId(),
                guid,
                "",
                "description",
                false,
                callbackUrl,
                convertType);
        // Check response status
        response = Utils.assertResponse(response);
        Double jobId = response.getResult().getJob_id();
        Thread.sleep(5000);
        GetJobDocumentsResponse jobDocumentsResponse =
            api.GetJobDocuments(credentials.getClientId(), jobId.toString(), "");
        jobDocumentsResponse = Utils.assertResponse(jobDocumentsResponse);

        String resultGuid =
            jobDocumentsResponse.getResult().getInputs().get(0).getOutputs().get(0).getGuid();

        FileOutputStream fileOutputStream = new FileOutputStream(USER_INFO_FILE);
        DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(credentials.getClientId());
        stringBuilder.append("|");
        stringBuilder.append(credentials.getPrivateKey());
        stringBuilder.append("|");
        stringBuilder.append(credentials.getBasePath());
        dataOutputStream.writeUTF(stringBuilder.toString());
        dataOutputStream.flush();
        fileOutputStream.close();

        return ok(views.html.sample18.render(true, resultGuid, form));
      } catch (Exception e) {
        return badRequest(views.html.sample18.render(false, null, form));
      }
    } else if (Utils.isGET(request())) {
      form = form.bind(session());
    }
    return ok(views.html.sample18.render(false, null, form));
  }
예제 #10
0
파일: Base.java 프로젝트: haijunsu/QC
 /**
  * Generate random number array in length with start value and end value
  *
  * @param start
  * @param len
  * @return
  */
 public int[] getRandomNumberSequence(int start, int end, int len) {
   return Utils.getRandomNumberSequence(start, end, len);
 }
예제 #11
0
파일: Base.java 프로젝트: haijunsu/QC
 /**
  * Generate random number in range
  *
  * @param start
  * @param end
  * @return random number
  */
 public int getRandomNumber(int start, int end) {
   return Utils.getRandomNumber(start, end);
 }
 // ===========================================================================
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_edit_game_key);
   LBbbcKey = (TextView) findViewById(R.id.LBbbcKey);
   LBandroidKey = (TextView) findViewById(R.id.LBandroidKey);
   BTsave = (Button) findViewById(R.id.BTsave);
   BTclose = (Button) findViewById(R.id.BTclose);
   BTreadKey = (Button) findViewById(R.id.BTreadKey);
   BTdelete = (Button) findViewById(R.id.BTdelete);
   // ===
   Intent intent = getIntent();
   bbcKey = intent.getStringExtra(LoadDisk.EXTRA_BBC_KEY_CODE);
   gameFilename = intent.getStringExtra(LoadDisk.EXTRA_GAME_FILENAME);
   int i = BeebKeys.parseBeebKeyIntFromString(bbcKey);
   String s = BeebKeys.getBbcKeyNamefromInt(i);
   Utils.writeLog(
       "EditGameKeyActivity Filename["
           + gameFilename
           + "] Key ["
           + bbcKey
           + "] Int ["
           + i
           + "] Key ["
           + s
           + "]");
   // ===
   LBbbcKey.setText(bbcKey);
   readKeyStateNow = false;
   // ===========================================================================
   BTsave.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View v) {
           // if (androidKey < 0) androidKey = 42; // TODO remove
           ConfigKey ck = new ConfigKey();
           ck.label = "label";
           ck.keylabel = "keylabel";
           ck.xc = 1f;
           ck.yc = 1f;
           ck.width = 1f;
           ck.height = 1f;
           ck.scancode = BeebKeys.parseBeebKeyIntFromString(bbcKey);
           ck.androidKeyCode1 = androidKey;
           ck.androidKeyCode2 = -1;
           Controllers.writeKeyConfigRow(gameFilename, ck);
           finish();
         }
       });
   // ===========================================================================
   BTclose.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View v) {
           finish();
         }
       });
   // ===========================================================================
   BTreadKey.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View v) {
           readKeyStateNow = true;
           Toast.makeText(EditGameKeyActivity.this, "Press your key now", Toast.LENGTH_SHORT)
               .show();
         }
       });
   // ===========================================================================
   BTdelete.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View v) {
           Controllers.deleteOrReplaceKeyConfigRow(gameFilename, bbcKey, "");
           finish();
         }
       });
 }
  public static Result index() {

    if (Utils.isPOST(request())) {
      form = Form.form(Credentials.class).bindFromRequest();
      // Check errors
      if (form.hasErrors()) {
        return badRequest(views.html.sample19.render(false, null, null, null, form));
      }
      // Save credentials to session
      Credentials credentials = form.get();
      session().put("clientId", credentials.getClientId());
      session().put("privateKey", credentials.getPrivateKey());
      session().put("basePath", credentials.getBasePath());
      credentials.normalizeBasePath("https://api.groupdocs.com/v2.0");
      // Get request parameters
      Http.MultipartFormData body = request().body().asMultipartFormData();
      String sourse = Utils.getFormValue(body, "sourse");
      String callbackUrl = Utils.getFormValue(body, "callbackUrl");
      // Initialize SDK with private key
      ApiInvoker.getInstance()
          .setRequestSigner(new GroupDocsRequestSigner(credentials.getPrivateKey()));

      try {
        //
        String sourseGuid = null;
        //
        if ("guid".equals(sourse)) { // File GUID
          sourseGuid = Utils.getFormValue(body, "sourceFileId");
        } else if ("url".equals(sourse)) { // Upload file fron URL
          String url = Utils.getFormValue(body, "url");
          StorageApi storageApi = new StorageApi();
          // Initialize API with base path
          storageApi.setBasePath(credentials.getBasePath());
          UploadResponse uploadResponse = storageApi.UploadWeb(credentials.getClientId(), url);
          // Check response status
          uploadResponse = Utils.assertResponse(uploadResponse);
          sourseGuid = uploadResponse.getResult().getGuid();
        } else if ("local".equals(sourse)) { // Upload local file
          Http.MultipartFormData.FilePart file = body.getFile("local");
          StorageApi storageApi = new StorageApi();
          // Initialize API with base path
          storageApi.setBasePath(credentials.getBasePath());
          FileInputStream is = new FileInputStream(file.getFile());
          UploadResponse uploadResponse =
              storageApi.Upload(
                  credentials.getClientId(),
                  file.getFilename(),
                  "uploaded",
                  "",
                  1,
                  new FileStream(is));
          // Check response status
          uploadResponse = Utils.assertResponse(uploadResponse);
          sourseGuid = uploadResponse.getResult().getGuid();
        }
        // Target
        String targetGuid = null;
        //
        if ("guid".equals(sourse)) { // File GUID
          targetGuid = Utils.getFormValue(body, "targetFileId");
        } else if ("url".equals(sourse)) { // Upload file fron URL
          String url = Utils.getFormValue(body, "targetUrl");
          StorageApi storageApi = new StorageApi();
          // Initialize API with base path
          storageApi.setBasePath(credentials.getBasePath());
          UploadResponse uploadResponse = storageApi.UploadWeb(credentials.getClientId(), url);
          // Check response status
          uploadResponse = Utils.assertResponse(uploadResponse);
          targetGuid = uploadResponse.getResult().getGuid();
        } else if ("local".equals(sourse)) { // Upload local file
          Http.MultipartFormData.FilePart file = body.getFile("target_local");
          StorageApi storageApi = new StorageApi();
          // Initialize API with base path
          storageApi.setBasePath(credentials.getBasePath());
          FileInputStream is = new FileInputStream(file.getFile());
          UploadResponse uploadResponse =
              storageApi.Upload(
                  credentials.getClientId(),
                  file.getFilename(),
                  "uploaded",
                  "",
                  1,
                  new FileStream(is));
          // Check response status
          uploadResponse = Utils.assertResponse(uploadResponse);
          targetGuid = uploadResponse.getResult().getGuid();
        }
        sourseGuid = Utils.assertNotNull(sourseGuid);
        targetGuid = Utils.assertNotNull(targetGuid);

        ComparisonApi api = new ComparisonApi();
        // Initialize API with base path
        api.setBasePath(credentials.getBasePath());
        callbackUrl = callbackUrl == null ? "" : callbackUrl;

        CompareResponse compareResponse =
            api.Compare(credentials.getClientId(), sourseGuid, targetGuid, callbackUrl);
        compareResponse = Utils.assertResponse(compareResponse);

        AsyncApi asyncApi = new AsyncApi();
        // Initialize API with base path
        asyncApi.setBasePath(credentials.getBasePath());
        //
        GetJobDocumentsResponse jobDocumentsResponse = null;
        do {
          Thread.sleep(5000);
          jobDocumentsResponse =
              asyncApi.GetJobDocuments(
                  credentials.getClientId(),
                  compareResponse.getResult().getJob_id().toString(),
                  "");
          jobDocumentsResponse = Utils.assertResponse(jobDocumentsResponse);
        } while ("Inprogress".equalsIgnoreCase(jobDocumentsResponse.getResult().getJob_status()));
        String resultGuid = jobDocumentsResponse.getResult().getOutputs().get(0).getGuid();
        Utils.assertNotNull(resultGuid);

        MgmtApi mgmtApi = new MgmtApi();
        // Initialize API with base path
        mgmtApi.setBasePath(credentials.getBasePath());
        GetUserEmbedKeyResponse userEmbedKeyResponse =
            mgmtApi.GetUserEmbedKey(credentials.getClientId(), "comparison");
        Utils.assertResponse(userEmbedKeyResponse);
        String compareKey = userEmbedKeyResponse.getResult().getKey().getGuid();

        FileOutputStream fileOutputStream = new FileOutputStream(USER_INFO_FILE);
        DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(credentials.getClientId());
        stringBuilder.append("|");
        stringBuilder.append(credentials.getPrivateKey());
        stringBuilder.append("|");
        stringBuilder.append(credentials.getBasePath());

        dataOutputStream.writeUTF(stringBuilder.toString());

        dataOutputStream.flush();
        fileOutputStream.close();

        String server =
            credentials
                .getBasePath()
                .substring(0, credentials.getBasePath().indexOf(".com") + 4)
                .replace("api", "apps");

        // Render view
        return ok(views.html.sample19.render(true, resultGuid, compareKey, server, form));
      } catch (Exception e) {
        return badRequest(views.html.sample19.render(false, null, null, null, form));
      }
    } else if (Utils.isGET(request())) {
      form = form.bind(session());
    }
    return ok(views.html.sample19.render(false, null, null, null, form));
  }