Example usage for java.sql Timestamp toString

List of usage examples for java.sql Timestamp toString

Introduction

In this page you can find the example usage for java.sql Timestamp toString.

Prototype

@SuppressWarnings("deprecation")
public String toString() 

Source Link

Document

Formats a timestamp in JDBC timestamp escape format.

Usage

From source file:org.apache.stratos.usage.summary.helper.util.DataAccessObject.java

public String getAndUpdateLastCartridgeStatsHourlyTimestamp() throws SQLException {

    Timestamp lastSummaryTs = null;
    Connection connection = null;

    try {/*from w ww .j  a  v a 2  s.co m*/
        connection = dataSource.getConnection();
        String sql = "SELECT TIMESTMP FROM CARTRIDGE_STATS_LAST_HOURLY_TS WHERE ID='LatestTS'";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            lastSummaryTs = resultSet.getTimestamp("TIMESTMP");
        } else {
            lastSummaryTs = new Timestamp(0);
        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
        Timestamp currentTs = Timestamp.valueOf(formatter.format(new Date()));

        String currentSql = "INSERT INTO CARTRIDGE_STATS_LAST_HOURLY_TS (ID, TIMESTMP) VALUES('LatestTS',?) ON DUPLICATE KEY UPDATE TIMESTMP=?";
        PreparedStatement ps1 = connection.prepareStatement(currentSql);
        ps1.setTimestamp(1, currentTs);
        ps1.setTimestamp(2, currentTs);
        ps1.execute();

    } catch (SQLException e) {
        log.error(
                "Error occurred while trying to get and update the last hourly timestamp for cartridge stats. ",
                e);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }

    return lastSummaryTs.toString();
}

From source file:org.apache.stratos.usage.summary.helper.util.DataAccessObject.java

public String getAndUpdateLastCartridgeStatsMonthlyTimestamp() throws SQLException {

    Timestamp lastSummaryTs = null;
    Connection connection = null;

    try {/*from   w  w w  .j a va 2 s  .  co m*/
        connection = dataSource.getConnection();
        String sql = "SELECT TIMESTMP FROM CARTRIDGE_STATS_LAST_MONTHLY_TS WHERE ID='LatestTS'";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            lastSummaryTs = resultSet.getTimestamp("TIMESTMP");
        } else {
            lastSummaryTs = new Timestamp(0);
        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Timestamp currentTs = Timestamp.valueOf(formatter.format(new Date()));

        String currentSql = "INSERT INTO CARTRIDGE_STATS_LAST_MONTHLY_TS (ID, TIMESTMP) VALUES('LatestTS',?) ON DUPLICATE KEY UPDATE TIMESTMP=?";
        PreparedStatement ps1 = connection.prepareStatement(currentSql);
        ps1.setTimestamp(1, currentTs);
        ps1.setTimestamp(2, currentTs);
        ps1.execute();

    } catch (SQLException e) {
        log.error(
                "Error occurred while trying to get and update the last monthly timestamp for cartridge stats. ",
                e);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }

    return lastSummaryTs.toString();
}

From source file:org.epics.archiverappliance.retrieval.DataRetrievalServlet.java

/**
 * Parse the timeranges parameter and generate a list of TimeSpans.
 * @param resp//from  w w w. jav a2s  .c om
 * @param pvName
 * @param requestTimes - list of timespans that we add the valid times to.
 * @param timeRangesStr
 * @return
 * @throws IOException
 */
private boolean parseTimeRanges(HttpServletResponse resp, String pvName, LinkedList<TimeSpan> requestTimes,
        String timeRangesStr) throws IOException {
    String[] timeRangesStrList = timeRangesStr.split(",");
    if (timeRangesStrList.length % 2 != 0) {
        String msg = "Need to specify an even number of times in timeranges for pv " + pvName + ". We have "
                + timeRangesStrList.length + " times";
        logger.error(msg);
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return false;
    }

    LinkedList<Timestamp> timeRangesList = new LinkedList<Timestamp>();
    for (String timeRangesStrItem : timeRangesStrList) {
        try {
            Timestamp ts = TimeUtils.convertFromISO8601String(timeRangesStrItem);
            timeRangesList.add(ts);
        } catch (IllegalArgumentException ex) {
            try {
                Timestamp ts = TimeUtils.convertFromDateTimeStringWithOffset(timeRangesStrItem);
                timeRangesList.add(ts);
            } catch (IllegalArgumentException ex2) {
                String msg = "Cannot parse time " + timeRangesStrItem;
                logger.warn(msg, ex2);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return false;
            }
        }
    }

    assert (timeRangesList.size() % 2 == 0);
    Timestamp prevEnd = null;
    while (!timeRangesList.isEmpty()) {
        Timestamp t0 = timeRangesList.pop();
        Timestamp t1 = timeRangesList.pop();

        if (t1.before(t0)) {
            String msg = "For request, end " + t1.toString() + " is before start " + t0.toString() + " for pv "
                    + pvName;
            logger.error(msg);
            resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return false;
        }

        if (prevEnd != null) {
            if (t0.before(prevEnd)) {
                String msg = "For request, start time " + t0.toString() + " is before previous end time "
                        + prevEnd.toString() + " for pv " + pvName;
                logger.error(msg);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return false;
            }
        }
        prevEnd = t1;
        requestTimes.add(new TimeSpan(t0, t1));
    }
    return true;
}

From source file:com.krawler.esp.portalmsg.Forum.java

public static String insertForumPost(Connection conn, String repto, String title, String ptext, String u_id,
        String group_id, int firstReply) throws ServiceException, ParseException, JSONException {
    DbResults rs = null;// w ww.  j ava2s  . c  om
    DbResults rs1 = null;
    DbResults rs2 = null;
    String post_id = UUID.randomUUID().toString();
    String topic_id = "1";
    String topic_title = null;
    String UserName = null;
    String Image = null;

    String query = null;
    JSONStringer j = new JSONStringer();
    JSONObject jobj = new JSONObject();
    String temp = null;

    repto = repto;
    title = StringUtil.serverHTMLStripper(title);
    ptext = ptext;
    u_id = u_id;
    group_id = StringUtil.serverHTMLStripper(group_id);
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    java.util.Date d = new java.util.Date();
    java.sql.Timestamp sqlPostDate = new Timestamp(d.getTime());
    if (StringUtil.isNullOrEmpty(repto) /*|| StringUtil.isNullOrEmpty(title)*/ || StringUtil.isNullOrEmpty(u_id)
            || StringUtil.isNullOrEmpty(group_id)) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    if (firstReply == 0) {

        query = "INSERT INTO krawlerforum_topics(topic_id, group_id, topic_title, topic_poster, post_time, post_subject,post_text, ifread,flag) VALUES (?, ?, ?, ?, ?, ?,?, ?, ?)";
        DbUtil.executeUpdate(conn, query,
                new Object[] { post_id, group_id, title, u_id, sqlPostDate, ptext, ptext, false, false });

        post_id = "topic" + post_id;
    } else if (firstReply == 1) {
        repto = repto.substring(5);

        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title,post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, repto, false, false, "-999" });

        repto = "topic" + repto;
    } else if (firstReply == 2) {
        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title, post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, "1", false, false, repto });

    }

    query = "SELECT userlogin.username,image FROM users inner join userlogin on users.userid=userlogin.userid where users.userid=?;";
    rs2 = DbUtil.executeQuery(conn, query, u_id);

    if (rs2.next()) {
        UserName = (rs2.getString(1));
        Image = (rs2.getString(2));
    }
    String userTime = Timezone.toCompanyTimezone(conn, sqlPostDate.toString(),
            CompanyHandler.getCompanyByUser(conn, u_id));
    java.util.Date tempdate = sdf.parse(userTime);
    com.krawler.utils.json.base.JSONObject jtemp = new com.krawler.utils.json.base.JSONObject();
    jtemp.put("Success", "Success");
    jtemp.put("ID", post_id);
    jtemp.put("Subject", title);
    jtemp.put("Received", sdf.format(tempdate));
    jtemp.put("From", UserName);
    jtemp.put("Details", "");
    jtemp.put("Flag", "false");
    jtemp.put("Image", Image);
    jtemp.put("Parent", repto);
    jobj.append("data", jtemp);
    /*temp = j.object().key("Success").value("Success").key("ID").value(
    post_id).key("Subject").value(title).key("Received").value(
    sdf1.format(tempdate).toString()).key("From").value(UserName)
    .key("Details").value("").key("Flag").value("false").key(
    "Image").value(Image).key("Parent").value(repto)
    .endObject().toString();*/
    return jobj.toString();
}

From source file:com.collabnet.ccf.core.AbstractReader.java

/**
 * Update the sync info with the artifact lastmodifiedtime and
 * lastModifiedVersion fetched from the identity mapping. This will makes
 * reader to sync all the comments and attachment in an artifact, as Sync is
 * based on Artifact last modified timestamp or last modified version as
 * previously it was based on repository lastmodifiedtime or version. This
 * will resolve the leftover comments/attachments during stale scenario.
 * /*from  w  ww .ja v  a  2 s. c o  m*/
 * @param syncInfo
 * @param artifactId
 * @param artifactType
 */
private void updateSyncInfoFromIdentityMapping(Document syncInfo, String artifactId, String artifactType) {
    IOrderedMap inputParameters = new OrderedHashMap();
    String lastModifiedTime = null, lastModifiedVersion = null;
    if (!isCCF2xProcess) {
        inputParameters.add(this.getSourceSystemId(syncInfo));//sourceSystemId
        inputParameters.add(this.getSourceRepositoryId(syncInfo));//sourceRepositoryId
        inputParameters.add(this.getTargetSystemId(syncInfo));//targetSystemId
        inputParameters.add(this.getTargetRepositoryId(syncInfo));//targetRepositoryId
    } else {
        inputParameters.add(this.getRepositoryMappingId(syncInfo));//repositorymappingid
    }
    inputParameters.add(artifactId);//artifactId
    inputParameters.add(artifactType);//artifactType
    try {
        identityMappingDatabaseReader.connect();
        Object[] resultSet = identityMappingDatabaseReader.next(inputParameters, 1000);
        if (resultSet == null || resultSet.length == 0) {
            lastModifiedTime = new Timestamp(0).toString();
            lastModifiedVersion = "0";
            log.debug("Setting the lastModifiedTime and lastModifiedVersion to default values");
        } else {
            IOrderedMap resultSetMap = (OrderedHashMap) resultSet[0];
            Timestamp lastModifiedTimestamp = (java.sql.Timestamp) resultSetMap.get(1);
            lastModifiedVersion = (String) resultSetMap.get(2);
            lastModifiedTime = lastModifiedTimestamp.toString();
        }
        modifySyncInfo(syncInfo, lastModifiedTime, lastModifiedVersion);
    } catch (Exception e) {
        log.debug("Update syncInfo from IdentityMapping failed due to following exception ", e);
    }
}

From source file:org.jboss.bqt.client.xml.XMLQueryVisitationStrategy.java

/**
 * Produce an XML message for an instance of the Timestamp.
 * <br>/*from  ww w .j a  v  a 2 s.c  om*/
 * @param object the instance for which the message is to be produced.
 * @param parent the XML element that is to be the parent of the produced XML message.
 * @return the root element of the XML segment that was produced.
 * @exception JDOMException if there is an error producing the message.
 */
private Element produceMsg(Timestamp object, Element parent) throws JDOMException {

    // ----------------------
    // Create the Timestamp element ...
    // ----------------------
    Element timestampElement = new Element(TagNames.Elements.TIMESTAMP);
    timestampElement.setText(object.toString());
    if (parent != null) {
        timestampElement = parent.addContent(timestampElement);
    }

    return timestampElement;
}

From source file:com.krawler.esp.portalmsg.Forum.java

public static String insertForumPost(Connection conn, HttpServletRequest request)
        throws ServiceException, ParseException, JSONException {
    org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
    java.util.List fileItems = null;
    org.apache.commons.fileupload.FileItem fi = null;
    int sizeinmb = forummsgcomm.getmaxfilesize(conn, AuthHandler.getCompanyid(request, false));
    long maxsize = sizeinmb * 1024 * 1024;
    boolean fileupload = false;
    fu.setSizeMax(maxsize);//from  w ww  . j a va  2  s  .c  om
    java.util.HashMap arrParam = new java.util.HashMap();
    JSONObject jobj = new JSONObject();
    try {
        fileItems = fu.parseRequest(request);
    } catch (org.apache.commons.fileupload.FileUploadException e) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jerrtemp.put("msg", "Problem while uploading file.");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
        fi = (org.apache.commons.fileupload.FileItem) k.next();
        arrParam.put(fi.getFieldName(), fi.getString());
        if (!fi.isFormField()) {
            if (fi.getSize() > maxsize) {
                com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
                jerrtemp.put("Success", "Fail");
                jerrtemp.put("msg", "For attachments, maximum file size allowed is " + sizeinmb + " MB");
                jobj.append("data", jerrtemp);
                return jobj.toString();
            }
            fileupload = true;
        }
    }
    //                destinationDirectory = com.krawler.esp.handlers.StorageHandler
    //               .GetDocStorePath()
    int firstReply = Integer.parseInt(request.getParameter("firstReply"));
    String ptext = java.net.URLDecoder.decode(arrParam.get("ptxt").toString());
    String repto = request.getParameter("repto");
    String title = java.net.URLDecoder.decode(arrParam.get("title").toString());
    String u_id = request.getParameter("userId");
    String group_id = request.getParameter("groupId");
    DbResults rs = null;
    DbResults rs1 = null;
    DbResults rs2 = null;
    String post_id = UUID.randomUUID().toString();
    String topic_id = "1";
    String topic_title = null;
    String dateTime = null;
    String UserName = null;
    String Image = null;
    String query = null;
    JSONStringer j = new JSONStringer();

    String temp = null;
    title = StringUtil.serverHTMLStripper(title);

    group_id = StringUtil.serverHTMLStripper(group_id);
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    java.util.Date d = new java.util.Date();
    java.sql.Timestamp sqlPostDate = new Timestamp(d.getTime());
    if (StringUtil.isNullOrEmpty(repto) /*|| StringUtil.isNullOrEmpty(title)*/ || StringUtil.isNullOrEmpty(u_id)
            || StringUtil.isNullOrEmpty(group_id)) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    if (fileupload) {
        forummsgcomm.doPost(conn, fileItems, post_id, sqlPostDate, u_id, "");
    }
    if (firstReply == 0) {

        query = "INSERT INTO krawlerforum_topics(topic_id, group_id, topic_title, topic_poster, post_time, post_subject,post_text, ifread,flag) VALUES (?, ?, ?, ?, ?, ?,?, ?, ?)";
        DbUtil.executeUpdate(conn, query,
                new Object[] { post_id, group_id, title, u_id, sqlPostDate, ptext, ptext, false, false });

        post_id = "topic" + post_id;
    } else if (firstReply == 1) {
        repto = repto.substring(5);

        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title,post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, repto, false, false, "-999" });

        repto = "topic" + repto;
    } else if (firstReply == 2) {
        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title, post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, "1", false, false, repto });

    }

    query = "SELECT userlogin.username,image FROM users inner join userlogin on users.userid = userlogin.userid where users.userid=?;";
    rs2 = DbUtil.executeQuery(conn, query, u_id);

    if (rs2.next()) {
        UserName = (rs2.getString(1));
        Image = (rs2.getString(2));
    }
    String userTime = Timezone.toCompanyTimezone(conn, sqlPostDate.toString(),
            CompanyHandler.getCompanyByUser(conn, u_id));
    java.util.Date tempdate = sdf.parse(userTime);
    com.krawler.utils.json.base.JSONObject jtemp = new com.krawler.utils.json.base.JSONObject();
    jtemp.put("Success", "Success");
    jtemp.put("ID", post_id);
    jtemp.put("Subject", title);
    jtemp.put("Received", sdf.format(tempdate));
    jtemp.put("From", UserName);
    jtemp.put("Details", "");
    jtemp.put("Flag", "false");
    jtemp.put("Image", Image);
    jtemp.put("Parent", repto);
    jobj.append("data", jtemp);
    /*temp = j.object().key("Success").value("Success").key("ID").value(
    post_id).key("Subject").value(title).key("Received").value(
    sdf1.format(tempdate).toString()).key("From").value(UserName)
    .key("Details").value("").key("Flag").value("false").key(
    "Image").value(Image).key("Parent").value(repto)
    .endObject().toString();*/
    return jobj.toString();
}

From source file:pt.fct.di.benchmarks.TPCW_Riak.database.TPCW_Riak_Executor.java

public void CustomerRegistration(String costumer_id) throws Exception {

    String name = (BenchmarkUtil.getRandomAString(8, 13) + " " + BenchmarkUtil.getRandomAString(8, 15));
    String[] names = name.split(" ");
    Random r = new Random();
    int random_int = r.nextInt(1000);

    String key = names[0] + "_" + (costumer_id);

    String pass = names[0].charAt(0) + names[1].charAt(0) + "" + random_int;

    String first_name = names[0];

    String last_name = names[1];/*from   w  w w  . ja  v a  2 s .c om*/

    int phone = r.nextInt(999999999 - 100000000) + 100000000;

    String email = key + "@" + BenchmarkUtil.getRandomAString(2, 9) + ".com";

    double discount = r.nextDouble();

    String adress = "Street: "
            + (BenchmarkUtil.getRandomAString(8, 15) + " " + BenchmarkUtil.getRandomAString(8, 15))
            + " number: " + r.nextInt(500);

    double C_BALANCE = 0.00;

    double C_YTD_PMT = (double) BenchmarkUtil.getRandomInt(0, 99999) / 100.0;

    GregorianCalendar cal = new GregorianCalendar();
    cal.add(Calendar.DAY_OF_YEAR, -1 * BenchmarkUtil.getRandomInt(1, 730));

    java.sql.Date C_SINCE = new java.sql.Date(cal.getTime().getTime());

    cal.add(Calendar.DAY_OF_YEAR, BenchmarkUtil.getRandomInt(0, 60));
    if (cal.after(new GregorianCalendar())) {
        cal = new GregorianCalendar();
    }

    java.sql.Date C_LAST_LOGIN = new java.sql.Date(cal.getTime().getTime());

    java.sql.Timestamp C_LOGIN = new java.sql.Timestamp(System.currentTimeMillis());

    cal = new GregorianCalendar();
    cal.add(Calendar.HOUR, 2);

    java.sql.Timestamp C_EXPIRATION = new java.sql.Timestamp(cal.getTime().getTime());

    cal = BenchmarkUtil.getRandomDate(1880, 2000);
    java.sql.Date C_BIRTHDATE = new java.sql.Date(cal.getTime().getTime());

    String C_DATA = BenchmarkUtil.getRandomAString(100, 500);

    String address_id = insertAdress();

    Customer c = new Customer(costumer_id, key, pass, last_name, first_name, phone + "", email,
            C_SINCE.toString(), C_LAST_LOGIN.toString(), C_LOGIN.toString(), C_EXPIRATION.toString(), C_BALANCE,
            C_YTD_PMT, C_BIRTHDATE.toString(), C_DATA, discount, address_id);

    insert(costumer_id, "customer", c);

}

From source file:com.stratio.qa.specs.CommonG.java

/**
 * Capture a snapshot or an evidence in the driver
 *
 * @param driver driver used for testing
 * @param type type/*from   w ww  .  j  a  v  a2 s.  c  om*/
 * @param suffix suffix
 * @return String
 */
public String captureEvidence(WebDriver driver, String type, String suffix) {
    String testSuffix = System.getProperty("TESTSUFFIX");
    String dir = "./target/executions/";
    if (testSuffix != null) {
        dir = dir + testSuffix + "/";
    }

    String clazz = ThreadProperty.get("class");
    String currentBrowser = ThreadProperty.get("browser");
    String currentData = ThreadProperty.get("dataSet");

    if (!currentData.equals("")) {
        currentData = currentData.replaceAll("[\\\\|\\/|\\|\\s|:|\\*]", "_");
    }

    if (!"".equals(currentData)) {
        currentData = "-" + HashUtils.doHash(currentData);
    }

    Timestamp ts = new Timestamp(new java.util.Date().getTime());
    String outputFile = dir + clazz + "/" + ThreadProperty.get("feature") + "." + ThreadProperty.get("scenario")
            + "/" + currentBrowser + currentData + ts.toString() + suffix;

    outputFile = outputFile.replaceAll(" ", "_");

    if (type.endsWith("htmlSource")) {
        if (type.equals("framehtmlSource")) {
            boolean isFrame = (Boolean) ((JavascriptExecutor) driver)
                    .executeScript("return window.top != window.self");

            if (isFrame) {
                outputFile = outputFile + "frame.html";
            } else {
                outputFile = "";
            }
        } else if (type.equals("htmlSource")) {
            driver.switchTo().defaultContent();
            outputFile = outputFile + ".html";
        }

        if (!outputFile.equals("")) {
            String source = ((RemoteWebDriver) driver).getPageSource();

            File fout = new File(outputFile);
            boolean dirs = fout.getParentFile().mkdirs();

            FileOutputStream fos;
            try {
                fos = new FileOutputStream(fout, true);
                Writer out = new OutputStreamWriter(fos, "UTF8");
                PrintWriter writer = new PrintWriter(out, false);
                writer.append(source);
                writer.close();
                out.close();
            } catch (IOException e) {
                logger.error("Exception on evidence capture", e);
            }
        }

    } else if ("screenCapture".equals(type)) {
        outputFile = outputFile + ".png";
        File file = null;
        driver.switchTo().defaultContent();
        ((Locatable) driver.findElement(By.tagName("body"))).getCoordinates().inViewPort();

        if (currentBrowser.startsWith("chrome") || currentBrowser.startsWith("droidemu")) {
            Actions actions = new Actions(driver);
            actions.keyDown(Keys.CONTROL).sendKeys(Keys.HOME).perform();
            actions.keyUp(Keys.CONTROL).perform();

            file = chromeFullScreenCapture(driver);
        } else {
            file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        }
        try {
            FileUtils.copyFile(file, new File(outputFile));
        } catch (IOException e) {
            logger.error("Exception on copying browser screen capture", e);
        }
    }

    return outputFile;

}

From source file:fedora.server.access.dissemination.DisseminationService.java

/**
 * <p>//from  w  w w  . j a v a 2  s  .  c  o  m
 * Datastream locations are considered privileged information by the Fedora
 * repository. To prevent disclosing physical datastream locations to
 * external mechanism services, a proxy is used to disguise the datastream
 * locations. This method generates a temporary ID that maps to the physical
 * datastream location and registers this information in a memory resident
 * hashtable for subsequent resolution of the physical datastream location.
 * The servlet <code>DatastreamResolverServlet</code> provides the proxy
 * resolution service for datastreams.
 * </p>
 * <p>
 * </p>
 * <p>
 * The format of the tempID is derived from <code>java.sql.Timestamp</code>
 * with an arbitrary counter appended to the end to insure uniqueness. The
 * syntax is of the form:
 * <ul>
 * <p>
 * YYYY-MM-DD HH:mm:ss.mmm:dddddd where
 * </p>
 * <ul>
 * <li>YYYY - year (1900-8099)</li>
 * <li>MM - month (01-12)</li>
 * <li>DD - day (01-31)</li>
 * <li>hh - hours (0-23)</li>
 * <li>mm - minutes (0-59)</li>
 * <li>ss - seconds (0-59)</li>
 * <li>mmm - milliseconds (0-999)</li>
 * <li>dddddd - incremental counter (0-999999)</li>
 * </ul>
 * </ul>
 * 
 * @param dsLocation
 *        The physical location of the datastream.
 * @param dsControlGroupType
 *        The type of the datastream.
 * @return A temporary ID used to reference the physical location of the
 *         specified datastream
 * @throws ServerException
 *         If an error occurs in registering a datastream location.
 */
public String registerDatastreamLocation(String dsLocation, String dsControlGroupType,
        String beServiceCallbackRole, String methodName) throws ServerException {

    String tempID = null;
    Timestamp timeStamp = null;
    if (counter > 999999) {
        counter = 0;
    }
    long currentTime = new Timestamp(new Date().getTime()).getTime();
    long expireLimit = currentTime - (long) datastreamExpirationLimit * 1000;
    String dsMediatedServletPath = null;
    String dsMediatedCallbackHost = null;

    try {

        // Remove any datastream registrations that have expired.
        // The expiration limit can be adjusted using the Fedora config parameter
        // named "datastreamExpirationLimit" which is in seconds.
        for (Enumeration e = dsRegistry.keys(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            timeStamp = Timestamp.valueOf(extractTimestamp(key));
            if (expireLimit > timeStamp.getTime()) {
                dsRegistry.remove(key);
                LOG.debug("DatastreamMediationKey removed from Hash: " + key);
            }
        }

        // Register datastream.
        if (tempID == null) {
            timeStamp = new Timestamp(new Date().getTime());
            tempID = timeStamp.toString() + ":" + counter++;
            DatastreamMediation dm = new DatastreamMediation();
            dm.mediatedDatastreamID = tempID;
            dm.dsLocation = dsLocation;
            dm.dsControlGroupType = dsControlGroupType;
            dm.methodName = methodName;

            // See if datastream reference is to fedora server itself or an external location.
            // M and X type datastreams always reference fedora server. With E type datastreams
            // we must examine URL to see if this is referencing a remote datastream or is
            // simply a callback to the fedora server. If the reference is remote, then use
            // the role of the backend service that will make a callback for this datastream.
            // If the referenc s to the fedora server, use the special role of "fedoraInternalCall-1" to
            // denote that the callback will come from the fedora server itself.
            String beServiceRole = null;
            if (ServerUtility.isURLFedoraServer(dsLocation) || dsControlGroupType.equals("M")
                    || dsControlGroupType.equals("X")) {
                beServiceRole = BackendPolicies.FEDORA_INTERNAL_CALL;
            } else {
                beServiceRole = beServiceCallbackRole;
            }

            // Store beSecurity info in hash 
            Hashtable beHash = m_beSS.getSecuritySpec(beServiceRole, methodName);
            boolean beServiceCallbackBasicAuth = new Boolean((String) beHash.get("callbackBasicAuth"))
                    .booleanValue();
            boolean beServiceCallBasicAuth = new Boolean((String) beHash.get("callBasicAuth")).booleanValue();
            boolean beServiceCallbackSSL = new Boolean((String) beHash.get("callbackSSL")).booleanValue();
            boolean beServiceCallSSL = new Boolean((String) beHash.get("callSSL")).booleanValue();
            String beServiceCallUsername = (String) beHash.get("callUsername");
            String beServiceCallPassword = (String) beHash.get("callPassword");
            if (LOG.isDebugEnabled()) {
                LOG.debug("******************Registering datastream dsLocation: " + dsLocation);
                LOG.debug("******************Registering datastream dsControlGroupType: " + dsControlGroupType);
                LOG.debug("******************Registering datastream beServiceRole: " + beServiceRole);
                LOG.debug("******************Registering datastream beServiceCallbackBasicAuth: "
                        + beServiceCallbackBasicAuth);
                LOG.debug("******************Registering datastream beServiceCallBasicAuth: "
                        + beServiceCallBasicAuth);
                LOG.debug("******************Registering datastream beServiceCallbackSSL: "
                        + beServiceCallbackSSL);
                LOG.debug("******************Registering datastream beServiceCallSSL: " + beServiceCallSSL);
                LOG.debug("******************Registering datastream beServiceCallUsername: "
                        + beServiceCallUsername);
                LOG.debug("******************Registering datastream beServiceCallPassword: "
                        + beServiceCallPassword);
            }
            dm.callbackRole = beServiceRole;
            dm.callUsername = beServiceCallUsername;
            dm.callPassword = beServiceCallPassword;
            dm.callbackBasicAuth = beServiceCallbackBasicAuth;
            dm.callBasicAuth = beServiceCallBasicAuth;
            dm.callbackSSL = beServiceCallbackSSL;
            dm.callSSL = beServiceCallSSL;
            dsRegistry.put(tempID, dm);
            LOG.debug("DatastreammediationKey added to Hash: " + tempID);
        }

    } catch (Throwable th) {
        throw new DisseminationException("[DisseminationService] register" + "DatastreamLocation: "
                + "returned an error. The underlying error was a " + th.getClass().getName() + " The message "
                + "was \"" + th.getMessage() + "\" .");
    }

    // Replace the blank between date and time with the character "T".
    return tempID.replaceAll(" ", "T");
}