@Override public List<RepositoryFile> getChildren( Serializable folderId, String filter, Boolean showHiddenFiles) { return unmarshalFiles( repoWebService.getChildrenWithFilterAndHidden( folderId.toString() != null ? folderId.toString() : null, filter, showHiddenFiles)); }
@Override public Map<String, String> saveOrUpdataReturnCasecadeID( String objectType, HttpServletRequest request) throws Exception { Map<String, String> map = QueryUtil.getRequestParameterMapNoAjax(request); Object targetObject = Class.forName(objectType).newInstance(); String jsonString = map.get(this.getType(objectType).getSimpleName()); String cascadeTypes = map.get("cascadeType"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); Class<?> clazz = this.getType(objectType); targetObject = mapper.readValue(jsonString, clazz); Serializable id = this.commDao.saveOrUpdata(objectType, targetObject); Object target = this.findById(objectType, id.toString()); Map<String, String> returenIDs = new HashMap<String, String>(); returenIDs.put("id", id.toString()); if (cascadeTypes != null) { String[] s = cascadeTypes.split(","); for (int i = 0; i < s.length; i++) { PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, s[i]); Method method = pd.getReadMethod(); Object childTarget = method.invoke(target); PropertyDescriptor pdID = BeanUtils.getPropertyDescriptor(pd.getPropertyType(), "id"); String childTargetID = pdID.getReadMethod().invoke(childTarget).toString(); returenIDs.put(s[i], childTargetID); } } return returenIDs; }
@Override public RepositoryFile getFileAtVersion(Serializable fileId, Serializable versionId) { return repositoryFileAdapter.unmarshal( repoWebService.getFileAtVersion( fileId != null ? fileId.toString() : null, versionId != null ? versionId.toString() : null)); }
@Override public VersionSummary getVersionSummary(Serializable fileId, Serializable versionId) { return versionSummaryAdapter.unmarshal( repoWebService.getVersionSummary( fileId != null ? fileId.toString() : null, versionId != null ? versionId.toString() : null)); }
public static String changeID(Serializable id, String dbName, String type) { if (type.equals("int") || type.equals("java.lang.Integer") || type.equals("java.lang.integer") || type.equalsIgnoreCase("integer")) { return id.toString(); } if (type.equals("java.lang.Long") || type.equals("java.lang.long") || type.equalsIgnoreCase("long")) { return id.toString(); } if (type.equals("java.lang.String") || type.equalsIgnoreCase("string")) { char stringDelimiter = SQLManager.getInstance().getDBAdapter(dbName).getStringDelimiter(); return "" + stringDelimiter + id + stringDelimiter; } else { char stringDelimiter = SQLManager.getInstance().getDBAdapter(dbName).getStringDelimiter(); return "" + stringDelimiter + id + stringDelimiter; } }
@Override public RepositoryFile createFile( Serializable parentFolderId, RepositoryFile file, IRepositoryFileData data, String versionMessage) { if (data instanceof NodeRepositoryFileData) { return repositoryFileAdapter.unmarshal( repoWebService.createFile( parentFolderId != null ? parentFolderId.toString() : null, repositoryFileAdapter.marshal(file), nodeRepositoryFileDataAdapter.marshal((NodeRepositoryFileData) data), versionMessage)); } else if (data instanceof SimpleRepositoryFileData) { SimpleRepositoryFileData simpleData = (SimpleRepositoryFileData) data; return repositoryFileAdapter.unmarshal( repoWebService.createBinaryFile( parentFolderId != null ? parentFolderId.toString() : null, repositoryFileAdapter.marshal(file), SimpleRepositoryFileDataDto.convert(simpleData), versionMessage)); } else { throw new IllegalArgumentException(); } }
@Override @Deprecated public List<RepositoryFile> getChildren(Serializable folderId, String filter) { return unmarshalFiles( repoWebService.getChildrenWithFilter( folderId.toString() != null ? folderId.toString() : null, filter)); }
@Override protected String applyInternal() throws Exception { // get all users in the system List<PersonInfo> personInfos = _personService .getPeople(null, null, null, new PagingRequest(Integer.MAX_VALUE, null)) .getPage(); Set<NodeRef> people = new HashSet<NodeRef>(personInfos.size()); for (PersonInfo personInfo : personInfos) { people.add(personInfo.getNodeRef()); } int count = 0; // iterate through all the users for (final NodeRef person : people) { // get the username from the node final Serializable username = nodeService.getProperty(person, ContentModel.PROP_USERNAME); // if no username, continue if (username == null) { continue; } // if it's the guest or admin, skip as well if (username.toString().equals("guest") || username.toString().equals("admin")) { continue; } // list all sites that the user is excplicit member in final List<SiteInfo> sites = _siteService.listSites(username.toString()); // the user is member of 1 site or more, continue if (sites.size() > 0) { continue; } // if this point is reached, the user is not a member of any site, so it // should be deleted LOG.error("Deleting user '" + username + "', user is not a member of any site"); _personService.deletePerson(username.toString()); count++; } LOG.error( "Deleted " + count + " of " + people.size() + " users that wasn't a member in any sites."); return I18NUtil.getMessage(MSG_SUCCESS); }
public static Serializable getNewInstance(Type t, Serializable value) { switch (t) { case IntType: return Integer.valueOf(value.toString()); case StringType: return new String(value.toString()); case DoubleType: return Double.valueOf(value.toString()); default: throw new RuntimeException("Unable to instantiate type"); } }
protected RepositoryFileAcl internalUpdateAcl( final Session session, final PentahoJcrConstants pentahoJcrConstants, final Serializable fileId, final RepositoryFileAcl acl) throws RepositoryException { Node node = session.getNodeByIdentifier(fileId.toString()); if (node == null) { throw new RepositoryException( Messages.getInstance() .getString( "JackrabbitRepositoryFileAclDao.ERROR_0001_NODE_NOT_FOUND", fileId.toString())); // $NON-NLS-1$ } String absPath = node.getPath(); AccessControlManager acMgr = session.getAccessControlManager(); AccessControlList acList = getAccessControlList(acMgr, absPath); // clear all entries AccessControlEntry[] acEntries = acList.getAccessControlEntries(); for (int i = 0; i < acEntries.length; i++) { acList.removeAccessControlEntry(acEntries[i]); } JcrRepositoryFileAclUtils.setAclMetadata( session, absPath, acList, new AclMetadata(acl.getOwner().getName(), acl.isEntriesInheriting())); // add entries to now empty list but only if not inheriting; force user to start with clean // slate if (!acl.isEntriesInheriting()) { for (RepositoryFileAce ace : acl.getAces()) { Principal principal = null; if (RepositoryFileSid.Type.ROLE == ace.getSid().getType()) { principal = new SpringSecurityRolePrincipal(ace.getSid().getName()); } else { principal = new SpringSecurityUserPrincipal(ace.getSid().getName()); } acList.addAccessControlEntry( principal, permissionConversionHelper.pentahoPermissionsToPrivileges( session, ace.getPermissions())); } } acMgr.setPolicy(absPath, acList); session.save(); return getAcl(fileId); }
@Test(dataProvider = "objects") public void testURIs(Object object, String expectedPrefix) { Serializable id = URIGenerator.generate(object); assertNotNull(id, "generated null id"); assertFalse(id.toString().isEmpty(), "returned empty id"); assertTrue( id.toString().startsWith(expectedPrefix), "Generated id didn't start with correct prefix; expected: " + expectedPrefix + " but found " + id); }
@Override @SuppressWarnings("unchecked") public <T extends IRepositoryFileData> T getDataForRead(Serializable fileId, Class<T> dataClass) { if (dataClass.equals(NodeRepositoryFileData.class)) { return (T) nodeRepositoryFileDataAdapter.unmarshal( repoWebService.getDataAsNodeForRead(fileId != null ? fileId.toString() : null)); } else if (dataClass.equals(SimpleRepositoryFileData.class)) { SimpleRepositoryFileDataDto simpleJaxWsData = repoWebService.getDataAsBinaryForRead(fileId != null ? fileId.toString() : null); return (T) SimpleRepositoryFileDataDto.convert(simpleJaxWsData); } else { throw new IllegalArgumentException(); } }
private String getKeyword(Object bean, Serializable id) { StringBuffer buffer = new StringBuffer(); buffer.append(bean.getClass().getName()); buffer.append(':'); buffer.append(id.toString()); return buffer.toString(); }
/** * Get session instance from redis, the parameter sessionId without the redisSessionPrefix * * @param sessionId * @return */ public Session getSession(Serializable sessionId) { log.debug("get session, the sessionId is {}", sessionId); return (Session) SerializeUtils.deserialize( redisTemplate.getValue((redisSessionPrefix + sessionId.toString()).getBytes())); }
@SuppressWarnings({"unchecked"}) @Override public Resource convert(Object source) { if (null == repositoryMetadata || null == source) { return new Resource<Object>(source); } Serializable id = (Serializable) repositoryMetadata.entityMetadata().idAttribute().get(source); URI selfUri = buildUri(config.getBaseUri(), repositoryMetadata.name(), id.toString()); Set<Link> links = new HashSet<Link>(); for (Object attrName : entityMetadata.linkedAttributes().keySet()) { URI uri = buildUri(selfUri, attrName.toString()); String rel = repositoryMetadata.rel() + "." + source.getClass().getSimpleName() + "." + attrName; links.add(new Link(uri.toString(), rel)); } links.add(new Link(selfUri.toString(), "self")); Map<String, Object> entityDto = new HashMap<String, Object>(); for (Map.Entry<String, AttributeMetadata> attrMeta : ((Map<String, AttributeMetadata>) entityMetadata.embeddedAttributes()).entrySet()) { String name = attrMeta.getKey(); Object val; if (null != (val = attrMeta.getValue().get(source))) { entityDto.put(name, val); } } return new EntityResource(entityDto, links); }
/** * Send response to the client. Ignore exceptions. * * @param response Response to be sent. */ protected void sendResponse( final DaemonRequest request, final Serializable response, final boolean isLast) { try { if (isLast) { requestCount.decrementAndGet(); synchronized (requestCount) { requestCount.notifyAll(); } } if (response instanceof DaemonProgressMessage) { final DaemonProgressMessage daemonProgressMessage = (DaemonProgressMessage) response; // If response if a FileTokenHolder, set FileTokenFactory and force regenerating FileTokens. if (daemonProgressMessage.getProgressData() instanceof FileTokenHolder) { ((FileTokenHolder) daemonProgressMessage.getProgressData()) .translateOnSender(getDaemonConnection().getFileTokenFactory()); } } // This is the last response we will send - error occurred request.sendResponse(response, isLast); } catch (MprcException e1) { // SWALLOWED: We try to keep running even if we cannot report we failed translating the // message. LOGGER.error( "Ignored error: failed following response to client: '" + response.toString() + "'", e1); } }
@Override public Data process(Data data) { if (key != null && n != null && n >= 0) { Map<String, Double> counts = new LinkedHashMap<String, Double>(); Serializable val = data.get(key); if (val != null) { String str = val.toString(); for (int i = 0; i < str.length() - n; i++) { String ngram = str.substring(i, i + n); Double freq = counts.get(ngram); if (freq != null) { freq = freq + 1.0d; } else { freq = 1.0d; } counts.put(ngram, freq); } for (String key : counts.keySet()) { data.put(key, counts.get(key)); } log.debug("Added {} {}-grams to item", counts.size(), n); } } return data; }
@Override public RepositoryFile getFileById( Serializable fileId, boolean loadLocaleMaps, IPentahoLocale locale) { return this.repositoryFileAdapter.unmarshal( this.repoWebService.getFileById( fileId != null ? fileId.toString() : null, loadLocaleMaps, (PentahoLocale) locale)); }
@Override public ProcessStatus startSourceDocCreationOrUpdate( final String idNoSlash, final String projectSlug, final String iterationSlug, final Resource resource, final Set<String> extensions, final boolean copytrans) { HProjectIteration hProjectIteration = retrieveAndCheckIteration(projectSlug, iterationSlug, true); resourceUtils.validateExtensions(extensions); // gettext, comment String name = "SourceDocCreationOrUpdate: " + projectSlug + "-" + iterationSlug + "-" + idNoSlash; AsyncTaskHandle<HDocument> handle = new AsyncTaskHandle<HDocument>(); Serializable taskId = asyncTaskHandleManager.registerTaskHandle(handle); documentServiceImpl.saveDocumentAsync( projectSlug, iterationSlug, resource, extensions, copytrans, true, handle); return getProcessStatus(taskId.toString()); // TODO Change to return 202 // Accepted, // with a url to get the // progress }
@Override public List<RepositoryFileAce> getEffectiveAces( Serializable fileId, boolean forceEntriesInheriting) { return unmarshalAces( repoWebService.getEffectiveAcesWithForceFlag( fileId != null ? fileId.toString() : null, forceEntriesInheriting)); }
/** Corresponds to <element name="javaExecutable"> */ private Element createJavaExecutableElement(Document doc, JavaTask t) { Element executableE = doc.createElementNS(Schemas.SCHEMA_LATEST.namespace, XMLTags.JAVA_EXECUTABLE.getXMLName()); setAttribute(executableE, XMLAttributes.TASK_CLASS_NAME, t.getExecutableClassName(), true); // <ref name="javaParameters"/> try { Map<String, Serializable> args = t.getArguments(); if ((args != null) && (args.size() > 0)) { // <element name="parameter"> Element paramsE = doc.createElementNS( Schemas.SCHEMA_LATEST.namespace, XMLTags.TASK_PARAMETERS.getXMLName()); for (String name : args.keySet()) { Serializable val = args.get(name); Element paramE = doc.createElementNS( Schemas.SCHEMA_LATEST.namespace, XMLTags.TASK_PARAMETER.getXMLName()); setAttribute(paramE, XMLAttributes.COMMON_NAME, name, true); setAttribute(paramE, XMLAttributes.COMMON_VALUE, val.toString(), true); paramsE.appendChild(paramE); } executableE.appendChild(paramsE); } } catch (Exception e) { logger.error("Could not add arguments for Java Executable element of task " + t.getName(), e); } return executableE; }
public static void filterTree( Map<Department, Integer> tree, List<Department> temp, List<Department> list, Serializable ID, int deep) { if (temp.size() == 0) { return; } List<Department> tDepart = null; for (Department t : temp) { if (ID.toString().equals(t.getID() + "")) { continue; // 排除自己 } tree.put(t, deep); tDepart = new ArrayList<Department>(); for (Department depart : list) { if (depart.getParent() != null && t.getID() == depart.getParent().getID()) { tDepart.add(depart); } } if (tDepart.size() > 0) { filterTree(tree, tDepart, list, ID, deep + 1); } } }
/** {@inheritDoc} */ public void undeleteFile( final Session session, final PentahoJcrConstants pentahoJcrConstants, final Serializable fileId) throws RepositoryException { Node fileToUndeleteNode = session.getNodeByIdentifier(fileId.toString()); String trashFileIdNodePath = fileToUndeleteNode.getParent().getPath(); String origParentFolderPath = getOriginalParentFolderPath(session, pentahoJcrConstants, fileToUndeleteNode, false); String absDestPath = origParentFolderPath + RepositoryFile.SEPARATOR + fileToUndeleteNode.getName(); if (session.itemExists(absDestPath)) { RepositoryFile file = JcrRepositoryFileUtils.nodeToFile( session, pentahoJcrConstants, pathConversionHelper, lockHelper, (Node) session.getItem(absDestPath)); throw new RepositoryFileDaoFileExistsException(file); } session.move(fileToUndeleteNode.getPath(), absDestPath); session.getItem(trashFileIdNodePath).remove(); }
@Override public Optional<AttributeValidationReport> validate(final Attribute attribute) { Preconditions.checkArgument(attribute != null, "The attribute cannot be null."); final String name = attribute.getName(); for (final Serializable value : attribute.getValues()) { final BigDecimal bdValue; if (value instanceof Number) { bdValue = new BigDecimal(value.toString()); } else { continue; } if (!checkRange(bdValue)) { final String violationMessage = String.format( "%s must be between %s and %s", name, min.toPlainString(), max.toPlainString()); final AttributeValidationReportImpl report = new AttributeValidationReportImpl(); report.addViolation( new ValidationViolationImpl( Collections.singleton(name), violationMessage, Severity.ERROR)); return Optional.of(report); } } return Optional.empty(); }
@Override public ModuleService getModule(Serializable moduleID) { Module module; if (moduleID instanceof Long) module = (Module) moduleEngine.getModule((Long) moduleID); else module = (Module) moduleEngine.getModule(moduleID.toString()); if (module == null) return null; SFTSystem mainSystem = (SFTSystem) moduleEngine.getSystem(module); // TableService mainDataTable = this.makeBizTable(mainSystem); DemsyModuleService ret = new DemsyModuleService(module, mainDataTable); // List<TableService> childrenDataTables = new ArrayList(); List<IBizField> fkFields = bizEngine.getFieldsOfSlave(mainSystem); for (IBizField fkField : fkFields) { SFTSystem fkSystem = (SFTSystem) fkField.getSystem(); DemsyEntityTableService bizTable = this.makeBizTable(fkSystem); childrenDataTables.add(bizTable); // 设置该子表通过哪个字段引用了主表? bizTable.set("fkfield", fkField.getPropName()); // TODO:应通过模块表达式来解析数据表对象,目前暂时不支持模块对数据表的引用表达式。 } ret.setChildrenDataTables(childrenDataTables); return ret; }
public static TipoColaborador valueOf(Serializable codigo) { for (TipoColaborador tp : TipoColaborador.values()) { int codigoInt = Integer.parseInt(codigo.toString()); if (codigoInt == tp.codigo) return tp; } return null; }
public static String getStringFromAttribute(int type, Serializable attribute) { if (attribute == null) { return StringPool.BLANK; } if ((type == ExpandoColumnConstants.BOOLEAN) || (type == ExpandoColumnConstants.DOUBLE) || (type == ExpandoColumnConstants.FLOAT) || (type == ExpandoColumnConstants.INTEGER) || (type == ExpandoColumnConstants.LONG) || (type == ExpandoColumnConstants.SHORT)) { return String.valueOf(attribute); } else if ((type == ExpandoColumnConstants.BOOLEAN_ARRAY) || (type == ExpandoColumnConstants.DOUBLE_ARRAY) || (type == ExpandoColumnConstants.FLOAT_ARRAY) || (type == ExpandoColumnConstants.INTEGER_ARRAY) || (type == ExpandoColumnConstants.LONG_ARRAY) || (type == ExpandoColumnConstants.SHORT_ARRAY) || (type == ExpandoColumnConstants.STRING_ARRAY)) { return StringUtil.merge(ArrayUtil.toStringArray((Object[]) attribute)); } else if (type == ExpandoColumnConstants.DATE) { DateFormat dateFormat = _getDateFormat(); return dateFormat.format((Date) attribute); } else if (type == ExpandoColumnConstants.DATE_ARRAY) { return StringUtil.merge(ArrayUtil.toStringArray((Date[]) attribute, _getDateFormat())); } else { return attribute.toString(); } }
@Override public Qrcode httpQrcode(ReqTicket reqTicket, String scene) { Serializable sceneValue = reqTicket.generateScene(); String actionName = reqTicket.getActionName().toString(); Ticket ticket = weixinProxy.httpTicket(reqTicket); // 通过参数获取ticket String qrcodeUrl = String.format(QRCODE_URL, ticket.getTicket()); byte[] results = HttpClientUtil.httpGet(qrcodeUrl); Qrcode qrcode = new Qrcode(); qrcode.setTicketId(ticket.getId()); qrcode.setActionName(actionName); qrcode.setSceneValue(sceneValue.toString()); qrcode.setSceneType(sceneValue.getClass().getName()); qrcode.setName(weixinConfig.getName()); qrcode.setSuffix(weixinConfig.getSuffix()); qrcode.setBytes(results); qrcode.setSceneName(scene); if (log.isInfoEnabled()) { log.info( "返回二维码信息:{}", JSON.toJSONString( qrcode, SerializerFeature.PrettyFormat, SerializerFeature.WriteClassName)); } return qrcode; }
@Override public String toString() { if (value == null) { return "undefined"; } else { return value.toString(); } }
private RepositoryFileAcl toAcl( final Session session, final PentahoJcrConstants pentahoJcrConstants, final Serializable id) throws RepositoryException { Node node = session.getNodeByIdentifier(id.toString()); if (node == null) { throw new RepositoryException( Messages.getInstance() .getString( "JackrabbitRepositoryFileAclDao.ERROR_0001_NODE_NOT_FOUND", id.toString())); // $NON-NLS-1$ } String absPath = node.getPath(); AccessControlManager acMgr = session.getAccessControlManager(); AccessControlList acList = getAccessControlList(acMgr, absPath); RepositoryFileSid owner = null; String ownerString = getOwner(session, absPath, acList); if (ownerString != null) { // for now, just assume all owners are users; only has UI impact owner = new RepositoryFileSid( JcrTenantUtils.getUserNameUtils().getPrincipleName(ownerString), RepositoryFileSid.Type.USER); } RepositoryFileAcl.Builder aclBuilder = new RepositoryFileAcl.Builder(id, owner); aclBuilder.entriesInheriting(isEntriesInheriting(session, absPath, acList)); List<AccessControlEntry> cleanedAcEntries = JcrRepositoryFileAclUtils.removeAclMetadata( Arrays.asList(acList.getAccessControlEntries())); for (AccessControlEntry acEntry : cleanedAcEntries) { if (!acEntry .getPrincipal() .equals( new SpringSecurityRolePrincipal( JcrTenantUtils.getTenantedRole(tenantAdminAuthorityName)))) { aclBuilder.ace(toAce(session, acEntry)); } } return aclBuilder.build(); }