code
stringlengths
73
34.1k
label
stringclasses
1 value
void setFeature( XMLReader reader, String featureName, boolean value ) { try { if (reader.getFeature(featureName) != value) { reader.setFeature(featureName, value); } } catch (SAXException e) { getLogger().warn...
java
public long consumeLong() throws ParsingException, IllegalStateException { if (completed) throwNoMoreContent(); // Get the value from the current token ... String value = currentToken().value(); try { long result = Long.parseLong(value); moveToNextToken(); ...
java
public String consume() throws ParsingException, IllegalStateException { if (completed) throwNoMoreContent(); // Get the value from the current token ... String result = currentToken().value(); moveToNextToken(); return result; }
java
final Token currentToken() throws IllegalStateException, NoSuchElementException { if (currentToken == null) { if (completed) { throw new NoSuchElementException(CommonI18n.noMoreContent.text()); } throw new IllegalStateException(CommonI18n.startMethodMustBeCall...
java
final Token previousToken() throws IllegalStateException, NoSuchElementException { if (currentToken == null) { if (completed) { if (tokens.isEmpty()) { throw new NoSuchElementException(CommonI18n.noMoreContent.text()); } return toke...
java
static String generateFragment( String content, int indexOfProblem, int charactersToIncludeBeforeAndAfter, String highlightText ) { assert content != null; assert indexOfProblem < content.length()...
java
protected PlanNode createCanonicalPlan( QueryContext context, Query query ) { PlanNode plan = null; // Process the source of the query ... Map<SelectorName, Table> usedSources = new HashMap<SelectorName, Table>(); plan = createPlanNode(context...
java
protected void validate( QueryContext context, QueryCommand query, Map<SelectorName, Table> usedSelectors ) { // // Resolve everything ... // Visitors.visitAll(query, new Validator(context, usedSelectors)); // Resolve everything (except s...
java
protected PlanNode createCanonicalPlan( QueryContext context, SetQuery query ) { // Process the left and right parts of the query ... PlanNode left = createPlan(context, query.getLeft()); PlanNode right = createPlan(context, query.getRight()); ...
java
protected PlanNode createPlanNode( QueryContext context, Source source, Map<SelectorName, Table> usedSelectors ) { if (source instanceof Selector) { // No join required ... assert source instanceof AllNodes || ...
java
protected PlanNode attachCriteria( final QueryContext context, PlanNode plan, Constraint constraint, List<? extends Column> columns, Map<String, Subquery> subquerie...
java
protected PlanNode attachLimits( QueryContext context, PlanNode plan, Limit limit ) { if (limit.isUnlimited()) return plan; context.getHints().hasLimit = true; PlanNode limitNode = new PlanNode(Type.LIMIT); boolea...
java
protected PlanNode attachProject( QueryContext context, PlanNode plan, List<? extends Column> columns, Map<SelectorName, Table> selectors ) { PlanNode projectNode = new PlanNode(Type.PROJECT); ...
java
protected PlanNode attachSubqueries( QueryContext context, PlanNode plan, Map<String, Subquery> subqueriesByVariableName ) { // Order the variable names in reverse order ... List<String> varNames = new ArrayList<String>(su...
java
public synchronized Repository getRepository() throws ResourceException { if (this.repository == null) { LOGGER.debug("Deploying repository URL [{0}]", repositoryURL); this.repository = deployRepository(repositoryURL); } return this.repository; }
java
@Override public Object createConnectionFactory( ConnectionManager cxManager ) throws ResourceException { JcrRepositoryHandle handle = new JcrRepositoryHandle(this, cxManager); return handle; }
java
protected static void validate( IndexDefinition defn, Problems problems ) { if (!defn.hasSingleColumn()) { problems.addError(JcrI18n.localIndexProviderDoesNotSupportMultiColumnIndexes, defn.getName(), defn.getProviderName()); } switch (defn.getKind()) { case TEXT: ...
java
public boolean add( T entry ) { assert entry != null; if (!addEntries.get()) return false; try { producerLock.lock(); long position = cursor.claim(); // blocks; if this fails, we will not have successfully claimed and nothing to do ... int index = (int)(positi...
java
public boolean add( T[] entries ) { assert entries != null; if (entries.length == 0 || !addEntries.get()) return false; try { producerLock.lock(); long position = cursor.claim(entries.length); // blocks for (int i = 0; i != entries.length; ++i) { ...
java
public boolean remove( C consumer ) { if (consumer != null) { // Iterate through the map to find the runner that owns this consumer ... ConsumerRunner match = null; for (ConsumerRunner runner : consumers) { if (runner.getConsumer().equals(consumer)) { ...
java
public void shutdown() { // Prevent new entries from being added ... this.addEntries.set(false); // Mark the cursor as being finished; this will stop all consumers from waiting for a batch ... this.cursor.complete(); // Each of the consumer threads will complete the batch they'...
java
public void put(String name, Object value) { if (value instanceof EsRequest) { document.setDocument(name, ((EsRequest)value).document); } else { document.set(name, value); } }
java
public void put(String name, Object[] values) { if (values instanceof EsRequest[]) { Object[] docs = new Object[values.length]; for (int i = 0; i < docs.length; i++) { docs[i] = ((EsRequest)values[i]).document; } document.setArray(name, docs); ...
java
public static boolean isValidName( String name ) { if (name == null || name.length() == 0) return false; CharacterIterator iter = new StringCharacterIterator(name); char c = iter.first(); if (!isValidNameStart(c)) return false; while (c != CharacterIterator.DONE) { if...
java
public static boolean isValidNcName( String name ) { if (name == null || name.length() == 0) return false; CharacterIterator iter = new StringCharacterIterator(name); char c = iter.first(); if (!isValidNcNameStart(c)) return false; while (c != CharacterIterator.DONE) { ...
java
protected final QueryEngine queryEngine() { if (queryEngine == null) { try { engineInitLock.lock(); if (queryEngine == null) { QueryEngineBuilder builder = null; if (!repoConfig.getIndexProviders().isEmpty()) { ...
java
protected void reindexIfNeeded( boolean async, final boolean includeSystemContent ) { final ScanningRequest request = toBeScanned.drain(); if (!request.isEmpty()) { final RepositoryCache repoCache = runningState.repositoryCache(); scan(async, () -> { // Scan each ...
java
protected void cleanAndReindex( boolean async ) { final IndexWriter writer = getIndexWriter(); scan(async, getIndexWriter(), new Callable<Void>() { @SuppressWarnings( "synthetic-access" ) @Override public Void call() throws Exception { writer.clearAllI...
java
private void reindexContent( boolean includeSystemContent, IndexWriter indexes ) { if (indexes.canBeSkipped()) return; // The node type schemata changes every time a node type is (un)registered, so get the snapshot that we'll use throughout RepositoryCache repoCa...
java
public void reindexContent( JcrWorkspace workspace, Path path, int depth ) { if (getIndexWriter().canBeSkipped()) { // There's no indexes that require updating ... return; } CheckArg.isPositive(depth, "depth"...
java
public Future<Boolean> reindexContentAsync( final JcrWorkspace workspace ) { return indexingExecutorService.submit(() -> { reindexContent(workspace); return Boolean.TRUE; }); }
java
public Future<Boolean> reindexContentAsync( final JcrWorkspace workspace, final Path path, final int depth ) { return indexingExecutorService.submit(() -> { reindexContent(workspace, path, depth); ...
java
public void register( Map<String, String> namespaceUrisByPrefix ) { if (namespaceUrisByPrefix == null || namespaceUrisByPrefix.isEmpty()) return; final Lock lock = this.namespacesLock.writeLock(); try { lock.lock(); SystemContent systemContent = systemContent(false); ...
java
public static ReferrerCounts create( Map<NodeKey, Integer> strongCountsByReferrerKey, Map<NodeKey, Integer> weakCountsByReferrerKey ) { if (strongCountsByReferrerKey == null) strongCountsByReferrerKey = EMPTY_COUNTS; if (weakCountsByReferrerKey == null) weakCount...
java
protected void process( XSDSchema schema, String encoding, long contentSize, Node rootNode ) throws Exception { assert schema != null; logger.debug("Target namespace: '{0}'", schema.getTargetNamespace()); rootNo...
java
public void externalNodeRemoved( String externalNodeKey ) { if (this.snapshot.get().containsProjectionForExternalNode(externalNodeKey)) { // the external node was the root of a projection, so we need to remove that projection synchronized (this) { Snapshot current = this....
java
public void internalNodeRemoved( String internalNodeKey ) { if (this.snapshot.get().containsProjectionForInternalNode(internalNodeKey)) { // identify all the projections which from this internal (aka. federated node) and remove them synchronized (this) { Snapshot current ...
java
public Connector getConnectorForSourceName( String sourceName ) { assert sourceName != null; return this.snapshot.get().getConnectorWithSourceKey(NodeKey.keyForSourceName(sourceName)); }
java
public DocumentTranslator getDocumentTranslator() { if (translator == null) { // We don't want the connectors to use a translator that converts large strings to binary values that are // managed within ModeShape's binary store. Instead, all of the connector-created string property values...
java
void start( ScheduledExecutorService service ) { if (rollupFuture.get() != null) { // already started ... return; } // Pre-populate the metrics (overwriting any existing history object) ... durations.put(DurationMetric.QUERY_EXECUTION_TIME, new DurationHistory(Ti...
java
void stop() { ScheduledFuture<?> future = this.rollupFuture.getAndSet(null); if (future != null && !future.isDone() && !future.isCancelled()) { // Stop running the scheduled job, letting any currently running rollup finish ... future.cancel(false); } }
java
@SuppressWarnings( "fallthrough" ) private void rollup() { DateTime now = timeFactory.create(); Window largest = null; for (DurationHistory history : durations.values()) { largest = history.rollup(); } for (ValueHistory history : values.values()) { lar...
java
public void increment( ValueMetric metric, long incrementalValue ) { assert metric != null; ValueHistory history = values.get(metric); if (history != null) history.recordIncrement(incrementalValue); }
java
public void set( ValueMetric metric, long value ) { assert metric != null; ValueHistory history = values.get(metric); if (history != null) history.recordNewValue(value); }
java
void recordDuration( DurationMetric metric, long duration, TimeUnit timeUnit, Map<String, String> payload ) { assert metric != null; DurationHistory history = durations.get(metric); if (history != null) history.recordDura...
java
public static Statistics statisticsFor( long[] values ) { int length = values.length; if (length == 0) return EMPTY_STATISTICS; if (length == 1) return statisticsFor(values[0]); long total = 0L; long max = Long.MIN_VALUE; long min = Long.MAX_VALUE; for (long value...
java
public static Statistics statisticsFor( Statistics[] statistics ) { int length = statistics.length; if (length == 0) return EMPTY_STATISTICS; if (length == 1) return statistics[0] != null ? statistics[0] : EMPTY_STATISTICS; int count = 0; long max = Long.MIN_VALUE; long m...
java
public void setRecordsAmount(int amount) { int ipp = Integer.parseInt(itemsPerPageEditor.getValueAsString()); pageTotal = amount % ipp == 0? amount / ipp : amount / ipp + 1; draw(0); }
java
public List<ParsingResult> parseUsing( final String ddl, final String firstParserId, final String secondParserId, final String... additionalParserIds ) throws ParsingException { Check...
java
public ResolvedRequest withPath( String path ) { assert repositoryName != null; assert workspaceName != null; return new ResolvedRequest(request, repositoryName, workspaceName, path); }
java
public String findJcrName( String cmisName ) { for (int i = 0; i < list.size(); i++) { if (list.get(i).cmisName != null && list.get(i).cmisName.equals(cmisName)) { return list.get(i).jcrName; } } return cmisName; }
java
public String findCmisName( String jcrName ) { for (int i = 0; i < list.size(); i++) { if (list.get(i).jcrName != null && list.get(i).jcrName.equals(jcrName)) { return list.get(i).cmisName; } } return jcrName; }
java
public int getJcrType( PropertyType propertyType ) { switch (propertyType) { case BOOLEAN: return javax.jcr.PropertyType.BOOLEAN; case DATETIME: return javax.jcr.PropertyType.DATE; case DECIMAL: return javax.jcr.PropertyType.DEC...
java
public Object[] jcrValues( Property<?> property ) { @SuppressWarnings( "unchecked" ) List<Object> values = (List<Object>)property.getValues(); // convert CMIS values to JCR values switch (property.getType()) { case STRING: return asStrings(values); ...
java
private Boolean[] asBooleans( List<Object> values ) { ValueFactory<Boolean> factory = valueFactories.getBooleanFactory(); Boolean[] res = new Boolean[values.size()]; for (int i = 0; i < res.length; i++) { res[i] = factory.create(values.get(i)); } return res; }
java
private Long[] asIntegers( List<Object> values ) { ValueFactory<Long> factory = valueFactories.getLongFactory(); Long[] res = new Long[values.size()]; for (int i = 0; i < res.length; i++) { res[i] = factory.create(values.get(i)); } return res; }
java
private BigDecimal[] asDecimals( List<Object> values ) { ValueFactory<BigDecimal> factory = valueFactories.getDecimalFactory(); BigDecimal[] res = new BigDecimal[values.size()]; for (int i = 0; i < res.length; i++) { res[i] = factory.create(values.get(i)); } return re...
java
private URI[] asURI( List<Object> values ) { ValueFactory<URI> factory = valueFactories.getUriFactory(); URI[] res = new URI[values.size()]; for (int i = 0; i < res.length; i++) { res[i] = factory.create(((GregorianCalendar)values.get(i)).getTime()); } return res; ...
java
private String[] asIDs( List<Object> values ) { ValueFactory<String> factory = valueFactories.getStringFactory(); String[] res = new String[values.size()]; for (int i = 0; i < res.length; i++) { res[i] = factory.create(values.get(i)); } return res; }
java
protected void workspaceAdded( String workspaceName ) { String workspaceKey = NodeKey.keyForWorkspaceName(workspaceName); if (systemWorkspaceKey.equals(workspaceKey)) { // No sequencers for the system workspace! return; } Collection<SequencingConfiguration> config...
java
protected void workspaceRemoved( String workspaceName ) { // Otherwise, update the configs by workspace key ... try { configChangeLock.lock(); // Make a copy of the existing map ... Map<String, Collection<SequencingConfiguration>> configByWorkspaceName = new HashMap<S...
java
public static void register( String name, Object obj ) { register(name, obj, null, null, null, null); }
java
public Set<Name> getMixinTypes() { if (types.length == 1) { return Collections.emptySet(); } return new HashSet<Name>(Arrays.asList(Arrays.copyOfRange(types, 1, types.length))); }
java
private boolean hasModifierNamed( String modifierName ) { for (ModifierMetadata modifier : modifiers) { if (modifierName.equalsIgnoreCase(modifier.getName())) { return true; } } return false; }
java
public double getMedianValue() { Lock lock = this.getLock().writeLock(); try { lock.lock(); int count = this.values.size(); if (count == 0) { return 0.0d; } if (this.medianValue == null) { // Sort the values in n...
java
public double getStandardDeviation() { Lock lock = this.getLock().readLock(); lock.lock(); try { return this.sigma; } finally { lock.unlock(); } }
java
public org.modeshape.jcr.api.Problems backupRepository( File backupDirectory, BackupOptions options ) throws RepositoryException { // Create the activity ... final BackupActivity backupActivity = createBackupActivity(backupDirectory, options); //suspend any existing transactions try { ...
java
public org.modeshape.jcr.api.Problems restoreRepository( final JcrRepository repository, final File backupDirectory, final RestoreOptions options) throws RepositoryException { final String b...
java
protected final Metadata prepareMetadata( final Binary binary, final Context context ) throws IOException, RepositoryException { Metadata metadata = new Metadata(); String mimeType = binary.getMimeType(); if (StringUtil.isBlank(mimeType)) { ...
java
private List<ServerAddress> convertToServerAddresses(Set<String> addresses) { return addresses.stream() .map(this::stringToServerAddress) .filter(Objects::nonNull) .collect(Collectors.toList()); }
java
private void setAttribute( DBCollection content, String fieldName, Object value ) { DBObject header = content.findOne(HEADER_QUERY); BasicDBObject newHeader = new BasicDBObject(); // clone header newHeader.put(FIELD_CHUNK_TYP...
java
private Object getAttribute( DBCollection content, String fieldName ) { return content.findOne(HEADER_QUERY).get(fieldName); }
java
private boolean isExpired( DBCollection content, long deadline ) { Long unusedSince = (Long)getAttribute(content, FIELD_UNUSED_SINCE); return unusedSince != null && unusedSince < deadline; }
java
protected boolean pushDownJoinCriteria( PlanNode criteriaNode, PlanNode joinNode ) { JoinType joinType = (JoinType)joinNode.getProperty(Property.JOIN_TYPE); switch (joinType) { case CROSS: joinNode.setProperty(Property.JOIN_TYPE, J...
java
private void moveCriteriaIntoOnClause( PlanNode criteriaNode, PlanNode joinNode ) { List<Constraint> constraints = joinNode.getPropertyAsList(Property.JOIN_CONSTRAINTS, Constraint.class); Constraint criteria = criteriaNode.getProperty(Property.SELECT_CRITERIA, ...
java
protected void moveExtraProperties( String oldNodeId, String newNodeId ) { ExtraPropertiesStore extraPropertiesStore = extraPropertiesStore(); if (extraPropertiesStore == null || !extraPropertiesStore.contains(oldNodeId)) { return; } Ma...
java
protected void checkFieldNotNull( Object fieldValue, String fieldName ) throws RepositoryException { if (fieldValue == null) { throw new RepositoryException(JcrI18n.requiredFieldNotSetInConnector.text(getSourceName(), getClass(), fieldName)); } }
java
protected void populateRuleStack( LinkedList<OptimizerRule> ruleStack, PlanHints hints ) { ruleStack.addFirst(ReorderSortAndRemoveDuplicates.INSTANCE); ruleStack.addFirst(RewritePathAndNameCriteria.INSTANCE); if (hints.hasSubqueries) { ruleStack....
java
public Schemata getSchemataForSession( JcrSession session ) { assert session != null; // If the session does not override any namespace mappings used in this schemata ... if (!overridesNamespaceMappings(session)) { // Then we can just use this schemata instance ... return...
java
private boolean overridesNamespaceMappings( JcrSession session ) { NamespaceRegistry registry = session.context().getNamespaceRegistry(); if (registry instanceof LocalNamespaceRegistry) { Set<Namespace> localNamespaces = ((LocalNamespaceRegistry)registry).getLocalNamespaces(); if...
java
private List<Entry> removeValues( Collection<?> values, boolean ifMatch ) { LinkedList<Entry> results = null; // Record the list of entries that are removed, but start at the end of the values (so the indexes are correct) ListIterator<?> iter = this.values....
java
private boolean isExistCmisObject(String path) { try { session.getObjectByPath(path); return true; } catch (CmisObjectNotFoundException e) { return false; } }
java
private void rename(CmisObject object, String name){ Map<String, Object> newName = new HashMap<String, Object>(); newName.put("cmis:name", name); object.updateProperties(newName); }
java
private Document cmisObject( String id ) { CmisObject cmisObject; try { cmisObject = session.getObject(id); } catch (CmisObjectNotFoundException e) { return null; } // object does not exist? return null if (cmisObject == null) { ret...
java
private Document cmisFolder( CmisObject cmisObject ) { Folder folder = (Folder)cmisObject; DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.OBJECT, folder.getId())); ObjectType objectType = cmisObject.getType(); if (objectType.isBaseType()) { writer.setPri...
java
public Document cmisDocument( CmisObject cmisObject ) { org.apache.chemistry.opencmis.client.api.Document doc = (org.apache.chemistry.opencmis.client.api.Document)cmisObject; DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.OBJECT, doc.getId())); ObjectType objectType = cmisO...
java
private Document cmisContent( String id ) { DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.CONTENT, id)); org.apache.chemistry.opencmis.client.api.Document doc = (org.apache.chemistry.opencmis.client.api.Document)session.getObject(id); writer.setPrimaryType(NodeType.NT_RESO...
java
private void cmisProperties( CmisObject object, DocumentWriter writer ) { // convert properties List<Property<?>> list = object.getProperties(); for (Property<?> property : list) { String pname = properties.findJcrName(property.getId()); i...
java
private void cmisChildren( Folder folder, DocumentWriter writer ) { ItemIterable<CmisObject> it = folder.getChildren(); for (CmisObject obj : it) { writer.addChild(obj.getId(), obj.getName()); } }
java
private Document cmisRepository() { RepositoryInfo info = session.getRepositoryInfo(); DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.REPOSITORY_INFO, "")); writer.setPrimaryType(CmisLexicon.REPOSITORY); writer.setId(REPOSITORY_INFO_ID); // product name/ven...
java
private ContentStream jcrBinaryContent( Document document ) { // pickup node properties Document props = document.getDocument("properties").getDocument(JcrLexicon.Namespace.URI); // extract binary value and content Binary value = props.getBinary("data"); if (value == null) { ...
java
private void importTypes( List<Tree<ObjectType>> types, NodeTypeManager typeManager, NamespaceRegistry registry ) throws RepositoryException { for (Tree<ObjectType> tree : types) { importType(tree.getItem(), typeManager, registry); ...
java
@SuppressWarnings( "unchecked" ) public void importType( ObjectType cmisType, NodeTypeManager typeManager, NamespaceRegistry registry ) throws RepositoryException { // TODO: get namespace information and register // registry.registerNamespace(c...
java
private String[] superTypes( ObjectType cmisType ) { if (cmisType.getBaseTypeId() == BaseTypeId.CMIS_FOLDER) { return new String[] {JcrConstants.NT_FOLDER}; } if (cmisType.getBaseTypeId() == BaseTypeId.CMIS_DOCUMENT) { return new String[] {JcrConstants.NT_FILE}; ...
java
@SuppressWarnings( "unchecked" ) private void registerRepositoryInfoType( NodeTypeManager typeManager ) throws RepositoryException { // create node type template NodeTypeTemplate type = typeManager.createNodeTypeTemplate(); // convert CMIS type's attributes to node type template we have jus...
java
@Override public QueryResult execute( String query, String language ) throws RepositoryException { logger.trace("Executing query: {0}", query); // Create the query ... final Query jcrQuery = getLocalSession().getSession().getWorkspace().getQueryManager().cre...
java
public Repositories getRepositories() { JSONRestClient.Response response = jsonRestClient.doGet(); if (!response.isOK()) { throw new RuntimeException(JdbcI18n.invalidServerResponse.text(jsonRestClient.url(), response.asString())); } return new Repositories(response.json()); ...
java
public Workspaces getWorkspaces( String repositoryName ) { String url = jsonRestClient.appendToBaseURL(repositoryName); JSONRestClient.Response response = jsonRestClient.doGet(url); if (!response.isOK()) { throw new RuntimeException(JdbcI18n.invalidServerResponse.text(url, response.a...
java
public String queryPlan( String query, String queryLanguage ) { String url = jsonRestClient.appendToURL(QUERY_PLAN_METHOD); String contentType = contentTypeForQueryLanguage(queryLanguage); JSONRestClient.Response response = jsonRestClient.postStreamTextPlain(new Byte...
java
public long getCardinality() { if (pos > 0) { return totalHits; } try { EsResponse res = client.search(index, type, query); Document hits = (Document) res.get("hits"); totalHits = hits.getInteger("total"); return totalHits; } ca...
java