List of usage examples for java.util Set toString
public String toString()
From source file:org.openmainframe.ade.impl.PropertyAnnotation.java
@SuppressWarnings({ "unchecked" }) static private void setProps(Object obj, Map<String, ? extends Object> props, Pattern filter, boolean safe) throws MissingPropertyException, IllegalArgumentException { final Class<?> annotatedClass = obj.getClass(); final Set<String> keyset = new TreeSet<String>(props.keySet()); for (Field field : annotatedClass.getDeclaredFields()) { final Property annos = field.getAnnotation(Property.class); if (annos != null) { // skip missing and non-required properties final String key = annos.key(); if (!props.containsKey(key)) { if (annos.required()) { throw new MissingPropertyException("Missing property: " + key); } else { // no value for non-required property continue; }//from w w w . j a v a 2s .co m } final Class<? extends IPropertyFactory<?>> factoryClass = annos.factory(); final Object rawVal = props.get(key); final Type fieldType = field.getGenericType(); Object val = null; if (factoryClass != Property.NULL_PROPERTY_FACTORY.class) { // check if this factory is eligible for creating this property final Type factoryProductType = resolveActualTypeArgs(factoryClass, IPropertyFactory.class)[0]; if (!TypeUtils.isAssignable(factoryProductType, fieldType)) { throw new IllegalArgumentException("The factory provided for the field: " + field.getName() + " is not compatible for creating object of type: " + fieldType); } Constructor<? extends IPropertyFactory<?>> constructor; try { constructor = factoryClass.getConstructor(); } catch (Exception e) { throw new IllegalArgumentException( "Missing empty constructor in: " + factoryClass.getName(), e); } IPropertyFactory<?> factory; try { factory = constructor.newInstance(); } catch (Exception e) { throw new IllegalArgumentException("Failed instantiating: " + factoryClass.getName(), e); } try { val = factory.create(rawVal); } catch (Exception e) { throw new IllegalArgumentException("Failed extractring property value: " + key, e); } } else if (TypeUtils.isAssignable(rawVal.getClass(), fieldType)) { val = rawVal; } else if (rawVal.getClass().equals(String.class)) { final Class<?> fieldClass = field.getType(); final String stringVal = (String) rawVal; if (fieldClass == Integer.class || fieldClass == int.class) { try { val = Integer.parseInt(stringVal); } catch (Exception e) { throw new IllegalArgumentException("Failed parsing integer value for property: " + key, e); } } else if (fieldClass == Double.class || fieldClass == double.class) { try { val = Double.parseDouble(stringVal); } catch (Exception e) { throw new IllegalArgumentException("Failed parsing double value for property: " + key, e); } } else if (fieldClass == Boolean.class || fieldClass == boolean.class) { try { val = Boolean.parseBoolean(stringVal); } catch (Exception e) { throw new IllegalArgumentException("Failed parsing boolean value for property: " + key, e); } } else if (fieldClass == String.class) { // should never have reached here, since String is assignable from String val = stringVal; } else if (fieldClass.isEnum()) { Class<Enum> fieldEnum; try { fieldEnum = (Class<Enum>) fieldClass; } catch (ClassCastException e) { throw new IllegalArgumentException( "Failed casting to Class<Enum> field class: " + fieldClass.getName(), e); } try { val = Enum.valueOf(fieldEnum, stringVal); } catch (Exception e) { throw new IllegalArgumentException("Failed parsing enum value for property: " + key + "\n\t possible values: " + Arrays.toString(fieldEnum.getEnumConstants()), e); } } else { // try to find String constructor for field, or else throw exception Constructor<?> constructor; try { constructor = fieldClass.getConstructor(String.class); } catch (Exception e) { throw new IllegalArgumentException("Field: " + field.getName() + " of type " + fieldClass + " is not one of the known property type (Integer, Double, Boolean, String, Enum), does not have a String constructor and no custom factory is defined in the annotation!", e); } try { val = constructor.newInstance(stringVal); } catch (Exception e) { throw new IllegalArgumentException("Could not create a new instance for " + field.getName() + " using the String constructor for type: " + fieldClass, e); } } } if (val == null) { throw new IllegalArgumentException("For the key " + key + ", we expect the value to be either assignable to " + fieldType + " or a String"); } try { field.setAccessible(true); field.set(obj, val); keyset.remove(key); } catch (SecurityException e) { throw new SecurityException("Field " + field.getName() + " is not accesible, and could not be set as accesible (probably due to PermissionManager)", e); } catch (Exception e) { throw new IllegalArgumentException( "Failed setting field: " + field.getName() + " with value: " + val, e); } } } if (safe && !keyset.isEmpty()) { throw new IllegalArgumentException("Unrecongnized arguments in the properties: " + keyset.toString()); } }
From source file:com.vmware.bdd.cli.commands.ClusterCommands.java
@CliCommand(value = "cluster create", help = "Create a new cluster") public void createCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = {/*from www . j a va2s. c o m*/ "appManager" }, mandatory = false, help = "The application manager name") final String appManager, @CliOption(key = { "type" }, mandatory = false, help = "The cluster type is Hadoop or HBase") final String type, @CliOption(key = { "distro" }, mandatory = false, help = "The distro name") final String distro, @CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath, @CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames, @CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames, @CliOption(key = { "networkName" }, mandatory = false, help = "Network Name used for management") final String networkName, @CliOption(key = { "hdfsNetworkName" }, mandatory = false, help = "Network Name for HDFS traffic.") final String hdfsNetworkName, @CliOption(key = { "mapredNetworkName" }, mandatory = false, help = "Network Name for MapReduce traffic") final String mapredNetworkName, @CliOption(key = { "topology" }, mandatory = false, help = "You must specify the topology type: HVE or RACK_AS_RACK or HOST_AS_RACK") final String topology, @CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes, @CliOption(key = { "password" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Answer 'yes' to set password for all VMs in this cluster.") final boolean setClusterPassword, @CliOption(key = { "localRepoURL" }, mandatory = false, help = "Local yum server URL for application managers, ClouderaManager/Ambari.") final String localRepoURL, @CliOption(key = { "adminGroupName" }, mandatory = false, help = "AD/LDAP Admin Group Name.") final String adminGroupName, @CliOption(key = { "userGroupName" }, mandatory = false, help = "AD/LDAP User Group Name.") final String userGroupName, @CliOption(key = { "disableLocalUsers" }, mandatory = false, help = "Disable local users") final Boolean disableLocalUsersFlag, @CliOption(key = { "skipVcRefresh" }, mandatory = false, help = "flag to skip refreshing VC resources") final Boolean skipVcRefresh, @CliOption(key = { "template" }, mandatory = false, help = "The node template name") final String templateName) { // validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } else if (name.indexOf(" ") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_BLANK_SPACE); return; } // process resume if (resume && setClusterPassword) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.RESUME_DONOT_NEED_SET_PASSWORD); return; } else if (resume) { resumeCreateCluster(name, skipVcRefresh); return; } // build ClusterCreate object ClusterCreate clusterCreate = new ClusterCreate(); clusterCreate.setName(name); if (!CommandsUtils.isBlank(appManager) && !Constants.IRONFAN.equalsIgnoreCase(appManager)) { AppManagerRead appManagerRead = appManagerRestClient.get(appManager); if (appManagerRead == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, appManager + " cannot be found in the list of application managers."); return; } } if (CommandsUtils.isBlank(appManager)) { clusterCreate.setAppManager(Constants.IRONFAN); } else { clusterCreate.setAppManager(appManager); // local yum repo url for 3rd party app managers like ClouderaMgr, Ambari etc. if (!CommandsUtils.isBlank(localRepoURL)) { clusterCreate.setLocalRepoURL(localRepoURL); } } if (setClusterPassword) { String password = getPassword(); //user would like to set password, but failed to enter //a valid one, quit cluster create if (password == null) { return; } else { clusterCreate.setPassword(password); } } if (type != null) { ClusterType clusterType = ClusterType.getByDescription(type); if (clusterType == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "type=" + type); return; } clusterCreate.setType(clusterType); } else if (specFilePath == null) { // create Hadoop (HDFS + MapReduce) cluster as default clusterCreate.setType(ClusterType.HDFS_MAPRED); } TopologyType policy = null; if (topology != null) { policy = validateTopologyValue(name, topology); if (policy == null) { return; } } else { policy = TopologyType.NONE; } clusterCreate.setTopologyPolicy(policy); DistroRead distroRead4Create; try { if (distro != null) { DistroRead[] distroReads = appManagerRestClient.getDistros(clusterCreate.getAppManager()); distroRead4Create = getDistroByName(distroReads, distro); if (distroRead4Create == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO + Constants.PARAM_NOT_SUPPORTED + getDistroNames(distroReads)); return; } } else { distroRead4Create = appManagerRestClient.getDefaultDistro(clusterCreate.getAppManager()); if (distroRead4Create == null || CommandsUtils.isBlank(distroRead4Create.getName())) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NO_DEFAULT_DISTRO); return; } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } Map<String, Map<String, String>> infraConfigs = new HashMap<String, Map<String, String>>(); if (StringUtils.isBlank(adminGroupName) && StringUtils.isBlank(userGroupName)) { //both adminGroupName and userGroupName are null, supposes no need to enable ldap. } else if (!StringUtils.isBlank(adminGroupName) && !StringUtils.isBlank(userGroupName)) { if (MapUtils.isEmpty(infraConfigs.get(UserMgmtConstants.LDAP_USER_MANAGEMENT))) { initInfraConfigs(infraConfigs, disableLocalUsersFlag); } Map<String, String> userMgmtConfig = infraConfigs.get(UserMgmtConstants.LDAP_USER_MANAGEMENT); userMgmtConfig.put(UserMgmtConstants.ADMIN_GROUP_NAME, adminGroupName); userMgmtConfig.put(UserMgmtConstants.USER_GROUP_NAME, userGroupName); clusterCreate.setInfrastructure_config(infraConfigs); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, "You need to supply both AdminGroupName and UserGroupName."); return; } clusterCreate.setDistro(distroRead4Create.getName()); clusterCreate.setDistroVendor(distroRead4Create.getVendor()); clusterCreate.setDistroVersion(distroRead4Create.getVersion()); clusterCreate.setTemplateName(templateName); if (rpNames != null) { List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames); if (rpNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setRpNames(rpNamesList); } } if (dsNames != null) { List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames); if (dsNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setDsNames(dsNamesList); } } List<String> failedMsgList = new ArrayList<String>(); List<String> warningMsgList = new ArrayList<String>(); Set<String> allNetworkNames = new HashSet<String>(); try { if (specFilePath != null) { ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterCreate.setSpecFile(true); clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS()); clusterCreate.setExternalMapReduce(clusterSpec.getExternalMapReduce()); clusterCreate.setExternalNamenode(clusterSpec.getExternalNamenode()); clusterCreate.setExternalSecondaryNamenode(clusterSpec.getExternalSecondaryNamenode()); clusterCreate.setExternalDatanodes(clusterSpec.getExternalDatanodes()); clusterCreate.setNodeGroups(clusterSpec.getNodeGroups()); clusterCreate.setConfiguration(clusterSpec.getConfiguration()); // TODO: W'd better merge validateConfiguration with validateClusterSpec to avoid repeated validation. if (CommandsUtils.isBlank(appManager) || Constants.IRONFAN.equalsIgnoreCase(appManager)) { validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList, failedMsgList); } clusterCreate.validateNodeGroupNames(); if (!validateHAInfo(clusterCreate.getNodeGroups())) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath); return; } Map<String, Map<String, String>> specInfraConfigs = clusterSpec.getInfrastructure_config(); if (!MapUtils.isEmpty(specInfraConfigs)) //spec infra config is not empty { if (MapUtils.isNotEmpty(infraConfigs)) { System.out.println( "adminGroup and userGroup has been specified as commandline parameters, so the values inside spec file will be ignored."); } else { clusterCreate.setInfrastructure_config(specInfraConfigs); } } Map<String, Object> configuration = clusterSpec.getConfiguration(); if (MapUtils.isNotEmpty(configuration)) { Map<String, Map<String, String>> serviceUserConfig = (Map<String, Map<String, String>>) configuration .get(UserMgmtConstants.SERVICE_USER_CONFIG_IN_SPEC_FILE); if (MapUtils.isNotEmpty(serviceUserConfig)) { //user didn't specify ldap in command line and specfile, but specfiy ldap user in service user if (hasLdapServiceUser(serviceUserConfig) && (clusterCreate.getInfrastructure_config() == null)) { Map<String, Map<String, String>> infraConfig = new HashMap<>(); initInfraConfigs(infraConfig, disableLocalUsersFlag); clusterCreate.setInfrastructure_config(infraConfig); } validateServiceUserConfigs(appManager, clusterSpec, failedMsgList); } } } allNetworkNames = getAllNetworkNames(); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } if (allNetworkNames.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CANNOT_FIND_NETWORK); return; } LinkedHashMap<NetTrafficType, List<String>> networkConfig = new LinkedHashMap<NetTrafficType, List<String>>(); if (networkName == null) { if (allNetworkNames.size() == 1) { networkConfig.put(NetTrafficType.MGT_NETWORK, new ArrayList<String>()); networkConfig.get(NetTrafficType.MGT_NETWORK).addAll(allNetworkNames); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SPECIFIED); return; } } else { if (!allNetworkNames.contains(networkName) || (hdfsNetworkName != null && !allNetworkNames.contains(hdfsNetworkName)) || (mapredNetworkName != null && !allNetworkNames.contains(mapredNetworkName))) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SUPPORTED + allNetworkNames.toString()); return; } networkConfig.put(NetTrafficType.MGT_NETWORK, new ArrayList<String>()); networkConfig.get(NetTrafficType.MGT_NETWORK).add(networkName); if (hdfsNetworkName != null) { networkConfig.put(NetTrafficType.HDFS_NETWORK, new ArrayList<String>()); networkConfig.get(NetTrafficType.HDFS_NETWORK).add(hdfsNetworkName); } if (mapredNetworkName != null) { networkConfig.put(NetTrafficType.MAPRED_NETWORK, new ArrayList<String>()); networkConfig.get(NetTrafficType.MAPRED_NETWORK).add(mapredNetworkName); } } notifyNetsUsage(networkConfig, warningMsgList); clusterCreate.setNetworkConfig(networkConfig); clusterCreate.validateCDHVersion(warningMsgList); // Validate that the specified file is correct json format and proper value. //TODO(qjin): 1, in validateClusterCreate, implement roles check and validation // 2, consider use service to validate configuration for different appManager if (specFilePath != null) { validateClusterSpec(clusterCreate, failedMsgList, warningMsgList); } // give a warning message if both type and specFilePath are specified if (type != null && specFilePath != null) { warningMsgList.add(Constants.TYPE_SPECFILE_CONFLICT); } if (!failedMsgList.isEmpty()) { showFailedMsg(clusterCreate.getName(), Constants.OUTPUT_OP_CREATE, failedMsgList); return; } // rest invocation try { if (!CommandsUtils.showWarningMsg(clusterCreate.getName(), Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, warningMsgList, alwaysAnswerYes, null)) { return; } restClient.create(clusterCreate, BooleanUtils.toBoolean(skipVcRefresh)); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_RESULT_CREAT); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, CommandsUtils.getExceptionMessage(e)); return; } // check the instant clone type and the HA configuration for node groups // currently there are limitations on HA support with instant clone, so we will // display a warning message for instant clone with HA function ClusterRead cluster = restClient.get(name, false); if (cluster != null) { String cloneType = cluster.getClusterCloneType(); String INSTANT_CLONE = com.vmware.bdd.utils.Constants.CLUSTER_CLONE_TYPE_INSTANT_CLONE; if (null != cloneType && cloneType.equals(INSTANT_CLONE)) { String warningMsg = validateInstantCloneWithHA(specFilePath, clusterCreate); if (!CommonUtil.isBlank(warningMsg)) { System.out.println(warningMsg); } } } }
From source file:com.sourcesense.opencmis.server.HstCmisRepository.java
/** * Gathers all base properties of a file or folder. *///from w w w. ja v a 2s . co m private Properties compileProperties(HippoBean bean, Set<String> orgfilter, ObjectInfoImpl objectInfo) { if (bean == null) { throw new IllegalArgumentException("File must not be null!"); } // we can gather properties if the file or folder doesn't exist if (!bean.isHippoDocumentBean()) { throw new CmisObjectNotFoundException(String.format("Object %1 is not a document", bean)); } // copy filter Set<String> filter = (orgfilter == null ? null : new HashSet<String>(orgfilter)); // find base type String typeId = null; if (bean.isHippoFolderBean()) { typeId = TypeManager.FOLDER_TYPE_ID; objectInfo.setBaseType(BaseTypeId.CMIS_FOLDER); objectInfo.setTypeId(typeId); objectInfo.setContentType(null); objectInfo.setFileName(null); objectInfo.setHasAcl(true); objectInfo.setHasContent(false); objectInfo.setVersionSeriesId(null); objectInfo.setIsCurrentVersion(true); objectInfo.setRelationshipSourceIds(null); objectInfo.setRelationshipTargetIds(null); objectInfo.setRenditionInfos(null); objectInfo.setSupportsDescendants(true); objectInfo.setSupportsFolderTree(true); objectInfo.setSupportsPolicies(false); objectInfo.setSupportsRelationships(false); objectInfo.setWorkingCopyId(null); objectInfo.setWorkingCopyOriginalId(null); } else { typeId = TypeManager.DOCUMENT_TYPE_ID; objectInfo.setBaseType(BaseTypeId.CMIS_DOCUMENT); objectInfo.setTypeId(typeId); objectInfo.setHasAcl(true); objectInfo.setHasContent(true); objectInfo.setHasParent(true); objectInfo.setVersionSeriesId(null); objectInfo.setIsCurrentVersion(true); objectInfo.setRelationshipSourceIds(null); objectInfo.setRelationshipTargetIds(null); objectInfo.setRenditionInfos(null); objectInfo.setSupportsDescendants(false); objectInfo.setSupportsFolderTree(false); objectInfo.setSupportsPolicies(false); objectInfo.setSupportsRelationships(false); objectInfo.setWorkingCopyId(null); objectInfo.setWorkingCopyOriginalId(null); } // let's do it try { PropertiesImpl result = new PropertiesImpl(); // id String id = getId(bean); addPropertyId(result, typeId, filter, PropertyIds.OBJECT_ID, id); objectInfo.setId(id); // name String name = bean.getName(); addPropertyString(result, typeId, filter, PropertyIds.NAME, name); objectInfo.setName(name); Map<String, Object> beanProperties = bean.getProperties(); // created and modified by addPropertyString(result, typeId, filter, PropertyIds.CREATED_BY, USER_UNKNOWN); addPropertyString(result, typeId, filter, PropertyIds.LAST_MODIFIED_BY, USER_UNKNOWN); objectInfo.setCreatedBy(USER_UNKNOWN); // creation date GregorianCalendar creationDate = (GregorianCalendar) beanProperties.get(HIPPO_CREATION_DATE); addPropertyDateTime(result, typeId, filter, PropertyIds.CREATION_DATE, creationDate); objectInfo.setCreationDate(creationDate); // modification date GregorianCalendar lastModificationDate = (GregorianCalendar) beanProperties .get(HIPPO_MODIFICATION_DATE); addPropertyDateTime(result, typeId, filter, PropertyIds.LAST_MODIFICATION_DATE, lastModificationDate); objectInfo.setLastModificationDate(lastModificationDate); // directory or file if (bean.isHippoFolderBean()) { // base type and type name addPropertyId(result, typeId, filter, PropertyIds.BASE_TYPE_ID, BaseTypeId.CMIS_FOLDER.value()); addPropertyId(result, typeId, filter, PropertyIds.OBJECT_TYPE_ID, TypeManager.FOLDER_TYPE_ID); String path = bean.getPath(); addPropertyString(result, typeId, filter, PropertyIds.PATH, (path.length() == 0 ? "/" : path)); // folder properties if (!isRootBean(bean)) { addPropertyId(result, typeId, filter, PropertyIds.PARENT_ID, (isRootBean(bean.getParentBean()) ? ROOT_ID : bean.getParentBean().getCanonicalUUID())); objectInfo.setHasParent(true); } else { objectInfo.setHasParent(false); } } else { // base type and type name addPropertyId(result, typeId, filter, PropertyIds.BASE_TYPE_ID, BaseTypeId.CMIS_DOCUMENT.value()); addPropertyId(result, typeId, filter, PropertyIds.OBJECT_TYPE_ID, TypeManager.DOCUMENT_TYPE_ID); // file properties addPropertyBoolean(result, typeId, filter, PropertyIds.IS_IMMUTABLE, false); addPropertyBoolean(result, typeId, filter, PropertyIds.IS_LATEST_VERSION, true); addPropertyBoolean(result, typeId, filter, PropertyIds.IS_MAJOR_VERSION, true); addPropertyBoolean(result, typeId, filter, PropertyIds.IS_LATEST_MAJOR_VERSION, true); addPropertyString(result, typeId, filter, PropertyIds.VERSION_LABEL, bean.getName()); addPropertyId(result, typeId, filter, PropertyIds.VERSION_SERIES_ID, bean.getCanonicalUUID()); addPropertyString(result, typeId, filter, PropertyIds.CHECKIN_COMMENT, ""); addPropertyInteger(result, typeId, filter, PropertyIds.CONTENT_STREAM_LENGTH, 300); addPropertyString(result, typeId, filter, PropertyIds.CONTENT_STREAM_MIME_TYPE, "text/xml"); addPropertyString(result, typeId, filter, PropertyIds.CONTENT_STREAM_FILE_NAME, bean.getName()); objectInfo.setContentType("text/xml"); objectInfo.setFileName(bean.getName()); } // read custom properties readCustomProperties(bean, result, filter, objectInfo); if (filter != null) { if (!filter.isEmpty()) { debug("Unknown filter properties: " + filter.toString(), null); } } return result; } catch (Exception e) { if (e instanceof CmisBaseException) { throw (CmisBaseException) e; } throw new CmisRuntimeException(e.getMessage()); } }
From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java
/** * Gets the batch instance list on the basis of passed status, roles of the logged in user and flag whether the user is super admin * or not.// ww w. j av a 2 s .c o m * * @param statusParam the batch instance status * @param loggedInUserRole the logged in user role * @param isSuperAdmin the flag if the user is super admin * @return the batch instance list * @throws ValidationException * @throws ValidationException the validation exception */ public BatchInstances getBatchInstanceList(final String statusParam, final Set<String> loggedInUserRole, final boolean isSuperAdmin) throws ValidationException { final BatchInstances batchInstances = new BatchInstances(); boolean isStatusValid = false; String status = null; final List<String> statusList = BatchInstanceStatus.valuesAsStringList(); for (final String statusItem : statusList) { if (statusItem.equalsIgnoreCase(statusParam)) { status = statusItem; isStatusValid = true; break; } } if (!isStatusValid) { throw new ValidationException(WebServiceConstants.INVALID_BATCH_INSTANCE_STATUS_MESSAGE, new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INVALID_BATCH_INSTANCE_STATUS_CODE, WebServiceConstants.INVALID_BATCH_INSTANCE_STATUS_MESSAGE, WebServiceConstants.INVALID_BATCH_INSTANCE_STATUS_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL)); } else { final Set<String> batchInstancesId = new TreeSet<String>(); final BatchInstanceStatus batchInstanceStatus = BatchInstanceStatus.valueOf(status); LOGGER.info("Batch instance status is " + status); LOGGER.info("Fetching batch instance list from the database"); final List<BatchInstance> batchInstance = batchInstanceService .getBatchInstByStatus(batchInstanceStatus); if (CollectionUtils.isNotEmpty(batchInstance)) { if (!isSuperAdmin) { // fetch the batch instances from batch instance groups final Set<String> batchInstancesIdentifiers = batchInstanceGroupsService .getBatchInstanceIdentifierForUserRoles(loggedInUserRole); if (CollectionUtils.isNotEmpty(batchInstancesIdentifiers)) { batchInstancesId.addAll(batchInstancesIdentifiers); } // fetch the list of batch instances from the batch instance // table for batch classes having the given role. final List<BatchClass> batchClasses = batchClassService .getAllBatchClassesByUserRoles(loggedInUserRole); List<BatchInstance> eachBatchInstance; for (final BatchClass batchClass : batchClasses) { // TODO : service hit should not be inside a loop. // Modify the API to return list of Identifiers // only, rather than complete objects. eachBatchInstance = batchInstanceService.getBatchInstByBatchClass(batchClass); for (final BatchInstance bi : eachBatchInstance) { batchInstancesId.add(bi.getIdentifier()); } } } else { for (final BatchInstance bi : batchInstance) { batchInstancesId.add(bi.getIdentifier()); } } LOGGER.info("Fetched list of batch instances from the batch instance table" + " for batch classes having the given role:"); LOGGER.info(batchInstancesId.toString()); final List<com.ephesoft.dcma.batch.schema.BatchInstances.BatchInstance> batchInstanceList = batchInstances .getBatchInstance(); com.ephesoft.dcma.batch.schema.BatchInstances.BatchInstance batchLocal; for (final BatchInstance eachBatchInstance : batchInstance) { if (batchInstancesId.contains(eachBatchInstance.getIdentifier())) { batchLocal = new com.ephesoft.dcma.batch.schema.BatchInstances.BatchInstance(); batchLocal.setIdentifier(eachBatchInstance.getIdentifier()); batchLocal.setBatchName(eachBatchInstance.getBatchName()); batchLocal.setCurrentUser(eachBatchInstance.getCurrentUser()); batchLocal.setExecutedModules(eachBatchInstance.getExecutedModules()); batchLocal.setLocalFolder(eachBatchInstance.getLocalFolder()); batchLocal.setRemoteBatchInstanceId(eachBatchInstance.getRemoteBatchInstance() != null ? eachBatchInstance.getRemoteBatchInstance().getRemoteBatchInstanceIdentifier() : null); batchLocal.setReviewOperatorName(eachBatchInstance.getReviewUserName()); batchLocal.setServerIP(eachBatchInstance.getServerIP()); batchLocal.setUncSubFolder(eachBatchInstance.getUncSubfolder()); batchLocal.setValidateOperatorName(eachBatchInstance.getValidationUserName()); batchInstanceList.add(batchLocal); } } } } return batchInstances; }
From source file:com.heliosdecompiler.helios.tasks.DecompileTask.java
private String recursivelyHandleNameExpr(MethodCallExpr methodCallExpr, NameExpr nameExpr, int depth) { //fixme generics if (methodCallExpr.getNameExpr() != nameExpr) return null; print(depth, "RHNE " + methodCallExpr + " " + nameExpr); print(depth,/*from ww w . j a va2 s.c om*/ "Scope is " + ((methodCallExpr.getScope() == null) ? null : methodCallExpr.getScope().getClass()) + " " + methodCallExpr.getScope()); Pair<Integer, Integer> offsets = getOffsets(lineSizes, nameExpr); ClickableSyntaxTextArea.Link link = new ClickableSyntaxTextArea.Link(nameExpr.getBeginLine(), nameExpr.getBeginColumn(), offsets.getValue0(), offsets.getValue1()); Set<String> possibleClassNames = new HashSet<>(); if (methodCallExpr.getScope() instanceof NameExpr || methodCallExpr.getScope() instanceof ArrayAccessExpr) { Node tmp = methodCallExpr.getScope(); if (tmp instanceof ArrayAccessExpr) { ArrayAccessExpr expr = (ArrayAccessExpr) tmp; tmp = expr.getName(); //todo could be other than nameexpr } /* * Cases: * Static method * SomeClass.someStaticMethod() * Variable * myVar.someVirtualMethod() * Field * field.someVirtualMethod() */ Node fnode = tmp; NameExpr scopeExpr = (NameExpr) tmp; String scope = scopeExpr.toString(); if (scope.contains(".")) { throw new IllegalArgumentException("Was not expecting '.' in " + scope); } /* * In Java, variables have priority * Therefore, something like this * * Object Integer = null; * Integer.parseInt("4"); * * would fail */ Node node = methodCallExpr.getParentNode(); List<com.github.javaparser.ast.type.Type> ref = new ArrayList<>(); List<Node> parentChain = new ArrayList<>(); Node tmpNode = node; while (tmpNode != null) { parentChain.add(tmpNode); tmpNode = tmpNode.getParentNode(); } while (ref.size() == 0 && node != null) { print(depth, "Trying to find localvar in " + node.getClass()); node.accept(new VoidVisitorAdapter<Node>() { @Override public void visit(VariableDeclarationExpr n, Node arg) { boolean equals = false; for (VariableDeclarator var : n.getVars()) { if (var.getId().getName().equals(scopeExpr.getName())) { equals = true; } } if (equals) { print(depth, "Found VariableDeclarationExpr " + n); print(depth, "This is it! Type is " + n.getType()); ref.add(n.getType()); } super.visit(n, n); } @Override public void visit(MultiTypeParameter n, Node arg) { if (n.getId().getName().equals(((NameExpr) fnode).getName())) { print(depth, "Found VariableDeclarationExpr " + n); print(depth, "This is it! Type is " + n.getType()); ref.addAll(n.getType().getElements()); } } @Override public void visit(Parameter n, Node arg) { if (n.getId().getName().equals(((NameExpr) fnode).getName())) { print(depth, "Found Parameter " + n); print(depth, "This is it! Type is " + n.getType()); ref.add(n.getType()); } } @Override public void visit(BlockStmt n, Node arg) { if (parentChain.contains(n)) { super.visit(n, n); } } }, null); if (node instanceof BodyDeclaration) { // We don't want to check for variables outside of this method. That would be a field break; } node = node.getParentNode(); } if (ref.size() > 0) { if (ref.size() > 1) { throw new IllegalArgumentException("Was not expecting more than one localvar " + ref); } com.github.javaparser.ast.type.Type type = ref.get(0); //fixme check all while (type instanceof ReferenceType) { type = ((ReferenceType) type).getType(); } print(depth, "Final type is " + type.getClass() + " " + type); if (type instanceof ClassOrInterfaceType) { ClassOrInterfaceType coit = (ClassOrInterfaceType) type; possibleClassNames.addAll(generatePossibilities(coit)); possibleClassNames.add("java/lang/" + coit.getName() + ".class"); if (packageName != null) { possibleClassNames.add(packageName + "/" + coit.getName() + ".class"); } } else { throw new IllegalArgumentException("Got unexpected type " + type.getClass()); } } /* * Check for static method invocation * If this class was called "Test" we want to check for * * Test.staticMethod(); */ print(depth, "Simple name is " + simpleName); if (scopeExpr.getName().equals(simpleName)) { possibleClassNames.add(this.className); } /* * Finally, check imports */ for (ImportDeclaration importDeclaration : compilationUnit.getImports()) { if (importDeclaration.isAsterisk()) { String fullImport = importDeclaration.getName().toString(); String internalName = fullImport.replace('.', '/'); possibleClassNames.add(internalName + "/" + scope + ".class"); } else if (importDeclaration.isStatic()) { } else { NameExpr importName = importDeclaration.getName(); if (importName.getName().equals(scope)) { String javaName = importDeclaration.getName().toString(); String internalName = javaName.replace('.', '/'); possibleClassNames.add(internalName + ".class"); } } } /* * java.lang.* classes don't need to be imported * Add it just in case */ possibleClassNames.add("java/lang/" + scope + ".class"); FieldAccessExpr expr = new FieldAccessExpr(null, scope); Set<String> owners = handleFieldExpr(expr, className, depth); possibleClassNames.addAll(owners); /* * Classes in the current package don't need to be imported * Add it just in case */ if (packageName != null) { possibleClassNames.add(packageName + "/" + scope + ".class"); } } else if (methodCallExpr.getScope() instanceof MethodCallExpr) { /* * Recursively handle the chained method. The return should be the class name we want */ possibleClassNames.add(recursivelyHandleNameExpr((MethodCallExpr) methodCallExpr.getScope(), ((MethodCallExpr) methodCallExpr.getScope()).getNameExpr(), depth + 1)); } else if (methodCallExpr.getScope() == null) { /* * Another way of calling a static/virtual method within the same class. * * someStaticMethod(); */ possibleClassNames.add(this.className); } else if (methodCallExpr.getScope() instanceof ThisExpr) { /* * Another way of calling a static/virtual method within the same class * * this.someVirtualMethod(); * * fixme what about Outer.this.method(); */ possibleClassNames.add(this.className); } else if (methodCallExpr.getScope() instanceof SuperExpr) { /* * Calling a super method * * super.someVirtualMethod(); */ LoadedFile loadedFile = Helios.getLoadedFile(fileName); ClassNode node = loadedFile.getClassNode(this.className); possibleClassNames.add(node.superName); } else if (methodCallExpr.getScope() instanceof EnclosedExpr) { /* * fixme We could be missing CastExprs elsewhere but it's unlikely * * EnclosedExpr represents an expression surrounded by brackets * It's assumed that there may be a cast within * * ((String) obj).toCharArray(); */ EnclosedExpr enclosedExpr = (EnclosedExpr) methodCallExpr.getScope(); if (enclosedExpr.getInner() instanceof CastExpr) { CastExpr castExpr = (CastExpr) enclosedExpr.getInner(); com.github.javaparser.ast.type.Type type = castExpr.getType(); while (type instanceof ReferenceType) { type = ((ReferenceType) type).getType(); } if (type instanceof ClassOrInterfaceType) { ClassOrInterfaceType coit = (ClassOrInterfaceType) type; possibleClassNames.addAll(handleClassOrInterfaceType(coit)); } else { throw new IllegalArgumentException("Got unexpected type " + type.getClass()); } } } else if (methodCallExpr.getScope() instanceof FieldAccessExpr) { // Handle fields /* * Could either be a field OR a FQN * * System.out.println(); -> System.out is the FieldAccessExpr * * java.lang.System.out.println(); -> java.lang.System.out is the FieldAccessExpr */ FieldAccessExpr expr = (FieldAccessExpr) methodCallExpr.getScope(); String left = expr.getScope().toString(); Set<String> possible; if (left.equals("this")) { possible = new HashSet<>(); possible.add(className); } else { ClassOrInterfaceType type = new ClassOrInterfaceType(left); type.setBeginLine(expr.getScope().getBeginLine()); type.setEndLine(expr.getScope().getEndLine()); type.setBeginColumn(expr.getScope().getBeginColumn()); type.setEndColumn(expr.getScope().getEndColumn()); possible = handleClassOrInterfaceType(type); } if (possible.size() > 0) { // Maybe field print(depth, "FieldAccessExpr field: " + expr.getScope() + " " + expr.getField() + " " + expr.getScope().getClass() + " " + possible); for (String p : possible) { Set<String> types = handleFieldExpr(expr, p, depth); possibleClassNames.addAll(types); } } else { ClassOrInterfaceType type = new ClassOrInterfaceType(expr.toString()); type.setBeginLine(expr.getBeginLine()); type.setEndLine(expr.getEndLine()); type.setBeginColumn(expr.getBeginColumn()); type.setEndColumn(expr.getEndColumn()); possible = handleClassOrInterfaceType(type); if (possible.size() == 0) { print(depth, "Error: Could not parse FieldAccessExpr"); } else { print(depth, "FieldAccessExpr fqn: " + expr.getScope() + " " + expr.getField() + " " + expr.getScope().getClass() + " " + possible); possibleClassNames.addAll(possible); } } } else if (methodCallExpr.getScope() instanceof ArrayAccessExpr) { /* * somearray[index].method() */ } else if (methodCallExpr.getScope() instanceof ObjectCreationExpr) { /* * new Object().method() */ ObjectCreationExpr objectCreationExpr = (ObjectCreationExpr) methodCallExpr.getScope(); possibleClassNames.addAll(handleClassOrInterfaceType(objectCreationExpr.getType())); } print(depth, possibleClassNames.toString()); Map<String, LoadedFile> mapping = possibleClassNames.stream() .map(name -> new AbstractMap.SimpleEntry<>(name, getFileFor(name))) .filter(ent -> ent.getValue() != null) .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); if (mapping.size() == 0) { print(depth, "Error: Could not find classname"); } else if (mapping.size() > 1) { print(depth, "Error: More than one classname found: " + mapping.keySet()); //fixme filter by which one contains the method } else { print(depth, "ClassName is " + mapping.keySet()); String className = mapping.keySet().iterator().next(); String internalName = className.substring(0, className.length() - 6); try { while (true) { LoadedFile readFrom = null; String fileName = internalName + ".class"; LoadedFile file = Helios.getLoadedFile(this.fileName); if (file.getAllData().get(fileName) != null) { readFrom = file; } else { Set<LoadedFile> check = new HashSet<>(); check.addAll(Helios.getAllFiles()); check.addAll(Helios.getPathFiles().values()); for (LoadedFile loadedFile : check) { if (loadedFile.getAllData().get(fileName) != null) { readFrom = loadedFile; break; } } } if (readFrom != null) { print(depth, "Found in " + readFrom.getName()); link.fileName = readFrom.getName(); link.className = fileName; link.jumpTo = " " + nameExpr.getName() + "("; textArea.links.add(link); ClassNode classNode = readFrom.getEmptyClasses().get(internalName); print(depth, "Looking for method with name " + methodCallExpr.getName() + " in " + internalName + " " + classNode); MethodNode node = classNode.methods.stream() .filter(mn -> mn.name.equals(methodCallExpr.getName())).findFirst().orElse(null); if (node != null) { link.className = internalName + ".class"; Type returnType = Type.getType(node.desc); if (returnType.getReturnType().getSort() == Type.OBJECT) { print(depth, "Found method with return type " + returnType); return returnType.getReturnType().getInternalName() + ".class"; } else if (returnType.getReturnType().getSort() == Type.ARRAY) { return "java/lang/Object.class"; } else { return null; } } else { print(depth, "Could not find methodnode " + methodCallExpr.getName()); } if (internalName.equals("java/lang/Object")) { break; } internalName = classNode.superName; } else { print(depth, "Could not find readfrom "); break; } } } catch (Exception e) { e.printStackTrace(System.out); } } return null; }
From source file:com.globalsight.webservices.Ambassador.java
private String zippedFolder(Set<Long> jobIdSet, Map<Long, Set<File>> exportFilesMap, Set<String> locales) { String fileUrl = null;/* ww w .j a v a 2 s . c om*/ String directory = AmbFileStoragePathUtils.getFileStorageDirPath(1).replace("\\", "/") + File.separator + "Reports" + File.separator + "apiQACheckDownload"; new File(directory).mkdirs(); String downloadFileName = null; if (jobIdSet != null && jobIdSet.size() == 1) { Long jobId = jobIdSet.iterator().next(); downloadFileName = ReportConstants.REPORT_QA_CHECKS_REPORT + "_(" + jobId + ").zip"; } else if (jobIdSet != null && jobIdSet.size() > 1) { String tempS = jobIdSet.toString(); tempS = tempS.replace(" ", ""); String jobNamesstr = tempS.substring(1, tempS.length() - 1); downloadFileName = ReportConstants.REPORT_QA_CHECKS_REPORT + "_(" + jobNamesstr + ").zip"; } String zipFileName = directory + File.separator + downloadFileName; File zipFile = new File(zipFileName); Map<File, String> allEntryFileToFileNameMap = new HashMap<File, String>(); Set<Long> keySet = exportFilesMap.keySet(); for (Long companyId : keySet) { Set<File> exportListFiles = exportFilesMap.get(companyId); Map<File, String> entryFileToFileNameMap = WorkflowHandlerHelper.getEntryFileToFileNameMap( exportListFiles, jobIdSet, locales, AmbFileStoragePathUtils.getReportsDir(companyId).getPath() + File.separator + ReportConstants.REPORT_QA_CHECKS_REPORT); allEntryFileToFileNameMap.putAll(entryFileToFileNameMap); } try { if (allEntryFileToFileNameMap.entrySet().size() > 0) { ZipIt.addEntriesToZipFile(zipFile, allEntryFileToFileNameMap, ""); String filestore = AmbFileStoragePathUtils.getFileStorageDirPath(1).replace("\\", "/"); String fullPathName = zipFile.getAbsolutePath().replace("\\", "/"); String path = fullPathName.substring(fullPathName.indexOf(filestore) + filestore.length()); String root = AmbassadorUtil.getCapLoginOrPublicUrl() + "/DownloadReports"; fileUrl = root + path; } else { fileUrl = "No QA report available for download."; } } catch (Exception e) { logger.error(e.getMessage(), e); } return fileUrl; }