Example usage for java.nio.file Files readAllBytes

List of usage examples for java.nio.file Files readAllBytes

Introduction

In this page you can find the example usage for java.nio.file Files readAllBytes.

Prototype

public static byte[] readAllBytes(Path path) throws IOException 

Source Link

Document

Reads all the bytes from a file.

Usage

From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java

@Override
public PutObjectResult putObject(String bucketName, String key, File file) throws AmazonClientException {
    try {//  w  w  w.  j av a 2 s . c o m
        ByteArrayInputStream stream = new ByteArrayInputStream(Files.readAllBytes(file.toPath()));
        S3Element elem = parse(stream, bucketName, key);

        persist(bucketName, elem);

        PutObjectResult putObjectResult = new PutObjectResult();
        putObjectResult.setETag("3a5c8b1ad448bca04584ecb55b836264");
        return putObjectResult;
    } catch (IOException e) {
        throw new AmazonServiceException("", e);
    }

}

From source file:coq.DebugUnivInconst.java

static String readFile(String path) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, Charset.defaultCharset());
}

From source file:com.pentaho.ctools.issues.cde.CDE417.java

/**
 * ############################### Test Case 1 ###############################
 *
 * Test Case Name: /*w  w w .  j  a  v  a 2 s . c om*/
 *   Popup Export issues
 *
 * Description: 
 *   CDE-417 issue, so when user clicks to export chart, popup shown has chart preview. 
 *   CDE-424 issue we'll delete the .js file prior to opening the dashboard and saving the dashboard should create 
 *   the .js file again and enable exporting.
 *   CDF-448 exporting chart with skip ticks (chart is too small to show all labels) is successful
 *   CDF-502 export chart with array parameters is successful
 *   CDE-514 all charts are available on charts to export property and all elements are available on the data to export property
 *   
 * Steps:
 * 424
 *    1. Open PUC and click Browse Files
 *    2. Go to dashboard folder, click countryChart.js file and click Move To Trash
 *    3. Open created sample and save Dashboard
 * 514
 *    4. Go to Export Component and assert all charts appear on the Chart to Export property
 *    5. Assert all charts and the table appear on data to export property
 *    
 * 417/448/502
 *    6. Click to export chart, click export, assert chart is shown and assert export works as expected (448 and 502)
 *    7. Click to export chart2, click export, assert chart is shown and assert export works as expected
 * 
 * @throws InterruptedException
 *
 */
@Test
public void tc01_PopupExportComponent_PreviewerRendersChart() throws InterruptedException {
    this.log.info("tc01_PopupExportComponent_PreviewerRendersChart");

    /*
     * ## Step 1
     */
    //Show Hidden Files
    BrowseFiles browser = new BrowseFiles(driver);
    if (!PUCSettings.SHOWHIDDENFILES) {
        browser.CheckShowHiddenFiles();
    }

    /*
     * ## Step 2
     */
    //String pathChart = "/public/Issues/CDF/CDF-548/chart.js";
    //String pathCdfChart = "/public/Issues/CDF/CDF-548/CDF-548_chart.js";
    String pathCountryChart = "/public/Issues/CDF/CDF-548/countryChart.js";
    String pathCdfCountryChart = "/public/Issues/CDF/CDF-548/CDF-548_countryChart.js";
    //boolean fileDeleteChart = browser.DeleteFile( pathChart );
    //boolean fileDeleteCdfChart = browser.DeleteFile( pathCdfChart );
    boolean fileDeleteCountryChart = browser.DeleteFile(pathCountryChart);
    boolean fileDeleteCdfCountryChart = browser.DeleteFile(pathCdfCountryChart);
    //assertTrue( fileDeleteChart );
    //assertTrue( fileDeleteCdfChart );
    assertTrue(fileDeleteCountryChart);
    assertTrue(fileDeleteCdfCountryChart);

    driver.switchTo().defaultContent();
    WebDriver frame = driver.switchTo().frame("browser.perspective");
    this.elemHelper.WaitForAttributeValue(frame, By.xpath("//div[@id='fileBrowserFiles']/div[2]/div[1]"),
            "title", "CDF-548.cda");
    String nameOfCdf548Wcdf = this.elemHelper.GetAttribute(frame,
            By.xpath("//div[@id='fileBrowserFiles']/div[2]/div[1]"), "title");
    assertEquals("CDF-548.cda", nameOfCdf548Wcdf);

    /*
     * ## Step 3
     */
    // Go to Export Popup Component sample in Edit mode
    driver.get(baseUrl + "api/repos/%3Apublic%3AIssues%3ACDF%3ACDF-548%3ACDF-548.wcdf/edit");

    //Save Dashboard
    WebElement saveButton = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.id("Save"));
    assertNotNull(saveButton);
    this.elemHelper.Click(driver, By.id("Save"));
    WebElement saveNotify = this.elemHelper.WaitForElementPresenceAndVisible(driver,
            By.cssSelector("div.notify-bar-message"));
    assertNotNull(saveNotify);
    String saveMessage = this.elemHelper.WaitForElementPresentGetText(driver,
            By.cssSelector("div.notify-bar-message"));
    assertEquals("Dashboard saved successfully", saveMessage);

    /* 
     * ## Step 4 
      */
    //Go to components panel and expand "Others"
    WebElement componentsPanelButton = this.elemHelper.FindElement(driver,
            By.cssSelector("div.componentsPanelButton"));
    assertNotNull(componentsPanelButton);
    componentsPanelButton.click();
    WebElement componentsTable = this.elemHelper.FindElement(driver, By.id("cdfdd-components-components"));
    assertNotNull(componentsTable);
    WebElement othersExpander = this.elemHelper.FindElement(driver,
            By.xpath("//table[@id='table-cdfdd-components-components']//tr[@id='OTHERCOMPONENTS']/td/span"));
    assertNotNull(othersExpander);
    othersExpander.click();

    //Select Export Popup Component
    WebElement exportPopupElement = this.elemHelper.FindElement(driver,
            By.xpath("//table[@id='table-cdfdd-components-components']//td[contains(text(),'exportPopup')]"));
    assertNotNull(exportPopupElement);
    exportPopupElement.click();

    //Open options for Chart Component to Export and assert "chart" and "countryChart"
    WebElement chartExportProperty = this.elemHelper.FindElement(driver, By.xpath(
            "//table[@id='table-cdfdd-components-properties']//td[@title='Id for Chart Component to Export']/../td[2]"));
    assertNotNull(chartExportProperty);
    chartExportProperty.click();
    WebElement chartExportInput = this.elemHelper.FindElement(driver, By.xpath(
            "//table[@id='table-cdfdd-components-properties']//td[@title='Id for Chart Component to Export']/../td[2]/form/input"));
    assertNotNull(chartExportInput);
    chartExportInput.clear();
    Robot robot;
    try {
        robot = new Robot();
        robot.keyPress(KeyEvent.VK_DOWN);
        robot.keyRelease(KeyEvent.VK_DOWN);
    } catch (AWTException e) {
        e.printStackTrace();
    }
    WebElement chartExportOptions = this.elemHelper.FindElement(driver, By.xpath("//body/ul"));
    assertNotNull(chartExportOptions);
    String chartOption1 = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//body/ul/li/a"));
    String chartOption2 = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//body/ul/li[2]/a"));
    assertEquals("chart", chartOption1);
    assertEquals("countryChart", chartOption2);
    this.elemHelper.Click(driver, By.xpath("//body/ul/li/a"));

    /* 
     * ## Step 5 
      */
    //Open options for Data Component to Export and assert "table", "chart" and "countryChart"
    WebElement dataExportProperty = this.elemHelper.FindElement(driver, By.xpath(
            "//table[@id='table-cdfdd-components-properties']//td[@title='Id for Data Component to Export']/../td[2]"));
    assertNotNull(dataExportProperty);
    dataExportProperty.click();
    WebElement dataExportInput = this.elemHelper.FindElement(driver, By.xpath(
            "//table[@id='table-cdfdd-components-properties']//td[@title='Id for Data Component to Export']/../td[2]/form/input"));
    assertNotNull(dataExportInput);
    dataExportInput.clear();
    Robot robot1;
    try {
        robot1 = new Robot();
        robot1.keyPress(KeyEvent.VK_DOWN);
        robot1.keyRelease(KeyEvent.VK_DOWN);
    } catch (AWTException e) {
        e.printStackTrace();
    }
    WebElement dataExportOptions = this.elemHelper.FindElement(driver, By.xpath("//body/ul"));
    assertNotNull(dataExportOptions);
    String dataOption1 = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//body/ul/li/a"));
    String dataOption2 = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//body/ul/li[2]/a"));
    String dataOption3 = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//body/ul/li[3]/a"));
    assertEquals("table", dataOption1);
    assertEquals("chart", dataOption2);
    assertEquals("countryChart", dataOption3);

    /* 
     * ## Step 6 
     */
    driver.get(baseUrl + "api/repos/%3Apublic%3AIssues%3ACDF%3ACDF-548%3ACDF-548.wcdf/generatedContent");
    this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay"));

    //Click export Button
    WebElement exportChartButton = this.elemHelper.FindElement(driver, By.xpath("//div[@id='export']/div"));
    assertNotNull(exportChartButton);
    exportChartButton.click();

    //Assert popup and click Export Chart link
    WebElement exportChartLink = this.elemHelper.FindElement(driver, By.cssSelector("div.exportElement"));
    assertNotNull(exportChartLink);
    exportChartLink.click();

    //Assert chart popup
    WebElement exportChartPopup = this.elemHelper.FindElement(driver, By.id("fancybox-content"));
    assertNotNull(exportChartPopup);

    // Check URL of displayed image
    String chartSRCUrl = this.elemHelper.GetAttribute(driver,
            By.xpath("//div[@id='fancybox-content']/div/div/div/div[2]/img"), "src");
    assertEquals(baseUrl
            + "plugin/cgg/api/services/draw?outputType=png&script=%2Fpublic%2FIssues%2FCDF%2FCDF-548%2Fchart.js&paramcountries=France&paramcountries=USA&paramwidth=400&paramheight=400",
            chartSRCUrl);
    assertEquals(200, HttpUtils.GetResponseCode(chartSRCUrl, "admin", "password"));

    // Export chart and assert export was successful
    WebElement chartExportButton = this.elemHelper.FindElement(driver,
            By.cssSelector("div.exportChartPopupButton.exportChartOkButton"));
    assertNotNull(chartExportButton);

    //Click export and assert file is correctly downloaded
    try {
        //Delete the existence if exist
        new File(this.exportFilePath).delete();

        //Click to export
        chartExportButton.click();

        //Wait for file to be created in the destination dir
        DirectoryWatcher dw = new DirectoryWatcher();
        dw.WatchForCreate(downloadDir);

        //Check if the file really exist
        File exportFile = new File(this.exportFilePath);
        // assertTrue(exportFile.exists());

        //Wait for the file to be downloaded totally
        for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms
            long nSize = FileUtils.sizeOf(exportFile);
            //Since the file always contents the same data, we wait for the expected bytes
            if (nSize >= 10000) {
                break;
            }
            this.log.info("BeforeSleep " + nSize);
            Thread.sleep(100);
        }

        this.log.info("File size :" + FileUtils.sizeOf(exportFile));

        //Check if the file downloaded is the expected
        String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath()));
        assertEquals(md5, "c8c3ad02461f7b5c8a36ee2aec0eca95");

        //The delete file
        DeleteFile();

    } catch (Exception e) {
        this.log.error(e.getMessage());
    }

    // Close dialog box
    this.elemHelper.Click(driver, By.id("fancybox-close"));
    assertTrue(this.elemHelper.WaitForElementNotPresent(driver,
            By.xpath("//div[@id='fancybox-content']/div/div/div/div/div[1]")));

    /* 
     * ## Step 7
     */
    this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.exportElement"));
    //Click export Button
    WebElement exportCountryChartButton = this.elemHelper.FindElement(driver,
            By.xpath("//div[@id='export2']/div"));
    assertNotNull(exportCountryChartButton);
    exportCountryChartButton.click();

    //Assert popup and click Export Chart link
    WebElement exportCountryChartLink = this.elemHelper.FindElement(driver,
            By.xpath("//div[contains(text(),'Export Chart2')]"));
    assertNotNull(exportCountryChartLink);
    exportCountryChartLink.click();

    //Assert chart popup
    WebElement exportCountryChartPopup = this.elemHelper.FindElement(driver, By.id("fancybox-content"));
    assertNotNull(exportCountryChartPopup);

    // Check URL of displayed image
    String countryChartSRCUrl = this.elemHelper.GetAttribute(driver,
            By.xpath("//div[@id='fancybox-content']/div/div/div/div[2]/img"), "src");
    assertEquals(baseUrl
            + "plugin/cgg/api/services/draw?outputType=svg&script=%2Fpublic%2FIssues%2FCDF%2FCDF-548%2FcountryChart.js&paramwidth=400&paramheight=300",
            countryChartSRCUrl);
    assertEquals(200, HttpUtils.GetResponseCode(countryChartSRCUrl, "admin", "password"));

    // Export chart and assert export was successful
    WebElement countryChartExportButton = this.elemHelper.FindElement(driver,
            By.cssSelector("div.exportChartPopupButton.exportChartOkButton"));
    assertNotNull(countryChartExportButton);

    //Click export and assert file is correctly downloaded
    try {
        //Delete the existence if exist
        new File(this.exportFilePath2).delete();

        //Click to export
        countryChartExportButton.click();

        //Wait for file to be created in the destination dir
        DirectoryWatcher dw = new DirectoryWatcher();
        dw.WatchForCreate(downloadDir);

        //Check if the file really exist
        File exportFile = new File(this.exportFilePath2);
        // assertTrue(exportFile.exists());

        //Wait for the file to be downloaded totally
        for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms
            long nSize = FileUtils.sizeOf(exportFile);
            //Since the file always contents the same data, we wait for the expected bytes
            if (nSize >= 30000) {
                break;
            }
            this.log.info("BeforeSleep " + nSize);
            Thread.sleep(100);
        }

        this.log.info("File size :" + FileUtils.sizeOf(exportFile));

        //Check if the file downloaded is the expected
        String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath()));
        assertEquals(md5, "c0d04625306dd1f32afed115c0bf94be");

        //The delete file
        DeleteFile();

    } catch (Exception e) {
        this.log.error(e.getMessage());
    }

    // Close dialog box
    this.elemHelper.Click(driver, By.id("fancybox-close"));
    assertTrue(this.elemHelper.WaitForElementNotPresent(driver,
            By.xpath("//div[@id='fancybox-content']/div/div/div/div/div[1]")));
}

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final Shops addBuy(String shopName, String cost, Player player) {
    try {/*from   w  ww . j  a  v a  2s . c  om*/
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONObject shopObj = (JSONObject) jsonObj.get(shopName);

        // Make sure the shop exists
        if (shopObj == null) {
            player.sendMessage("\u00a76That shop does not exist!");
            return this;
        }

        String newItem = player.getItemInHand().getType().name();

        Bukkit.getLogger()
                .info("Player \"" + player.getDisplayName() + "\" added " + newItem + " to shop " + shopName);

        JSONArray shopItems = (JSONArray) shopObj.get("ShopItems");

        shopItems.add(newItem + ":buy:" + player.getItemInHand().getDurability());

        shopObj.put("ShopItems", shopItems);

        JSONObject itemStub = new JSONObject();
        itemStub.put("amount", Integer.toString(player.getItemInHand().getAmount()));
        itemStub.put("price", cost);
        itemStub.put("type", "buy");
        itemStub.put("durability", "" + player.getItemInHand().getDurability());

        shopObj.put(newItem + ":buy:" + player.getItemInHand().getDurability(), itemStub);

        jsonObj.put(shopName, shopObj);

        // Update Shops.json
        FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json");

        shopsJSON.write(jsonObj.toJSONString());

        shopsJSON.flush();
        shopsJSON.close();

        player.sendMessage("\u00a7aShop updated!");

        return this;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in addBuy()");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in addBuy()");
        e.printStackTrace();
    }

    return this;
}

From source file:co.cask.cdap.etl.tool.UpgradeTool.java

private static void convertFile(String configFilePath, String outputFilePath, ArtifactClient artifactClient)
        throws Exception {
    File configFile = new File(configFilePath);
    if (!configFile.exists()) {
        throw new IllegalArgumentException(configFilePath + " does not exist.");
    }//  w  w w  .j a v  a2s . co  m
    if (!configFile.isFile()) {
        throw new IllegalArgumentException(configFilePath + " is not a file.");
    }
    String fileContents = new String(Files.readAllBytes(configFile.toPath()), StandardCharsets.UTF_8);

    ETLAppRequest artifactFile = GSON.fromJson(fileContents, ETLAppRequest.class);
    if (!shouldUpgrade(artifactFile.artifact)) {
        throw new IllegalArgumentException("Cannot update for artifact " + artifactFile.artifact + ". "
                + "Please check the artifact is cdap-etl-batch or cdap-etl-realtime in the system scope of version 3.2.x.");
    }

    String version = ETLVersion.getVersion();

    File outputFile = new File(outputFilePath);
    String oldArtifactVersion = artifactFile.artifact.getVersion();
    if (BATCH_NAME.equals(artifactFile.artifact.getName())) {
        ArtifactSummary artifact = new ArtifactSummary(BATCH_NAME, version, ArtifactScope.SYSTEM);
        UpgradeContext upgradeContext = new BatchClientBasedUpgradeContext(Id.Namespace.DEFAULT,
                artifactClient);
        ETLBatchConfig config = convertBatchConfig(oldArtifactVersion, artifactFile.config.toString(),
                upgradeContext);
        AppRequest<ETLBatchConfig> updated = new AppRequest<>(artifact, config);
        try (BufferedWriter writer = Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8)) {
            writer.write(GSON.toJson(updated));
        }
    } else {
        ArtifactSummary artifact = new ArtifactSummary(REALTIME_NAME, version, ArtifactScope.SYSTEM);
        UpgradeContext upgradeContext = new RealtimeClientBasedUpgradeContext(Id.Namespace.DEFAULT,
                artifactClient);
        ETLRealtimeConfig config = convertRealtimeConfig(oldArtifactVersion, artifactFile.config.toString(),
                upgradeContext);
        AppRequest<ETLRealtimeConfig> updated = new AppRequest<>(artifact, config);
        try (BufferedWriter writer = Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8)) {
            writer.write(GSON.toJson(updated));
        }
    }

    LOG.info("Successfully converted application details from file " + configFilePath + ". "
            + "Results have been written to " + outputFilePath);
}

From source file:com.netscape.cmstools.client.ClientCertRequestCLI.java

public String generatePkcs10Request(File certDatabase, String password, String algorithm, String length,
        String subjectDN) throws Exception {

    File csrFile = File.createTempFile("pki-client-cert-request-", ".csr", certDatabase);
    csrFile.deleteOnExit();/*from www  . j  a va  2 s.co  m*/

    String lenOrCurve = "ec".equals(algorithm) ? "-c" : "-l";

    String[] commands = { "/usr/bin/PKCS10Client", "-d", certDatabase.getAbsolutePath(), "-p", password, "-a",
            algorithm, lenOrCurve, "" + length, "-o", csrFile.getAbsolutePath(), "-n", subjectDN };

    try {
        runExternal(commands);
    } catch (Exception e) {
        throw new Exception("CSR generation failed", e);
    }

    if (verbose) {
        System.out.println("CSR generated: " + csrFile);
    }

    return new String(Files.readAllBytes(csrFile.toPath()));
}

From source file:contact.Contact.java

/**
 * Create contact from Outlook.//  w w w . ja  va  2  s.  c  om
 */
public Contact(String strUid, String strEntryID, String strTitle, String strFirstName, String strMiddleName,
        String strLastName, String strSuffix, String strCompanyName, String strJobTitle,
        String strEmail1Address, String strEmail2Address, String strEmail3Address, String strWebPage,
        String strMobileTelephoneNumber, String strAssistantTelephoneNumber, String strCallbackTelephoneNumber,
        String strCarTelephoneNumber, String strCompanyMainTelephoneNumber, String strOtherTelephoneNumber,
        String strPrimaryTelephoneNumber, String strRadioTelephoneNumber, String strTTYTDDTelephoneNumber,
        String strBusinessTelephoneNumber, String strBusiness2TelephoneNumber, String strBusinessFaxNumber,
        String strHomeTelephoneNumber, String strHome2TelephoneNumber, String strHomeFaxNumber,
        String strHomeAddressCity, String strHomeAddressCountry, String strHomeAddressPostalCode,
        String strHomeAddressState, String strHomeAddressStreet, String strBusinessAddressCity,
        String strBusinessAddressCountry, String strBusinessAddressPostalCode, String strBusinessAddressState,
        String strBusinessAddressStreet, String strBody, Calendar calBirthday, Calendar calAnniversary,
        String strPathToTmpPicture, String strLastModificationTime) {

    this.statusContact = Status.READIN;

    this.vcard = new VCard();

    //Legacy Correction with regards to the UID string which is included in the Body/Note field
    if (strUid.isEmpty()) {
        strUid = LegacyCorrectionUtilities.getBodyUID(strBody);
        this.statusContact = Status.UIDADDED;
    }

    if (strUid.isEmpty()) {
        this.vcard.setUid(Uid.random());
        this.statusContact = Status.UIDADDED;
    } else {
        this.vcard.setUid(new Uid(strUid.trim()));
    }
    this.strUid = this.vcard.getUid().getValue();

    this.strFileOnDavServer = null;

    if (strEntryID.length() > 0) {
        this.strEntryID = strEntryID;
    }

    if (strTitle.length() > 0 || strFirstName.length() > 0 || strMiddleName.length() > 0
            || strLastName.length() > 0 || strSuffix.length() > 0) {
        StructuredName sn = new StructuredName();
        sn.addPrefix(strTitle);
        sn.setGiven(strFirstName);
        sn.addAdditional(strMiddleName);
        sn.setFamily(strLastName);
        sn.addSuffix(strSuffix);
        this.vcard.setStructuredName(sn);
    }

    if (strCompanyName.length() > 0) {
        Organization org = new Organization();
        org.addValue(strCompanyName);
        this.vcard.setOrganization(org);
    }

    if (strJobTitle.length() > 0) {
        this.vcard.addTitle(new Title(strJobTitle));
    }

    if (strEmail1Address.length() > 0) {
        Email email = new Email(strEmail1Address);
        email.addType(EmailType.HOME);
        this.vcard.addEmail(email);
    }

    if (strEmail2Address.length() > 0) {
        Email email = new Email(strEmail2Address);
        email.addType(EmailType.WORK);
        this.vcard.addEmail(email);
    }

    if (strEmail3Address.length() > 0) {
        Email email = new Email(strEmail3Address);
        email.addType(EmailType.INTERNET);
        this.vcard.addEmail(email);
    }

    if (strWebPage.length() > 0) {
        this.vcard.addUrl(new Url(strWebPage));
    }

    if (strMobileTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strMobileTelephoneNumber);
        tel.addType(TelephoneType.CELL);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strAssistantTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strAssistantTelephoneNumber);
        tel.addType(TelephoneType.BBS);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strCallbackTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strCallbackTelephoneNumber);
        tel.addType(TelephoneType.MODEM);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strCarTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strCarTelephoneNumber);
        tel.addType(TelephoneType.PAGER);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strCompanyMainTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strCompanyMainTelephoneNumber);
        tel.addType(TelephoneType.PCS);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strOtherTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strOtherTelephoneNumber);
        tel.addType(TelephoneType.PREF);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strPrimaryTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strPrimaryTelephoneNumber);
        tel.addType(TelephoneType.VIDEO);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strRadioTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strRadioTelephoneNumber);
        tel.addType(TelephoneType.VOICE);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strTTYTDDTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strTTYTDDTelephoneNumber);
        tel.addType(TelephoneType.TEXT);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strBusinessTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strBusinessTelephoneNumber);
        tel.addType(TelephoneType.WORK);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strBusiness2TelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strBusiness2TelephoneNumber);
        tel.addType(TelephoneType.CAR);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strBusinessFaxNumber.length() > 0) {
        Telephone tel = new Telephone(strBusinessFaxNumber);
        tel.addType(TelephoneType.FAX);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strHomeTelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strHomeTelephoneNumber);
        tel.addType(TelephoneType.HOME);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strHome2TelephoneNumber.length() > 0) {
        Telephone tel = new Telephone(strHome2TelephoneNumber);
        tel.addType(TelephoneType.ISDN);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strHomeFaxNumber.length() > 0) {
        Telephone tel = new Telephone(strHomeFaxNumber);
        tel.addType(TelephoneType.MSG);
        this.vcard.addTelephoneNumber(tel);
    }

    if (strHomeAddressStreet.length() > 0 || strHomeAddressCity.length() > 0 || strHomeAddressState.length() > 0
            || strHomeAddressPostalCode.length() > 0 || strHomeAddressCountry.length() > 0) {
        Address adr = new Address();
        adr.setStreetAddress(strHomeAddressStreet);
        adr.setLocality(strHomeAddressCity);
        adr.setRegion(strHomeAddressState);
        adr.setPostalCode(strHomeAddressPostalCode);
        adr.setCountry(strHomeAddressCountry);
        adr.addType(AddressType.HOME);
        this.vcard.addAddress(adr);
    }

    if (strBusinessAddressStreet.length() > 0 || strBusinessAddressCity.length() > 0
            || strBusinessAddressState.length() > 0 || strBusinessAddressPostalCode.length() > 0
            || strBusinessAddressCountry.length() > 0) {
        Address adr = new Address();
        adr.setStreetAddress(strBusinessAddressStreet);
        adr.setLocality(strBusinessAddressCity);
        adr.setRegion(strBusinessAddressState);
        adr.setPostalCode(strBusinessAddressPostalCode);
        adr.setCountry(strBusinessAddressCountry);
        adr.addType(AddressType.WORK);
        this.vcard.addAddress(adr);
    }

    if (strBody.length() > 0) {
        Note note = new Note(strBody);
        this.vcard.addNote(note);
    }

    if (calBirthday != null) {
        this.vcard.setBirthday(new Birthday(calBirthday.getTime()));
    }

    if (calAnniversary != null) {
        this.vcard.setAnniversary(new Anniversary(calAnniversary.getTime()));
    }

    if (strPathToTmpPicture != null) {
        this.strPathToContactPicture = strPathToTmpPicture;

        File tmpFile = new File(this.strPathToContactPicture);
        if (tmpFile.exists()) {
            try {
                this.vcard.addPhoto(new Photo(Files.readAllBytes(tmpFile.toPath()), ImageType.JPEG));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
        this.dateLastModificationTme = sdf.parse(strLastModificationTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:io.frictionlessdata.datapackage.Package.java

private String getJsonStringContentFromLocalFile(String absoluteFilePath) throws JSONException {
    // Read file, it should be a JSON.
    try {//from  ww  w .j  a  v a  2s . c  o  m
        String jsonString = new String(Files.readAllBytes(Paths.get(absoluteFilePath)));
        return jsonString;

    } catch (IOException ioe) {
        // FIXME: Come up with better exception handling?
        return null;
    }
}

From source file:SdkUnitTests.java

@Test
public void CreateTemplateTest() {

    byte[] fileBytes = null;
    File f = null;/* w  w  w.  j  a  v a 2 s . c om*/
    try {
        //  String currentDir = new java.io.File(".").getCononicalPath();

        String currentDir = System.getProperty("user.dir");

        Path path = Paths.get(currentDir + SignTest1File);
        fileBytes = Files.readAllBytes(path);

        f = new File(path.toString());
    } catch (IOException ioExcp) {
        Assert.assertEquals(null, ioExcp);
    }

    // create an envelope to be signed

    EnvelopeTemplate templateDef = new EnvelopeTemplate();
    templateDef.setEmailSubject("Please Sign my Java SDK Envelope");
    templateDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");

    // add a document to the envelope
    Document doc = new Document();
    String base64Doc = Base64.getEncoder().encodeToString(fileBytes);
    doc.setDocumentBase64(base64Doc);
    doc.setName("TestFile.pdf");
    doc.setDocumentId("1");

    List<Document> docs = new ArrayList<Document>();
    docs.add(doc);
    templateDef.setDocuments(docs);

    // Add a recipient to sign the document
    Signer signer = new Signer();
    signer.setRoleName("Signer1");
    signer.setRecipientId("1");

    // Create a SignHere tab somewhere on the document for the signer to sign
    SignHere signHere = new SignHere();
    signHere.setDocumentId("1");
    signHere.setPageNumber("1");
    signHere.setRecipientId("1");
    signHere.setXPosition("100");
    signHere.setYPosition("100");

    List<SignHere> signHereTabs = new ArrayList<SignHere>();
    signHereTabs.add(signHere);
    Tabs tabs = new Tabs();
    tabs.setSignHereTabs(signHereTabs);
    signer.setTabs(tabs);

    templateDef.setRecipients(new Recipients());
    templateDef.getRecipients().setSigners(new ArrayList<Signer>());
    templateDef.getRecipients().getSigners().add(signer);

    EnvelopeTemplateDefinition envTemplateDef = new EnvelopeTemplateDefinition();
    envTemplateDef.setName("myTemplate");
    templateDef.setEnvelopeTemplateDefinition(envTemplateDef);

    try {

        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath(BaseUrl);

        String creds = createAuthHeaderCreds(UserName, Password, IntegratorKey);
        apiClient.addDefaultHeader("X-DocuSign-Authentication", creds);
        Configuration.setDefaultApiClient(apiClient);

        AuthenticationApi authApi = new AuthenticationApi();
        LoginInformation loginInfo = authApi.login();

        Assert.assertNotNull(loginInfo);
        Assert.assertNotNull(loginInfo.getLoginAccounts());
        Assert.assertTrue(loginInfo.getLoginAccounts().size() > 0);
        List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts();
        Assert.assertNotNull(loginAccounts.get(0).getAccountId());

        String accountId = loginInfo.getLoginAccounts().get(0).getAccountId();

        TemplatesApi templatesApi = new TemplatesApi();
        TemplateSummary templateSummary = templatesApi.createTemplate(accountId, templateDef);

        Assert.assertNotNull(templateSummary);
        Assert.assertNotNull(templateSummary.getTemplateId());

        System.out.println("TemplateSummary: " + templateSummary);

    } catch (ApiException ex) {
        System.out.println("Exception: " + ex);
        Assert.assertEquals(null, ex);
    }
}