Example usage for java.lang Number longValue

List of usage examples for java.lang Number longValue

Introduction

In this page you can find the example usage for java.lang Number longValue.

Prototype

public abstract long longValue();

Source Link

Document

Returns the value of the specified number as a long .

Usage

From source file:com.imaginary.home.cloud.api.RestApi.java

public @Nullable String authenticate(@Nonnull String method, @Nonnull HttpServletRequest request,
        Map<String, Object> headers) throws RestException {
    Number timestamp = (Number) headers.get(TIMESTAMP);
    String apiKey = (String) headers.get(API_KEY);
    String signature = (String) headers.get(SIGNATURE);
    String version = (String) headers.get(VERSION);

    if (timestamp == null || apiKey == null || signature == null || version == null) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INCOMPLETE_HEADERS,
                "Incomplete authentication headers, requires: " + API_KEY + " - " + TIMESTAMP + " - "
                        + SIGNATURE + " - " + VERSION);
    }//from   w w  w. j  ava 2 s.com
    if (signature.length() < 1) {
        throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.NO_SIGNATURE,
                "No signature was provided for authentication");
    }
    try {
        ControllerRelay relay = ControllerRelay.getRelay(apiKey);
        String userId = null;
        String customSalt;
        String secret;

        if (relay == null) {
            ApiKey key = ApiKey.getApiKey(apiKey);

            if (key == null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_KEY,
                        "Invalid API key");
            }
            secret = key.getApiKeySecret();
            userId = key.getUserId();
            customSalt = userId;
        } else {
            secret = relay.getApiKeySecret();
            customSalt = relay.getLocationId();
        }
        String stringToSign;

        if (relay != null) {
            String token = Configuration.decrypt(relay.getLocationId(), relay.getToken());

            stringToSign = method.toLowerCase() + ":" + request.getPathInfo().toLowerCase() + ":" + apiKey + ":"
                    + token + ":" + timestamp.longValue() + ":" + version;
        } else {
            stringToSign = method.toLowerCase() + ":" + request.getPathInfo().toLowerCase() + ":" + apiKey + ":"
                    + timestamp.longValue() + ":" + version;
        }
        String expected;

        try {
            expected = CloudService.sign(Configuration.decrypt(customSalt, secret).getBytes("utf-8"),
                    stringToSign);
        } catch (Exception e) {
            throw new RestException(e);
        }
        if (!signature.equals(expected)) {
            throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_SIGNATURE,
                    "String to sign was: " + stringToSign);
        }
        return userId;
    } catch (PersistenceException e) {
        throw new RestException(e);
    }
}

From source file:org.cloudgraph.hbase.results.ResultsAggregator.java

private void initAggregate(FunctionPath funcPath, PlasmaDataGraph graph) {
    DataType scalarType = funcPath.getFunc().getName().getScalarDatatype(funcPath.getDataType());
    PlasmaDataObject newEndpoint = null;
    if (funcPath.getPath().size() == 0) {
        newEndpoint = (PlasmaDataObject) graph.getRootObject();
    } else {//from   w  ww.j a  va  2 s.c  o m
        newEndpoint = (PlasmaDataObject) graph.getRootObject().getDataObject(funcPath.getPath().toString());
    }

    if (funcPath.getFunc().getName().ordinal() == FunctionName.COUNT.ordinal()) {
        Long newCount = new Long(1);
        newEndpoint.set(funcPath.getFunc().getName(), funcPath.getProperty(), newCount);
        // FIXME: original scalar value is irrelevant for aggregates
        // but need for comparison
        // newEndpoint.unset(funcPath.getProperty());
    } else {
        if (newEndpoint.isSet(funcPath.getProperty())) {
            Object newValue = newEndpoint.get(funcPath.getProperty());
            Number newScalarValue = (Number) DataConverter.INSTANCE.convert(scalarType,
                    funcPath.getProperty().getType(), newValue);
            // newEndpoint.unset(funcPath.getProperty());
            switch (funcPath.getFunc().getName()) {
            case AVG:
                switch (scalarType) {
                case Double:
                    Double doubleAvg = newScalarValue.doubleValue();
                    newEndpoint.set(funcPath.getFunc().getName(), funcPath.getProperty(), doubleAvg);
                    break;
                case Float:
                    Float floatAvg = newScalarValue.floatValue();
                    newEndpoint.set(funcPath.getFunc().getName(), funcPath.getProperty(), floatAvg);
                    break;
                default:
                    throw new IllegalArgumentException("illsgal datatype (" + scalarType
                            + ") conversion for function, " + funcPath.getFunc().getName());
                }
                break;
            case MAX:
                newEndpoint.set(funcPath.getFunc().getName(), funcPath.getProperty(), newScalarValue);
                break;
            case MIN:
                newEndpoint.set(funcPath.getFunc().getName(), funcPath.getProperty(), newScalarValue);
                break;
            case SUM:
                switch (scalarType) {
                case Double:
                    Double sum = newScalarValue.doubleValue();
                    newEndpoint.set(funcPath.getFunc().getName(), funcPath.getProperty(), sum);
                    break;
                case Float:
                    Float floatSum = newScalarValue.floatValue();
                    newEndpoint.set(funcPath.getFunc().getName(), funcPath.getProperty(), floatSum);
                    break;
                case Long:
                    Long longSum = newScalarValue.longValue();
                    newEndpoint.set(funcPath.getFunc().getName(), funcPath.getProperty(), longSum);
                    break;
                default:
                    throw new IllegalArgumentException("illsgal datatype (" + scalarType
                            + ") conversion for function, " + funcPath.getFunc().getName());
                }
                break;
            case COUNT:
                break; // handled above
            default:
                throw new GraphServiceException(
                        "unimplemented aggregate function, " + funcPath.getFunc().getName());
            }
        } else if (!funcPath.getProperty().isNullable())
            log.warn("expected value for non-nullable property, " + funcPath.getProperty());
    }
}

From source file:com.glaf.core.jdbc.QueryHelper.java

/**
 * @param conn// ww w .  j  a  v  a 2  s .  c o  m
 *            ?
 * @param sqlExecutor
 *            
 * @return
 */
@SuppressWarnings("unchecked")
public List<Map<String, Object>> getResultList(Connection conn, SqlExecutor sqlExecutor) {
    if (!DBUtils.isLegalQuerySql(sqlExecutor.getSql())) {
        throw new RuntimeException(" SQL statement illegal ");
    }
    List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
    PreparedStatement psmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        psmt = conn.prepareStatement(sqlExecutor.getSql());
        if (sqlExecutor.getParameter() != null) {
            List<Object> values = (List<Object>) sqlExecutor.getParameter();
            JdbcUtils.fillStatement(psmt, values);
        }

        rs = psmt.executeQuery();

        if (conf.getBoolean("useMyBatisResultHandler", false)) {

            resultList = this.getResults(rs);

        } else {

            rsmd = rs.getMetaData();

            int count = rsmd.getColumnCount();
            List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();

            for (int index = 1; index <= count; index++) {
                int sqlType = rsmd.getColumnType(index);
                ColumnDefinition column = new ColumnDefinition();
                column.setIndex(index);
                column.setColumnName(rsmd.getColumnName(index));
                column.setColumnLabel(rsmd.getColumnLabel(index));
                column.setJavaType(FieldType.getJavaType(sqlType));
                column.setPrecision(rsmd.getPrecision(index));
                column.setScale(rsmd.getScale(index));
                if (column.getScale() == 0 && sqlType == Types.NUMERIC) {
                    column.setJavaType("Long");
                }
                column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase()));
                columns.add(column);
            }
            int startIndex = 1;
            while (rs.next() && startIndex <= 50000) {
                int index = 0;
                startIndex++;
                Map<String, Object> rowMap = new HashMap<String, Object>();
                Iterator<ColumnDefinition> iterator = columns.iterator();
                while (iterator.hasNext()) {
                    ColumnDefinition column = iterator.next();
                    String columnLabel = column.getColumnLabel();
                    String columnName = column.getColumnName();
                    if (StringUtils.isEmpty(columnName)) {
                        columnName = column.getColumnLabel();
                    }
                    columnName = columnName.toLowerCase();
                    String javaType = column.getJavaType();
                    index = index + 1;
                    if ("String".equals(javaType)) {
                        String value = rs.getString(column.getIndex());
                        if (value != null) {
                            value = value.trim();
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, value);
                        }
                    } else if ("Integer".equals(javaType)) {
                        try {
                            Integer value = rs.getInt(column.getIndex());
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, value);
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("integer:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.intValue());
                            rowMap.put(columnLabel, rowMap.get(columnName));
                            logger.debug("?:" + num.intValue());
                        }
                    } else if ("Long".equals(javaType)) {
                        try {
                            Long value = rs.getLong(column.getIndex());
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("long:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.longValue());
                            rowMap.put(columnLabel, num.longValue());
                            logger.debug("?:" + num.longValue());
                        }
                    } else if ("Double".equals(javaType)) {
                        try {
                            Double d = rs.getDouble(column.getIndex());
                            rowMap.put(columnName, d);
                            rowMap.put(columnLabel, d);
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("double:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.doubleValue());
                            rowMap.put(columnLabel, num.doubleValue());
                            logger.debug("?:" + num.doubleValue());
                        }
                    } else if ("Boolean".equals(javaType)) {
                        rowMap.put(columnName, rs.getBoolean(column.getIndex()));
                        rowMap.put(columnLabel, rowMap.get(columnName));
                    } else if ("Date".equals(javaType)) {
                        rowMap.put(columnName, rs.getTimestamp(column.getIndex()));
                        rowMap.put(columnLabel, rowMap.get(columnName));
                    } else if ("Blob".equals(javaType)) {
                        // ignore
                    } else {
                        Object value = rs.getObject(column.getIndex());
                        if (value != null) {
                            if (value instanceof String) {
                                value = (String) value.toString().trim();
                            }
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        }
                    }
                }
                rowMap.put("startIndex", startIndex);
                resultList.add(rowMap);
            }
        }

        logger.debug(">resultList size=" + resultList.size());
        return resultList;
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
        JdbcUtils.close(rs);
    }
}

From source file:com.glaf.core.jdbc.QueryHelper.java

/**
 * @param conn/*from  w  w  w  . ja  v  a2 s.  co  m*/
 *            ?
 * @param sqlExecutor
 *            ?
 * @param start
 *            0
 * @param pageSize
 *            ?
 * @return
 */
@SuppressWarnings("unchecked")
public List<Map<String, Object>> getResultList(Connection conn, SqlExecutor sqlExecutor, int start,
        int pageSize) {
    if (!DBUtils.isLegalQuerySql(sqlExecutor.getSql())) {
        throw new RuntimeException(" SQL statement illegal ");
    }
    List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
    String sql = sqlExecutor.getSql();
    PreparedStatement psmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    boolean supportsPhysicalPage = false;
    try {
        Dialect dialect = DBConfiguration.getDatabaseDialect(conn);
        if (dialect != null && dialect.supportsPhysicalPage()) {
            supportsPhysicalPage = true;
            sql = dialect.getLimitString(sql, start, pageSize);
            logger.debug("sql=" + sqlExecutor.getSql());
            logger.debug(">>sql=" + sql);
        }

        psmt = conn.prepareStatement(sql);
        if (sqlExecutor.getParameter() != null) {
            List<Object> values = (List<Object>) sqlExecutor.getParameter();
            JdbcUtils.fillStatement(psmt, values);
            logger.debug(">>values=" + values);
        }

        rs = psmt.executeQuery();

        if (conf.getBoolean("useMyBatisResultHandler", false)) {

            resultList = this.getResults(rs);

        } else {
            rsmd = rs.getMetaData();

            int count = rsmd.getColumnCount();
            List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();

            for (int i = 1; i <= count; i++) {
                int sqlType = rsmd.getColumnType(i);
                ColumnDefinition column = new ColumnDefinition();
                column.setIndex(i);
                column.setColumnName(rsmd.getColumnName(i));
                column.setColumnLabel(rsmd.getColumnLabel(i));
                column.setJavaType(FieldType.getJavaType(sqlType));
                column.setPrecision(rsmd.getPrecision(i));
                column.setScale(rsmd.getScale(i));
                if (column.getScale() == 0 && sqlType == Types.NUMERIC) {
                    column.setJavaType("Long");
                }
                column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase()));
                columns.add(column);
            }

            if (!supportsPhysicalPage) {
                logger.debug("---------------------skipRows:" + start);
                this.skipRows(rs, start, pageSize);
            }

            logger.debug("---------------------columns:" + columns.size());
            logger.debug("---------------------start:" + start);
            logger.debug("---------------------pageSize:" + pageSize);
            // int index = 0;
            while (rs.next()) {
                // index++;
                // logger.debug("---------------------row index:" + index);

                Map<String, Object> rowMap = new HashMap<String, Object>();
                Iterator<ColumnDefinition> iterator = columns.iterator();
                while (iterator.hasNext()) {
                    ColumnDefinition column = iterator.next();
                    String columnLabel = column.getColumnLabel();
                    String columnName = column.getColumnName();
                    if (StringUtils.isEmpty(columnName)) {
                        columnName = column.getColumnLabel();
                    }
                    columnName = columnName.toLowerCase();
                    String javaType = column.getJavaType();

                    if ("String".equals(javaType)) {
                        String value = rs.getString(column.getIndex());
                        if (value != null) {
                            value = value.trim();
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        }
                    } else if ("Integer".equals(javaType)) {
                        try {
                            Integer value = rs.getInt(column.getIndex());
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("integer:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.intValue());
                            rowMap.put(columnLabel, rowMap.get(columnName));
                            logger.debug("?:" + num.intValue());
                        }
                    } else if ("Long".equals(javaType)) {
                        try {
                            Long value = rs.getLong(column.getIndex());
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("long:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.longValue());
                            rowMap.put(columnLabel, rowMap.get(columnName));
                            logger.debug("?:" + num.longValue());
                        }
                    } else if ("Double".equals(javaType)) {
                        try {
                            Double d = rs.getDouble(column.getIndex());
                            rowMap.put(columnName, d);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("double:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.doubleValue());
                            rowMap.put(columnLabel, rowMap.get(columnName));
                            logger.debug("?:" + num.doubleValue());
                        }
                    } else if ("Boolean".equals(javaType)) {
                        rowMap.put(columnName, rs.getBoolean(column.getIndex()));
                        rowMap.put(columnLabel, rowMap.get(columnName));
                    } else if ("Date".equals(javaType)) {
                        rowMap.put(columnName, rs.getTimestamp(column.getIndex()));
                        rowMap.put(columnLabel, rowMap.get(columnName));
                    } else if ("Blob".equals(javaType)) {

                    } else {
                        Object value = rs.getObject(column.getIndex());
                        if (value != null) {
                            if (value instanceof String) {
                                value = (String) value.toString().trim();
                            }
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        }
                    }
                }
                resultList.add(rowMap);
            }
        }

        logger.debug(">resultList size = " + resultList.size());
        return resultList;
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
        JdbcUtils.close(rs);
    }
}

From source file:org.ohmage.query.impl.SurveyUploadQuery.java

/**
 * Creates the prompt response entry in the corresponding table and saves
 * any attached files, images, videos, etc..
 * /* w  w w  . j  a  va2 s. co m*/
 * @param username
 *        The username of the user saving this prompt response.
 * 
 * @param client
 *        The name of the device used to generate the response.
 * 
 * @param surveyResponseId
 *        The unique identifier for this survey response.
 * 
 * @param fileList
 *        The list of files saved to the disk, which should be a reference
 *        to a list that will be populated by this function.
 * 
 * @param promptUploadList
 *        The collection of prompt responses to store.
 * 
 * @param repeatableSetIteration
 *        If these prompt responses were part of a repeatable set, this is
 *        the iteration of that repeatable set; otherwise, null.
 * 
 * @param bufferedImageMap
 *        The map of image IDs to their contents.
 * 
 * @param videoContentsMap
 *        The map of video IDs to their contents.
 * 
 * @param transactionManager
 *        The manager for this transaction.
 * 
 * @param status
 *        The status of this transaction.
 * 
 * @throws DataAccessException
 *         There was an error saving the information.
 */
private void createPromptResponse(final String username, final String client, final Number surveyResponseId,
        final List<File> fileList, final Collection<Response> promptUploadList,
        final Integer repeatableSetIteration, final Map<UUID, Image> bufferedImageMap,
        final Map<String, Video> videoContentsMap, final Map<String, Audio> audioContentsMap,
        final DataSourceTransactionManager transactionManager, final TransactionStatus status)
        throws DataAccessException {

    for (Response response : promptUploadList) {
        if (response instanceof RepeatableSetResponse) {
            Map<Integer, Map<Integer, Response>> iterationToResponse = ((RepeatableSetResponse) response)
                    .getResponseGroups();

            for (Integer iteration : iterationToResponse.keySet()) {
                createPromptResponse(username, client, surveyResponseId, fileList,
                        iterationToResponse.get(iteration).values(), iteration, bufferedImageMap,
                        videoContentsMap, audioContentsMap, transactionManager, status);
            }
            continue;
        }
        final PromptResponse promptResponse = (PromptResponse) response;

        getJdbcTemplate().update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(SQL_INSERT_PROMPT_RESPONSE);
                ps.setLong(1, surveyResponseId.longValue());

                RepeatableSet parent = promptResponse.getPrompt().getParent();
                if (parent == null) {
                    ps.setNull(2, java.sql.Types.NULL);
                    ps.setNull(3, java.sql.Types.NULL);
                } else {
                    ps.setString(2, parent.getId());
                    ps.setInt(3, repeatableSetIteration);
                }
                ps.setString(4, promptResponse.getPrompt().getType().toString());
                ps.setString(5, promptResponse.getPrompt().getId());

                Object response = promptResponse.getResponse();
                if (response instanceof DateTime) {
                    ps.setString(6, DateTimeUtils.getW3cIso8601DateString((DateTime) response, true));
                } else if ((promptResponse instanceof MultiChoiceCustomPromptResponse)
                        && (response instanceof Collection)) {
                    JSONArray json = new JSONArray();

                    for (Object currResponse : (Collection<?>) response) {
                        json.put(currResponse);
                    }

                    ps.setString(6, json.toString());
                } else {
                    ps.setString(6, response.toString());
                }

                return ps;
            }
        });

        if (promptResponse instanceof PhotoPromptResponse) {
            // Grab the associated image and save it
            String imageId = promptResponse.getResponse().toString();

            // If it wasn't skipped and it was displayed, save the
            // associated images.
            if (!JsonInputKeys.PROMPT_SKIPPED.equals(imageId)
                    && !JsonInputKeys.PROMPT_NOT_DISPLAYED.equals(imageId)
                    && !JsonInputKeys.IMAGE_NOT_UPLOADED.equals(imageId)) {

                // Get the directory to save the image and save it.
                File originalFile;
                try {
                    originalFile = bufferedImageMap.get(UUID.fromString(imageId)).saveImage(getDirectory());
                } catch (DomainException e) {
                    rollback(transactionManager, status);
                    throw new DataAccessException("Error saving the images.", e);
                }

                // Get the image's URL.
                String url = "file://" + originalFile.getAbsolutePath();
                // Insert the image URL into the database.
                try {
                    getJdbcTemplate().update(SQL_INSERT_IMAGE, new Object[] { username, client, imageId, url });
                } catch (org.springframework.dao.DataAccessException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Error executing SQL '" + SQL_INSERT_IMAGE
                            + "' with parameters: " + username + ", " + client + ", " + imageId + ", " + url,
                            e);
                }
            }
        }
        // Save the video.
        else if (promptResponse instanceof VideoPromptResponse) {
            // Make sure the response contains an actual video response.
            Object responseValue = promptResponse.getResponse();
            if (!((responseValue instanceof NoResponse) || (responseValue instanceof NoResponseMedia))) {

                // Attempt to write it to the file system.
                try {
                    // Get the current video directory.
                    File currVideoDirectory = VideoDirectoryCache.getDirectory();

                    // Get the video ID.
                    String responseValueString = responseValue.toString();

                    // Get the video object.
                    Video video = videoContentsMap.get(responseValueString);

                    // Get the file.
                    File videoFile = new File(currVideoDirectory.getAbsolutePath() + "/" + responseValueString
                            + "." + video.getType());

                    // Get the video contents.
                    InputStream content = video.getContentStream();
                    if (content == null) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("The video contents did not exist in the map.");
                    }

                    // Write the video contents to disk.
                    FileOutputStream fos = new FileOutputStream(videoFile);

                    // Write the content to the output stream.
                    int bytesRead;
                    byte[] buffer = new byte[4096];
                    while ((bytesRead = content.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                    fos.close();

                    // Store the file reference in the video list.
                    fileList.add(videoFile);

                    // Get the video's URL.
                    String url = "file://" + videoFile.getAbsolutePath();

                    // Insert the video URL into the database.
                    try {
                        getJdbcTemplate().update(SQL_INSERT_IMAGE,
                                new Object[] { username, client, responseValueString, url });
                    } catch (org.springframework.dao.DataAccessException e) {
                        videoFile.delete();
                        transactionManager.rollback(status);
                        throw new DataAccessException(
                                "Error executing SQL '" + SQL_INSERT_IMAGE + "' with parameters: " + username
                                        + ", " + client + ", " + responseValueString + ", " + url,
                                e);
                    }
                }
                // If it fails, roll back the transaction.
                catch (DomainException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Could not get the video directory.", e);
                } catch (IOException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Could not write the file.", e);
                }
            }
        } else if (promptResponse instanceof AudioPromptResponse) {
            // Make sure the response contains an actual audio response.
            Object responseValue = promptResponse.getResponse();
            if (!((responseValue instanceof NoResponse) || (responseValue instanceof NoResponseMedia))) {

                // Attempt to write it to the file system.
                try {
                    // Get the current audio directory.
                    File currAudioDirectory = AudioDirectoryCache.getDirectory();

                    // Get the audio ID.
                    String responseValueString = responseValue.toString();

                    // Get the audio object.
                    Audio audio = audioContentsMap.get(responseValueString);

                    // Get the file.
                    File audioFile = new File(currAudioDirectory.getAbsolutePath() + "/" + responseValueString
                            + "." + audio.getType());

                    // Get the video contents.
                    InputStream content = audio.getContentStream();
                    if (content == null) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("The audio contents did not exist in the map.");
                    }

                    // Write the video contents to disk.
                    FileOutputStream fos = new FileOutputStream(audioFile);

                    // Write the content to the output stream.
                    int bytesRead;
                    byte[] buffer = new byte[4096];
                    while ((bytesRead = content.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                    fos.close();

                    // Store the file reference in the video list.
                    fileList.add(audioFile);

                    // Get the video's URL.
                    String url = "file://" + audioFile.getAbsolutePath();

                    // Insert the video URL into the database.
                    try {
                        getJdbcTemplate().update(SQL_INSERT_IMAGE,
                                new Object[] { username, client, responseValueString, url });
                    } catch (org.springframework.dao.DataAccessException e) {
                        audioFile.delete();
                        transactionManager.rollback(status);
                        throw new DataAccessException(
                                "Error executing SQL '" + SQL_INSERT_IMAGE + "' with parameters: " + username
                                        + ", " + client + ", " + responseValueString + ", " + url,
                                e);
                    }
                }
                // If it fails, roll back the transaction.
                catch (DomainException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Could not get the video directory.", e);
                } catch (IOException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Could not write the file.", e);
                }
            }
        }
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}/*from  ww  w .  j a v a 2s. c om*/
 * 
 * @see org.opencastproject.serviceregistry.api.ServiceRegistry#countByHost(java.lang.String, java.lang.String,
 *      org.opencastproject.job.api.Job.Status)
 */
@Override
public long countByHost(String serviceType, String host, Status status) throws ServiceRegistryException {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query query = em.createNamedQuery("Job.countByHost");
        query.setParameter("status", status);
        query.setParameter("serviceType", serviceType);
        query.setParameter("host", host);
        Number countResult = (Number) query.getSingleResult();
        return countResult.longValue();
    } catch (Exception e) {
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}//w w w .  j  a va2  s.c o m
 * 
 * @see org.opencastproject.serviceregistry.api.ServiceRegistry#countByOperation(java.lang.String, java.lang.String,
 *      org.opencastproject.job.api.Job.Status)
 */
@Override
public long countByOperation(String serviceType, String operation, Status status)
        throws ServiceRegistryException {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query query = em.createNamedQuery("Job.countByOperation");
        query.setParameter("status", status);
        query.setParameter("serviceType", serviceType);
        query.setParameter("operation", operation);
        Number countResult = (Number) query.getSingleResult();
        return countResult.longValue();
    } catch (Exception e) {
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}/*www. ja v a2 s  .com*/
 * 
 * @see org.opencastproject.serviceregistry.api.ServiceRegistry#count(java.lang.String,
 *      org.opencastproject.job.api.Job.Status)
 */
@Override
public long count(String serviceType, Status status) throws ServiceRegistryException {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query query;
        if (status == null) {
            query = em.createNamedQuery("Job.count.nullStatus");
        } else {
            query = em.createNamedQuery("Job.count");
            query.setParameter("status", status);
        }
        query.setParameter("serviceType", serviceType);
        Number countResult = (Number) query.getSingleResult();
        return countResult.longValue();
    } catch (Exception e) {
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}/*from  w w  w .  j ava  2  s  . com*/
 * 
 * @see org.opencastproject.serviceregistry.api.ServiceRegistry#count(java.lang.String, java.lang.String,
 *      java.lang.String, org.opencastproject.job.api.Job.Status)
 */
public long count(String serviceType, String host, String operation, Status status)
        throws ServiceRegistryException {
    if (StringUtils.isBlank(serviceType) || StringUtils.isBlank(host) || StringUtils.isBlank(operation)
            || status == null)
        throw new IllegalArgumentException("service type, host, operation, and status must be provided");
    Query query = null;
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        query = em.createNamedQuery("Job.fullMonty");
        query.setParameter("status", status);
        query.setParameter("serviceType", serviceType);
        query.setParameter("operation", operation);
        Number countResult = (Number) query.getSingleResult();
        return countResult.longValue();
    } catch (Exception e) {
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.openmicroscopy.shoola.agents.util.ui.ScriptingDialog.java

/** Initializes the components. */
private void initComponents() {
    sorter = new ViewerSorter();
    cancelButton = new JButton("Cancel");
    cancelButton.setToolTipText("Close the dialog.");
    cancelButton.setActionCommand("" + CANCEL);
    cancelButton.addActionListener(this);
    applyButton = new JButton("Run Script");
    applyButton.setToolTipText("Run the selected script.");
    applyButton.setActionCommand("" + APPLY);
    applyButton.addActionListener(this);
    IconManager icons = IconManager.getInstance();
    menuButton = new JButton(icons.getIcon(IconManager.FILTER_MENU));
    menuButton.setText("Script");
    menuButton.setHorizontalTextPosition(JButton.LEFT);
    menuButton.addMouseListener(new MouseAdapter() {

        public void mouseReleased(MouseEvent e) {
            Object src = e.getSource();
            if (src instanceof Component) {
                Point p = e.getPoint();
                createOptionMenu().show((Component) src, p.x, p.y);
            }//from   ww w . ja  v  a2 s .c o  m
        }
    });
    components = new LinkedHashMap<String, ScriptComponent>();
    componentsAll = new LinkedHashMap<String, ScriptComponent>();
    Map<String, ParamData> types = script.getInputs();
    if (types == null)
        return;
    List<ScriptComponent> results = new ArrayList<ScriptComponent>();
    Entry<String, ParamData> entry;
    ParamData param;
    JComponent comp;
    ScriptComponent c;
    String name;
    Class<?> type;
    Object defValue;
    Iterator<Entry<String, ParamData>> i = types.entrySet().iterator();
    List<Object> values;
    Number n;
    String details = "";
    String text = "";
    String grouping;
    String parent;
    Map<String, List<ScriptComponent>> childrenMap = new HashMap<String, List<ScriptComponent>>();
    List<ScriptComponent> l;
    int length;
    boolean columnsSet;
    while (i.hasNext()) {
        text = "";
        columnsSet = false;
        comp = null;
        entry = i.next();
        param = entry.getValue();
        name = entry.getKey();
        type = param.getPrototype();
        values = param.getValues();
        defValue = param.getDefaultValue();
        if (CollectionUtils.isNotEmpty(values)) {
            comp = createValuesBox(values, defValue);
        }
        if (Long.class.equals(type) || Integer.class.equals(type) || Float.class.equals(type)
                || Double.class.equals(type)) {
            if (comp == null) {
                if (script.isIdentifier(name)) {
                    comp = new NumericalTextField();
                    ((NumericalTextField) comp).setNumberType(type);
                    ((NumericalTextField) comp).setNegativeAccepted(false);
                    if (CollectionUtils.isNotEmpty(refObjects)) {
                        //support of image type
                        DataObject object = refObjects.get(0);
                        if (script.isSupportedType(object, name)) {
                            defValue = object.getId();
                        }
                    }
                } else {
                    comp = new NumericalTextField();
                    ((NumericalTextField) comp).setNumberType(type);
                    n = param.getMinValue();
                    if (n != null) {
                        if (Long.class.equals(type)) {
                            text += "Min: " + n.longValue() + " ";
                            ((NumericalTextField) comp).setMinimum(n.longValue());
                        } else if (Integer.class.equals(type)) {
                            text += "Min: " + n.intValue() + " ";
                            ((NumericalTextField) comp).setMinimum(n.intValue());
                        } else if (Double.class.equals(type)) {
                            text += "Min: " + n.doubleValue() + " ";
                            ((NumericalTextField) comp).setMinimum(n.doubleValue());
                        } else if (Float.class.equals(type)) {
                            text += "Min: " + n.floatValue() + " ";
                            ((NumericalTextField) comp).setMinimum(n.floatValue());
                        }
                    } else {
                        ((NumericalTextField) comp).setNegativeAccepted(true);
                    }
                    n = param.getMaxValue();
                    if (n != null) {
                        if (Long.class.equals(type)) {
                            text += "Max: " + n.longValue() + " ";
                            ((NumericalTextField) comp).setMaximum(n.longValue());
                        } else if (Integer.class.equals(type)) {
                            text += "Max: " + n.intValue() + " ";
                            ((NumericalTextField) comp).setMaximum(n.intValue());
                        } else if (Double.class.equals(type)) {
                            text += "Max: " + n.doubleValue() + " ";
                            ((NumericalTextField) comp).setMaximum(n.doubleValue());
                        } else if (Float.class.equals(type)) {
                            text += "Max: " + n.floatValue() + " ";
                            ((NumericalTextField) comp).setMaximum(n.floatValue());
                        }
                    }
                }
                if (defValue != null)
                    ((NumericalTextField) comp).setText("" + defValue);
            }
        } else if (String.class.equals(type)) {
            if (comp == null) {
                comp = new JTextField();
                if (defValue != null) {
                    length = defValue.toString().length();
                    String s = defValue.toString().trim();
                    ((JTextField) comp).setColumns(length);
                    ((JTextField) comp).setText(s);
                    columnsSet = s.length() > 0;
                }
            }
        } else if (Boolean.class.equals(type)) {
            if (comp == null) {
                comp = new JCheckBox();
                if (defValue != null)
                    ((JCheckBox) comp).setSelected((Boolean) defValue);
            }
        } else if (Map.class.equals(type)) {
            if (comp == null)
                comp = new ComplexParamPane(param.getKeyType(), param.getValueType());
            else
                comp = new ComplexParamPane(param.getKeyType(), (JComboBox) comp);
        } else if (List.class.equals(type)) {
            if (script.isIdentifier(name)) {
                identifier = new IdentifierParamPane(Long.class);
                identifier.setValues(refObjects);
                identifier.addDocumentListener(this);
                comp = identifier;
            } else {
                if (comp == null)
                    comp = new ComplexParamPane(param.getKeyType());
                else
                    comp = new ComplexParamPane((JComboBox) comp);
            }
        }
        if (comp != null) {
            if (comp instanceof JTextField) {
                if (!columnsSet)
                    ((JTextField) comp).setColumns(ScriptComponent.COLUMNS);
                ((JTextField) comp).getDocument().addDocumentListener(this);
            }
            if (comp instanceof ComplexParamPane)
                comp.addPropertyChangeListener(this);
            comp.setToolTipText(param.getDescription());
            c = new ScriptComponent(comp, name);
            if (text.trim().length() > 0)
                c.setUnit(text);
            if (!(comp instanceof JComboBox || comp instanceof JCheckBox))
                c.setRequired(!param.isOptional());
            if (details != null && details.trim().length() > 0)
                c.setInfo(details);
            if (comp instanceof JComboBox && script.isDataType(name)) {
                dataTypes = (JComboBox) comp;
                dataTypes.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        handleDataTypeChanges();
                    }
                });
            }
            grouping = param.getGrouping();
            parent = param.getParent();
            c.setParentIndex(parent);
            if (parent.length() > 0) {
                l = childrenMap.get(parent);
                if (l == null) {
                    l = new ArrayList<ScriptComponent>();
                    childrenMap.put(parent, l);
                }
                l.add(c);
            }

            if (grouping.length() > 0) {
                c.setGrouping(grouping);
                c.setNameLabel(grouping);
            } else {
                c.setNameLabel(name);
            }
            if (c.hasChildren() || parent.length() == 0) {
                results.add(c);
            }
            componentsAll.put(c.getParameterName(), c);
        }
    }
    ScriptComponent key;
    Iterator<ScriptComponent> k = results.iterator();
    while (k.hasNext()) {
        key = k.next();
        grouping = key.getGrouping();
        l = childrenMap.get(grouping);
        childrenMap.remove(grouping);
        if (l != null)
            key.setChildren(sorter.sort(l));
    }
    if (childrenMap != null && childrenMap.size() > 0) {
        Iterator<String> j = childrenMap.keySet().iterator();
        ScriptComponent sc;
        while (j.hasNext()) {
            parent = j.next();
            sc = new ScriptComponent();
            sc.setGrouping(parent);
            sc.setNameLabel(parent);
            sc.setChildren(sorter.sort(childrenMap.get(parent)));
            results.add(sc);
        }
    }
    List<ScriptComponent> sortedKeys = sorter.sort(results);
    k = sortedKeys.iterator();

    while (k.hasNext()) {
        key = k.next();
        components.put(key.getParameterName(), key);
    }
    setSelectedDataType();
    if (identifier != null)
        identifier.addPropertyChangeListener(this);
    canRunScript();
}