Example usage for java.io Serializable toString

List of usage examples for java.io Serializable toString

Introduction

In this page you can find the example usage for java.io Serializable toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.sakaiproject.genericdao.hibernate.HibernateGenericDao.java

public void update(Object object) {
    Class<?> type = findClass(object);
    checkClass(type);//from  ww  w .j a  va  2  s .c  om

    Serializable idValue = baseGetIdValue(object);
    if (idValue == null) {
        throw new IllegalArgumentException(
                "Could not get an id value from the supplied object, cannot update without an id: " + object);
    }

    String operation = "update";
    beforeWrite(operation, type, new Serializable[] { idValue }, new Object[] { object });

    baseUpdate(type, idValue, object);

    // clear the search caches
    getCacheProvider().clear(getSearchCacheName(type));
    // clear the cache entry since this was updated
    String key = idValue.toString();
    String cacheName = getCacheName(type);
    getCacheProvider().remove(cacheName, key);

    afterWrite(operation, type, new Serializable[] { idValue }, new Object[] { object }, 1);
}

From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java

/**
 * Validate member and add to the database as the new member if he/she is not registered yet
 * @return HttpResponse status if validation success
 *//*from ww w. jav a2s. c o m*/
@POST
@Path("/validation")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "memberLoginValidation", notes = "Simple function to validate a member login.")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Member is registered"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "User data error to be retrieved"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "User data error to be retrieved. Not JSON object") })
public HttpResponse memberLoginValidation() {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/applications/validation");

    JSONObject objResponse = new JSONObject();

    MemberModel member;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    // take username as default name
    String name = userAgent.getLoginName();
    System.out.println("User name : " + name);
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    // try to fetch firstname/lastname from user data received from OpenID
    Serializable userData = userAgent.getUserData();

    if (userData != null) {
        Object jsonUserData = JSONValue.parse(userData.toString());
        if (jsonUserData instanceof JSONObject) {
            JSONObject obj = (JSONObject) jsonUserData;
            Object firstnameObj = obj.get("given_name");
            Object lastnameObj = obj.get("family_name");
            Object emailObj = obj.get("email");
            String firstname, lastname, email;
            if (firstnameObj != null) {
                firstname = ((String) firstnameObj);
            } else {
                firstname = "";
            }

            if (lastnameObj != null) {
                lastname = ((String) lastnameObj);
            } else {
                lastname = "";
            }

            if (emailObj != null) {
                email = ((String) emailObj);
            } else {
                email = "";
            }

            member = new MemberModel(name, firstname, lastname, email);
            //logger.info(member.getId()+" "+member.getFullName()+" "+member.getEmail());
            try {
                conn = dbm.getConnection();
                if (!applicationAccess.isMemberRegistered(conn, member.getId())) {
                    applicationAccess.registerMember(conn, member);
                    objResponse.put("message", "Welcome " + member.getId() + "!");
                    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_7, "" + member.getId());

                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
                }
            } catch (SQLException e) {
                e.printStackTrace();
                objResponse.put("message", "Cannot validate member login. Database Error. " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
            // always close connections
            finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    logger.printStackTrace(e);
                }
            }
        } else {
            //logger.warning("Parsing user data failed! Got '" + jsonUserData.getClass().getName() + " instead of "+ JSONObject.class.getName() + " expected!");
            objResponse.put("message",
                    "Cannot validate member login. User data error to be retrieved. Not JSON object.");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        objResponse.put("message", "Member already registered");
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_8, "" + member.getId());

        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
    } else {
        objResponse.put("message", "Cannot validate member login. User data error to be retrieved.");
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    }

}

From source file:org.alfresco.repo.virtual.bundle.VirtualNodeServiceExtension.java

@Override
public ChildAssociationRef getPrimaryParent(NodeRef nodeRef) {
    if (Reference.isReference(nodeRef)) {
        Reference reference = Reference.fromNodeRef(nodeRef);
        Reference parent = reference.execute(new GetParentReferenceMethod());
        if (parent == null) {
            return getTrait().getPrimaryParent(reference.execute(new GetActualNodeRefMethod(environment)));
        } else {/*w  w  w. j  a  v  a  2  s . c  om*/
            Reference parentsParent = parent.execute(new GetParentReferenceMethod());

            NodeRef parentNodeRef = parent.toNodeRef();
            if (parentsParent == null) {
                parentNodeRef = parent.execute(new GetActualNodeRefMethod(environment));

            }

            NodeRef referenceNodeRef = reference.toNodeRef();
            Map<QName, Serializable> refProperties = smartStore.getProperties(reference);
            Serializable childName = refProperties.get(ContentModel.PROP_NAME);
            QName childAssocQName = QName.createQNameWithValidLocalName(
                    VirtualContentModel.VIRTUAL_CONTENT_MODEL_1_0_URI, childName.toString());
            ChildAssociationRef assoc = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, parentNodeRef,
                    childAssocQName, referenceNodeRef, true, -1);
            return assoc;
        }
    } else {
        return getTrait().getPrimaryParent(nodeRef);
    }
}

From source file:org.apache.jcs.engine.memory.lru.LRUMemoryCache.java

/**
 * Removes an item from the cache. This method handles hierarchical removal. If the key is a
 * String and ends with the CacheConstants.NAME_COMPONENT_DELIMITER, then all items with keys
 * starting with the argument String will be removed.
 * <p>//from  w  ww. j ava2s.  co m
 * @param key
 * @return true if the removal was successful
 * @exception IOException
 */
public synchronized boolean remove(Serializable key) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("removing item for key: " + key);
    }

    boolean removed = false;

    // handle partial removal
    if (key instanceof String && ((String) key).endsWith(CacheConstants.NAME_COMPONENT_DELIMITER)) {
        // remove all keys of the same name hierarchy.
        synchronized (map) {
            for (Iterator itr = map.entrySet().iterator(); itr.hasNext();) {
                Map.Entry entry = (Map.Entry) itr.next();
                Object k = entry.getKey();

                if (k instanceof String && ((String) k).startsWith(key.toString())) {
                    list.remove((MemoryElementDescriptor) entry.getValue());

                    itr.remove();

                    removed = true;
                }
            }
        }
    } else if (key instanceof GroupId) {
        // remove all keys of the same name hierarchy.
        synchronized (map) {
            for (Iterator itr = map.entrySet().iterator(); itr.hasNext();) {
                Map.Entry entry = (Map.Entry) itr.next();
                Object k = entry.getKey();

                if (k instanceof GroupAttrName && ((GroupAttrName) k).groupId.equals(key)) {
                    itr.remove();

                    list.remove((MemoryElementDescriptor) entry.getValue());

                    removed = true;
                }
            }
        }
    } else {
        // remove single item.
        MemoryElementDescriptor me = (MemoryElementDescriptor) map.remove(key);

        if (me != null) {
            list.remove(me);
            removed = true;
        }
    }

    return removed;
}

From source file:org.alfresco.repo.virtual.bundle.VirtualNodeServiceExtension.java

@Override
public List<ChildAssociationRef> getParentAssocs(NodeRef nodeRef, QNamePattern typeQNamePattern,
        QNamePattern qnamePattern) {/*from   w w  w.j  av a  2  s  .c  o m*/
    NodeServiceTrait theTrait = getTrait();
    if (Reference.isReference(nodeRef)) {
        Reference reference = Reference.fromNodeRef(nodeRef);
        Reference parent = reference.execute(new GetParentReferenceMethod());
        if (parent == null) {
            return theTrait.getParentAssocs(reference.execute(new GetActualNodeRefMethod(environment)),
                    typeQNamePattern, qnamePattern);
        } else {
            if (typeQNamePattern.isMatch(ContentModel.ASSOC_CONTAINS)) {
                Reference parentsParent = parent.execute(new GetParentReferenceMethod());

                NodeRef parentNodeRef = parent.toNodeRef();
                if (parentsParent == null) {
                    parentNodeRef = parent.execute(new GetActualNodeRefMethod(environment));

                }

                NodeRef referenceNodeRef = reference.toNodeRef();
                Map<QName, Serializable> properties = smartStore.getProperties(reference);
                Serializable name = properties.get(ContentModel.PROP_NAME);
                QName assocChildName = QName.createQNameWithValidLocalName(
                        VirtualContentModel.VIRTUAL_CONTENT_MODEL_1_0_URI, name.toString());
                if (qnamePattern.isMatch(assocChildName)) {
                    ChildAssociationRef assoc = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS,
                            parentNodeRef, assocChildName, referenceNodeRef);
                    return Arrays.asList(assoc);
                } else {
                    return Collections.emptyList();
                }
            } else {
                return Collections.emptyList();
            }
        }
    } else {
        return theTrait.getParentAssocs(nodeRef, typeQNamePattern, qnamePattern);
    }
}

From source file:gsn.storage.StorageManager.java

public void executeInsert(CharSequence tableName, DataField[] fields, StreamElement streamElement,
        Connection connection) throws SQLException {
    PreparedStatement ps = null;/*from  w ww .j  av a2  s .co m*/
    String query = getStatementInsert(tableName, fields).toString();
    try {
        ps = connection.prepareStatement(query);
        int counter = 1;
        for (DataField dataField : fields) {
            if (dataField.getName().equalsIgnoreCase("timed"))
                continue;
            Serializable value = streamElement.getData(dataField.getName());

            switch (dataField.getDataTypeID()) {
            case DataTypes.VARCHAR:
                if (value == null)
                    ps.setNull(counter, Types.VARCHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.CHAR:
                if (value == null)
                    ps.setNull(counter, Types.CHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.INTEGER:
                if (value == null)
                    ps.setNull(counter, Types.INTEGER);
                else
                    ps.setInt(counter, ((Number) value).intValue());
                break;
            case DataTypes.SMALLINT:
                if (value == null)
                    ps.setNull(counter, Types.SMALLINT);
                else
                    ps.setShort(counter, ((Number) value).shortValue());
                break;
            case DataTypes.TINYINT:
                if (value == null)
                    ps.setNull(counter, Types.TINYINT);
                else
                    ps.setByte(counter, ((Number) value).byteValue());
                break;
            case DataTypes.DOUBLE:
                if (value == null)
                    ps.setNull(counter, Types.DOUBLE);
                else
                    ps.setDouble(counter, ((Number) value).doubleValue());
                break;
            case DataTypes.FLOAT:
                if (value == null)
                    ps.setNull(counter, Types.FLOAT);
                else
                    ps.setFloat(counter, ((Number) value).floatValue());
                break;
            case DataTypes.BIGINT:
                if (value == null)
                    ps.setNull(counter, Types.BIGINT);
                else
                    ps.setLong(counter, ((Number) value).longValue());
                break;
            case DataTypes.BINARY:
                if (value == null)
                    ps.setNull(counter, Types.BINARY);
                else
                    ps.setBytes(counter, (byte[]) value);
                break;
            default:
                logger.error("The type conversion is not supported for : " + dataField.getName() + "("
                        + dataField.getDataTypeID() + ") : ");
            }
            counter++;
        }
        ps.setLong(counter, streamElement.getTimeStamp());
        ps.execute();
    } catch (GSNRuntimeException e) {
        //if (e.getType() == GSNRuntimeException.UNEXPECTED_VIRTUAL_SENSOR_REMOVAL) {
        //    if (logger.isDebugEnabled())
        //        logger.debug("An stream element dropped due to unexpected virtual sensor removal. (Stream element: " + streamElement.toString() + ")+ Query: " + query, e);
        //} else
        logger.warn("Inserting a stream element failed : " + streamElement.toString(), e);
    } catch (SQLException e) {
        if (e.getMessage().toLowerCase().contains("duplicate entry"))
            logger.info("Error occurred on inserting data to the database, an stream element dropped due to: "
                    + e.getMessage() + ". (Stream element: " + streamElement.toString() + ")+ Query: " + query);
        else
            logger.warn("Error occurred on inserting data to the database, an stream element dropped due to: "
                    + e.getMessage() + ". (Stream element: " + streamElement.toString() + ")+ Query: " + query);
        throw e;
    } finally {
        close(ps);
    }
}

From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java

/**
 *
 * {@inheritDoc}// w  w w  .  j av a 2 s .c  o  m
 */
@Override
public Map<QName, Serializable> prepareTaskProperties(WorkflowTask task,
        Map<QName, Serializable> propertiesCurrent) {
    Map<QName, Serializable> taskProperties = new HashMap<QName, Serializable>();
    Set<Entry<QName, Serializable>> entrySet = propertiesCurrent.entrySet();

    if (DEBUG_ENABLED) {
        LOGGER.debug("Metadata of '" + task.getId() + "' is :" + propertiesCurrent);
    }
    if (propertiesCurrent.get(WorkflowModel.ASSOC_POOLED_ACTORS) instanceof Collection) {
        Collection<?> pooledActors = (Collection<?>) propertiesCurrent
                .remove(WorkflowModel.ASSOC_POOLED_ACTORS);
        // process if actually there is data
        if (pooledActors.size() > 0) {
            LinkedHashSet<String> pooledUsers = new LinkedHashSet<String>();
            LinkedHashSet<String> pooledGroups = new LinkedHashSet<String>();
            for (Object object : pooledActors) {
                String actorId = getActor(object).getSecond();
                AuthorityType authorityType = AuthorityType.getAuthorityType(actorId);
                if (authorityType == AuthorityType.GROUP) {
                    pooledGroups.add(actorId);
                } else if (authorityType == AuthorityType.USER) {
                    pooledUsers.add(actorId);
                }
            }
            taskProperties.put(WorkflowReportConstants.PROP_POOLED_GROUPS, pooledGroups);
            taskProperties.put(WorkflowReportConstants.PROP_POOLED_ACTORS, pooledUsers);
        }
    }
    if (propertiesCurrent.get(WorkflowModel.ASSOC_ASSIGNEES) instanceof Collection) {
        Collection<?> pooledActors = (Collection<?>) propertiesCurrent.get(WorkflowModel.ASSOC_ASSIGNEES);

        taskProperties.put(WorkflowModel.ASSOC_ASSIGNEES, (Serializable) pooledActors);
    }
    if (propertiesCurrent.get(WorkflowModel.ASSOC_GROUP_ASSIGNEE) != null) {
        String pooledGroup = propertiesCurrent.get(WorkflowModel.ASSOC_GROUP_ASSIGNEE).toString();
        String actorId = getActor(pooledGroup).getSecond();
        taskProperties.put(WorkflowModel.ASSOC_GROUP_ASSIGNEE, actorId);
    }
    for (Entry<QName, Serializable> entry : entrySet) {
        QName qName = entry.getKey();
        if (SKIPPED_DATA.contains(qName)) {
            continue;
        }
        if (StringUtils.isEmpty(qName.getNamespaceURI())) {
            continue;
        }
        if (UPDATED_DATA.containsKey(qName)) {
            QName qNameToUpdate = UPDATED_DATA.get(qName);
            if (qNameToUpdate != null) {
                taskProperties.put(qNameToUpdate, entry.getValue());
            } // else skip
        } else {
            taskProperties.put(qName, entry.getValue());
        }
    }
    taskProperties.put(ContentModel.PROP_NAME, task.getId());
    taskProperties.put(ContentModel.PROP_TITLE, task.getName());

    Serializable taskId = taskProperties.remove(WorkflowModel.PROP_TASK_ID);
    if (taskId != null) {
        taskId = taskId.toString().replaceAll("\\D?", "");
    }
    taskProperties.put(WorkflowModel.PROP_TASK_ID, taskId);
    if (!taskProperties.containsKey(WorkflowModel.PROP_OUTCOME)) {
        taskProperties.put(WorkflowModel.PROP_OUTCOME, "Not Yet Started");
    }
    taskProperties.put(CMFModel.PROP_WF_TASK_STATE, task.getState().toString());
    QName packageId = UPDATED_DATA.get(WorkflowModel.TYPE_PACKAGE);
    Object nodeRef = taskProperties.get(packageId);
    if (nodeRef != null && !nodeRef.toString().trim().isEmpty()) {
        NodeRef nodeRefCreated = new NodeRef(nodeRef.toString());
        if (nodeService.exists(nodeRefCreated)) {
            Pair<String, String> workflowItems = getWorkflowItems(nodeRefCreated, CMFModel.PROP_TYPE);
            taskProperties.put(CMFModel.PROP_WF_CONTEXT_TYPE, workflowItems.getFirst());
            taskProperties.put(CMFModel.PROP_WF_CONTEXT_ID, workflowItems.getSecond());
        }
    }

    WorkflowPath workflowPath = task.getPath();
    if (workflowPath == null) {
        // skip wf data
        return taskProperties;
    }

    WorkflowInstance instance = workflowPath.getInstance();
    taskProperties.put(WorkflowModel.PROP_WORKFLOW_DEFINITION_ID,
            workflowPath.getInstance().getDefinition().getId());

    taskProperties.put(WorkflowModel.PROP_WORKFLOW_DEFINITION_NAME, instance.getDefinition().getName());
    taskProperties.put(WorkflowModel.PROP_WORKFLOW_INSTANCE_ID, instance.getId());

    String definitionId = task.getDefinition().getNode().getName();
    if (definitionId != null) {
        taskProperties.put(CMFModel.PROP_TYPE, definitionId);
    }
    // fix priority if not set
    if (!propertiesCurrent.containsKey(WorkflowModel.PROP_PRIORITY)) {
        taskProperties.put(WorkflowModel.PROP_PRIORITY, workflowPath.getInstance().getPriority());
    } else {
        taskProperties.put(WorkflowModel.PROP_PRIORITY, propertiesCurrent.get(WorkflowModel.PROP_PRIORITY));
    }
    return taskProperties;
}

From source file:org.cbioportal.security.spring.CancerStudyPermissionEvaluator.java

/**
 * Implementation of {@code PermissionEvaluator}.
 *
 * @param authentication//  w ww  .jav a  2s  .  c om
 * @param targetId Serialized String cancer study id, 
 *   String molecular profile id, 
 *   String sample list id, 
 *   List<String> of cancer study ids, 
 *   List<String> of molecular profile ids,
 *   or List<String> of sample list ids
 * @param targetType String 'CancerStudy', 
 *   'MolecularProfile', 
 *   'SampleList',
 *   'List<CancerStudyId>', 
 *   'List<MolecularProfileId>', 
 *   'MolecularDataMultipleStudyFilter',
 *   'MolecularProfileFilter',
 *   'MutationMultipleStudyFilter',
 *   or 'List<SampleListId>'
 * @param permission
 */
@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
        Object permission) {
    if (log.isDebugEnabled()) {
        log.debug("hasPermission(), checking permissions on targetId");
    }
    if (targetId == null) {
        if (log.isDebugEnabled()) {
            log.debug("hasPermission(), targetId is null, returning false");
        }
        return false;
    }

    if ("CancerStudy".equals(targetType)) {
        // everybody has access the 'all' cancer study
        // we have to check this right here (instead of checking later)
        // because the 'all' cancer study does not exist in the database
        if (targetId.toString().equalsIgnoreCase(ALL_CANCER_STUDIES_ID)) {
            return true;
        }
        CancerStudy cancerStudy = cancerStudies.get(targetId.toString());
        if (cancerStudy == null) {
            return false;
        }
        return hasPermission(authentication, cancerStudy, permission);
    } else if ("MolecularProfile".equals(targetType) || "GeneticProfile".equals(targetType)) {
        MolecularProfile molecularProfile = molecularProfiles.get(targetId.toString());
        if (molecularProfile == null) {
            return false;
        }
        return hasPermission(authentication, molecularProfile, permission);
    } else if ("SampleList".equals(targetType)) {
        SampleList sampleList = sampleLists.get(targetId.toString());
        if (sampleList == null) {
            return false;
        }
        return hasPermission(authentication, sampleList, permission);
    } else if ("List<SampleListId>".equals(targetType)) {
        return hasAccessToSampleLists(authentication, (List<String>) targetId, permission);
    } else if ("List<CancerStudyId>".equals(targetType)) {
        return hasAccessToCancerStudies(authentication, (List<String>) targetId, permission);
    } else if ("List<MolecularProfileId>".equals(targetType) || "List<GeneticProfileId>".equals(targetType)) {
        return hasAccessToMolecularProfiles(authentication, (List<String>) targetId, permission);
    } else if ("ClinicalAttributeCountFilter".equals(targetType)) {
        return hasAccessToCancerStudies(authentication, (ClinicalAttributeCountFilter) targetId, permission);
    } else if ("ClinicalDataMultiStudyFilter".equals(targetType)) {
        return hasAccessToCancerStudies(authentication, (ClinicalDataMultiStudyFilter) targetId, permission);
    } else if ("GenePanelMultipleStudyFilter".equals(targetType)) {
        GenePanelMultipleStudyFilter genePanelMultipleStudyFilter = (GenePanelMultipleStudyFilter) targetId;
        return hasAccessToCancerStudiesBySampleMolecularIdentifier(authentication,
                genePanelMultipleStudyFilter.getSampleMolecularIdentifiers(), permission);
    } else if ("MolecularDataMultipleStudyFilter".equals(targetType)) {
        MolecularDataMultipleStudyFilter molecularDataMultipleStudyFilter = (MolecularDataMultipleStudyFilter) targetId;
        if (molecularDataMultipleStudyFilter.getMolecularProfileIds() != null) {
            return hasAccessToMolecularProfiles(authentication,
                    molecularDataMultipleStudyFilter.getMolecularProfileIds(), permission);
        } else {
            return hasAccessToCancerStudiesBySampleMolecularIdentifier(authentication,
                    molecularDataMultipleStudyFilter.getSampleMolecularIdentifiers(), permission);
        }
    } else if ("MolecularProfileFilter".equals(targetType)) {
        MolecularProfileFilter molecularProfileFilter = (MolecularProfileFilter) targetId;
        if (molecularProfileFilter.getStudyIds() != null) {
            return hasAccessToCancerStudies(authentication, molecularProfileFilter.getStudyIds(), permission);
        } else {
            return hasAccessToMolecularProfiles(authentication, molecularProfileFilter.getMolecularProfileIds(),
                    permission);
        }
    } else if ("MutationMultipleStudyFilter".equals(targetType)) {
        MutationMultipleStudyFilter mutationMultipleStudyFilter = (MutationMultipleStudyFilter) targetId;
        if (mutationMultipleStudyFilter.getMolecularProfileIds() != null) {
            return hasAccessToMolecularProfiles(authentication,
                    mutationMultipleStudyFilter.getMolecularProfileIds(), permission);
        } else {
            return hasAccessToCancerStudiesBySampleMolecularIdentifier(authentication,
                    mutationMultipleStudyFilter.getSampleMolecularIdentifiers(), permission);
        }
    } else if ("PatientFilter".equals(targetType)) {
        return hasAccessToCancerStudies(authentication, (PatientFilter) targetId, permission);
    } else if ("SampleFilter".equals(targetType)) {
        return hasAccessToCancerStudies(authentication, (SampleFilter) targetId, permission);
    } else if ("ClinicalDataCountFilter".equals(targetType)) {
        return hasAccessToCancerStudiesByClinicalDataCountFilter(authentication,
                (ClinicalDataCountFilter) targetId, permission);
    } else if ("ClinicalDataBinCountFilter".equals(targetType)) {
        return hasAccessToCancerStudiesByClinicalDataBinCountFilter(authentication,
                (ClinicalDataBinCountFilter) targetId, permission);
    } else if ("StudyViewFilter".equals(targetType)) {
        return hasAccessToCancerStudiesByStudyViewFilter(authentication, (StudyViewFilter) targetId,
                permission);
    } else if ("List<SampleIdentifier>".equals(targetType)) {
        return hasAccessToCancerStudiesBySampleIdentifier(authentication, (List<SampleIdentifier>) targetId,
                permission);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("hasPermission(), unknown targetType '" + targetType + "'");
        }
    }
    return false;
}

From source file:tinygsn.storage.StorageManager.java

public void executeInsert(CharSequence tableName, DataField[] fields, StreamElement streamElement,
        Connection connection) throws SQLException {
    PreparedStatement ps = null;/* w  ww  . j av a 2s  .  c  o  m*/
    String query = getStatementInsert(tableName, fields).toString();
    try {
        ps = connection.prepareStatement(query);
        int counter = 1;
        for (DataField dataField : fields) {
            if (dataField.getName().equalsIgnoreCase("timed"))
                continue;
            Serializable value = streamElement.getData(dataField.getName());

            switch (dataField.getDataTypeID()) {
            case DataTypes.VARCHAR:
                if (value == null)
                    ps.setNull(counter, Types.VARCHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.CHAR:
                if (value == null)
                    ps.setNull(counter, Types.CHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.INTEGER:
                if (value == null)
                    ps.setNull(counter, Types.INTEGER);
                else
                    ps.setInt(counter, ((Number) value).intValue());
                break;
            case DataTypes.SMALLINT:
                if (value == null)
                    ps.setNull(counter, Types.SMALLINT);
                else
                    ps.setShort(counter, ((Number) value).shortValue());
                break;
            case DataTypes.TINYINT:
                if (value == null)
                    ps.setNull(counter, Types.TINYINT);
                else
                    ps.setByte(counter, ((Number) value).byteValue());
                break;
            case DataTypes.DOUBLE:
                if (value == null)
                    ps.setNull(counter, Types.DOUBLE);
                else
                    ps.setDouble(counter, ((Number) value).doubleValue());
                break;
            case DataTypes.BIGINT:
                if (value == null)
                    ps.setNull(counter, Types.BIGINT);
                else
                    ps.setLong(counter, ((Number) value).longValue());
                break;
            case DataTypes.BINARY:
                if (value == null)
                    ps.setNull(counter, Types.BINARY);
                else
                    ps.setBytes(counter, (byte[]) value);
                break;
            default:
                // logger.error("The type conversion is not supported for : "
                // + dataField.getName() + "(" + dataField.getDataTypeID() + ") : ");
            }
            counter++;
        }
        ps.setLong(counter, streamElement.getTimeStamp());
        ps.execute();
    } catch (GSNRuntimeException e) {
        // if (e.getType() ==
        // GSNRuntimeException.UNEXPECTED_VIRTUAL_SENSOR_REMOVAL) {
        // if (logger.isDebugEnabled())
        //
        // logger
        // .debug(
        // "An stream element dropped due to unexpected virtual sensor removal. (Stream element: "
        // + streamElement.toString() + ")+ Query: " + query, e);
        // } else
        // logger.warn(
        // "Inserting a stream element failed : " + streamElement.toString(), e);
    } catch (SQLException e) {
        if (e.getMessage().toLowerCase().contains("duplicate entry"))
            // logger
            // .info("Error occurred on inserting data to the database, an stream element dropped due to: "
            // + e.getMessage()
            // + ". (Stream element: "
            // + streamElement.toString() + ")+ Query: " + query);
            // else
            // logger
            // .warn("Error occurred on inserting data to the database, an stream element dropped due to: "
            // + e.getMessage()
            // + ". (Stream element: "
            // + streamElement.toString() + ")+ Query: " + query);
            throw e;
    } finally {
        close(ps);
    }
}

From source file:gov.pnnl.goss.gridappsd.app.AppManagerImpl.java

@Override
public void process(int processId, DataResponse event, Serializable message) throws Exception {

    // TODO:Get username from message's metadata e.g. event.getUserName()
    username = GridAppsDConstants.username;

    if (client == null) {
        Credentials credentials = new UsernamePasswordCredentials(GridAppsDConstants.username,
                GridAppsDConstants.password);
        client = clientFactory.create(PROTOCOL.STOMP, credentials);
    }/*from w w w  . j  a  v  a 2 s  .c o m*/
    Destination replyDestination = event.getReplyDestination();

    String destination = event.getDestination();
    if (destination.contains(GridAppsDConstants.topic_app_list)) {
        RequestAppList requestObj = RequestAppList.parse(message.toString());
        if (!requestObj.list_running_only) {
            List<AppInfo> appResponseList = listApps();
            // TODO publish on event.getReplyDestination();
            client.publish(replyDestination, new ResponseAppInfo(appResponseList));

        } else {
            List<AppInstance> appInstanceResponseList;
            if (requestObj.app_id != null) {
                appInstanceResponseList = listRunningApps(requestObj.app_id);
            } else {
                appInstanceResponseList = listRunningApps();
            }
            // TODO publish list on event.getReplyDestination();
            client.publish(replyDestination, new ResponseAppInstance(appInstanceResponseList));

        }

    } else if (destination.contains(GridAppsDConstants.topic_app_get)) {
        String appId = message.toString();
        AppInfo appInfo = getApp(appId);
        // TODO publish appinfo object on reply destination
        client.publish(replyDestination, appInfo);

    } else if (destination.contains(GridAppsDConstants.topic_app_register)) {
        RequestAppRegister requestObj = RequestAppRegister.parse(message.toString());
        registerApp(requestObj.app_info, requestObj.app_package);

    } else if (destination.contains(GridAppsDConstants.topic_app_deregister)) {
        String appId = message.toString();
        deRegisterApp(appId);

    } else if (destination.contains(GridAppsDConstants.topic_app_start)) {
        RequestAppStart requestObj = RequestAppStart.parse(message.toString());
        String instanceId = null;
        if (requestObj.getSimulation_id() == null) {
            instanceId = startApp(requestObj.getApp_id(), requestObj.getRuntime_options(),
                    new Integer(processId).toString());
        } else {
            instanceId = startAppForSimultion(requestObj.getApp_id(), requestObj.getRuntime_options(), null);
        }

        client.publish(replyDestination, instanceId);

    } else if (destination.contains(GridAppsDConstants.topic_app_stop)) {
        String appId = message.toString();
        stopApp(appId);
    } else if (destination.contains(GridAppsDConstants.topic_app_stop_instance)) {
        String appInstanceId = message.toString();
        stopAppInstance(appInstanceId);

    } else {
        // throw error, destination unrecognized
        client.publish(replyDestination,
                new DataError("App manager destination not recognized: " + event.getDestination()));

    }

}