List of usage examples for java.util List equals
boolean equals(Object o);
From source file:org.opencb.opencga.storage.core.variant.VariantStoragePipeline.java
/** * PreLoad step for modify the StudyConfiguration. * This step is executed inside a study lock. * * @see StudyConfigurationManager#lockStudy(int) * @param studyConfiguration StudyConfiguration * @param source VariantSource * @throws StorageEngineException If any condition is wrong *//*w w w. j a v a 2s .co m*/ protected void securePreLoad(StudyConfiguration studyConfiguration, VariantSource source) throws StorageEngineException { /* * Before load file, check and add fileName to the StudyConfiguration. * FileID and FileName is read from the VariantSource * If fileId is -1, read fileId from Options * Will fail if: * fileId is not an integer * fileId was already in the studyConfiguration.indexedFiles * fileId was already in the studyConfiguration.fileIds with a different fileName * fileName was already in the studyConfiguration.fileIds with a different fileId */ int fileId; String fileName = source.getFileName(); try { fileId = Integer.parseInt(source.getFileId()); } catch (NumberFormatException e) { throw new StorageEngineException("FileId '" + source.getFileId() + "' is not an integer", e); } if (fileId < 0) { fileId = options.getInt(Options.FILE_ID.key(), Options.FILE_ID.defaultValue()); } else { int fileIdFromParams = options.getInt(Options.FILE_ID.key(), Options.FILE_ID.defaultValue()); if (fileIdFromParams >= 0 && fileIdFromParams != fileId) { if (!options.getBoolean(Options.OVERRIDE_FILE_ID.key(), Options.OVERRIDE_FILE_ID.defaultValue())) { throw new StorageEngineException("Wrong fileId! Unable to load using fileId: " + fileIdFromParams + ". " + "The input file has fileId: " + fileId + ". Use " + Options.OVERRIDE_FILE_ID.key() + " to ignore original fileId."); } else { //Override the fileId fileId = fileIdFromParams; } } } if (studyConfiguration.getIndexedFiles().isEmpty()) { // First indexed file // Use the EXCLUDE_GENOTYPES value from CLI. Write in StudyConfiguration.attributes boolean excludeGenotypes = options.getBoolean(Options.EXCLUDE_GENOTYPES.key(), Options.EXCLUDE_GENOTYPES.defaultValue()); studyConfiguration.setAggregation(options.get(Options.AGGREGATED_TYPE.key(), VariantSource.Aggregation.class, Options.AGGREGATED_TYPE.defaultValue())); studyConfiguration.getAttributes().put(Options.EXCLUDE_GENOTYPES.key(), excludeGenotypes); } else { // Not first indexed file // Use the EXCLUDE_GENOTYPES value from StudyConfiguration. Ignore CLI value boolean excludeGenotypes = studyConfiguration.getAttributes() .getBoolean(Options.EXCLUDE_GENOTYPES.key(), Options.EXCLUDE_GENOTYPES.defaultValue()); options.put(Options.EXCLUDE_GENOTYPES.key(), excludeGenotypes); } fileId = checkNewFile(studyConfiguration, fileId, fileName); options.put(Options.FILE_ID.key(), fileId); studyConfiguration.getFileIds().put(source.getFileName(), fileId); // studyConfiguration.getHeaders().put(fileId, source.getMetadata().get(VariantFileUtils.VARIANT_FILE_HEADER).toString()); checkAndUpdateStudyConfiguration(studyConfiguration, fileId, source, options); // Check Extra genotype fields if (options.containsKey(Options.EXTRA_GENOTYPE_FIELDS.key()) && StringUtils.isNotEmpty(options.getString(Options.EXTRA_GENOTYPE_FIELDS.key()))) { List<String> extraFields = options.getAsStringList(Options.EXTRA_GENOTYPE_FIELDS.key()); if (studyConfiguration.getIndexedFiles().isEmpty()) { studyConfiguration.getAttributes().put(Options.EXTRA_GENOTYPE_FIELDS.key(), extraFields); } else { if (!extraFields.equals( studyConfiguration.getAttributes().getAsStringList(Options.EXTRA_GENOTYPE_FIELDS.key()))) { throw new StorageEngineException( "Unable to change Stored Extra Fields if there are already indexed files."); } } if (!studyConfiguration.getAttributes().containsKey(Options.EXTRA_GENOTYPE_FIELDS_TYPE.key())) { List<String> extraFieldsType = new ArrayList<>(extraFields.size()); for (String extraField : extraFields) { List<Map<String, Object>> formats = (List) source.getHeader().getMeta().get("FORMAT"); VCFHeaderLineType type = VCFHeaderLineType.String; for (Map<String, Object> format : formats) { if (format.get("ID").toString().equals(extraField)) { if ("1".equals(format.get("Number"))) { try { type = VCFHeaderLineType.valueOf(Objects.toString(format.get("Type"))); } catch (IllegalArgumentException ignore) { type = VCFHeaderLineType.String; } } else { //Fields with arity != 1 are loaded as String type = VCFHeaderLineType.String; } break; } } switch (type) { case String: case Float: case Integer: break; case Character: default: type = VCFHeaderLineType.String; break; } extraFieldsType.add(type.toString()); logger.debug(extraField + " : " + type); } studyConfiguration.getAttributes().put(Options.EXTRA_GENOTYPE_FIELDS_TYPE.key(), extraFieldsType); } } }
From source file:org.apache.hadoop.hbase.master.TestLoadBalancer.java
@Test public void testRandomizer() { for (int[] mockCluster : clusterStateMocks) { if (mockCluster.length < 5) continue; Map<HServerInfo, List<HRegionInfo>> servers = mockClusterServers(mockCluster); for (Map.Entry<HServerInfo, List<HRegionInfo>> e : servers.entrySet()) { List<HRegionInfo> original = e.getValue(); if (original.size() < 5) continue; // Try ten times in case random chances upon original order more than // one or two times in a row. boolean same = true; for (int i = 0; i < 10 && same; i++) { List<HRegionInfo> copy = new ArrayList<HRegionInfo>(original); System.out.println("Randomizing before " + copy.size()); for (HRegionInfo hri : copy) { System.out.println(hri.getEncodedName()); }/*from ww w .ja va2 s.c o m*/ List<HRegionInfo> randomized = LoadBalancer.randomize(copy); System.out.println("Randomizing after " + randomized.size()); for (HRegionInfo hri : randomized) { System.out.println(hri.getEncodedName()); } if (original.equals(randomized)) continue; same = false; break; } assertFalse(same); } } }
From source file:org.jahia.services.content.ConflictResolver.java
private List<Diff> compare(JCRNodeWrapper sourceNode, JCRNodeWrapper targetNode, String basePath) throws RepositoryException { List<Diff> diffs = new ArrayList<Diff>(); boolean remotelyPublished = targetNode.isNodeType("jmix:remotelyPublished"); if (!remotelyPublished) { final ListOrderedMap targetUuids = getChildEntries(targetNode, targetNode.getSession()); final ListOrderedMap sourceUuids = getChildEntries(sourceNode, sourceNode.getSession()); if (!targetUuids.values().equals(sourceUuids.values())) { for (Iterator<?> iterator = sourceUuids.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); if (targetUuids.containsKey(key) && !targetUuids.get(key).equals(sourceUuids.get(key))) { diffs.add(new ChildRenamedDiff(key, addPath(basePath, (String) targetUuids.get(key)), addPath(basePath, (String) sourceUuids.get(key)))); }//from ww w. j a v a2 s . c om } } // Child nodes if (!targetUuids.keyList().equals(sourceUuids.keyList())) { @SuppressWarnings("unchecked") List<String> addedUuids = new ArrayList<String>(sourceUuids.keySet()); addedUuids.removeAll(targetUuids.keySet()); @SuppressWarnings("unchecked") List<String> removedUuids = new ArrayList<String>(targetUuids.keySet()); removedUuids.removeAll(sourceUuids.keySet()); // Ordering if (targetNode.getPrimaryNodeType().hasOrderableChildNodes()) { Map<String, String> newOrdering = getOrdering(sourceUuids, Collections.<String>emptyList()); @SuppressWarnings("unchecked") List<String> oldUuidsList = new ArrayList<String>(targetUuids.keySet()); oldUuidsList.removeAll(removedUuids); @SuppressWarnings("unchecked") List<String> newUuidsList = new ArrayList<String>(sourceUuids.keySet()); newUuidsList.removeAll(addedUuids); if (!oldUuidsList.equals(newUuidsList)) { for (int i = 1; i < oldUuidsList.size(); i++) { String x = oldUuidsList.get(i); int j = i; while (j > 0 && sourceUuids.indexOf(oldUuidsList.get(j - 1)) > sourceUuids.indexOf(x)) { oldUuidsList.set(j, oldUuidsList.get(j - 1)); j--; } if (j != i) { String orderBeforeUuid = (j + 1 == oldUuidsList.size()) ? null : oldUuidsList.get(j + 1); diffs.add(new ChildNodeReorderedDiff(x, orderBeforeUuid, addPath(basePath, (String) sourceUuids.get(x)), (String) sourceUuids.get(orderBeforeUuid), newOrdering)); logger.debug("reorder " + sourceUuids.get(x) + " before " + sourceUuids.get(orderBeforeUuid)); oldUuidsList.set(j, x); } } } } // Removed nodes for (String removedUuid : removedUuids) { try { this.sourceNode.getSession().getNodeByUUID(removedUuid); } catch (ItemNotFoundException e) { // Item has been moved diffs.add(new ChildRemovedDiff(removedUuid, addPath(basePath, (String) targetUuids.get(removedUuid)), removedUuid)); } } // Added nodes for (String addedUuid : addedUuids) { diffs.add(new ChildAddedDiff(addedUuid, addPath(basePath, (String) sourceUuids.get(addedUuid)), addedUuid.equals(sourceUuids.lastKey()) ? null : (String) sourceUuids .get(sourceUuids.get(sourceUuids.indexOf(addedUuid) + 1)))); } } } PropertyIterator targetProperties = targetNode.getProperties(); while (targetProperties.hasNext()) { JCRPropertyWrapper targetProperty = (JCRPropertyWrapper) targetProperties.next(); String propertyName = targetProperty.getName(); if (IGNORED_PROPRTIES.contains(propertyName)) { continue; } if (!sourceNode.hasProperty(propertyName)) { if (targetProperty.isMultiple()) { Value[] values = targetProperty.getRealValues(); for (Value value : values) { diffs.add(new PropertyRemovedDiff(addPath(basePath, propertyName), value)); } } else { diffs.add(new PropertyChangedDiff(addPath(basePath, propertyName), null)); } } else { JCRPropertyWrapper sourceProperty = sourceNode.getProperty(propertyName); if (targetProperty.isMultiple() != sourceProperty.isMultiple()) { throw new RepositoryException(); } if (targetProperty.isMultiple()) { List<? extends Value> targetValues = Arrays.asList(targetProperty.getRealValues()); List<? extends Value> sourceValues = Arrays.asList(sourceProperty.getRealValues()); Map<String, Value> addedValues = new HashMap<String, Value>(); for (Value value : sourceValues) { addedValues.put(value.getString(), value); } for (Value value : targetValues) { addedValues.remove(value.getString()); } for (Value value : addedValues.values()) { diffs.add(new PropertyAddedDiff(addPath(basePath, propertyName), value)); } Map<String, Value> removedValues = new HashMap<String, Value>(); for (Value value : targetValues) { removedValues.put(value.getString(), value); } for (Value value : sourceValues) { removedValues.remove(value.getString()); } for (Value value : removedValues.values()) { diffs.add(new PropertyRemovedDiff(addPath(basePath, propertyName), value)); } } else { if (!equalsValue(targetProperty.getRealValue(), sourceProperty.getRealValue())) { diffs.add(new PropertyChangedDiff(addPath(basePath, propertyName), sourceProperty.getRealValue())); } } } } PropertyIterator sourceProperties = sourceNode.getProperties(); while (sourceProperties.hasNext()) { JCRPropertyWrapper sourceProperty = (JCRPropertyWrapper) sourceProperties.next(); String propertyName = sourceProperty.getName(); if (IGNORED_PROPRTIES.contains(propertyName)) { continue; } if (!targetNode.hasProperty(propertyName)) { if (sourceProperty.isMultiple()) { Value[] values = sourceProperty.getRealValues(); for (Value value : values) { diffs.add(new PropertyAddedDiff(addPath(basePath, sourceProperty.getName()), value)); } } else { diffs.add(new PropertyChangedDiff(addPath(basePath, sourceProperty.getName()), sourceProperty.getRealValue())); } } } for (Diff diff : new ArrayList<Diff>(diffs)) { if (diff instanceof PropertyAddedDiff && ((PropertyAddedDiff) diff).propertyPath.endsWith(Constants.JCR_MIXINTYPES)) { diffs.remove(diff); diffs.add(0, diff); } } for (Diff diff : new ArrayList<Diff>(diffs)) { if (diff instanceof PropertyRemovedDiff && ((PropertyRemovedDiff) diff).propertyPath.endsWith(Constants.JCR_MIXINTYPES)) { diffs.remove(diff); diffs.add(0, diff); } } if (!remotelyPublished) { NodeIterator targetSubNodes = targetNode.getNodes(); while (targetSubNodes.hasNext()) { JCRNodeWrapper targetSubNode = (JCRNodeWrapper) targetSubNodes.next(); if (sourceNode.hasNode(targetSubNode.getName()) && !targetSubNode.isVersioned() && !sourceNode.getNode(targetSubNode.getName()).isVersioned() && JCRPublicationService.supportsPublication(targetSubNode.getSession(), targetSubNode)) { diffs.addAll(compare(sourceNode.getNode(targetSubNode.getName()), targetSubNode, addPath(basePath, targetSubNode.getName()))); } } } return diffs; }
From source file:org.jdal.vaadin.beans.TableBeanDefinitionParser.java
/** * {@inheritDoc}//from ww w .j a v a 2s .co m */ @SuppressWarnings("rawtypes") public BeanDefinition parse(Element element, ParserContext parserContext) { // Defaults String entity = null; if (element.hasAttribute(ENTITY)) entity = element.getAttribute(ENTITY); String name = StringUtils.uncapitalize(StringUtils.substringAfterLast(entity, ".")); if (element.hasAttribute(ID)) name = element.getAttribute(ID); parserContext.pushContainingComponent( new CompositeComponentDefinition(name, parserContext.extractSource(element))); // Bean names String pageableTableBeanName = name + PAGEABLE_TABLE_SUFFIX; String tableBeanName = name + TABLE_SUFFIX; String dataSource = name + SERVICE_SUFFIX; String paginator = PAGINATOR_VIEW; String editor = name + EDITOR_SUFFIX; String actions = DefaultsBeanDefinitionParser.DEFAULT_TABLE_ACTIONS; String guiFactory = DefaultsBeanDefinitionParser.DEFAULT_GUI_FACTORY; String scope = BeanDefinition.SCOPE_PROTOTYPE; String pageableTableClass = DEFAULT_PAGEABLE_TABLE_CLASS; String tableClass = DEFAULT_TABLE_CLASS; if (element.hasAttribute(DATA_SOURCE)) dataSource = element.getAttribute(DATA_SOURCE); if (element.hasAttribute(PAGINATOR)) paginator = element.getAttribute(PAGINATOR); if (element.hasAttribute(ACTIONS)) actions = element.getAttribute(ACTIONS); if (element.hasAttribute(GUI_FACTORY)) guiFactory = element.getAttribute(GUI_FACTORY); if (element.hasAttribute(EDITOR)) editor = element.getAttribute(EDITOR); if (element.hasAttribute(SCOPE)) scope = element.getAttribute(SCOPE); if (element.hasAttribute(PAGEABLE_TABLE_CLASS)) pageableTableClass = element.getAttribute(PAGEABLE_TABLE_CLASS); if (element.hasAttribute(TABLE_CLASS)) tableClass = element.getAttribute(TABLE_CLASS); // create PageableTable BeanDefinitionBuilder bdb = BeanDefinitionBuilder.genericBeanDefinition(pageableTableClass); bdb.setScope(scope); bdb.addPropertyReference(DATA_SOURCE, dataSource); bdb.addPropertyReference(PAGINATOR_VIEW, paginator); bdb.addPropertyValue(NAME, pageableTableBeanName); bdb.addPropertyReference(TABLE, tableBeanName); bdb.addPropertyReference(GUI_FACTORY, guiFactory); bdb.addPropertyValue(EDITOR_NAME, editor); bdb.addPropertyValue(ENTITY_CLASS, entity); BeanDefinitionUtils.addPropertyReferenceIfNeeded(bdb, element, TABLE_SERVICE); BeanDefinitionUtils.addPropertyReferenceIfNeeded(bdb, element, FILTER); BeanDefinitionUtils.addPropertyReferenceIfNeeded(bdb, element, MESSAGE_SOURCE); BeanDefinitionUtils.addPropertyReferenceIfNeeded(bdb, element, FILTER_FORM); BeanDefinitionUtils.addPropertyValueIfNeeded(bdb, element, SORT_PROPERTY); BeanDefinitionUtils.addPropertyValueIfNeeded(bdb, element, ORDER); BeanDefinitionUtils.addPropertyValueIfNeeded(bdb, element, PAGE_SIZE); BeanDefinitionUtils.addPropertyValueIfNeeded(bdb, element, NATIVE_BUTTONS); BeanDefinitionUtils.addPropertyValueIfNeeded(bdb, element, PROPAGATE_SERVICE); if (!element.hasAttribute(USE_ACTIONS) || "true".equals(element.getAttribute(USE_ACTIONS))) bdb.addPropertyReference(ACTIONS, actions); parserContext.getDelegate().parseBeanDefinitionAttributes(element, pageableTableBeanName, null, bdb.getBeanDefinition()); BeanDefinitionHolder holder = new BeanDefinitionHolder(bdb.getBeanDefinition(), pageableTableBeanName); // Test Decorators like aop:scoped-proxy NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node n = childNodes.item(i); if (Node.ELEMENT_NODE != n.getNodeType() || COLUMNS.equals(n.getLocalName())) continue; NamespaceHandler handler = parserContext.getReaderContext().getNamespaceHandlerResolver() .resolve(n.getNamespaceURI()); if (handler != null) { holder = handler.decorate(n, holder, parserContext); } } parserContext.registerBeanComponent(new BeanComponentDefinition(holder)); // create ConfigurableTable bdb = BeanDefinitionBuilder.genericBeanDefinition(tableClass); bdb.setScope(BeanDefinition.SCOPE_PROTOTYPE); BeanDefinitionUtils.addPropertyReferenceIfNeeded(bdb, element, FIELD_FACTORY); BeanDefinitionUtils.addPropertyValueIfNeeded(bdb, element, MULTISELECT); if (element.hasAttribute(SELECTABLE)) { bdb.addPropertyValue(SELECTABLE, element.getAttribute(SELECTABLE)); } else { // set selectable by default bdb.addPropertyValue(SELECTABLE, true); } // parse columns NodeList nl = element.getElementsByTagNameNS(element.getNamespaceURI(), COLUMNS); if (nl.getLength() > 0) { List columns = parserContext.getDelegate().parseListElement((Element) nl.item(0), bdb.getRawBeanDefinition()); bdb.addPropertyValue(COLUMNS, columns); } registerBeanDefinition(element, parserContext, tableBeanName, bdb); parserContext.popAndRegisterContainingComponent(); return null; }
From source file:com.ciphertool.genetics.algorithms.mutation.ConservativeMutationAlgorithmTest.java
@Test public void testMutateChromosome() { conservativeMutationAlgorithm.setMaxMutationsPerChromosome(MAX_MUTATIONS); MockKeylessChromosome mockKeylessChromosome = new MockKeylessChromosome(); List<Gene> originalGenes = new ArrayList<Gene>(); MockGene mockGene1 = new MockGene(); mockGene1.addSequence(new MockSequence("a")); mockGene1.addSequence(new MockSequence("b")); mockGene1.addSequence(new MockSequence("c")); mockKeylessChromosome.addGene(mockGene1); originalGenes.add(mockGene1);//from w ww . ja v a2 s . co m MockGene mockGene2 = new MockGene(); mockGene2.addSequence(new MockSequence("1")); mockGene2.addSequence(new MockSequence("2")); mockGene2.addSequence(new MockSequence("3")); mockKeylessChromosome.addGene(mockGene2); originalGenes.add(mockGene2); MockGene mockGeneToReturn = new MockGene(); mockGeneToReturn.addSequence(new MockSequence("x")); mockGeneToReturn.addSequence(new MockSequence("y")); mockGeneToReturn.addSequence(new MockSequence("z")); when(geneDaoMock.findRandomGeneOfLength(same(mockKeylessChromosome), anyInt())) .thenReturn(mockGeneToReturn); conservativeMutationAlgorithm.mutateChromosome(mockKeylessChromosome); assertFalse(originalGenes.equals(mockKeylessChromosome.getGenes())); verify(geneDaoMock, atLeastOnce()).findRandomGeneOfLength(same(mockKeylessChromosome), anyInt()); verify(geneDaoMock, atMost(2)).findRandomGeneOfLength(same(mockKeylessChromosome), anyInt()); verifyZeroInteractions(logMock); }
From source file:org.apache.hadoop.tools.rumen.TestRumenJobTraces.java
/** * Validate if the input history log paths are as expected. * @param inputs the resultant input paths to be validated * @param expectedHistoryFileNames the expected input history logs * @throws IOException/*from w w w. ja va 2s .c om*/ */ private void validateHistoryLogPaths(List<Path> inputs, List<String> expectedHistoryFileNames) throws IOException { System.out.println("\nExpected history files are:"); for (String historyFile : expectedHistoryFileNames) { System.out.println(historyFile); } System.out.println("\nResultant history files are:"); List<String> historyLogs = new ArrayList<String>(); for (Path p : inputs) { historyLogs.add(p.toUri().getPath()); System.out.println(p.toUri().getPath()); } assertEquals("Number of history logs found is different from the expected.", expectedHistoryFileNames.size(), inputs.size()); // Verify if all the history logs are expected ones and they are in the // expected order assertTrue("Some of the history log files do not match the expected.", historyLogs.equals(expectedHistoryFileNames)); }
From source file:org.trnltk.experiment.morphology.ambiguity.DataDiffUtil.java
/** * Find the differences between two texts. Simplifies the problem by * stripping any common prefix or suffix off the texts before diffing. * * @param list1 Old string to be diffed. * @param list2 New string to be diffed. * @param checklines Speedup flag. If false, then don't run a * line-level diff first to identify the changed areas. * If true, then run a faster slightly less optimal diff. * @param deadline Time when the diff should be complete by. Used * internally for recursive calls. Users should set DiffTimeout instead. * @return Linked List of Diff objects./*w w w . ja va 2 s. co m*/ */ private LinkedList<Diff<T>> diff_main(List<T> list1, List<T> list2, boolean checklines, long deadline) { // Check for null inputs. if (list1 == null || list2 == null) { throw new IllegalArgumentException("Null inputs. (diff_main)"); } // Check for equality (speedup). LinkedList<Diff<T>> diffs; if (list1.equals(list2)) { diffs = new LinkedList<Diff<T>>(); if (list1.size() != 0) { diffs.add(new Diff<T>(Operation.EQUAL, list1)); } return diffs; } // Trim off common prefix (speedup). int commonlength = diff_commonPrefix(list1, list2); List<T> commonprefix = list1.subList(0, commonlength); list1 = list1.subList(commonlength, list1.size()); list2 = list2.subList(commonlength, list2.size()); // Trim off common suffix (speedup). commonlength = diff_commonSuffix(list1, list2); List<T> commonsuffix = list1.subList(list1.size() - commonlength, list1.size()); list1 = list1.subList(0, list1.size() - commonlength); list2 = list2.subList(0, list2.size() - commonlength); // Compute the diff on the middle block. diffs = diff_compute(list1, list2, checklines, deadline); // Restore the prefix and suffix. if (commonprefix.size() != 0) { diffs.addFirst(new Diff<T>(Operation.EQUAL, commonprefix)); } if (commonsuffix.size() != 0) { diffs.addLast(new Diff<T>(Operation.EQUAL, commonsuffix)); } diff_cleanupMerge(diffs); return diffs; }
From source file:org.onebusaway.transit_data_federation.impl.beans.itineraries.ItinerariesBeanServiceImpl.java
private boolean isItineraryMatch(ItineraryBean a, ItineraryBean b) { List<String> instancesA = getTransitInstancesForItinerary(a); List<String> instancesB = getTransitInstancesForItinerary(b); return instancesA.equals(instancesB); }
From source file:de.innovationgate.wgpublisher.WGPRequestPath.java
protected WGPRequestPath(HttpServletRequest request, HttpServletResponse response, WGPDispatcher dispatcher) throws HttpErrorException, WGException, IOException, URIException { this.core = dispatcher.getCore(); this.queryString = request.getQueryString(); this.completeURL = buildCompleteURL(request); this.publisherURL = WGPDispatcher.getPublisherURL(request); // Extract the base part of the path - Redirect to start.jsp if no path information given this.basePath = this.getBasePath(request, dispatcher); if (this.basePath.equals("") || this.basePath.equals("/")) { if (core.getWgaConfiguration().getDefaultDatabase() == null) { this.pathType = TYPE_REDIRECT; this.resourcePath = this.publisherURL + this.core.getStartPageURL(); return; } else {/*from www .j a v a 2s . c o m*/ this.basePath = "/" + core.getWgaConfiguration().getDefaultDatabase(); } } // Tokenize Path int tildeTokenPos = -1; java.util.StringTokenizer pathTokens = new StringTokenizer(this.basePath, "/"); String token; while (pathTokens.hasMoreTokens()) { token = pathTokens.nextToken(); this.pathElements.add(token); if (token.charAt(0) == '~') { tildeTokenPos = this.pathElements.size() - 1; } } if (this.pathElements.size() < 1) { this.pathType = TYPE_INVALID; return; } // Resolve database this.databaseKey = ((String) this.pathElements.get(0)).toLowerCase(); ; this.database = (WGDatabase) core.getContentdbs().get(this.databaseKey); // if no database under this key, try to recognize a special path command if (this.database == null) { determineSpecialPathCommand(); if (this.database == null) { return; } } // Check if we need to enforce secure app mode URL secureURL = enforceSecureAppMode(database, request); if (secureURL != null) { pathType = TYPE_REDIRECT; resourcePath = secureURL.toString(); return; } // check if db is accessed via right protocol, host and port - Must be before login so it may get redirected to some certauth port URL currentURL = new URL(request.getRequestURL().toString()); URL redirectURL = enforceRedirectionRules(database, currentURL); // currentURL differs from redirectURL - redirect necessary if (redirectURL != null && !dispatcher.isBrowserInterface(request.getSession())) { pathType = TYPE_REDIRECT; resourcePath = redirectURL.toString(); return; } // Handle special db commands "login" and "logout". The only one not requiring to login to the database if (this.pathElements.size() == 2) { if ("login".equals(this.pathElements.get(1))) { this.pathType = TYPE_REDIRECT; String sourceURL = (request.getParameter("redirect") != null ? dispatcher.getCore().getURLEncoder().decode(request.getParameter("redirect")) : WGPDispatcher.getPublisherURL(request) + "/" + this.databaseKey); this.resourcePath = dispatcher.getLoginURL(request, database, sourceURL); this.appendQueryString = false; return; } else if ("logout".equals(this.pathElements.get(1))) { this.pathType = TYPE_LOGOUT; if (request.getParameter("redirect") != null) { this.resourcePath = request.getParameter("redirect"); this.appendQueryString = false; } else { this.resourcePath = WGPDispatcher.getPublisherURL(request) + "/" + this.databaseKey; } return; } } // Open the database try { if (pathType == TYPE_STATICTML && "admintml".equals(getPathCommand()) && dispatcher.isAdminLoggedIn(request)) { this.masterLogin = true; } // Prepare HTTP credentials if available String credentials = request.getHeader("Authorization"); if (credentials != null && credentials.trim().toLowerCase().startsWith("basic")) { DBLoginInfo loginInfo = DBLoginInfo.createFromHttpCredentials(credentials); if (loginInfo != null) { // Look if ANY media key uses HTTP login. Only if so we accept this login if (isHttpLoginUsed(database)) { request.setAttribute(REQATTRIB_HTTPLOGIN, loginInfo); } } } this.database = core.openContentDB(database, request, this.masterLogin); } catch (WGUnavailableException e) { throw new HttpErrorException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The website is currently unavailable: " + e.getMessage(), getDatabaseKey()); } catch (de.innovationgate.wgpublisher.AuthenticationException e) { throw new HttpErrorException(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage(), null); } catch (AccessException e) { throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN, e.getMessage(), null); } if (!database.isSessionOpen()) { handleLoginFailure(request, response, dispatcher); this.proceedRequest = false; return; } // If request is static/admin tml we are done here if (pathType == TYPE_STATICTML) { return; } // If only database given, go to home page if (this.pathElements.size() == 1) { this.pathType = TYPE_GOTO_HOMEPAGE; setPermanentRedirect(core.getWgaConfiguration().isUsePermanentRedirect()); return; } // Process tilde tokens if (tildeTokenPos != -1) { String tildeToken = (String) this.pathElements.get(tildeTokenPos); // Url to file attachment via ~file-Syntax if (tildeToken.equalsIgnoreCase("~file")) { this.pathType = TYPE_FILE; List<String> preTildeTokenElems = this.pathElements.subList(1, tildeTokenPos); this.containerKey = (String) preTildeTokenElems.get(preTildeTokenElems.size() - 1); this.fileName = WGUtils.serializeCollection( this.pathElements.subList(tildeTokenPos + 1, this.pathElements.size()), "/"); return; } } // Catch special db-related urls String elem1 = ((String) this.pathElements.get(1)).toLowerCase(); int elementsSize = this.pathElements.size(); if (elementsSize >= 3 && (elem1.equals("css"))) { this.pathType = TYPE_CSS; this.cssjsKey = this.database.toLowerCaseMeta( WGUtils.serializeCollection(this.pathElements.subList(2, this.pathElements.size()), "/")); return; } else if (elementsSize >= 3 && (elem1.equals("js"))) { this.pathType = TYPE_JS; this.cssjsKey = this.database.toLowerCaseMeta( WGUtils.serializeCollection(this.pathElements.subList(2, this.pathElements.size()), "/")); return; } else if (elementsSize >= 3 && elem1.equals("file")) { this.pathType = TYPE_FILE; int fileNameIndex = determineFileNameIndex(this.pathElements, 2); this.containerKey = this.database .toLowerCaseMeta(WGUtils.serializeCollection(this.pathElements.subList(2, fileNameIndex), ":")); this.fileName = WGUtils.serializeCollection(this.pathElements.subList(fileNameIndex, elementsSize), "/"); return; } // Find out if we have a title path URL TitlePathManager tpm = (TitlePathManager) database.getAttribute(WGACore.DBATTRIB_TITLEPATHMANAGER); if (tpm != null && tpm.isGenerateTitlePathURLs()) { TitlePathManager.TitlePath url = tpm.parseTitlePathURL(pathElements.subList(1, pathElements.size())); if (url != null) { this.pathType = TYPE_TITLE_PATH; this.titlePathURL = url; this.mediaKey = core.getMediaKey(url.getMediaKey()); if (url.getLanguage() == null) { completePath = false; } } } // Path identified as normal TML request, read media and layout key if (pathType == TYPE_UNKNOWN) { pathType = TYPE_TML; int elementIdx = this.readMediaKey(core, this.pathElements, 1); elementIdx = this.readLayoutKey(core, this.pathElements, elementIdx); if (elementIdx < this.pathElements.size()) { this.contentKey = this.database.toLowerCaseMeta((String) this.pathElements.get(elementIdx)); } if (this.layoutKey == null && this.contentKey == null) { this.pathType = TYPE_INVALID; } } // Retrieve the content if (getPathType() == WGPRequestPath.TYPE_TITLE_PATH) { this.content = getContentByTitlePath(request); if (this.content == null) { pathType = TYPE_UNKNOWN_CONTENT; } // If content was retrieved with struct key we check if the title path is correct. If not we force redirection to the correct version (#00003145) else if (getTitlePathURL().getStructKey() != null) { List<String> correctTitlePath = tpm.buildTitlePath(this.content, mediaKey.getKey(), new RequestLanguageChooser(this.database, request)); if (correctTitlePath == null || !correctTitlePath.equals(getTitlePathURL().getEncodedTitles())) { completePath = false; } } // If title path is configured to include keys but the current tp has no key we force redirection to the version including a key (#00003304). else if (tpm.isIncludeKeys()) { completePath = false; } } else if (getPathType() == TYPE_TML) { if (this.contentKey != null) { URLID contentid = new URLID(this.contentKey, this.database); boolean isBI = WGPDispatcher.isBrowserInterface(request.getSession()) || WGPDispatcher.isAuthoringMode(database.getDbReference(), request.getSession()); this.content = WGPDispatcher.getContentByAnyKey(contentid, database, new RequestLanguageChooser(database, request), isBI); if (this.content != null) { // Look if we really used the parsed content URLID information. if (!contentid.isCompleteFormat()) { completePath = false; } this.requestLanguage = content.getLanguage().getName(); } else { pathType = TYPE_UNKNOWN_CONTENT; } } // Contextless request. If we have no request language we have no complete path and we must determine a language else { if (requestLanguage == null) { completePath = false; LanguageBehaviour langBehaviour = LanguageBehaviourTools.retrieve(database); WGLanguage lang = langBehaviour.requestSelectDatabaseLanguage(database, request); if (lang != null) { this.requestLanguage = lang.getName(); } // Fallback to the database default language else { this.requestLanguage = database.getDefaultLanguage(); } } } } }
From source file:org.eurekastreams.server.persistence.mappers.LuceneSearchMapper.java
/** * Execute the mapper./*from ww w. j ava 2s.co m*/ * * @param inRequest * the request. * @return the items. */ @SuppressWarnings("unchecked") @Override public PagedSet<T> execute(final LuceneSearchRequest inRequest) { /** * Convoluted like this to make testing possible. */ FullTextEntityManager sessionEntityManager = fullTextEntityManager; if (sessionEntityManager == null) { sessionEntityManager = Search.getFullTextEntityManager(getEntityManager()); } QueryParser parser = queryBuilder.buildQueryParser(); List<T> results = null; PagedSet<T> pagedSet = null; try { StringBuilder query = new StringBuilder(); // TODO Escape!! for (Entry<String, Float> entry : inRequest.getFields().entrySet()) { query.append(entry.getKey()); query.append(":"); query.append("(%1$s)^"); query.append(Float.toString(entry.getValue())); query.append(" "); } String luceneQueryString = String.format(query.toString(), inRequest.getSearchString()); org.apache.lucene.search.Query luceneQuery = parser.parse(luceneQueryString); FullTextQuery fullTextQuery = sessionEntityManager.createFullTextQuery(luceneQuery, inRequest.getObjectType()); fullTextQuery.setFirstResult(inRequest.getFirstResult()); fullTextQuery.setMaxResults(inRequest.getMaxResults()); SortField[] fields = new SortField[inRequest.getSortFields().size()]; for (int i = 0; i < inRequest.getSortFields().size(); i++) { fields[i] = new SortField(inRequest.getSortFields().get(i), true); } Sort sort = new Sort(fields); fullTextQuery.setSort(sort); results = fullTextQuery.getResultList(); /** * GWT can't serialize EMPTY_LIST. */ if (results.equals(Collections.EMPTY_LIST)) { results = new ArrayList<T>(); } pagedSet = new PagedSet<T>(inRequest.getFirstResult(), inRequest.getFirstResult() + results.size() - 1, fullTextQuery.getResultSize(), results); } catch (ParseException e) { log.error(e); } return pagedSet; }