Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
299
public class ServiceException extends Exception { private static final long serialVersionUID = -7084792578727995587L; // for serialization purposes protected ServiceException() { super(); } public ServiceException(String message, Throwable cause) { super(message, cause); } public ServiceException(String message) { super(message); } public ServiceException(Throwable cause) { super(cause); } /** * Checks to see if any of the causes of the chain of exceptions that led to this ServiceException are an instance * of the given class. * * @param clazz * @return whether or not this exception's causes includes the given class. */ public boolean containsCause(Class<? extends Throwable> clazz) { Throwable current = this; do { if (clazz.isAssignableFrom(current.getClass())) { return true; } current = current.getCause(); } while (current.getCause() != null); return false; } }
1no label
common_src_main_java_org_broadleafcommerce_common_exception_ServiceException.java
201
public interface ReadBuffer extends ScanBuffer, StaticBuffer { public int getPosition(); public void movePositionTo(int position); public<T> T asRelative(Factory<T> factory); public ReadBuffer subrange(int length, boolean invert); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_ReadBuffer.java
137
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_SC") @EntityListeners(value = { AdminAuditableListener.class }) @AdminPresentationOverrides( { @AdminPresentationOverride(name = "auditable.createdBy.id", value = @AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)), @AdminPresentationOverride(name = "auditable.updatedBy.id", value = @AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)), @AdminPresentationOverride(name = "auditable.createdBy.name", value = @AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)), @AdminPresentationOverride(name = "auditable.updatedBy.name", value = @AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)), @AdminPresentationOverride(name = "auditable.dateCreated", value = @AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)), @AdminPresentationOverride(name = "auditable.dateUpdated", value = @AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)), @AdminPresentationOverride(name = "structuredContentType.name", value = @AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)), @AdminPresentationOverride(name = "structuredContentType.structuredContentFieldTemplate.name", value = @AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)) } ) @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "StructuredContentImpl_baseStructuredContent") public class StructuredContentImpl implements StructuredContent { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "StructuredContentId") @GenericGenerator( name="StructuredContentId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="StructuredContentImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.cms.structure.domain.StructuredContentImpl") } ) @Column(name = "SC_ID") protected Long id; @Embedded @AdminPresentation(excluded = true) protected AdminAuditable auditable = new AdminAuditable(); @AdminPresentation(friendlyName = "StructuredContentImpl_Content_Name", order = 1, group = Presentation.Group.Name.Description, groupOrder = Presentation.Group.Order.Description, prominent = true, gridOrder = 1) @Column(name = "CONTENT_NAME", nullable = false) @Index(name="CONTENT_NAME_INDEX", columnNames={"CONTENT_NAME", "ARCHIVED_FLAG", "SC_TYPE_ID"}) protected String contentName; @ManyToOne(targetEntity = LocaleImpl.class, optional = false) @JoinColumn(name = "LOCALE_CODE") @AdminPresentation(friendlyName = "StructuredContentImpl_Locale", order = 2, group = Presentation.Group.Name.Description, groupOrder = Presentation.Group.Order.Description, prominent = true, gridOrder = 2) @AdminPresentationToOneLookup(lookupDisplayProperty = "friendlyName", lookupType = LookupType.DROPDOWN) protected Locale locale; @Column(name = "PRIORITY", nullable = false) @AdminPresentation(friendlyName = "StructuredContentImpl_Priority", order = 3, group = Presentation.Group.Name.Description, groupOrder = Presentation.Group.Order.Description) @Index(name="CONTENT_PRIORITY_INDEX", columnNames={"PRIORITY"}) protected Integer priority; @ManyToMany(targetEntity = StructuredContentRuleImpl.class, cascade = {CascadeType.ALL}) @JoinTable(name = "BLC_SC_RULE_MAP", inverseJoinColumns = @JoinColumn(name = "SC_RULE_ID", referencedColumnName = "SC_RULE_ID")) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @MapKeyColumn(name = "MAP_KEY", nullable = false) @AdminPresentationMapFields( mapDisplayFields = { @AdminPresentationMapField( fieldName = RuleIdentifier.CUSTOMER_FIELD_KEY, fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE, order = 1, tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules, group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules, ruleIdentifier = RuleIdentifier.CUSTOMER, friendlyName = "Generic_Customer_Rule") ), @AdminPresentationMapField( fieldName = RuleIdentifier.TIME_FIELD_KEY, fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE, order = 2, tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules, group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules, ruleIdentifier = RuleIdentifier.TIME, friendlyName = "Generic_Time_Rule") ), @AdminPresentationMapField( fieldName = RuleIdentifier.REQUEST_FIELD_KEY, fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE, order = 3, tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules, group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules, ruleIdentifier = RuleIdentifier.REQUEST, friendlyName = "Generic_Request_Rule") ), @AdminPresentationMapField( fieldName = RuleIdentifier.PRODUCT_FIELD_KEY, fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE, order = 4, tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules, group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules, ruleIdentifier = RuleIdentifier.PRODUCT, friendlyName = "Generic_Product_Rule") ), @AdminPresentationMapField( fieldName = RuleIdentifier.ORDER_FIELD_KEY, fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE, order = 5, tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules, group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules, ruleIdentifier = RuleIdentifier.ORDER, friendlyName = "Generic_Order_Rule") ), @AdminPresentationMapField( fieldName = RuleIdentifier.CATEGORY, fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE, order = 6, tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules, group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules, ruleIdentifier = RuleIdentifier.CATEGORY, friendlyName = "Generic_Category_Rule") ) } ) Map<String, StructuredContentRule> structuredContentMatchRules = new HashMap<String, StructuredContentRule>(); @OneToMany(fetch = FetchType.LAZY, targetEntity = StructuredContentItemCriteriaImpl.class, cascade={CascadeType.ALL}) @JoinTable(name = "BLC_QUAL_CRIT_SC_XREF", joinColumns = @JoinColumn(name = "SC_ID"), inverseJoinColumns = @JoinColumn(name = "SC_ITEM_CRITERIA_ID")) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @AdminPresentation(friendlyName = "Generic_Item_Rule", order = 5, tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules, group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules, fieldType = SupportedFieldType.RULE_WITH_QUANTITY, ruleIdentifier = RuleIdentifier.ORDERITEM) protected Set<StructuredContentItemCriteria> qualifyingItemCriteria = new HashSet<StructuredContentItemCriteria>(); @Column(name = "ORIG_ITEM_ID") @Index(name="SC_ORIG_ITEM_ID_INDEX", columnNames={"ORIG_ITEM_ID"}) @AdminPresentation(friendlyName = "StructuredContentImpl_Original_Item_Id", order = 1, group = Presentation.Group.Name.Internal, groupOrder = Presentation.Group.Order.Internal, visibility = VisibilityEnum.HIDDEN_ALL) protected Long originalItemId; @ManyToOne (targetEntity = SandBoxImpl.class) @JoinColumn(name="SANDBOX_ID") @AdminPresentation(friendlyName = "StructuredContentImpl_Content_SandBox", order = 1, group = Presentation.Group.Name.Internal, groupOrder = Presentation.Group.Order.Internal, excluded = true) protected SandBox sandbox; @ManyToOne(targetEntity = SandBoxImpl.class) @JoinColumn(name = "ORIG_SANDBOX_ID") @AdminPresentation(excluded = true) protected SandBox originalSandBox; @ManyToOne(targetEntity = StructuredContentTypeImpl.class) @JoinColumn(name="SC_TYPE_ID") @AdminPresentation(friendlyName = "StructuredContentImpl_Content_Type", order = 2, prominent = true, group = Presentation.Group.Name.Description, groupOrder = Presentation.Group.Order.Description, requiredOverride = RequiredOverride.REQUIRED) @AdminPresentationToOneLookup(lookupDisplayProperty = "name", forcePopulateChildProperties = true) protected StructuredContentType structuredContentType; @ManyToMany(targetEntity = StructuredContentFieldImpl.class, cascade = CascadeType.ALL) @JoinTable(name = "BLC_SC_FLD_MAP", joinColumns = @JoinColumn(name = "SC_ID", referencedColumnName = "SC_ID"), inverseJoinColumns = @JoinColumn(name = "SC_FLD_ID", referencedColumnName = "SC_FLD_ID")) @MapKeyColumn(name = "MAP_KEY") @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @BatchSize(size = 20) protected Map<String,StructuredContentField> structuredContentFields = new HashMap<String,StructuredContentField>(); @Column(name = "DELETED_FLAG") @Index(name="SC_DLTD_FLG_INDX", columnNames={"DELETED_FLAG"}) @AdminPresentation(friendlyName = "StructuredContentImpl_Deleted", order = 2, group = Presentation.Group.Name.Internal, groupOrder = Presentation.Group.Order.Internal, visibility = VisibilityEnum.HIDDEN_ALL) protected Boolean deletedFlag = false; @Column(name = "ARCHIVED_FLAG") @Index(name="SC_ARCHVD_FLG_INDX", columnNames={"ARCHIVED_FLAG"}) @AdminPresentation(friendlyName = "StructuredContentImpl_Archived", order = 3, group = Presentation.Group.Name.Internal, groupOrder = Presentation.Group.Order.Internal, visibility = VisibilityEnum.HIDDEN_ALL) protected Boolean archivedFlag = false; @AdminPresentation(friendlyName = "StructuredContentImpl_Offline", order = 4, group = Presentation.Group.Name.Description, groupOrder = Presentation.Group.Order.Description) @Column(name = "OFFLINE_FLAG") @Index(name="SC_OFFLN_FLG_INDX", columnNames={"OFFLINE_FLAG"}) protected Boolean offlineFlag = false; @Column (name = "LOCKED_FLAG") @AdminPresentation(friendlyName = "StructuredContentImpl_Is_Locked", visibility = VisibilityEnum.HIDDEN_ALL) @Index(name="SC_LCKD_FLG_INDX", columnNames={"LOCKED_FLAG"}) protected Boolean lockedFlag = false; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getContentName() { return contentName; } @Override public void setContentName(String contentName) { this.contentName = contentName; } @Override public Locale getLocale() { return locale; } @Override public void setLocale(Locale locale) { this.locale = locale; } @Override public SandBox getSandbox() { return sandbox; } @Override public void setSandbox(SandBox sandbox) { this.sandbox = sandbox; } @Override public StructuredContentType getStructuredContentType() { return structuredContentType; } @Override public void setStructuredContentType(StructuredContentType structuredContentType) { this.structuredContentType = structuredContentType; } @Override public Map<String, StructuredContentField> getStructuredContentFields() { return structuredContentFields; } @Override public void setStructuredContentFields(Map<String, StructuredContentField> structuredContentFields) { this.structuredContentFields = structuredContentFields; } @Override public Boolean getDeletedFlag() { if (deletedFlag == null) { return Boolean.FALSE; } else { return deletedFlag; } } @Override public void setDeletedFlag(Boolean deletedFlag) { this.deletedFlag = deletedFlag; } @Override public Boolean getOfflineFlag() { if (offlineFlag == null) { return Boolean.FALSE; } else { return offlineFlag; } } @Override public void setOfflineFlag(Boolean offlineFlag) { this.offlineFlag = offlineFlag; } @Override public Integer getPriority() { return priority; } @Override public void setPriority(Integer priority) { this.priority = priority; } @Override public Long getOriginalItemId() { return originalItemId; } @Override public void setOriginalItemId(Long originalItemId) { this.originalItemId = originalItemId; } @Override public Boolean getArchivedFlag() { if (archivedFlag == null) { return Boolean.FALSE; } else { return archivedFlag; } } @Override public void setArchivedFlag(Boolean archivedFlag) { this.archivedFlag = archivedFlag; } @Override public AdminAuditable getAuditable() { return auditable; } @Override public void setAuditable(AdminAuditable auditable) { this.auditable = auditable; } @Override public Boolean getLockedFlag() { if (lockedFlag == null) { return Boolean.FALSE; } else { return lockedFlag; } } @Override public void setLockedFlag(Boolean lockedFlag) { this.lockedFlag = lockedFlag; } @Override public SandBox getOriginalSandBox() { return originalSandBox; } @Override public void setOriginalSandBox(SandBox originalSandBox) { this.originalSandBox = originalSandBox; } @Override public Map<String, StructuredContentRule> getStructuredContentMatchRules() { return structuredContentMatchRules; } @Override public void setStructuredContentMatchRules(Map<String, StructuredContentRule> structuredContentMatchRules) { this.structuredContentMatchRules = structuredContentMatchRules; } @Override public Set<StructuredContentItemCriteria> getQualifyingItemCriteria() { return qualifyingItemCriteria; } @Override public void setQualifyingItemCriteria(Set<StructuredContentItemCriteria> qualifyingItemCriteria) { this.qualifyingItemCriteria = qualifyingItemCriteria; } public String getMainEntityName() { return getContentName(); } @Override public StructuredContent cloneEntity() { StructuredContentImpl newContent = new StructuredContentImpl(); newContent.archivedFlag = archivedFlag; newContent.contentName = contentName; newContent.deletedFlag = deletedFlag; newContent.locale = locale; newContent.offlineFlag = offlineFlag; newContent.originalItemId = originalItemId; newContent.priority = priority; newContent.structuredContentType = structuredContentType; Map<String, StructuredContentRule> ruleMap = newContent.getStructuredContentMatchRules(); for (String key : structuredContentMatchRules.keySet()) { StructuredContentRule newField = structuredContentMatchRules.get(key).cloneEntity(); ruleMap.put(key, newField); } Set<StructuredContentItemCriteria> criteriaList = newContent.getQualifyingItemCriteria(); for (StructuredContentItemCriteria structuredContentItemCriteria : qualifyingItemCriteria) { StructuredContentItemCriteria newField = structuredContentItemCriteria.cloneEntity(); criteriaList.add(newField); } Map<String, StructuredContentField> fieldMap = newContent.getStructuredContentFields(); for (StructuredContentField field : structuredContentFields.values()) { StructuredContentField newField = field.cloneEntity(); fieldMap.put(newField.getFieldKey(), newField); } return newContent; } public static class Presentation { public static class Tab { public static class Name { public static final String Rules = "StructuredContentImpl_Rules_Tab"; } public static class Order { public static final int Rules = 1000; } } public static class Group { public static class Name { public static final String Description = "StructuredContentImpl_Description"; public static final String Internal = "StructuredContentImpl_Internal"; public static final String Rules = "StructuredContentImpl_Rules"; } public static class Order { public static final int Description = 1000; public static final int Internal = 2000; public static final int Rules = 1000; } } } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentImpl.java
62
public interface Fun<A,T> { T apply(A a); }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
158
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); }});
0true
src_main_java_jsr166y_ConcurrentLinkedDeque.java
135
public interface TitanGraphIndex extends TitanIndex { /** * Returns the name of the index * @return */ public String getName(); /** * Returns the name of the backing index. For composite indexes this returns a default name. * For mixed indexes, this returns the name of the configured indexing backend. * * @return */ public String getBackingIndex(); /** * Returns which element type is being indexed by this index (vertex, edge, or property) * * @return */ public Class<? extends Element> getIndexedElement(); /** * Returns the indexed keys of this index. If the returned array contains more than one element, its a * composite index. * * @return */ public PropertyKey[] getFieldKeys(); /** * Returns the parameters associated with an indexed key of this index. Parameters modify the indexing * behavior of the underlying indexing backend. * * @param key * @return */ public Parameter[] getParametersFor(PropertyKey key); /** * Whether this is a unique index, i.e. values are uniquely associated with at most one element in the graph (for * a particular type) * * @return */ public boolean isUnique(); /** * Returns the status of this index with respect to the provided {@link PropertyKey}. * For composite indexes, the key is ignored and the status of the index as a whole is returned. * For mixed indexes, the status of that particular key within the index is returned. * * @return */ public SchemaStatus getIndexStatus(PropertyKey key); /** * Whether this is a composite index * @return */ public boolean isCompositeIndex(); /** * Whether this is a mixed index * @return */ public boolean isMixedIndex(); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_schema_TitanGraphIndex.java
1,311
public class ODurablePage { protected static final int MAGIC_NUMBER_OFFSET = 0; protected static final int CRC32_OFFSET = MAGIC_NUMBER_OFFSET + OLongSerializer.LONG_SIZE; public static final int WAL_SEGMENT_OFFSET = CRC32_OFFSET + OIntegerSerializer.INT_SIZE; public static final int WAL_POSITION_OFFSET = WAL_SEGMENT_OFFSET + OLongSerializer.LONG_SIZE; public static final int MAX_PAGE_SIZE_BYTES = OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024; protected static final int NEXT_FREE_POSITION = WAL_POSITION_OFFSET + OLongSerializer.LONG_SIZE; protected OPageChanges pageChanges = new OPageChanges(); protected final ODirectMemoryPointer pagePointer; protected final TrackMode trackMode; public ODurablePage(ODirectMemoryPointer pagePointer, TrackMode trackMode) { this.pagePointer = pagePointer; this.trackMode = trackMode; } public static OLogSequenceNumber getLogSequenceNumberFromPage(ODirectMemoryPointer dataPointer) { final long segment = OLongSerializer.INSTANCE.deserializeFromDirectMemory(dataPointer, WAL_SEGMENT_OFFSET); final long position = OLongSerializer.INSTANCE.deserializeFromDirectMemory(dataPointer, WAL_POSITION_OFFSET); return new OLogSequenceNumber(segment, position); } public static enum TrackMode { NONE, FULL, ROLLBACK_ONLY } public int getIntValue(int pageOffset) { return OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(pagePointer, pageOffset); } public long getLongValue(int pageOffset) { return OLongSerializer.INSTANCE.deserializeFromDirectMemory(pagePointer, pageOffset); } public byte[] getBinaryValue(int pageOffset, int valLen) { return pagePointer.get(pageOffset, valLen); } public byte getByteValue(int pageOffset) { return pagePointer.getByte(pageOffset); } public void setIntValue(int pageOffset, int value) throws IOException { if (trackMode.equals(TrackMode.FULL)) { byte[] oldValues = pagePointer.get(pageOffset, OIntegerSerializer.INT_SIZE); OIntegerSerializer.INSTANCE.serializeInDirectMemory(value, pagePointer, pageOffset); byte[] newValues = pagePointer.get(pageOffset, OIntegerSerializer.INT_SIZE); pageChanges.addChanges(pageOffset, newValues, oldValues); } else if (trackMode.equals(TrackMode.ROLLBACK_ONLY)) { byte[] oldValues = pagePointer.get(pageOffset, OIntegerSerializer.INT_SIZE); OIntegerSerializer.INSTANCE.serializeInDirectMemory(value, pagePointer, pageOffset); pageChanges.addChanges(pageOffset, null, oldValues); } else OIntegerSerializer.INSTANCE.serializeInDirectMemory(value, pagePointer, pageOffset); } public void setByteValue(int pageOffset, byte value) { if (trackMode.equals(TrackMode.FULL)) { byte[] oldValues = new byte[] { pagePointer.getByte(pageOffset) }; pagePointer.setByte(pageOffset, value); byte[] newValues = new byte[] { pagePointer.getByte(pageOffset) }; pageChanges.addChanges(pageOffset, newValues, oldValues); } else if (trackMode.equals(TrackMode.ROLLBACK_ONLY)) { byte[] oldValues = new byte[] { pagePointer.getByte(pageOffset) }; pagePointer.setByte(pageOffset, value); pageChanges.addChanges(pageOffset, null, oldValues); } else pagePointer.setByte(pageOffset, value); } public void setLongValue(int pageOffset, long value) throws IOException { if (trackMode.equals(TrackMode.FULL)) { byte[] oldValues = pagePointer.get(pageOffset, OLongSerializer.LONG_SIZE); OLongSerializer.INSTANCE.serializeInDirectMemory(value, pagePointer, pageOffset); byte[] newValues = pagePointer.get(pageOffset, OLongSerializer.LONG_SIZE); pageChanges.addChanges(pageOffset, newValues, oldValues); } else if (trackMode.equals(TrackMode.ROLLBACK_ONLY)) { byte[] oldValues = pagePointer.get(pageOffset, OLongSerializer.LONG_SIZE); OLongSerializer.INSTANCE.serializeInDirectMemory(value, pagePointer, pageOffset); pageChanges.addChanges(pageOffset, null, oldValues); } else OLongSerializer.INSTANCE.serializeInDirectMemory(value, pagePointer, pageOffset); } public void setBinaryValue(int pageOffset, byte[] value) throws IOException { if (value.length == 0) return; if (trackMode.equals(TrackMode.FULL)) { byte[] oldValues = pagePointer.get(pageOffset, value.length); pagePointer.set(pageOffset, value, 0, value.length); pageChanges.addChanges(pageOffset, value, oldValues); } else if (trackMode.equals(TrackMode.ROLLBACK_ONLY)) { byte[] oldValues = pagePointer.get(pageOffset, value.length); pagePointer.set(pageOffset, value, 0, value.length); pageChanges.addChanges(pageOffset, null, oldValues); } else pagePointer.set(pageOffset, value, 0, value.length); } public void moveData(int from, int to, int len) throws IOException { if (len == 0) return; if (trackMode.equals(TrackMode.FULL)) { byte[] content = pagePointer.get(from, len); byte[] oldContent = pagePointer.get(to, len); pagePointer.moveData(from, pagePointer, to, len); pageChanges.addChanges(to, content, oldContent); } else if (trackMode.equals(TrackMode.ROLLBACK_ONLY)) { byte[] oldContent = pagePointer.get(to, len); pagePointer.moveData(from, pagePointer, to, len); pageChanges.addChanges(to, null, oldContent); } else pagePointer.moveData(from, pagePointer, to, len); } public OPageChanges getPageChanges() { return pageChanges; } public void restoreChanges(OPageChanges pageChanges) { pageChanges.applyChanges(pagePointer); } public void revertChanges(OPageChanges pageChanges) { pageChanges.revertChanges(pagePointer); } public OLogSequenceNumber getLsn() { final long segment = getLongValue(WAL_SEGMENT_OFFSET); final long position = getLongValue(WAL_POSITION_OFFSET); return new OLogSequenceNumber(segment, position); } public void setLsn(OLogSequenceNumber lsn) { OLongSerializer.INSTANCE.serializeInDirectMemory(lsn.getSegment(), pagePointer, WAL_SEGMENT_OFFSET); OLongSerializer.INSTANCE.serializeInDirectMemory(lsn.getPosition(), pagePointer, WAL_POSITION_OFFSET); } }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_ODurablePage.java
1,218
public class CeylonNature extends ProjectNatureBase { public static final String NATURE_ID = PLUGIN_ID + ".ceylonNature"; public static boolean isEnabled(IProject project) { try { return project.hasNature(NATURE_ID); } catch (CoreException e) { e.printStackTrace(); return false; } } private String systemRepo; boolean enableJdtClasses; boolean astAwareIncrementalBuilds; boolean hideWarnings; boolean keepSettings; boolean compileJs; boolean compileJava; public CeylonNature() { keepSettings=true; } public CeylonNature(String systemRepo, boolean enableJdtClasses, boolean hideWarnings, boolean java, boolean js, boolean astAwareIncrementalBuilds) { this.systemRepo = systemRepo; this.enableJdtClasses = enableJdtClasses; this.hideWarnings = hideWarnings; compileJs = js; compileJava = java; this.astAwareIncrementalBuilds = astAwareIncrementalBuilds; } public String getNatureID() { return NATURE_ID; } public String getBuilderID() { return BUILDER_ID; } public void addToProject(final IProject project) { super.addToProject(project); try { new CeylonLanguageModuleContainer(project).install(); } catch (JavaModelException e) { e.printStackTrace(); } new CeylonProjectModulesContainer(project).runReconfigure(); } protected void refreshPrefs() { // TODO implement preferences and hook in here } /** * Run the Java builder before the Ceylon builder, since * it's more common for Ceylon to call Java than the * other way around, and because the Java builder erases * the output directory during a full build. */ protected String getUpstreamBuilderID() { return JavaCore.BUILDER_ID; } @Override protected Map<String, String> getBuilderArguments() { Map<String, String> args = super.getBuilderArguments(); if (!keepSettings) { if (!"${ceylon.repo}".equals(systemRepo)) { args.put("systemRepo", systemRepo); } else { args.remove("systemRepo"); } if (hideWarnings) { args.put("hideWarnings", "true"); } else { args.remove("hideWarnings"); } if (enableJdtClasses) { args.put("explodeModules", "true"); } else { args.remove("explodeModules"); } if (astAwareIncrementalBuilds) { args.remove("astAwareIncrementalBuilds"); } else { args.put("astAwareIncrementalBuilds", "false"); } if (compileJava) { args.remove("compileJava"); } else { args.put("compileJava", "false"); } if (compileJs) { args.put("compileJs", "true"); } else { args.remove("compileJs"); } } return args; } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_builder_CeylonNature.java
521
public class BLCCollectionUtils { /** * Delegates to {@link CollectionUtils#collect(Collection, Transformer)}, but performs the necessary type coercion * to allow the returned collection to be correctly casted based on the TypedTransformer. * * @param inputCollection * @param transformer * @return the typed, collected Collection */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Collection<T> collect(Collection inputCollection, TypedTransformer<T> transformer) { return CollectionUtils.collect(inputCollection, transformer); } /** * Delegates to {@link CollectionUtils#select(Collection, org.apache.commons.collections.Predicate)}, but will * force the return type to be a List<T>. * * @param inputCollection * @param predicate * @return */ public static <T> List<T> selectList(Collection<T> inputCollection, TypedPredicate<T> predicate) { ArrayList<T> answer = new ArrayList<T>(inputCollection.size()); CollectionUtils.select(inputCollection, predicate, answer); return answer; } }
0true
common_src_main_java_org_broadleafcommerce_common_util_BLCCollectionUtils.java
1,881
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() { public Boolean execute(TransactionalTaskContext context) throws TransactionException { final TransactionalMap<Object, Object> txMap1 = context.getMap(map1); final TransactionalMap<Object, Object> txMap2 = context.getMap(map2); txMap1.put(key, "value"); assertEquals("value", txMap1.put(key, "value1")); assertEquals("value1", txMap1.get(key)); txMap2.put(key, "value"); assertEquals("value", txMap2.put(key, "value2")); assertEquals("value2", txMap2.get(key)); assertEquals(true, txMap1.containsKey(key)); assertEquals(true, txMap2.containsKey(key)); assertNull(h2.getMap(map1).get(key)); assertNull(h2.getMap(map2).get(key)); return true; } });
0true
hazelcast_src_test_java_com_hazelcast_map_MapTransactionTest.java
1,540
public class XAResourceWrapper implements XAResource { private final ManagedConnectionImpl managedConnection; private int transactionTimeoutSeconds; private XAResource inner; public XAResourceWrapper(ManagedConnectionImpl managedConnectionImpl) { this.managedConnection = managedConnectionImpl; } //XAResource --START @Override public void start(Xid xid, int flags) throws XAException { managedConnection.log(Level.FINEST, "XA start: " + xid); switch (flags) { case TMNOFLAGS: setInner(); break; case TMRESUME: case TMJOIN: break; default: throw new XAException(XAException.XAER_INVAL); } if (inner != null) { inner.start(xid, flags); } } @Override public void end(Xid xid, int flags) throws XAException { managedConnection.log(Level.FINEST, "XA end: " + xid + ", " + flags); validateInner(); inner.end(xid, flags); } @Override public int prepare(Xid xid) throws XAException { managedConnection.log(Level.FINEST, "XA prepare: " + xid); validateInner(); return inner.prepare(xid); } @Override public void commit(Xid xid, boolean onePhase) throws XAException { managedConnection.log(Level.FINEST, "XA commit: " + xid); validateInner(); inner.commit(xid, onePhase); } @Override public void rollback(Xid xid) throws XAException { managedConnection.log(Level.FINEST, "XA rollback: " + xid); validateInner(); inner.rollback(xid); } @Override public void forget(Xid xid) throws XAException { throw new XAException(XAException.XAER_PROTO); } @Override public boolean isSameRM(XAResource xaResource) throws XAException { if (xaResource instanceof XAResourceWrapper) { final ManagedConnectionImpl otherManagedConnection = ((XAResourceWrapper) xaResource).managedConnection; final HazelcastInstance hazelcastInstance = managedConnection.getHazelcastInstance(); final HazelcastInstance otherHazelcastInstance = otherManagedConnection.getHazelcastInstance(); return hazelcastInstance != null && hazelcastInstance.equals(otherHazelcastInstance); } return false; } @Override public Xid[] recover(int flag) throws XAException { if (inner == null) { setInner(); } return inner.recover(flag); } @Override public int getTransactionTimeout() throws XAException { return transactionTimeoutSeconds; } @Override public boolean setTransactionTimeout(int seconds) throws XAException { this.transactionTimeoutSeconds = seconds; return false; } private void validateInner() throws XAException { if (inner == null) { throw new XAException(XAException.XAER_NOTA); } } private void setInner() throws XAException { final TransactionContext transactionContext = HazelcastTransactionImpl .createTransaction(this.getTransactionTimeout(), managedConnection.getHazelcastInstance()); this.managedConnection.getTx().setTxContext(transactionContext); inner = transactionContext.getXaResource(); } }
1no label
hazelcast-ra_hazelcast-jca_src_main_java_com_hazelcast_jca_XAResourceWrapper.java
252
public enum STRATEGY { POP_RECORD, COPY_RECORD }
0true
core_src_main_java_com_orientechnologies_orient_core_cache_OLevel2RecordCache.java
1,432
public class MetaDataTests extends ElasticsearchTestCase { @Test public void testIndexOptions_strict() { MetaData.Builder mdBuilder = MetaData.builder() .put(indexBuilder("foo")) .put(indexBuilder("foobar")) .put(indexBuilder("foofoo").putAlias(AliasMetaData.builder("barbaz"))); MetaData md = mdBuilder.build(); IndicesOptions options = IndicesOptions.strict(); String[] results = md.concreteIndices(Strings.EMPTY_ARRAY, options); assertEquals(3, results.length); results = md.concreteIndices(new String[]{"foo"}, options); assertEquals(1, results.length); assertEquals("foo", results[0]); try { md.concreteIndices(new String[]{"bar"}, options); fail(); } catch (IndexMissingException e) {} results = md.concreteIndices(new String[]{"foofoo", "foobar"}, options); assertEquals(2, results.length); assertThat(results, arrayContainingInAnyOrder("foofoo", "foobar")); try { md.concreteIndices(new String[]{"foo", "bar"}, options); fail(); } catch (IndexMissingException e) {} results = md.concreteIndices(new String[]{"barbaz", "foobar"}, options); assertEquals(2, results.length); assertThat(results, arrayContainingInAnyOrder("foofoo", "foobar")); try { md.concreteIndices(new String[]{"barbaz", "bar"}, options); fail(); } catch (IndexMissingException e) {} results = md.concreteIndices(new String[]{"baz*"}, options); assertThat(results, emptyArray()); results = md.concreteIndices(new String[]{"foo", "baz*"}, options); assertEquals(1, results.length); assertEquals("foo", results[0]); } @Test public void testIndexOptions_lenient() { MetaData.Builder mdBuilder = MetaData.builder() .put(indexBuilder("foo")) .put(indexBuilder("foobar")) .put(indexBuilder("foofoo").putAlias(AliasMetaData.builder("barbaz"))); MetaData md = mdBuilder.build(); IndicesOptions options = IndicesOptions.lenient(); String[] results = md.concreteIndices(Strings.EMPTY_ARRAY, options); assertEquals(3, results.length); results = md.concreteIndices(new String[]{"foo"}, options); assertEquals(1, results.length); assertEquals("foo", results[0]); results = md.concreteIndices(new String[]{"bar"}, options); assertThat(results, emptyArray()); results = md.concreteIndices(new String[]{"foofoo", "foobar"}, options); assertEquals(2, results.length); assertThat(results, arrayContainingInAnyOrder("foofoo", "foobar")); results = md.concreteIndices(new String[]{"foo", "bar"}, options); assertEquals(1, results.length); assertThat(results, arrayContainingInAnyOrder("foo")); results = md.concreteIndices(new String[]{"barbaz", "foobar"}, options); assertEquals(2, results.length); assertThat(results, arrayContainingInAnyOrder("foofoo", "foobar")); results = md.concreteIndices(new String[]{"barbaz", "bar"}, options); assertEquals(1, results.length); assertThat(results, arrayContainingInAnyOrder("foofoo")); results = md.concreteIndices(new String[]{"baz*"}, options); assertThat(results, emptyArray()); results = md.concreteIndices(new String[]{"foo", "baz*"}, options); assertEquals(1, results.length); assertEquals("foo", results[0]); } @Test public void testIndexOptions_allowUnavailableExpandOpenDisAllowEmpty() { MetaData.Builder mdBuilder = MetaData.builder() .put(indexBuilder("foo")) .put(indexBuilder("foobar")) .put(indexBuilder("foofoo").putAlias(AliasMetaData.builder("barbaz"))); MetaData md = mdBuilder.build(); IndicesOptions options = IndicesOptions.fromOptions(true, false, true, false); String[] results = md.concreteIndices(Strings.EMPTY_ARRAY, options); assertEquals(3, results.length); results = md.concreteIndices(new String[]{"foo"}, options); assertEquals(1, results.length); assertEquals("foo", results[0]); results = md.concreteIndices(new String[]{"bar"}, options); assertThat(results, emptyArray()); try { md.concreteIndices(new String[]{"baz*"}, options); fail(); } catch (IndexMissingException e) {} try { md.concreteIndices(new String[]{"foo", "baz*"}, options); fail(); } catch (IndexMissingException e) {} } @Test public void testIndexOptions_wildcardExpansion() { MetaData.Builder mdBuilder = MetaData.builder() .put(indexBuilder("foo").state(IndexMetaData.State.CLOSE)) .put(indexBuilder("bar")) .put(indexBuilder("foobar").putAlias(AliasMetaData.builder("barbaz"))); MetaData md = mdBuilder.build(); // Only closed IndicesOptions options = IndicesOptions.fromOptions(false, true, false, true); String[] results = md.concreteIndices(Strings.EMPTY_ARRAY, options); assertEquals(1, results.length); assertEquals("foo", results[0]); results = md.concreteIndices(new String[]{"foo*"}, options); assertEquals(1, results.length); assertEquals("foo", results[0]); // no wildcards, so wildcard expansion don't apply results = md.concreteIndices(new String[]{"bar"}, options); assertEquals(1, results.length); assertEquals("bar", results[0]); // Only open options = IndicesOptions.fromOptions(false, true, true, false); results = md.concreteIndices(Strings.EMPTY_ARRAY, options); assertEquals(2, results.length); assertThat(results, arrayContainingInAnyOrder("bar", "foobar")); results = md.concreteIndices(new String[]{"foo*"}, options); assertEquals(1, results.length); assertEquals("foobar", results[0]); results = md.concreteIndices(new String[]{"bar"}, options); assertEquals(1, results.length); assertEquals("bar", results[0]); // Open and closed options = IndicesOptions.fromOptions(false, true, true, true); results = md.concreteIndices(Strings.EMPTY_ARRAY, options); assertEquals(3, results.length); assertThat(results, arrayContainingInAnyOrder("bar", "foobar", "foo")); results = md.concreteIndices(new String[]{"foo*"}, options); assertEquals(2, results.length); assertThat(results, arrayContainingInAnyOrder("foobar", "foo")); results = md.concreteIndices(new String[]{"bar"}, options); assertEquals(1, results.length); assertEquals("bar", results[0]); results = md.concreteIndices(new String[]{"-foo*"}, options); assertEquals(1, results.length); assertEquals("bar", results[0]); results = md.concreteIndices(new String[]{"-*"}, options); assertEquals(0, results.length); options = IndicesOptions.fromOptions(false, false, true, true); try { md.concreteIndices(new String[]{"-*"}, options); fail(); } catch (IndexMissingException e) {} } @Test public void testIndexOptions_emptyCluster() { MetaData md = MetaData.builder().build(); IndicesOptions options = IndicesOptions.strict(); String[] results = md.concreteIndices(Strings.EMPTY_ARRAY, options); assertThat(results, emptyArray()); try { md.concreteIndices(new String[]{"foo"}, options); fail(); } catch (IndexMissingException e) {} results = md.concreteIndices(new String[]{"foo*"}, options); assertThat(results, emptyArray()); try { md.concreteIndices(new String[]{"foo*", "bar"}, options); fail(); } catch (IndexMissingException e) {} options = IndicesOptions.lenient(); results = md.concreteIndices(Strings.EMPTY_ARRAY, options); assertThat(results, emptyArray()); results = md.concreteIndices(new String[]{"foo"}, options); assertThat(results, emptyArray()); results = md.concreteIndices(new String[]{"foo*"}, options); assertThat(results, emptyArray()); results = md.concreteIndices(new String[]{"foo*", "bar"}, options); assertThat(results, emptyArray()); options = IndicesOptions.fromOptions(true, false, true, false); try { md.concreteIndices(Strings.EMPTY_ARRAY, options); } catch (IndexMissingException e) {} } @Test public void convertWildcardsJustIndicesTests() { MetaData.Builder mdBuilder = MetaData.builder() .put(indexBuilder("testXXX")) .put(indexBuilder("testXYY")) .put(indexBuilder("testYYY")) .put(indexBuilder("kuku")); MetaData md = mdBuilder.build(); assertThat(newHashSet(md.convertFromWildcards(new String[]{"testXXX"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX"))); assertThat(newHashSet(md.convertFromWildcards(new String[]{"testXXX", "testYYY"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testYYY"))); assertThat(newHashSet(md.convertFromWildcards(new String[]{"testXXX", "ku*"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "kuku"))); assertThat(newHashSet(md.convertFromWildcards(new String[]{"test*"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY", "testYYY"))); assertThat(newHashSet(md.convertFromWildcards(new String[]{"testX*"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY"))); assertThat(newHashSet(md.convertFromWildcards(new String[]{"testX*", "kuku"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY", "kuku"))); } @Test public void convertWildcardsTests() { MetaData.Builder mdBuilder = MetaData.builder() .put(indexBuilder("testXXX").putAlias(AliasMetaData.builder("alias1")).putAlias(AliasMetaData.builder("alias2"))) .put(indexBuilder("testXYY").putAlias(AliasMetaData.builder("alias2"))) .put(indexBuilder("testYYY").putAlias(AliasMetaData.builder("alias3"))) .put(indexBuilder("kuku")); MetaData md = mdBuilder.build(); assertThat(newHashSet(md.convertFromWildcards(new String[]{"testYY*", "alias*"}, IndicesOptions.lenient())), equalTo(newHashSet("alias1", "alias2", "alias3", "testYYY"))); assertThat(newHashSet(md.convertFromWildcards(new String[]{"-kuku"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY", "testYYY"))); assertThat(newHashSet(md.convertFromWildcards(new String[]{"+test*", "-testYYY"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY"))); assertThat(newHashSet(md.convertFromWildcards(new String[]{"+testX*", "+testYYY"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY", "testYYY"))); assertThat(newHashSet(md.convertFromWildcards(new String[]{"+testYYY", "+testX*"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY", "testYYY"))); } private IndexMetaData.Builder indexBuilder(String index) { return IndexMetaData.builder(index).settings(ImmutableSettings.settingsBuilder().put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)); } @Test(expected = IndexMissingException.class) public void concreteIndicesIgnoreIndicesOneMissingIndex() { MetaData.Builder mdBuilder = MetaData.builder() .put(indexBuilder("testXXX")) .put(indexBuilder("kuku")); MetaData md = mdBuilder.build(); md.concreteIndices(new String[]{"testZZZ"}, IndicesOptions.strict()); } @Test public void concreteIndicesIgnoreIndicesOneMissingIndexOtherFound() { MetaData.Builder mdBuilder = MetaData.builder() .put(indexBuilder("testXXX")) .put(indexBuilder("kuku")); MetaData md = mdBuilder.build(); assertThat(newHashSet(md.concreteIndices(new String[]{"testXXX", "testZZZ"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX"))); } @Test(expected = IndexMissingException.class) public void concreteIndicesIgnoreIndicesAllMissing() { MetaData.Builder mdBuilder = MetaData.builder() .put(indexBuilder("testXXX")) .put(indexBuilder("kuku")); MetaData md = mdBuilder.build(); assertThat(newHashSet(md.concreteIndices(new String[]{"testMo", "testMahdy"}, IndicesOptions.strict())), equalTo(newHashSet("testXXX"))); } @Test public void concreteIndicesIgnoreIndicesEmptyRequest() { MetaData.Builder mdBuilder = MetaData.builder() .put(indexBuilder("testXXX")) .put(indexBuilder("kuku")); MetaData md = mdBuilder.build(); assertThat(newHashSet(md.concreteIndices(new String[]{}, IndicesOptions.lenient())), equalTo(Sets.<String>newHashSet("kuku", "testXXX"))); } @Test public void testIsAllIndices_null() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isAllIndices(null), equalTo(true)); } @Test public void testIsAllIndices_empty() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isAllIndices(new String[0]), equalTo(true)); } @Test public void testIsAllIndices_explicitAll() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isAllIndices(new String[]{"_all"}), equalTo(true)); } @Test public void testIsAllIndices_explicitAllPlusOther() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isAllIndices(new String[]{"_all", "other"}), equalTo(false)); } @Test public void testIsAllIndices_normalIndexes() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isAllIndices(new String[]{"index1", "index2", "index3"}), equalTo(false)); } @Test public void testIsAllIndices_wildcard() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isAllIndices(new String[]{"*"}), equalTo(false)); } @Test public void testIsExplicitAllIndices_null() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isExplicitAllPattern(null), equalTo(false)); } @Test public void testIsExplicitAllIndices_empty() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isExplicitAllPattern(new String[0]), equalTo(false)); } @Test public void testIsExplicitAllIndices_explicitAll() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isExplicitAllPattern(new String[]{"_all"}), equalTo(true)); } @Test public void testIsExplicitAllIndices_explicitAllPlusOther() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isExplicitAllPattern(new String[]{"_all", "other"}), equalTo(false)); } @Test public void testIsExplicitAllIndices_normalIndexes() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isExplicitAllPattern(new String[]{"index1", "index2", "index3"}), equalTo(false)); } @Test public void testIsExplicitAllIndices_wildcard() throws Exception { MetaData metaData = MetaData.builder().build(); assertThat(metaData.isExplicitAllPattern(new String[]{"*"}), equalTo(false)); } @Test public void testIsPatternMatchingAllIndices_explicitList() throws Exception { //even though it does identify all indices, it's not a pattern but just an explicit list of them String[] concreteIndices = new String[]{"index1", "index2", "index3"}; String[] indicesOrAliases = concreteIndices; String[] allConcreteIndices = concreteIndices; MetaData metaData = metaDataBuilder(allConcreteIndices); assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(false)); } @Test public void testIsPatternMatchingAllIndices_onlyWildcard() throws Exception { String[] indicesOrAliases = new String[]{"*"}; String[] concreteIndices = new String[]{"index1", "index2", "index3"}; String[] allConcreteIndices = concreteIndices; MetaData metaData = metaDataBuilder(allConcreteIndices); assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(true)); } @Test public void testIsPatternMatchingAllIndices_matchingTrailingWildcard() throws Exception { String[] indicesOrAliases = new String[]{"index*"}; String[] concreteIndices = new String[]{"index1", "index2", "index3"}; String[] allConcreteIndices = concreteIndices; MetaData metaData = metaDataBuilder(allConcreteIndices); assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(true)); } @Test public void testIsPatternMatchingAllIndices_nonMatchingTrailingWildcard() throws Exception { String[] indicesOrAliases = new String[]{"index*"}; String[] concreteIndices = new String[]{"index1", "index2", "index3"}; String[] allConcreteIndices = new String[]{"index1", "index2", "index3", "a", "b"}; MetaData metaData = metaDataBuilder(allConcreteIndices); assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(false)); } @Test public void testIsPatternMatchingAllIndices_matchingSingleExclusion() throws Exception { String[] indicesOrAliases = new String[]{"-index1", "+index1"}; String[] concreteIndices = new String[]{"index1", "index2", "index3"}; String[] allConcreteIndices = concreteIndices; MetaData metaData = metaDataBuilder(allConcreteIndices); assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(true)); } @Test public void testIsPatternMatchingAllIndices_nonMatchingSingleExclusion() throws Exception { String[] indicesOrAliases = new String[]{"-index1"}; String[] concreteIndices = new String[]{"index2", "index3"}; String[] allConcreteIndices = new String[]{"index1", "index2", "index3"}; MetaData metaData = metaDataBuilder(allConcreteIndices); assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(false)); } @Test public void testIsPatternMatchingAllIndices_matchingTrailingWildcardAndExclusion() throws Exception { String[] indicesOrAliases = new String[]{"index*", "-index1", "+index1"}; String[] concreteIndices = new String[]{"index1", "index2", "index3"}; String[] allConcreteIndices = concreteIndices; MetaData metaData = metaDataBuilder(allConcreteIndices); assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(true)); } @Test public void testIsPatternMatchingAllIndices_nonMatchingTrailingWildcardAndExclusion() throws Exception { String[] indicesOrAliases = new String[]{"index*", "-index1"}; String[] concreteIndices = new String[]{"index2", "index3"}; String[] allConcreteIndices = new String[]{"index1", "index2", "index3"}; MetaData metaData = metaDataBuilder(allConcreteIndices); assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(false)); } private MetaData metaDataBuilder(String... indices) { MetaData.Builder mdBuilder = MetaData.builder(); for (String concreteIndex : indices) { mdBuilder.put(indexBuilder(concreteIndex)); } return mdBuilder.build(); } }
0true
src_test_java_org_elasticsearch_cluster_metadata_MetaDataTests.java
590
public interface ServiceStatusDetectable<T extends Serializable> { public ServiceStatusType getServiceStatus(); public String getServiceName(); public Object process(T arg) throws Exception; }
0true
common_src_main_java_org_broadleafcommerce_common_vendor_service_monitor_ServiceStatusDetectable.java
1,837
Thread t = new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) { map.lock(i); latch.countDown(); } } });
0true
hazelcast_src_test_java_com_hazelcast_map_MapLockTest.java
1,608
public enum SortDirection { ASCENDING, DESCENDING }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_SortDirection.java
938
public class OfferType implements Serializable, BroadleafEnumerationType, Comparable<OfferType> { private static final long serialVersionUID = 1L; private static final Map<String, OfferType> TYPES = new LinkedHashMap<String, OfferType>(); public static final OfferType ORDER_ITEM = new OfferType("ORDER_ITEM", "Order Item", 1000); public static final OfferType ORDER = new OfferType("ORDER", "Order", 2000); public static final OfferType FULFILLMENT_GROUP = new OfferType("FULFILLMENT_GROUP", "Fulfillment Group", 3000); public static OfferType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; private int order; public OfferType() { //do nothing } public OfferType(final String type, final String friendlyType, int order) { this.friendlyType = friendlyType; setType(type); setOrder(order); } public void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OfferType other = (OfferType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } @Override public int compareTo(OfferType arg0) { return this.order - arg0.order; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_type_OfferType.java
173
public interface Entry extends StaticBuffer, MetaAnnotated { public int getValuePosition(); public boolean hasValue(); public StaticBuffer getColumn(); public<T> T getColumnAs(Factory<T> factory); public StaticBuffer getValue(); public<T> T getValueAs(Factory<T> factory); /** * Returns the cached parsed representation of this Entry if it exists, else NULL * * @return */ public RelationCache getCache(); /** * Sets the cached parsed representation of this Entry. This method does not synchronize, * so a previously set representation would simply be overwritten. * * @param cache */ public void setCache(RelationCache cache); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Entry.java
1,324
@Test public class DirtyPagesRecordTest { public void testSerialization() { Set<ODirtyPage> dirtyPages = new HashSet<ODirtyPage>(); Random rnd = new Random(); for (int i = 0; i < 10; i++) { long pagIndex = rnd.nextLong(); long position = rnd.nextLong(); if (position < 0) position = -position; int segment = rnd.nextInt(); if (segment < 0) segment = -segment; dirtyPages.add(new ODirtyPage("test", pagIndex, new OLogSequenceNumber(segment, position))); } ODirtyPagesRecord originalDirtyPagesRecord = new ODirtyPagesRecord(dirtyPages); byte[] content = new byte[originalDirtyPagesRecord.serializedSize() + 1]; Assert.assertEquals(originalDirtyPagesRecord.toStream(content, 1), content.length); ODirtyPagesRecord storedDirtyPagesRecord = new ODirtyPagesRecord(); Assert.assertEquals(storedDirtyPagesRecord.fromStream(content, 1), content.length); Assert.assertEquals(storedDirtyPagesRecord, originalDirtyPagesRecord); } }
0true
core_src_test_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_DirtyPagesRecordTest.java
1,529
public interface HazelcastConnection extends Connection { /** * @see HazelcastInstance#getQueue(String) */ <E> IQueue<E> getQueue(String name); /** * @see HazelcastInstance#getTopic(String) */ <E> ITopic<E> getTopic(String name); /** * @see HazelcastInstance#getSet(String) */ <E> ISet<E> getSet(String name); /** * @see HazelcastInstance#getList(String) */ <E> IList<E> getList(String name); /** * @see HazelcastInstance#getMap(String) */ <K, V> IMap<K, V> getMap(String name); /** * @see HazelcastInstance#getMultiMap(String) */ <K, V> MultiMap<K, V> getMultiMap(String name); /** * @see HazelcastInstance#getExecutorService(String) */ ExecutorService getExecutorService(String name); /** * @see HazelcastInstance#getAtomicLong(String) */ IAtomicLong getAtomicLong(String name); /** * @see HazelcastInstance#getCountDownLatch(String) */ ICountDownLatch getCountDownLatch(String name); /** * @see HazelcastInstance#getSemaphore(String) */ ISemaphore getSemaphore(String name); //Transactionals /** * @see TransactionalTaskContext#getMap(String) */ <K, V> TransactionalMap<K, V> getTransactionalMap(String name); /** * @see TransactionalTaskContext#getQueue(String) */ <E> TransactionalQueue<E> getTransactionalQueue(String name); /** * @see TransactionalTaskContext#getMultiMap(String) */ <K, V> TransactionalMultiMap<K, V> getTransactionalMultiMap(String name); /** * @see TransactionalTaskContext#getList(String) */ <E> TransactionalList<E> getTransactionalList(String name); /** * @see TransactionalTaskContext#getSet(String) */ <E> TransactionalSet<E> getTransactionalSet(String name); }
0true
hazelcast-ra_hazelcast-jca_src_main_java_com_hazelcast_jca_HazelcastConnection.java
684
constructors[COLLECTION_SIZE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new CollectionSizeOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
396
public class CurrencyConsiderationContext { private static final ThreadLocal<CurrencyDeterminationService> currencyDeterminationService = ThreadLocalManager.createThreadLocal(CurrencyDeterminationService.class); private static final ThreadLocal<HashMap> currencyConsiderationContext = ThreadLocalManager.createThreadLocal(HashMap.class); public static HashMap getCurrencyConsiderationContext() { return CurrencyConsiderationContext.currencyConsiderationContext.get(); } public static void setCurrencyConsiderationContext(HashMap currencyConsiderationContext) { CurrencyConsiderationContext.currencyConsiderationContext.set(currencyConsiderationContext); } public static CurrencyDeterminationService getCurrencyDeterminationService() { return CurrencyConsiderationContext.currencyDeterminationService.get(); } public static void setCurrencyDeterminationService(CurrencyDeterminationService currencyDeterminationService) { CurrencyConsiderationContext.currencyDeterminationService.set(currencyDeterminationService); } }
0true
common_src_main_java_org_broadleafcommerce_common_money_CurrencyConsiderationContext.java
664
constructors[COLLECTION_EVENT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new CollectionEvent(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
128
public abstract class AbstractConverterTest { protected OBinaryConverter converter; public void testPutIntBigEndian() { int value = 0xFE23A067; byte[] result = new byte[4]; converter.putInt(result, 0, value, ByteOrder.BIG_ENDIAN); Assert.assertEquals(result, new byte[] { (byte) 0xFE, 0x23, (byte) 0xA0, 0x67 }); Assert.assertEquals(converter.getInt(result, 0, ByteOrder.BIG_ENDIAN), value); } public void testPutIntLittleEndian() { int value = 0xFE23A067; byte[] result = new byte[4]; converter.putInt(result, 0, value, ByteOrder.LITTLE_ENDIAN); Assert.assertEquals(result, new byte[] { 0x67, (byte) 0xA0, 0x23, (byte) 0xFE }); Assert.assertEquals(converter.getInt(result, 0, ByteOrder.LITTLE_ENDIAN), value); } public void testPutLongBigEndian() { long value = 0xFE23A067ED890C14L; byte[] result = new byte[8]; converter.putLong(result, 0, value, ByteOrder.BIG_ENDIAN); Assert.assertEquals(result, new byte[] { (byte) 0xFE, 0x23, (byte) 0xA0, 0x67, (byte) 0xED, (byte) 0x89, 0x0C, 0x14 }); Assert.assertEquals(converter.getLong(result, 0, ByteOrder.BIG_ENDIAN), value); } public void testPutLongLittleEndian() { long value = 0xFE23A067ED890C14L; byte[] result = new byte[8]; converter.putLong(result, 0, value, ByteOrder.LITTLE_ENDIAN); Assert.assertEquals(result, new byte[] { 0x14, 0x0C, (byte) 0x89, (byte) 0xED, 0x67, (byte) 0xA0, 0x23, (byte) 0xFE }); Assert.assertEquals(converter.getLong(result, 0, ByteOrder.LITTLE_ENDIAN), value); } public void testPutShortBigEndian() { short value = (short) 0xA028; byte[] result = new byte[2]; converter.putShort(result, 0, value, ByteOrder.BIG_ENDIAN); Assert.assertEquals(result, new byte[] { (byte) 0xA0, 0x28 }); Assert.assertEquals(converter.getShort(result, 0, ByteOrder.BIG_ENDIAN), value); } public void testPutShortLittleEndian() { short value = (short) 0xA028; byte[] result = new byte[2]; converter.putShort(result, 0, value, ByteOrder.LITTLE_ENDIAN); Assert.assertEquals(result, new byte[] { 0x28, (byte) 0xA0 }); Assert.assertEquals(converter.getShort(result, 0, ByteOrder.LITTLE_ENDIAN), value); } public void testPutCharBigEndian() { char value = (char) 0xA028; byte[] result = new byte[2]; converter.putChar(result, 0, value, ByteOrder.BIG_ENDIAN); Assert.assertEquals(result, new byte[] { (byte) 0xA0, 0x28 }); Assert.assertEquals(converter.getChar(result, 0, ByteOrder.BIG_ENDIAN), value); } public void testPutCharLittleEndian() { char value = (char) 0xA028; byte[] result = new byte[2]; converter.putChar(result, 0, value, ByteOrder.LITTLE_ENDIAN); Assert.assertEquals(result, new byte[] { 0x28, (byte) 0xA0 }); Assert.assertEquals(converter.getChar(result, 0, ByteOrder.LITTLE_ENDIAN), value); } }
0true
commons_src_test_java_com_orientechnologies_common_serialization_AbstractConverterTest.java
651
constructors[LIST_SET] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ListSetOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
4,922
public class RestMultiGetAction extends BaseRestHandler { private final boolean allowExplicitIndex; @Inject public RestMultiGetAction(Settings settings, Client client, RestController controller) { super(settings, client); controller.registerHandler(GET, "/_mget", this); controller.registerHandler(POST, "/_mget", this); controller.registerHandler(GET, "/{index}/_mget", this); controller.registerHandler(POST, "/{index}/_mget", this); controller.registerHandler(GET, "/{index}/{type}/_mget", this); controller.registerHandler(POST, "/{index}/{type}/_mget", this); this.allowExplicitIndex = settings.getAsBoolean("rest.action.multi.allow_explicit_index", true); } @Override public void handleRequest(final RestRequest request, final RestChannel channel) { MultiGetRequest multiGetRequest = new MultiGetRequest(); multiGetRequest.listenerThreaded(false); multiGetRequest.refresh(request.paramAsBoolean("refresh", multiGetRequest.refresh())); multiGetRequest.preference(request.param("preference")); multiGetRequest.realtime(request.paramAsBoolean("realtime", null)); String[] sFields = null; String sField = request.param("fields"); if (sField != null) { sFields = Strings.splitStringByCommaToArray(sField); } FetchSourceContext defaultFetchSource = FetchSourceContext.parseFromRestRequest(request); try { multiGetRequest.add(request.param("index"), request.param("type"), sFields, defaultFetchSource, request.param("routing"), RestActions.getRestContent(request), allowExplicitIndex); } catch (Exception e) { try { XContentBuilder builder = restContentBuilder(request); channel.sendResponse(new XContentRestResponse(request, BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject())); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } return; } client.multiGet(multiGetRequest, new ActionListener<MultiGetResponse>() { @Override public void onResponse(MultiGetResponse response) { try { XContentBuilder builder = restContentBuilder(request); response.toXContent(builder, request); channel.sendResponse(new XContentRestResponse(request, OK, builder)); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); } }
1no label
src_main_java_org_elasticsearch_rest_action_get_RestMultiGetAction.java
1,042
public class MultiTermVectorsRequest extends ActionRequest<MultiTermVectorsRequest> { String preference; List<TermVectorRequest> requests = new ArrayList<TermVectorRequest>(); final Set<String> ids = new HashSet<String>(); public MultiTermVectorsRequest add(TermVectorRequest termVectorRequest) { requests.add(termVectorRequest); return this; } public MultiTermVectorsRequest add(String index, @Nullable String type, String id) { requests.add(new TermVectorRequest(index, type, id)); return this; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (requests.isEmpty()) { validationException = ValidateActions.addValidationError("multi term vectors: no documents requested", validationException); } else { for (int i = 0; i < requests.size(); i++) { TermVectorRequest termVectorRequest = requests.get(i); ActionRequestValidationException validationExceptionForDoc = termVectorRequest.validate(); if (validationExceptionForDoc != null) { validationException = ValidateActions.addValidationError("at multi term vectors for doc " + i, validationExceptionForDoc); } } } return validationException; } public void add(TermVectorRequest template, BytesReference data) throws Exception { XContentParser.Token token; String currentFieldName = null; if (data.length() > 0) { XContentParser parser = XContentFactory.xContent(data).createParser(data); try { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("docs".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token != XContentParser.Token.START_OBJECT) { throw new ElasticsearchIllegalArgumentException("docs array element should include an object"); } TermVectorRequest termVectorRequest = new TermVectorRequest(template); TermVectorRequest.parseRequest(termVectorRequest, parser); add(termVectorRequest); } } else if ("ids".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (!token.isValue()) { throw new ElasticsearchIllegalArgumentException("ids array element should only contain ids"); } ids.add(parser.text()); } } else { throw new ElasticsearchParseException( "No parameter named " + currentFieldName + "and type ARRAY"); } } else if (token == XContentParser.Token.START_OBJECT && currentFieldName != null) { if ("parameters".equals(currentFieldName)) { TermVectorRequest.parseRequest(template, parser); } else { throw new ElasticsearchParseException( "No parameter named " + currentFieldName + "and type OBJECT"); } } else if (currentFieldName != null) { throw new ElasticsearchParseException("_mtermvectors: Parameter " + currentFieldName + "not supported"); } } } finally { parser.close(); } } for (String id : ids) { TermVectorRequest curRequest = new TermVectorRequest(template); curRequest.id(id); requests.add(curRequest); } } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); preference = in.readOptionalString(); int size = in.readVInt(); requests = new ArrayList<TermVectorRequest>(size); for (int i = 0; i < size; i++) { requests.add(TermVectorRequest.readTermVectorRequest(in)); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeOptionalString(preference); out.writeVInt(requests.size()); for (TermVectorRequest termVectorRequest : requests) { termVectorRequest.writeTo(out); } } public void ids(String[] ids) { for (String id : ids) { this.ids.add(id.replaceAll("\\s", "")); } } }
0true
src_main_java_org_elasticsearch_action_termvector_MultiTermVectorsRequest.java
1,387
public static class Map extends Mapper<NullWritable, FaunusElement, LongWritable, FaunusVertex> { private final HashMap<Long, FaunusVertex> map = new HashMap<Long, FaunusVertex>(); private static final int MAX_MAP_SIZE = 5000; private final LongWritable longWritable = new LongWritable(); private int counter = 0; private Configuration faunusConf; @Override public void setup(Context context) { faunusConf = ModifiableHadoopConfiguration.of(DEFAULT_COMPAT.getContextConfiguration(context)); } @Override public void map(final NullWritable key, final FaunusElement value, final Mapper<NullWritable, FaunusElement, LongWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { if (value instanceof StandardFaunusEdge) { final long outId = ((StandardFaunusEdge) value).getVertexId(OUT); final long inId = ((StandardFaunusEdge) value).getVertexId(IN); FaunusVertex vertex = this.map.get(outId); if (null == vertex) { vertex = new FaunusVertex(faunusConf, outId); this.map.put(outId, vertex); } vertex.addEdge(OUT, WritableUtils.clone((StandardFaunusEdge) value, context.getConfiguration())); this.counter++; vertex = this.map.get(inId); if (null == vertex) { vertex = new FaunusVertex(faunusConf, inId); this.map.put(inId, vertex); } vertex.addEdge(IN, WritableUtils.clone((StandardFaunusEdge) value, context.getConfiguration())); DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGES_PROCESSED, 1L); this.counter++; } else { final long id = value.getLongId(); FaunusVertex vertex = this.map.get(id); if (null == vertex) { vertex = new FaunusVertex(faunusConf, id); this.map.put(id, vertex); } vertex.addAllProperties(value.getPropertyCollection()); vertex.addEdges(BOTH, WritableUtils.clone((FaunusVertex) value, context.getConfiguration())); this.counter++; } if (this.counter > MAX_MAP_SIZE) this.flush(context); } @Override public void cleanup(final Mapper<NullWritable, FaunusElement, LongWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { this.flush(context); } private void flush(final Mapper<NullWritable, FaunusElement, LongWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { for (final FaunusVertex vertex : this.map.values()) { this.longWritable.set(vertex.getLongId()); context.write(this.longWritable, vertex); DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_EMITTED, 1L); } this.map.clear(); this.counter = 0; } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_formats_edgelist_EdgeListInputMapReduce.java
1,448
public static class Factory implements MetaData.Custom.Factory<SnapshotMetaData> { @Override public String type() { return TYPE; //To change body of implemented methods use File | Settings | File Templates. } @Override public SnapshotMetaData readFrom(StreamInput in) throws IOException { Entry[] entries = new Entry[in.readVInt()]; for (int i = 0; i < entries.length; i++) { SnapshotId snapshotId = SnapshotId.readSnapshotId(in); boolean includeGlobalState = in.readBoolean(); State state = State.fromValue(in.readByte()); int indices = in.readVInt(); ImmutableList.Builder<String> indexBuilder = ImmutableList.builder(); for (int j = 0; j < indices; j++) { indexBuilder.add(in.readString()); } ImmutableMap.Builder<ShardId, ShardSnapshotStatus> builder = ImmutableMap.<ShardId, ShardSnapshotStatus>builder(); int shards = in.readVInt(); for (int j = 0; j < shards; j++) { ShardId shardId = ShardId.readShardId(in); String nodeId = in.readOptionalString(); State shardState = State.fromValue(in.readByte()); builder.put(shardId, new ShardSnapshotStatus(nodeId, shardState)); } entries[i] = new Entry(snapshotId, includeGlobalState, state, indexBuilder.build(), builder.build()); } return new SnapshotMetaData(entries); } @Override public void writeTo(SnapshotMetaData repositories, StreamOutput out) throws IOException { out.writeVInt(repositories.entries().size()); for (Entry entry : repositories.entries()) { entry.snapshotId().writeTo(out); out.writeBoolean(entry.includeGlobalState()); out.writeByte(entry.state().value()); out.writeVInt(entry.indices().size()); for (String index : entry.indices()) { out.writeString(index); } out.writeVInt(entry.shards().size()); for (Map.Entry<ShardId, ShardSnapshotStatus> shardEntry : entry.shards().entrySet()) { shardEntry.getKey().writeTo(out); out.writeOptionalString(shardEntry.getValue().nodeId()); out.writeByte(shardEntry.getValue().state().value()); } } } @Override public SnapshotMetaData fromXContent(XContentParser parser) throws IOException { throw new UnsupportedOperationException(); } @Override public void toXContent(SnapshotMetaData customIndexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startArray("snapshots"); for (Entry entry : customIndexMetaData.entries()) { toXContent(entry, builder, params); } builder.endArray(); } public void toXContent(Entry entry, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field("repository", entry.snapshotId().getRepository()); builder.field("snapshot", entry.snapshotId().getSnapshot()); builder.field("include_global_state", entry.includeGlobalState()); builder.field("state", entry.state()); builder.startArray("indices"); { for (String index : entry.indices()) { builder.value(index); } } builder.endArray(); builder.startArray("shards"); { for (Map.Entry<ShardId, ShardSnapshotStatus> shardEntry : entry.shards.entrySet()) { ShardId shardId = shardEntry.getKey(); ShardSnapshotStatus status = shardEntry.getValue(); builder.startObject(); { builder.field("index", shardId.getIndex()); builder.field("shard", shardId.getId()); builder.field("state", status.state()); builder.field("node", status.nodeId()); } builder.endObject(); } } builder.endArray(); builder.endObject(); } public boolean isPersistent() { return false; } }
0true
src_main_java_org_elasticsearch_cluster_metadata_SnapshotMetaData.java
2,726
YES() { @Override public boolean shouldImport() { return true; } },
0true
src_main_java_org_elasticsearch_gateway_local_state_meta_LocalGatewayMetaState.java
2,461
public abstract class PrioritizedCallable<T> implements Callable<T>, Comparable<PrioritizedCallable> { private final Priority priority; public static <T> PrioritizedCallable<T> wrap(Callable<T> callable, Priority priority) { return new Wrapped<T>(callable, priority); } protected PrioritizedCallable(Priority priority) { this.priority = priority; } @Override public int compareTo(PrioritizedCallable pc) { return priority.compareTo(pc.priority); } public Priority priority() { return priority; } static class Wrapped<T> extends PrioritizedCallable<T> { private final Callable<T> callable; private Wrapped(Callable<T> callable, Priority priority) { super(priority); this.callable = callable; } @Override public T call() throws Exception { return callable.call(); } } }
0true
src_main_java_org_elasticsearch_common_util_concurrent_PrioritizedCallable.java
1,194
public interface MembershipListener extends EventListener { /** * Invoked when a new member is added to the cluster. * * @param membershipEvent membership event */ void memberAdded(MembershipEvent membershipEvent); /** * Invoked when an existing member leaves the cluster. * * @param membershipEvent membership event */ void memberRemoved(MembershipEvent membershipEvent); /** * Invoked when an attribute of a member was changed. * * @param memberAttributeEvent member attribute event * @since 3.2 */ void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent); }
0true
hazelcast_src_main_java_com_hazelcast_core_MembershipListener.java
373
ConfigOption.Type.MASKABLE, Integer.class, new Predicate<Integer>() { @Override public boolean apply(Integer input) { return null != input && MIN_REGION_COUNT <= input; } }
0true
titan-hbase-parent_titan-hbase-core_src_main_java_com_thinkaurelius_titan_diskstorage_hbase_HBaseStoreManager.java
198
Analyzer analyzer = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName, Reader reader) { Tokenizer t = new WhitespaceTokenizer(Lucene.VERSION, reader); return new TokenStreamComponents(t, new UniqueTokenFilter(t)); } };
0true
src_test_java_org_apache_lucene_analysis_miscellaneous_UniqueTokenFilterTests.java
2,279
public class ConcurrentDequeRecycler<T> extends DequeRecycler<T> { // we maintain size separately because concurrent deque implementations typically have linear-time size() impls final AtomicInteger size; public ConcurrentDequeRecycler(C<T> c, int maxSize) { super(c, ConcurrentCollections.<T>newDeque(), maxSize); this.size = new AtomicInteger(); } @Override public void close() { assert deque.size() == size.get(); super.close(); size.set(0); } @Override public V<T> obtain(int sizing) { final V<T> v = super.obtain(sizing); if (v.isRecycled()) { size.decrementAndGet(); } return v; } @Override protected boolean beforeRelease() { return size.incrementAndGet() <= maxSize; } @Override protected void afterRelease(boolean recycled) { if (!recycled) { size.decrementAndGet(); } } }
0true
src_main_java_org_elasticsearch_common_recycler_ConcurrentDequeRecycler.java
1,615
public class AdminSandBoxContext extends SandBoxContext { protected AdminUser adminUser; protected SandBoxMode sandBoxMode; protected String sandBoxName; protected boolean resetData = false; protected boolean isReplay = false; protected boolean rebuildSandBox = false; public AdminUser getAdminUser() { return adminUser; } public void setAdminUser(AdminUser adminUser) { this.adminUser = adminUser; } public SandBoxMode getSandBoxMode() { return sandBoxMode; } public void setSandBoxMode(SandBoxMode sandBoxMode) { this.sandBoxMode = sandBoxMode; } public String getSandBoxName() { return sandBoxName; } public void setSandBoxName(String sandBoxName) { this.sandBoxName = sandBoxName; } public boolean isReplay() { return isReplay; } public void setReplay(boolean replay) { isReplay = replay; } public boolean isRebuildSandBox() { return rebuildSandBox; } public void setRebuildSandBox(boolean rebuildSandBox) { this.rebuildSandBox = rebuildSandBox; } public boolean isResetData() { return resetData; } public void setResetData(boolean resetData) { this.resetData = resetData; } public SandBoxContext clone() { AdminSandBoxContext myContext = new AdminSandBoxContext(); myContext.setResetData(isResetData()); myContext.setAdminUser(getAdminUser()); myContext.setSandBoxId(getSandBoxId()); myContext.setPreviewMode(getPreviewMode()); myContext.setSandBoxMode(getSandBoxMode()); myContext.setSandBoxName(getSandBoxName()); myContext.setReplay(isReplay()); myContext.setRebuildSandBox(isRebuildSandBox()); return myContext; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_security_AdminSandBoxContext.java
554
public class GetMappingsRequest extends ClusterInfoRequest<GetMappingsRequest> { @Override public ActionRequestValidationException validate() { return null; } }
0true
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetMappingsRequest.java
478
register(IdGeneratorService.SERVICE_NAME, new ClientProxyFactory() { public ClientProxy create(String id) { String instanceName = client.getName(); IAtomicLong atomicLong = client.getAtomicLong(IdGeneratorService.ATOMIC_LONG_NAME + id); return new ClientIdGeneratorProxy(instanceName, IdGeneratorService.SERVICE_NAME, id, atomicLong); } });
1no label
hazelcast-client_src_main_java_com_hazelcast_client_spi_ProxyManager.java
1,655
public final class Numbers { private Numbers() { } /** * Converts a byte array to an short. * * @param arr The byte array to convert to an short * @return The int converted */ public static short bytesToShort(byte[] arr) { return (short) (((arr[0] & 0xff) << 8) | (arr[1] & 0xff)); } public static short bytesToShort(BytesRef bytes) { return (short) (((bytes.bytes[bytes.offset] & 0xff) << 8) | (bytes.bytes[bytes.offset + 1] & 0xff)); } /** * Converts a byte array to an int. * * @param arr The byte array to convert to an int * @return The int converted */ public static int bytesToInt(byte[] arr) { return (arr[0] << 24) | ((arr[1] & 0xff) << 16) | ((arr[2] & 0xff) << 8) | (arr[3] & 0xff); } public static int bytesToInt(BytesRef bytes) { return (bytes.bytes[bytes.offset] << 24) | ((bytes.bytes[bytes.offset + 1] & 0xff) << 16) | ((bytes.bytes[bytes.offset + 2] & 0xff) << 8) | (bytes.bytes[bytes.offset + 3] & 0xff); } /** * Converts a byte array to a long. * * @param arr The byte array to convert to a long * @return The long converter */ public static long bytesToLong(byte[] arr) { int high = (arr[0] << 24) | ((arr[1] & 0xff) << 16) | ((arr[2] & 0xff) << 8) | (arr[3] & 0xff); int low = (arr[4] << 24) | ((arr[5] & 0xff) << 16) | ((arr[6] & 0xff) << 8) | (arr[7] & 0xff); return (((long) high) << 32) | (low & 0x0ffffffffL); } public static long bytesToLong(BytesRef bytes) { int high = (bytes.bytes[bytes.offset + 0] << 24) | ((bytes.bytes[bytes.offset + 1] & 0xff) << 16) | ((bytes.bytes[bytes.offset + 2] & 0xff) << 8) | (bytes.bytes[bytes.offset + 3] & 0xff); int low = (bytes.bytes[bytes.offset + 4] << 24) | ((bytes.bytes[bytes.offset + 5] & 0xff) << 16) | ((bytes.bytes[bytes.offset + 6] & 0xff) << 8) | (bytes.bytes[bytes.offset + 7] & 0xff); return (((long) high) << 32) | (low & 0x0ffffffffL); } /** * Converts a byte array to float. * * @param arr The byte array to convert to a float * @return The float converted */ public static float bytesToFloat(byte[] arr) { return Float.intBitsToFloat(bytesToInt(arr)); } public static float bytesToFloat(BytesRef bytes) { return Float.intBitsToFloat(bytesToInt(bytes)); } /** * Converts a byte array to double. * * @param arr The byte array to convert to a double * @return The double converted */ public static double bytesToDouble(byte[] arr) { return Double.longBitsToDouble(bytesToLong(arr)); } public static double bytesToDouble(BytesRef bytes) { return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Converts an int to a byte array. * * @param val The int to convert to a byte array * @return The byte array converted */ public static byte[] intToBytes(int val) { byte[] arr = new byte[4]; arr[0] = (byte) (val >>> 24); arr[1] = (byte) (val >>> 16); arr[2] = (byte) (val >>> 8); arr[3] = (byte) (val); return arr; } /** * Converts an int to a byte array. * * @param val The int to convert to a byte array * @return The byte array converted */ public static byte[] shortToBytes(int val) { byte[] arr = new byte[2]; arr[0] = (byte) (val >>> 8); arr[1] = (byte) (val); return arr; } /** * Converts a long to a byte array. * * @param val The long to convert to a byte array * @return The byte array converted */ public static byte[] longToBytes(long val) { byte[] arr = new byte[8]; arr[0] = (byte) (val >>> 56); arr[1] = (byte) (val >>> 48); arr[2] = (byte) (val >>> 40); arr[3] = (byte) (val >>> 32); arr[4] = (byte) (val >>> 24); arr[5] = (byte) (val >>> 16); arr[6] = (byte) (val >>> 8); arr[7] = (byte) (val); return arr; } /** * Converts a float to a byte array. * * @param val The float to convert to a byte array * @return The byte array converted */ public static byte[] floatToBytes(float val) { return intToBytes(Float.floatToRawIntBits(val)); } /** * Converts a double to a byte array. * * @param val The double to convert to a byte array * @return The byte array converted */ public static byte[] doubleToBytes(double val) { return longToBytes(Double.doubleToRawLongBits(val)); } }
0true
src_main_java_org_elasticsearch_common_Numbers.java
1,970
public interface ReachabilityHandler<T> { /** * @param record * @param criteria * @param time * @return <tt>null</tt> if record is not reachable atm. * otherwise returns record. <tt>T</tt> */ T process(T record, long criteria, long time); /** * @return Handler priority. * Min nice values correspond to a higher priority. */ short niceNumber(); void setSuccessorHandler(ReachabilityHandler successorHandler); ReachabilityHandler getSuccessorHandler(); void resetHandler(); }
0true
hazelcast_src_main_java_com_hazelcast_map_eviction_ReachabilityHandler.java
272
public interface OCommandRequest { public <RET> RET execute(Object... iArgs); /** * Returns the limit of result set. -1 means no limits. * */ public int getLimit(); /** * Sets the maximum items the command can returns. -1 means no limits. * * @param iLimit * -1 = no limit. 1 to N to limit the result set. * @return */ public OCommandRequest setLimit(int iLimit); /** * Returns the command timeout. 0 means no timeout. * * @return */ public long getTimeoutTime(); /** * Returns the command timeout strategy between the defined ones. * * @return */ public TIMEOUT_STRATEGY getTimeoutStrategy(); /** * Sets the command timeout. When the command execution time is major than the timeout the command returns * * @param timeout */ public void setTimeout(long timeout, TIMEOUT_STRATEGY strategy); /** * Returns true if the command doesn't change the database, otherwise false. */ public boolean isIdempotent(); /** * Returns the fetch plan if any * * @return Fetch plan as unique string or null if it was not defined. */ public String getFetchPlan(); /** * Set the fetch plan. The format is: * * <pre> * &lt;field&gt;:&lt;depth-level&gt;* * </pre> * * Where: * <ul> * <li><b>field</b> is the name of the field to specify the depth-level. <b>*</b> wildcard means any fields</li> * <li><b>depth-level</b> is the depth level to fetch. -1 means infinite, 0 means no fetch at all and 1-N the depth level value.</li> * </ul> * Uses the blank spaces to separate the fields strategies.<br/> * Example: * * <pre> * children:-1 parent:0 sibling:3 *:0 * </pre> * * <br/> * * @param iFetchPlan * @return */ public <RET extends OCommandRequest> RET setFetchPlan(String iFetchPlan); public void setUseCache(boolean iUseCache); public OCommandContext getContext(); public OCommandRequest setContext(final OCommandContext iContext); }
0true
core_src_main_java_com_orientechnologies_orient_core_command_OCommandRequest.java
3,035
private final class TestCodec extends Lucene46Codec { @Override public PostingsFormat getPostingsFormatForField(String field) { return new Elasticsearch090PostingsFormat(); } }
0true
src_test_java_org_elasticsearch_index_codec_postingformat_DefaultPostingsFormatTests.java
843
public class InlineRefactoring extends AbstractRefactoring { private final Declaration declaration; private boolean delete = true; private boolean justOne = false; public InlineRefactoring(IEditorPart editor) { super(editor); Referenceable ref = getReferencedDeclaration(node); if (ref instanceof Declaration) { declaration = (Declaration) ref; } else { declaration = null; } } boolean isReference() { return !(node instanceof Tree.Declaration); } @Override public boolean isEnabled() { return declaration!=null && project != null && inSameProject(declaration) && declaration instanceof MethodOrValue && !declaration.isParameter() && !(declaration instanceof Setter) && !declaration.isDefault() && !declaration.isFormal() && (((MethodOrValue)declaration).getTypeDeclaration()!=null) && (!((MethodOrValue)declaration).getTypeDeclaration().isAnonymous()) && (declaration.isToplevel() || !declaration.isShared() || (!declaration.isFormal() && !declaration.isDefault() && !declaration.isActual())); //TODO: && !declaration is a control structure variable //TODO: && !declaration is a value with lazy init } public int getCount() { return declaration==null ? 0 : countDeclarationOccurrences(); } @Override int countReferences(Tree.CompilationUnit cu) { FindReferencesVisitor frv = new FindReferencesVisitor(declaration); cu.visit(frv); return frv.getNodes().size(); } public String getName() { return "Inline"; } public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { final RefactoringStatus result = new RefactoringStatus(); Tree.Declaration declarationNode=null; Tree.CompilationUnit declarationUnit=null; if (searchInEditor()) { Tree.CompilationUnit cu = editor.getParseController().getRootNode(); if (cu.getUnit().equals(declaration.getUnit())) { declarationUnit = cu; } } if (declarationUnit==null) { for (final PhasedUnit pu: CeylonBuilder.getUnits(project)) { if (pu.getUnit().equals(declaration.getUnit())) { declarationUnit = pu.getCompilationUnit(); break; } } } FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(declaration); declarationUnit.visit(fdv); declarationNode = (Tree.Declaration) fdv.getDeclarationNode(); if (declarationNode instanceof Tree.AttributeDeclaration && ((Tree.AttributeDeclaration) declarationNode).getSpecifierOrInitializerExpression()==null || declarationNode instanceof Tree.MethodDeclaration && ((Tree.MethodDeclaration) declarationNode).getSpecifierExpression()==null) { return createFatalErrorStatus("Cannot inline forward declaration: " + declaration.getName()); } if (declarationNode instanceof Tree.AttributeGetterDefinition) { Tree.AttributeGetterDefinition attributeGetterDefinition = (Tree.AttributeGetterDefinition) declarationNode; List<Tree.Statement> statements = attributeGetterDefinition.getBlock().getStatements(); if (statements.size()!=1) { return createFatalErrorStatus("Getter body is not a single statement: " + declaration.getName()); } if (!(statements.get(0) instanceof Tree.Return)) { return createFatalErrorStatus("Getter body is not a return statement: " + declaration.getName()); } } if (declarationNode instanceof Tree.MethodDefinition) { Tree.MethodDefinition methodDefinition = (Tree.MethodDefinition) declarationNode; List<Tree.Statement> statements = methodDefinition.getBlock().getStatements(); if (statements.size()!=1) { return createFatalErrorStatus("Method body is not a single statement: " + declaration.getName()); } if (methodDefinition.getType() instanceof Tree.VoidModifier) { if (!(statements.get(0) instanceof Tree.ExpressionStatement)) { return createFatalErrorStatus("Method body is not an expression: " + declaration.getName()); } } else { if (!(statements.get(0) instanceof Tree.Return)) { return createFatalErrorStatus("Method body is not a return statement: " + declaration.getName()); } } } if (declarationNode instanceof Tree.AnyAttribute && ((Tree.AnyAttribute) declarationNode).getDeclarationModel().isVariable()) { result.merge(createWarningStatus("Inlined value is variable")); } declarationNode.visit(new Visitor() { @Override public void visit(Tree.BaseMemberOrTypeExpression that) { super.visit(that); if (that.getDeclaration()==null) { result.merge(createWarningStatus("Definition contains unresolved reference")); } else if (declaration.isShared() && !that.getDeclaration().isShared() && !that.getDeclaration().isParameter()) { result.merge(createWarningStatus("Definition contains reference to unshared declaration: " + that.getDeclaration().getName())); } } }); return result; } public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { return new RefactoringStatus(); } public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { Tree.Declaration declarationNode=null; Tree.CompilationUnit declarationUnit=null; Tree.Term term = null; List<CommonToken> declarationTokens = null; Tree.CompilationUnit editorRootNode = editor.getParseController().getRootNode(); List<CommonToken> editorTokens = editor.getParseController().getTokens(); if (declaration!=null) { if (searchInEditor()) { if (editorRootNode.getUnit() .equals(declaration.getUnit())) { declarationUnit = editorRootNode; declarationTokens = editorTokens; } } if (declarationUnit==null) { for (PhasedUnit pu: getAllUnits()) { if (pu.getUnit().equals(declaration.getUnit())) { declarationUnit = pu.getCompilationUnit(); declarationTokens = pu.getTokens(); break; } } } FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(declaration); declarationUnit.visit(fdv); declarationNode = (Tree.Declaration) fdv.getDeclarationNode(); term = getInlinedTerm(declarationNode); } CompositeChange cc = new CompositeChange(getName()); if (declarationNode!=null) { for (PhasedUnit pu: getAllUnits()) { if (searchInFile(pu) && affectsUnit(pu.getUnit())) { TextFileChange tfc = newTextFileChange(pu); Tree.CompilationUnit cu = pu.getCompilationUnit(); inlineInFile(tfc, cc, declarationNode, declarationUnit, term, declarationTokens, cu, pu.getTokens()); } } } if (searchInEditor() && affectsUnit(editorRootNode.getUnit())) { DocumentChange dc = newDocumentChange(); inlineInFile(dc, cc, declarationNode, declarationUnit, term, declarationTokens, editorRootNode, editorTokens); } return cc; } private boolean affectsUnit(Unit unit) { return delete && unit.equals(declaration.getUnit()) || !justOne || unit.equals(node.getUnit()); } private boolean addImports(final TextChange change, final Tree.Declaration declarationNode, final Tree.CompilationUnit cu) { final Package decPack = declarationNode.getUnit().getPackage(); final Package filePack = cu.getUnit().getPackage(); final class AddImportsVisitor extends Visitor { private final Set<Declaration> already; boolean importedFromDeclarationPackage; private AddImportsVisitor(Set<Declaration> already) { this.already = already; } @Override public void visit(Tree.BaseMemberOrTypeExpression that) { super.visit(that); if (that.getDeclaration()!=null) { importDeclaration(already, that.getDeclaration(), cu); Package refPack = that.getDeclaration().getUnit().getPackage(); importedFromDeclarationPackage = importedFromDeclarationPackage || //result!=0 && refPack.equals(decPack) && !decPack.equals(filePack); //unnecessary } } } final Set<Declaration> already = new HashSet<Declaration>(); AddImportsVisitor aiv = new AddImportsVisitor(already); declarationNode.visit(aiv); applyImports(change, already, declarationNode.getDeclarationModel(), cu, document); return aiv.importedFromDeclarationPackage; } private void inlineInFile(TextChange tfc, CompositeChange cc, Tree.Declaration declarationNode, Tree.CompilationUnit declarationUnit, Tree.Term term, List<CommonToken> declarationTokens, Tree.CompilationUnit cu, List<CommonToken> tokens) { tfc.setEdit(new MultiTextEdit()); inlineReferences(declarationNode, declarationUnit, term, declarationTokens, cu, tokens, tfc); boolean inlined = tfc.getEdit().hasChildren(); deleteDeclaration(declarationNode, declarationUnit, cu, tokens, tfc); boolean importsAddedToDeclarationPackage = false; if (inlined) { importsAddedToDeclarationPackage = addImports(tfc, declarationNode, cu); } deleteImports(tfc, declarationNode, cu, tokens, importsAddedToDeclarationPackage); if (tfc.getEdit().hasChildren()) { cc.add(tfc); } } private void deleteImports(TextChange tfc, Tree.Declaration declarationNode, Tree.CompilationUnit cu, List<CommonToken> tokens, boolean importsAddedToDeclarationPackage) { Tree.ImportList il = cu.getImportList(); if (il!=null) { for (Tree.Import i: il.getImports()) { List<Tree.ImportMemberOrType> list = i.getImportMemberOrTypeList() .getImportMemberOrTypes(); for (Tree.ImportMemberOrType imt: list) { Declaration d = imt.getDeclarationModel(); if (d!=null && d.equals(declarationNode.getDeclarationModel())) { if (list.size()==1 && !importsAddedToDeclarationPackage) { //delete the whole import statement tfc.addEdit(new DeleteEdit(i.getStartIndex(), i.getStopIndex()-i.getStartIndex()+1)); } else { //delete just the item in the import statement... tfc.addEdit(new DeleteEdit(imt.getStartIndex(), imt.getStopIndex()-imt.getStartIndex()+1)); //...along with a comma before or after int ti = Nodes.getTokenIndexAtCharacter(tokens, imt.getStartIndex()); CommonToken prev = tokens.get(ti-1); if (prev.getChannel()==CommonToken.HIDDEN_CHANNEL) { prev = tokens.get(ti-2); } CommonToken next = tokens.get(ti+1); if (next.getChannel()==CommonToken.HIDDEN_CHANNEL) { next = tokens.get(ti+2); } if (prev.getType()==CeylonLexer.COMMA) { tfc.addEdit(new DeleteEdit(prev.getStartIndex(), imt.getStartIndex()-prev.getStartIndex())); } else if (next.getType()==CeylonLexer.COMMA) { tfc.addEdit(new DeleteEdit(imt.getStopIndex()+1, next.getStopIndex()-imt.getStopIndex())); } } } } } } } private void deleteDeclaration(Tree.Declaration declarationNode, Tree.CompilationUnit declarationUnit, Tree.CompilationUnit cu, List<CommonToken> tokens, TextChange tfc) { if (delete && cu.getUnit().equals(declarationUnit.getUnit())) { CommonToken from = (CommonToken) declarationNode.getToken(); Tree.AnnotationList anns = declarationNode.getAnnotationList(); if (!anns.getAnnotations().isEmpty()) { from = (CommonToken) anns.getAnnotations().get(0).getToken(); } int prevIndex = from.getTokenIndex()-1; if (prevIndex>=0) { CommonToken tok = tokens.get(prevIndex); if (tok.getChannel()==Token.HIDDEN_CHANNEL) { from=tok; } } tfc.addEdit(new DeleteEdit(from.getStartIndex(), declarationNode.getStopIndex()-from.getStartIndex()+1)); } } private static Tree.Term getInlinedTerm(Tree.Declaration declarationNode) { if (declarationNode!=null) { if (declarationNode instanceof Tree.AttributeDeclaration) { Tree.AttributeDeclaration att = (Tree.AttributeDeclaration) declarationNode; return att.getSpecifierOrInitializerExpression() .getExpression().getTerm(); } else if (declarationNode instanceof Tree.MethodDefinition) { Tree.MethodDefinition meth = (Tree.MethodDefinition) declarationNode; List<Tree.Statement> statements = meth.getBlock().getStatements(); if (meth.getType() instanceof Tree.VoidModifier) { //TODO: in the case of a void method, tolerate // multiple statements , including control // structures, not just expression statements if (statements.size()!=1 || !(statements.get(0) instanceof Tree.ExpressionStatement)) { throw new RuntimeException("method body is not a single expression statement"); } Tree.ExpressionStatement e = (Tree.ExpressionStatement) statements.get(0); return e.getExpression().getTerm(); } else { if (statements.size()!=1 || !(statements.get(0) instanceof Tree.Return)) { throw new RuntimeException("method body is not a single expression statement"); } Tree.Return r = (Tree.Return) statements.get(0); return r.getExpression().getTerm(); } } else if (declarationNode instanceof Tree.MethodDeclaration) { Tree.MethodDeclaration meth = (Tree.MethodDeclaration) declarationNode; return meth.getSpecifierExpression().getExpression().getTerm(); } else if (declarationNode instanceof Tree.AttributeGetterDefinition) { Tree.AttributeGetterDefinition att = (Tree.AttributeGetterDefinition) declarationNode; List<Tree.Statement> statements = att.getBlock().getStatements(); if (statements.size()!=1 || !(statements.get(0) instanceof Tree.Return)) { throw new RuntimeException("getter body is not a single expression statement"); } Tree.Return r = (Tree.Return) att.getBlock().getStatements().get(0); return r.getExpression().getTerm(); } else { throw new RuntimeException("not a value or function"); } } else { return null; } } private void inlineReferences(Tree.Declaration declarationNode, Tree.CompilationUnit declarationUnit, Tree.Term term, List<CommonToken> declarationTokens, Tree.CompilationUnit pu, List<CommonToken> tokens, TextChange tfc) { if (declarationNode instanceof Tree.AnyAttribute) { inlineAttributeReferences(pu, tokens, term, declarationTokens, tfc); } else if (declarationNode instanceof Tree.AnyMethod) { inlineFunctionReferences(pu, tokens, term, (Tree.AnyMethod) declarationNode, declarationTokens, tfc); } } private void inlineFunctionReferences(final Tree.CompilationUnit pu, final List<CommonToken> tokens, final Tree.Term term, final Tree.AnyMethod declaration, final List<CommonToken> declarationTokens, final TextChange tfc) { new Visitor() { private boolean needsParens = false; @Override public void visit(final Tree.InvocationExpression that) { super.visit(that); if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) { Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary(); inlineDefinition(tokens, declarationTokens, term, tfc, that, mte, needsParens); } } @Override public void visit(final Tree.MemberOrTypeExpression that) { super.visit(that); Declaration d = that.getDeclaration(); if (!that.getDirectlyInvoked() && inlineRef(that, d)) { StringBuilder text = new StringBuilder(); Method dec = declaration.getDeclarationModel(); if (dec.isDeclaredVoid()) { text.append("void "); } for (Tree.ParameterList pl: declaration.getParameterLists()) { text.append(Nodes.toString(pl, declarationTokens)); } text.append(" => "); text.append(Nodes.toString(term, declarationTokens)); tfc.addEdit(new ReplaceEdit(that.getStartIndex(), that.getStopIndex()-that.getStartIndex()+1, text.toString())); } } @Override public void visit(Tree.OperatorExpression that) { boolean onp = needsParens; needsParens=true; super.visit(that); needsParens = onp; } @Override public void visit(Tree.StatementOrArgument that) { boolean onp = needsParens; needsParens = false; super.visit(that); needsParens = onp; } @Override public void visit(Tree.Expression that) { boolean onp = needsParens; needsParens = false; super.visit(that); needsParens = onp; } }.visit(pu); } private void inlineAttributeReferences(final Tree.CompilationUnit pu, final List<CommonToken> tokens, final Term term, final List<CommonToken> declarationTokens, final TextChange tfc) { new Visitor() { private boolean needsParens = false; @Override public void visit(Tree.Variable that) { if (that.getType() instanceof Tree.SyntheticVariable) { TypedDeclaration od = that.getDeclarationModel().getOriginalDeclaration(); if (od!=null && od.equals(declaration) && delete) { Integer startIndex = that.getSpecifierExpression().getStartIndex(); tfc.addEdit(new InsertEdit(startIndex, that.getIdentifier().getText()+" = ")); } } super.visit(that); } @Override public void visit(Tree.MemberOrTypeExpression that) { super.visit(that); inlineDefinition(tokens, declarationTokens, term, tfc, null, that, needsParens); } @Override public void visit(Tree.OperatorExpression that) { boolean onp = needsParens; needsParens=true; super.visit(that); needsParens = onp; } @Override public void visit(Tree.StatementOrArgument that) { boolean onp = needsParens; needsParens = false; super.visit(that); needsParens = onp; } @Override public void visit(Tree.Expression that) { boolean onp = needsParens; needsParens = false; super.visit(that); needsParens = onp; } }.visit(pu); } private void inlineDefinitionReference(List<CommonToken> tokens, List<CommonToken> declarationTokens, Tree.MemberOrTypeExpression re, Tree.InvocationExpression ie, StringBuilder result, Tree.StaticMemberOrTypeExpression it) { Declaration dec = it.getDeclaration(); if (dec.isParameter() && ie!=null && it instanceof Tree.BaseMemberOrTypeExpression) { Parameter param = ((MethodOrValue) dec).getInitializerParameter(); if (param.getDeclaration().equals(declaration)) { boolean sequenced = param.isSequenced(); if (ie.getPositionalArgumentList()!=null) { interpolatePositionalArguments(result, ie, it, sequenced, tokens); } if (ie.getNamedArgumentList()!=null) { interpolateNamedArguments(result, ie, it, sequenced, tokens); } return; //NOTE: early exit! } } String expressionText = Nodes.toString(it, declarationTokens); if (re instanceof Tree.QualifiedMemberOrTypeExpression) { Tree.QualifiedMemberOrTypeExpression qmtre = (Tree.QualifiedMemberOrTypeExpression) re; String prim = Nodes.toString(qmtre.getPrimary(), tokens); if (it instanceof Tree.QualifiedMemberOrTypeExpression) { //TODO: handle more depth, for example, foo.bar.baz Tree.QualifiedMemberOrTypeExpression qmte = (Tree.QualifiedMemberOrTypeExpression) it; Tree.Primary p = qmte.getPrimary(); if (p instanceof Tree.This) { result.append(prim) .append(qmte.getMemberOperator().getText()) .append(qmte.getIdentifier().getText()); } else { String primaryText = Nodes.toString(p, declarationTokens); if (p instanceof Tree.MemberOrTypeExpression) { if (((Tree.MemberOrTypeExpression) p).getDeclaration() .isClassOrInterfaceMember()) { result.append(prim) .append(".") .append(primaryText); } } else { result.append(primaryText); } } } else { if (it.getDeclaration().isClassOrInterfaceMember()) { result.append(prim) .append(".") .append(expressionText); } else { result.append(expressionText); } } } else { result.append(expressionText); } } private void inlineDefinition(final List<CommonToken> tokens, final List<CommonToken> declarationTokens, final Tree.Term term, final TextChange tfc, final Tree.InvocationExpression that, final Tree.MemberOrTypeExpression mte, final boolean needsParens) { Declaration d = mte.getDeclaration(); if (inlineRef(mte, d)) { //TODO: breaks for invocations like f(f(x, y),z) final StringBuilder result = new StringBuilder(); class InterpolationVisitor extends Visitor { int start = 0; final String template = Nodes.toString(term, declarationTokens); final int templateStart = term.getStartIndex(); void text(Node it) { result.append(template.substring(start, it.getStartIndex()-templateStart)); start = it.getStopIndex()-templateStart+1; } @Override public void visit(Tree.BaseMemberExpression it) { super.visit(it); text(it); inlineDefinitionReference(tokens, declarationTokens, mte, that, result, it); } @Override public void visit(Tree.QualifiedMemberExpression it) { super.visit(it); text(it); inlineDefinitionReference(tokens, declarationTokens, mte, that, result, it); } void finish() { result.append(template.substring(start, template.length())); } } InterpolationVisitor iv = new InterpolationVisitor(); iv.visit(term); iv.finish(); if (needsParens && term instanceof Tree.OperatorExpression) { result.insert(0,'(').append(')'); } Node node = that==null ? mte : that; tfc.addEdit(new ReplaceEdit(node.getStartIndex(), node.getStopIndex()-node.getStartIndex()+1, result.toString())); } } private boolean inlineRef(Tree.MemberOrTypeExpression that, Declaration d) { return (!justOne || that.getUnit().equals(node.getUnit()) && that.getStartIndex()!=null && that.getStartIndex().equals(node.getStartIndex())) && d!=null && d.equals(declaration); } private static void interpolatePositionalArguments(StringBuilder result, Tree.InvocationExpression that, Tree.StaticMemberOrTypeExpression it, boolean sequenced, List<CommonToken> tokens) { boolean first = true; boolean found = false; if (sequenced) { result.append("{"); } for (Tree.PositionalArgument arg: that.getPositionalArgumentList() .getPositionalArguments()) { if (it.getDeclaration().equals(arg.getParameter().getModel())) { if (arg.getParameter().isSequenced() && arg instanceof Tree.ListedArgument) { if (first) result.append(" "); if (!first) result.append(", "); first = false; } result.append(Nodes.toString(arg, tokens)); found = true; } } if (sequenced) { if (!first) result.append(" "); result.append("}"); } if (!found) {} //TODO: use default value! } private static void interpolateNamedArguments(StringBuilder result, Tree.InvocationExpression that, Tree.StaticMemberOrTypeExpression it, boolean sequenced, List<CommonToken> tokens) { boolean found = false; for (Tree.NamedArgument arg: that.getNamedArgumentList().getNamedArguments()) { if (it.getDeclaration().equals(arg.getParameter().getModel())) { Tree.SpecifiedArgument sa = (Tree.SpecifiedArgument) arg; Tree.Term argTerm = sa.getSpecifierExpression() .getExpression().getTerm(); result//.append(template.substring(start,it.getStartIndex()-templateStart)) .append(Nodes.toString(argTerm, tokens) ); //start = it.getStopIndex()-templateStart+1; found=true; } } Tree.SequencedArgument seqArg = that.getNamedArgumentList().getSequencedArgument(); if (seqArg!=null && it.getDeclaration().equals(seqArg.getParameter())) { result//.append(template.substring(start,it.getStartIndex()-templateStart)) .append("{"); //start = it.getStopIndex()-templateStart+1;; boolean first=true; for (Tree.PositionalArgument pa: seqArg.getPositionalArguments()) { if (first) result.append(" "); if (!first) result.append(", "); first=false; result.append(Nodes.toString(pa, tokens)); } if (!first) result.append(" "); result.append("}"); found=true; } if (!found) { if (sequenced) { result.append("{}"); } else {} //TODO: use default value! } } public Declaration getDeclaration() { return declaration; } public void setDelete() { this.delete = !delete; } public void setJustOne() { this.justOne = !justOne; } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_refactor_InlineRefactoring.java
1,867
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() { public Boolean execute(TransactionalTaskContext context) throws TransactionException { final TransactionalMap<Object, Object> txMap = context.getMap("default"); txMap.put("3", "3"); map2.put("4", "4"); txMap.delete("1"); map2.delete("2"); assertEquals("1", map2.get("1")); assertEquals(null, txMap.get("1")); txMap.delete("2"); assertEquals(2, txMap.size()); return true; } });
0true
hazelcast_src_test_java_com_hazelcast_map_MapTransactionTest.java
637
@Component("blStatelessSessionFilter") public class StatelessSessionFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { BLCRequestUtils.setOKtoUseSession(new ServletWebRequest((HttpServletRequest) request, (HttpServletResponse) response), Boolean.FALSE); filterChain.doFilter(request, response); } }
1no label
common_src_main_java_org_broadleafcommerce_common_web_filter_StatelessSessionFilter.java
1,653
public abstract class Names { public static String randomNodeName(URL nodeNames) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(nodeNames.openStream(), Charsets.UTF_8)); int numberOfNames = 0; while (reader.readLine() != null) { numberOfNames++; } reader.close(); reader = new BufferedReader(new InputStreamReader(nodeNames.openStream(), Charsets.UTF_8)); int number = ((ThreadLocalRandom.current().nextInt(numberOfNames)) % numberOfNames); for (int i = 0; i < number; i++) { reader.readLine(); } return reader.readLine(); } catch (IOException e) { return null; } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { // ignore this exception } } } public static String randomNodeName(InputStream nodeNames) { if (nodeNames == null) { return null; } try { BufferedReader reader = new BufferedReader(new InputStreamReader(nodeNames, Charsets.UTF_8)); int numberOfNames = Integer.parseInt(reader.readLine()); int number = ((new Random().nextInt(numberOfNames)) % numberOfNames) - 2; // remove 2 for last line and first line for (int i = 0; i < number; i++) { reader.readLine(); } return reader.readLine(); } catch (Exception e) { return null; } finally { try { nodeNames.close(); } catch (IOException e) { // ignore } } } private Names() { } }
1no label
src_main_java_org_elasticsearch_common_Names.java
2,704
cluster().fullRestart(new RestartCallback() { @Override public Settings onNodeStopped(String nodeName) throws Exception { if (node_1.equals(nodeName)) { logger.info("--> deleting the data for the first node"); gateway1.reset(); } return null; } });
0true
src_test_java_org_elasticsearch_gateway_local_LocalGatewayIndexStateTests.java
1,709
public class PermissionType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, PermissionType> TYPES = new LinkedHashMap<String, PermissionType>(); public static final PermissionType READ = new PermissionType("READ", "Read"); public static final PermissionType CREATE = new PermissionType("CREATE", "Create"); public static final PermissionType UPDATE = new PermissionType("UPDATE", "Update"); public static final PermissionType DELETE = new PermissionType("DELETE", "Delete"); public static final PermissionType ALL = new PermissionType("ALL", "All"); public static final PermissionType OTHER = new PermissionType("OTHER", "Other"); public static PermissionType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public PermissionType() { //do nothing } public PermissionType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } else { throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName()); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PermissionType other = (PermissionType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_security_service_type_PermissionType.java
332
public class CommaDelimitedNodeValueMerge extends NodeValueMerge { @Override public String getDelimiter() { return ","; } @Override public String getRegEx() { return getDelimiter(); } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_CommaDelimitedNodeValueMerge.java
646
public class DeleteIndexTemplateResponse extends AcknowledgedResponse { DeleteIndexTemplateResponse() { } DeleteIndexTemplateResponse(boolean acknowledged) { super(acknowledged); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); readAcknowledged(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); writeAcknowledged(out); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_template_delete_DeleteIndexTemplateResponse.java
348
transportService.sendRequest(node, NodeShutdownRequestHandler.ACTION, new NodeShutdownRequest(request), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleResponse(TransportResponse.Empty response) { logger.trace("[cluster_shutdown]: received shutdown response from [{}]", node); latch.countDown(); } @Override public void handleException(TransportException exp) { logger.warn("[cluster_shutdown]: received failed shutdown response from [{}]", exp, node); latch.countDown(); } });
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_shutdown_TransportNodesShutdownAction.java
1,067
public class ODynamicSQLElementFactory implements OCommandExecutorSQLFactory, OQueryOperatorFactory, OSQLFunctionFactory { // Used by SQLEngine to register on the fly new elements static final Map<String, Object> FUNCTIONS = new ConcurrentHashMap<String, Object>(); static final Map<String, Class<? extends OCommandExecutorSQLAbstract>> COMMANDS = new ConcurrentHashMap<String, Class<? extends OCommandExecutorSQLAbstract>>(); static final Set<OQueryOperator> OPERATORS = Collections .synchronizedSet(new HashSet<OQueryOperator>()); public Set<String> getFunctionNames() { return FUNCTIONS.keySet(); } public boolean hasFunction(final String name) { return FUNCTIONS.containsKey(name); } public OSQLFunction createFunction(final String name) throws OCommandExecutionException { final Object obj = FUNCTIONS.get(name); if (obj == null) { throw new OCommandExecutionException("Unknowned function name :" + name); } if (obj instanceof OSQLFunction) { return (OSQLFunction) obj; } else { // it's a class final Class<?> clazz = (Class<?>) obj; try { return (OSQLFunction) clazz.newInstance(); } catch (Exception e) { throw new OCommandExecutionException("Error in creation of function " + name + "(). Probably there is not an empty constructor or the constructor generates errors", e); } } } public Set<String> getCommandNames() { return COMMANDS.keySet(); } public OCommandExecutorSQLAbstract createCommand(final String name) throws OCommandExecutionException { final Class<? extends OCommandExecutorSQLAbstract> clazz = COMMANDS.get(name); if (clazz == null) throw new OCommandExecutionException("Unknowned command name :" + name); try { return clazz.newInstance(); } catch (Exception e) { throw new OCommandExecutionException("Error in creation of command " + name + "(). Probably there is not an empty constructor or the constructor generates errors", e); } } public Set<OQueryOperator> getOperators() { return OPERATORS; } }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_ODynamicSQLElementFactory.java
78
public enum Cmp implements TitanPredicate { EQUAL { @Override public boolean isValidValueType(Class<?> clazz) { return true; } @Override public boolean isValidCondition(Object condition) { return true; } @Override public boolean evaluate(Object value, Object condition) { if (condition==null) { return value==null; } else { return condition.equals(value); } } @Override public String toString() { return "="; } @Override public TitanPredicate negate() { return NOT_EQUAL; } }, NOT_EQUAL { @Override public boolean isValidValueType(Class<?> clazz) { return true; } @Override public boolean isValidCondition(Object condition) { return true; } @Override public boolean evaluate(Object value, Object condition) { if (condition==null) { return value!=null; } else { return !condition.equals(value); } } @Override public String toString() { return "<>"; } @Override public TitanPredicate negate() { return EQUAL; } }, LESS_THAN { @Override public boolean isValidValueType(Class<?> clazz) { Preconditions.checkNotNull(clazz); return Comparable.class.isAssignableFrom(clazz); } @Override public boolean isValidCondition(Object condition) { return condition!=null && condition instanceof Comparable; } @Override public boolean evaluate(Object value, Object condition) { Integer cmp = AttributeUtil.compare(value,condition); return cmp!=null?cmp<0:false; } @Override public String toString() { return "<"; } @Override public TitanPredicate negate() { return GREATER_THAN_EQUAL; } }, LESS_THAN_EQUAL { @Override public boolean isValidValueType(Class<?> clazz) { Preconditions.checkNotNull(clazz); return Comparable.class.isAssignableFrom(clazz); } @Override public boolean isValidCondition(Object condition) { return condition!=null && condition instanceof Comparable; } @Override public boolean evaluate(Object value, Object condition) { Integer cmp = AttributeUtil.compare(value,condition); return cmp!=null?cmp<=0:false; } @Override public String toString() { return "<="; } @Override public TitanPredicate negate() { return GREATER_THAN; } }, GREATER_THAN { @Override public boolean isValidValueType(Class<?> clazz) { Preconditions.checkNotNull(clazz); return Comparable.class.isAssignableFrom(clazz); } @Override public boolean isValidCondition(Object condition) { return condition!=null && condition instanceof Comparable; } @Override public boolean evaluate(Object value, Object condition) { Integer cmp = AttributeUtil.compare(value,condition); return cmp!=null?cmp>0:false; } @Override public String toString() { return ">"; } @Override public TitanPredicate negate() { return LESS_THAN_EQUAL; } }, GREATER_THAN_EQUAL { @Override public boolean isValidValueType(Class<?> clazz) { Preconditions.checkNotNull(clazz); return Comparable.class.isAssignableFrom(clazz); } @Override public boolean isValidCondition(Object condition) { return condition!=null && condition instanceof Comparable; } @Override public boolean evaluate(Object value, Object condition) { Integer cmp = AttributeUtil.compare(value,condition); return cmp!=null?cmp>=0:false; } @Override public String toString() { return ">="; } @Override public TitanPredicate negate() { return LESS_THAN; } }; @Override public boolean hasNegation() { return true; } @Override public boolean isQNF() { return true; } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java
709
public class OWOWCache { public static final String NAME_ID_MAP_EXTENSION = ".cm"; private static final String NAME_ID_MAP = "name_id_map" + NAME_ID_MAP_EXTENSION; public static final int MIN_CACHE_SIZE = 16; public static final long MAGIC_NUMBER = 0xFACB03FEL; private final ConcurrentSkipListMap<GroupKey, WriteGroup> writeGroups = new ConcurrentSkipListMap<GroupKey, WriteGroup>(); private Map<String, Long> nameIdMap; private RandomAccessFile nameIdMapHolder; private final Map<Long, OFileClassic> files; private final boolean syncOnPageFlush; private final int pageSize; private final long groupTTL; private final OWriteAheadLog writeAheadLog; private final AtomicInteger cacheSize = new AtomicInteger(); private final OLockManager<GroupKey, Thread> lockManager = new OLockManager<GroupKey, Thread>( true, OGlobalConfiguration.DISK_WRITE_CACHE_FLUSH_LOCK_TIMEOUT .getValueAsInteger()); private volatile int cacheMaxSize; private final OStorageLocalAbstract storageLocal; private final Object syncObject = new Object(); private long fileCounter = 0; private GroupKey lastGroupKey = new GroupKey(0, -1); private final ScheduledExecutorService commitExecutor = Executors .newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); thread.setName("Write Cache Flush Task"); return thread; } }); private File nameIdMapHolderFile; public OWOWCache(boolean syncOnPageFlush, int pageSize, long groupTTL, OWriteAheadLog writeAheadLog, long pageFlushInterval, int cacheMaxSize, OStorageLocalAbstract storageLocal, boolean checkMinSize) { this.files = new ConcurrentHashMap<Long, OFileClassic>(); this.syncOnPageFlush = syncOnPageFlush; this.pageSize = pageSize; this.groupTTL = groupTTL; this.writeAheadLog = writeAheadLog; this.cacheMaxSize = cacheMaxSize; this.storageLocal = storageLocal; if (checkMinSize && this.cacheMaxSize < MIN_CACHE_SIZE) this.cacheMaxSize = MIN_CACHE_SIZE; if (pageFlushInterval > 0) commitExecutor.scheduleWithFixedDelay(new PeriodicFlushTask(), pageFlushInterval, pageFlushInterval, TimeUnit.MILLISECONDS); } public long openFile(String fileName) throws IOException { synchronized (syncObject) { initNameIdMapping(); Long fileId = nameIdMap.get(fileName); OFileClassic fileClassic; if (fileId == null) fileClassic = null; else fileClassic = files.get(fileId); if (fileClassic == null) { fileId = ++fileCounter; fileClassic = createFile(fileName); files.put(fileId, fileClassic); nameIdMap.put(fileName, fileId); writeNameIdEntry(new NameFileIdEntry(fileName, fileId), true); } openFile(fileClassic); return fileId; } } private void openFile(OFileClassic fileClassic) throws IOException { if (fileClassic.exists()) { if (!fileClassic.isOpen()) fileClassic.open(); } else fileClassic.create(-1); } private void initNameIdMapping() throws IOException { if (nameIdMapHolder == null) { final File storagePath = new File(storageLocal.getStoragePath()); if (!storagePath.exists()) if (!storagePath.mkdirs()) throw new OStorageException("Can not create directories for the path " + storagePath); nameIdMapHolderFile = new File(storagePath, NAME_ID_MAP); nameIdMapHolder = new RandomAccessFile(nameIdMapHolderFile, "rw"); readNameIdMap(); } } private OFileClassic createFile(String fileName) { OFileClassic fileClassic = new OFileClassic(); String path = storageLocal.getVariableParser().resolveVariables(storageLocal.getStoragePath() + File.separator + fileName); fileClassic.init(path, storageLocal.getMode()); return fileClassic; } public void openFile(long fileId) throws IOException { synchronized (syncObject) { initNameIdMapping(); final OFileClassic fileClassic = files.get(fileId); if (fileClassic == null) throw new OStorageException("File with id " + fileId + " does not exist."); openFile(fileClassic); } } public boolean exists(String fileName) { synchronized (syncObject) { if (nameIdMap != null && nameIdMap.containsKey(fileName)) return true; final File file = new File(storageLocal.getVariableParser().resolveVariables( storageLocal.getStoragePath() + File.separator + fileName)); return file.exists(); } } private void readNameIdMap() throws IOException { nameIdMap = new HashMap<String, Long>(); long localFileCounter = -1; nameIdMapHolder.seek(0); NameFileIdEntry nameFileIdEntry; while ((nameFileIdEntry = readNextNameIdEntry()) != null) { if (localFileCounter < nameFileIdEntry.fileId) localFileCounter = nameFileIdEntry.fileId; if (nameFileIdEntry.fileId >= 0) nameIdMap.put(nameFileIdEntry.name, nameFileIdEntry.fileId); else nameIdMap.remove(nameFileIdEntry.name); } if (localFileCounter > 0) fileCounter = localFileCounter; for (Map.Entry<String, Long> nameIdEntry : nameIdMap.entrySet()) { if (!files.containsKey(nameIdEntry.getValue())) { OFileClassic fileClassic = createFile(nameIdEntry.getKey()); files.put(nameIdEntry.getValue(), fileClassic); } } } private NameFileIdEntry readNextNameIdEntry() throws IOException { try { final int nameSize = nameIdMapHolder.readInt(); byte[] serializedName = new byte[nameSize]; nameIdMapHolder.readFully(serializedName); final String name = OStringSerializer.INSTANCE.deserialize(serializedName, 0); final long fileId = nameIdMapHolder.readLong(); return new NameFileIdEntry(name, fileId); } catch (EOFException eof) { return null; } } private void writeNameIdEntry(NameFileIdEntry nameFileIdEntry, boolean sync) throws IOException { nameIdMapHolder.seek(nameIdMapHolder.length()); final int nameSize = OStringSerializer.INSTANCE.getObjectSize(nameFileIdEntry.name); byte[] serializedName = new byte[nameSize]; OStringSerializer.INSTANCE.serialize(nameFileIdEntry.name, serializedName, 0); nameIdMapHolder.writeInt(nameSize); nameIdMapHolder.write(serializedName); nameIdMapHolder.writeLong(nameFileIdEntry.fileId); if (sync) nameIdMapHolder.getFD().sync(); } public Future store(final long fileId, final long pageIndex, final OCachePointer dataPointer) { Future future = null; synchronized (syncObject) { final GroupKey groupKey = new GroupKey(fileId, pageIndex >>> 4); lockManager.acquireLock(Thread.currentThread(), groupKey, OLockManager.LOCK.EXCLUSIVE); try { WriteGroup writeGroup = writeGroups.get(groupKey); if (writeGroup == null) { writeGroup = new WriteGroup(System.currentTimeMillis()); writeGroups.put(groupKey, writeGroup); } int entryIndex = (int) (pageIndex & 15); if (writeGroup.pages[entryIndex] == null) { dataPointer.incrementReferrer(); writeGroup.pages[entryIndex] = dataPointer; cacheSize.incrementAndGet(); } else { if (!writeGroup.pages[entryIndex].equals(dataPointer)) { writeGroup.pages[entryIndex].decrementReferrer(); dataPointer.incrementReferrer(); writeGroup.pages[entryIndex] = dataPointer; } } writeGroup.recencyBit = true; } finally { lockManager.releaseLock(Thread.currentThread(), groupKey, OLockManager.LOCK.EXCLUSIVE); } if (cacheSize.get() > cacheMaxSize) { future = commitExecutor.submit(new PeriodicFlushTask()); } return future; } } public OCachePointer load(long fileId, long pageIndex) throws IOException { synchronized (syncObject) { final GroupKey groupKey = new GroupKey(fileId, pageIndex >>> 4); lockManager.acquireLock(Thread.currentThread(), groupKey, OLockManager.LOCK.SHARED); try { final WriteGroup writeGroup = writeGroups.get(groupKey); OCachePointer pagePointer; if (writeGroup == null) { pagePointer = cacheFileContent(fileId, pageIndex); pagePointer.incrementReferrer(); return pagePointer; } final int entryIndex = (int) (pageIndex & 15); pagePointer = writeGroup.pages[entryIndex]; if (pagePointer == null) pagePointer = cacheFileContent(fileId, pageIndex); pagePointer.incrementReferrer(); return pagePointer; } finally { lockManager.releaseLock(Thread.currentThread(), groupKey, OLockManager.LOCK.SHARED); } } } public void flush(long fileId) { final Future<Void> future = commitExecutor.submit(new FileFlushTask(fileId)); try { future.get(); } catch (InterruptedException e) { Thread.interrupted(); throw new OException("File flush was interrupted", e); } catch (Exception e) { throw new OException("File flush was abnormally terminated", e); } } public void flush() { for (long fileId : files.keySet()) flush(fileId); } public long getFilledUpTo(long fileId) throws IOException { synchronized (syncObject) { return files.get(fileId).getFilledUpTo() / pageSize; } } public void forceSyncStoredChanges() throws IOException { synchronized (syncObject) { for (OFileClassic fileClassic : files.values()) fileClassic.synch(); } } public boolean isOpen(long fileId) { synchronized (syncObject) { OFileClassic fileClassic = files.get(fileId); if (fileClassic != null) return fileClassic.isOpen(); return false; } } public long isOpen(String fileName) throws IOException { synchronized (syncObject) { initNameIdMapping(); final Long fileId = nameIdMap.get(fileName); if (fileId == null) return -1; final OFileClassic fileClassic = files.get(fileId); if (fileClassic == null || !fileClassic.isOpen()) return -1; return fileId; } } public void setSoftlyClosed(long fileId, boolean softlyClosed) throws IOException { synchronized (syncObject) { OFileClassic fileClassic = files.get(fileId); if (fileClassic != null && fileClassic.isOpen()) fileClassic.setSoftlyClosed(softlyClosed); } } public void setSoftlyClosed(boolean softlyClosed) throws IOException { synchronized (syncObject) { for (long fileId : files.keySet()) setSoftlyClosed(fileId, softlyClosed); } } public boolean wasSoftlyClosed(long fileId) throws IOException { synchronized (syncObject) { OFileClassic fileClassic = files.get(fileId); if (fileClassic == null) return false; return fileClassic.wasSoftlyClosed(); } } public void deleteFile(long fileId) throws IOException { synchronized (syncObject) { final String name = doDeleteFile(fileId); if (name != null) { nameIdMap.remove(name); writeNameIdEntry(new NameFileIdEntry(name, -1), true); } } } private String doDeleteFile(long fileId) throws IOException { if (isOpen(fileId)) truncateFile(fileId); final OFileClassic fileClassic = files.remove(fileId); String name = null; if (fileClassic != null) { name = fileClassic.getName(); if (fileClassic.exists()) fileClassic.delete(); } return name; } public void truncateFile(long fileId) throws IOException { synchronized (syncObject) { removeCachedPages(fileId); files.get(fileId).shrink(0); } } public void renameFile(long fileId, String oldFileName, String newFileName) throws IOException { synchronized (syncObject) { if (!files.containsKey(fileId)) return; final OFileClassic file = files.get(fileId); final String osFileName = file.getName(); if (osFileName.startsWith(oldFileName)) { final File newFile = new File(storageLocal.getStoragePath() + File.separator + newFileName + osFileName.substring(osFileName.lastIndexOf(oldFileName) + oldFileName.length())); boolean renamed = file.renameTo(newFile); while (!renamed) { OMemoryWatchDog.freeMemoryForResourceCleanup(100); renamed = file.renameTo(newFile); } } writeNameIdEntry(new NameFileIdEntry(oldFileName, -1), false); writeNameIdEntry(new NameFileIdEntry(newFileName, fileId), true); nameIdMap.remove(oldFileName); nameIdMap.put(newFileName, fileId); } } public void close() throws IOException { flush(); if (!commitExecutor.isShutdown()) { commitExecutor.shutdown(); try { if (!commitExecutor.awaitTermination(5, TimeUnit.MINUTES)) throw new OException("Background data flush task can not be stopped."); } catch (InterruptedException e) { OLogManager.instance().error(this, "Data flush thread was interrupted"); Thread.interrupted(); throw new OException("Data flush thread was interrupted", e); } } synchronized (syncObject) { for (OFileClassic fileClassic : files.values()) { if (fileClassic.isOpen()) fileClassic.close(); } if (nameIdMapHolder != null) { nameIdMapHolder.setLength(0); for (Map.Entry<String, Long> entry : nameIdMap.entrySet()) { writeNameIdEntry(new NameFileIdEntry(entry.getKey(), entry.getValue()), false); } nameIdMapHolder.getFD().sync(); nameIdMapHolder.close(); } } } public Set<ODirtyPage> logDirtyPagesTable() throws IOException { synchronized (syncObject) { if (writeAheadLog == null) return Collections.emptySet(); Set<ODirtyPage> logDirtyPages = new HashSet<ODirtyPage>(writeGroups.size() * 16); for (Map.Entry<GroupKey, WriteGroup> writeGroupEntry : writeGroups.entrySet()) { final GroupKey groupKey = writeGroupEntry.getKey(); final WriteGroup writeGroup = writeGroupEntry.getValue(); for (int i = 0; i < 16; i++) { final OCachePointer cachePointer = writeGroup.pages[i]; if (cachePointer != null) { final OLogSequenceNumber lastFlushedLSN = cachePointer.getLastFlushedLsn(); final String fileName = files.get(groupKey.fileId).getName(); final long pageIndex = (groupKey.groupIndex << 4) + i; final ODirtyPage logDirtyPage = new ODirtyPage(fileName, pageIndex, lastFlushedLSN); logDirtyPages.add(logDirtyPage); } } } writeAheadLog.logDirtyPages(logDirtyPages); return logDirtyPages; } } private void removeCachedPages(long fileId) { Future<Void> future = commitExecutor.submit(new RemoveFilePagesTask(fileId)); try { future.get(); } catch (InterruptedException e) { Thread.interrupted(); throw new OException("File data removal was interrupted", e); } catch (Exception e) { throw new OException("File data removal was abnormally terminated", e); } } private OCachePointer cacheFileContent(long fileId, long pageIndex) throws IOException { final long startPosition = pageIndex * pageSize; final long endPosition = startPosition + pageSize; byte[] content = new byte[pageSize]; OCachePointer dataPointer; final OFileClassic fileClassic = files.get(fileId); if (fileClassic.getFilledUpTo() >= endPosition) { fileClassic.read(startPosition, content, content.length); final ODirectMemoryPointer pointer = new ODirectMemoryPointer(content); final OLogSequenceNumber storedLSN = ODurablePage.getLogSequenceNumberFromPage(pointer); dataPointer = new OCachePointer(pointer, storedLSN); } else { fileClassic.allocateSpace((int) (endPosition - fileClassic.getFilledUpTo())); final ODirectMemoryPointer pointer = new ODirectMemoryPointer(content); dataPointer = new OCachePointer(pointer, new OLogSequenceNumber(0, -1)); } return dataPointer; } private void flushPage(long fileId, long pageIndex, ODirectMemoryPointer dataPointer) throws IOException { if (writeAheadLog != null) { OLogSequenceNumber lsn = ODurablePage.getLogSequenceNumberFromPage(dataPointer); OLogSequenceNumber flushedLSN = writeAheadLog.getFlushedLSN(); if (flushedLSN == null || flushedLSN.compareTo(lsn) < 0) writeAheadLog.flush(); } final byte[] content = dataPointer.get(0, pageSize); OLongSerializer.INSTANCE.serializeNative(MAGIC_NUMBER, content, 0); final int crc32 = calculatePageCrc(content); OIntegerSerializer.INSTANCE.serializeNative(crc32, content, OLongSerializer.LONG_SIZE); final OFileClassic fileClassic = files.get(fileId); fileClassic.write(pageIndex * pageSize, content); if (syncOnPageFlush) fileClassic.synch(); } private static int calculatePageCrc(byte[] pageData) { int systemSize = OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE; final CRC32 crc32 = new CRC32(); crc32.update(pageData, systemSize, pageData.length - systemSize); return (int) crc32.getValue(); } public void close(long fileId, boolean flush) throws IOException { synchronized (syncObject) { if (flush) flush(fileId); else removeCachedPages(fileId); files.get(fileId).close(); } } public OPageDataVerificationError[] checkStoredPages(OCommandOutputListener commandOutputListener) { final int notificationTimeOut = 5000; final List<OPageDataVerificationError> errors = new ArrayList<OPageDataVerificationError>(); synchronized (syncObject) { for (long fileId : files.keySet()) { OFileClassic fileClassic = files.get(fileId); boolean fileIsCorrect; try { if (commandOutputListener != null) commandOutputListener.onMessage("Flashing file " + fileClassic.getName() + "... "); flush(fileId); if (commandOutputListener != null) commandOutputListener.onMessage("Start verification of content of " + fileClassic.getName() + "file ..."); long time = System.currentTimeMillis(); long filledUpTo = fileClassic.getFilledUpTo(); fileIsCorrect = true; for (long pos = 0; pos < filledUpTo; pos += pageSize) { boolean checkSumIncorrect = false; boolean magicNumberIncorrect = false; byte[] data = new byte[pageSize]; fileClassic.read(pos, data, data.length); long magicNumber = OLongSerializer.INSTANCE.deserializeNative(data, 0); if (magicNumber != MAGIC_NUMBER) { magicNumberIncorrect = true; if (commandOutputListener != null) commandOutputListener.onMessage("Error: Magic number for page " + (pos / pageSize) + " in file " + fileClassic.getName() + " does not much !!!"); fileIsCorrect = false; } final int storedCRC32 = OIntegerSerializer.INSTANCE.deserializeNative(data, OLongSerializer.LONG_SIZE); final int calculatedCRC32 = calculatePageCrc(data); if (storedCRC32 != calculatedCRC32) { checkSumIncorrect = true; if (commandOutputListener != null) commandOutputListener.onMessage("Error: Checksum for page " + (pos / pageSize) + " in file " + fileClassic.getName() + " is incorrect !!!"); fileIsCorrect = false; } if (magicNumberIncorrect || checkSumIncorrect) errors.add(new OPageDataVerificationError(magicNumberIncorrect, checkSumIncorrect, pos / pageSize, fileClassic .getName())); if (commandOutputListener != null && System.currentTimeMillis() - time > notificationTimeOut) { time = notificationTimeOut; commandOutputListener.onMessage((pos / pageSize) + " pages were processed ..."); } } } catch (IOException ioe) { if (commandOutputListener != null) commandOutputListener.onMessage("Error: Error during processing of file " + fileClassic.getName() + ". " + ioe.getMessage()); fileIsCorrect = false; } if (!fileIsCorrect) { if (commandOutputListener != null) commandOutputListener.onMessage("Verification of file " + fileClassic.getName() + " is finished with errors."); } else { if (commandOutputListener != null) commandOutputListener.onMessage("Verification of file " + fileClassic.getName() + " is successfully finished."); } } return errors.toArray(new OPageDataVerificationError[errors.size()]); } } public void delete() throws IOException { synchronized (syncObject) { for (long fileId : files.keySet()) doDeleteFile(fileId); if (nameIdMapHolderFile != null) { nameIdMapHolder.close(); if (!nameIdMapHolderFile.delete()) throw new OStorageException("Can not delete disk cache file which contains name-id mapping."); } } } public String fileNameById(long fileId) { synchronized (syncObject) { return files.get(fileId).getName(); } } private final class GroupKey implements Comparable<GroupKey> { private final long fileId; private final long groupIndex; private GroupKey(long fileId, long groupIndex) { this.fileId = fileId; this.groupIndex = groupIndex; } @Override public int compareTo(GroupKey other) { if (fileId > other.fileId) return 1; if (fileId < other.fileId) return -1; if (groupIndex > other.groupIndex) return 1; if (groupIndex < other.groupIndex) return -1; return 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GroupKey groupKey = (GroupKey) o; if (fileId != groupKey.fileId) return false; if (groupIndex != groupKey.groupIndex) return false; return true; } @Override public int hashCode() { int result = (int) (fileId ^ (fileId >>> 32)); result = 31 * result + (int) (groupIndex ^ (groupIndex >>> 32)); return result; } @Override public String toString() { return "GroupKey{" + "fileId=" + fileId + ", groupIndex=" + groupIndex + '}'; } } private final class PeriodicFlushTask implements Runnable { @Override public void run() { try { if (writeGroups.isEmpty()) return; int writeGroupsToFlush; boolean useForceSync = false; double threshold = ((double) cacheSize.get()) / cacheMaxSize; if (threshold > 0.8) { writeGroupsToFlush = (int) (0.2 * writeGroups.size()); useForceSync = true; } else if (threshold > 0.9) { writeGroupsToFlush = (int) (0.4 * writeGroups.size()); useForceSync = true; } else writeGroupsToFlush = 1; if (writeGroupsToFlush < 1) writeGroupsToFlush = 1; int flushedGroups = 0; flushedGroups = flushRing(writeGroupsToFlush, flushedGroups, false); if (flushedGroups < writeGroupsToFlush && useForceSync) flushedGroups = flushRing(writeGroupsToFlush, flushedGroups, true); if (flushedGroups < writeGroupsToFlush && cacheSize.get() > cacheMaxSize) { if (OGlobalConfiguration.SERVER_CACHE_INCREASE_ON_DEMAND.getValueAsBoolean()) { final long oldCacheMaxSize = cacheMaxSize; cacheMaxSize = (int) Math.ceil(cacheMaxSize * (1 + OGlobalConfiguration.SERVER_CACHE_INCREASE_STEP.getValueAsFloat())); OLogManager.instance().warn(this, "Write cache size is increased from %d to %d", oldCacheMaxSize, cacheMaxSize); } else { throw new OAllCacheEntriesAreUsedException("All records in write cache are used!"); } } } catch (Exception e) { OLogManager.instance().error(this, "Exception during data flush.", e); } } private int flushRing(int writeGroupsToFlush, int flushedGroups, boolean forceFlush) throws IOException { NavigableMap<GroupKey, WriteGroup> subMap = writeGroups.tailMap(lastGroupKey, false); if (!subMap.isEmpty()) { flushedGroups = iterateBySubRing(subMap, writeGroupsToFlush, 0, forceFlush); if (flushedGroups < writeGroupsToFlush) { if (!subMap.isEmpty()) { subMap = writeGroups.headMap(subMap.firstKey(), false); flushedGroups = iterateBySubRing(subMap, writeGroupsToFlush, flushedGroups, forceFlush); } } } else flushedGroups = iterateBySubRing(writeGroups, writeGroupsToFlush, flushedGroups, forceFlush); return flushedGroups; } private int iterateBySubRing(NavigableMap<GroupKey, WriteGroup> subMap, int writeGroupsToFlush, int flushedWriteGroups, boolean forceFlush) throws IOException { Iterator<Map.Entry<GroupKey, WriteGroup>> entriesIterator = subMap.entrySet().iterator(); long currentTime = System.currentTimeMillis(); groupsLoop: while (entriesIterator.hasNext() && flushedWriteGroups < writeGroupsToFlush) { Map.Entry<GroupKey, WriteGroup> entry = entriesIterator.next(); final WriteGroup group = entry.getValue(); final GroupKey groupKey = entry.getKey(); final boolean weakLockMode = group.creationTime - currentTime < groupTTL && !forceFlush; if (group.recencyBit && weakLockMode) { group.recencyBit = false; continue; } lockManager.acquireLock(Thread.currentThread(), entry.getKey(), OLockManager.LOCK.EXCLUSIVE); try { if (group.recencyBit && weakLockMode) group.recencyBit = false; else { group.recencyBit = false; int flushedPages = 0; for (int i = 0; i < 16; i++) { final OCachePointer pagePointer = group.pages[i]; if (pagePointer != null) { if (!pagePointer.tryAcquireExclusiveLock()) continue groupsLoop; try { flushPage(groupKey.fileId, (groupKey.groupIndex << 4) + i, pagePointer.getDataPointer()); flushedPages++; final OLogSequenceNumber flushedLSN = ODurablePage.getLogSequenceNumberFromPage(pagePointer.getDataPointer()); pagePointer.setLastFlushedLsn(flushedLSN); } finally { pagePointer.releaseExclusiveLock(); } } } for (OCachePointer pagePointer : group.pages) if (pagePointer != null) pagePointer.decrementReferrer(); entriesIterator.remove(); flushedWriteGroups++; cacheSize.addAndGet(-flushedPages); } } finally { lockManager.releaseLock(Thread.currentThread(), entry.getKey(), OLockManager.LOCK.EXCLUSIVE); } lastGroupKey = groupKey; } return flushedWriteGroups; } } private final class FileFlushTask implements Callable<Void> { private final long fileId; private FileFlushTask(long fileId) { this.fileId = fileId; } @Override public Void call() throws Exception { final GroupKey firstKey = new GroupKey(fileId, 0); final GroupKey lastKey = new GroupKey(fileId, Long.MAX_VALUE); NavigableMap<GroupKey, WriteGroup> subMap = writeGroups.subMap(firstKey, true, lastKey, true); Iterator<Map.Entry<GroupKey, WriteGroup>> entryIterator = subMap.entrySet().iterator(); groupsLoop: while (entryIterator.hasNext()) { Map.Entry<GroupKey, WriteGroup> entry = entryIterator.next(); final WriteGroup writeGroup = entry.getValue(); final GroupKey groupKey = entry.getKey(); lockManager.acquireLock(Thread.currentThread(), groupKey, OLockManager.LOCK.EXCLUSIVE); try { int flushedPages = 0; for (int i = 0; i < 16; i++) { OCachePointer pagePointer = writeGroup.pages[i]; if (pagePointer != null) { if (!pagePointer.tryAcquireExclusiveLock()) continue groupsLoop; try { flushPage(groupKey.fileId, (groupKey.groupIndex << 4) + i, pagePointer.getDataPointer()); flushedPages++; } finally { pagePointer.releaseExclusiveLock(); } } } for (OCachePointer pagePointer : writeGroup.pages) if (pagePointer != null) pagePointer.decrementReferrer(); cacheSize.addAndGet(-flushedPages); entryIterator.remove(); } finally { lockManager.releaseLock(Thread.currentThread(), entry.getKey(), OLockManager.LOCK.EXCLUSIVE); } } files.get(fileId).synch(); return null; } } private final class RemoveFilePagesTask implements Callable<Void> { private final long fileId; private RemoveFilePagesTask(long fileId) { this.fileId = fileId; } @Override public Void call() throws Exception { final GroupKey firstKey = new GroupKey(fileId, 0); final GroupKey lastKey = new GroupKey(fileId, Long.MAX_VALUE); NavigableMap<GroupKey, WriteGroup> subMap = writeGroups.subMap(firstKey, true, lastKey, true); Iterator<Map.Entry<GroupKey, WriteGroup>> entryIterator = subMap.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<GroupKey, WriteGroup> entry = entryIterator.next(); WriteGroup writeGroup = entry.getValue(); GroupKey groupKey = entry.getKey(); lockManager.acquireLock(Thread.currentThread(), groupKey, OLockManager.LOCK.EXCLUSIVE); try { for (OCachePointer pagePointer : writeGroup.pages) { if (pagePointer != null) { pagePointer.acquireExclusiveLock(); try { pagePointer.decrementReferrer(); cacheSize.decrementAndGet(); } finally { pagePointer.releaseExclusiveLock(); } } } entryIterator.remove(); } finally { lockManager.releaseLock(Thread.currentThread(), groupKey, OLockManager.LOCK.EXCLUSIVE); } } return null; } } private static final class NameFileIdEntry { private final String name; private final long fileId; private NameFileIdEntry(String name, long fileId) { this.name = name; this.fileId = fileId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NameFileIdEntry that = (NameFileIdEntry) o; if (fileId != that.fileId) return false; if (!name.equals(that.name)) return false; return true; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + (int) (fileId ^ (fileId >>> 32)); return result; } } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_cache_OWOWCache.java
4,754
public class RestController extends AbstractLifecycleComponent<RestController> { private final PathTrie<RestHandler> getHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final PathTrie<RestHandler> postHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final PathTrie<RestHandler> putHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final PathTrie<RestHandler> deleteHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final PathTrie<RestHandler> headHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final PathTrie<RestHandler> optionsHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final RestHandlerFilter handlerFilter = new RestHandlerFilter(); // non volatile since the assumption is that pre processors are registered on startup private RestFilter[] filters = new RestFilter[0]; @Inject public RestController(Settings settings) { super(settings); } @Override protected void doStart() throws ElasticsearchException { } @Override protected void doStop() throws ElasticsearchException { } @Override protected void doClose() throws ElasticsearchException { for (RestFilter filter : filters) { filter.close(); } } /** * Registers a pre processor to be executed before the rest request is actually handled. */ public synchronized void registerFilter(RestFilter preProcessor) { RestFilter[] copy = new RestFilter[filters.length + 1]; System.arraycopy(filters, 0, copy, 0, filters.length); copy[filters.length] = preProcessor; Arrays.sort(copy, new Comparator<RestFilter>() { @Override public int compare(RestFilter o1, RestFilter o2) { return o2.order() - o1.order(); } }); filters = copy; } /** * Registers a rest handler to be execute when the provided method and path match the request. */ public void registerHandler(RestRequest.Method method, String path, RestHandler handler) { switch (method) { case GET: getHandlers.insert(path, handler); break; case DELETE: deleteHandlers.insert(path, handler); break; case POST: postHandlers.insert(path, handler); break; case PUT: putHandlers.insert(path, handler); break; case OPTIONS: optionsHandlers.insert(path, handler); break; case HEAD: headHandlers.insert(path, handler); break; default: throw new ElasticsearchIllegalArgumentException("Can't handle [" + method + "] for path [" + path + "]"); } } /** * Returns a filter chain (if needed) to execute. If this method returns null, simply execute * as usual. */ @Nullable public RestFilterChain filterChainOrNull(RestFilter executionFilter) { if (filters.length == 0) { return null; } return new ControllerFilterChain(executionFilter); } /** * Returns a filter chain with the final filter being the provided filter. */ public RestFilterChain filterChain(RestFilter executionFilter) { return new ControllerFilterChain(executionFilter); } public void dispatchRequest(final RestRequest request, final RestChannel channel) { if (filters.length == 0) { try { executeHandler(request, channel); } catch (Exception e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response for uri [" + request.uri() + "]", e1); } } } else { ControllerFilterChain filterChain = new ControllerFilterChain(handlerFilter); filterChain.continueProcessing(request, channel); } } void executeHandler(RestRequest request, RestChannel channel) { final RestHandler handler = getHandler(request); if (handler != null) { handler.handleRequest(request, channel); } else { if (request.method() == RestRequest.Method.OPTIONS) { // when we have OPTIONS request, simply send OK by default (with the Access Control Origin header which gets automatically added) StringRestResponse response = new StringRestResponse(OK); channel.sendResponse(response); } else { channel.sendResponse(new StringRestResponse(BAD_REQUEST, "No handler found for uri [" + request.uri() + "] and method [" + request.method() + "]")); } } } private RestHandler getHandler(RestRequest request) { String path = getPath(request); RestRequest.Method method = request.method(); if (method == RestRequest.Method.GET) { return getHandlers.retrieve(path, request.params()); } else if (method == RestRequest.Method.POST) { return postHandlers.retrieve(path, request.params()); } else if (method == RestRequest.Method.PUT) { return putHandlers.retrieve(path, request.params()); } else if (method == RestRequest.Method.DELETE) { return deleteHandlers.retrieve(path, request.params()); } else if (method == RestRequest.Method.HEAD) { return headHandlers.retrieve(path, request.params()); } else if (method == RestRequest.Method.OPTIONS) { return optionsHandlers.retrieve(path, request.params()); } else { return null; } } private String getPath(RestRequest request) { // we use rawPath since we don't want to decode it while processing the path resolution // so we can handle things like: // my_index/my_type/http%3A%2F%2Fwww.google.com return request.rawPath(); } class ControllerFilterChain implements RestFilterChain { private final RestFilter executionFilter; private volatile int index; ControllerFilterChain(RestFilter executionFilter) { this.executionFilter = executionFilter; } @Override public void continueProcessing(RestRequest request, RestChannel channel) { try { int loc = index; index++; if (loc > filters.length) { throw new ElasticsearchIllegalStateException("filter continueProcessing was called more than expected"); } else if (loc == filters.length) { executionFilter.process(request, channel, this); } else { RestFilter preProcessor = filters[loc]; preProcessor.process(request, channel, this); } } catch (Exception e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response for uri [" + request.uri() + "]", e1); } } } } class RestHandlerFilter extends RestFilter { @Override public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) { executeHandler(request, channel); } } }
1no label
src_main_java_org_elasticsearch_rest_RestController.java
2,400
public final class BigFloatArrayList extends AbstractBigArray { /** * Default page size, 16KB of memory per page. */ private static final int DEFAULT_PAGE_SIZE = 1 << 12; private float[][] pages; public BigFloatArrayList(int pageSize, long initialCapacity) { super(pageSize, null, true); pages = new float[numPages(initialCapacity)][]; } public BigFloatArrayList(long initialCapacity) { this(DEFAULT_PAGE_SIZE, initialCapacity); } public BigFloatArrayList() { this(1024); } public float get(long index) { assert index >= 0 && index < size; final int pageIndex = pageIndex(index); final int indexInPage = indexInPage(index); return pages[pageIndex][indexInPage]; } public void add(float f) { final int pageIndex = pageIndex(size); pages = ArrayUtil.grow(pages, pageIndex + 1); if (pages[pageIndex] == null) { pages[pageIndex] = new float[pageSize()]; } final int indexInPage = indexInPage(size); pages[pageIndex][indexInPage] = f; ++size; } @Override protected int numBytesPerElement() { return RamUsageEstimator.NUM_BYTES_FLOAT; } }
0true
src_main_java_org_elasticsearch_common_util_BigFloatArrayList.java
310
private abstract class Processor extends Visitor implements NaturalVisitor {}
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_TerminateStatementAction.java
5,228
public static class Bucket implements Histogram.Bucket { long key; long docCount; InternalAggregations aggregations; public Bucket(long key, long docCount, InternalAggregations aggregations) { this.key = key; this.docCount = docCount; this.aggregations = aggregations; } @Override public String getKey() { return String.valueOf(key); } @Override public Text getKeyAsText() { return new StringText(getKey()); } @Override public Number getKeyAsNumber() { return key; } @Override public long getDocCount() { return docCount; } @Override public Aggregations getAggregations() { return aggregations; } <B extends Bucket> B reduce(List<B> buckets, CacheRecycler cacheRecycler) { if (buckets.size() == 1) { // we only need to reduce the sub aggregations Bucket bucket = buckets.get(0); bucket.aggregations.reduce(cacheRecycler); return (B) bucket; } List<InternalAggregations> aggregations = new ArrayList<InternalAggregations>(buckets.size()); Bucket reduced = null; for (Bucket bucket : buckets) { if (reduced == null) { reduced = bucket; } else { reduced.docCount += bucket.docCount; } aggregations.add((InternalAggregations) bucket.getAggregations()); } reduced.aggregations = InternalAggregations.reduce(aggregations, cacheRecycler); return (B) reduced; } }
1no label
src_main_java_org_elasticsearch_search_aggregations_bucket_histogram_InternalHistogram.java
2,654
threadPool.schedule(TimeValue.timeValueMillis(request.timeout.millis() * 2), ThreadPool.Names.SAME, new Runnable() { @Override public void run() { temporalResponses.remove(request.pingResponse); } });
0true
src_main_java_org_elasticsearch_discovery_zen_ping_unicast_UnicastZenPing.java
3,436
public class SnapshotStatus { public static enum Stage { NONE, INDEX, TRANSLOG, FINALIZE, DONE, FAILURE } private Stage stage = Stage.NONE; private long startTime; private long time; private Index index = new Index(); private Translog translog = new Translog(); private Throwable failure; public Stage stage() { return this.stage; } public SnapshotStatus updateStage(Stage stage) { this.stage = stage; return this; } public long startTime() { return this.startTime; } public void startTime(long startTime) { this.startTime = startTime; } public long time() { return this.time; } public void time(long time) { this.time = time; } public void failed(Throwable failure) { this.failure = failure; } public Index index() { return index; } public Translog translog() { return translog; } public static class Index { private long startTime; private long time; private int numberOfFiles; private long totalSize; public long startTime() { return this.startTime; } public void startTime(long startTime) { this.startTime = startTime; } public long time() { return this.time; } public void time(long time) { this.time = time; } public void files(int numberOfFiles, long totalSize) { this.numberOfFiles = numberOfFiles; this.totalSize = totalSize; } public int numberOfFiles() { return numberOfFiles; } public long totalSize() { return totalSize; } } public static class Translog { private long startTime; private long time; private int expectedNumberOfOperations; public long startTime() { return this.startTime; } public void startTime(long startTime) { this.startTime = startTime; } public long time() { return this.time; } public void time(long time) { this.time = time; } public int expectedNumberOfOperations() { return expectedNumberOfOperations; } public void expectedNumberOfOperations(int expectedNumberOfOperations) { this.expectedNumberOfOperations = expectedNumberOfOperations; } } }
0true
src_main_java_org_elasticsearch_index_gateway_SnapshotStatus.java
1,905
EntryListener<Object, Object> listener = new EntryListener<Object, Object>() { public void entryAdded(EntryEvent<Object, Object> event) { addedKey[0] = event.getKey(); addedValue[0] = event.getValue(); } public void entryRemoved(EntryEvent<Object, Object> event) { removedKey[0] = event.getKey(); removedValue[0] = event.getOldValue(); } public void entryUpdated(EntryEvent<Object, Object> event) { updatedKey[0] = event.getKey(); oldValue[0] = event.getOldValue(); newValue[0] = event.getValue(); } public void entryEvicted(EntryEvent<Object, Object> event) { } };
0true
hazelcast_src_test_java_com_hazelcast_map_QueryListenerTest.java
3,599
private static ThreadLocal<NumericTokenStream> tokenStreamMax = new ThreadLocal<NumericTokenStream>() { @Override protected NumericTokenStream initialValue() { return new NumericTokenStream(Integer.MAX_VALUE); } };
0true
src_main_java_org_elasticsearch_index_mapper_core_NumberFieldMapper.java
712
private final class GroupKey implements Comparable<GroupKey> { private final long fileId; private final long groupIndex; private GroupKey(long fileId, long groupIndex) { this.fileId = fileId; this.groupIndex = groupIndex; } @Override public int compareTo(GroupKey other) { if (fileId > other.fileId) return 1; if (fileId < other.fileId) return -1; if (groupIndex > other.groupIndex) return 1; if (groupIndex < other.groupIndex) return -1; return 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GroupKey groupKey = (GroupKey) o; if (fileId != groupKey.fileId) return false; if (groupIndex != groupKey.groupIndex) return false; return true; } @Override public int hashCode() { int result = (int) (fileId ^ (fileId >>> 32)); result = 31 * result + (int) (groupIndex ^ (groupIndex >>> 32)); return result; } @Override public String toString() { return "GroupKey{" + "fileId=" + fileId + ", groupIndex=" + groupIndex + '}'; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_cache_OWOWCache.java
1,645
public class ShutdownMemberRequest implements ConsoleRequest { public ShutdownMemberRequest() { } @Override public int getType() { return ConsoleRequestConstants.REQUEST_TYPE_MEMBER_SHUTDOWN; } @Override public Object readResponse(ObjectDataInput in) throws IOException { return in.readUTF(); } @Override public void writeResponse(ManagementCenterService mcs, ObjectDataOutput dos) throws Exception { mcs.getHazelcastInstance().getLifecycleService().shutdown(); dos.writeUTF("successful"); } @Override public void writeData(ObjectDataOutput out) throws IOException { } @Override public void readData(ObjectDataInput in) throws IOException { } }
0true
hazelcast_src_main_java_com_hazelcast_management_request_ShutdownMemberRequest.java
909
new Thread(new Runnable() { public void run() { try { latch.await(30, TimeUnit.SECONDS); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } lock.destroy(); } }).start();
0true
hazelcast_src_test_java_com_hazelcast_concurrent_lock_ConditionTest.java
61
public interface FieldEnumeration extends Serializable { List<FieldEnumerationItem> getEnumerationItems(); void setEnumerationItems(List<FieldEnumerationItem> enumerationItems); Long getId(); void setId(Long id); String getName(); void setName(String name); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_field_domain_FieldEnumeration.java
1,298
es.submit(new Runnable() { public void run() { Random random = new Random(); while (true) { int ran = random.nextInt(100); Queue<byte[]> queue = hz1.getQueue("default" + ran); for (int j = 0; j < 1000; j++) { queue.offer(new byte[VALUE_SIZE]); stats.offers.incrementAndGet(); } for (int j = 0; j < 1000; j++) { queue.poll(); stats.polls.incrementAndGet(); } } } });
0true
hazelcast_src_main_java_com_hazelcast_examples_SimpleQueueTest.java
107
public static class Tab { public static class Name { public static final String Rules = "PageImpl_Rules_Tab"; } public static class Order { public static final int Rules = 1000; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageImpl.java
915
public final class LockEvictionProcessor implements ScheduledEntryProcessor<Data, Object> { private static final int AWAIT_COMPLETION_TIMEOUT_SECONDS = 30; private final NodeEngine nodeEngine; private final ObjectNamespace namespace; public LockEvictionProcessor(NodeEngine nodeEngine, ObjectNamespace namespace) { this.nodeEngine = nodeEngine; this.namespace = namespace; } @Override public void process(EntryTaskScheduler<Data, Object> scheduler, Collection<ScheduledEntry<Data, Object>> entries) { Collection<Future> futures = sendUnlockOperations(entries); awaitCompletion(futures); } private Collection<Future> sendUnlockOperations(Collection<ScheduledEntry<Data, Object>> entries) { Collection<Future> futures = new ArrayList<Future>(entries.size()); for (ScheduledEntry<Data, Object> entry : entries) { Data key = entry.getKey(); sendUnlockOperation(futures, key); } return futures; } private void sendUnlockOperation(Collection<Future> futures, Data key) { Operation operation = new UnlockOperation(namespace, key, -1, true); try { Future f = invoke(operation, key); futures.add(f); } catch (Throwable t) { ILogger logger = nodeEngine.getLogger(getClass()); logger.warning(t); } } private void awaitCompletion(Collection<Future> futures) { ILogger logger = nodeEngine.getLogger(getClass()); for (Future future : futures) { try { future.get(AWAIT_COMPLETION_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (TimeoutException e) { logger.finest(e); } catch (Exception e) { logger.warning(e); } } } private InternalCompletableFuture invoke(Operation operation, Data key) { int partitionId = nodeEngine.getPartitionService().getPartitionId(key); OperationService operationService = nodeEngine.getOperationService(); return operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId); } }
1no label
hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockEvictionProcessor.java
689
public class CollectionGetAllOperation extends CollectionOperation { public CollectionGetAllOperation() { } public CollectionGetAllOperation(String name) { super(name); } @Override public int getId() { return CollectionDataSerializerHook.COLLECTION_GET_ALL; } @Override public void beforeRun() throws Exception { } @Override public void run() throws Exception { final Collection<Data> all = getOrCreateContainer().getAll(); response = new SerializableCollection(all); } @Override public void afterRun() throws Exception { } }
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionGetAllOperation.java
295
public abstract class OTraverseAbstractProcess<T> extends OCommandProcess<OTraverse, T, OIdentifiable> { public OTraverseAbstractProcess(final OTraverse iCommand, final T iTarget) { super(iCommand, iTarget); command.getContext().push(this); } public abstract String getStatus(); public OIdentifiable drop() { command.getContext().pop(); return null; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_command_traverse_OTraverseAbstractProcess.java
2,640
threadPool.generic().execute(new Runnable() { @Override public void run() { // connect to the node if possible try { transportService.connectToNode(requestingNode); transportService.sendRequest(requestingNode, MulticastPingResponseRequestHandler.ACTION, multicastPingResponse, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { logger.warn("failed to receive confirmation on sent ping response to [{}]", exp, requestingNode); } }); } catch (Exception e) { logger.warn("failed to connect to requesting node {}", e, requestingNode); } } });
0true
src_main_java_org_elasticsearch_discovery_zen_ping_multicast_MulticastZenPing.java
1,059
public class LoginModuleConfig { private String className; private LoginModuleUsage usage; private Properties properties = new Properties(); public LoginModuleConfig() { super(); } public LoginModuleConfig(String className, LoginModuleUsage usage) { super(); this.className = className; this.usage = usage; } public enum LoginModuleUsage { REQUIRED, REQUISITE, SUFFICIENT, OPTIONAL; public static LoginModuleUsage get(String v) { try { return LoginModuleUsage.valueOf(v.toUpperCase()); } catch (Exception ignore) { } return REQUIRED; } } public String getClassName() { return className; } public Properties getProperties() { return properties; } public LoginModuleUsage getUsage() { return usage; } public LoginModuleConfig setClassName(String className) { this.className = className; return this; } public LoginModuleConfig setUsage(LoginModuleUsage usage) { this.usage = usage; return this; } public LoginModuleConfig setProperties(Properties properties) { this.properties = properties; return this; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("LoginModuleConfig"); sb.append("{className='").append(className).append('\''); sb.append(", usage=").append(usage); sb.append(", properties=").append(properties); sb.append('}'); return sb.toString(); } }
0true
hazelcast_src_main_java_com_hazelcast_config_LoginModuleConfig.java
46
static final class PackageDescriptorProposal extends CompletionProposal { PackageDescriptorProposal(int offset, String prefix, String packageName) { super(offset, prefix, PACKAGE, "package " + packageName, "package " + packageName + ";"); } @Override protected boolean qualifiedNameIsPath() { return true; } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_PackageCompletions.java
3,760
static class IndexUpgraderOneMerge extends OneMerge { public IndexUpgraderOneMerge(List<SegmentCommitInfo> segments) { super(segments); } @Override public List<AtomicReader> getMergeReaders() throws IOException { final List<AtomicReader> readers = super.getMergeReaders(); ImmutableList.Builder<AtomicReader> newReaders = ImmutableList.builder(); for (AtomicReader reader : readers) { newReaders.add(filter(reader)); } return newReaders.build(); } }
0true
src_main_java_org_elasticsearch_index_merge_policy_IndexUpgraderMergePolicy.java
1
private static final class AndroidCeylonBuildHook extends CeylonBuildHook { public static final String CEYLON_GENERATED_ARCHIVES_PREFIX = "ceylonGenerated-"; public static final String CEYLON_GENERATED_CLASSES_ARCHIVE = CEYLON_GENERATED_ARCHIVES_PREFIX + "CeylonClasses.jar"; public static final String ANDROID_LIBS_DIRECTORY = "libs"; public static final String[] ANDROID_PROVIDED_PACKAGES = new String[] {"android.app"}; public static final String[] UNNECESSARY_CEYLON_RUNTIME_LIBRARIES = new String[] {"org.jboss.modules", "com.redhat.ceylon.module-resolver", "com.redhat.ceylon.common"}; boolean areModulesChanged = false; boolean hasAndroidNature = false; boolean isReentrantBuild = false; boolean isFullBuild = false; WeakReference<IProgressMonitor> monitorRef = null; WeakReference<IProject> projectRef = null; private IProgressMonitor getMonitor() { if (monitorRef != null) { return monitorRef.get(); } return null; } private IProject getProject() { if (projectRef != null) { return projectRef.get(); } return null; } @Override protected void startBuild(int kind, @SuppressWarnings("rawtypes") Map args, IProject project, IBuildConfiguration config, IBuildContext context, IProgressMonitor monitor) throws CoreException { try { hasAndroidNature = project.hasNature("com.android.ide.eclipse.adt.AndroidNature"); } catch (CoreException e) { hasAndroidNature= false; } areModulesChanged = false; monitorRef = new WeakReference<IProgressMonitor>(monitor); projectRef = new WeakReference<IProject>(project); isReentrantBuild = args.containsKey(CeylonBuilder.BUILDER_ID + ".reentrant"); if (hasAndroidNature) { IJavaProject javaProject =JavaCore.create(project); boolean CeylonCPCFound = false; IMarker[] buildMarkers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_ZERO); for (IMarker m: buildMarkers) { if (CeylonAndroidPlugin.PLUGIN_ID.equals(m.getAttribute(IMarker.SOURCE_ID))) { m.delete(); } } for (IClasspathEntry entry : javaProject.getRawClasspath()) { if (CeylonClasspathUtil.isProjectModulesClasspathContainer(entry.getPath())) { CeylonCPCFound = true; } else { IPath containerPath = entry.getPath(); int size = containerPath.segmentCount(); if (size > 0) { if (containerPath.segment(0).equals("com.android.ide.eclipse.adt.LIBRARIES") || containerPath.segment(0).equals("com.android.ide.eclipse.adt.DEPENDENCIES")) { if (! CeylonCPCFound) { //if the ClassPathContainer is missing, add an error IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER); marker.setAttribute(IMarker.SOURCE_ID, CeylonAndroidPlugin.PLUGIN_ID); marker.setAttribute(IMarker.MESSAGE, "Invalid Java Build Path for project " + project.getName() + " : " + "The Ceylon libraries should be set before the Android libraries in the Java Build Path. " + "Move down the 'Android Private Libraries' and 'Android Dependencies' after the Ceylon Libraries " + "in the 'Order and Export' tab of the 'Java Build Path' properties page."); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LOCATION, "Java Build Path Order"); throw new CoreException(new Status(IStatus.CANCEL, CeylonAndroidPlugin.PLUGIN_ID, IResourceStatus.OK, "Build cancelled because of invalid build path", null)); } } } } } } } @Override protected void deltasAnalyzed(List<IResourceDelta> currentDeltas, BooleanHolder sourceModified, BooleanHolder mustDoFullBuild, BooleanHolder mustResolveClasspathContainer, boolean mustContinueBuild) { if (mustContinueBuild && hasAndroidNature) { CeylonBuilder.waitForUpToDateJavaModel(10000, getProject(), getMonitor()); } } @Override protected void setAndRefreshClasspathContainer() { areModulesChanged = true; } @Override protected void doFullBuild() { isFullBuild = true; } @Override protected void afterGeneratingBinaries() { IProject project = getProject(); if (project == null) { return; } if (! isReentrantBuild && hasAndroidNature) { try { File libsDirectory = project.findMember(ANDROID_LIBS_DIRECTORY).getLocation().toFile(); if (!libsDirectory.exists()) { libsDirectory.mkdirs(); } Files.walkFileTree(java.nio.file.FileSystems.getDefault().getPath(libsDirectory.getAbsolutePath()), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { if (areModulesChanged || isFullBuild ? path.getFileName().toString().startsWith(CEYLON_GENERATED_ARCHIVES_PREFIX) : path.getFileName().toString().equals(CEYLON_GENERATED_CLASSES_ARCHIVE)) { try { Files.delete(path); } catch(IOException ioe) { CeylonAndroidPlugin.logError("Could not delete a ceylon jar from the android libs directory", ioe); } } return FileVisitResult.CONTINUE; } }); final List<IFile> filesToAddInArchive = new LinkedList<>(); final IFolder ceylonOutputFolder = CeylonBuilder.getCeylonClassesOutputFolder(project); ceylonOutputFolder.refreshLocal(DEPTH_INFINITE, getMonitor()); ceylonOutputFolder.accept(new IResourceVisitor() { @Override public boolean visit(IResource resource) throws CoreException { if (resource instanceof IFile) { filesToAddInArchive.add((IFile)resource); } return true; } }); if (! filesToAddInArchive.isEmpty()) { JarPackageData jarPkgData = new JarPackageData(); jarPkgData.setBuildIfNeeded(false); jarPkgData.setOverwrite(true); jarPkgData.setGenerateManifest(true); jarPkgData.setExportClassFiles(true); jarPkgData.setCompress(true); jarPkgData.setJarLocation(project.findMember("libs").getLocation().append(CEYLON_GENERATED_CLASSES_ARCHIVE).makeAbsolute()); jarPkgData.setElements(filesToAddInArchive.toArray()); JarWriter3 jarWriter = null; try { jarWriter = new JarWriter3(jarPkgData, null); for (IFile fileToAdd : filesToAddInArchive) { jarWriter.write(fileToAdd, fileToAdd.getFullPath().makeRelativeTo(ceylonOutputFolder.getFullPath())); } } finally { if (jarWriter != null) { jarWriter.close(); } } } if (isFullBuild || areModulesChanged) { List<Path> jarsToCopyToLib = new LinkedList<>(); IJavaProject javaProject = JavaCore.create(project); List<IClasspathContainer> cpContainers = CeylonClasspathUtil.getCeylonClasspathContainers(javaProject); if (cpContainers != null) { for (IClasspathContainer cpc : cpContainers) { for (IClasspathEntry cpe : cpc.getClasspathEntries()) { if (cpe.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { Path path = FileSystems.getDefault().getPath(cpe.getPath().toOSString()); if (! Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS) && Files.exists(path, LinkOption.NOFOLLOW_LINKS)) { boolean isAndroidProvidedJar = false; providerPackageFound: for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) { if (javaProject.isOnClasspath(root) && cpe.equals(root.getResolvedClasspathEntry())) { for (String providedPackage : ANDROID_PROVIDED_PACKAGES) { if (root.getPackageFragment(providedPackage).exists()) { isAndroidProvidedJar = true; break providerPackageFound; } } } } if (! isAndroidProvidedJar) { jarsToCopyToLib.add(path); } } } } } } for (String runtimeJar : CeylonPlugin.getRuntimeRequiredJars()) { boolean isNecessary = true; for (String unnecessaryRuntime : UNNECESSARY_CEYLON_RUNTIME_LIBRARIES) { if (runtimeJar.contains(unnecessaryRuntime + "-")) { isNecessary = false; break; } } if (isNecessary) { jarsToCopyToLib.add(FileSystems.getDefault().getPath(runtimeJar)); } } for (Path archive : jarsToCopyToLib) { String newName = CEYLON_GENERATED_ARCHIVES_PREFIX + archive.getFileName(); if (newName.endsWith(ArtifactContext.CAR)) { newName = newName.replaceFirst("\\.car$", "\\.jar"); } Path destinationPath = FileSystems.getDefault().getPath(project.findMember(ANDROID_LIBS_DIRECTORY).getLocation().toOSString(), newName); try { Files.copy(archive, destinationPath); } catch (IOException e) { CeylonAndroidPlugin.logError("Could not copy a ceylon jar to the android libs directory", e); } } } project.findMember(ANDROID_LIBS_DIRECTORY).refreshLocal(DEPTH_INFINITE, getMonitor()); } catch (Exception e) { CeylonAndroidPlugin.logError("Error during the generation of ceylon-derived archives for Android", e); } } } @Override protected void endBuild() { areModulesChanged = false; hasAndroidNature = false; isReentrantBuild = false; isFullBuild = false; monitorRef = null; projectRef = null; } }
0true
plugins_com.redhat.ceylon.eclipse.android.plugin_src_com_redhat_ceylon_eclipse_android_plugin_AndroidBuildHookProvider.java
2,090
public abstract class AdapterStreamInput extends StreamInput { protected StreamInput in; protected AdapterStreamInput() { } public AdapterStreamInput(StreamInput in) { this.in = in; super.setVersion(in.getVersion()); } @Override public StreamInput setVersion(Version version) { in.setVersion(version); return super.setVersion(version); } public void reset(StreamInput in) { this.in = in; } @Override public byte readByte() throws IOException { return in.readByte(); } @Override public void readBytes(byte[] b, int offset, int len) throws IOException { in.readBytes(b, offset, len); } @Override public BytesReference readBytesReference() throws IOException { return in.readBytesReference(); } @Override public BytesReference readBytesReference(int length) throws IOException { return in.readBytesReference(length); } @Override public void reset() throws IOException { in.reset(); } @Override public void close() throws IOException { in.close(); } @Override public int read() throws IOException { return in.read(); } // override ones to direct them @Override public void readFully(byte[] b) throws IOException { in.readFully(b); } @Override public short readShort() throws IOException { return in.readShort(); } @Override public int readInt() throws IOException { return in.readInt(); } @Override public int readVInt() throws IOException { return in.readVInt(); } @Override public long readLong() throws IOException { return in.readLong(); } @Override public long readVLong() throws IOException { return in.readVLong(); } @Override public String readString() throws IOException { return in.readString(); } @Override public String readSharedString() throws IOException { return in.readSharedString(); } @Override public Text readText() throws IOException { return in.readText(); } @Override public Text readSharedText() throws IOException { return in.readSharedText(); } @Override public int read(byte[] b) throws IOException { return in.read(b); } @Override public int read(byte[] b, int off, int len) throws IOException { return in.read(b, off, len); } @Override public long skip(long n) throws IOException { return in.skip(n); } @Override public int available() throws IOException { return in.available(); } @Override public void mark(int readlimit) { in.mark(readlimit); } @Override public boolean markSupported() { return in.markSupported(); } @Override public String toString() { return in.toString(); } }
0true
src_main_java_org_elasticsearch_common_io_stream_AdapterStreamInput.java
1,398
CollectionUtil.timSort(templates, new Comparator<IndexTemplateMetaData>() { @Override public int compare(IndexTemplateMetaData o1, IndexTemplateMetaData o2) { return o2.order() - o1.order(); } });
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataCreateIndexService.java
19
private static enum STATE { unInitialized, initializing, initialized; }
0true
timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_config_DiskBufferEnv.java
860
public class ApplyOperation extends AtomicReferenceBaseOperation { protected Data function; protected Data returnValue; public ApplyOperation() { super(); } public ApplyOperation(String name, Data function) { super(name); this.function = function; } @Override public void run() throws Exception { NodeEngine nodeEngine = getNodeEngine(); IFunction f = nodeEngine.toObject(function); ReferenceWrapper reference = getReference(); Object input = nodeEngine.toObject(reference.get()); //noinspection unchecked Object output = f.apply(input); returnValue = nodeEngine.toData(output); } @Override public Object getResponse() { return returnValue; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(function); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); function = in.readObject(); } @Override public int getId() { return AtomicReferenceDataSerializerHook.APPLY; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_operations_ApplyOperation.java
38
@Component("blInventoryTypeOptionsExtensionListener") public class InventoryTypeEnumOptionsExtensionListener extends AbstractRuleBuilderEnumOptionsExtensionListener { @Override protected Map<String, Class<? extends BroadleafEnumerationType>> getValuesToGenerate() { Map<String, Class<? extends BroadleafEnumerationType>> map = new HashMap<String, Class<? extends BroadleafEnumerationType>>(); map.put("blcOptions_InventoryType", InventoryType.class); return map; } }
0true
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_rulebuilder_service_options_InventoryTypeEnumOptionsExtensionListener.java
221
public class NodeLabelsFieldTest { @Test public void shouldInlineOneLabel() throws Exception { // GIVEN long labelId = 10; NodeRecord node = nodeRecordWithInlinedLabels(); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN nodeLabels.add( labelId, null ); // THEN assertEquals( inlinedLabelsLongRepresentation( labelId ), node.getLabelField() ); } @Test public void shouldInlineOneLabelWithHighId() throws Exception { // GIVEN long labelId = 10000; NodeRecord node = nodeRecordWithInlinedLabels(); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN nodeLabels.add( labelId, null ); // THEN assertEquals( inlinedLabelsLongRepresentation( labelId ), node.getLabelField() ); } @Test public void shouldInlineTwoSmallLabels() throws Exception { // GIVEN long labelId1 = 10, labelId2 = 30; NodeRecord node = nodeRecordWithInlinedLabels( labelId1 ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN nodeLabels.add( labelId2, null ); // THEN assertEquals( inlinedLabelsLongRepresentation( labelId1, labelId2 ), node.getLabelField() ); } @Test public void shouldInlineThreeSmallLabels() throws Exception { // GIVEN long labelId1 = 10, labelId2 = 30, labelId3 = 4095; NodeRecord node = nodeRecordWithInlinedLabels( labelId1, labelId2 ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN nodeLabels.add( labelId3, null ); // THEN assertEquals( inlinedLabelsLongRepresentation( labelId1, labelId2, labelId3 ), node.getLabelField() ); } @Test public void shouldInlineFourSmallLabels() throws Exception { // GIVEN long labelId1 = 10, labelId2 = 30, labelId3 = 45, labelId4 = 60; NodeRecord node = nodeRecordWithInlinedLabels( labelId1, labelId2, labelId3 ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN nodeLabels.add( labelId4, null ); // THEN assertEquals( inlinedLabelsLongRepresentation( labelId1, labelId2, labelId3, labelId4 ), node.getLabelField() ); } @Test public void shouldInlineFiveSmallLabels() throws Exception { // GIVEN long labelId1 = 10, labelId2 = 30, labelId3 = 45, labelId4 = 60, labelId5 = 61; NodeRecord node = nodeRecordWithInlinedLabels( labelId1, labelId2, labelId3, labelId4 ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN nodeLabels.add( labelId5, null ); // THEN assertEquals( inlinedLabelsLongRepresentation( labelId1, labelId2, labelId3, labelId4, labelId5 ), node.getLabelField() ); } @Test public void shouldSpillOverToDynamicRecordIfExceedsInlinedSpace() throws Exception { // GIVEN -- the upper limit for a label ID for 3 labels would be 36b/3 - 1 = 12b - 1 = 4095 long labelId1 = 10, labelId2 = 30, labelId3 = 4096; NodeRecord node = nodeRecordWithInlinedLabels( labelId1, labelId2 ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN Collection<DynamicRecord> changedDynamicRecords = nodeLabels.add( labelId3, nodeStore ); // THEN assertEquals( 1, count( changedDynamicRecords ) ); assertEquals( dynamicLabelsLongRepresentation( changedDynamicRecords ), node.getLabelField() ); assertTrue( Arrays.equals( new long[] {labelId1, labelId2, labelId3}, nodeStore.getDynamicLabelsArray( changedDynamicRecords ) ) ); } @Test public void oneDynamicRecordShouldExtendIntoAnAdditionalIfTooManyLabels() throws Exception { // GIVEN // will occupy 60B of data, i.e. one dynamic record NodeRecord node = nodeRecordWithDynamicLabels( nodeStore, oneByteLongs( 56 ) ); Collection<DynamicRecord> initialRecords = node.getDynamicLabelRecords(); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN Set<DynamicRecord> changedDynamicRecords = asSet( nodeLabels.add( 1, nodeStore ) ); // THEN assertTrue( changedDynamicRecords.containsAll( initialRecords ) ); assertEquals( initialRecords.size()+1, changedDynamicRecords.size() ); } @Test public void oneDynamicRecordShouldStoreItsOwner() throws Exception { // GIVEN // will occupy 60B of data, i.e. one dynamic record Long nodeId = 24l; NodeRecord node = nodeRecordWithDynamicLabels( nodeId, nodeStore, oneByteLongs(56) ); Collection<DynamicRecord> initialRecords = node.getDynamicLabelRecords(); // WHEN Pair<Long,long[]> pair = nodeStore.getDynamicLabelsArrayAndOwner( initialRecords ); // THEN assertEquals( nodeId, pair.first() ); } @Test public void twoDynamicRecordsShouldShrinkToOneWhenRemoving() throws Exception { // GIVEN // will occupy 61B of data, i.e. just two dynamic records NodeRecord node = nodeRecordWithDynamicLabels( nodeStore, oneByteLongs( 57 ) ); Collection<DynamicRecord> initialRecords = node.getDynamicLabelRecords(); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN List<DynamicRecord> changedDynamicRecords = addToCollection( nodeLabels.remove( 255 /*Initial labels go from 255 and down to 255-58*/, nodeStore ), new ArrayList<DynamicRecord>() ); // THEN assertEquals( initialRecords, changedDynamicRecords ); assertTrue( changedDynamicRecords.get( 0 ).inUse() ); assertFalse( changedDynamicRecords.get( 1 ).inUse() ); } @Test public void twoDynamicRecordsShouldShrinkToOneWhenRemovingWithoutChangingItsOwner() throws Exception { // GIVEN // will occupy 61B of data, i.e. just two dynamic records Long nodeId = 42l; NodeRecord node = nodeRecordWithDynamicLabels( nodeId, nodeStore, oneByteLongs( 57 ) ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); List<DynamicRecord> changedDynamicRecords = addToCollection( nodeLabels.remove( 255 /*Initial labels go from 255 and down to 255-58*/, nodeStore ), new ArrayList<DynamicRecord>() ); // WHEN Pair<Long,long[]> changedPair = nodeStore.getDynamicLabelsArrayAndOwner( changedDynamicRecords ); // THEN assertEquals( nodeId, changedPair.first() ); } @Test public void oneDynamicRecordShouldShrinkIntoInlinedWhenRemoving() throws Exception { // GIVEN NodeRecord node = nodeRecordWithDynamicLabels( nodeStore, oneByteLongs( 5 ) ); Collection<DynamicRecord> initialRecords = node.getDynamicLabelRecords(); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN Collection<DynamicRecord> changedDynamicRecords = asCollection( nodeLabels.remove( 255, nodeStore ) ); // THEN assertEquals( initialRecords, changedDynamicRecords ); assertFalse( single( changedDynamicRecords ).inUse() ); assertEquals( inlinedLabelsLongRepresentation( 251, 252, 253, 254 ), node.getLabelField() ); } @Test public void shouldReadIdOfDynamicRecordFromDynamicLabelsField() throws Exception { // GIVEN NodeRecord node = nodeRecordWithDynamicLabels( nodeStore, oneByteLongs( 5 ) ); DynamicRecord dynamicRecord = node.getDynamicLabelRecords().iterator().next(); // WHEN Long dynRecordId = NodeLabelsField.fieldDynamicLabelRecordId( node.getLabelField() ); // THEN assertEquals( (Long) dynamicRecord.getLongId(), dynRecordId ); } @Test public void shouldReadNullDynamicRecordFromInlineLabelsField() throws Exception { // GIVEN NodeRecord node = nodeRecordWithInlinedLabels( 23l ); // WHEN Long dynRecordId = NodeLabelsField.fieldDynamicLabelRecordId( node.getLabelField() ); // THEN assertNull( dynRecordId ); } @Test public void maximumOfSevenInlinedLabels() throws Exception { // GIVEN long[] labels = new long[] {0, 1, 2, 3, 4, 5, 6}; NodeRecord node = nodeRecordWithInlinedLabels( labels ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN Iterable<DynamicRecord> changedDynamicRecords = nodeLabels.add( 23, nodeStore ); // THEN assertEquals( dynamicLabelsLongRepresentation( changedDynamicRecords ), node.getLabelField() ); assertEquals( 1, count( changedDynamicRecords ) ); } @Test public void addingAnAlreadyAddedLabelWhenLabelsAreInlinedShouldFail() throws Exception { // GIVEN int labelId = 1; NodeRecord node = nodeRecordWithInlinedLabels( labelId ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN try { nodeLabels.add( labelId, nodeStore ); fail( "Should have thrown exception" ); } catch ( IllegalStateException e ) { // THEN } } @Test public void addingAnAlreadyAddedLabelWhenLabelsAreInDynamicRecordsShouldFail() throws Exception { // GIVEN long[] labels = oneByteLongs( 20 ); NodeRecord node = nodeRecordWithDynamicLabels( nodeStore, labels ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN try { nodeLabels.add( safeCastLongToInt( labels[0] ), nodeStore ); fail( "Should have thrown exception" ); } catch ( IllegalStateException e ) { // THEN } } @Test public void removingNonExistentInlinedLabelShouldFail() throws Exception { // GIVEN int labelId1 = 1, labelId2 = 2; NodeRecord node = nodeRecordWithInlinedLabels( labelId1 ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN try { nodeLabels.remove( labelId2, nodeStore ); fail( "Should have thrown exception" ); } catch ( IllegalStateException e ) { // THEN } } @Test public void removingNonExistentLabelInDynamicRecordsShouldFail() throws Exception { // GIVEN long[] labels = oneByteLongs( 20 ); NodeRecord node = nodeRecordWithDynamicLabels( nodeStore, labels ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN try { nodeLabels.remove( 123456, nodeStore ); fail( "Should have thrown exception" ); } catch ( IllegalStateException e ) { // THEN } } @Test public void shouldReallocateSomeOfPreviousDynamicRecords() throws Exception { // GIVEN NodeRecord node = nodeRecordWithDynamicLabels( nodeStore, oneByteLongs( 5 ) ); Set<DynamicRecord> initialRecords = asUniqueSet( node.getDynamicLabelRecords() ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN Set<DynamicRecord> reallocatedRecords = asUniqueSet( nodeLabels.put( fourByteLongs( 100 ), nodeStore ) ); // THEN assertTrue( reallocatedRecords.containsAll( initialRecords ) ); assertTrue( reallocatedRecords.size() > initialRecords.size() ); } @Test public void shouldReallocateAllOfPreviousDynamicRecordsAndThenSome() throws Exception { // GIVEN NodeRecord node = nodeRecordWithDynamicLabels( nodeStore, fourByteLongs( 100 ) ); Set<DynamicRecord> initialRecords = asSet( cloned( node.getDynamicLabelRecords(), DynamicRecord.class ) ); NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node ); // WHEN Set<DynamicRecord> reallocatedRecords = asUniqueSet( nodeLabels.put( fourByteLongs( 5 ), nodeStore ) ); // THEN assertTrue( "initial:" + initialRecords + ", reallocated:" + reallocatedRecords , initialRecords.containsAll( used( reallocatedRecords ) ) ); assertTrue( used( reallocatedRecords ).size() < initialRecords.size() ); } private long dynamicLabelsLongRepresentation( Iterable<DynamicRecord> records ) { return 0x8000000000L|first( records ).getId(); } private long inlinedLabelsLongRepresentation( long... labelIds ) { long header = (long)labelIds.length << 36; byte bitsPerLabel = (byte) (36/labelIds.length); Bits bits = bits( 5 ); for ( long labelId : labelIds ) { bits.put( labelId, bitsPerLabel ); } return header|bits.getLongs()[0]; } @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); private NodeStore nodeStore; @Before public void startUp() { StoreFactory storeFactory = new StoreFactory( new Config(), new DefaultIdGeneratorFactory(), new DefaultWindowPoolFactory(), fs.get(), StringLogger.DEV_NULL, new DefaultTxHook() ); File storeFile = new File( "store" ); storeFactory.createNodeStore( storeFile ); nodeStore = storeFactory.newNodeStore( storeFile ); } @After public void cleanUp() { if ( nodeStore != null ) { nodeStore.close(); } } private NodeRecord nodeRecordWithInlinedLabels( long... labels ) { NodeRecord node = new NodeRecord( 0, 0, 0 ); if ( labels.length > 0 ) { node.setLabelField( inlinedLabelsLongRepresentation( labels ), Collections.<DynamicRecord>emptyList() ); } return node; } private NodeRecord nodeRecordWithDynamicLabels( NodeStore nodeStore, long... labels ) { return nodeRecordWithDynamicLabels( 0, nodeStore, labels ); } private NodeRecord nodeRecordWithDynamicLabels( long nodeId, NodeStore nodeStore, long... labels ) { NodeRecord node = new NodeRecord( nodeId, 0, 0 ); Collection<DynamicRecord> initialRecords = allocateAndApply( nodeStore, node.getId(), labels ); node.setLabelField( dynamicLabelsLongRepresentation( initialRecords ), initialRecords ); return node; } private Collection<DynamicRecord> allocateAndApply( NodeStore nodeStore, long nodeId, long[] longs ) { Collection<DynamicRecord> records = nodeStore.allocateRecordsForDynamicLabels( nodeId, longs ); nodeStore.updateDynamicLabelRecords( records ); return records; } private long[] oneByteLongs( int numberOfLongs ) { long[] result = new long[numberOfLongs]; for ( int i = 0; i < numberOfLongs; i++ ) { result[i] = 255-i; } Arrays.sort( result ); return result; } private long[] fourByteLongs( int numberOfLongs ) { long[] result = new long[numberOfLongs]; for ( int i = 0; i < numberOfLongs; i++ ) { result[i] = Integer.MAX_VALUE-i; } Arrays.sort( result ); return result; } private Set<DynamicRecord> used( Set<DynamicRecord> reallocatedRecords ) { Set<DynamicRecord> used = new HashSet<>(); for ( DynamicRecord record : reallocatedRecords ) { if ( record.inUse() ) { used.add( record ); } } return used; } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_nioneo_xa_NodeLabelsFieldTest.java
1,977
@Entity @EntityListeners(value = { AuditableListener.class, CustomerPersistedEntityListener.class }) @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_CUSTOMER", uniqueConstraints = @UniqueConstraint(columnNames = { "USER_NAME" })) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "blCustomerElements") @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "CustomerImpl_baseCustomer") public class CustomerImpl implements Customer, AdminMainEntity { private static final long serialVersionUID = 1L; @Id @Column(name = "CUSTOMER_ID") @AdminPresentation(friendlyName = "CustomerImpl_Customer_Id", group = "CustomerImpl_Primary_Key", visibility = VisibilityEnum.HIDDEN_ALL) protected Long id; @Embedded protected Auditable auditable = new Auditable(); @Column(name = "USER_NAME") @AdminPresentation(friendlyName = "CustomerImpl_UserName", order = 4000, group = "CustomerImpl_Customer", visibility = VisibilityEnum.HIDDEN_ALL) protected String username; @Column(name = "PASSWORD") @AdminPresentation(excluded = true) protected String password; @Column(name = "EMAIL_ADDRESS") @Index(name = "CUSTOMER_EMAIL_INDEX", columnNames = { "EMAIL_ADDRESS" }) @AdminPresentation(friendlyName = "CustomerImpl_Email_Address", order = 1000, group = "CustomerImpl_Customer", prominent = true, gridOrder = 1000) protected String emailAddress; @Column(name = "FIRST_NAME") @AdminPresentation(friendlyName = "CustomerImpl_First_Name", order = 2000, group = "CustomerImpl_Customer", prominent = true, gridOrder = 2000) protected String firstName; @Column(name = "LAST_NAME") @AdminPresentation(friendlyName = "CustomerImpl_Last_Name", order = 3000, group = "CustomerImpl_Customer", prominent = true, gridOrder = 3000) protected String lastName; @ManyToOne(targetEntity = ChallengeQuestionImpl.class) @JoinColumn(name = "CHALLENGE_QUESTION_ID") @Index(name="CUSTOMER_CHALLENGE_INDEX", columnNames={"CHALLENGE_QUESTION_ID"}) @AdminPresentation(friendlyName = "CustomerImpl_Challenge_Question", order = 4000, tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, excluded = true) protected ChallengeQuestion challengeQuestion; @Column(name = "CHALLENGE_ANSWER") @AdminPresentation(friendlyName = "CustomerImpl_Challenge_Answer", order = 5000, tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, excluded = true) protected String challengeAnswer; @Column(name = "PASSWORD_CHANGE_REQUIRED") @AdminPresentation(excluded = true) protected Boolean passwordChangeRequired = false; @Column(name = "RECEIVE_EMAIL") @AdminPresentation(friendlyName = "CustomerImpl_Customer_Receive_Email",order=1000, tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced) protected Boolean receiveEmail = true; @Column(name = "IS_REGISTERED") @AdminPresentation(friendlyName = "CustomerImpl_Customer_Registered", order = 4000, prominent = true, gridOrder = 4000) protected Boolean registered = false; @Column(name = "DEACTIVATED") @AdminPresentation(friendlyName = "CustomerImpl_Customer_Deactivated", order=3000, tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced) protected Boolean deactivated = false; @ManyToOne(targetEntity = LocaleImpl.class) @JoinColumn(name = "LOCALE_CODE") @AdminPresentation(friendlyName = "CustomerImpl_Customer_Locale",order=4000, tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, excluded = true, visibility = VisibilityEnum.GRID_HIDDEN) protected Locale customerLocale; @OneToMany(mappedBy = "customer", targetEntity = CustomerAttributeImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true) @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blStandardElements") @MapKey(name="name") @BatchSize(size = 50) @AdminPresentationMap(friendlyName = "CustomerAttributeImpl_Attribute_Name", deleteEntityUponRemove = true, forceFreeFormKeys = true, keyPropertyFriendlyName = "ProductAttributeImpl_Attribute_Name", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced ) protected Map<String, CustomerAttribute> customerAttributes = new HashMap<String, CustomerAttribute>(); @OneToMany(mappedBy = "customer", targetEntity = CustomerAddressImpl.class, cascade = {CascadeType.ALL}) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @AdminPresentationCollection(friendlyName = "CustomerImpl_Customer_Addresses", order = 1000, addType = AddMethodType.PERSIST, tab = Presentation.Tab.Name.Contact, tabOrder = Presentation.Tab.Order.Contact) protected List<CustomerAddress> customerAddresses = new ArrayList<CustomerAddress>(); @OneToMany(mappedBy = "customer", targetEntity = CustomerPhoneImpl.class, cascade = {CascadeType.ALL}) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @AdminPresentationCollection(friendlyName = "CustomerImpl_Customer_Phones", order = 2000, addType = AddMethodType.PERSIST, tab = Presentation.Tab.Name.Contact, tabOrder = Presentation.Tab.Order.Contact) protected List<CustomerPhone> customerPhones = new ArrayList<CustomerPhone>(); @OneToMany(mappedBy = "customer", targetEntity = CustomerPaymentImpl.class, cascade = {CascadeType.ALL}) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @BatchSize(size = 50) @AdminPresentationCollection(friendlyName = "CustomerImpl_Customer_Payments", order = 3000, addType = AddMethodType.PERSIST, tab = Presentation.Tab.Name.Contact, tabOrder = Presentation.Tab.Order.Contact) protected List<CustomerPayment> customerPayments = new ArrayList<CustomerPayment>(); @Column(name = "TAX_EXEMPTION_CODE") @AdminPresentation(friendlyName = "CustomerImpl_Customer_TaxExemptCode", order = 5000, tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, visibility = VisibilityEnum.GRID_HIDDEN) protected String taxExemptionCode; @Transient protected String unencodedPassword; @Transient protected String unencodedChallengeAnswer; @Transient protected boolean anonymous; @Transient protected boolean cookied; @Transient protected boolean loggedIn; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getUsername() { return username; } @Override public void setUsername(String username) { this.username = username; } @Override public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public boolean isPasswordChangeRequired() { if (passwordChangeRequired == null) { return false; } else { return passwordChangeRequired.booleanValue(); } } @Override public void setPasswordChangeRequired(boolean passwordChangeRequired) { this.passwordChangeRequired = Boolean.valueOf(passwordChangeRequired); } @Override public String getFirstName() { return firstName; } @Override public void setFirstName(String firstName) { this.firstName = firstName; } @Override public String getLastName() { return lastName; } @Override public void setLastName(String lastName) { this.lastName = lastName; } @Override public String getEmailAddress() { return emailAddress; } @Override public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } @Override public ChallengeQuestion getChallengeQuestion() { return challengeQuestion; } @Override public void setChallengeQuestion(ChallengeQuestion challengeQuestion) { this.challengeQuestion = challengeQuestion; } @Override public String getChallengeAnswer() { return challengeAnswer; } @Override public void setChallengeAnswer(String challengeAnswer) { this.challengeAnswer = challengeAnswer; } @Override public String getUnencodedPassword() { return unencodedPassword; } @Override public void setUnencodedPassword(String unencodedPassword) { this.unencodedPassword = unencodedPassword; } @Override public boolean isReceiveEmail() { if (receiveEmail == null) { return false; } else { return receiveEmail.booleanValue(); } } @Override public void setReceiveEmail(boolean receiveEmail) { this.receiveEmail = Boolean.valueOf(receiveEmail); } @Override public boolean isRegistered() { if (registered == null) { return true; } else { return registered.booleanValue(); } } @Override public void setRegistered(boolean registered) { this.registered = Boolean.valueOf(registered); } @Override public String getUnencodedChallengeAnswer() { return unencodedChallengeAnswer; } @Override public void setUnencodedChallengeAnswer(String unencodedChallengeAnswer) { this.unencodedChallengeAnswer = unencodedChallengeAnswer; } @Override public Auditable getAuditable() { return auditable; } @Override public void setAuditable(Auditable auditable) { this.auditable = auditable; } @Override public boolean isAnonymous() { return anonymous; } @Override public boolean isCookied() { return cookied; } @Override public boolean isLoggedIn() { return loggedIn; } @Override public void setAnonymous(boolean anonymous) { this.anonymous = anonymous; if (anonymous) { cookied = false; loggedIn = false; } } @Override public void setCookied(boolean cookied) { this.cookied = cookied; if (cookied) { anonymous = false; loggedIn = false; } } @Override public void setLoggedIn(boolean loggedIn) { this.loggedIn = loggedIn; if (loggedIn) { anonymous = false; cookied = false; } } @Override public Locale getCustomerLocale() { return customerLocale; } @Override public void setCustomerLocale(Locale customerLocale) { this.customerLocale = customerLocale; } @Override public Map<String, CustomerAttribute> getCustomerAttributes() { return customerAttributes; } @Override public void setCustomerAttributes(Map<String, CustomerAttribute> customerAttributes) { this.customerAttributes = customerAttributes; } @Override public boolean isDeactivated() { if (deactivated == null) { return false; } else { return deactivated.booleanValue(); } } @Override public void setDeactivated(boolean deactivated) { this.deactivated = Boolean.valueOf(deactivated); } @Override public List<CustomerAddress> getCustomerAddresses() { return customerAddresses; } @Override public void setCustomerAddresses(List<CustomerAddress> customerAddresses) { this.customerAddresses = customerAddresses; } @Override public List<CustomerPhone> getCustomerPhones() { return customerPhones; } @Override public void setCustomerPhones(List<CustomerPhone> customerPhones) { this.customerPhones = customerPhones; } @Override public List<CustomerPayment> getCustomerPayments() { return customerPayments; } @Override public void setCustomerPayments(List<CustomerPayment> customerPayments) { this.customerPayments = customerPayments; } @Override public String getMainEntityName() { if (!StringUtils.isEmpty(getFirstName()) && !StringUtils.isEmpty(getLastName())) { return getFirstName() + " " + getLastName(); } return String.valueOf(getId()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CustomerImpl other = (CustomerImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (username == null) { if (other.username != null) { return false; } } else if (!username.equals(other.username)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } public static class Presentation { public static class Tab { public static class Name { public static final String Contact = "CustomerImpl_Contact_Tab"; public static final String Advanced = "CustomerImpl_Advanced_Tab"; } public static class Order { public static final int Contact = 2000; public static final int Advanced = 3000; } } } @Override public String getTaxExemptionCode() { return this.taxExemptionCode; } @Override public void setTaxExemptionCode(String exemption) { this.taxExemptionCode = exemption; } }
1no label
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_domain_CustomerImpl.java
257
return Iterators.filter(rows.iterator(), new Predicate<Row>() { @Override public boolean apply(@Nullable Row row) { // The hasOnlyTombstones(x) call below ultimately calls Column.isMarkedForDelete(x) return !(row == null || row.cf == null || row.cf.isMarkedForDelete() || row.cf.hasOnlyTombstones(nowMillis)); } });
0true
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_embedded_CassandraEmbeddedKeyColumnValueStore.java
1,257
public class AutoBundleActivity extends BaseActivity<PricingContext> { @Resource(name="blCatalogService") protected CatalogService catalogService; @Resource(name="blOrderService") protected OrderService orderService; @Resource(name="blOrderItemDao") protected OrderItemDao orderItemDao; @Resource(name="blFulfillmentGroupItemDao") protected FulfillmentGroupItemDao fulfillmentGroupItemDao; public PricingContext execute(PricingContext context) throws Exception { Order order = context.getSeedData(); order = handleAutomaticBundling(order); context.setSeedData(order); return context; } public Order handleAutomaticBundling(Order order) throws PricingException, RemoveFromCartException { boolean itemsHaveBeenUnbundled = false; List<DiscreteOrderItem> unbundledItems = null; List<ProductBundle> productBundles = catalogService.findAutomaticProductBundles(); Set<Long> processedBundleIds = new HashSet<Long>(); for (ProductBundle productBundle : productBundles) { int existingUses = countExistingUsesOfBundle(order, productBundle); Integer maxApplications = null; for (SkuBundleItem skuBundleItem : productBundle.getSkuBundleItems()) { int maxSkuApplications = countMaximumApplications(order, skuBundleItem, processedBundleIds); if (maxApplications == null || maxApplications > maxSkuApplications) { maxApplications = maxSkuApplications; } } processedBundleIds.add(productBundle.getId()); if (maxApplications != existingUses) { if (! itemsHaveBeenUnbundled) { // Store the discrete items that were part of automatic bundles unbundledItems = unBundleItems(order); order = removeAutomaticBundles(order); itemsHaveBeenUnbundled = true; } // Create a new bundle with maxApplication occurrences order = bundleItems(order, productBundle, maxApplications, unbundledItems); } } return order; } /** * Removes all automatic bundles from the order and replaces with DiscreteOrderItems. * * @param order * @throws PricingException */ private Order removeAutomaticBundles(Order order) throws PricingException { List<BundleOrderItem> bundlesToRemove = new ArrayList<BundleOrderItem>(); for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof BundleOrderItem) { BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItem; if (bundleOrderItem.getProductBundle() != null && bundleOrderItem.getProductBundle().getAutoBundle()) { bundlesToRemove.add(bundleOrderItem); } } } for (BundleOrderItem bundleOrderItem : bundlesToRemove) { try { order = orderService.removeItem(order.getId(), bundleOrderItem.getId(), false); } catch (RemoveFromCartException e) { throw new PricingException("Could not remove item", e); } } return order; } /** * Removes all automatic bundles from the order and replaces with DiscreteOrderItems. * * @param order */ private List<DiscreteOrderItem> unBundleItems(Order order) throws PricingException{ List<DiscreteOrderItem> unbundledItems = null; for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof BundleOrderItem) { BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItem; if (bundleOrderItem.getProductBundle() != null && bundleOrderItem.getProductBundle().getAutoBundle()) { if (unbundledItems == null) { unbundledItems = new ArrayList<DiscreteOrderItem>(); } for(DiscreteOrderItem item : bundleOrderItem.getDiscreteOrderItems()) { DiscreteOrderItem newOrderItem = (DiscreteOrderItem) item.clone(); newOrderItem.setQuantity(item.getQuantity() * bundleOrderItem.getQuantity()); newOrderItem.setSkuBundleItem(null); newOrderItem.setBundleOrderItem(null); newOrderItem.updateSaleAndRetailPrices(); newOrderItem.setOrder(order); unbundledItems.add(newOrderItem); } } } } return unbundledItems; } /** * Builds a BundleOrderItem based on the passed in productBundle. Creates new DiscreteOrderItems. * Removes the existing matching DiscreteOrderItems or modifies the quantity if needed. * * @param order * @param productBundle * @param numApplications * @throws PricingException * @throws ItemNotFoundException */ private Order bundleItems(Order order, ProductBundle productBundle, Integer numApplications, List<DiscreteOrderItem> unbundledItems) throws PricingException, RemoveFromCartException { BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItemDao.create(OrderItemType.BUNDLE); bundleOrderItem.setQuantity(numApplications); bundleOrderItem.setCategory(productBundle.getDefaultCategory()); bundleOrderItem.setSku(productBundle.getDefaultSku()); bundleOrderItem.setName(productBundle.getName()); bundleOrderItem.setProductBundle(productBundle); bundleOrderItem.setOrder(order); // make a copy of the fulfillment group items since they will be deleted when the order items are removed Map<Long, FulfillmentGroupItem> skuIdFulfillmentGroupMap = new HashMap<Long, FulfillmentGroupItem>(); for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) { for (FulfillmentGroupItem fulfillmentGroupItem : fulfillmentGroup.getFulfillmentGroupItems()) { if (fulfillmentGroupItem.getOrderItem() instanceof DiscreteOrderItem) { DiscreteOrderItem discreteOrderItem = (DiscreteOrderItem) fulfillmentGroupItem.getOrderItem(); skuIdFulfillmentGroupMap.put(discreteOrderItem.getSku().getId(), fulfillmentGroupItem); } } } for (SkuBundleItem skuBundleItem : productBundle.getSkuBundleItems()) { List<DiscreteOrderItem> itemMatches = new ArrayList<DiscreteOrderItem>(); int skuMatches = populateItemMatchesForSku(itemMatches, order, unbundledItems, skuBundleItem.getSku().getId()); int skusRequired = skuBundleItem.getQuantity()* numApplications; if (skuMatches < skusRequired) { throw new IllegalArgumentException("Something went wrong creating automatic bundles. Not enough skus to fulfill bundle requirements for sku id: " + skuBundleItem.getSku().getId()); } // remove-all-items from order // this call also deletes any fulfillment group items that are associated with that order item for (DiscreteOrderItem item : itemMatches) { order = orderService.removeItem(order.getId(), item.getId(), false); } DiscreteOrderItem baseItem = null; if (itemMatches.size() > 0) { baseItem = itemMatches.get(0); } else { for (DiscreteOrderItem discreteOrderItem : unbundledItems) { if (discreteOrderItem.getSku().getId().equals(skuBundleItem.getSku().getId())) { baseItem = discreteOrderItem; } } } // Add item to the skuBundle DiscreteOrderItem newSkuBundleItem = (DiscreteOrderItem) baseItem.clone(); newSkuBundleItem.setSkuBundleItem(skuBundleItem); newSkuBundleItem.setBundleOrderItem(bundleOrderItem); newSkuBundleItem.setQuantity(skuBundleItem.getQuantity()); newSkuBundleItem.setOrder(null); bundleOrderItem.getDiscreteOrderItems().add(newSkuBundleItem); if (skuMatches > skusRequired) { // Add a non-bundled item to the order with the remaining sku count. DiscreteOrderItem newOrderItem = (DiscreteOrderItem) baseItem.clone(); newOrderItem.setBundleOrderItem(null); newOrderItem.setSkuBundleItem(null); newOrderItem.setQuantity(skuMatches - skusRequired); newOrderItem = (DiscreteOrderItem) orderItemDao.save(newOrderItem); newOrderItem.setOrder(order); newOrderItem.updateSaleAndRetailPrices(); // Re-associate fulfillment group item to newOrderItem FulfillmentGroupItem fulfillmentGroupItem = skuIdFulfillmentGroupMap.get(newSkuBundleItem.getSku().getId()); if (fulfillmentGroupItem != null) { FulfillmentGroupItem newFulfillmentGroupItem = fulfillmentGroupItem.clone(); newFulfillmentGroupItem.setOrderItem(newOrderItem); newFulfillmentGroupItem.setQuantity(newOrderItem.getQuantity()); newFulfillmentGroupItem = fulfillmentGroupItemDao.save(newFulfillmentGroupItem); //In case this activity is run inside a transaction, we need to set the relationships on the order directly //these associations may have not been committed yet. This order is used in other activities and will not be reloaded if in a transaction. for (FulfillmentGroup fg : order.getFulfillmentGroups()) { if (newFulfillmentGroupItem.getFulfillmentGroup() != null && fg.getId().equals(newFulfillmentGroupItem.getFulfillmentGroup().getId())) { fg.addFulfillmentGroupItem(newFulfillmentGroupItem); } } } order.getOrderItems().add(newOrderItem); } } bundleOrderItem.updateSaleAndRetailPrices(); order.getOrderItems().add(bundleOrderItem); order = orderService.save(order, false); for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof BundleOrderItem) { BundleOrderItem bundleItem = (BundleOrderItem) orderItem; for (DiscreteOrderItem discreteOrderItem : bundleItem.getDiscreteOrderItems()) { // Re-associate fulfillment group item to newly created skuBundles FulfillmentGroupItem fulfillmentGroupItem = skuIdFulfillmentGroupMap.get(discreteOrderItem.getSku().getId()); if (fulfillmentGroupItem != null) { FulfillmentGroupItem newFulfillmentGroupItem = fulfillmentGroupItem.clone(); newFulfillmentGroupItem.setOrderItem(discreteOrderItem); newFulfillmentGroupItem.setQuantity(discreteOrderItem.getQuantity()); //In case this activity is run inside a transaction, we need to set the relationships on the order directly //these associations may have not been committed yet. This order is used in other activities and will not be reloaded if in a transaction. for (FulfillmentGroup fg : order.getFulfillmentGroups()) { if (newFulfillmentGroupItem.getFulfillmentGroup() != null && fg.getId().equals(newFulfillmentGroupItem.getFulfillmentGroup().getId())) { fg.addFulfillmentGroupItem(newFulfillmentGroupItem); } } } } } } //reload order with new fulfillment group items order = orderService.save(order, false); return order; } protected int countExistingUsesOfBundle(Order order, ProductBundle bundle) { int existingUses=0; for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof BundleOrderItem) { BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItem; if (bundleOrderItem.getProductBundle() != null) { if (bundleOrderItem.getProductBundle().getId().equals(bundle.getId())) { existingUses = existingUses+1; } } } } return existingUses; } protected int populateItemMatchesForSku(List<DiscreteOrderItem> matchingItems, Order order, List<DiscreteOrderItem> unbundledItems, Long skuId) { int skuMatches = 0; for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof DiscreteOrderItem) { DiscreteOrderItem item = (DiscreteOrderItem) orderItem; if (skuId.equals(item.getSku().getId())) { matchingItems.add(item); skuMatches = skuMatches + item.getQuantity(); } } } if (unbundledItems != null) { for (DiscreteOrderItem discreteOrderItem : unbundledItems) { if (skuId.equals(discreteOrderItem.getSku().getId())) { skuMatches = skuMatches + discreteOrderItem.getQuantity(); } } } return skuMatches; } protected int countMaximumApplications(Order order, SkuBundleItem skuBundleItem, Set<Long> processedBundles) { int skuMatches = 0; Long skuId = skuBundleItem.getSku().getId(); for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof DiscreteOrderItem) { DiscreteOrderItem item = (DiscreteOrderItem) orderItem; if (skuId.equals(item.getSku().getId())) { skuMatches = skuMatches + item.getQuantity(); } } else if (orderItem instanceof BundleOrderItem) { BundleOrderItem bundleItem = (BundleOrderItem) orderItem; if (bundleItem.getProductBundle() != null && bundleItem.getProductBundle().getAutoBundle()) { if (! processedBundles.contains(bundleItem.getId())) { for(DiscreteOrderItem discreteItem : bundleItem.getDiscreteOrderItems()) { if (skuId.equals(discreteItem.getSku().getId())) { skuMatches = skuMatches + (discreteItem.getQuantity() * bundleItem.getQuantity()); } } } } } } return skuMatches / skuBundleItem.getQuantity(); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_workflow_AutoBundleActivity.java
304
public class SourceTransfer extends ByteArrayTransfer { public static final SourceTransfer INSTANCE = new SourceTransfer(); private static final String TYPE_NAME = "ceylon-source-transfer-format" + System.currentTimeMillis(); private static final int TYPEID = registerType(TYPE_NAME); public static String text; @Override protected int[] getTypeIds() { return new int[] { TYPEID }; } @Override protected String[] getTypeNames() { return new String[] { TYPE_NAME }; } @Override protected void javaToNative(Object object, TransferData transferData) { text = (String) object; super.javaToNative(new byte[1], transferData); } @Override protected String nativeToJava(TransferData transferData) { return text; } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_SourceTransfer.java
1,147
public class OSQLMethodKeys extends OAbstractSQLMethod { public static final String NAME = "keys"; public OSQLMethodKeys() { super(NAME); } @Override public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) { ioResult = ioResult != null && ioResult instanceof Map<?, ?> ? ((Map<?, ?>) ioResult).keySet() : null; return ioResult; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodKeys.java
245
private static class AnalyzingComparator implements Comparator<BytesRef> { private final boolean hasPayloads; public AnalyzingComparator(boolean hasPayloads) { this.hasPayloads = hasPayloads; } private final ByteArrayDataInput readerA = new ByteArrayDataInput(); private final ByteArrayDataInput readerB = new ByteArrayDataInput(); private final BytesRef scratchA = new BytesRef(); private final BytesRef scratchB = new BytesRef(); @Override public int compare(BytesRef a, BytesRef b) { // First by analyzed form: readerA.reset(a.bytes, a.offset, a.length); scratchA.length = readerA.readShort(); scratchA.bytes = a.bytes; scratchA.offset = readerA.getPosition(); readerB.reset(b.bytes, b.offset, b.length); scratchB.bytes = b.bytes; scratchB.length = readerB.readShort(); scratchB.offset = readerB.getPosition(); int cmp = scratchA.compareTo(scratchB); if (cmp != 0) { return cmp; } readerA.skipBytes(scratchA.length); readerB.skipBytes(scratchB.length); // Next by cost: long aCost = readerA.readInt(); long bCost = readerB.readInt(); if (aCost < bCost) { return -1; } else if (aCost > bCost) { return 1; } // Finally by surface form: if (hasPayloads) { scratchA.length = readerA.readShort(); scratchA.offset = readerA.getPosition(); scratchB.length = readerB.readShort(); scratchB.offset = readerB.getPosition(); } else { scratchA.offset = readerA.getPosition(); scratchA.length = a.length - scratchA.offset; scratchB.offset = readerB.getPosition(); scratchB.length = b.length - scratchB.offset; } return scratchA.compareTo(scratchB); } }
0true
src_main_java_org_apache_lucene_search_suggest_analyzing_XAnalyzingSuggester.java
509
public class OEntityManager { private static Map<String, OEntityManager> databaseInstances = new HashMap<String, OEntityManager>(); private OEntityManagerClassHandler classHandler = new OEntityManagerClassHandler(); protected OEntityManager() { OLogManager.instance().debug(this, "Registering entity manager"); classHandler.registerEntityClass(OUser.class); classHandler.registerEntityClass(ORole.class); } public static synchronized OEntityManager getEntityManagerByDatabaseURL(final String iURL) { OEntityManager instance = databaseInstances.get(iURL); if (instance == null) { instance = new OEntityManager(); databaseInstances.put(iURL, instance); } return instance; } /** * Create a POJO by its class name. * * @see #registerEntityClasses(String) */ public synchronized Object createPojo(final String iClassName) throws OConfigurationException { if (iClassName == null) throw new IllegalArgumentException("Cannot create the object: class name is empty"); final Class<?> entityClass = classHandler.getEntityClass(iClassName); try { if (entityClass != null) return createInstance(entityClass); } catch (Exception e) { throw new OConfigurationException("Error while creating new pojo of class '" + iClassName + "'", e); } try { // TRY TO INSTANTIATE THE CLASS DIRECTLY BY ITS NAME return createInstance(Class.forName(iClassName)); } catch (Exception e) { throw new OConfigurationException("The class '" + iClassName + "' was not found between the entity classes. Ensure registerEntityClasses(package) has been called first.", e); } } /** * Returns the Java class by its name * * @param iClassName * Simple class name without the package * @return Returns the Java class by its name */ public synchronized Class<?> getEntityClass(final String iClassName) { return classHandler.getEntityClass(iClassName); } public synchronized void deregisterEntityClass(final Class<?> iClass) { classHandler.deregisterEntityClass(iClass); } public synchronized void deregisterEntityClasses(final String iPackageName) { deregisterEntityClasses(iPackageName, Thread.currentThread().getContextClassLoader()); } /** * Scans all classes accessible from the context class loader which belong to the given package and subpackages. * * @param iPackageName * The base package */ public synchronized void deregisterEntityClasses(final String iPackageName, final ClassLoader iClassLoader) { OLogManager.instance().debug(this, "Discovering entity classes inside package: %s", iPackageName); List<Class<?>> classes = null; try { classes = OReflectionHelper.getClassesFor(iPackageName, iClassLoader); } catch (ClassNotFoundException e) { throw new OException(e); } for (Class<?> c : classes) { deregisterEntityClass(c); } if (OLogManager.instance().isDebugEnabled()) { for (Entry<String, Class<?>> entry : classHandler.getClassesEntrySet()) { OLogManager.instance().debug(this, "Unloaded entity class '%s' from: %s", entry.getKey(), entry.getValue()); } } } public synchronized void registerEntityClass(final Class<?> iClass) { classHandler.registerEntityClass(iClass); } /** * Registers provided classes * * @param iClassNames * to be registered */ public synchronized void registerEntityClasses(final Collection<String> iClassNames) { registerEntityClasses(iClassNames, Thread.currentThread().getContextClassLoader()); } /** * Registers provided classes * * @param iClassNames * to be registered * @param iClassLoader */ public synchronized void registerEntityClasses(final Collection<String> iClassNames, final ClassLoader iClassLoader) { OLogManager.instance().debug(this, "Discovering entity classes for class names: %s", iClassNames); try { registerEntityClasses(OReflectionHelper.getClassesFor(iClassNames, iClassLoader)); } catch (ClassNotFoundException e) { throw new OException(e); } } /** * Scans all classes accessible from the context class loader which belong to the given package and subpackages. * * @param iPackageName * The base package */ public synchronized void registerEntityClasses(final String iPackageName) { registerEntityClasses(iPackageName, Thread.currentThread().getContextClassLoader()); } /** * Scans all classes accessible from the context class loader which belong to the given package and subpackages. * * @param iPackageName * The base package * @param iClassLoader */ public synchronized void registerEntityClasses(final String iPackageName, final ClassLoader iClassLoader) { OLogManager.instance().debug(this, "Discovering entity classes inside package: %s", iPackageName); try { registerEntityClasses(OReflectionHelper.getClassesFor(iPackageName, iClassLoader)); } catch (ClassNotFoundException e) { throw new OException(e); } } protected synchronized void registerEntityClasses(final List<Class<?>> classes) { for (Class<?> c : classes) { if (!classHandler.containsEntityClass(c)) { if (c.isAnonymousClass()) { OLogManager.instance().debug(this, "Skip registration of anonymous class '%s'.", c.getName()); continue; } classHandler.registerEntityClass(c); } } if (OLogManager.instance().isDebugEnabled()) { for (Entry<String, Class<?>> entry : classHandler.getClassesEntrySet()) { OLogManager.instance().debug(this, "Loaded entity class '%s' from: %s", entry.getKey(), entry.getValue()); } } } /** * Sets the received handler as default and merges the classes all together. * * @param iClassHandler */ public synchronized void setClassHandler(final OEntityManagerClassHandler iClassHandler) { for (Entry<String, Class<?>> entry : classHandler.getClassesEntrySet()) { iClassHandler.registerEntityClass(entry.getValue()); } this.classHandler = iClassHandler; } public synchronized Collection<Class<?>> getRegisteredEntities() { return classHandler.getRegisteredEntities(); } protected Object createInstance(final Class<?> iClass) throws InstantiationException, IllegalAccessException, InvocationTargetException { return classHandler.createInstance(iClass); } }
0true
core_src_main_java_com_orientechnologies_orient_core_entity_OEntityManager.java
2,696
public class LocalGateway extends AbstractLifecycleComponent<Gateway> implements Gateway, ClusterStateListener { private final ClusterService clusterService; private final NodeEnvironment nodeEnv; private final LocalGatewayShardsState shardsState; private final LocalGatewayMetaState metaState; private final TransportNodesListGatewayMetaState listGatewayMetaState; private final String initialMeta; @Inject public LocalGateway(Settings settings, ClusterService clusterService, NodeEnvironment nodeEnv, LocalGatewayShardsState shardsState, LocalGatewayMetaState metaState, TransportNodesListGatewayMetaState listGatewayMetaState) { super(settings); this.clusterService = clusterService; this.nodeEnv = nodeEnv; this.metaState = metaState; this.listGatewayMetaState = listGatewayMetaState; this.shardsState = shardsState; clusterService.addLast(this); // we define what is our minimum "master" nodes, use that to allow for recovery this.initialMeta = componentSettings.get("initial_meta", settings.get("discovery.zen.minimum_master_nodes", "1")); } @Override public String type() { return "local"; } @Override protected void doStart() throws ElasticsearchException { } @Override protected void doStop() throws ElasticsearchException { } @Override protected void doClose() throws ElasticsearchException { clusterService.remove(this); } @Override public void performStateRecovery(final GatewayStateRecoveredListener listener) throws GatewayException { ObjectOpenHashSet<String> nodesIds = ObjectOpenHashSet.from(clusterService.state().nodes().masterNodes().keys()); logger.trace("performing state recovery from {}", nodesIds); TransportNodesListGatewayMetaState.NodesLocalGatewayMetaState nodesState = listGatewayMetaState.list(nodesIds.toArray(String.class), null).actionGet(); int requiredAllocation = 1; try { if ("quorum".equals(initialMeta)) { if (nodesIds.size() > 2) { requiredAllocation = (nodesIds.size() / 2) + 1; } } else if ("quorum-1".equals(initialMeta) || "half".equals(initialMeta)) { if (nodesIds.size() > 2) { requiredAllocation = ((1 + nodesIds.size()) / 2); } } else if ("one".equals(initialMeta)) { requiredAllocation = 1; } else if ("full".equals(initialMeta) || "all".equals(initialMeta)) { requiredAllocation = nodesIds.size(); } else if ("full-1".equals(initialMeta) || "all-1".equals(initialMeta)) { if (nodesIds.size() > 1) { requiredAllocation = nodesIds.size() - 1; } } else { requiredAllocation = Integer.parseInt(initialMeta); } } catch (Exception e) { logger.warn("failed to derived initial_meta from value {}", initialMeta); } if (nodesState.failures().length > 0) { for (FailedNodeException failedNodeException : nodesState.failures()) { logger.warn("failed to fetch state from node", failedNodeException); } } ObjectFloatOpenHashMap<String> indices = new ObjectFloatOpenHashMap<String>(); MetaData electedGlobalState = null; int found = 0; for (TransportNodesListGatewayMetaState.NodeLocalGatewayMetaState nodeState : nodesState) { if (nodeState.metaData() == null) { continue; } found++; if (electedGlobalState == null) { electedGlobalState = nodeState.metaData(); } else if (nodeState.metaData().version() > electedGlobalState.version()) { electedGlobalState = nodeState.metaData(); } for (ObjectCursor<IndexMetaData> cursor : nodeState.metaData().indices().values()) { indices.addTo(cursor.value.index(), 1); } } if (found < requiredAllocation) { listener.onFailure("found [" + found + "] metadata states, required [" + requiredAllocation + "]"); return; } // update the global state, and clean the indices, we elect them in the next phase MetaData.Builder metaDataBuilder = MetaData.builder(electedGlobalState).removeAllIndices(); final boolean[] states = indices.allocated; final Object[] keys = indices.keys; for (int i = 0; i < states.length; i++) { if (states[i]) { String index = (String) keys[i]; IndexMetaData electedIndexMetaData = null; int indexMetaDataCount = 0; for (TransportNodesListGatewayMetaState.NodeLocalGatewayMetaState nodeState : nodesState) { if (nodeState.metaData() == null) { continue; } IndexMetaData indexMetaData = nodeState.metaData().index(index); if (indexMetaData == null) { continue; } if (electedIndexMetaData == null) { electedIndexMetaData = indexMetaData; } else if (indexMetaData.version() > electedIndexMetaData.version()) { electedIndexMetaData = indexMetaData; } indexMetaDataCount++; } if (electedIndexMetaData != null) { if (indexMetaDataCount < requiredAllocation) { logger.debug("[{}] found [{}], required [{}], not adding", index, indexMetaDataCount, requiredAllocation); } metaDataBuilder.put(electedIndexMetaData, false); } } } ClusterState.Builder builder = ClusterState.builder(); builder.metaData(metaDataBuilder); listener.onSuccess(builder.build()); } @Override public Class<? extends Module> suggestIndexGateway() { return LocalIndexGatewayModule.class; } @Override public void reset() throws Exception { FileSystemUtils.deleteRecursively(nodeEnv.nodeDataLocations()); } @Override public void clusterChanged(final ClusterChangedEvent event) { // order is important, first metaState, and then shardsState // so dangling indices will be recorded metaState.clusterChanged(event); shardsState.clusterChanged(event); } }
0true
src_main_java_org_elasticsearch_gateway_local_LocalGateway.java
60
class AddParameterProposal extends InitializerProposal { private AddParameterProposal(Declaration d, Declaration dec, ProducedType type, int offset, int len, TextChange change, int exitPos, CeylonEditor editor) { super("Add '" + d.getName() + "' to parameter list of '" + dec.getName() + "'", change, dec, type, new Region(offset, len), ADD_CORR, exitPos, editor); } private static void addParameterProposal(Tree.CompilationUnit cu, Collection<ICompletionProposal> proposals, IFile file, Tree.TypedDeclaration decNode, Tree.SpecifierOrInitializerExpression sie, Node node, CeylonEditor editor) { MethodOrValue dec = (MethodOrValue) decNode.getDeclarationModel(); if (dec==null) return; if (dec.getInitializerParameter()==null && !dec.isFormal()) { TextChange change = new TextFileChange("Add Parameter", file); change.setEdit(new MultiTextEdit()); IDocument doc = EditorUtil.getDocument(change); //TODO: copy/pasted from SplitDeclarationProposal String params = null; if (decNode instanceof Tree.MethodDeclaration) { List<ParameterList> pls = ((Tree.MethodDeclaration) decNode).getParameterLists(); if (pls.isEmpty()) { return; } else { Integer start = pls.get(0).getStartIndex(); Integer end = pls.get(pls.size()-1).getStopIndex(); try { params = doc.get(start, end-start+1); } catch (BadLocationException e) { e.printStackTrace(); return; } } } Tree.Declaration container = findDeclarationWithBody(cu, decNode); Tree.ParameterList pl; if (container instanceof Tree.ClassDefinition) { pl = ((Tree.ClassDefinition) container).getParameterList(); if (pl==null) { return; } } else if (container instanceof Tree.MethodDefinition) { List<Tree.ParameterList> pls = ((Tree.MethodDefinition) container).getParameterLists(); if (pls.isEmpty()) { return; } pl = pls.get(0); } else { return; } String def; int len; if (sie==null) { String defaultValue = defaultValue(cu.getUnit(), dec.getType()); len = defaultValue.length(); if (decNode instanceof Tree.MethodDeclaration) { def = " => " + defaultValue; } else { def = " = " + defaultValue; } } else { len = 0; int start; try { def = doc.get(sie.getStartIndex(), sie.getStopIndex()-sie.getStartIndex()+1); start = sie.getStartIndex(); if (start>0 && doc.get(start-1,1).equals(" ")) { start--; def = " " + def; } } catch (BadLocationException e) { e.printStackTrace(); return; } change.addEdit(new DeleteEdit(start, sie.getStopIndex()-start+1)); } if (params!=null) { def = " = " + params + def; } String param = (pl.getParameters().isEmpty() ? "" : ", ") + dec.getName() + def; Integer offset = pl.getStopIndex(); change.addEdit(new InsertEdit(offset, param)); Tree.Type type = decNode.getType(); int shift=0; ProducedType paramType; if (type instanceof Tree.LocalModifier) { Integer typeOffset = type.getStartIndex(); paramType = type.getTypeModel(); String explicitType; if (paramType==null) { explicitType = "Object"; paramType = type.getUnit().getObjectDeclaration().getType(); } else { explicitType = paramType.getProducedTypeName(); HashSet<Declaration> decs = new HashSet<Declaration>(); importType(decs, paramType, cu); shift = applyImports(change, decs, cu, doc); } change.addEdit(new ReplaceEdit(typeOffset, type.getText().length(), explicitType)); } else { paramType = type.getTypeModel(); } int exitPos = node.getStopIndex()+1; proposals.add(new AddParameterProposal(dec, container.getDeclarationModel(), paramType, offset+param.length()+shift-len, len, change, exitPos, editor)); } } static void addParameterProposals(Collection<ICompletionProposal> proposals, IFile file, Tree.CompilationUnit cu, Node node, CeylonEditor editor) { if (node instanceof Tree.AttributeDeclaration) { Tree.AttributeDeclaration attDecNode = (Tree.AttributeDeclaration) node; Tree.SpecifierOrInitializerExpression sie = attDecNode.getSpecifierOrInitializerExpression(); if (!(sie instanceof Tree.LazySpecifierExpression)) { addParameterProposal(cu, proposals, file, attDecNode, sie, node, editor); } } if (node instanceof Tree.MethodDeclaration) { Tree.MethodDeclaration methDecNode = (Tree.MethodDeclaration) node; Tree.SpecifierExpression sie = methDecNode.getSpecifierExpression(); addParameterProposal(cu, proposals, file, methDecNode, sie, node, editor); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddParameterProposal.java
1,807
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class MapClientRequestTest extends ClientTestSupport { static final String mapName = "test"; protected Config createConfig() { return new Config(); } private IMap getMap() { return getInstance().getMap(mapName); } @Test public void testPutGetSet() throws IOException { final SimpleClient client = getClient(); client.send(new MapPutRequest(mapName, TestUtil.toData(1), TestUtil.toData(3), ThreadUtil.getThreadId())); assertNull(client.receive()); client.send(new MapPutRequest(mapName, TestUtil.toData(1), TestUtil.toData(5), ThreadUtil.getThreadId())); assertEquals(3, client.receive()); client.send(new MapGetRequest(mapName, TestUtil.toData(1))); assertEquals(5, client.receive()); client.send(new MapGetRequest(mapName, TestUtil.toData(7))); assertNull(client.receive()); client.send(new MapSetRequest(mapName, TestUtil.toData(1), TestUtil.toData(7), ThreadUtil.getThreadId())); assertFalse((Boolean)client.receive()); client.send(new MapGetRequest(mapName, TestUtil.toData(1))); assertEquals(7, client.receive()); client.send(new MapPutTransientRequest(mapName, TestUtil.toData(1), TestUtil.toData(9), ThreadUtil.getThreadId())); client.receive(); client.send(new MapGetRequest(mapName, TestUtil.toData(1))); assertEquals(9, client.receive()); } @Test public void testMapSize() throws IOException { int size = 100; final IMap map = getMap(); for (int i = 0; i < size; i++) { map.put("-" + i, "-" + i); } final SimpleClient client = getClient(); client.send(new MapSizeRequest(mapName)); assertEquals(size, client.receive()); } @Test public void testMapKeyset() throws IOException { int size = 100; Set testSet = new HashSet(); final IMap map = getMap(); for (int i = 0; i < size; i++) { map.put(i, "v" + i); testSet.add(i); } final SimpleClient client = getClient(); client.send(new MapKeySetRequest(mapName)); MapKeySet keyset = (MapKeySet) client.receive(); for (Data o : keyset.getKeySet()) { Object x = TestUtil.toObject(o); assertTrue(testSet.remove(x)); } assertEquals(0, testSet.size()); } @Test public void testMapValues() throws IOException { int size = 100; Set testSet = new HashSet(); final IMap map = getMap(); for (int i = 0; i < size; i++) { map.put(i, "v" + i); testSet.add("v" + i); } final SimpleClient client = getClient(); client.send(new MapValuesRequest(mapName)); MapValueCollection values = (MapValueCollection) client.receive(); for (Data o : values.getValues()) { Object x = TestUtil.toObject(o); assertTrue(testSet.remove(x)); } assertEquals(0, testSet.size()); } @Test public void testMapContainsKeyValue() throws IOException { int size = 100; final SimpleClient client = getClient(); client.send(new MapContainsKeyRequest(mapName, TestUtil.toData("-"))); assertFalse((Boolean) client.receive()); for (int i = 0; i < size; i++) { getMap().put("-" + i, "-" + i); } for (int i = 0; i < size; i++) { client.send(new MapContainsKeyRequest(mapName, TestUtil.toData("-" + i))); assertTrue((Boolean) client.receive()); } client.send(new MapContainsKeyRequest(mapName, TestUtil.toData("-"))); assertFalse((Boolean) client.receive()); client.send(new MapContainsValueRequest(mapName, TestUtil.toData("-"))); assertFalse((Boolean) client.receive()); for (int i = 0; i < size; i++) { client.send(new MapContainsValueRequest(mapName, TestUtil.toData("-" + i))); assertTrue((Boolean) client.receive()); } client.send(new MapContainsValueRequest(mapName, TestUtil.toData("--"))); assertFalse((Boolean) client.receive()); } @Test public void testMapRemoveDeleteEvict() throws IOException { final IMap map = getMap(); final SimpleClient client = getClient(); for (int i = 0; i < 100; i++) { map.put(i, i); } for (int i = 0; i < 100; i++) { getClient().send(new MapRemoveRequest(mapName, TestUtil.toData(i), ThreadUtil.getThreadId())); assertEquals(i, client.receive()); } for (int i = 0; i < 100; i++) { map.put(i, i); } for (int i = 0; i < 100; i++) { client.send(new MapDeleteRequest(mapName, TestUtil.toData(i), ThreadUtil.getThreadId())); client.receive(); assertNull(map.get(i)); } for (int i = 0; i < 100; i++) { map.put(i, i); } for (int i = 0; i < 100; i++) { client.send(new MapEvictRequest(mapName, TestUtil.toData(i), ThreadUtil.getThreadId())); client.receive(); assertNull(map.get(i)); } assertEquals(0, map.size()); } @Test public void testRemoveIfSame() throws IOException { getMap().put(1, 5); final SimpleClient client = getClient(); client.send(new MapRemoveIfSameRequest(mapName, TestUtil.toData(1), TestUtil.toData(3), ThreadUtil.getThreadId())); assertEquals(false, client.receive()); client.send(new MapRemoveIfSameRequest(mapName, TestUtil.toData(1), TestUtil.toData(5), ThreadUtil.getThreadId())); assertEquals(true, client.receive()); assertEquals(0, getMap().size()); } @Test public void testPutIfAbsent() throws IOException { final IMap map = getMap(); map.put(1, 3); final SimpleClient client = getClient(); client.send(new MapPutIfAbsentRequest(mapName, TestUtil.toData(1), TestUtil.toData(5), ThreadUtil.getThreadId())); assertEquals(3, client.receive()); client.send(new MapPutIfAbsentRequest(mapName, TestUtil.toData(2), TestUtil.toData(5), ThreadUtil.getThreadId())); assertEquals(null, client.receive()); assertEquals(5, map.get(2)); } @Test public void testMapReplace() throws IOException { final IMap map = getMap(); map.put(1, 2); final SimpleClient client = getClient(); client.send(new MapReplaceRequest(mapName, TestUtil.toData(1), TestUtil.toData(3), ThreadUtil.getThreadId())); assertEquals(2, client.receive()); assertEquals(3, map.get(1)); client.send(new MapReplaceRequest(mapName, TestUtil.toData(2), TestUtil.toData(3), ThreadUtil.getThreadId())); client.receive(); assertEquals(null, map.get(2)); client.send(new MapReplaceIfSameRequest(mapName, TestUtil.toData(1), TestUtil.toData(3), TestUtil.toData(5), ThreadUtil.getThreadId())); assertEquals(true, client.receive()); assertEquals(5, map.get(1)); client.send(new MapReplaceIfSameRequest(mapName, TestUtil.toData(1), TestUtil.toData(0), TestUtil.toData(7), ThreadUtil.getThreadId())); assertEquals(false, client.receive()); assertEquals(5, map.get(1)); } @Test public void testMapTryPutRemove() throws IOException { final SimpleClient client = getClient(); client.send(new MapLockRequest(mapName, TestUtil.toData(1), ThreadUtil.getThreadId() + 1)); client.receive(); assertEquals(true, getMap().isLocked(1)); client.send(new MapTryPutRequest(mapName, TestUtil.toData(1), TestUtil.toData(1), ThreadUtil.getThreadId(), 0)); assertEquals(false, client.receive()); client.send(new MapTryRemoveRequest(mapName, TestUtil.toData(1), ThreadUtil.getThreadId(), 0)); assertEquals(false, client.receive()); } @Test public void testMapLockUnlock() throws IOException { final SimpleClient client = getClient(); client.send(new MapLockRequest(mapName, TestUtil.toData(1), ThreadUtil.getThreadId())); client.receive(); final IMap map = getMap(); assertEquals(true, map.isLocked(1)); client.send(new MapUnlockRequest(mapName, TestUtil.toData(1), ThreadUtil.getThreadId())); client.receive(); assertEquals(false, map.isLocked(1)); } @Test public void testMapIsLocked() throws IOException { final IMap map = getMap(); map.lock(1); final SimpleClient client = getClient(); client.send(new MapIsLockedRequest(mapName, TestUtil.toData(1))); assertEquals(true, client.receive()); map.unlock(1); client.send(new MapIsLockedRequest(mapName, TestUtil.toData(1))); assertEquals(false, client.receive()); } @Test public void testMapQuery() throws IOException { Set testSet = new HashSet(); testSet.add("serra"); testSet.add("met"); final IMap map = getMap(); map.put(1, new Employee("enes", 29, true, 100d)); map.put(2, new Employee("serra", 3, true, 100d)); map.put(3, new Employee("met", 7, true, 100d)); MapQueryRequest request = new MapQueryRequest(mapName, new SqlPredicate("age < 10"), IterationType.VALUE); final SimpleClient client = getClient(); client.send(request); Object receive = client.receive(); QueryResultSet result = (QueryResultSet) receive; for (Object aResult : result) { Employee x = (Employee) TestUtil.toObject((Data) aResult); testSet.remove(x.getName()); } assertEquals(0, testSet.size()); } @Test public void testEntryProcessorWithPredicate() throws IOException { final IMap map = getMap(); int size = 10; for (int i = 0; i < size; i++) { map.put(i, new SampleObjects.Employee(i, "", 0, false, 0D, SampleObjects.State.STATE1)); } EntryProcessor entryProcessor = new ChangeStateEntryProcessor(); EntryObject e = new PredicateBuilder().getEntryObject(); Predicate p = e.get("id").lessThan(5); MapExecuteWithPredicateRequest request = new MapExecuteWithPredicateRequest(map.getName(), entryProcessor, p); final SimpleClient client = getClient(); client.send(request); MapEntrySet entrySet = (MapEntrySet) client.receive(); Map<Integer, Employee> result = new HashMap<Integer, Employee>(); for (Map.Entry<Data, Data> dataEntry : entrySet.getEntrySet()) { final Data keyData = dataEntry.getKey(); final Data valueData = dataEntry.getValue(); Integer key = (Integer)TestUtil.toObject(keyData); result.put(key, (Employee)TestUtil.toObject(valueData)); } assertEquals(5,entrySet.getEntrySet().size()); for (int i = 0; i < 5; i++) { assertEquals(SampleObjects.State.STATE2, ((Employee) map.get(i)).getState()); } for (int i = 5; i < size; i++) { assertEquals(SampleObjects.State.STATE1, ((Employee)map.get(i)).getState()); } for (int i = 0; i < 5; i++) { assertEquals(result.get(i).getState(), SampleObjects.State.STATE2); } } private static class ChangeStateEntryProcessor implements EntryProcessor, EntryBackupProcessor { ChangeStateEntryProcessor() { } public Object process(Map.Entry entry) { SampleObjects.Employee value = (SampleObjects.Employee) entry.getValue(); value.setState(SampleObjects.State.STATE2); entry.setValue(value); return value; } public EntryBackupProcessor getBackupProcessor() { return ChangeStateEntryProcessor.this; } public void processBackup(Map.Entry entry) { SampleObjects.Employee value = (SampleObjects.Employee) entry.getValue(); value.setState(SampleObjects.State.STATE2); entry.setValue(value); } } }
0true
hazelcast_src_test_java_com_hazelcast_map_MapClientRequestTest.java
268
public class PlaceboTm extends AbstractTransactionManager { private LockManager lockManager; private final TxIdGenerator txIdGenerator; private final Transaction tx = new PlaceboTransaction(); public PlaceboTm( LockManager lockManager, TxIdGenerator txIdGenerator ) { this.lockManager = lockManager; this.txIdGenerator = txIdGenerator; } public void setLockManager( LockManager lockManager ) { this.lockManager = lockManager; } @Override public void begin() throws NotSupportedException, SystemException { } @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { } @Override public int getStatus() throws SystemException { return Status.STATUS_ACTIVE; } @Override public Transaction getTransaction() throws SystemException { return tx; } @Override public void resume( Transaction arg0 ) throws InvalidTransactionException, IllegalStateException, SystemException { } @Override public void rollback() throws IllegalStateException, SecurityException, SystemException { } @Override public void setRollbackOnly() throws IllegalStateException, SystemException { } @Override public void setTransactionTimeout( int arg0 ) throws SystemException { } @Override public Transaction suspend() throws SystemException { return null; } @Override public void init() { } @Override public void start() throws Throwable { } @Override public void stop() { } @Override public void shutdown() throws Throwable { } @Override public int getEventIdentifier() { return 0; } @Override public void doRecovery() throws Throwable { } @Override public TransactionState getTransactionState() { return new NoTransactionState() { @Override public LockElement acquireReadLock( Object resource ) { try { Transaction tx = getTransaction(); lockManager.getReadLock( resource, tx ); return new LockElement( resource, tx, LockType.READ, lockManager ); } catch ( Exception e ) { throw launderedException( e ); } } @Override public LockElement acquireWriteLock( Object resource ) { try { Transaction tx = getTransaction(); lockManager.getWriteLock( resource, tx ); return new LockElement( resource, tx, LockType.WRITE, lockManager ); } catch ( SystemException e ) { throw launderedException( e ); } } @Override public TxIdGenerator getTxIdGenerator() { return txIdGenerator; } }; } private static class PlaceboTransaction implements Transaction { @Override public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException { } @Override public boolean delistResource( XAResource xaRes, int flag ) throws IllegalStateException, SystemException { return true; } @Override public boolean enlistResource( XAResource xaRes ) throws IllegalStateException, RollbackException, SystemException { return true; } @Override public int getStatus() throws SystemException { return Status.STATUS_ACTIVE; } @Override public void registerSynchronization( Synchronization synch ) throws IllegalStateException, RollbackException, SystemException { } @Override public void rollback() throws IllegalStateException, SystemException { } @Override public void setRollbackOnly() throws IllegalStateException, SystemException { } } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_PlaceboTm.java
831
cls = getDatabase().getStorage().callInLock(new Callable<OClass>() { @Override public OClass call() throws Exception { return classes.get(iClassName.toLowerCase()); } }, false);
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OSchemaShared.java
1,790
public class HppcMapsTests extends ElasticsearchTestCase { @Test public void testIntersection() throws Exception { assumeTrue(ASSERTIONS_ENABLED); ObjectOpenHashSet<String> set1 = ObjectOpenHashSet.from("1", "2", "3"); ObjectOpenHashSet<String> set2 = ObjectOpenHashSet.from("1", "2", "3"); List<String> values = toList(HppcMaps.intersection(set1, set2)); assertThat(values.size(), equalTo(3)); assertThat(values.contains("1"), equalTo(true)); assertThat(values.contains("2"), equalTo(true)); assertThat(values.contains("3"), equalTo(true)); set1 = ObjectOpenHashSet.from("1", "2", "3"); set2 = ObjectOpenHashSet.from("3", "4", "5"); values = toList(HppcMaps.intersection(set1, set2)); assertThat(values.size(), equalTo(1)); assertThat(values.get(0), equalTo("3")); set1 = ObjectOpenHashSet.from("1", "2", "3"); set2 = ObjectOpenHashSet.from("4", "5", "6"); values = toList(HppcMaps.intersection(set1, set2)); assertThat(values.size(), equalTo(0)); set1 = ObjectOpenHashSet.from(); set2 = ObjectOpenHashSet.from("3", "4", "5"); values = toList(HppcMaps.intersection(set1, set2)); assertThat(values.size(), equalTo(0)); set1 = ObjectOpenHashSet.from("1", "2", "3"); set2 = ObjectOpenHashSet.from(); values = toList(HppcMaps.intersection(set1, set2)); assertThat(values.size(), equalTo(0)); set1 = ObjectOpenHashSet.from(); set2 = ObjectOpenHashSet.from(); values = toList(HppcMaps.intersection(set1, set2)); assertThat(values.size(), equalTo(0)); set1 = null; set2 = ObjectOpenHashSet.from(); try { toList(HppcMaps.intersection(set1, set2)); fail(); } catch (AssertionError e) {} set1 = ObjectOpenHashSet.from(); set2 = null; try { toList(HppcMaps.intersection(set1, set2)); fail(); } catch (AssertionError e) {} set1 = null; set2 = null; try { toList(HppcMaps.intersection(set1, set2)); fail(); } catch (AssertionError e) {} } private List<String> toList(Iterable<String> iterable) { List<String> list = new ArrayList<String>(); for (String s : iterable) { list.add(s); } return list; } }
0true
src_test_java_org_elasticsearch_common_hppc_HppcMapsTests.java
4,199
static final class Fields { static final XContentBuilderString NAME = new XContentBuilderString("name"); static final XContentBuilderString PHYSICAL_NAME = new XContentBuilderString("physical_name"); static final XContentBuilderString LENGTH = new XContentBuilderString("length"); static final XContentBuilderString CHECKSUM = new XContentBuilderString("checksum"); static final XContentBuilderString PART_SIZE = new XContentBuilderString("part_size"); }
1no label
src_main_java_org_elasticsearch_index_snapshots_blobstore_BlobStoreIndexShardSnapshot.java
825
public class GetOperation extends AtomicLongBaseOperation { private long returnValue; public GetOperation() { } public GetOperation(String name) { super(name); } @Override public void run() throws Exception { LongWrapper number = getNumber(); returnValue = number.get(); } @Override public int getId() { return AtomicLongDataSerializerHook.GET; } @Override public Object getResponse() { return returnValue; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_operations_GetOperation.java
2,854
final class PromoteFromBackupOperation extends AbstractOperation implements PartitionAwareOperation, MigrationCycleOperation { @Override public void run() throws Exception { logPromotingPartition(); PartitionMigrationEvent event = createPartitionMigrationEvent(); sendToAllMigrationAwareServices(event); } private void sendToAllMigrationAwareServices(PartitionMigrationEvent event) { NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine(); for (MigrationAwareService service : nodeEngine.getServices(MigrationAwareService.class)) { try { service.beforeMigration(event); service.commitMigration(event); } catch (Throwable e) { logMigrationError(e); } } } private PartitionMigrationEvent createPartitionMigrationEvent() { int partitionId = getPartitionId(); return new PartitionMigrationEvent(MigrationEndpoint.DESTINATION, partitionId); } private void logMigrationError(Throwable e) { ILogger logger = getLogger(); logger.warning("While promoting partition " + getPartitionId(), e); } private void logPromotingPartition() { ILogger logger = getLogger(); if (logger.isFinestEnabled()) { logger.finest("Promoting partition " + getPartitionId()); } } @Override public boolean returnsResponse() { return false; } @Override public boolean validatesTarget() { return false; } @Override protected void readInternal(ObjectDataInput in) throws IOException { throw new UnsupportedOperationException(); } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { throw new UnsupportedOperationException(); } }
1no label
hazelcast_src_main_java_com_hazelcast_partition_impl_PromoteFromBackupOperation.java
2,002
private static class InSubpackage extends AbstractMatcher<Class> implements Serializable { private final String targetPackageName; public InSubpackage(String targetPackageName) { this.targetPackageName = targetPackageName; } public boolean matches(Class c) { String classPackageName = c.getPackage().getName(); return classPackageName.equals(targetPackageName) || classPackageName.startsWith(targetPackageName + "."); } @Override public boolean equals(Object other) { return other instanceof InSubpackage && ((InSubpackage) other).targetPackageName.equals(targetPackageName); } @Override public int hashCode() { return 37 * targetPackageName.hashCode(); } @Override public String toString() { return "inSubpackage(" + targetPackageName + ")"; } private static final long serialVersionUID = 0; }
0true
src_main_java_org_elasticsearch_common_inject_matcher_Matchers.java
1,016
public class NullOrderImpl implements Order { private static final long serialVersionUID = 1L; @Override public Long getId() { return null; } @Override public void setId(Long id) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public String getName() { return null; } @Override public void setName(String name) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Auditable getAuditable() { return null; } @Override public void setAuditable(Auditable auditable) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Money getSubTotal() { return Money.ZERO; } @Override public void setSubTotal(Money subTotal) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public void assignOrderItemsFinalPrice() { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Money getTotal() { return null; } @Override public Money getRemainingTotal() { return null; } @Override public Money getCapturedTotal() { return null; } @Override public void setTotal(Money orderTotal) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Customer getCustomer() { return null; } @Override public void setCustomer(Customer customer) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public OrderStatus getStatus() { return null; } @Override public void setStatus(OrderStatus status) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public List<OrderItem> getOrderItems() { return null; } @Override public void setOrderItems(List<OrderItem> orderItems) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public void addOrderItem(OrderItem orderItem) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public List<FulfillmentGroup> getFulfillmentGroups() { return null; } @Override public void setFulfillmentGroups(List<FulfillmentGroup> fulfillmentGroups) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public void setCandidateOrderOffers(List<CandidateOrderOffer> candidateOrderOffers) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public List<CandidateOrderOffer> getCandidateOrderOffers() { return null; } @Override public Date getSubmitDate() { return null; } @Override public void setSubmitDate(Date submitDate) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Money getTotalTax() { return null; } @Override public void setTotalTax(Money totalTax) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Money getTotalShipping() { return null; } @Override public void setTotalShipping(Money totalShipping) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public List<PaymentInfo> getPaymentInfos() { return null; } @Override public void setPaymentInfos(List<PaymentInfo> paymentInfos) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public boolean hasCategoryItem(String categoryName) { return false; } @Override public List<OrderAdjustment> getOrderAdjustments() { return null; } @Override public List<DiscreteOrderItem> getDiscreteOrderItems() { return null; } @Override public boolean containsSku(Sku sku) { return false; } @Override public List<OfferCode> getAddedOfferCodes() { return null; } @Override public String getFulfillmentStatus() { return null; } @Override public String getOrderNumber() { return null; } @Override public void setOrderNumber(String orderNumber) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public String getEmailAddress() { return null; } @Override public void setEmailAddress(String emailAddress) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Map<Offer, OfferInfo> getAdditionalOfferInformation() { return null; } @Override public void setAdditionalOfferInformation(Map<Offer, OfferInfo> additionalOfferInformation) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Money getItemAdjustmentsValue() { return null; } @Override public Money getOrderAdjustmentsValue() { return Money.ZERO; } @Override public Money getTotalAdjustmentsValue() { return null; } @Override public boolean updatePrices() { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Money getFulfillmentGroupAdjustmentsValue() { return null; } @Override public void addOfferCode(OfferCode addedOfferCode) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public void addAddedOfferCode(OfferCode offerCode) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Map<String, OrderAttribute> getOrderAttributes() { return null; } @Override public void setOrderAttributes(Map<String, OrderAttribute> orderAttributes) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public int getItemCount() { return 0; } @Override public BroadleafCurrency getCurrency() { return null; } @Override public void setCurrency(BroadleafCurrency currency) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Locale getLocale() { return null; } @Override public void setLocale(Locale locale) { } @Override public Money calculateSubTotal() { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public Money getTotalFulfillmentCharges() { return null; } @Override public void setTotalFulfillmentCharges(Money totalFulfillmentCharges) { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public boolean finalizeItemPrices() { throw new UnsupportedOperationException("NullOrder does not support any modification operations."); } @Override public boolean getHasOrderAdjustments() { return false; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_NullOrderImpl.java