answer stringlengths 17 10.2M |
|---|
package fr.openwide.core.wicket.more.lesscss.service;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FilenameUtils;
import org.apache.wicket.util.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.github.sommeri.less4j.Less4jException;
import com.github.sommeri.less4j.LessCompiler.CompilationResult;
import com.github.sommeri.less4j.LessCompiler.Configuration;
import com.github.sommeri.less4j.LessCompiler.Problem;
import com.github.sommeri.less4j.core.ThreadUnsafeLessCompiler;
import com.google.common.collect.Maps;
import fr.openwide.core.jpa.exception.ServiceException;
import fr.openwide.core.spring.config.CoreConfigurer;
import fr.openwide.core.spring.util.StringUtils;
import fr.openwide.core.wicket.more.config.spring.WicketMoreServiceConfig;
import fr.openwide.core.wicket.more.lesscss.model.CssStylesheetInformation;
/**
* @see WicketMoreServiceConfig
*/
@Service("lessCssService")
public class LessCssServiceImpl implements ILessCssService {
private static final Logger LOGGER = LoggerFactory.getLogger(LessCssServiceImpl.class);
private static final Pattern LESSCSS_IMPORT_PATTERN =
Pattern.compile("^\\p{Blank}*@import\\p{Blank}+\"([^\"]+)\"\\p{Blank}*;", Pattern.MULTILINE);
private static final Pattern LESSCSS_IMPORT_SCOPE_PATTERN =
Pattern.compile("^@\\{scope-([a-zA-Z0-9_-]*)\\}(.*)$");
private static final Pattern SCOPE_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_-]*$");
private static final Map<String, Class<?>> SCOPES = Maps.newHashMapWithExpectedSize(3);
@Autowired
private CoreConfigurer configurer;
@Override
// If checkCacheInvalidation is true and, before invocation, a cached value exists and is not up to date, we evict the cache entry.
@CacheEvict(value = "lessCssService.compiledStylesheets",
key = "T(fr.openwide.core.wicket.more.lesscss.service.LessCssServiceImpl).getCacheKey(#lessInformation)",
beforeInvocation = true,
condition= "#checkCacheEntryUpToDate && !(caches.?[name=='lessCssService.compiledStylesheets'][0]?.get(T(fr.openwide.core.wicket.more.lesscss.service.LessCssServiceImpl).getCacheKey(#lessInformation))?.get()?.isUpToDate() ?: false)"
)
// THEN, we check if a cached value exists. If it does, it is returned ; if not, the method is called.
@Cacheable(value = "lessCssService.compiledStylesheets",
key = "T(fr.openwide.core.wicket.more.lesscss.service.LessCssServiceImpl).getCacheKey(#lessInformation)")
public CssStylesheetInformation getCompiledStylesheet(CssStylesheetInformation lessInformation, boolean checkCacheEntryUpToDate)
throws ServiceException {
prepareRawStylesheet(lessInformation);
try {
Configuration configuration = new Configuration();
if (configurer.isConfigurationTypeDevelopment()) {
configuration.getSourceMapConfiguration().setInline(true);
} else {
configuration.getSourceMapConfiguration().setLinkSourceMap(false);
}
CompilationResult compilationResult = new ThreadUnsafeLessCompiler().compile(lessInformation.getSource(), configuration);
CssStylesheetInformation compiledStylesheet = new CssStylesheetInformation(
lessInformation, compilationResult.getCss()
);
List<Problem> warnings = compilationResult.getWarnings();
if (!CollectionUtils.isEmpty(warnings)) {
for (Problem warning : warnings) {
LOGGER.warn(formatLess4jProblem(warning));
}
}
return compiledStylesheet;
} catch (Less4jException e) {
List<Problem> errors = e.getErrors();
if (!CollectionUtils.isEmpty(errors)) {
for (Problem error : errors) {
LOGGER.error(formatLess4jProblem(error));
}
}
throw new ServiceException(String.format("Error compiling %1$s (scope: %2$s)",
lessInformation.getName(), lessInformation.getScope()), e);
}
}
private void prepareRawStylesheet(CssStylesheetInformation lessSource) throws ServiceException {
Matcher matcher = LESSCSS_IMPORT_PATTERN.matcher(lessSource.getSource());
ClassPathResource importedResource;
while (matcher.find()) {
Class<?> scope;
String importedResourceFilename;
String importUrl = matcher.group(1);
Matcher scopeMatcher = LESSCSS_IMPORT_SCOPE_PATTERN.matcher(importUrl);
if (scopeMatcher.matches()) {
Class<?> referencedScope = SCOPES.get(scopeMatcher.group(1));
if (referencedScope != null) {
scope = referencedScope;
} else {
throw new IllegalStateException(String.format("Scope %1$s is not supported", scopeMatcher.group(1)));
}
importedResourceFilename = scopeMatcher.group(2);
} else {
// Defaults to importing file's scope
scope = lessSource.getScope();
importedResourceFilename = getRelativeToScopePath(lessSource.getName(), matcher.group(1));
}
InputStream inputStream = null;
try {
importedResource = new ClassPathResource(importedResourceFilename, scope);
inputStream = importedResource.getURL().openStream();
CssStylesheetInformation importedStylesheet = new CssStylesheetInformation(scope, importedResourceFilename, IOUtils.toString(inputStream), importedResource.lastModified());
prepareRawStylesheet(importedStylesheet);
lessSource.addImportedStylesheet(importedStylesheet);
lessSource.setSource(StringUtils.replace(lessSource.getSource(), matcher.group(), importedStylesheet.getSource()));
} catch (Exception e) {
throw new ServiceException(String.format("Error reading lesscss source for %1$s in %2$s (scope: %3$s)",
importedResourceFilename, lessSource.getName(), scope), e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
LOGGER.error(String.format("Error closing the resource stream for: %1$s", importedResourceFilename));
}
}
}
}
}
private String getRelativeToScopePath(String sourceFile, String importFilename) {
String contextPath = FilenameUtils.getFullPath(sourceFile);
String relativeToScopeFilename;
if (StringUtils.hasLength(contextPath)) {
relativeToScopeFilename = FilenameUtils.concat(contextPath, importFilename);
} else {
relativeToScopeFilename = importFilename;
}
return relativeToScopeFilename;
}
@Override
public void registerImportScope(String scopeName, Class<?> scope) {
if (SCOPES.containsKey(scopeName)) {
LOGGER.warn(String.format("Scope %1$s already registered: ignored", scopeName));
return;
}
Matcher matcher = SCOPE_NAME_PATTERN.matcher(scopeName);
if (!matcher.matches()) {
LOGGER.error(String.format("Scope name %1$s invalid (%2$s): ignored", scopeName, SCOPE_NAME_PATTERN.toString()));
return;
}
SCOPES.put(scopeName, scope);
}
public static String getCacheKey(CssStylesheetInformation resourceInformation) {
StringBuilder cacheKeyBuilder = new StringBuilder();
cacheKeyBuilder.append(resourceInformation.getScope().getName());
cacheKeyBuilder.append("-");
cacheKeyBuilder.append(resourceInformation.getName());
return cacheKeyBuilder.toString();
}
public static String formatLess4jProblem(Problem problem) {
StringBuilder sb = new StringBuilder();
sb.append(problem.getMessage());
sb.append(" at line ").append(problem.getLine());
sb.append(" at character ").append(problem.getCharacter());
return sb.toString();
}
} |
package polyglot.visit;
import java.util.HashMap;
import java.util.Map;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.frontend.Job;
import polyglot.types.*;
import polyglot.util.*;
/** Visitor which checks if exceptions are caught or declared properly. */
public class ExceptionChecker extends ErrorHandlingVisitor
{
protected ExceptionChecker outer;
private SubtypeSet scope = null; // lazily instantiated
protected Map exceptionPositions;
public ExceptionChecker(Job job, TypeSystem ts, NodeFactory nf) {
super(job, ts, nf);
this.outer = null;
this.exceptionPositions = new HashMap();
}
public ExceptionChecker push() {
ExceptionChecker ec = (ExceptionChecker) this.visitChildren();
ec.outer = this;
ec.exceptionPositions = new HashMap();
return ec;
}
public ExceptionChecker pop() {
return outer;
}
/**
* This method is called when we are to perform a "normal" traversal of
* a subtree rooted at <code>n</code>. At every node, we will push a
* stack frame. Each child node will add the exceptions that it throws
* to this stack frame. For most nodes ( excdeption for the try / catch)
* will just aggregate the stack frames.
*
* @param n The root of the subtree to be traversed.
* @return The <code>NodeVisitor</code> which should be used to visit the
* children of <code>n</code>.
*
*/
protected NodeVisitor enterCall(Node n) throws SemanticException {
return n.exceptionCheckEnter(push());
}
protected NodeVisitor enterError(Node n) {
return push();
}
/**
* Here, we pop the stack frame that we pushed in enter and agregate the
* exceptions.
*
* @param old The original state of root of the current subtree.
* @param n The current state of the root of the current subtree.
* @param v The <code>NodeVisitor</code> object used to visit the children.
* @return The final result of the traversal of the tree rooted at
* <code>n</code>.
*/
protected Node leaveCall(Node old, Node n, NodeVisitor v)
throws SemanticException {
ExceptionChecker inner = (ExceptionChecker) v;
if (inner.outer != this) throw new InternalCompilerError("oops!");
// gather exceptions from this node.
n = n.del().exceptionCheck(inner);
// Merge results from the children and free the checker used for the
// children.
SubtypeSet t = inner.throwsSet();
throwsSet().addAll(t);
exceptionPositions.putAll(inner.exceptionPositions);
return n;
}
/**
* The ast nodes will use this callback to notify us that they throw an
* exception of type t. This should only be called by MethodExpr node,
* and throw node, since they are the only node which can generate
* exceptions.
*
* @param t The type of exception that the node throws.
*/
public void throwsException(Type t, Position pos) {
throwsSet().add(t) ;
exceptionPositions.put(t, pos);
}
/**
* Method to allow the throws clause and method body to inspect and
* modify the throwsSet.
*/
public SubtypeSet throwsSet() {
if (scope == null) {
scope = new SubtypeSet(ts.Throwable());
}
return scope;
}
/**
* Method to determine the position at which a particular exception is
* thrown
*/
public Position exceptionPosition(Type t) {
return (Position)exceptionPositions.get(t);
}
} |
package com.jcwhatever.nucleus.npc.traits;
import com.jcwhatever.nucleus.providers.npc.INpc;
import com.jcwhatever.nucleus.providers.npc.traits.NpcTrait;
import com.jcwhatever.nucleus.providers.npc.traits.NpcTraitType;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.Vector;
/**
* Causes the NPC's Y coordinate position to be frozen.
*
* <p>Trait is registered with the lookup name "NpcTraitPack:FreezeHeight"</p>
*/
public class FreezeHeightTrait extends NpcTraitType {
@Override
public Plugin getPlugin() {
return NpcTraitPack.getPlugin();
}
@Override
public String getName() {
return "FreezeHeight";
}
@Override
protected NpcTrait createTrait(INpc npc) {
return new FreezeHeight(npc, this);
}
public static class FreezeHeight extends NpcTrait implements Runnable {
private boolean _isEnabled;
private double _y;
/**
* Constructor.
*
* @param npc The NPC the trait is for.
* @param type The parent type that instantiated the trait.
*/
FreezeHeight(INpc npc, NpcTraitType type) {
super(npc, type);
}
public boolean isEnabled() {
return _isEnabled;
}
public FreezeHeight setEnabled(boolean isEnabled) {
_isEnabled = isEnabled;
setY();
return this;
}
@Override
public void onAdd() {
setY();
}
@Override
public void onSpawn() {
setY();
}
@Override
public void run() {
if (!_isEnabled || !getNpc().isSpawned())
return;
Entity entity = getNpc().getEntity();
assert entity != null;
Vector vector = entity.getVelocity();
Location location = getNpc().getLocation();
assert location != null;
if (Double.compare(location.getY(), _y) < 0) {
vector.setY(0.20);
}
else {
vector.setY(0);
}
entity.setVelocity(vector);
}
private void setY() {
if (getNpc().isSpawned()) {
Location location = getNpc().getLocation();
assert location != null;
_y = location.getY();
}
}
}
} |
package com.thaiopensource.datatype.xsd;
import java.util.Hashtable;
import org.xml.sax.XMLReader;
import com.thaiopensource.datatype.DatatypeFactory;
import com.thaiopensource.datatype.Datatype;
import com.thaiopensource.datatype.DatatypeReader;
import com.thaiopensource.datatype.DatatypeContext;
import com.thaiopensource.datatype.DatatypeAssignment;
public class DatatypeFactoryImpl implements DatatypeFactory {
static private final String xsdns = "http:
private final Hashtable typeTable = new Hashtable();
private RegexEngine regexEngine;
static private final String LONG_MAX = "9223372036854775807";
static private final String LONG_MIN = "-9223372036854775808";
static private final String INT_MAX = "2147483647";
static private final String INT_MIN = "-2147483648";
static private final String SHORT_MAX = "32767";
static private final String SHORT_MIN = "-32768";
static private final String BYTE_MAX = "127";
static private final String BYTE_MIN = "-128";
static private final String UNSIGNED_LONG_MAX = "18446744073709551615";
static private final String UNSIGNED_INT_MAX = "4294967295";
static private final String UNSIGNED_SHORT_MAX = "65535";
static private final String UNSIGNED_BYTE_MAX = "255";
public DatatypeFactoryImpl() {
this(new NullRegexEngine());
}
public DatatypeFactoryImpl(RegexEngine regexEngine) {
this.regexEngine = regexEngine;
typeTable.put("string", new StringDatatype());
typeTable.put("normalizedString", new CdataDatatype());
typeTable.put("token", new TokenDatatype());
typeTable.put("boolean", new BooleanDatatype());
DatatypeBase decimalType = new DecimalDatatype();
typeTable.put("decimal", decimalType);
DatatypeBase integerType = new ScaleRestrictDatatype(decimalType, 0);
typeTable.put("integer", integerType);
typeTable.put("nonPositiveInteger", restrictMax(integerType, "0"));
typeTable.put("negativeInteger", restrictMax(integerType, "-1"));
typeTable.put("long", restrictMax(restrictMin(integerType, LONG_MIN), LONG_MAX));
typeTable.put("int", restrictMax(restrictMin(integerType, INT_MIN), INT_MAX));
typeTable.put("short", restrictMax(restrictMin(integerType, SHORT_MIN), SHORT_MAX));
typeTable.put("byte", restrictMax(restrictMin(integerType, BYTE_MIN), BYTE_MAX));
DatatypeBase nonNegativeIntegerType = restrictMin(integerType, "0");
typeTable.put("nonNegativeInteger", nonNegativeIntegerType);
typeTable.put("unsignedLong", restrictMax(nonNegativeIntegerType, UNSIGNED_LONG_MAX));
typeTable.put("unsignedInt", restrictMax(nonNegativeIntegerType, UNSIGNED_INT_MAX));
typeTable.put("unsignedShort", restrictMax(nonNegativeIntegerType, UNSIGNED_SHORT_MAX));
typeTable.put("unsignedByte", restrictMax(nonNegativeIntegerType, UNSIGNED_BYTE_MAX));
typeTable.put("positiveInteger", restrictMin(integerType, "1"));
typeTable.put("double", new DoubleDatatype());
typeTable.put("float", new FloatDatatype());
typeTable.put("Name", new NameDatatype());
typeTable.put("QName", new QNameDatatype());
DatatypeBase ncNameType = new NCNameDatatype();
typeTable.put("NCName", ncNameType);
DatatypeBase nmtokenDatatype = new NmtokenDatatype();
typeTable.put("NMTOKEN", nmtokenDatatype);
typeTable.put("NMTOKENS", list(nmtokenDatatype));
typeTable.put("ID", new IdDatatype());
DatatypeBase idrefType = new IdrefDatatype();
typeTable.put("IDREF", idrefType);
typeTable.put("IDREFS", list(idrefType));
// Partially implemented
DatatypeBase entityType = ncNameType;
typeTable.put("ENTITY", entityType);
typeTable.put("ENTITIES", list(entityType));
typeTable.put("NOTATION", new NameDatatype());
typeTable.put("language", new LanguageDatatype());
// Not implemented yet
typeTable.put("anyURI", new StringDatatype());
typeTable.put("base64Binary", new StringDatatype());
typeTable.put("hexBinary", new StringDatatype());
typeTable.put("duration", new StringDatatype());
typeTable.put("dateTime", new StringDatatype());
typeTable.put("time", new StringDatatype());
typeTable.put("date", new StringDatatype());
typeTable.put("gYearMonth", new StringDatatype());
typeTable.put("gYear", new StringDatatype());
typeTable.put("gMonthDay", new StringDatatype());
typeTable.put("gDay", new StringDatatype());
typeTable.put("gMonth", new StringDatatype());
}
public Datatype createDatatype(String namespaceURI, String localName) {
if (xsdns.equals(namespaceURI))
return createXsdDatatype(localName);
return null;
}
public DatatypeReader createDatatypeReader(String namespaceURI, DatatypeContext context) {
if (xsdns.equals(namespaceURI))
return new DatatypeReaderImpl(this, context);
return null;
}
public DatatypeAssignment createDatatypeAssignment(XMLReader xr) {
return new DatatypeAssignmentImpl(xr);
}
DatatypeBase createXsdDatatype(String localName) {
return (DatatypeBase)typeTable.get(localName);
}
RegexEngine getRegexEngine() {
return regexEngine;
}
private DatatypeBase restrictMax(DatatypeBase base, String limit) {
return new MaxInclusiveRestrictDatatype(base, base.getValue(limit, null));
}
private DatatypeBase restrictMin(DatatypeBase base, String limit) {
return new MinInclusiveRestrictDatatype(base, base.getValue(limit, null));
}
private DatatypeBase list(DatatypeBase base) {
return new MinLengthRestrictDatatype(new ListDatatype(base), 1);
}
} |
package com.thinkbiganalytics.feedmgr.service.feed;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.thinkbiganalytics.datalake.authorization.service.HadoopAuthorizationService;
import com.thinkbiganalytics.feedmgr.rest.model.FeedMetadata;
import com.thinkbiganalytics.feedmgr.rest.model.FeedSummary;
import com.thinkbiganalytics.feedmgr.rest.model.NifiFeed;
import com.thinkbiganalytics.feedmgr.rest.model.RegisteredTemplate;
import com.thinkbiganalytics.feedmgr.rest.model.UIFeed;
import com.thinkbiganalytics.feedmgr.rest.model.UserField;
import com.thinkbiganalytics.feedmgr.rest.model.UserProperty;
import com.thinkbiganalytics.feedmgr.security.FeedsAccessControl;
import com.thinkbiganalytics.feedmgr.service.UserPropertyTransform;
import com.thinkbiganalytics.feedmgr.service.feed.datasource.DerivedDatasourceFactory;
import com.thinkbiganalytics.feedmgr.service.template.FeedManagerTemplateService;
import com.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementService;
import com.thinkbiganalytics.json.ObjectMapperSerializer;
import com.thinkbiganalytics.metadata.api.MetadataAccess;
import com.thinkbiganalytics.metadata.api.datasource.Datasource;
import com.thinkbiganalytics.metadata.api.datasource.DatasourceProvider;
import com.thinkbiganalytics.metadata.api.event.MetadataEventListener;
import com.thinkbiganalytics.metadata.api.event.MetadataEventService;
import com.thinkbiganalytics.metadata.api.event.feed.FeedPropertyChangeEvent;
import com.thinkbiganalytics.metadata.api.extension.UserFieldDescriptor;
import com.thinkbiganalytics.metadata.api.feed.Feed;
import com.thinkbiganalytics.metadata.api.feed.FeedProperties;
import com.thinkbiganalytics.metadata.api.feed.FeedProvider;
import com.thinkbiganalytics.metadata.api.feed.FeedSource;
import com.thinkbiganalytics.metadata.api.feed.OpsManagerFeedProvider;
import com.thinkbiganalytics.metadata.api.feedmgr.category.FeedManagerCategory;
import com.thinkbiganalytics.metadata.api.feedmgr.category.FeedManagerCategoryProvider;
import com.thinkbiganalytics.metadata.api.feedmgr.feed.FeedManagerFeed;
import com.thinkbiganalytics.metadata.api.feedmgr.feed.FeedManagerFeedProvider;
import com.thinkbiganalytics.metadata.api.feedmgr.template.FeedManagerTemplate;
import com.thinkbiganalytics.metadata.api.feedmgr.template.FeedManagerTemplateProvider;
import com.thinkbiganalytics.metadata.api.security.HadoopSecurityGroup;
import com.thinkbiganalytics.metadata.rest.model.sla.Obligation;
import com.thinkbiganalytics.metadata.sla.api.ObligationGroup;
import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementBuilder;
import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementProvider;
import com.thinkbiganalytics.nifi.rest.model.NiFiPropertyDescriptorTransform;
import com.thinkbiganalytics.policy.precondition.DependentFeedPrecondition;
import com.thinkbiganalytics.policy.precondition.Precondition;
import com.thinkbiganalytics.policy.precondition.transform.PreconditionPolicyTransformer;
import com.thinkbiganalytics.policy.rest.model.FieldRuleProperty;
import com.thinkbiganalytics.policy.rest.model.PreconditionRule;
import com.thinkbiganalytics.rest.model.LabelValue;
import com.thinkbiganalytics.security.AccessController;
import com.thinkbiganalytics.support.FeedNameUtil;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
public class DefaultFeedManagerFeedService extends AbstractFeedManagerFeedService implements FeedManagerFeedService {
@Inject
private FeedProvider feedProvider;
@Inject
private DatasourceProvider datasourceProvider;
@Inject
private FeedManagerFeedProvider feedManagerFeedProvider;
@Inject
FeedManagerCategoryProvider categoryProvider;
@Inject
FeedManagerTemplateProvider templateProvider;
@Inject
FeedManagerTemplateService templateRestProvider;
@Inject
FeedManagerPreconditionService feedPreconditionModelTransform;
@Inject
FeedModelTransform feedModelTransform;
@Inject
ServiceLevelAgreementProvider slaProvider;
@Inject
ServiceLevelAgreementService serviceLevelAgreementService;
@Inject
OpsManagerFeedProvider opsManagerFeedProvider;
@Inject
MetadataAccess metadataAccess;
/** Metadata event service */
@Inject
private MetadataEventService eventService;
@Inject
private AccessController accessController;
@Inject
private MetadataEventService metadataEventService;
@Inject
private NiFiPropertyDescriptorTransform propertyDescriptorTransform;
@Inject
private DerivedDatasourceFactory derivedDatasourceFactory;
@Override
public List<FeedMetadata> getReusableFeeds() {
return null;
}
// I had to use autowired instead of Inject to allow null values.
@Autowired(required = false)
@Qualifier("hadoopAuthorizationService")
private HadoopAuthorizationService hadoopAuthorizationService;
/**
* Event listener for precondition events
*/
private final MetadataEventListener<FeedPropertyChangeEvent> feedPropertyChangeListener = new FeedPropertyChangeDispatcher();
/**
* Adds listeners for transferring events.
*/
@PostConstruct
public void addEventListener() {
metadataEventService.addListener(feedPropertyChangeListener);
}
/**
* Removes listeners and stops transferring events.
*/
@PreDestroy
public void removeEventListener() {
metadataEventService.removeListener(feedPropertyChangeListener);
}
@Override
public FeedMetadata getFeedByName(final String categoryName, final String feedName) {
FeedMetadata feedMetadata = metadataAccess.read(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ACCESS_FEEDS);
FeedManagerFeed domainFeed = feedManagerFeedProvider.findBySystemName(categoryName, feedName);
if (domainFeed != null) {
return feedModelTransform.domainToFeedMetadata(domainFeed);
}
return null;
});
return feedMetadata;
}
@Override
public FeedMetadata getFeedById(final String id) {
return metadataAccess.read(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ACCESS_FEEDS);
return getFeedById(id, false);
});
}
@Override
public FeedMetadata getFeedById(final String id, final boolean refreshTargetTableSchema) {
return metadataAccess.read(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ACCESS_FEEDS);
FeedMetadata feedMetadata = null;
FeedManagerFeed.ID domainId = feedManagerFeedProvider.resolveId(id);
FeedManagerFeed domainFeed = feedManagerFeedProvider.findById(domainId);
if (domainFeed != null) {
feedMetadata = feedModelTransform.domainToFeedMetadata(domainFeed);
}
if (refreshTargetTableSchema && feedMetadata != null) {
//commented out for now as some issues were found with feeds with TEXTFILE as their output
// feedModelTransform.refreshTableSchemaFromHive(feedMetadata);
}
return feedMetadata;
});
}
@Override
public Collection<FeedMetadata> getFeeds() {
return metadataAccess.read(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ACCESS_FEEDS);
Collection<FeedMetadata> feeds = null;
List<FeedManagerFeed> domainFeeds = feedManagerFeedProvider.findAll();
if (domainFeeds != null) {
feeds = feedModelTransform.domainToFeedMetadata(domainFeeds);
}
return feeds;
});
}
@Override
public Collection<? extends UIFeed> getFeeds(boolean verbose) {
if (verbose) {
return getFeeds();
} else {
return getFeedSummaryData();
}
}
@Override
public List<FeedSummary> getFeedSummaryData() {
return metadataAccess.read(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ACCESS_FEEDS);
List<FeedSummary> feeds = null;
Collection<? extends Feed> domainFeeds = feedManagerFeedProvider.findAll();
if (domainFeeds != null) {
feeds = feedModelTransform.domainToFeedSummary(domainFeeds);
}
return feeds;
});
}
@Override
public List<FeedSummary> getFeedSummaryForCategory(final String categoryId) {
return metadataAccess.read(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ACCESS_FEEDS);
List<FeedSummary> summaryList = new ArrayList<>();
FeedManagerCategory.ID categoryDomainId = categoryProvider.resolveId(categoryId);
List<? extends FeedManagerFeed> domainFeeds = feedManagerFeedProvider.findByCategoryId(categoryDomainId);
if (domainFeeds != null && !domainFeeds.isEmpty()) {
List<FeedMetadata> feeds = feedModelTransform.domainToFeedMetadata(domainFeeds);
for (FeedMetadata feed : feeds) {
summaryList.add(new FeedSummary(feed));
}
}
return summaryList;
});
}
@Override
public List<FeedMetadata> getFeedsWithTemplate(final String registeredTemplateId) {
return metadataAccess.read(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ACCESS_FEEDS);
List<FeedMetadata> feedMetadatas = null;
FeedManagerTemplate.ID templateDomainId = templateProvider.resolveId(registeredTemplateId);
List<? extends FeedManagerFeed> domainFeeds = feedManagerFeedProvider.findByTemplateId(templateDomainId);
if (domainFeeds != null) {
feedMetadatas = feedModelTransform.domainToFeedMetadata(domainFeeds);
}
return feedMetadatas;
});
}
@Override
protected RegisteredTemplate getRegisteredTemplateWithAllProperties(final String templateId) {
return metadataAccess.read(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ACCESS_FEEDS);
return templateRestProvider.getRegisteredTemplate(templateId);
});
}
@Override
public Feed.ID resolveFeed(@Nonnull Serializable fid) {
return metadataAccess.read(() -> feedProvider.resolveFeed(fid));
}
// @Transactional(transactionManager = "metadataTransactionManager")
public NifiFeed createFeed(final FeedMetadata feedMetadata) {
if (feedMetadata.getState() == null) {
if (feedMetadata.isActive()) {
feedMetadata.setState(Feed.State.ENABLED.name());
} else {
feedMetadata.setState(Feed.State.DISABLED.name());
}
}
return super.createFeed(feedMetadata);
}
@Override
//@Transactional(transactionManager = "metadataTransactionManager")
public void saveFeed(final FeedMetadata feed) {
if (StringUtils.isBlank(feed.getId())) {
feed.setIsNew(true);
}
metadataAccess.commit(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.EDIT_FEEDS);
List<HadoopSecurityGroup> previousSavedSecurityGroups = null;
// Store the old security groups before saving beccause we need to compare afterward
if (feed.isNew()) {
FeedManagerFeed existing = feedManagerFeedProvider.findBySystemName(feed.getCategory().getSystemName(), feed.getSystemFeedName());
// Since we know this is expected to be new check if the category/feed name combo is already being used.
if (existing != null) {
throw new DuplicateFeedNameException(feed.getCategoryName(), feed.getFeedName());
}
} else {
FeedManagerFeed previousStateBeforeSaving = feedManagerFeedProvider.findById(feedManagerFeedProvider.resolveId(feed.getId()));
Map<String, String> userProperties = previousStateBeforeSaving.getUserProperties();
previousSavedSecurityGroups = previousStateBeforeSaving.getSecurityGroups();
}
//if this is the first time saving this feed create a new one
FeedManagerFeed domainFeed = feedModelTransform.feedToDomain(feed);
if (domainFeed.getState() == null) {
domainFeed.setState(Feed.State.ENABLED);
}
//initially save the feed
if (feed.isNew()) {
domainFeed = feedManagerFeedProvider.update(domainFeed);
}
final String domainId = domainFeed.getId().toString();
final String feedName = FeedNameUtil.fullName(domainFeed.getCategory().getName(), domainFeed.getName());
// Build preconditions
assignFeedDependencies(feed, domainFeed);
//Assign the datasources
assignFeedDatasources(feed, domainFeed);
//sync the feed information to ops manager
metadataAccess.commit(() -> opsManagerFeedProvider.save(opsManagerFeedProvider.resolveId(domainId), feedName));
// Update hadoop security group polices if the groups changed
if (!feed.isNew() && !ListUtils.isEqualList(previousSavedSecurityGroups, domainFeed.getSecurityGroups())) {
List<HadoopSecurityGroup> securityGroups = domainFeed.getSecurityGroups();
List<String> groupsAsCommaList = securityGroups.stream().map(group -> group.getName()).collect(Collectors.toList());
hadoopAuthorizationService.updateSecurityGroupsForAllPolicies(feed.getSystemCategoryName(), feed.getSystemFeedName(), groupsAsCommaList, domainFeed.getProperties());
}
domainFeed = feedManagerFeedProvider.update(domainFeed);
// Return result
return feed;
}, (e) -> {
if (feed.isNew() && StringUtils.isNotBlank(feed.getId())) {
//Rollback ops Manager insert if it is newly created
metadataAccess.commit(() -> {
opsManagerFeedProvider.delete(opsManagerFeedProvider.resolveId(feed.getId()));
return null;
});
}
});
}
/**
* Looks for the Feed Preconditions and assigns the Feed Dependencies
*/
private void assignFeedDependencies(FeedMetadata feed, FeedManagerFeed domainFeed) {
final Feed.ID domainFeedId = domainFeed.getId();
List<PreconditionRule> preconditions = feed.getSchedule().getPreconditions();
if (preconditions != null) {
PreconditionPolicyTransformer transformer = new PreconditionPolicyTransformer(preconditions);
transformer.applyFeedNameToCurrentFeedProperties(feed.getCategory().getSystemName(), feed.getSystemFeedName());
List<com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup> transformedPreconditions = transformer.getPreconditionObligationGroups();
ServiceLevelAgreementBuilder
preconditionBuilder =
feedProvider.buildPrecondition(domainFeed.getId()).name("Precondition for feed " + feed.getCategoryAndFeedName() + " (" + domainFeed.getId() + ")");
for (com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup precondition : transformedPreconditions) {
for (Obligation group : precondition.getObligations()) {
preconditionBuilder.obligationGroupBuilder(ObligationGroup.Condition.valueOf(precondition.getCondition())).obligationBuilder().metric(group.getMetrics()).build();
}
}
preconditionBuilder.build();
//add in the lineage dependency relationships
//will the feed exist in the jcr store here if it is new??
//store the existing list of dependent feeds to track and delete those that dont match
Set<Feed.ID> oldDependentFeedIds = new HashSet<Feed.ID>();
Set<Feed.ID> newDependentFeedIds = new HashSet<Feed.ID>();
List<Feed> dependentFeeds = domainFeed.getDependentFeeds();
if (dependentFeeds != null && !dependentFeeds.isEmpty()) {
dependentFeeds.stream().forEach(dependentFeed -> {
oldDependentFeedIds.add(dependentFeed.getId());
});
}
//find those preconditions that are marked as dependent feed types
List<Precondition> preconditionPolicies = transformer.getPreconditionPolicies();
preconditionPolicies.stream().filter(precondition -> precondition instanceof DependentFeedPrecondition).forEach(dependentFeedPrecondition -> {
DependentFeedPrecondition feedPrecondition = (DependentFeedPrecondition) dependentFeedPrecondition;
List<String> dependentFeedNames = feedPrecondition.getDependentFeedNames();
if (dependentFeedNames != null && !dependentFeedNames.isEmpty()) {
//find the feed
for (String dependentFeedName : dependentFeedNames) {
Feed dependentFeed = feedProvider.findBySystemName(dependentFeedName);
if (dependentFeed != null) {
Feed.ID newDependentFeedId = dependentFeed.getId();
newDependentFeedIds.add(newDependentFeedId);
//add and persist it if it doesnt already exist
if (!oldDependentFeedIds.contains(newDependentFeedId)) {
feedProvider.addDependent(domainFeedId, dependentFeed.getId());
}
}
}
}
});
//delete any of those dependent feed ids from the oldDependentFeeds that are not part of the newDependentFeedIds
oldDependentFeedIds.stream().filter(oldFeedId -> !newDependentFeedIds.contains(oldFeedId))
.forEach(dependentFeedToDelete -> feedProvider.removeDependent(domainFeedId, dependentFeedToDelete));
}
}
private void assignFeedDatasources(FeedMetadata feed, FeedManagerFeed domainFeed) {
final Feed.ID domainFeedId = domainFeed.getId();
Set<com.thinkbiganalytics.metadata.api.datasource.Datasource.ID> sources = new HashSet<com.thinkbiganalytics.metadata.api.datasource.Datasource.ID>();
Set<com.thinkbiganalytics.metadata.api.datasource.Datasource.ID> destinations = new HashSet<com.thinkbiganalytics.metadata.api.datasource.Datasource.ID>();
String uniqueName = FeedNameUtil.fullName(feed.getCategory().getSystemName(), feed.getSystemFeedName());
RegisteredTemplate template = feed.getRegisteredTemplate();
if (template == null) {
//fetch it for checks
template = templateRestProvider.getRegisteredTemplate(feed.getTemplateId());
}
//find Definition registration
derivedDatasourceFactory.populateDatasources(feed, template, sources, destinations);
//remove the older sources only if they have changed
if (domainFeed.getSources() != null) {
Set<Datasource.ID>
existingSourceIds =
((List<FeedSource>) domainFeed.getSources()).stream().filter(source -> source.getDatasource() != null).map(source1 -> source1.getDatasource().getId()).collect(Collectors.toSet());
if (!sources.containsAll(existingSourceIds) || (sources.size() != existingSourceIds.size())) {
//remove older sources
//cant do it here for some reason.. need to do it in a separate transaction
feedProvider.removeFeedSources(domainFeedId);
}
}
sources.stream().forEach(sourceId -> feedProvider.ensureFeedSource(domainFeedId, sourceId));
destinations.stream().forEach(sourceId -> feedProvider.ensureFeedDestination(domainFeedId, sourceId));
//TODO deal with inputs changing sources?
}
@Override
public void deleteFeed(@Nonnull final String feedId) {
metadataAccess.commit(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.EDIT_FEEDS);
Feed feed = feedProvider.getFeed(feedProvider.resolveFeed(feedId));
//unschedule any SLAs
serviceLevelAgreementService.unscheduleServiceLevelAgreement(feed.getId());
feedManagerFeedProvider.deleteById(feed.getId());
opsManagerFeedProvider.delete(opsManagerFeedProvider.resolveId(feedId));
return true;
});
}
@Override
public void enableFeedCleanup(@Nonnull String feedId) {
metadataAccess.commit(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ADMIN_FEEDS);
final Feed.ID id = feedProvider.resolveFeed(feedId);
return feedProvider.mergeFeedProperties(id, ImmutableMap.of(FeedProperties.CLEANUP_ENABLED, "true"));
});
}
// @Transactional(transactionManager = "metadataTransactionManager")
private boolean enableFeed(final Feed.ID feedId) {
return metadataAccess.commit(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ADMIN_FEEDS);
boolean enabled = feedProvider.enableFeed(feedId);
FeedManagerFeed domainFeed = feedManagerFeedProvider.findById(feedId);
if (domainFeed != null) {
FeedMetadata feedMetadata = feedModelTransform.deserializeFeedMetadata(domainFeed);
feedMetadata.setState(FeedMetadata.STATE.ENABLED.name());
domainFeed.setJson(ObjectMapperSerializer.serialize(feedMetadata));
feedManagerFeedProvider.update(domainFeed);
}
return enabled;
});
}
// @Transactional(transactionManager = "metadataTransactionManager")
private boolean disableFeed(final Feed.ID feedId) {
return metadataAccess.commit(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ADMIN_FEEDS);
boolean disabled = feedProvider.disableFeed(feedId);
FeedManagerFeed domainFeed = feedManagerFeedProvider.findById(feedId);
if (domainFeed != null) {
FeedMetadata feedMetadata = feedModelTransform.deserializeFeedMetadata(domainFeed);
feedMetadata.setState(FeedMetadata.STATE.DISABLED.name());
domainFeed.setJson(ObjectMapperSerializer.serialize(feedMetadata));
feedManagerFeedProvider.update(domainFeed);
}
return disabled;
});
}
public FeedSummary enableFeed(final String feedId) {
return metadataAccess.commit(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ADMIN_FEEDS);
if (StringUtils.isNotBlank(feedId)) {
FeedMetadata feedMetadata = getFeedById(feedId);
Feed.ID domainId = feedProvider.resolveFeed(feedId);
boolean enabled = enableFeed(domainId);
//re fetch it
if (enabled) {
feedMetadata.setState(Feed.State.ENABLED.name());
serviceLevelAgreementService.enableServiceLevelAgreementSchedule(domainId);
}
FeedSummary feedSummary = new FeedSummary(feedMetadata);
//start any Slas
return feedSummary;
}
return null;
});
}
public FeedSummary disableFeed(final String feedId) {
return metadataAccess.commit(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ADMIN_FEEDS);
if (StringUtils.isNotBlank(feedId)) {
FeedMetadata feedMetadata = getFeedById(feedId);
Feed.ID domainId = feedProvider.resolveFeed(feedId);
boolean disabled = disableFeed(domainId);
//re fetch it
if (disabled) {
feedMetadata.setState(Feed.State.DISABLED.name());
serviceLevelAgreementService.disableServiceLevelAgreementSchedule(domainId);
}
FeedSummary feedSummary = new FeedSummary(feedMetadata);
return feedSummary;
}
return null;
});
}
@Override
/**
* Applies new LableValue array to the FieldProperty.selectableValues {label = Category.Display Feed Name, value=category.system_feed_name}
*/
public void applyFeedSelectOptions(List<FieldRuleProperty> properties) {
if (properties != null && !properties.isEmpty()) {
List<FeedSummary> feedSummaries = getFeedSummaryData();
List<LabelValue> feedSelection = new ArrayList<>();
for (FeedSummary feedSummary : feedSummaries) {
boolean isDisabled = feedSummary.getState() == Feed.State.DISABLED.name();
feedSelection.add(new LabelValue(feedSummary.getCategoryAndFeedDisplayName() + (isDisabled ? " (DISABLED) ": ""), feedSummary.getCategoryAndFeedSystemName(), isDisabled ? "This feed is currently disabled" : ""));
}
for (FieldRuleProperty property : properties) {
property.setSelectableValues(feedSelection);
if (property.getValues() == null) {
property.setValues(new ArrayList<>()); // reset the intial values to be an empty arraylist
}
}
}
}
@Override
public void updateFeedsWithTemplate(String oldTemplateId, String newTemplateId) {
//not needed
}
@Nonnull
@Override
public Set<UserField> getUserFields() {
return metadataAccess.read(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ACCESS_FEEDS);
return UserPropertyTransform.toUserFields(feedProvider.getUserFields());
});
}
@Nonnull
@Override
public Optional<Set<UserProperty>> getUserFields(@Nonnull final String categoryId) {
return metadataAccess.read(() -> {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ACCESS_FEEDS);
final Optional<Set<UserFieldDescriptor>> categoryUserFields = categoryProvider.getFeedUserFields(categoryProvider.resolveId(categoryId));
final Set<UserFieldDescriptor> globalUserFields = feedProvider.getUserFields();
if (categoryUserFields.isPresent()) {
return Optional.of(UserPropertyTransform.toUserProperties(Collections.emptyMap(), Sets.union(globalUserFields, categoryUserFields.get())));
} else {
return Optional.empty();
}
});
}
@Override
public void setUserFields(@Nonnull final Set<UserField> userFields) {
this.accessController.checkPermission(AccessController.SERVICES, FeedsAccessControl.ADMIN_FEEDS);
feedProvider.setUserFields(UserPropertyTransform.toUserFieldDescriptors(userFields));
}
private class FeedPropertyChangeDispatcher implements MetadataEventListener<FeedPropertyChangeEvent> {
@Override
public void notify(@Nonnull final FeedPropertyChangeEvent metadataEvent) {
Properties oldProperties = metadataEvent.getData().getNifiPropertiesToDelete();
metadataAccess.commit(() -> {
Feed feed = feedProvider.getFeed(feedProvider.resolveFeed(metadataEvent.getData().getFeedId()));
oldProperties.forEach((k,v) -> {
feed.removeProperty((String)k);
});
}, MetadataAccess.SERVICE) ;
}
}
} |
package com.thaiopensource.relaxng.mns;
import com.thaiopensource.relaxng.Schema;
import com.thaiopensource.relaxng.ValidatorHandler;
import com.thaiopensource.util.Localizer;
import org.xml.sax.Attributes;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.Stack;
import java.util.Hashtable;
class ValidatorHandlerImpl extends DefaultHandler implements ValidatorHandler {
private SchemaImpl.Mode currentMode;
private int laxDepth = 0;
private ErrorHandler eh;
private Locator locator;
private Subtree subtrees = null;
private boolean validSoFar = true;
private boolean complete = false;
private final Hashset attributeNamespaces = new Hashset();
private PrefixMapping prefixMapping = null;
private final Localizer localizer = new Localizer(ValidatorHandlerImpl.class);
private final Hashtable validatorHandlerCache = new Hashtable();
static private class Subtree {
final Subtree parent;
final ValidatorHandler validator;
final Schema schema;
final String namespace;
final Hashset coveredNamespaces;
final boolean prune;
final SchemaImpl.Mode parentMode;
final int parentLaxDepth;
int depth = 0;
Subtree(String namespace, Hashset coveredNamespaces, boolean prune, ValidatorHandler validator,
Schema schema, SchemaImpl.Mode parentMode, int parentLaxDepth, Subtree parent) {
this.namespace = namespace;
this.coveredNamespaces = coveredNamespaces;
this.prune = prune;
this.validator = validator;
this.schema = schema;
this.parentMode = parentMode;
this.parentLaxDepth = parentLaxDepth;
this.parent = parent;
}
}
static private class PrefixMapping {
final String prefix;
final String uri;
final PrefixMapping parent;
PrefixMapping(String prefix, String uri, PrefixMapping parent) {
this.prefix = prefix;
this.uri = uri;
this.parent = parent;
}
}
ValidatorHandlerImpl(SchemaImpl.Mode mode, ErrorHandler eh) {
this.currentMode = mode;
this.eh = eh;
}
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
public void characters(char ch[], int start, int length)
throws SAXException {
for (Subtree st = subtrees; wantsEvent(st); st = st.parent)
st.validator.characters(ch, start, length);
}
public void ignorableWhitespace(char ch[], int start, int length)
throws SAXException {
for (Subtree st = subtrees; wantsEvent(st); st = st.parent)
st.validator.ignorableWhitespace(ch, start, length);
}
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if (namespaceCovered(uri))
subtrees.depth++;
else {
SchemaImpl.ElementAction elementAction = currentMode.getElementAction(uri);
if (elementAction == null) {
if (laxDepth == 0 && currentMode.isStrict())
error("element_undeclared_namespace", uri);
laxDepth++;
}
else {
subtrees = new Subtree(uri,
elementAction.getCoveredNamespaces(),
elementAction.getPrune(),
createValidatorHandler(elementAction.getSchema()),
elementAction.getSchema(),
currentMode,
laxDepth,
subtrees);
currentMode = elementAction.getMode();
laxDepth = 0;
startSubtree(subtrees.validator);
}
}
for (Subtree st = subtrees; wantsEvent(st); st = st.parent) {
Attributes prunedAtts;
if (st.prune)
prunedAtts = new NamespaceFilteredAttributes(uri, true, attributes);
else
prunedAtts = attributes;
st.validator.startElement(uri, localName, qName, prunedAtts);
}
for (int i = 0, len = attributes.getLength(); i < len; i++) {
String ns = attributes.getURI(i);
if (!ns.equals("")
&& !ns.equals(uri)
&& !namespaceCovered(ns)
&& !attributeNamespaces.contains(ns)) {
attributeNamespaces.add(ns);
validateAttributes(ns, attributes);
}
}
attributeNamespaces.clear();
}
private boolean namespaceCovered(String ns) {
return (laxDepth == 0 && subtrees != null
&& (ns.equals(subtrees.namespace) || subtrees.coveredNamespaces.contains(ns)));
}
private boolean wantsEvent(Subtree st) {
return st != null && (!st.prune || (laxDepth == 0 && st == subtrees));
}
private void validateAttributes(String ns, Attributes attributes) throws SAXException {
Schema attributesSchema = currentMode.getAttributesSchema(ns);
if (attributesSchema == null) {
if (currentMode.isStrict())
error("attributes_undeclared_namespace", ns);
return;
}
ValidatorHandler vh = createValidatorHandler(attributesSchema);
startSubtree(vh);
vh.startElement(SchemaImpl.BEARER_URI, SchemaImpl.BEARER_LOCAL_NAME, SchemaImpl.BEARER_LOCAL_NAME,
new NamespaceFilteredAttributes(ns, false, attributes));
vh.endElement(SchemaImpl.BEARER_URI, SchemaImpl.BEARER_LOCAL_NAME, SchemaImpl.BEARER_LOCAL_NAME);
endSubtree(vh);
releaseValidatorHandler(attributesSchema, vh);
}
private void startSubtree(ValidatorHandler vh) throws SAXException {
if (locator != null)
vh.setDocumentLocator(locator);
vh.startDocument();
for (PrefixMapping pm = prefixMapping; pm != null; pm = pm.parent)
vh.startPrefixMapping(pm.prefix, pm.uri);
}
private void endSubtree(ValidatorHandler vh) throws SAXException {
for (PrefixMapping pm = prefixMapping; pm != null; pm = pm.parent)
vh.endPrefixMapping(pm.prefix);
vh.endDocument();
if (!vh.isValidSoFar())
validSoFar = false;
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
for (Subtree st = subtrees; wantsEvent(st); st = st.parent)
st.validator.endElement(uri, localName, qName);
if (laxDepth > 0)
laxDepth
else if (subtrees.depth > 0)
subtrees.depth
else {
endSubtree(subtrees.validator);
releaseValidatorHandler(subtrees.schema, subtrees.validator);
currentMode = subtrees.parentMode;
laxDepth = subtrees.parentLaxDepth;
subtrees = subtrees.parent;
}
}
private ValidatorHandler createValidatorHandler(Schema schema) {
Stack stack = (Stack)validatorHandlerCache.get(schema);
if (stack == null) {
stack = new Stack();
validatorHandlerCache.put(schema, stack);
}
if (stack.empty())
return schema.createValidator(eh);
return (ValidatorHandler)stack.pop();
}
private void releaseValidatorHandler(Schema schema, ValidatorHandler vh) {
vh.reset();
((Stack)validatorHandlerCache.get(schema)).push(vh);
}
public void endDocument()
throws SAXException {
complete = true;
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
super.startPrefixMapping(prefix, uri);
prefixMapping = new PrefixMapping(prefix, uri, prefixMapping);
}
public void endPrefixMapping(String prefix)
throws SAXException {
super.endPrefixMapping(prefix);
prefixMapping = prefixMapping.parent;
}
public boolean isValidSoFar() {
for (Subtree st = subtrees; st != null; st = st.parent)
if (!st.validator.isValidSoFar())
return false;
return validSoFar;
}
public boolean isComplete() {
return complete;
}
public void reset() {
validSoFar = true;
complete = false;
subtrees = null;
locator = null;
}
public void setErrorHandler(ErrorHandler eh) {
this.eh = eh;
}
public ErrorHandler getErrorHandler() {
return eh;
}
private void error(String key, String arg) throws SAXException {
validSoFar = false;
if (eh == null)
return;
eh.error(new SAXParseException(localizer.message(key, arg), locator));
}
} |
package ameba.http.session;
import ameba.util.Times;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import javax.annotation.Priority;
import javax.inject.Singleton;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.*;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.NewCookie;
import java.lang.invoke.MethodHandle;
import java.net.URI;
import java.util.UUID;
/**
* @author icode
*/
@PreMatching
@Priority(Priorities.AUTHENTICATION - 1)
@Singleton
public class SessionFilter implements ContainerRequestFilter, ContainerResponseFilter {
private static final String SET_COOKIE_KEY = SessionFilter.class.getName() + ".__SET_SESSION_COOKIE__";
static String DEFAULT_SESSION_ID_COOKIE_KEY = "s";
static long SESSION_TIMEOUT = Times.parseDuration("2h") * 1000;
static int COOKIE_MAX_AGE = NewCookie.DEFAULT_MAX_AGE;
static MethodHandle METHOD_HANDLE;
@Override
@SuppressWarnings("unchecked")
public void filter(ContainerRequestContext requestContext) {
Cookie cookie = requestContext.getCookies().get(DEFAULT_SESSION_ID_COOKIE_KEY);
boolean isNew = false;
if (cookie == null) {
isNew = true;
cookie = newCookie(requestContext);
}
AbstractSession session;
if (METHOD_HANDLE != null) {
try {
session = (AbstractSession) METHOD_HANDLE.invoke(cookie.getValue(), SESSION_TIMEOUT, isNew);
} catch (Throwable throwable) {
throw new SessionExcption("new session instance error");
}
} else {
session = new CacheSession(cookie.getValue(), SESSION_TIMEOUT, isNew);
}
if (!session.isNew() && session.isInvalid()) {
cookie = newCookie(requestContext);
session.setId(cookie.getValue());
}
Session.sessionThreadLocal.set(session);
}
protected String newSessionId() {
return Hashing.sha1()
.hashString(
UUID.randomUUID().toString() + Math.random() + this.hashCode() + System.nanoTime(),
Charsets.UTF_8
)
.toString();
}
private NewCookie newCookie(ContainerRequestContext requestContext) {
URI uri = requestContext.getUriInfo().getBaseUri();
NewCookie cookie = new NewCookie(
DEFAULT_SESSION_ID_COOKIE_KEY,
newSessionId(),
uri.getPath(),
uri.getHost(),
Cookie.DEFAULT_VERSION,
null,
COOKIE_MAX_AGE,
null,
requestContext.getSecurityContext().isSecure(),
true);
requestContext.setProperty(SET_COOKIE_KEY, cookie);
return cookie;
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
Session.flush();
NewCookie cookie = (NewCookie) requestContext.getProperty(SET_COOKIE_KEY);
if (cookie != null)
responseContext.getHeaders().add("Set-Cookie", cookie.toString());
}
} |
package com.areen.jlib.gui;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
/**
*
* @author Dejan
*/
public class ImageLoaderSW extends SwingWorker<Image, Void> {
JLabel imageLabel;
URL webAddress;
private boolean pictureAvailable; /// Indicates whether picture exists on remote server or not.
public ImageLoaderSW(JLabel argLabel, URL argURL) {
imageLabel = argLabel;
webAddress = argURL;
pictureAvailable = false;
}
@Override
protected Image doInBackground() throws Exception {
Image image = null;
try {
image = ImageIO.read(webAddress);
} catch (IOException e) {
//e.printStackTrace();
System.err.println("ImageLoaderSW:IOException caught, cause: " + e.getCause());
}
return image;
} // diInBackground() method
@Override
protected void done() {
try {
Image image = get();
if (image == null) {
imageLabel.setIcon(new ImageIcon(GuiTools.getResource(getClass(),
"/com/areen/jlib/res/icons/image_not_available.png")));
imageLabel.setText("");
// we use this value to check whether we may show picture dialog or not
imageLabel.setName("imageLabel(na)");
pictureAvailable = false;
} else {
imageLabel.setIcon(new ImageIcon(image));
imageLabel.setText("");
imageLabel.setName("imageLabel(ok)");
pictureAvailable = true;
}
} catch (InterruptedException ex) {
System.out.println(ex);
//Logger.getLogger(ImageLoaderSW.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
System.out.println(ex);
//Logger.getLogger(ImageLoaderSW.class.getName()).log(Level.SEVERE, null, ex);
} // catch
} // done() method
public boolean isPictureAvailable() {
return pictureAvailable;
}
} // ImageLoaderSW class |
package purejavacomm;
// FIXME move javadoc comments for input stream to SerialPort.java
import java.io.*;
import java.util.*;
import com.sun.jna.Native;
import jtermios.*;
import static jtermios.JTermios.JTermiosLogging.*;
import static jtermios.JTermios.*;
public class PureJavaSerialPort extends SerialPort {
final boolean USE_POLL;
final boolean RAW_READ_MODE;
private Thread m_Thread;
private volatile SerialPortEventListener m_EventListener;
private volatile OutputStream m_OutputStream;
private volatile InputStream m_InputStream;
private volatile int m_FD = -1;
private volatile boolean m_HaveNudgePipe = false;
private volatile int m_PipeWrFD = 0;
private volatile int m_PipeRdFD = 0;
private byte[] m_NudgeData = { 0 };
private volatile int m_BaudRate;
private volatile int m_DataBits;
private volatile int m_FlowControlMode;
private volatile int m_Parity;
private volatile int m_StopBits;
private volatile Object m_ThresholdTimeoutLock = new Object();
private volatile boolean m_TimeoutThresholdChanged = true;
private volatile boolean m_ReceiveTimeoutEnabled;
private volatile int m_ReceiveTimeoutValue;
private volatile int m_ReceiveTimeoutVTIME;
private volatile boolean m_ReceiveThresholdEnabled;
private volatile int m_ReceiveThresholdValue;
private volatile boolean m_PollingReadMode;
private volatile boolean m_NotifyOnDataAvailable;
private volatile boolean m_DataAvailableNotified;
private volatile boolean m_NotifyOnOutputEmpty;
private volatile boolean m_OutputEmptyNotified;
private volatile boolean m_NotifyOnRI;
private volatile boolean m_NotifyOnCTS;
private volatile boolean m_NotifyOnDSR;
private volatile boolean m_NotifyOnCD;
private volatile boolean m_NotifyOnOverrunError;
private volatile boolean m_NotifyOnParityError;
private volatile boolean m_NotifyOnFramingError;
private volatile boolean m_NotifyOnBreakInterrupt;
private volatile boolean m_ThreadRunning;
private volatile boolean m_ThreadStarted;
private int[] m_ioctl = { 0 };
private int m_ControlLineStates;
// we cache termios in m_Termios because we don't rely on reading it back with tcgetattr()
// which for Mac OS X / CRTSCTS does not work, it is also more efficient
private Termios m_Termios = new Termios();
private int m_MinVTIME;
private void sendDataEvents(boolean read, boolean write) {
if (read && m_NotifyOnDataAvailable && !m_DataAvailableNotified) {
m_DataAvailableNotified = true;
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.DATA_AVAILABLE, false, true));
}
if (write && m_NotifyOnOutputEmpty && !m_OutputEmptyNotified) {
m_OutputEmptyNotified = true;
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.OUTPUT_BUFFER_EMPTY, false, true));
}
}
private synchronized void sendNonDataEvents() {
if (ioctl(m_FD, TIOCMGET, m_ioctl) < 0)
return; // FIXME decide what to with errors in the background thread
int oldstates = m_ControlLineStates;
m_ControlLineStates = m_ioctl[0];
int newstates = m_ControlLineStates;
int changes = oldstates ^ newstates;
if (changes == 0)
return;
int line;
if (m_NotifyOnCTS && (((line = TIOCM_CTS) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.CTS, (oldstates & line) != 0, (newstates & line) != 0));
if (m_NotifyOnDSR && (((line = TIOCM_DSR) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.DSR, (oldstates & line) != 0, (newstates & line) != 0));
if (m_NotifyOnRI && (((line = TIOCM_RI) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.RI, (oldstates & line) != 0, (newstates & line) != 0));
if (m_NotifyOnCD && (((line = TIOCM_CD) & changes) != 0))
m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.CD, (oldstates & line) != 0, (newstates & line) != 0));
}
@Override
synchronized public void addEventListener(SerialPortEventListener eventListener) throws TooManyListenersException {
checkState();
if (eventListener == null)
throw new IllegalArgumentException("eventListener cannot be null");
if (m_EventListener != null)
throw new TooManyListenersException();
m_EventListener = eventListener;
if (!m_ThreadStarted) {
m_ThreadStarted = true;
m_Thread.start();
}
}
@Override
synchronized public int getBaudRate() {
checkState();
return m_BaudRate;
}
@Override
synchronized public int getDataBits() {
checkState();
return m_DataBits;
}
@Override
synchronized public int getFlowControlMode() {
checkState();
return m_FlowControlMode;
}
@Override
synchronized public int getParity() {
checkState();
return m_Parity;
}
@Override
synchronized public int getStopBits() {
checkState();
return m_StopBits;
}
@Override
synchronized public boolean isCD() {
checkState();
return getControlLineState(TIOCM_CD);
}
@Override
synchronized public boolean isCTS() {
checkState();
return getControlLineState(TIOCM_CTS);
}
@Override
synchronized public boolean isDSR() {
checkState();
return getControlLineState(TIOCM_DSR);
}
@Override
synchronized public boolean isDTR() {
checkState();
return getControlLineState(TIOCM_DTR);
}
@Override
synchronized public boolean isRI() {
checkState();
return getControlLineState(TIOCM_RI);
}
@Override
synchronized public boolean isRTS() {
checkState();
return getControlLineState(TIOCM_RTS);
}
@Override
synchronized public void notifyOnBreakInterrupt(boolean x) {
checkState();
m_NotifyOnBreakInterrupt = x;
}
@Override
synchronized public void notifyOnCTS(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_CTS);
m_NotifyOnCTS = x;
nudgePipe();
}
@Override
synchronized public void notifyOnCarrierDetect(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_CD);
m_NotifyOnCD = x;
nudgePipe();
}
@Override
synchronized public void notifyOnDSR(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_DSR);
m_NotifyOnDSR = x;
nudgePipe();
}
@Override
synchronized public void notifyOnDataAvailable(boolean x) {
checkState();
m_NotifyOnDataAvailable = x;
nudgePipe();
}
@Override
synchronized public void notifyOnFramingError(boolean x) {
checkState();
m_NotifyOnFramingError = x;
}
@Override
synchronized public void notifyOnOutputEmpty(boolean x) {
checkState();
m_NotifyOnOutputEmpty = x;
nudgePipe();
}
@Override
synchronized public void notifyOnOverrunError(boolean x) {
checkState();
m_NotifyOnOverrunError = x;
}
@Override
synchronized public void notifyOnParityError(boolean x) {
checkState();
m_NotifyOnParityError = x;
}
@Override
synchronized public void notifyOnRingIndicator(boolean x) {
checkState();
if (x)
updateControlLineState(TIOCM_RI);
m_NotifyOnRI = x;
nudgePipe();
}
@Override
synchronized public void removeEventListener() {
checkState();
m_EventListener = null;
}
@Override
synchronized public void sendBreak(int duration) {
checkState();
// FIXME POSIX does not specify how duration is interpreted
// Opengroup POSIX says:
// If the terminal is using asynchronous serial data transmission, tcsendbreak()
// shall cause transmission of a continuous stream of zero-valued bits for a specific duration.
// If duration is 0, it shall cause transmission of zero-valued bits for at least 0.25 seconds,
// and not more than 0.5 seconds. If duration is not 0, it shall send zero-valued bits for an implementation-defined period of time.
// From the man page for Linux tcsendbreak:
// The effect of a non-zero duration with tcsendbreak() varies.
// SunOS specifies a break of duration*N seconds,
// where N is at least 0.25, and not more than 0.5. Linux, AIX, DU, Tru64 send a break of duration milliseconds.
// FreeBSD and NetBSD and HP-UX and MacOS ignore the value of duration.
// Under Solaris and Unixware, tcsendbreak() with non-zero duration behaves like tcdrain().
tcsendbreak(m_FD, duration);
}
@Override
synchronized public void setDTR(boolean x) {
checkState();
setControlLineState(TIOCM_DTR, x);
}
@Override
synchronized public void setRTS(boolean x) {
checkState();
setControlLineState(TIOCM_RTS, x);
}
@Override
synchronized public void disableReceiveFraming() {
checkState();
// Not supported
}
@Override
synchronized public void disableReceiveThreshold() {
checkState();
synchronized (m_ThresholdTimeoutLock) {
m_ReceiveThresholdEnabled = false;
thresholdOrTimeoutChanged();
}
}
@Override
synchronized public void disableReceiveTimeout() {
checkState();
synchronized (m_ThresholdTimeoutLock) {
m_ReceiveTimeoutEnabled = false;
thresholdOrTimeoutChanged();
}
}
@Override
synchronized public void enableReceiveThreshold(int value) throws UnsupportedCommOperationException {
checkState();
if (value < 0)
throw new IllegalArgumentException("threshold" + value + " < 0 ");
if (RAW_READ_MODE && value > 255)
throw new IllegalArgumentException("threshold" + value + " > 255 in raw read mode");
synchronized (m_ThresholdTimeoutLock) {
m_ReceiveThresholdEnabled = true;
m_ReceiveThresholdValue = value;
thresholdOrTimeoutChanged();
}
}
@Override
synchronized public void enableReceiveTimeout(int value) throws UnsupportedCommOperationException {
if (value < 0)
throw new IllegalArgumentException("threshold" + value + " < 0 ");
if (value > 25500)
throw new UnsupportedCommOperationException("threshold" + value + " > 25500 ");
checkState();
synchronized (m_ThresholdTimeoutLock) {
m_ReceiveTimeoutEnabled = true;
m_ReceiveTimeoutValue = value;
thresholdOrTimeoutChanged();
}
}
@Override
synchronized public void enableReceiveFraming(int arg0) throws UnsupportedCommOperationException {
checkState();
throw new UnsupportedCommOperationException("receive framing not supported/implemented");
}
private void thresholdOrTimeoutChanged() { // only call if you hold the lock
m_PollingReadMode = (m_ReceiveTimeoutEnabled && m_ReceiveTimeoutValue == 0) || (m_ReceiveThresholdEnabled && m_ReceiveThresholdValue == 0);
m_ReceiveTimeoutVTIME = (m_ReceiveTimeoutValue + 99) / 100; // precalculate this so we don't need the division in read
m_TimeoutThresholdChanged = true;
}
@Override
synchronized public int getInputBufferSize() {
checkState();
// Not supported
return 0;
}
@Override
synchronized public int getOutputBufferSize() {
checkState();
// Not supported
return 0;
}
@Override
synchronized public void setFlowControlMode(int mode) throws UnsupportedCommOperationException {
checkState();
synchronized (m_Termios) {
m_Termios.c_iflag &= ~IXANY;
if ((mode & (FLOWCONTROL_RTSCTS_IN | FLOWCONTROL_RTSCTS_OUT)) != 0)
m_Termios.c_cflag |= CRTSCTS;
else
m_Termios.c_cflag &= ~CRTSCTS;
if ((mode & FLOWCONTROL_XONXOFF_IN) != 0)
m_Termios.c_iflag |= IXOFF;
else
m_Termios.c_iflag &= ~IXOFF;
if ((mode & FLOWCONTROL_XONXOFF_OUT) != 0)
m_Termios.c_iflag |= IXON;
else
m_Termios.c_iflag &= ~IXON;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
m_FlowControlMode = mode;
}
}
@Override
synchronized public void setSerialPortParams(int baudRate, int dataBits, int stopBits, int parity) throws UnsupportedCommOperationException {
checkState();
synchronized (m_Termios) {
Termios prev = new Termios();// (termios);
// save a copy in case we need to restore it
prev.set(m_Termios);
try {
checkReturnCode(setspeed(m_FD, m_Termios, baudRate));
int db;
switch (dataBits) {
case SerialPort.DATABITS_5:
db = CS5;
break;
case SerialPort.DATABITS_6:
db = CS6;
break;
case SerialPort.DATABITS_7:
db = CS7;
break;
case SerialPort.DATABITS_8:
db = CS8;
break;
default:
throw new UnsupportedCommOperationException("dataBits = " + dataBits);
}
int sb;
switch (stopBits) {
case SerialPort.STOPBITS_1:
sb = 1;
break;
case SerialPort.STOPBITS_1_5:
// This setting must have been copied from the Win32 API and
// hasn't been properly thought through. 1.5 stop bits are
// only valid with 5 data bits and replace the 2 stop bits
// in this mode. This is a feature of the 16550 and even
// documented on MSDN
// As nobody is aware of course, we silently use 1.5 and 2
// stop bits interchangeably (just as the hardware does)
// Many linux drivers follow this convention and termios
// can't even differ between 1.5 and 2 stop bits
sb = 2;
break;
case SerialPort.STOPBITS_2:
sb = 2;
break;
default:
throw new UnsupportedCommOperationException("stopBits = " + stopBits);
}
int fi = m_Termios.c_iflag & ~(INPCK | ISTRIP);
int fc = m_Termios.c_cflag & ~(PARENB | CMSPAR | PARODD);
switch (parity) {
case SerialPort.PARITY_NONE:
break;
case SerialPort.PARITY_EVEN:
fc |= PARENB;
break;
case SerialPort.PARITY_ODD:
fc |= PARENB;
fc |= PARODD;
break;
case SerialPort.PARITY_MARK:
fc |= PARENB;
fc |= CMSPAR;
fc |= PARODD;
break;
case SerialPort.PARITY_SPACE:
fc |= PARENB;
fc |= CMSPAR;
break;
default:
throw new UnsupportedCommOperationException("parity = " + parity);
}
// update the hardware
fc &= ~CSIZE; /* Mask the character size bits */
fc |= db; /* Set data bits */
if (sb == 2)
fc |= CSTOPB;
else
fc &= ~CSTOPB;
m_Termios.c_cflag = fc;
m_Termios.c_iflag = fi;
if (tcsetattr(m_FD, TCSANOW, m_Termios) != 0)
throw new UnsupportedCommOperationException("tcsetattr failed");
// Even if termios(3) tells us that tcsetattr succeeds if any change
// has been made, not necessary all of them we cannot check them by reading back
// and checking the result as not every driver/OS playes by the rules
// finally everything went ok, so we can update our settings
m_BaudRate = baudRate;
m_Parity = parity;
m_DataBits = dataBits;
m_StopBits = stopBits;
} catch (UnsupportedCommOperationException e) {
m_Termios.set(prev);
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
throw e;
} catch (IllegalStateException e) {
m_Termios.set(prev);
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
if (e instanceof PureJavaIllegalStateException) {
throw e;
} else {
throw new PureJavaIllegalStateException(e);
}
}
}
}
/**
* Gets the native file descriptor used by this port.
* <p>
* The file descriptor can be used in calls to JTermios functions. This
* maybe useful in extreme cases where performance is more important than
* convenience, for example using <code>JTermios.read(...)</code> instead of
* <code>SerialPort.getInputStream().read(...)</code>.
* <p>
* Note that mixing direct JTermios read/write calls with SerialPort stream
* read/write calls is at best fragile and likely to fail, which also
* implies that when using JTermios directly then configuring the port,
* especially termios.cc[VMIN] and termios.cc[VTIME] is the users
* responsibility.
* <p>
* Below is a sketch of minimum necessary to perform a read using raw
* JTermios functionality.
*
* <pre>
* <code>
* // import the JTermios functionality like this
* import jtermios.*;
* import static jtermios.JTermios.*;
*
* SerialPort port = ...;
*
* // cast the port to PureJavaSerialPort to get access to getNativeFileDescriptor
* int FD = ((PureJavaSerialPort) port).getNativeFileDescriptor();
*
* // timeout and threshold values
* int messageLength = 25; // bytes
* int timeout = 200; // msec
*
* // to initialize timeout and threshold first read current termios
* Termios termios = new Termios();
*
* if (0 != tcgetattr(FD, termios))
* errorHandling();
*
* // then set VTIME and VMIN, note VTIME in 1/10th of sec and both max 255
* termios.c_cc[VTIME] = (byte) ((timeout+99) / 100);
* termios.c_cc[VMIN] = (byte) messageLength;
*
* // update termios
* if (0 != tcsetattr(FD, TCSANOW, termios))
* errorHandling();
*
* ...
* // allocate read buffer
* byte[] readBuffer = new byte[messageLength];
* ...
*
* // then perform raw read, not this may block indefinitely
* int n = read(FD, readBuffer, messageLength);
* if (n < 0)
* errorHandling();
* <code>
* </pre>
*
* @return the native OS file descriptor as int
*/
public int getNativeFileDescriptor() {
return m_FD;
}
@Override
synchronized public OutputStream getOutputStream() throws IOException {
checkState();
if (m_OutputStream == null) {
m_OutputStream = new OutputStream() {
// im_ for inner class member
private byte[] im_Buffer = new byte[2048];
@Override
final public void write(int b) throws IOException {
checkState();
byte[] buf = { (byte) b };
write(buf, 0, 1);
}
@Override
final public void write(byte[] buffer, int offset, int length) throws IOException {
if (buffer == null)
throw new IllegalArgumentException();
if (offset < 0 || length < 0 || offset + length > buffer.length)
throw new IndexOutOfBoundsException("buffer.lengt " + buffer.length + " offset " + offset + " length " + length);
checkState();
while (length > 0) {
int n = buffer.length - offset;
if (n > im_Buffer.length)
n = im_Buffer.length;
if (n > length)
n = length;
if (offset > 0) {
System.arraycopy(buffer, offset, im_Buffer, 0, n);
n = jtermios.JTermios.write(m_FD, im_Buffer, n);
} else
n = jtermios.JTermios.write(m_FD, buffer, n);
if (n < 0) {
PureJavaSerialPort.this.close();
throw new IOException();
}
length -= n;
offset += n;
}
m_OutputEmptyNotified = false;
}
@Override
final public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void close() throws IOException {
super.close();
}
@Override
final public void flush() throws IOException {
checkState();
if (tcdrain(m_FD) < 0) {
close();
throw new IOException();
}
}
};
}
return m_OutputStream;
}
synchronized public InputStream getInputStream() throws IOException {
checkState();
if (m_InputStream == null) {
// NOTE: Windows and unixes are so different that it actually might
// make sense to have the backend (ie JTermiosImpl) to provide
// an InputStream that is optimal for the platform, instead of
// trying to share of the InputStream logic here and force
// Windows backend to conform to the the POSIX select()/
// read()/vtim/vtime model. See the amount of code here
// and in windows.JTermiosImpl for select() and read().
m_InputStream = new InputStream() {
// im_ for inner class members
private int[] im_Available = { 0 };
private byte[] im_Buffer = new byte[2048];
// this stuff is just cached/precomputed stuff to make read() faster
private int im_VTIME = -1;
private int im_VMIN = -1;
private final jtermios.Pollfd[] im_ReadPollFD = new Pollfd[] { new Pollfd(), new Pollfd() };
private byte[] im_Nudge;
private FDSet im_ReadFDSet;
private TimeVal im_ReadTimeVal;
private int im_PollFDn;
private boolean im_ReceiveTimeoutEnabled;
private int im_ReceiveTimeoutValue;
private boolean im_ReceiveThresholdEnabled;
private int im_ReceiveThresholdValue;
private boolean im_PollingReadMode;
private int im_ReceiveTimeoutVTIME;
{ // initialized block instead of construct in anonymous class
im_ReadFDSet = newFDSet();
im_ReadTimeVal = new TimeVal();
im_ReadPollFD[0].fd = m_FD;
im_ReadPollFD[0].events = POLLIN;
im_ReadPollFD[1].fd = m_PipeRdFD;
im_ReadPollFD[1].events = POLLIN;
im_PollFDn = m_HaveNudgePipe ? 2 : 1;
im_Nudge = new byte[1];
}
@Override
final public int available() throws IOException {
if (m_FD < 0)
return 0;
checkState();
if (ioctl(m_FD, FIONREAD, im_Available) < 0) {
PureJavaSerialPort.this.close();
System.out.println(Native.getLastError());
throw new IOException();
}
return im_Available[0];
}
@Override
final public int read() throws IOException {
byte[] buf = { 0 };
int n = read(buf, 0, 1);
return n > 0 ? buf[0] & 0xFF : -1;
}
@Override
public void close() throws IOException {
super.close();
}
@Override
final public int read(byte[] buffer, int offset, int length) throws IOException {
try {
if (buffer == null)
throw new IllegalArgumentException("buffer null");
if (length == 0)
return 0;
if (offset < 0 || length < 0 || offset + length > buffer.length)
throw new IndexOutOfBoundsException("buffer.length " + buffer.length + " offset " + offset + " length " + length);
if (m_FD < 0)
return -1;
if (RAW_READ_MODE) {
if (m_TimeoutThresholdChanged) { // does not need the lock if we just check the value
synchronized (m_ThresholdTimeoutLock) {
int vtime = m_ReceiveTimeoutEnabled ? m_ReceiveTimeoutVTIME : 0;
int vmin = m_ReceiveThresholdEnabled ? m_ReceiveThresholdValue : 1;
synchronized (m_Termios) {
m_Termios.c_cc[VTIME] = (byte) vtime;
m_Termios.c_cc[VMIN] = (byte) vmin;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
}
m_TimeoutThresholdChanged = false;
}
}
int bytesRead;
if (offset > 0) {
if (length < im_Buffer.length)
bytesRead = jtermios.JTermios.read(m_FD, im_Buffer, length);
else
bytesRead = jtermios.JTermios.read(m_FD, im_Buffer, im_Buffer.length);
if (bytesRead > 0)
System.arraycopy(im_Buffer, 0, buffer, offset, bytesRead);
} else
bytesRead = jtermios.JTermios.read(m_FD, buffer, length);
m_DataAvailableNotified = false;
return bytesRead;
} // End of raw read mode code
if (m_TimeoutThresholdChanged) { // does not need the lock if we just check the alue
synchronized (m_ThresholdTimeoutLock) {
// capture these here under guard so that we get a coherent picture of the settings
im_ReceiveTimeoutEnabled = m_ReceiveTimeoutEnabled;
im_ReceiveTimeoutValue = m_ReceiveTimeoutValue;
im_ReceiveThresholdEnabled = m_ReceiveThresholdEnabled;
im_ReceiveThresholdValue = m_ReceiveThresholdValue;
im_PollingReadMode = m_PollingReadMode;
im_ReceiveTimeoutVTIME = m_ReceiveTimeoutVTIME;
m_TimeoutThresholdChanged = false;
}
}
int bytesLeft = length;
int bytesReceived = 0;
int minBytesRequired;
// Note for optimal performance: message length == receive threshold == read length <= 255
// the best case execution path is marked with BEST below
while (true) {
// loops++;
int vmin;
int vtime;
if (im_PollingReadMode) {
minBytesRequired = 0;
vmin = 0;
vtime = 0;
} else {
if (im_ReceiveThresholdEnabled)
minBytesRequired = im_ReceiveThresholdValue; // BEST
else
minBytesRequired = 1;
if (minBytesRequired > bytesLeft) // in BEST case 'if' not taken
minBytesRequired = bytesLeft;
if (minBytesRequired <= 255)
vmin = minBytesRequired; // BEST case
else
vmin = 255;
// FIXME someone might change m_ReceiveTimeoutEnabled
if (im_ReceiveTimeoutEnabled)
vtime = im_ReceiveTimeoutVTIME; // BEST case
else
vtime = 0;
}
if (vmin != im_VMIN || vtime != im_VTIME) { // in BEST case 'if' not taken more than once for given InputStream instance
// ioctls++;
im_VMIN = vmin;
im_VTIME = vtime;
// This needs to be guarded with m_Termios so that these thing don't change on us
synchronized (m_Termios) {
m_Termios.c_cc[VTIME] = (byte) im_VTIME;
m_Termios.c_cc[VMIN] = (byte) im_VMIN;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
}
}
// Now wait for data to be available, except in raw read mode
// and polling read modes. Following looks a bit longish
// but there is actually not that much code to be executed
boolean dataAvailable = false;
boolean timedout = false;
if (!im_PollingReadMode) {
int n;
// long T0 = System.nanoTime();
// do a select()/poll(), just in case this read was
// called when no data is available
// so that we will not hang for ever in a read
int timeoutValue = im_ReceiveTimeoutEnabled ? im_ReceiveTimeoutValue : Integer.MAX_VALUE;
if (USE_POLL) { // BEST case in Linux but not on
// Windows or Mac OS X
n = poll(im_ReadPollFD, im_PollFDn, timeoutValue);
if (n < 0 || m_FD < 0) // the port closed while we were blocking in poll
throw new IOException();
if ((im_ReadPollFD[1].revents & POLLIN) != 0)
jtermios.JTermios.read(m_PipeRdFD, im_Nudge, 1);
int re = im_ReadPollFD[0].revents;
if ((re & POLLNVAL_OUT) != 0)
throw new IOException();
dataAvailable = (re & POLLIN) != 0;
} else { // this is a bit slower but then again it is unlikely
// this gets executed in a low horsepower system
FD_ZERO(im_ReadFDSet);
FD_SET(m_FD, im_ReadFDSet);
int maxFD = m_FD;
if (m_HaveNudgePipe) {
FD_SET(m_PipeRdFD, im_ReadFDSet);
if (m_PipeRdFD > maxFD)
maxFD = m_PipeRdFD;
}
if (timeoutValue >= 1000) {
int t = timeoutValue / 1000;
im_ReadTimeVal.tv_sec = t;
im_ReadTimeVal.tv_usec = (timeoutValue - t * 1000) * 1000;
} else {
im_ReadTimeVal.tv_sec = 0;
im_ReadTimeVal.tv_usec = timeoutValue * 1000;
}
n = select(maxFD + 1, im_ReadFDSet, null, null, im_ReadTimeVal);
if (n < 0)
throw new IOException();
if (m_FD < 0) // the port closed while we were
// blocking in select
throw new IOException();
dataAvailable = FD_ISSET(m_FD, im_ReadFDSet);
}
if (n == 0 && m_ReceiveTimeoutEnabled)
timedout = true;
}
if (timedout)
break;
// At this point data is either available or we take our
// chances in raw mode or this polling read which can't block
int bytesRead = 0;
if (dataAvailable || im_PollingReadMode) {
if (offset > 0) {
if (bytesLeft < im_Buffer.length)
bytesRead = jtermios.JTermios.read(m_FD, im_Buffer, bytesLeft);
else
bytesRead = jtermios.JTermios.read(m_FD, im_Buffer, im_Buffer.length);
if (bytesRead > 0)
System.arraycopy(im_Buffer, 0, buffer, offset, bytesRead);
} else
// this the BEST case execution path
bytesRead = jtermios.JTermios.read(m_FD, buffer, bytesLeft);
// readtime += System.nanoTime() - T0;
if (bytesRead == 0)
timedout = true;
}
// Now we have read data and try to return as quickly as
// possibly or we have timed out.
if (bytesRead < 0) // an error occured
throw new IOException();
bytesReceived += bytesRead;
if (bytesReceived >= minBytesRequired) // BEST case this if is taken and we exit
break; // we have read the minimum required and will return that
if (timedout)
break;
// Ok, looks like we are in for an other loop, so update
// the offset
// and loop for some more
offset += bytesRead;
bytesLeft -= bytesRead;
}
m_DataAvailableNotified = false;
return bytesReceived;
} catch (IOException e) {
// if the exception is caused by some other thread closing the device then just return -1
if (m_FD < 0)
return -1;
else
throw e;
}
}
};
}
return m_InputStream;
}
@Override
synchronized public int getReceiveFramingByte() {
checkState();
// Not supported
return 0;
}
@Override
synchronized public int getReceiveThreshold() {
checkState();
return m_ReceiveThresholdValue;
}
@Override
synchronized public int getReceiveTimeout() {
checkState();
return m_ReceiveTimeoutValue;
}
@Override
synchronized public boolean isReceiveFramingEnabled() {
checkState();
// Not supported
return false;
}
@Override
synchronized public boolean isReceiveThresholdEnabled() {
checkState();
return m_ReceiveThresholdEnabled;
}
@Override
synchronized public boolean isReceiveTimeoutEnabled() {
checkState();
return m_ReceiveTimeoutEnabled;
}
@Override
synchronized public void setInputBufferSize(int arg0) {
checkState();
// Not supported
}
@Override
synchronized public void setOutputBufferSize(int arg0) {
checkState();
// Not supported
}
private void nudgePipe() {
if (m_HaveNudgePipe)
write(m_PipeWrFD, m_NudgeData, 1);
}
@Override
synchronized public void close() {
int fd = m_FD;
if (fd != -1) {
m_FD = -1;
try {
if (m_InputStream != null)
m_InputStream.close();
} catch (IOException e) {
log = log && log(1, "m_InputStream.close threw an IOException %s\n", e.getMessage());
} finally {
m_InputStream = null;
}
try {
if (m_OutputStream != null)
m_OutputStream.close();
} catch (IOException e) {
log = log && log(1, "m_OutputStream.close threw an IOException %s\n", e.getMessage());
} finally {
m_OutputStream = null;
}
nudgePipe();
int flags = fcntl(fd, F_GETFL, 0);
flags |= O_NONBLOCK;
int fcres = fcntl(fd, F_SETFL, flags);
if (fcres != 0) // not much we can do if this fails, so just log it
log = log && log(1, "fcntl(%d,%d,%d) returned %d\n", fd, F_SETFL, flags, fcres);
if (m_Thread != null)
m_Thread.interrupt();
int err = jtermios.JTermios.close(fd);
if (err < 0)
log = log && log(1, "JTermios.close returned %d, errno %d\n", err, errno());
if (m_HaveNudgePipe) {
err = jtermios.JTermios.close(m_PipeRdFD);
if (err < 0)
log = log && log(1, "JTermios.close returned %d, errno %d\n", err, errno());
err = jtermios.JTermios.close(m_PipeWrFD);
if (err < 0)
log = log && log(1, "JTermios.close returned %d, errno %d\n", err, errno());
}
long t0 = System.currentTimeMillis();
while (m_ThreadRunning) {
try {
Thread.sleep(5);
if (System.currentTimeMillis() - t0 > 2000)
break;
} catch (InterruptedException e) {
break;
}
}
super.close();
}
}
/* package */PureJavaSerialPort(String name, int timeout) throws PortInUseException {
super();
boolean usepoll = false;
if (JTermios.canPoll()) {
String key1 = "purejavacomm.use_poll";
String key2 = "purejavacomm.usepoll";
if (System.getProperty(key1) != null) {
usepoll = Boolean.getBoolean(key1);
log = log && log(1, "use of '%s' is deprecated, use '%s' instead\n", key1, key2);
} else if (System.getProperty(key2) != null)
usepoll = Boolean.getBoolean(key2);
else
usepoll = true;
}
USE_POLL = usepoll;
RAW_READ_MODE = Boolean.getBoolean("purejavacomm.rawreadmode");
this.name = name;
int tries = (timeout + 5) / 10;
while ((m_FD = open(name, O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0) {
int errno = errno();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
if (tries
throw new PortInUseException("Unknown Application", errno);
}
m_MinVTIME = Integer.getInteger("purejavacomm.minvtime", 100);
int flags = fcntl(m_FD, F_GETFL, 0);
if (flags < 0)
checkReturnCode(flags);
flags &= ~O_NONBLOCK;
checkReturnCode(fcntl(m_FD, F_SETFL, flags));
m_BaudRate = 9600;
m_DataBits = SerialPort.DATABITS_8;
m_FlowControlMode = SerialPort.FLOWCONTROL_NONE;
m_Parity = SerialPort.PARITY_NONE;
m_StopBits = SerialPort.STOPBITS_1;
checkReturnCode(tcgetattr(m_FD, m_Termios));
cfmakeraw(m_FD, m_Termios);
m_Termios.c_cflag |= CLOCAL | CREAD;
m_Termios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
m_Termios.c_oflag &= ~OPOST;
m_Termios.c_cc[VSTART] = (byte) DC1;
m_Termios.c_cc[VSTOP] = (byte) DC3;
m_Termios.c_cc[VMIN] = 0;
m_Termios.c_cc[VTIME] = 0;
checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios));
try {
setSerialPortParams(m_BaudRate, m_DataBits, m_StopBits, m_Parity);
} catch (UnsupportedCommOperationException e) {
// This really should not happen
e.printStackTrace();
}
try {
setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
} catch (UnsupportedCommOperationException e) {
// This really should not happen
e.printStackTrace();
}
int res = ioctl(m_FD, TIOCMGET, m_ioctl);
if (res == 0)
m_ControlLineStates = m_ioctl[0];
else
log = log && log(1, "ioctl(TIOCMGET) returned %d, errno %d\n", res, errno());
String nudgekey = "purejavacomm.usenudgepipe";
if (System.getProperty(nudgekey) == null || Boolean.getBoolean(nudgekey)) {
int[] pipes = new int[2];
if (pipe(pipes) == 0) {
m_HaveNudgePipe = true;
m_PipeRdFD = pipes[0];
m_PipeWrFD = pipes[1];
checkReturnCode(fcntl(m_PipeRdFD, F_SETFL, fcntl(m_PipeRdFD, F_GETFL, 0) | O_NONBLOCK));
}
}
Runnable runnable = new Runnable() {
public void run() {
try {
m_ThreadRunning = true;
final int TIMEOUT = Integer.getInteger("purejavacomm.pollperiod", 10);
TimeVal timeout = null;
FDSet rset = null;
FDSet wset = null;
jtermios.Pollfd[] pollfd = null;
byte[] nudge = null;
if (USE_POLL) {
pollfd = new Pollfd[] { new Pollfd(), new Pollfd() };
nudge = new byte[1];
pollfd[0].fd = m_FD;
pollfd[1].fd = m_PipeRdFD;
} else {
rset = newFDSet();
wset = newFDSet();
timeout = new TimeVal();
int t = TIMEOUT * 1000;
timeout.tv_sec = t / 1000000;
timeout.tv_usec = t - timeout.tv_sec * 1000000;
}
while (m_FD >= 0) {
boolean read = (m_NotifyOnDataAvailable && !m_DataAvailableNotified);
boolean write = (m_NotifyOnOutputEmpty && !m_OutputEmptyNotified);
int n = 0;
boolean pollCtrlLines = m_NotifyOnCTS || m_NotifyOnDSR || m_NotifyOnRI || m_NotifyOnCD;
if (read || write || (!pollCtrlLines && m_HaveNudgePipe)) {
if (USE_POLL) {
short e = 0;
if (read)
e |= POLLIN;
if (write)
e |= POLLOUT;
pollfd[0].events = e;
pollfd[1].events = POLLIN;
if (m_HaveNudgePipe)
n = poll(pollfd, 2, TIMEOUT);
else
n = poll(pollfd, 1, TIMEOUT);
int re = pollfd[1].revents;
if ((re & POLLNVAL) != 0) {
log = log && log(1, "poll() returned POLLNVAL, errno %d\n", errno());
break;
}
if ((re & POLLIN) != 0)
read(m_PipeRdFD, nudge, 1);
re = pollfd[0].revents;
if ((re & POLLNVAL) != 0) {
log = log && log(1, "poll() returned POLLNVAL, errno %d\n", errno());
break;
}
read = read && (re & POLLIN) != 0;
write = write && (re & POLLOUT) != 0;
} else {
FD_ZERO(rset);
FD_ZERO(wset);
if (read)
FD_SET(m_FD, rset);
if (write)
FD_SET(m_FD, wset);
if (m_HaveNudgePipe)
FD_SET(m_PipeRdFD, rset);
n = select(m_FD + 1, rset, wset, null, m_HaveNudgePipe ? null : timeout);
read = read && FD_ISSET(m_FD, rset);
write = write && FD_ISSET(m_FD, wset);
}
if (m_FD < 0)
break;
if (n < 0) {
log = log && log(1, "select() or poll() returned %d, errno %d\n", n, errno());
close();
break;
}
} else {
Thread.sleep(TIMEOUT);
}
if (m_EventListener != null) {
if (read || write)
sendDataEvents(read, write);
if (pollCtrlLines)
sendNonDataEvents();
}
}
} catch (InterruptedException ie) {
} finally {
m_ThreadRunning = false;
}
}
};
m_Thread = new Thread(runnable, getName());
m_Thread.setDaemon(true);
}
synchronized private void updateControlLineState(int line) {
checkState();
if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1)
throw new PureJavaIllegalStateException("ioctl(m_FD, TIOCMGET, m_ioctl) == -1");
m_ControlLineStates = (m_ioctl[0] & line) + (m_ControlLineStates & ~line);
}
synchronized private boolean getControlLineState(int line) {
checkState();
if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1)
throw new PureJavaIllegalStateException("ioctl(m_FD, TIOCMGET, m_ioctl) == -1");
return (m_ioctl[0] & line) != 0;
}
synchronized private void setControlLineState(int line, boolean state) {
checkState();
if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1)
throw new PureJavaIllegalStateException("ioctl(m_FD, TIOCMGET, m_ioctl) == -1");
if (state)
m_ioctl[0] |= line;
else
m_ioctl[0] &= ~line;
if (ioctl(m_FD, TIOCMSET, m_ioctl) == -1)
throw new PureJavaIllegalStateException("ioctl(m_FD, TIOCMSET, m_ioctl) == -1");
}
private void failWithIllegalStateException() {
throw new PureJavaIllegalStateException("File descriptor is " + m_FD + " < 0, maybe closed by previous error condition");
}
private void checkState() {
if (m_FD < 0)
failWithIllegalStateException();
}
private void checkReturnCode(int code) {
if (code != 0) {
String msg = String.format("JTermios call returned %d at %s", code, lineno(1));
log = log && log(1, "%s\n", msg);
try {
close();
} catch (Exception e) {
StackTraceElement st = e.getStackTrace()[0];
String msg2 = String.format("close threw %s at class %s line% d", e.getClass().getName(), st.getClassName(), st.getLineNumber());
log = log && log(1, "%s\n", msg2);
}
throw new PureJavaIllegalStateException(msg);
}
}
/**
* This is not part of the PureJavaComm API, this is purely for testing, do
* not depend on this
*/
public boolean isInternalThreadRunning() {
return m_ThreadRunning;
}
} |
package com.codeborne.selenide;
import org.openqa.selenium.By;
import static com.codeborne.selenide.impl.Quotes.escape;
public class Selectors {
/**
* Find element CONTAINING given text (as a substring)
*
* NB! It seems that Selenium WebDriver does not support i18n characters in XPath :(
*
* @param elementText Text to search inside element
* @return standard selenium By criteria
*/
public static By withText(String elementText) {
return By.xpath(".//*/text()[contains(normalize-space(.), " + escape.quotes(elementText) + ")]/parent::*");
}
/**
* Find element that has EXACTLY this text
*
* NB! It seems that Selenium WebDriver does not support i18n characters in XPath :(
*
* @param elementText Text that searched element should have
* @return standard selenium By criteria
*/
public static By byText(String elementText) {
return By.xpath(".//*/text()[normalize-space(.) = " + escape.quotes(elementText) + "]/parent::*");
}
/**
* Find elements having attribute with given value.
*
* Seems to work incorrectly if attribute name contains dash, for example: <option data-mailServerId="123"></option>
*
* @param attributeName name of attribute, should not be empty or null
* @param attributeValue value of attribute, should not contain both apostrophes and quotes
* @return standard selenium By criteria
*/
public static By byAttribute(String attributeName, String attributeValue) {
/**
* Synonym for #byAttribute
*
* Seems to work incorrectly in HtmlUnit and PhantomJS if attribute name contains dash (e.g. "data-mailServerId")
*/
public static By by(String attributeName, String attributeValue) {
return byAttribute(attributeName, attributeValue);
}
/**
* Find element with given title ("title" attribute)
*/
public static By byTitle(String title) {
return byAttribute("title", title);
}
public static By byValue(String value) {
return byAttribute("value", value);
}
} |
package com.fewlaps.quitnowcache;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class QNCache<T> {
public static final long KEEPALIVE_FOREVER = 0;
private final ConcurrentHashMap<String, QNCacheBean<T>> cache;
private boolean caseSensitiveKeys = true;
private Integer autoReleaseInSeconds;
private Long defaultKeepaliveInMillis;
private DateProvider dateProvider = DateProvider.SYSTEM;
public QNCache(boolean caseSensitiveKeys, Integer autoReleaseInSeconds, Long defaultKeepaliveInMillis) {
this.caseSensitiveKeys = caseSensitiveKeys;
if (autoReleaseInSeconds != null && autoReleaseInSeconds > 0) {
this.autoReleaseInSeconds = autoReleaseInSeconds;
}
if (defaultKeepaliveInMillis != null && defaultKeepaliveInMillis > 0) {
this.defaultKeepaliveInMillis = defaultKeepaliveInMillis;
}
cache = new ConcurrentHashMap<String, QNCacheBean<T>>();
startAutoReleaseServiceIfNeeded();
}
private void startAutoReleaseServiceIfNeeded() {
if (autoReleaseInSeconds != null) {
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
purge();
}
}, autoReleaseInSeconds, autoReleaseInSeconds, TimeUnit.SECONDS);
}
}
boolean isCaseSensitiveKeys() {
return caseSensitiveKeys;
}
Integer getAutoReleaseInSeconds() {
return autoReleaseInSeconds;
}
Long getDefaultKeepaliveInMillis() {
return defaultKeepaliveInMillis;
}
private long now() {
return dateProvider.now();
}
protected void setDateProvider(DateProvider dateProvider) {
this.dateProvider = dateProvider;
}
public void set(String key, T value) {
if (defaultKeepaliveInMillis != null) {
set(key, value, defaultKeepaliveInMillis);
} else {
set(key, value, KEEPALIVE_FOREVER);
}
}
public void set(String key, T value, long keepAliveInMillis) {
String effectiveKey = getEffectiveKey(key);
if (keepAliveInMillis >= 0) {
cache.put(effectiveKey, new QNCacheBean<T>(value, now(), keepAliveInMillis));
}
}
public List<String> listCachedKeysStartingWith(String keyStartingWith) {
List<String> keys = new ArrayList<String>();
String effectiveKeyStartingWith = getEffectiveKey(keyStartingWith);
for (String key : Collections.list(cache.keys())) {
if (key.startsWith(effectiveKeyStartingWith)) {
keys.add(key);
}
}
return keys;
}
public List<String> listCachedKeysStartingWithIfAlive(String keyStartingWith) {
List<String> keys = new ArrayList<String>();
long now = now();
for (String key : listCachedKeysStartingWith(keyStartingWith)) {
if (cache.get(key).isAlive(now)) {
keys.add(key);
}
}
return keys;
}
public void set(String key, T value, long keepAliveUnits, TimeUnit timeUnit) {
set(key, value, timeUnit.toMillis(keepAliveUnits));
}
/**
* Gets an element from the cache.
*/
public T get(String key) {
String effectiveKey = getEffectiveKey(key);
QNCacheBean<T> retrievedValue = cache.get(effectiveKey);
if (retrievedValue == null || !retrievedValue.isAlive(now())) {
return null;
} else {
return retrievedValue.getValue();
}
}
/**
* Gets an element from the cache. If the element exists but it's dead,
* it will be removed of the cache, to free memory
*/
T getAndRemoveIfDead(String key) {
String effectiveKey = getEffectiveKey(key);
QNCacheBean<T> retrievedValue = cache.get(effectiveKey);
if (retrievedValue == null) {
return null;
} else if (retrievedValue.isAlive(now())) {
return retrievedValue.getValue();
} else {
cache.remove(effectiveKey);
return null;
}
}
public void remove(String key) {
String effectiveKey = getEffectiveKey(key);
cache.remove(effectiveKey);
}
/**
* Removes all the elements of the cache, ignoring if they're dead or alive
*/
public void clear() {
cache.clear();
}
/**
* Removes the dead elements of the cache, to free memory
*/
void purge() {
Iterator<Map.Entry<String, QNCacheBean<T>>> it = cache.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, QNCacheBean<T>> entry = it.next();
QNCacheBean<T> bean = entry.getValue();
if (!bean.isAlive(now())) {
it.remove();
}
}
}
/**
* Counts how much alive elements are living in the cache
*/
public int size() {
return sizeCountingOnlyAliveElements();
}
/**
* Counts how much alive elements are living in the cache
*/
int sizeCountingOnlyAliveElements() {
int size = 0;
for (QNCacheBean<T> cacheValue : cache.values()) {
if (cacheValue.isAlive(now())) {
size++;
}
}
return size;
}
/**
* Counts how much elements are living in the cache, ignoring if they are dead or alive
*/
int sizeCountingDeadAndAliveElements() {
return cache.size();
}
/**
* The common isEmpty() method, but only looking for alive elements
*/
public boolean isEmpty() {
return sizeCountingOnlyAliveElements() == 0;
}
public boolean contains(String key) {
String effectiveKey = getEffectiveKey(key);
return get(effectiveKey) != null;
}
/**
* If caseSensitiveKeys is false, it returns a key in lowercase. It will be
* the key of all stored values, so the cache will be totally caseinsensitive
*/
private String getEffectiveKey(String key) {
if (!caseSensitiveKeys) {
return key.toLowerCase();
}
return key;
}
} |
package org.innovateuk.ifs.project.workflow.projectdetails;
import org.innovateuk.ifs.project.domain.Project;
import org.innovateuk.ifs.project.projectdetails.domain.ProjectDetailsProcess;
import org.innovateuk.ifs.project.domain.ProjectUser;
import org.innovateuk.ifs.project.projectdetails.repository.ProjectDetailsProcessRepository;
import org.innovateuk.ifs.project.resource.ProjectDetailsEvent;
import org.innovateuk.ifs.project.resource.ProjectDetailsState;
import org.innovateuk.ifs.project.projectdetails.workflow.actions.BaseProjectDetailsAction;
import org.innovateuk.ifs.project.projectdetails.workflow.configuration.ProjectDetailsWorkflowHandler;
import org.innovateuk.ifs.user.domain.Organisation;
import org.innovateuk.ifs.workflow.BaseWorkflowHandlerIntegrationTest;
import org.innovateuk.ifs.workflow.domain.ActivityState;
import org.innovateuk.ifs.workflow.repository.ActivityStateRepository;
import org.innovateuk.ifs.workflow.resource.State;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.Repository;
import java.time.LocalDate;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher;
import static org.innovateuk.ifs.address.builder.AddressBuilder.newAddress;
import static org.innovateuk.ifs.invite.domain.ProjectParticipantRole.PROJECT_FINANCE_CONTACT;
import static org.innovateuk.ifs.invite.domain.ProjectParticipantRole.PROJECT_MANAGER;
import static org.innovateuk.ifs.project.builder.ProjectBuilder.newProject;
import static org.innovateuk.ifs.project.builder.ProjectUserBuilder.newProjectUser;
import static org.innovateuk.ifs.project.resource.ProjectDetailsEvent.*;
import static org.innovateuk.ifs.user.builder.OrganisationBuilder.newOrganisation;
import static org.innovateuk.ifs.util.CollectionFunctions.combineLists;
import static org.innovateuk.ifs.workflow.domain.ActivityType.PROJECT_SETUP_PROJECT_DETAILS;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class ProjectDetailsWorkflowHandlerIntegrationTest extends
BaseWorkflowHandlerIntegrationTest<ProjectDetailsWorkflowHandler, ProjectDetailsProcessRepository, BaseProjectDetailsAction> {
@Autowired
private ProjectDetailsWorkflowHandler projectDetailsWorkflowHandler;
private ActivityStateRepository activityStateRepositoryMock;
private ProjectDetailsProcessRepository projectDetailsProcessRepositoryMock;
@Override
protected void collectMocks(Function<Class<? extends Repository>, Repository> mockSupplier) {
activityStateRepositoryMock = (ActivityStateRepository) mockSupplier.apply(ActivityStateRepository.class);
projectDetailsProcessRepositoryMock = (ProjectDetailsProcessRepository) mockSupplier.apply(ProjectDetailsProcessRepository.class);
}
@Test
public void testProjectCreated() throws Exception {
Project project = newProject().build();
ProjectUser projectUser = newProjectUser().build();
ActivityState pendingState = new ActivityState(PROJECT_SETUP_PROJECT_DETAILS, State.PENDING);
when(activityStateRepositoryMock.findOneByActivityTypeAndState(PROJECT_SETUP_PROJECT_DETAILS, State.PENDING)).thenReturn(pendingState);
// this first step will not have access to an existing Process, because it's just starting
when(projectDetailsProcessRepositoryMock.findOneByTargetId(project.getId())).thenReturn(null);
// now call the method under test
assertTrue(projectDetailsWorkflowHandler.projectCreated(project, projectUser));
verify(projectDetailsProcessRepositoryMock).findOneByTargetId(project.getId());
verify(activityStateRepositoryMock).findOneByActivityTypeAndState(PROJECT_SETUP_PROJECT_DETAILS, State.PENDING);
verify(projectDetailsProcessRepositoryMock).save(
processExpectations(project.getId(), projectUser.getId(), ProjectDetailsState.PENDING, PROJECT_CREATED));
verifyNoMoreInteractionsWithMocks();
}
@Test
public void testAddProjectStartDate() throws Exception {
assertAddMandatoryValue((project, projectUser) -> projectDetailsWorkflowHandler.projectStartDateAdded(project, projectUser),
PROJECT_START_DATE_ADDED);
}
@Test
public void testAddProjectStartDateAndSubmitted() throws Exception {
assertAddMandatoryValueAndNowSubmittedFromPending(
(project, projectUser) -> projectDetailsWorkflowHandler.projectStartDateAdded(project, projectUser), PROJECT_START_DATE_ADDED);
}
@Test
public void testAddProjectAddress() throws Exception {
assertAddMandatoryValue((project, projectUser) -> projectDetailsWorkflowHandler.projectAddressAdded(project, projectUser),
PROJECT_ADDRESS_ADDED);
}
@Test
public void testAddProjectAddressAndSubmitted() throws Exception {
assertAddMandatoryValueAndNowSubmittedFromPending(
(project, projectUser) -> projectDetailsWorkflowHandler.projectAddressAdded(project, projectUser), PROJECT_ADDRESS_ADDED);
}
@Test
public void testAddProjectManager() throws Exception {
assertAddMandatoryValue((project, projectUser) -> projectDetailsWorkflowHandler.projectManagerAdded(project, projectUser),
PROJECT_MANAGER_ADDED);
}
@Test
public void testAddProjectManagerAndSubmitted() throws Exception {
assertAddMandatoryValueAndNowSubmittedFromPending(
(project, projectUser) -> projectDetailsWorkflowHandler.projectManagerAdded(project, projectUser), PROJECT_MANAGER_ADDED);
}
/**
* Test that adding one of the mandatory values prior to being able to submit the project details works and keeps the
* state in pending until ready to submit
*/
private void assertAddMandatoryValue(BiFunction<Project, ProjectUser, Boolean> handlerMethod, ProjectDetailsEvent expectedEvent) {
Project project = newProject().build();
ProjectUser projectUser = newProjectUser().build();
ActivityState pendingState = new ActivityState(PROJECT_SETUP_PROJECT_DETAILS, State.PENDING);
ProjectDetailsProcess pendingProcess = new ProjectDetailsProcess(projectUser, project, pendingState);
when(activityStateRepositoryMock.findOneByActivityTypeAndState(PROJECT_SETUP_PROJECT_DETAILS, State.PENDING)).thenReturn(pendingState);
when(projectDetailsProcessRepositoryMock.findOneByTargetId(project.getId())).thenReturn(pendingProcess);
// now call the method under test
assertTrue(handlerMethod.apply(project, projectUser));
verify(activityStateRepositoryMock, atLeastOnce()).findOneByActivityTypeAndState(PROJECT_SETUP_PROJECT_DETAILS, State.PENDING);
verify(projectDetailsProcessRepositoryMock, atLeastOnce()).findOneByTargetId(project.getId());
verify(projectDetailsProcessRepositoryMock).save(
processExpectations(project.getId(), projectUser.getId(), ProjectDetailsState.PENDING, expectedEvent));
verifyNoMoreInteractionsWithMocks();
}
private void assertAddMandatoryValueAndNowSubmittedFromPending(BiFunction<Project, ProjectUser, Boolean> handlerFn, ProjectDetailsEvent expectedEvent) {
assertAddMandatoryValueAndNowSubmitted(ProjectDetailsState.PENDING, handlerFn, expectedEvent);
}
/**
* This asserts that triggering the given handler method with a fully filled in Project will move the process into
* Submitted state because all the mandatory values are now provided
*/
private void assertAddMandatoryValueAndNowSubmitted(ProjectDetailsState originalState, BiFunction<Project, ProjectUser, Boolean> handlerFn, ProjectDetailsEvent expectedEvent) {
List<Organisation> partnerOrgs = newOrganisation().build(2);
List<ProjectUser> financeContacts = newProjectUser().
withOrganisation(partnerOrgs.get(0), partnerOrgs.get(1)).
withRole(PROJECT_FINANCE_CONTACT).
build(2);
ProjectUser projectManager = newProjectUser().
withOrganisation(partnerOrgs.get(0)).
withRole(PROJECT_MANAGER).
build();
Project project = newProject().
withTargetStartDate(LocalDate.of(2016, 11, 01)).
withProjectUsers(combineLists(projectManager, financeContacts)).
withAddress(newAddress().build()).
build();
ProjectUser projectUser = newProjectUser().build();
ActivityState originalActivityState = new ActivityState(PROJECT_SETUP_PROJECT_DETAILS, originalState.getBackingState());
ProjectDetailsProcess originalProcess = new ProjectDetailsProcess(projectUser, project, originalActivityState);
ProjectDetailsProcess updatedProcess = new ProjectDetailsProcess(projectUser, project, originalActivityState);
ActivityState submittedState = new ActivityState(PROJECT_SETUP_PROJECT_DETAILS, State.SUBMITTED);
when(activityStateRepositoryMock.findOneByActivityTypeAndState(PROJECT_SETUP_PROJECT_DETAILS, State.SUBMITTED)).thenReturn(submittedState);
when(projectDetailsProcessRepositoryMock.findOneByTargetId(project.getId())).thenReturn(originalProcess);
when(projectDetailsProcessRepositoryMock.findOneByTargetId(project.getId())).thenReturn(updatedProcess);
// now call the method under test
assertTrue(handlerFn.apply(project, projectUser));
verify(activityStateRepositoryMock, atLeastOnce()).findOneByActivityTypeAndState(PROJECT_SETUP_PROJECT_DETAILS, State.SUBMITTED);
verify(projectDetailsProcessRepositoryMock, atLeastOnce()).findOneByTargetId(project.getId());
verify(projectDetailsProcessRepositoryMock).save(processExpectations(project.getId(), projectUser.getId(), ProjectDetailsState.SUBMITTED, expectedEvent));
verifyNoMoreInteractionsWithMocks();
}
private ProjectDetailsProcess processExpectations(Long expectedProjectId, Long expectedProjectUserId, ProjectDetailsState expectedState, ProjectDetailsEvent expectedEvent) {
return createLambdaMatcher(process -> {
assertProcessState(expectedProjectId, expectedProjectUserId, expectedState, expectedEvent, process);
});
}
private void assertProcessState(Long expectedProjectId, Long expectedProjectUserId, ProjectDetailsState expectedState, ProjectDetailsEvent expectedEvent, ProjectDetailsProcess process) {
assertEquals(expectedProjectId, process.getTarget().getId());
assertEquals(expectedProjectUserId, process.getParticipant().getId());
assertEquals(expectedState, process.getActivityState());
assertEquals(expectedEvent.getType(), process.getProcessEvent());
}
@Override
protected Class getBaseActionType() {
return BaseProjectDetailsAction.class;
}
@Override
protected Class<ProjectDetailsWorkflowHandler> getWorkflowHandlerType() {
return ProjectDetailsWorkflowHandler.class;
}
@Override
protected Class<ProjectDetailsProcessRepository> getProcessRepositoryType() {
return ProjectDetailsProcessRepository.class;
}
} |
package io.getlime.security.powerauth.lib.webflow.authentication.service;
import io.getlime.core.rest.model.base.response.ObjectResponse;
import io.getlime.powerauth.soap.ActivationStatus;
import io.getlime.powerauth.soap.GetActivationListForUserResponse;
import io.getlime.security.powerauth.lib.nextstep.client.NextStepClient;
import io.getlime.security.powerauth.lib.nextstep.client.NextStepServiceException;
import io.getlime.security.powerauth.lib.nextstep.model.entity.AuthMethodDetail;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthMethod;
import io.getlime.security.powerauth.lib.nextstep.model.response.GetAuthMethodsResponse;
import io.getlime.security.powerauth.soap.spring.client.PowerAuthServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Service for getting information about current availability of authentication methods.
*
* @author Roman Strobl, roman.strobl@lime-company.eu
*/
@Service
public class AuthMethodAvailabilityService {
private final NextStepClient nextStepClient;
private final PowerAuthServiceClient powerAuthServiceClient;
@Autowired
public AuthMethodAvailabilityService(NextStepClient nextStepClient, PowerAuthServiceClient powerAuthServiceClient) {
this.nextStepClient = nextStepClient;
this.powerAuthServiceClient = powerAuthServiceClient;
}
/**
* Returns whether authentication method is currently available.
*
* @param authMethod Authentication method.
* @param userId User ID.
* @param operationId Operation ID.
* @return Whether authentication method is available.
*/
public boolean isAuthMethodEnabled(AuthMethod authMethod, String userId, String operationId) {
try {
ObjectResponse<GetAuthMethodsResponse> response = nextStepClient.getAuthMethodsEnabledForUser(userId);
List<AuthMethodDetail> enabledAuthMethods = response.getResponseObject().getAuthMethods();
for (AuthMethodDetail authMethodDetail: enabledAuthMethods) {
if (authMethodDetail.getAuthMethod() == authMethod) {
// AuthMethod POWERAUTH_TOKEN requires special logic - activation could be BLOCKED at any time
if (authMethod != AuthMethod.POWERAUTH_TOKEN) {
return true;
} else {
return isMobileTokenAuthMethodAvailable(userId, operationId);
}
}
}
return false;
} catch (NextStepServiceException e) {
return false;
}
}
/**
* Returns whether Mobile Token authentication method is currently available by querying the PowerAuth backend for ACTIVE activations.
* @param userId User ID.
* @param operationId Operation ID.
* @return Whether Mobile Token authentication method is available.
*/
private boolean isMobileTokenAuthMethodAvailable(String userId, String operationId) {
// check whether user has an ACTIVE activation
List<GetActivationListForUserResponse.Activations> allActivations = powerAuthServiceClient.getActivationListForUser(userId);
for (GetActivationListForUserResponse.Activations activation: allActivations) {
if (activation.getActivationStatus() == ActivationStatus.ACTIVE) {
// user has an active activation - method can be used
// TODO - filter activations based on applicationId, ACTIVE activation may come from another application, see #122
return true;
}
}
return false;
}
} |
package scalac.transformer.matching;
import scalac.ast.*;
import scalac.util.*;
import scalac.symtab.*;
import java.util.*;
public class TestRegTraverser extends Traverser {
boolean result = false;
Set variables = new HashSet();
public void traverse(Tree tree) {
if (!result)
switch (tree) {
case Alternative(Tree[] ts):
result = true;
break;
case Bind(_, Tree pat):
variables.add(tree.symbol());
traverse(pat);
break;
case Ident(_):
if (variables.contains(tree.symbol()))
result = true;
break;
default:
super.traverse( tree );
}
}
public static boolean apply(Tree t) {
TestRegTraverser trt = new TestRegTraverser();
trt.traverse(t);
//System.err.println("TestRegTraverser says "+t+" -> "+trt.result);
return trt.result;
}
} |
package com.github.petrovich4j;
public class Petrovich {
private final RuleSet firstNameRules;
private final RuleSet lastNameRules;
private final RuleSet patronymicNameRules;
public Petrovich() {
this(Library.FIRST_NAME_RULES, Library.LAST_NAME_RULES, Library.PATRONYMIC_NAME_RULES);
}
public Petrovich(RuleSet firstNameRules, RuleSet lastNameRules, RuleSet patronymicNameRules) {
if (firstNameRules == null || lastNameRules == null || patronymicNameRules == null) {
throw new IllegalArgumentException("Rule set is null! First:" + firstNameRules + ", last:" + lastNameRules + ", patronymic: " + patronymicNameRules);
}
this.firstNameRules = firstNameRules;
this.lastNameRules = lastNameRules;
this.patronymicNameRules = patronymicNameRules;
}
public String say(String name, NameType type, Gender gender, Case cas) {
if (name == null || name.isEmpty()) { // do not force caller to check every name it asks.
return null;
}
if (type == null || gender == null || cas == null) { // configuration parameters must always be set up correctly.
throw new IllegalArgumentException("Not all required parameters are set! Type: " + type + ", gender:" + gender + ", case: " + cas);
}
RuleSet rules = type == NameType.FirstName ? firstNameRules : type == NameType.LastName ? lastNameRules : patronymicNameRules;
Rule exceptionRule = findRule(rules.exceptions, gender, name, true);
Rule suffixRule = findRule(rules.suffixes, gender, name, true);
Rule rule;
if (exceptionRule != null && exceptionRule.gender == gender) {
rule = exceptionRule;
} else if (suffixRule != null && suffixRule.gender == gender) {
rule = suffixRule;
} else {
rule = exceptionRule != null ? exceptionRule : suffixRule;
}
return rule == null ? name : applyMod(rule.mods[cas.modIdx], name);
}
public Gender resolve(String name, NameType type, Gender defaultValue) {
if (name == null || name.isEmpty()) {
return defaultValue;
}
if (type == null) {
throw new IllegalArgumentException("Not all required parameters are set! Type: " + type + ", gender:" + gender + ", case: " + cas);
}
RuleSet rules = type == NameType.FirstName ? firstNameRules : type == NameType.LastName ? lastNameRules : patronymicNameRules;
Rule exceptionRule = findRule(rules.exceptions, gender, name, false);
Rule suffixRule = findRule(rules.suffixes, gender, name, false);
Rule rule;
if (exceptionRule != null) {
return defaulValue;
} else if (suffixRule != null) {
return rule.gender;
}
return defaultValue;
}
static String applyMod(String mod, String name) {
if (mod.equals(Library.KEEP_MOD)) {
return name;
}
String result = name;
if (mod.indexOf(Library.REMOVE_CHARACTER) >= 0) {
for (int i = 0; i < mod.length(); i++) {
if (mod.charAt(i) == Library.REMOVE_CHARACTER) {
result = result.substring(0, result.length() - 1);
} else {
result += mod.substring(i);
break;
}
}
} else {
result = name + mod;
}
return result;
}
static Rule findRule(Rule[] allRules, Gender gender, String name, boolean checkGender) {
if (allRules == null) {
return null;
}
String lcName = name.toLowerCase();
for (Rule rule : allRules) {
for (String test : rule.test) {
boolean fullMatch = test.charAt(0) == '^';
boolean nameMatched = fullMatch ? test.substring(1).equals(lcName) : lcName.endsWith(test);
if (nameMatched && (!checkGender || rule.gender == Gender.Both || rule.gender == gender)) {
return rule;
}
}
}
return null;
}
} |
package dk.statsbiblioteket.medieplatform.autonomous.iterator.filesystem.transforming;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.DelegatingTreeIterator;
import dk.statsbiblioteket.util.Pair;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.AbstractFileFilter;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* This is the transforming iterator for filesystems. It allows one to iterate over a tree structure on the file system
* but having it transformed inline to a format that is suitable to ingest into doms.
*
* The transformations are
*
* 1. All data files (ie. the ones matched by the dataFilePattern) will be made into special folders. The contents
* of the datafile will reside in a virtual file called contents in that folder
* 2. Prefix grouping. If a folder contains a number of files with a common prefix, these will be grouped into a
* virtual
* folder, named as the prefix. This only happens if there are more than one common prefix.
* 2b. If only one of the groups contain no datafiles, this group will be cancelled, and the files will reside in the
* real folder.
*
* There will be no virtual folders inside virtual folders.
*/
public class TransformingIteratorForFileSystems extends CommonTransformingIterator {
protected List<DelegatingTreeIterator> virtualChildren;
/**
* Create the transforming Iterator for file systems
*
* @param id The root folder
* @param groupingPattern the grouping regular expression, ie. the char used as separator between prefix and
* postfix.
* Should be "\\."
* @param dataFilePattern a regular expression that should match the names of all datafiles
* @param checksumPostfix this is the postfix for the checksum files. Note, THIS IS NOT A PATTERN
*/
public TransformingIteratorForFileSystems(File id, String groupingPattern, String dataFilePattern,
String checksumPostfix) {
this(id, id.getParentFile(), groupingPattern, dataFilePattern, checksumPostfix);
}
/**
* Create the transforming Iterator for file systems
*
* @param id The root folder
* @param groupingChar the grouping regular expression, ie. the char used as separator between prefix and
* postfix.
* Should be "\\."
* @param dataFilePattern a regular expression that should match the names of all datafiles
*/
protected TransformingIteratorForFileSystems(File id, File prefix, String groupingChar, String dataFilePattern,
String checksumPostfix) {
super(id, prefix, dataFilePattern, checksumPostfix, groupingChar);
virtualChildren = new ArrayList<>();
}
@Override
protected Iterator<DelegatingTreeIterator> initializeChildrenIterator() {
File[] children = id.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);
ArrayList<DelegatingTreeIterator> result = new ArrayList<>(children.length + virtualChildren.size());
for (File child : children) {
result.add(
new TransformingIteratorForFileSystems(
child, getBatchFolder(), getGroupingChar(), getDataFilePattern(), getChecksumPostfix()));
}
for (DelegatingTreeIterator virtualChild : virtualChildren) {
result.add(virtualChild);
}
return result.iterator();
}
@Override
protected Iterator<File> initilizeAttributeIterator() throws IOException {
if (!(id.isDirectory() && id.canRead())) {
throw new IOException("Failed to read directory '" + id.getAbsolutePath() + "'");
}
Collection<File> attributes = FileUtils.listFiles(
id, new AbstractFileFilter() {
@Override
public boolean accept(File file) {
boolean isFile = file.isFile();
boolean isNotChecksum = !file.getName()
.endsWith(getChecksumPostfix());
boolean isNotTransferComplete = !file.getName()
.equals("transfer_complete");
boolean isNotTransfer_acknowledged = !file.getName()
.equals("transfer_acknowledged");
return isFile && isNotChecksum && isNotTransferComplete && isNotTransfer_acknowledged;
}
}, null);
//If there is any datafiles, we group by prefix. If there are no datafiles, we expect the structure to be flat
if (containsDatafiles(attributes)) {
Map<String, List<File>> groupedByPrefix = groupByPrefix(attributes);
Pair<String, List<File>> noDataGroup = getUniqueNoDataFilesGroup(groupedByPrefix);
if (noDataGroup != null) {
attributes = noDataGroup.getRight();
}
for (String prefix : groupedByPrefix.keySet()) {
if (noDataGroup != null && prefix.equals(noDataGroup.getLeft())) {
continue;
}
List<File> group = groupedByPrefix.get(prefix);
virtualChildren.add(
new VirtualIteratorForFileSystems(
id,
prefix,
getBatchFolder(),
getDataFilePattern(),
group,
getGroupingChar(),
getChecksumPostfix()));
attributes.removeAll(group);
}
}
return attributes.iterator();
}
/**
* group a collection of files according to their prefix
*
* @param files the files to group
*
* @return a map of prefixes to lists of files
* @see #getPrefix(java.io.File)
*/
private Map<String, List<File>> groupByPrefix(Collection<File> files) {
Map<String, List<File>> prefixToFile = new HashMap<>();
for (File file : files) {
String prefix = getPrefix(file);
List<File> fileList = prefixToFile.get(prefix);
if (fileList == null) {
fileList = new ArrayList<>();
}
fileList.add(file);
prefixToFile.put(prefix, fileList);
}
return prefixToFile;
}
} |
package com.haogrgr.test.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;
/**
* BigDecimal
*
* @author desheng.tu
* @date 2015612 2:17:23
*
*/
public final class ArithUtils {
/**
* return a + b + c
*/
public static BigDecimal add(BigDecimal a, BigDecimal b, BigDecimal... c) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
BigDecimal sum = a.add(b);
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
Objects.requireNonNull(c[i]);
sum = sum.add(c[i]);
}
}
return sum;
}
/**
* return a + b + c
*/
public static BigDecimal add(BigDecimal a, long b, long... c) {
Objects.requireNonNull(a);
BigDecimal sum = a.add(BigDecimal.valueOf(b));
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
sum = sum.add(BigDecimal.valueOf(c[i]));
}
}
return sum;
}
/**
* return a + b + c
*/
public static BigDecimal add(BigDecimal a, double b, double... c) {
Objects.requireNonNull(a);
BigDecimal sum = a.add(BigDecimal.valueOf(b));
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
sum = sum.add(BigDecimal.valueOf(c[i]));
}
}
return sum;
}
/**
* return a + b + c
*/
public static BigDecimal add(double a, double b, double... c) {
BigDecimal sum = BigDecimal.valueOf(a).add(BigDecimal.valueOf(b));
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
sum = sum.add(BigDecimal.valueOf(c[i]));
}
}
return sum;
}
/**
* return a + b + c, , 0
*/
public static BigDecimal addna(BigDecimal a, BigDecimal b, BigDecimal... c) {
a = a == null ? BigDecimal.ZERO : a;
b = b == null ? BigDecimal.ZERO : b;
BigDecimal sum = a.add(b);
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
if (c[i] != null)
sum = sum.add(c[i]);
}
}
return sum;
}
/**
* return a -b -c
*/
public static BigDecimal sub(BigDecimal a, BigDecimal b, BigDecimal... c) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
BigDecimal sub = a.subtract(b);
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
Objects.requireNonNull(c[i]);
sub = sub.subtract(c[i]);
}
}
return sub;
}
/**
* return a -b -c
*/
public static BigDecimal sub(BigDecimal a, long b, long... c) {
Objects.requireNonNull(a);
BigDecimal sub = a.subtract(BigDecimal.valueOf(b));
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
sub = sub.subtract(BigDecimal.valueOf(c[i]));
}
}
return sub;
}
/**
* return a -b -c
*/
public static BigDecimal sub(BigDecimal a, double b, double... c) {
Objects.requireNonNull(a);
BigDecimal sub = a.subtract(BigDecimal.valueOf(b));
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
sub = sub.subtract(BigDecimal.valueOf(c[i]));
}
}
return sub;
}
/**
* return a -b -c, , 0
*/
public static BigDecimal subna(BigDecimal a, BigDecimal b, BigDecimal... c) {
a = a == null ? BigDecimal.ZERO : a;
b = b == null ? BigDecimal.ZERO : b;
BigDecimal sub = a.subtract(b);
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
if (c[i] != null)
sub = sub.subtract(c[i]);
}
}
return sub;
}
/**
* return a * b * c
*/
public static BigDecimal mul(BigDecimal a, BigDecimal b, BigDecimal... c) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
BigDecimal mul = a.multiply(b);
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
Objects.requireNonNull(c[i]);
mul = mul.multiply(c[i]);
}
}
return mul;
}
/**
* return a * b * c
*/
public static BigDecimal mul(BigDecimal a, long b, long... c) {
Objects.requireNonNull(a);
BigDecimal mul = a.multiply(BigDecimal.valueOf(b));
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
mul = mul.multiply(BigDecimal.valueOf(c[i]));
}
}
return mul;
}
/**
* return a * b * c
*/
public static BigDecimal mul(BigDecimal a, double b, double... c) {
Objects.requireNonNull(a);
BigDecimal mul = a.multiply(BigDecimal.valueOf(b));
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
mul = mul.multiply(BigDecimal.valueOf(c[i]));
}
}
return mul;
}
/**
* return (a / b) / c
*/
public static BigDecimal div(BigDecimal a, BigDecimal b, BigDecimal... c) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
BigDecimal divide = a.divide(b);
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
Objects.requireNonNull(c[i]);
divide = divide.divide(c[i]);
}
}
return divide;
}
/**
* return (a / b) / c
*/
public static BigDecimal div(BigDecimal a, long b, long... c) {
Objects.requireNonNull(a);
BigDecimal divide = a.divide(BigDecimal.valueOf(b));
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
divide = divide.divide(BigDecimal.valueOf(c[i]));
}
}
return divide;
}
/**
* return (a / b) / c
*/
public static BigDecimal div(BigDecimal a, double b, double... c) {
Objects.requireNonNull(a);
BigDecimal divide = a.divide(BigDecimal.valueOf(b));
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
divide = divide.divide(BigDecimal.valueOf(c[i]));
}
}
return divide;
}
/**
* return a > b
*/
public static boolean gt(BigDecimal a, BigDecimal b) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
return a.compareTo(b) == 1;
}
/**
* return a > b
*/
public static boolean gt(BigDecimal a, long b) {
Objects.requireNonNull(a);
return a.compareTo(BigDecimal.valueOf(b)) == 1;
}
/**
* return a > b
*/
public static boolean gt(BigDecimal a, double b) {
Objects.requireNonNull(a);
return a.compareTo(BigDecimal.valueOf(b)) == 1;
}
/**
* return a >= b
*/
public static boolean gtOrEq(BigDecimal a, BigDecimal b) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
return a.compareTo(b) > -1;
}
/**
* return a >= b
*/
public static boolean gtOrEq(BigDecimal a, long b) {
Objects.requireNonNull(a);
return a.compareTo(BigDecimal.valueOf(b)) > -1;
}
/**
* return a >= b
*/
public static boolean gtOrEq(BigDecimal a, double b) {
Objects.requireNonNull(a);
return a.compareTo(BigDecimal.valueOf(b)) > -1;
}
/**
* return a < b
*/
public static boolean lt(BigDecimal a, BigDecimal b) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
return a.compareTo(b) == -1;
}
/**
* return a < b
*/
public static boolean lt(BigDecimal a, long b) {
Objects.requireNonNull(a);
return a.compareTo(BigDecimal.valueOf(b)) == -1;
}
/**
* return a < b
*/
public static boolean lt(BigDecimal a, double b) {
Objects.requireNonNull(a);
return a.compareTo(BigDecimal.valueOf(b)) == -1;
}
/**
* return a <= b
*/
public static boolean ltOrEq(BigDecimal a, BigDecimal b) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
return a.compareTo(b) < 1;
}
/**
* return a <= b
*/
public static boolean ltOrEq(BigDecimal a, long b) {
Objects.requireNonNull(a);
return a.compareTo(BigDecimal.valueOf(b)) < 1;
}
/**
* return a <= b
*/
public static boolean ltOrEq(BigDecimal a, double b) {
Objects.requireNonNull(a);
return a.compareTo(BigDecimal.valueOf(b)) < 1;
}
/**
* return a == b
*/
public static boolean eq(BigDecimal a, BigDecimal b, BigDecimal... c) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);
if (a.compareTo(b) != 0) {
return false;
}
if (c != null && c.length > 0) {
for (int i = 0; i < c.length; i++) {
Objects.requireNonNull(c[i]);
if (a.compareTo(c[i]) != 0)
return false;
}
}
return true;
}
/**
* return a == b
*/
public static boolean eq(BigDecimal a, long b) {
Objects.requireNonNull(a);
return a.compareTo(BigDecimal.valueOf(b)) == 0;
}
/**
* return a == b
*/
public static boolean eq(BigDecimal a, double b) {
Objects.requireNonNull(a);
return a.compareTo(BigDecimal.valueOf(b)) == 0;
}
public static BigDecimal halfUp(BigDecimal n) {
return n.setScale(2, RoundingMode.HALF_UP);
}
public static BigDecimal halfUp(double n) {
return BigDecimal.valueOf(n).setScale(2, RoundingMode.HALF_UP);
}
public static BigDecimal halfUp(BigDecimal n, int scale) {
return n.setScale(scale, RoundingMode.HALF_UP);
}
public static BigDecimal halfUp(double n, int scale) {
return BigDecimal.valueOf(n).setScale(scale, RoundingMode.HALF_UP);
}
public static String halfUpStr(BigDecimal n) {
return n.setScale(2, RoundingMode.HALF_UP).toString();
}
public static String halfUpStr(double n) {
return BigDecimal.valueOf(n).setScale(2, RoundingMode.HALF_UP).toString();
}
public static String halfUpStr(BigDecimal n, int scale) {
return n.setScale(scale, RoundingMode.HALF_UP).toString();
}
public static String halfUpStr(double n, int scale) {
return BigDecimal.valueOf(n).setScale(scale, RoundingMode.HALF_UP).toString();
}
public static BigDecimal max(BigDecimal... eles) {
if (eles == null || eles.length == 0) {
return null;
}
BigDecimal max = eles[0];
for (BigDecimal ele : eles) {
Objects.requireNonNull(ele);
if (gt(ele, max))
max = ele;
}
return max;
}
public static BigDecimal min(BigDecimal... eles) {
if (eles == null || eles.length == 0) {
return null;
}
BigDecimal min = eles[0];
for (BigDecimal ele : eles) {
Objects.requireNonNull(ele);
if (lt(ele, min))
min = ele;
}
return min;
}
public static BigDecimal transform(Number number) {
if (BigDecimal.class.isInstance(number)) {
return (BigDecimal) number;
}
if (Float.class.isInstance(number)) {
return BigDecimal.valueOf((Float) number);
}
if (Double.class.isInstance(number)) {
return BigDecimal.valueOf((Double) number);
}
if (Long.class.isInstance(number)) {
return BigDecimal.valueOf((Long) number);
}
if (Integer.class.isInstance(number)) {
return BigDecimal.valueOf((Integer) number);
}
if (Short.class.isInstance(number)) {
return BigDecimal.valueOf((Short) number);
}
if (Byte.class.isInstance(number)) {
return BigDecimal.valueOf((Byte) number);
}
throw new IllegalArgumentException(" : " + number);
}
} |
package org.xwiki.component.embed;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import javax.inject.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.component.annotation.ComponentAnnotationLoader;
import org.xwiki.component.annotation.DisposePriority;
import org.xwiki.component.descriptor.ComponentDependency;
import org.xwiki.component.descriptor.ComponentDescriptor;
import org.xwiki.component.descriptor.ComponentInstantiationStrategy;
import org.xwiki.component.descriptor.DefaultComponentDescriptor;
import org.xwiki.component.internal.RoleHint;
import org.xwiki.component.manager.ComponentEventManager;
import org.xwiki.component.manager.ComponentLifecycleException;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.manager.ComponentManagerInitializer;
import org.xwiki.component.manager.ComponentRepositoryException;
import org.xwiki.component.manager.NamespacedComponentManager;
import org.xwiki.component.phase.Disposable;
import org.xwiki.component.util.ReflectionUtils;
/**
* Simple implementation of {@link ComponentManager} to be used when using some XWiki modules standalone.
*
* @version $Id$
* @since 2.0M1
*/
public class EmbeddableComponentManager implements NamespacedComponentManager, Disposable
{
/**
* Logger to use to log shutdown information (opposite of initialization).
*/
private static final Logger SHUTDOWN_LOGGER = LoggerFactory.getLogger("org.xwiki.shutdown");
/**
* @see #getNamespace()
*/
private String namespace;
private ComponentEventManager eventManager;
/**
* Used as fallback for lookup methods.
*/
private ComponentManager parent;
private static class ComponentEntry<R>
{
/**
* Descriptor of the component.
*/
public final ComponentDescriptor<R> descriptor;
public volatile R instance;
/**
* Flag used when computing the disposal order.
*/
public boolean disposing = false;
public ComponentEntry(ComponentDescriptor<R> descriptor, R instance)
{
this.descriptor = descriptor;
this.instance = instance;
}
}
private Map<Type, Map<String, ComponentEntry<?>>> componentEntries = new ConcurrentHashMap<>();
private Logger logger = LoggerFactory.getLogger(EmbeddableComponentManager.class);
/**
* Finds all lifecycle handlers to use when instantiating a Component.
*/
private ServiceLoader<LifecycleHandler> lifecycleHandlers = ServiceLoader.load(LifecycleHandler.class);
public EmbeddableComponentManager()
{
registerThis();
}
/**
* @param namespace the namespace associated with this component manager
* @since 6.4M2
*/
public EmbeddableComponentManager(String namespace)
{
registerThis();
this.namespace = namespace;
}
@Override
public String getNamespace()
{
return this.namespace;
}
/**
* Allow to lookup the this as default {@link ComponentManager} implementation.
*/
private void registerThis()
{
DefaultComponentDescriptor<ComponentManager> cd = new DefaultComponentDescriptor<>();
cd.setRoleType(ComponentManager.class);
registerComponent(cd, this);
}
/**
* Load all component annotations and register them as components.
*
* @param classLoader the class loader to use to look for component definitions
*/
public void initialize(ClassLoader classLoader)
{
ComponentAnnotationLoader loader = new ComponentAnnotationLoader();
loader.initialize(this, classLoader);
// Extension point to allow component to manipulate ComponentManager initialized state.
try {
List<ComponentManagerInitializer> initializers = this.getInstanceList(ComponentManagerInitializer.class);
for (ComponentManagerInitializer initializer : initializers) {
initializer.initialize(this);
}
} catch (ComponentLookupException e) {
// Should never happen
this.logger.error("Failed to lookup ComponentManagerInitializer components", e);
}
}
@Override
public boolean hasComponent(Type role)
{
return hasComponent(role, null);
}
@Override
public boolean hasComponent(Type roleType, String roleHint)
{
if (getComponentEntry(roleType, roleHint) != null) {
return true;
}
return getParent() != null ? getParent().hasComponent(roleType, roleHint) : false;
}
@Override
public <T> T getInstance(Type roleType) throws ComponentLookupException
{
return getInstance(roleType, null);
}
@Override
public <T> T getInstance(Type roleType, String roleHint) throws ComponentLookupException
{
T instance;
ComponentEntry<T> componentEntry = (ComponentEntry<T>) getComponentEntry(roleType, roleHint);
if (componentEntry != null) {
try {
instance = getComponentInstance(componentEntry);
} catch (Throwable e) {
throw new ComponentLookupException(
String.format("Failed to lookup component [%s] identified by type [%s] and hint [%s]",
componentEntry.descriptor.getImplementation().getName(), roleType, roleHint),
e);
}
} else {
if (getParent() != null) {
instance = getParent().getInstance(roleType, roleHint);
} else {
throw new ComponentLookupException(
"Can't find descriptor for the component with type [" + roleType + "] and hint [" + roleHint + "]");
}
}
return instance;
}
@Override
public <T> List<T> getInstanceList(Type role) throws ComponentLookupException
{
// Reuse getInstanceMap to make sure to not return components from parent Component Manager overridden by this
// Component Manager
Map<String, T> objects = getInstanceMap(role);
return objects.isEmpty() ? Collections.<T>emptyList() : new ArrayList<>(objects.values());
}
@Override
@SuppressWarnings("unchecked")
public <T> Map<String, T> getInstanceMap(Type roleType) throws ComponentLookupException
{
Map<String, T> components = new HashMap<>();
Map<String, ComponentEntry<?>> entries = this.componentEntries.get(roleType);
// Add local components
if (entries != null) {
for (Map.Entry<String, ComponentEntry<?>> entry : entries.entrySet()) {
try {
components.put(entry.getKey(), getComponentInstance((ComponentEntry<T>) entry.getValue()));
} catch (Exception e) {
throw new ComponentLookupException(
"Failed to lookup component with type [" + roleType + "] and hint [" + entry.getKey() + "]", e);
}
}
}
// Add parent components
if (getParent() != null) {
// If the hint already exists in the children Component Manager then don't add the one from the parent.
for (Map.Entry<String, T> entry : getParent().<T>getInstanceMap(roleType).entrySet()) {
if (!components.containsKey(entry.getKey())) {
components.put(entry.getKey(), entry.getValue());
}
}
}
return components;
}
private ComponentEntry<?> getComponentEntry(Type role, String hint)
{
Map<String, ComponentEntry<?>> entries = this.componentEntries.get(role);
if (entries != null) {
return entries.get(hint != null ? hint : RoleHint.DEFAULT_HINT);
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public <T> ComponentDescriptor<T> getComponentDescriptor(Type role, String hint)
{
ComponentDescriptor<T> result = null;
ComponentEntry<?> componentEntry = getComponentEntry(role, hint);
if (componentEntry == null) {
// Check in parent!
if (getParent() != null) {
result = getParent().getComponentDescriptor(role, hint);
}
} else {
result = (ComponentDescriptor<T>) componentEntry.descriptor;
}
return result;
}
@Override
@SuppressWarnings("unchecked")
public <T> List<ComponentDescriptor<T>> getComponentDescriptorList(Type role)
{
Map<String, ComponentDescriptor<T>> descriptors = new HashMap<>();
// Add local descriptors
Map<String, ComponentEntry<?>> enries = this.componentEntries.get(role);
if (enries != null) {
for (Map.Entry<String, ComponentEntry<?>> entry : enries.entrySet()) {
descriptors.put(entry.getKey(), (ComponentDescriptor<T>) entry.getValue().descriptor);
}
}
// Add parent descriptors
if (getParent() != null) {
List<ComponentDescriptor<T>> parentDescriptors = getParent().getComponentDescriptorList(role);
for (ComponentDescriptor<T> parentDescriptor : parentDescriptors) {
// If the hint already exists in the children Component Manager then don't add the one from the parent.
if (!descriptors.containsKey(parentDescriptor.getRoleHint())) {
descriptors.put(parentDescriptor.getRoleHint(), parentDescriptor);
}
}
}
return new ArrayList<>(descriptors.values());
}
@Override
public ComponentEventManager getComponentEventManager()
{
return this.eventManager;
}
@Override
public void setComponentEventManager(ComponentEventManager eventManager)
{
this.eventManager = eventManager;
}
@Override
public ComponentManager getParent()
{
return this.parent;
}
@Override
public void setParent(ComponentManager parentComponentManager)
{
this.parent = parentComponentManager;
}
private <T> T createInstance(ComponentDescriptor<T> descriptor) throws Exception
{
T instance = descriptor.getImplementation().newInstance();
// Set each dependency
for (ComponentDependency<?> dependency : descriptor.getComponentDependencies()) {
// TODO: Handle dependency cycles
// Handle different field types
Object fieldValue = getDependencyInstance(descriptor, instance, dependency);
// Set the field by introspection
if (fieldValue != null) {
ReflectionUtils.setFieldValue(instance, dependency.getName(), fieldValue);
}
}
// Call Lifecycle Handlers
for (LifecycleHandler lifecycleHandler : this.lifecycleHandlers) {
lifecycleHandler.handle(instance, descriptor, this);
}
return instance;
}
protected Object getDependencyInstance(ComponentDescriptor<?> descriptor, Object parentInstance,
ComponentDependency<?> dependency) throws ComponentLookupException
{
// TODO: Handle dependency cycles
// Handle different field types
Object fieldValue;
// Step 1: Verify if there's a Provider registered for the field type
// - A Provider is a component like any other (except it cannot have a field produced by itself!)
// - A Provider must implement the JSR330 Producer interface
// Step 2: Handle Logger injection.
// Step 3: No producer found, handle scalar and collection types by looking up standard component
// implementations.
Class<?> dependencyRoleClass = ReflectionUtils.getTypeClass(dependency.getRoleType());
if (dependencyRoleClass.isAssignableFrom(Logger.class)) {
fieldValue = createLogger(parentInstance.getClass());
} else if (dependencyRoleClass.isAssignableFrom(List.class)) {
fieldValue = getInstanceList(ReflectionUtils.getLastTypeGenericArgument(dependency.getRoleType()));
} else if (dependencyRoleClass.isAssignableFrom(Map.class)) {
fieldValue = getInstanceMap(ReflectionUtils.getLastTypeGenericArgument(dependency.getRoleType()));
} else if (dependencyRoleClass.isAssignableFrom(Provider.class)) {
// Check if there's a Provider registered for the type
if (hasComponent(dependency.getRoleType(), dependency.getRoleHint())) {
fieldValue = getInstance(dependency.getRoleType(), dependency.getRoleHint());
} else {
fieldValue = createGenericProvider(descriptor, dependency);
}
} else if (dependencyRoleClass.isAssignableFrom(ComponentDescriptor.class)) {
fieldValue = new DefaultComponentDescriptor<>(descriptor);
} else {
fieldValue = getInstance(dependency.getRoleType(), dependency.getRoleHint());
}
return fieldValue;
}
protected Provider<?> createGenericProvider(ComponentDescriptor<?> descriptor, ComponentDependency<?> dependency)
{
return new GenericProvider<>(this, new RoleHint<>(
ReflectionUtils.getLastTypeGenericArgument(dependency.getRoleType()), dependency.getRoleHint()));
}
/**
* Create a Logger instance to inject.
*/
protected Object createLogger(Class<?> instanceClass)
{
return LoggerFactory.getLogger(instanceClass);
}
/**
* @deprecated use {@link #getInstance(Type, String)} instead
*/
@Deprecated
protected <T> T getComponentInstance(RoleHint<T> roleHint) throws ComponentLookupException
{
return getInstance(roleHint.getRoleType(), roleHint.getHint());
}
private <T> T getComponentInstance(ComponentEntry<T> componentEntry) throws Exception
{
T instance;
ComponentDescriptor<T> descriptor = componentEntry.descriptor;
if (descriptor.getInstantiationStrategy() == ComponentInstantiationStrategy.SINGLETON) {
if (componentEntry.instance != null) {
// If the instance exists return it
instance = componentEntry.instance;
} else {
synchronized (componentEntry) {
// Re-check in case it has been created while we were waiting
if (componentEntry.instance != null) {
instance = componentEntry.instance;
} else {
componentEntry.instance = createInstance(descriptor);
instance = componentEntry.instance;
}
}
}
} else {
instance = createInstance(descriptor);
}
return instance;
}
// Add
@Override
public <T> void registerComponent(ComponentDescriptor<T> componentDescriptor) throws ComponentRepositoryException
{
registerComponent(componentDescriptor, null);
}
@Override
public <T> void registerComponent(ComponentDescriptor<T> componentDescriptor, T componentInstance)
{
// Remove any existing component associated to the provided roleHint
removeComponentWithoutException(componentDescriptor.getRoleType(), componentDescriptor.getRoleHint());
// Register new component
addComponent(new DefaultComponentDescriptor<T>(componentDescriptor), componentInstance);
}
private <T> void addComponent(ComponentDescriptor<T> descriptor, T instance)
{
ComponentEntry<T> componentEntry = new ComponentEntry<>(descriptor, instance);
// Register new component
Map<String, ComponentEntry<?>> entries = this.componentEntries.get(descriptor.getRoleType());
if (entries == null) {
entries = new ConcurrentHashMap<>();
this.componentEntries.put(descriptor.getRoleType(), entries);
}
entries.put(descriptor.getRoleHint(), componentEntry);
// Send event about component registration
if (this.eventManager != null) {
this.eventManager.notifyComponentRegistered(descriptor, this);
}
}
// Remove
@Override
public void unregisterComponent(Type role, String hint)
{
removeComponentWithoutException(role, hint);
}
@Override
public void unregisterComponent(ComponentDescriptor<?> componentDescriptor)
{
if (Objects.equals(getComponentDescriptor(componentDescriptor.getRoleType(), componentDescriptor.getRoleHint()),
componentDescriptor)) {
unregisterComponent(componentDescriptor.getRoleType(), componentDescriptor.getRoleHint());
}
}
@Override
public void release(Object component) throws ComponentLifecycleException
{
// First find the descriptor matching the passed component
ComponentEntry<?> componentEntry = null;
for (Map<String, ComponentEntry<?>> entries : this.componentEntries.values()) {
for (ComponentEntry<?> entry : entries.values()) {
if (entry.instance == component) {
componentEntry = entry;
break;
}
}
}
// Note that we're not removing inside the for loop above since it would cause a Concurrent
// exception since we'd modify the map accessed by the iterator.
if (componentEntry != null) {
// Release the entry
releaseInstance(componentEntry);
// Warn others about it:
// - fire an unregistration event, to tell the world that this reference is now dead
// - fire a registration event, to tell the world that it could get a new reference for this component
// now
// We need to do this since code holding a reference on the released component may need to know it's
// been removed and thus discard its own reference to that component and look it up again.
// Another solution would be to introduce a new event for Component creation/destruction (right now
// we only send events for Component registration/unregistration).
if (this.eventManager != null) {
this.eventManager.notifyComponentUnregistered(componentEntry.descriptor, this);
this.eventManager.notifyComponentRegistered(componentEntry.descriptor, this);
}
}
}
private void releaseInstance(ComponentEntry<?> componentEntry) throws ComponentLifecycleException
{
// Make sure the singleton component instance can't be "lost" (impossible to dispose because returned but not
// stored).
synchronized (componentEntry) {
Object instance = componentEntry.instance;
// Give a chance to the component to clean up
if (instance instanceof Disposable) {
((Disposable) instance).dispose();
}
componentEntry.instance = null;
}
}
private void releaseComponentEntry(ComponentEntry<?> componentEntry) throws ComponentLifecycleException
{
// clean existing instance
releaseInstance(componentEntry);
}
private void removeComponent(Type role, String hint) throws ComponentLifecycleException
{
// Make sure to remove the entry from the map before destroying it to reduce at the minimum the risk of
// lookupping something invalid
Map<String, ComponentEntry<?>> entries = this.componentEntries.get(role);
if (entries != null) {
ComponentEntry<?> componentEntry = entries.remove(hint != null ? hint : RoleHint.DEFAULT_HINT);
if (componentEntry != null) {
ComponentDescriptor<?> oldDescriptor = componentEntry.descriptor;
// We don't want the component manager to dispose itself just because it's not registered as component*
// anymore
if (componentEntry.instance != this) {
// clean any resource associated to the component instance and descriptor
releaseComponentEntry(componentEntry);
}
// Send event about component unregistration
if (this.eventManager != null && oldDescriptor != null) {
this.eventManager.notifyComponentUnregistered(oldDescriptor, this);
}
}
}
}
/**
* Note: This method shouldn't exist but register/unregister methods should throw a
* {@link ComponentLifecycleException} but that would break backward compatibility to add it.
*/
private void removeComponentWithoutException(Type role, String hint)
{
try {
removeComponent(role, hint);
} catch (Exception e) {
this.logger.warn("Instance released but disposal failed. Some resources may not have been released.", e);
}
}
private void addForDisposalReversedOrder(ComponentEntry<?> componentEntry, List<RoleHint<?>> keys)
{
if (!componentEntry.disposing) {
componentEntry.disposing = true;
ComponentDescriptor<?> descriptor = componentEntry.descriptor;
for (ComponentDependency<?> dependency : descriptor.getComponentDependencies()) {
ComponentEntry<?> dependencyEntry = getComponentEntry(dependency.getRoleType(), dependency.getRoleHint());
if (dependencyEntry != null) {
addForDisposalReversedOrder(dependencyEntry, keys);
}
}
keys.add(new RoleHint<>(descriptor.getRoleType(), descriptor.getRoleHint()));
}
}
@Override
public void dispose()
{
List<RoleHint<?>> keys = new ArrayList<>(this.componentEntries.size() * 2);
// Add components based on dependencies relations.
for (Map<String, ComponentEntry<?>> entries : this.componentEntries.values()) {
for (ComponentEntry<?> entry : entries.values()) {
addForDisposalReversedOrder(entry, keys);
}
}
Collections.reverse(keys);
// Exclude this component
RoleHint<ComponentManager> cmRoleHint = new RoleHint<>(ComponentManager.class);
ComponentEntry<?> cmEntry = getComponentEntry(cmRoleHint.getRoleType(), cmRoleHint.getHint());
if (cmEntry != null && cmEntry.instance == this) {
cmEntry.disposing = false;
keys.remove(cmRoleHint);
}
// Sort component by DisposePriority
Collections.sort(keys, new Comparator<RoleHint<?>>()
{
@Override
public int compare(RoleHint<?> rh1, RoleHint<?> rh2)
{
return getPriority(rh1) - getPriority(rh2);
}
private int getPriority(RoleHint<?> rh)
{
Object instance = getComponentEntry(rh.getRoleType(), rh.getHint()).instance;
if (instance == null) {
// The component has not been instantiated yet. We don't need to dispose it in this case... :)
// Return the default priority since it doesn't matter.
return DisposePriority.DEFAULT_PRIORITY;
} else {
DisposePriority priorityAnnotation = instance.getClass().getAnnotation(DisposePriority.class);
return (priorityAnnotation == null) ? DisposePriority.DEFAULT_PRIORITY : priorityAnnotation.value();
}
}
});
// Dispose old components
for (RoleHint<?> key : keys) {
ComponentEntry<?> componentEntry = getComponentEntry(key.getRoleType(), key.getHint());
synchronized (componentEntry) {
Object instance = componentEntry.instance;
// Protection to prevent infinite recursion in case a component implementation points to this
// instance.
if (instance instanceof Disposable && componentEntry.instance != this) {
try {
SHUTDOWN_LOGGER.debug("Disposing component [{}]...", instance.getClass().getName());
((Disposable) instance).dispose();
SHUTDOWN_LOGGER.debug("Component [{}] has been disposed", instance.getClass().getName());
} catch (ComponentLifecycleException e) {
this.logger.error("Failed to dispose component with role type [{}] and role hint [{}]",
componentEntry.descriptor.getRoleType(), componentEntry.descriptor.getRoleHint(), e);
}
}
}
}
// Remove disposed components from the map. Doing it in two steps to give as many chances as possible to the
// components that have to use a component already disposed (usually because it dynamically requires it and
// there is no way for the ComponentManager to know that dependency).
for (RoleHint<?> key : keys) {
this.componentEntries.get(key.getRoleType()).remove(key.getHint());
}
}
// Deprecated
@Override
@Deprecated
public <T> List<ComponentDescriptor<T>> getComponentDescriptorList(Class<T> role)
{
return getComponentDescriptorList((Type) role);
}
} |
package com.hpe.caf.api.worker;
import com.hpe.caf.api.HealthReporter;
import java.io.InputStream;
import java.io.OutputStream;
/**
* A representation of a generic data store, for reading and writing data
* typically used by workers in the course of their computation.
*/
public abstract class DataStore implements HealthReporter
{
/**
* Provide a stream to Get data by reference
* @param reference the arbitrary string reference to a piece of data
* @return the raw data referred to
* @throws DataStoreException if the data store cannot service the request
*/
public abstract InputStream getInputStream(final String reference)
throws DataStoreException;
/**
* Get the byte size of some data in the DataStore by reference
* @param reference the arbitrary string reference to a piece of data
* @return the size in bytes of the data being referred to
* @throws DataStoreException if the data store cannot service the requeste
*/
public abstract long getDataSize(final String reference)
throws DataStoreException;
/**
* @return metrics for the data store
*/
public abstract DataStoreMetricsReporter getMetrics();
/**
* Provide a stream to Store data by reference
* @param reference the arbitrary string reference to store the data by
* @return reference to the stored data, which can be used to retrieve
* @throws DataStoreException if the data store cannot service the request
*/
public abstract OutputStream getOutputStream(final String reference)
throws DataStoreException;
/**
* Perform necessary shut down operations.
*/
public abstract void shutdown();
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.services.KalturaAccessControlProfileService;
import com.kaltura.client.services.KalturaAccessControlService;
import com.kaltura.client.services.KalturaAdminUserService;
import com.kaltura.client.services.KalturaAnalyticsService;
import com.kaltura.client.services.KalturaAppTokenService;
import com.kaltura.client.services.KalturaBaseEntryService;
import com.kaltura.client.services.KalturaBulkUploadService;
import com.kaltura.client.services.KalturaCategoryEntryService;
import com.kaltura.client.services.KalturaCategoryService;
import com.kaltura.client.services.KalturaCategoryUserService;
import com.kaltura.client.services.KalturaConversionProfileAssetParamsService;
import com.kaltura.client.services.KalturaConversionProfileService;
import com.kaltura.client.services.KalturaDataService;
import com.kaltura.client.services.KalturaDeliveryProfileService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
import com.kaltura.client.services.KalturaEntryServerNodeService;
import com.kaltura.client.services.KalturaFileAssetService;
import com.kaltura.client.services.KalturaFlavorAssetService;
import com.kaltura.client.services.KalturaFlavorParamsOutputService;
import com.kaltura.client.services.KalturaFlavorParamsService;
import com.kaltura.client.services.KalturaGroupUserService;
import com.kaltura.client.services.KalturaLiveChannelSegmentService;
import com.kaltura.client.services.KalturaLiveChannelService;
import com.kaltura.client.services.KalturaLiveReportsService;
import com.kaltura.client.services.KalturaLiveStatsService;
import com.kaltura.client.services.KalturaLiveStreamService;
import com.kaltura.client.services.KalturaMediaInfoService;
import com.kaltura.client.services.KalturaMediaService;
import com.kaltura.client.services.KalturaMixingService;
import com.kaltura.client.services.KalturaNotificationService;
import com.kaltura.client.services.KalturaPartnerService;
import com.kaltura.client.services.KalturaPermissionItemService;
import com.kaltura.client.services.KalturaPermissionService;
import com.kaltura.client.services.KalturaPlaylistService;
import com.kaltura.client.services.KalturaReportService;
import com.kaltura.client.services.KalturaResponseProfileService;
import com.kaltura.client.services.KalturaSchemaService;
import com.kaltura.client.services.KalturaSearchService;
import com.kaltura.client.services.KalturaServerNodeService;
import com.kaltura.client.services.KalturaSessionService;
import com.kaltura.client.services.KalturaStatsService;
import com.kaltura.client.services.KalturaStorageProfileService;
import com.kaltura.client.services.KalturaSyndicationFeedService;
import com.kaltura.client.services.KalturaSystemService;
import com.kaltura.client.services.KalturaThumbAssetService;
import com.kaltura.client.services.KalturaThumbParamsOutputService;
import com.kaltura.client.services.KalturaThumbParamsService;
import com.kaltura.client.services.KalturaUiConfService;
import com.kaltura.client.services.KalturaUploadService;
import com.kaltura.client.services.KalturaUploadTokenService;
import com.kaltura.client.services.KalturaUserEntryService;
import com.kaltura.client.services.KalturaUserRoleService;
import com.kaltura.client.services.KalturaUserService;
import com.kaltura.client.services.KalturaWidgetService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaVirusScanProfileService;
import com.kaltura.client.services.KalturaDistributionProfileService;
import com.kaltura.client.services.KalturaEntryDistributionService;
import com.kaltura.client.services.KalturaDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderActionService;
import com.kaltura.client.services.KalturaCuePointService;
import com.kaltura.client.services.KalturaAnnotationService;
import com.kaltura.client.services.KalturaQuizService;
import com.kaltura.client.services.KalturaShortLinkService;
import com.kaltura.client.services.KalturaBulkService;
import com.kaltura.client.services.KalturaDropFolderService;
import com.kaltura.client.services.KalturaDropFolderFileService;
import com.kaltura.client.services.KalturaCaptionAssetService;
import com.kaltura.client.services.KalturaCaptionParamsService;
import com.kaltura.client.services.KalturaCaptionAssetItemService;
import com.kaltura.client.services.KalturaAttachmentAssetService;
import com.kaltura.client.services.KalturaTagService;
import com.kaltura.client.services.KalturaLikeService;
import com.kaltura.client.services.KalturaVarConsoleService;
import com.kaltura.client.services.KalturaEventNotificationTemplateService;
import com.kaltura.client.services.KalturaExternalMediaService;
import com.kaltura.client.services.KalturaScheduleEventService;
import com.kaltura.client.services.KalturaScheduleResourceService;
import com.kaltura.client.services.KalturaScheduleEventResourceService;
import com.kaltura.client.services.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using exec.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaClient extends KalturaClientBase {
public KalturaClient(KalturaConfiguration config) {
super(config);
this.setClientTag("java:17-04-23");
this.setApiVersion("3.3.0");
}
protected KalturaAccessControlProfileService accessControlProfileService;
public KalturaAccessControlProfileService getAccessControlProfileService() {
if(this.accessControlProfileService == null)
this.accessControlProfileService = new KalturaAccessControlProfileService(this);
return this.accessControlProfileService;
}
protected KalturaAccessControlService accessControlService;
public KalturaAccessControlService getAccessControlService() {
if(this.accessControlService == null)
this.accessControlService = new KalturaAccessControlService(this);
return this.accessControlService;
}
protected KalturaAdminUserService adminUserService;
public KalturaAdminUserService getAdminUserService() {
if(this.adminUserService == null)
this.adminUserService = new KalturaAdminUserService(this);
return this.adminUserService;
}
protected KalturaAnalyticsService analyticsService;
public KalturaAnalyticsService getAnalyticsService() {
if(this.analyticsService == null)
this.analyticsService = new KalturaAnalyticsService(this);
return this.analyticsService;
}
protected KalturaAppTokenService appTokenService;
public KalturaAppTokenService getAppTokenService() {
if(this.appTokenService == null)
this.appTokenService = new KalturaAppTokenService(this);
return this.appTokenService;
}
protected KalturaBaseEntryService baseEntryService;
public KalturaBaseEntryService getBaseEntryService() {
if(this.baseEntryService == null)
this.baseEntryService = new KalturaBaseEntryService(this);
return this.baseEntryService;
}
protected KalturaBulkUploadService bulkUploadService;
public KalturaBulkUploadService getBulkUploadService() {
if(this.bulkUploadService == null)
this.bulkUploadService = new KalturaBulkUploadService(this);
return this.bulkUploadService;
}
protected KalturaCategoryEntryService categoryEntryService;
public KalturaCategoryEntryService getCategoryEntryService() {
if(this.categoryEntryService == null)
this.categoryEntryService = new KalturaCategoryEntryService(this);
return this.categoryEntryService;
}
protected KalturaCategoryService categoryService;
public KalturaCategoryService getCategoryService() {
if(this.categoryService == null)
this.categoryService = new KalturaCategoryService(this);
return this.categoryService;
}
protected KalturaCategoryUserService categoryUserService;
public KalturaCategoryUserService getCategoryUserService() {
if(this.categoryUserService == null)
this.categoryUserService = new KalturaCategoryUserService(this);
return this.categoryUserService;
}
protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService;
public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() {
if(this.conversionProfileAssetParamsService == null)
this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this);
return this.conversionProfileAssetParamsService;
}
protected KalturaConversionProfileService conversionProfileService;
public KalturaConversionProfileService getConversionProfileService() {
if(this.conversionProfileService == null)
this.conversionProfileService = new KalturaConversionProfileService(this);
return this.conversionProfileService;
}
protected KalturaDataService dataService;
public KalturaDataService getDataService() {
if(this.dataService == null)
this.dataService = new KalturaDataService(this);
return this.dataService;
}
protected KalturaDeliveryProfileService deliveryProfileService;
public KalturaDeliveryProfileService getDeliveryProfileService() {
if(this.deliveryProfileService == null)
this.deliveryProfileService = new KalturaDeliveryProfileService(this);
return this.deliveryProfileService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
protected KalturaEntryServerNodeService entryServerNodeService;
public KalturaEntryServerNodeService getEntryServerNodeService() {
if(this.entryServerNodeService == null)
this.entryServerNodeService = new KalturaEntryServerNodeService(this);
return this.entryServerNodeService;
}
protected KalturaFileAssetService fileAssetService;
public KalturaFileAssetService getFileAssetService() {
if(this.fileAssetService == null)
this.fileAssetService = new KalturaFileAssetService(this);
return this.fileAssetService;
}
protected KalturaFlavorAssetService flavorAssetService;
public KalturaFlavorAssetService getFlavorAssetService() {
if(this.flavorAssetService == null)
this.flavorAssetService = new KalturaFlavorAssetService(this);
return this.flavorAssetService;
}
protected KalturaFlavorParamsOutputService flavorParamsOutputService;
public KalturaFlavorParamsOutputService getFlavorParamsOutputService() {
if(this.flavorParamsOutputService == null)
this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this);
return this.flavorParamsOutputService;
}
protected KalturaFlavorParamsService flavorParamsService;
public KalturaFlavorParamsService getFlavorParamsService() {
if(this.flavorParamsService == null)
this.flavorParamsService = new KalturaFlavorParamsService(this);
return this.flavorParamsService;
}
protected KalturaGroupUserService groupUserService;
public KalturaGroupUserService getGroupUserService() {
if(this.groupUserService == null)
this.groupUserService = new KalturaGroupUserService(this);
return this.groupUserService;
}
protected KalturaLiveChannelSegmentService liveChannelSegmentService;
public KalturaLiveChannelSegmentService getLiveChannelSegmentService() {
if(this.liveChannelSegmentService == null)
this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this);
return this.liveChannelSegmentService;
}
protected KalturaLiveChannelService liveChannelService;
public KalturaLiveChannelService getLiveChannelService() {
if(this.liveChannelService == null)
this.liveChannelService = new KalturaLiveChannelService(this);
return this.liveChannelService;
}
protected KalturaLiveReportsService liveReportsService;
public KalturaLiveReportsService getLiveReportsService() {
if(this.liveReportsService == null)
this.liveReportsService = new KalturaLiveReportsService(this);
return this.liveReportsService;
}
protected KalturaLiveStatsService liveStatsService;
public KalturaLiveStatsService getLiveStatsService() {
if(this.liveStatsService == null)
this.liveStatsService = new KalturaLiveStatsService(this);
return this.liveStatsService;
}
protected KalturaLiveStreamService liveStreamService;
public KalturaLiveStreamService getLiveStreamService() {
if(this.liveStreamService == null)
this.liveStreamService = new KalturaLiveStreamService(this);
return this.liveStreamService;
}
protected KalturaMediaInfoService mediaInfoService;
public KalturaMediaInfoService getMediaInfoService() {
if(this.mediaInfoService == null)
this.mediaInfoService = new KalturaMediaInfoService(this);
return this.mediaInfoService;
}
protected KalturaMediaService mediaService;
public KalturaMediaService getMediaService() {
if(this.mediaService == null)
this.mediaService = new KalturaMediaService(this);
return this.mediaService;
}
protected KalturaMixingService mixingService;
public KalturaMixingService getMixingService() {
if(this.mixingService == null)
this.mixingService = new KalturaMixingService(this);
return this.mixingService;
}
protected KalturaNotificationService notificationService;
public KalturaNotificationService getNotificationService() {
if(this.notificationService == null)
this.notificationService = new KalturaNotificationService(this);
return this.notificationService;
}
protected KalturaPartnerService partnerService;
public KalturaPartnerService getPartnerService() {
if(this.partnerService == null)
this.partnerService = new KalturaPartnerService(this);
return this.partnerService;
}
protected KalturaPermissionItemService permissionItemService;
public KalturaPermissionItemService getPermissionItemService() {
if(this.permissionItemService == null)
this.permissionItemService = new KalturaPermissionItemService(this);
return this.permissionItemService;
}
protected KalturaPermissionService permissionService;
public KalturaPermissionService getPermissionService() {
if(this.permissionService == null)
this.permissionService = new KalturaPermissionService(this);
return this.permissionService;
}
protected KalturaPlaylistService playlistService;
public KalturaPlaylistService getPlaylistService() {
if(this.playlistService == null)
this.playlistService = new KalturaPlaylistService(this);
return this.playlistService;
}
protected KalturaReportService reportService;
public KalturaReportService getReportService() {
if(this.reportService == null)
this.reportService = new KalturaReportService(this);
return this.reportService;
}
protected KalturaResponseProfileService responseProfileService;
public KalturaResponseProfileService getResponseProfileService() {
if(this.responseProfileService == null)
this.responseProfileService = new KalturaResponseProfileService(this);
return this.responseProfileService;
}
protected KalturaSchemaService schemaService;
public KalturaSchemaService getSchemaService() {
if(this.schemaService == null)
this.schemaService = new KalturaSchemaService(this);
return this.schemaService;
}
protected KalturaSearchService searchService;
public KalturaSearchService getSearchService() {
if(this.searchService == null)
this.searchService = new KalturaSearchService(this);
return this.searchService;
}
protected KalturaServerNodeService serverNodeService;
public KalturaServerNodeService getServerNodeService() {
if(this.serverNodeService == null)
this.serverNodeService = new KalturaServerNodeService(this);
return this.serverNodeService;
}
protected KalturaSessionService sessionService;
public KalturaSessionService getSessionService() {
if(this.sessionService == null)
this.sessionService = new KalturaSessionService(this);
return this.sessionService;
}
protected KalturaStatsService statsService;
public KalturaStatsService getStatsService() {
if(this.statsService == null)
this.statsService = new KalturaStatsService(this);
return this.statsService;
}
protected KalturaStorageProfileService storageProfileService;
public KalturaStorageProfileService getStorageProfileService() {
if(this.storageProfileService == null)
this.storageProfileService = new KalturaStorageProfileService(this);
return this.storageProfileService;
}
protected KalturaSyndicationFeedService syndicationFeedService;
public KalturaSyndicationFeedService getSyndicationFeedService() {
if(this.syndicationFeedService == null)
this.syndicationFeedService = new KalturaSyndicationFeedService(this);
return this.syndicationFeedService;
}
protected KalturaSystemService systemService;
public KalturaSystemService getSystemService() {
if(this.systemService == null)
this.systemService = new KalturaSystemService(this);
return this.systemService;
}
protected KalturaThumbAssetService thumbAssetService;
public KalturaThumbAssetService getThumbAssetService() {
if(this.thumbAssetService == null)
this.thumbAssetService = new KalturaThumbAssetService(this);
return this.thumbAssetService;
}
protected KalturaThumbParamsOutputService thumbParamsOutputService;
public KalturaThumbParamsOutputService getThumbParamsOutputService() {
if(this.thumbParamsOutputService == null)
this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this);
return this.thumbParamsOutputService;
}
protected KalturaThumbParamsService thumbParamsService;
public KalturaThumbParamsService getThumbParamsService() {
if(this.thumbParamsService == null)
this.thumbParamsService = new KalturaThumbParamsService(this);
return this.thumbParamsService;
}
protected KalturaUiConfService uiConfService;
public KalturaUiConfService getUiConfService() {
if(this.uiConfService == null)
this.uiConfService = new KalturaUiConfService(this);
return this.uiConfService;
}
protected KalturaUploadService uploadService;
public KalturaUploadService getUploadService() {
if(this.uploadService == null)
this.uploadService = new KalturaUploadService(this);
return this.uploadService;
}
protected KalturaUploadTokenService uploadTokenService;
public KalturaUploadTokenService getUploadTokenService() {
if(this.uploadTokenService == null)
this.uploadTokenService = new KalturaUploadTokenService(this);
return this.uploadTokenService;
}
protected KalturaUserEntryService userEntryService;
public KalturaUserEntryService getUserEntryService() {
if(this.userEntryService == null)
this.userEntryService = new KalturaUserEntryService(this);
return this.userEntryService;
}
protected KalturaUserRoleService userRoleService;
public KalturaUserRoleService getUserRoleService() {
if(this.userRoleService == null)
this.userRoleService = new KalturaUserRoleService(this);
return this.userRoleService;
}
protected KalturaUserService userService;
public KalturaUserService getUserService() {
if(this.userService == null)
this.userService = new KalturaUserService(this);
return this.userService;
}
protected KalturaWidgetService widgetService;
public KalturaWidgetService getWidgetService() {
if(this.widgetService == null)
this.widgetService = new KalturaWidgetService(this);
return this.widgetService;
}
protected KalturaMetadataService metadataService;
public KalturaMetadataService getMetadataService() {
if(this.metadataService == null)
this.metadataService = new KalturaMetadataService(this);
return this.metadataService;
}
protected KalturaMetadataProfileService metadataProfileService;
public KalturaMetadataProfileService getMetadataProfileService() {
if(this.metadataProfileService == null)
this.metadataProfileService = new KalturaMetadataProfileService(this);
return this.metadataProfileService;
}
protected KalturaDocumentsService documentsService;
public KalturaDocumentsService getDocumentsService() {
if(this.documentsService == null)
this.documentsService = new KalturaDocumentsService(this);
return this.documentsService;
}
protected KalturaVirusScanProfileService virusScanProfileService;
public KalturaVirusScanProfileService getVirusScanProfileService() {
if(this.virusScanProfileService == null)
this.virusScanProfileService = new KalturaVirusScanProfileService(this);
return this.virusScanProfileService;
}
protected KalturaDistributionProfileService distributionProfileService;
public KalturaDistributionProfileService getDistributionProfileService() {
if(this.distributionProfileService == null)
this.distributionProfileService = new KalturaDistributionProfileService(this);
return this.distributionProfileService;
}
protected KalturaEntryDistributionService entryDistributionService;
public KalturaEntryDistributionService getEntryDistributionService() {
if(this.entryDistributionService == null)
this.entryDistributionService = new KalturaEntryDistributionService(this);
return this.entryDistributionService;
}
protected KalturaDistributionProviderService distributionProviderService;
public KalturaDistributionProviderService getDistributionProviderService() {
if(this.distributionProviderService == null)
this.distributionProviderService = new KalturaDistributionProviderService(this);
return this.distributionProviderService;
}
protected KalturaGenericDistributionProviderService genericDistributionProviderService;
public KalturaGenericDistributionProviderService getGenericDistributionProviderService() {
if(this.genericDistributionProviderService == null)
this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this);
return this.genericDistributionProviderService;
}
protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService;
public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() {
if(this.genericDistributionProviderActionService == null)
this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this);
return this.genericDistributionProviderActionService;
}
protected KalturaCuePointService cuePointService;
public KalturaCuePointService getCuePointService() {
if(this.cuePointService == null)
this.cuePointService = new KalturaCuePointService(this);
return this.cuePointService;
}
protected KalturaAnnotationService annotationService;
public KalturaAnnotationService getAnnotationService() {
if(this.annotationService == null)
this.annotationService = new KalturaAnnotationService(this);
return this.annotationService;
}
protected KalturaQuizService quizService;
public KalturaQuizService getQuizService() {
if(this.quizService == null)
this.quizService = new KalturaQuizService(this);
return this.quizService;
}
protected KalturaShortLinkService shortLinkService;
public KalturaShortLinkService getShortLinkService() {
if(this.shortLinkService == null)
this.shortLinkService = new KalturaShortLinkService(this);
return this.shortLinkService;
}
protected KalturaBulkService bulkService;
public KalturaBulkService getBulkService() {
if(this.bulkService == null)
this.bulkService = new KalturaBulkService(this);
return this.bulkService;
}
protected KalturaDropFolderService dropFolderService;
public KalturaDropFolderService getDropFolderService() {
if(this.dropFolderService == null)
this.dropFolderService = new KalturaDropFolderService(this);
return this.dropFolderService;
}
protected KalturaDropFolderFileService dropFolderFileService;
public KalturaDropFolderFileService getDropFolderFileService() {
if(this.dropFolderFileService == null)
this.dropFolderFileService = new KalturaDropFolderFileService(this);
return this.dropFolderFileService;
}
protected KalturaCaptionAssetService captionAssetService;
public KalturaCaptionAssetService getCaptionAssetService() {
if(this.captionAssetService == null)
this.captionAssetService = new KalturaCaptionAssetService(this);
return this.captionAssetService;
}
protected KalturaCaptionParamsService captionParamsService;
public KalturaCaptionParamsService getCaptionParamsService() {
if(this.captionParamsService == null)
this.captionParamsService = new KalturaCaptionParamsService(this);
return this.captionParamsService;
}
protected KalturaCaptionAssetItemService captionAssetItemService;
public KalturaCaptionAssetItemService getCaptionAssetItemService() {
if(this.captionAssetItemService == null)
this.captionAssetItemService = new KalturaCaptionAssetItemService(this);
return this.captionAssetItemService;
}
protected KalturaAttachmentAssetService attachmentAssetService;
public KalturaAttachmentAssetService getAttachmentAssetService() {
if(this.attachmentAssetService == null)
this.attachmentAssetService = new KalturaAttachmentAssetService(this);
return this.attachmentAssetService;
}
protected KalturaTagService tagService;
public KalturaTagService getTagService() {
if(this.tagService == null)
this.tagService = new KalturaTagService(this);
return this.tagService;
}
protected KalturaLikeService likeService;
public KalturaLikeService getLikeService() {
if(this.likeService == null)
this.likeService = new KalturaLikeService(this);
return this.likeService;
}
protected KalturaVarConsoleService varConsoleService;
public KalturaVarConsoleService getVarConsoleService() {
if(this.varConsoleService == null)
this.varConsoleService = new KalturaVarConsoleService(this);
return this.varConsoleService;
}
protected KalturaEventNotificationTemplateService eventNotificationTemplateService;
public KalturaEventNotificationTemplateService getEventNotificationTemplateService() {
if(this.eventNotificationTemplateService == null)
this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this);
return this.eventNotificationTemplateService;
}
protected KalturaExternalMediaService externalMediaService;
public KalturaExternalMediaService getExternalMediaService() {
if(this.externalMediaService == null)
this.externalMediaService = new KalturaExternalMediaService(this);
return this.externalMediaService;
}
protected KalturaScheduleEventService scheduleEventService;
public KalturaScheduleEventService getScheduleEventService() {
if(this.scheduleEventService == null)
this.scheduleEventService = new KalturaScheduleEventService(this);
return this.scheduleEventService;
}
protected KalturaScheduleResourceService scheduleResourceService;
public KalturaScheduleResourceService getScheduleResourceService() {
if(this.scheduleResourceService == null)
this.scheduleResourceService = new KalturaScheduleResourceService(this);
return this.scheduleResourceService;
}
protected KalturaScheduleEventResourceService scheduleEventResourceService;
public KalturaScheduleEventResourceService getScheduleEventResourceService() {
if(this.scheduleEventResourceService == null)
this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this);
return this.scheduleEventResourceService;
}
protected KalturaScheduledTaskProfileService scheduledTaskProfileService;
public KalturaScheduledTaskProfileService getScheduledTaskProfileService() {
if(this.scheduledTaskProfileService == null)
this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this);
return this.scheduledTaskProfileService;
}
protected KalturaIntegrationService integrationService;
public KalturaIntegrationService getIntegrationService() {
if(this.integrationService == null)
this.integrationService = new KalturaIntegrationService(this);
return this.integrationService;
}
/**
* @param String $clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return (String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param String $apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return (String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param Integer $partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return (Integer) this.requestConfiguration.get("partnerId");
}
return null;
}
/**
* Kaltura API session
*
* @param String $ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param String $sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param KalturaBaseResponseProfile $responseProfile
*/
public void setResponseProfile(KalturaBaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return KalturaBaseResponseProfile
*/
public KalturaBaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
/**
* Clear all volatile configuration parameters
*/
protected void resetRequest(){
this.requestConfiguration.remove("responseProfile");
}
} |
package org.wso2.carbon.device.mgt.core.geo.service;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.geo.service.Alert;
import org.wso2.carbon.device.mgt.common.geo.service.GeoFence;
import org.wso2.carbon.device.mgt.core.TestDeviceManagementService;
import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.registry.core.config.RegistryContext;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.internal.RegistryDataHolder;
import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.List;
import static org.powermock.api.mockito.PowerMockito.*;
@PrepareForTest(GeoLocationProviderServiceImpl.class)
public class GeoLocationProviderServiceTest {
private static final Log log = LogFactory.getLog(GeoLocationProviderServiceTest.class);
private static final String DEVICE_TYPE = "GL_TEST_TYPE";
private static final String DEVICE_ID = "GL-TEST-DEVICE-ID-1";
private static final String SAMPLE_GEO_JSON = "12121";
private static final String SAMPLE_AREA_NAME = "CUSTOM_NAME";
private static final String SAMPLE_QUERY_NAME = "QUERY_NAME";
private static final String SAMPLE_PROXIMITY_DISATANCE = "100";
private static final String SAMPLE_PROXIMITY_TIME = "50";
private static final String SAMPLE_SPEED_ALERT_VALUE = "120";
private static final String SAMPLE_STATIONARY_TIME = "1500";
private static final String SAMPLE_FLUCTUATION_RADIUS = "2000";
private EventProcessorAdminServiceStub mockEventProcessorAdminServiceStub;
private GeoLocationProviderServiceImpl geoLocationProviderServiceImpl;
@BeforeClass
public void init() throws Exception {
initMocks();
enrollTestDevice();
}
@Test
public void createGeoExitAlert() throws Exception {
Boolean result = geoLocationProviderServiceImpl.
createGeoAlert(getTestAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_EXIT);
Assert.assertEquals(result, Boolean.TRUE);
verifyPrivate(geoLocationProviderServiceImpl).invoke("getEventProcessorAdminServiceStub");
}
@Test
public void createGeoWithinAlert() throws Exception {
Boolean result = geoLocationProviderServiceImpl.
createGeoAlert(getTestAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_WITHIN);
Assert.assertEquals(result, Boolean.TRUE);
}
@Test
public void createGeoProximityAlert() throws Exception {
Boolean result = geoLocationProviderServiceImpl.
createGeoAlert(getProximityAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_PROXIMITY);
Assert.assertEquals(result, Boolean.TRUE);
}
@Test
public void createGeoSpeedAlert() throws Exception {
Boolean result = geoLocationProviderServiceImpl.
createGeoAlert(getSpeedAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_SPEED);
Assert.assertEquals(result, Boolean.TRUE);
}
@Test
public void createGeoStationaryAlert() throws Exception {
Boolean result = geoLocationProviderServiceImpl.
createGeoAlert(getStationaryAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_STATIONARY);
Assert.assertEquals(result, Boolean.TRUE);
}
@Test
public void createGeoTrafficAlert() throws Exception {
Boolean result = geoLocationProviderServiceImpl.
createGeoAlert(getTrafficAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_TRAFFIC);
Assert.assertEquals(result, Boolean.TRUE);
}
//Test methods to retrieve saved Data.
@Test(dependsOnMethods = "createGeoExitAlert")
public void getGeoExitAlerts() throws Exception {
List<GeoFence> geoFences;
geoFences = geoLocationProviderServiceImpl.getExitAlerts(getDeviceIdentifier());
Assert.assertNotNull(geoFences);
GeoFence geoFenceNode = geoFences.get(0);
Assert.assertEquals(geoFenceNode.getGeoJson(), SAMPLE_GEO_JSON);
Assert.assertEquals(geoFenceNode.getAreaName(), SAMPLE_AREA_NAME);
Assert.assertEquals(geoFenceNode.getQueryName(), SAMPLE_QUERY_NAME);
}
@Test(dependsOnMethods = "createGeoWithinAlert")
public void getGeoWithinAlerts() throws Exception {
List<GeoFence> geoFences;
geoFences = geoLocationProviderServiceImpl.getWithinAlerts(getDeviceIdentifier());
Assert.assertNotNull(geoFences);
GeoFence geoFenceNode = geoFences.get(0);
Assert.assertEquals(geoFenceNode.getAreaName(), SAMPLE_AREA_NAME);
Assert.assertEquals(geoFenceNode.getQueryName(), SAMPLE_QUERY_NAME);
}
@Test(dependsOnMethods = "createGeoSpeedAlert")
public void getGeoSpeedAlerts() throws Exception {
String result;
result = geoLocationProviderServiceImpl.getSpeedAlerts(getDeviceIdentifier());
Assert.assertNotNull(result);
Assert.assertEquals(result, "{'speedLimit':" +
SAMPLE_SPEED_ALERT_VALUE + "}");
}
@Test(dependsOnMethods = "createGeoTrafficAlert")
public void getGeoTrafficAlerts() throws Exception {
List<GeoFence> geoFences;
geoFences = geoLocationProviderServiceImpl.getTrafficAlerts(getDeviceIdentifier());
Assert.assertNotNull(geoFences);
GeoFence geoFenceNode = geoFences.get(0);
Assert.assertEquals(geoFenceNode.getGeoJson(), "{\n" +
" \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\"\n" +
"}");
}
@Test(dependsOnMethods = "createGeoStationaryAlert")
public void getGeoStationaryAlerts() throws Exception {
List<GeoFence> geoFences;
geoFences = geoLocationProviderServiceImpl.getStationaryAlerts(getDeviceIdentifier());
Assert.assertNotNull(geoFences);
GeoFence geoFenceNode = geoFences.get(0);
Assert.assertEquals(geoFenceNode.getAreaName(), SAMPLE_AREA_NAME);
Assert.assertEquals(geoFenceNode.getQueryName(), SAMPLE_QUERY_NAME);
Assert.assertEquals(geoFenceNode.getStationaryTime(), SAMPLE_STATIONARY_TIME);
}
private void initMocks() throws JWTClientException, RemoteException {
mockEventProcessorAdminServiceStub = Mockito.mock(EventProcessorAdminServiceStub.class);
geoLocationProviderServiceImpl = Mockito.mock(GeoLocationProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS);
doReturn(mockEventProcessorAdminServiceStub).when(geoLocationProviderServiceImpl).getEventProcessorAdminServiceStub();
doReturn("success").when(mockEventProcessorAdminServiceStub).validateExecutionPlan(Mockito.anyString());
}
private DeviceIdentifier getDeviceIdentifier() {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId("1234");
deviceIdentifier.setType("TEST");
return deviceIdentifier;
}
private RegistryService getRegistryService() throws RegistryException {
RealmService realmService = new InMemoryRealmService();
RegistryDataHolder.getInstance().setRealmService(realmService);
DeviceManagementDataHolder.getInstance().setRealmService(realmService);
InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
context.setSetup(true);
return context.getEmbeddedRegistryService();
}
private void enrollTestDevice() throws Exception {
Device device = TestDataHolder.generateDummyDeviceData(DEVICE_ID);
DeviceManagementProviderService deviceMgtService = new DeviceManagementProviderServiceImpl();
DeviceManagementServiceComponent.notifyStartupListeners();
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService);
DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService());
DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(new DeviceAccessAuthorizationServiceImpl());
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new GroupManagementProviderServiceImpl());
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);
deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE,
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME));
deviceMgtService.enrollDevice(device);
}
private Alert getTestAlert() {
Alert alert = new Alert();
alert.setDeviceId(DEVICE_ID);
alert.setCepAction("CEP_ACTION");
alert.setParseData("{\n" +
" \" " + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\"\n" +
"}");
alert.setCustomName(SAMPLE_AREA_NAME);
alert.setExecutionPlan("EXECUTION_PLAN");
alert.setQueryName(SAMPLE_QUERY_NAME);
return alert;
}
private Alert getProximityAlert() {
Alert alert = new Alert();
alert.setDeviceId(DEVICE_ID);
alert.setProximityTime(SAMPLE_PROXIMITY_TIME);
alert.setProximityDistance(SAMPLE_PROXIMITY_DISATANCE);
alert.setParseData("{\n" +
" \" " + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\"\n" +
"}");
return alert;
}
private Alert getSpeedAlert() {
Alert alert = getTestAlert();
alert.setParseData("{\n" +
" \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\",\n" +
" \"" + DeviceManagementConstants.GeoServices.SPEED_ALERT_VALUE + "\": \"" + SAMPLE_SPEED_ALERT_VALUE + "\"\n" +
"}");
return alert;
}
private Alert getStationaryAlert() {
Alert alert = new Alert();
alert.setDeviceId(DEVICE_ID);
alert.setQueryName(SAMPLE_QUERY_NAME);
alert.setCustomName(SAMPLE_AREA_NAME);
alert.setStationeryTime(SAMPLE_STATIONARY_TIME);
alert.setFluctuationRadius(SAMPLE_FLUCTUATION_RADIUS);
alert.setParseData("{\n" +
" \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\"\n" +
"}");
return alert;
}
private Alert getTrafficAlert() {
Alert alert = new Alert();
alert.setDeviceId(DEVICE_ID);
alert.setParseData("{\n" +
" \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON +"\": \"" + SAMPLE_GEO_JSON + "\"\n" +
"}");
alert.setCustomName(SAMPLE_AREA_NAME);
alert.setExecutionPlan("EXECUTION_PLAN");
alert.setQueryName(SAMPLE_QUERY_NAME);
return alert;
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.services.KalturaAccessControlProfileService;
import com.kaltura.client.services.KalturaAccessControlService;
import com.kaltura.client.services.KalturaAdminUserService;
import com.kaltura.client.services.KalturaAnalyticsService;
import com.kaltura.client.services.KalturaAppTokenService;
import com.kaltura.client.services.KalturaBaseEntryService;
import com.kaltura.client.services.KalturaBulkUploadService;
import com.kaltura.client.services.KalturaCategoryEntryService;
import com.kaltura.client.services.KalturaCategoryService;
import com.kaltura.client.services.KalturaCategoryUserService;
import com.kaltura.client.services.KalturaConversionProfileAssetParamsService;
import com.kaltura.client.services.KalturaConversionProfileService;
import com.kaltura.client.services.KalturaDataService;
import com.kaltura.client.services.KalturaDeliveryProfileService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
import com.kaltura.client.services.KalturaEntryServerNodeService;
import com.kaltura.client.services.KalturaFileAssetService;
import com.kaltura.client.services.KalturaFlavorAssetService;
import com.kaltura.client.services.KalturaFlavorParamsOutputService;
import com.kaltura.client.services.KalturaFlavorParamsService;
import com.kaltura.client.services.KalturaGroupUserService;
import com.kaltura.client.services.KalturaLiveChannelSegmentService;
import com.kaltura.client.services.KalturaLiveChannelService;
import com.kaltura.client.services.KalturaLiveReportsService;
import com.kaltura.client.services.KalturaLiveStatsService;
import com.kaltura.client.services.KalturaLiveStreamService;
import com.kaltura.client.services.KalturaMediaInfoService;
import com.kaltura.client.services.KalturaMediaService;
import com.kaltura.client.services.KalturaMixingService;
import com.kaltura.client.services.KalturaNotificationService;
import com.kaltura.client.services.KalturaPartnerService;
import com.kaltura.client.services.KalturaPermissionItemService;
import com.kaltura.client.services.KalturaPermissionService;
import com.kaltura.client.services.KalturaPlaylistService;
import com.kaltura.client.services.KalturaReportService;
import com.kaltura.client.services.KalturaResponseProfileService;
import com.kaltura.client.services.KalturaSchemaService;
import com.kaltura.client.services.KalturaSearchService;
import com.kaltura.client.services.KalturaServerNodeService;
import com.kaltura.client.services.KalturaSessionService;
import com.kaltura.client.services.KalturaStatsService;
import com.kaltura.client.services.KalturaStorageProfileService;
import com.kaltura.client.services.KalturaSyndicationFeedService;
import com.kaltura.client.services.KalturaSystemService;
import com.kaltura.client.services.KalturaThumbAssetService;
import com.kaltura.client.services.KalturaThumbParamsOutputService;
import com.kaltura.client.services.KalturaThumbParamsService;
import com.kaltura.client.services.KalturaUiConfService;
import com.kaltura.client.services.KalturaUploadService;
import com.kaltura.client.services.KalturaUploadTokenService;
import com.kaltura.client.services.KalturaUserEntryService;
import com.kaltura.client.services.KalturaUserRoleService;
import com.kaltura.client.services.KalturaUserService;
import com.kaltura.client.services.KalturaWidgetService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaVirusScanProfileService;
import com.kaltura.client.services.KalturaDistributionProfileService;
import com.kaltura.client.services.KalturaEntryDistributionService;
import com.kaltura.client.services.KalturaDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderActionService;
import com.kaltura.client.services.KalturaCuePointService;
import com.kaltura.client.services.KalturaAnnotationService;
import com.kaltura.client.services.KalturaQuizService;
import com.kaltura.client.services.KalturaShortLinkService;
import com.kaltura.client.services.KalturaBulkService;
import com.kaltura.client.services.KalturaDropFolderService;
import com.kaltura.client.services.KalturaDropFolderFileService;
import com.kaltura.client.services.KalturaCaptionAssetService;
import com.kaltura.client.services.KalturaCaptionParamsService;
import com.kaltura.client.services.KalturaCaptionAssetItemService;
import com.kaltura.client.services.KalturaAttachmentAssetService;
import com.kaltura.client.services.KalturaTagService;
import com.kaltura.client.services.KalturaLikeService;
import com.kaltura.client.services.KalturaVarConsoleService;
import com.kaltura.client.services.KalturaEventNotificationTemplateService;
import com.kaltura.client.services.KalturaExternalMediaService;
import com.kaltura.client.services.KalturaScheduleEventService;
import com.kaltura.client.services.KalturaScheduleResourceService;
import com.kaltura.client.services.KalturaScheduleEventResourceService;
import com.kaltura.client.services.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using exec.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaClient extends KalturaClientBase {
public KalturaClient(KalturaConfiguration config) {
super(config);
this.setClientTag("java:16-12-28");
this.setApiVersion("3.3.0");
}
protected KalturaAccessControlProfileService accessControlProfileService;
public KalturaAccessControlProfileService getAccessControlProfileService() {
if(this.accessControlProfileService == null)
this.accessControlProfileService = new KalturaAccessControlProfileService(this);
return this.accessControlProfileService;
}
protected KalturaAccessControlService accessControlService;
public KalturaAccessControlService getAccessControlService() {
if(this.accessControlService == null)
this.accessControlService = new KalturaAccessControlService(this);
return this.accessControlService;
}
protected KalturaAdminUserService adminUserService;
public KalturaAdminUserService getAdminUserService() {
if(this.adminUserService == null)
this.adminUserService = new KalturaAdminUserService(this);
return this.adminUserService;
}
protected KalturaAnalyticsService analyticsService;
public KalturaAnalyticsService getAnalyticsService() {
if(this.analyticsService == null)
this.analyticsService = new KalturaAnalyticsService(this);
return this.analyticsService;
}
protected KalturaAppTokenService appTokenService;
public KalturaAppTokenService getAppTokenService() {
if(this.appTokenService == null)
this.appTokenService = new KalturaAppTokenService(this);
return this.appTokenService;
}
protected KalturaBaseEntryService baseEntryService;
public KalturaBaseEntryService getBaseEntryService() {
if(this.baseEntryService == null)
this.baseEntryService = new KalturaBaseEntryService(this);
return this.baseEntryService;
}
protected KalturaBulkUploadService bulkUploadService;
public KalturaBulkUploadService getBulkUploadService() {
if(this.bulkUploadService == null)
this.bulkUploadService = new KalturaBulkUploadService(this);
return this.bulkUploadService;
}
protected KalturaCategoryEntryService categoryEntryService;
public KalturaCategoryEntryService getCategoryEntryService() {
if(this.categoryEntryService == null)
this.categoryEntryService = new KalturaCategoryEntryService(this);
return this.categoryEntryService;
}
protected KalturaCategoryService categoryService;
public KalturaCategoryService getCategoryService() {
if(this.categoryService == null)
this.categoryService = new KalturaCategoryService(this);
return this.categoryService;
}
protected KalturaCategoryUserService categoryUserService;
public KalturaCategoryUserService getCategoryUserService() {
if(this.categoryUserService == null)
this.categoryUserService = new KalturaCategoryUserService(this);
return this.categoryUserService;
}
protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService;
public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() {
if(this.conversionProfileAssetParamsService == null)
this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this);
return this.conversionProfileAssetParamsService;
}
protected KalturaConversionProfileService conversionProfileService;
public KalturaConversionProfileService getConversionProfileService() {
if(this.conversionProfileService == null)
this.conversionProfileService = new KalturaConversionProfileService(this);
return this.conversionProfileService;
}
protected KalturaDataService dataService;
public KalturaDataService getDataService() {
if(this.dataService == null)
this.dataService = new KalturaDataService(this);
return this.dataService;
}
protected KalturaDeliveryProfileService deliveryProfileService;
public KalturaDeliveryProfileService getDeliveryProfileService() {
if(this.deliveryProfileService == null)
this.deliveryProfileService = new KalturaDeliveryProfileService(this);
return this.deliveryProfileService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
protected KalturaEntryServerNodeService entryServerNodeService;
public KalturaEntryServerNodeService getEntryServerNodeService() {
if(this.entryServerNodeService == null)
this.entryServerNodeService = new KalturaEntryServerNodeService(this);
return this.entryServerNodeService;
}
protected KalturaFileAssetService fileAssetService;
public KalturaFileAssetService getFileAssetService() {
if(this.fileAssetService == null)
this.fileAssetService = new KalturaFileAssetService(this);
return this.fileAssetService;
}
protected KalturaFlavorAssetService flavorAssetService;
public KalturaFlavorAssetService getFlavorAssetService() {
if(this.flavorAssetService == null)
this.flavorAssetService = new KalturaFlavorAssetService(this);
return this.flavorAssetService;
}
protected KalturaFlavorParamsOutputService flavorParamsOutputService;
public KalturaFlavorParamsOutputService getFlavorParamsOutputService() {
if(this.flavorParamsOutputService == null)
this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this);
return this.flavorParamsOutputService;
}
protected KalturaFlavorParamsService flavorParamsService;
public KalturaFlavorParamsService getFlavorParamsService() {
if(this.flavorParamsService == null)
this.flavorParamsService = new KalturaFlavorParamsService(this);
return this.flavorParamsService;
}
protected KalturaGroupUserService groupUserService;
public KalturaGroupUserService getGroupUserService() {
if(this.groupUserService == null)
this.groupUserService = new KalturaGroupUserService(this);
return this.groupUserService;
}
protected KalturaLiveChannelSegmentService liveChannelSegmentService;
public KalturaLiveChannelSegmentService getLiveChannelSegmentService() {
if(this.liveChannelSegmentService == null)
this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this);
return this.liveChannelSegmentService;
}
protected KalturaLiveChannelService liveChannelService;
public KalturaLiveChannelService getLiveChannelService() {
if(this.liveChannelService == null)
this.liveChannelService = new KalturaLiveChannelService(this);
return this.liveChannelService;
}
protected KalturaLiveReportsService liveReportsService;
public KalturaLiveReportsService getLiveReportsService() {
if(this.liveReportsService == null)
this.liveReportsService = new KalturaLiveReportsService(this);
return this.liveReportsService;
}
protected KalturaLiveStatsService liveStatsService;
public KalturaLiveStatsService getLiveStatsService() {
if(this.liveStatsService == null)
this.liveStatsService = new KalturaLiveStatsService(this);
return this.liveStatsService;
}
protected KalturaLiveStreamService liveStreamService;
public KalturaLiveStreamService getLiveStreamService() {
if(this.liveStreamService == null)
this.liveStreamService = new KalturaLiveStreamService(this);
return this.liveStreamService;
}
protected KalturaMediaInfoService mediaInfoService;
public KalturaMediaInfoService getMediaInfoService() {
if(this.mediaInfoService == null)
this.mediaInfoService = new KalturaMediaInfoService(this);
return this.mediaInfoService;
}
protected KalturaMediaService mediaService;
public KalturaMediaService getMediaService() {
if(this.mediaService == null)
this.mediaService = new KalturaMediaService(this);
return this.mediaService;
}
protected KalturaMixingService mixingService;
public KalturaMixingService getMixingService() {
if(this.mixingService == null)
this.mixingService = new KalturaMixingService(this);
return this.mixingService;
}
protected KalturaNotificationService notificationService;
public KalturaNotificationService getNotificationService() {
if(this.notificationService == null)
this.notificationService = new KalturaNotificationService(this);
return this.notificationService;
}
protected KalturaPartnerService partnerService;
public KalturaPartnerService getPartnerService() {
if(this.partnerService == null)
this.partnerService = new KalturaPartnerService(this);
return this.partnerService;
}
protected KalturaPermissionItemService permissionItemService;
public KalturaPermissionItemService getPermissionItemService() {
if(this.permissionItemService == null)
this.permissionItemService = new KalturaPermissionItemService(this);
return this.permissionItemService;
}
protected KalturaPermissionService permissionService;
public KalturaPermissionService getPermissionService() {
if(this.permissionService == null)
this.permissionService = new KalturaPermissionService(this);
return this.permissionService;
}
protected KalturaPlaylistService playlistService;
public KalturaPlaylistService getPlaylistService() {
if(this.playlistService == null)
this.playlistService = new KalturaPlaylistService(this);
return this.playlistService;
}
protected KalturaReportService reportService;
public KalturaReportService getReportService() {
if(this.reportService == null)
this.reportService = new KalturaReportService(this);
return this.reportService;
}
protected KalturaResponseProfileService responseProfileService;
public KalturaResponseProfileService getResponseProfileService() {
if(this.responseProfileService == null)
this.responseProfileService = new KalturaResponseProfileService(this);
return this.responseProfileService;
}
protected KalturaSchemaService schemaService;
public KalturaSchemaService getSchemaService() {
if(this.schemaService == null)
this.schemaService = new KalturaSchemaService(this);
return this.schemaService;
}
protected KalturaSearchService searchService;
public KalturaSearchService getSearchService() {
if(this.searchService == null)
this.searchService = new KalturaSearchService(this);
return this.searchService;
}
protected KalturaServerNodeService serverNodeService;
public KalturaServerNodeService getServerNodeService() {
if(this.serverNodeService == null)
this.serverNodeService = new KalturaServerNodeService(this);
return this.serverNodeService;
}
protected KalturaSessionService sessionService;
public KalturaSessionService getSessionService() {
if(this.sessionService == null)
this.sessionService = new KalturaSessionService(this);
return this.sessionService;
}
protected KalturaStatsService statsService;
public KalturaStatsService getStatsService() {
if(this.statsService == null)
this.statsService = new KalturaStatsService(this);
return this.statsService;
}
protected KalturaStorageProfileService storageProfileService;
public KalturaStorageProfileService getStorageProfileService() {
if(this.storageProfileService == null)
this.storageProfileService = new KalturaStorageProfileService(this);
return this.storageProfileService;
}
protected KalturaSyndicationFeedService syndicationFeedService;
public KalturaSyndicationFeedService getSyndicationFeedService() {
if(this.syndicationFeedService == null)
this.syndicationFeedService = new KalturaSyndicationFeedService(this);
return this.syndicationFeedService;
}
protected KalturaSystemService systemService;
public KalturaSystemService getSystemService() {
if(this.systemService == null)
this.systemService = new KalturaSystemService(this);
return this.systemService;
}
protected KalturaThumbAssetService thumbAssetService;
public KalturaThumbAssetService getThumbAssetService() {
if(this.thumbAssetService == null)
this.thumbAssetService = new KalturaThumbAssetService(this);
return this.thumbAssetService;
}
protected KalturaThumbParamsOutputService thumbParamsOutputService;
public KalturaThumbParamsOutputService getThumbParamsOutputService() {
if(this.thumbParamsOutputService == null)
this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this);
return this.thumbParamsOutputService;
}
protected KalturaThumbParamsService thumbParamsService;
public KalturaThumbParamsService getThumbParamsService() {
if(this.thumbParamsService == null)
this.thumbParamsService = new KalturaThumbParamsService(this);
return this.thumbParamsService;
}
protected KalturaUiConfService uiConfService;
public KalturaUiConfService getUiConfService() {
if(this.uiConfService == null)
this.uiConfService = new KalturaUiConfService(this);
return this.uiConfService;
}
protected KalturaUploadService uploadService;
public KalturaUploadService getUploadService() {
if(this.uploadService == null)
this.uploadService = new KalturaUploadService(this);
return this.uploadService;
}
protected KalturaUploadTokenService uploadTokenService;
public KalturaUploadTokenService getUploadTokenService() {
if(this.uploadTokenService == null)
this.uploadTokenService = new KalturaUploadTokenService(this);
return this.uploadTokenService;
}
protected KalturaUserEntryService userEntryService;
public KalturaUserEntryService getUserEntryService() {
if(this.userEntryService == null)
this.userEntryService = new KalturaUserEntryService(this);
return this.userEntryService;
}
protected KalturaUserRoleService userRoleService;
public KalturaUserRoleService getUserRoleService() {
if(this.userRoleService == null)
this.userRoleService = new KalturaUserRoleService(this);
return this.userRoleService;
}
protected KalturaUserService userService;
public KalturaUserService getUserService() {
if(this.userService == null)
this.userService = new KalturaUserService(this);
return this.userService;
}
protected KalturaWidgetService widgetService;
public KalturaWidgetService getWidgetService() {
if(this.widgetService == null)
this.widgetService = new KalturaWidgetService(this);
return this.widgetService;
}
protected KalturaMetadataService metadataService;
public KalturaMetadataService getMetadataService() {
if(this.metadataService == null)
this.metadataService = new KalturaMetadataService(this);
return this.metadataService;
}
protected KalturaMetadataProfileService metadataProfileService;
public KalturaMetadataProfileService getMetadataProfileService() {
if(this.metadataProfileService == null)
this.metadataProfileService = new KalturaMetadataProfileService(this);
return this.metadataProfileService;
}
protected KalturaDocumentsService documentsService;
public KalturaDocumentsService getDocumentsService() {
if(this.documentsService == null)
this.documentsService = new KalturaDocumentsService(this);
return this.documentsService;
}
protected KalturaVirusScanProfileService virusScanProfileService;
public KalturaVirusScanProfileService getVirusScanProfileService() {
if(this.virusScanProfileService == null)
this.virusScanProfileService = new KalturaVirusScanProfileService(this);
return this.virusScanProfileService;
}
protected KalturaDistributionProfileService distributionProfileService;
public KalturaDistributionProfileService getDistributionProfileService() {
if(this.distributionProfileService == null)
this.distributionProfileService = new KalturaDistributionProfileService(this);
return this.distributionProfileService;
}
protected KalturaEntryDistributionService entryDistributionService;
public KalturaEntryDistributionService getEntryDistributionService() {
if(this.entryDistributionService == null)
this.entryDistributionService = new KalturaEntryDistributionService(this);
return this.entryDistributionService;
}
protected KalturaDistributionProviderService distributionProviderService;
public KalturaDistributionProviderService getDistributionProviderService() {
if(this.distributionProviderService == null)
this.distributionProviderService = new KalturaDistributionProviderService(this);
return this.distributionProviderService;
}
protected KalturaGenericDistributionProviderService genericDistributionProviderService;
public KalturaGenericDistributionProviderService getGenericDistributionProviderService() {
if(this.genericDistributionProviderService == null)
this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this);
return this.genericDistributionProviderService;
}
protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService;
public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() {
if(this.genericDistributionProviderActionService == null)
this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this);
return this.genericDistributionProviderActionService;
}
protected KalturaCuePointService cuePointService;
public KalturaCuePointService getCuePointService() {
if(this.cuePointService == null)
this.cuePointService = new KalturaCuePointService(this);
return this.cuePointService;
}
protected KalturaAnnotationService annotationService;
public KalturaAnnotationService getAnnotationService() {
if(this.annotationService == null)
this.annotationService = new KalturaAnnotationService(this);
return this.annotationService;
}
protected KalturaQuizService quizService;
public KalturaQuizService getQuizService() {
if(this.quizService == null)
this.quizService = new KalturaQuizService(this);
return this.quizService;
}
protected KalturaShortLinkService shortLinkService;
public KalturaShortLinkService getShortLinkService() {
if(this.shortLinkService == null)
this.shortLinkService = new KalturaShortLinkService(this);
return this.shortLinkService;
}
protected KalturaBulkService bulkService;
public KalturaBulkService getBulkService() {
if(this.bulkService == null)
this.bulkService = new KalturaBulkService(this);
return this.bulkService;
}
protected KalturaDropFolderService dropFolderService;
public KalturaDropFolderService getDropFolderService() {
if(this.dropFolderService == null)
this.dropFolderService = new KalturaDropFolderService(this);
return this.dropFolderService;
}
protected KalturaDropFolderFileService dropFolderFileService;
public KalturaDropFolderFileService getDropFolderFileService() {
if(this.dropFolderFileService == null)
this.dropFolderFileService = new KalturaDropFolderFileService(this);
return this.dropFolderFileService;
}
protected KalturaCaptionAssetService captionAssetService;
public KalturaCaptionAssetService getCaptionAssetService() {
if(this.captionAssetService == null)
this.captionAssetService = new KalturaCaptionAssetService(this);
return this.captionAssetService;
}
protected KalturaCaptionParamsService captionParamsService;
public KalturaCaptionParamsService getCaptionParamsService() {
if(this.captionParamsService == null)
this.captionParamsService = new KalturaCaptionParamsService(this);
return this.captionParamsService;
}
protected KalturaCaptionAssetItemService captionAssetItemService;
public KalturaCaptionAssetItemService getCaptionAssetItemService() {
if(this.captionAssetItemService == null)
this.captionAssetItemService = new KalturaCaptionAssetItemService(this);
return this.captionAssetItemService;
}
protected KalturaAttachmentAssetService attachmentAssetService;
public KalturaAttachmentAssetService getAttachmentAssetService() {
if(this.attachmentAssetService == null)
this.attachmentAssetService = new KalturaAttachmentAssetService(this);
return this.attachmentAssetService;
}
protected KalturaTagService tagService;
public KalturaTagService getTagService() {
if(this.tagService == null)
this.tagService = new KalturaTagService(this);
return this.tagService;
}
protected KalturaLikeService likeService;
public KalturaLikeService getLikeService() {
if(this.likeService == null)
this.likeService = new KalturaLikeService(this);
return this.likeService;
}
protected KalturaVarConsoleService varConsoleService;
public KalturaVarConsoleService getVarConsoleService() {
if(this.varConsoleService == null)
this.varConsoleService = new KalturaVarConsoleService(this);
return this.varConsoleService;
}
protected KalturaEventNotificationTemplateService eventNotificationTemplateService;
public KalturaEventNotificationTemplateService getEventNotificationTemplateService() {
if(this.eventNotificationTemplateService == null)
this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this);
return this.eventNotificationTemplateService;
}
protected KalturaExternalMediaService externalMediaService;
public KalturaExternalMediaService getExternalMediaService() {
if(this.externalMediaService == null)
this.externalMediaService = new KalturaExternalMediaService(this);
return this.externalMediaService;
}
protected KalturaScheduleEventService scheduleEventService;
public KalturaScheduleEventService getScheduleEventService() {
if(this.scheduleEventService == null)
this.scheduleEventService = new KalturaScheduleEventService(this);
return this.scheduleEventService;
}
protected KalturaScheduleResourceService scheduleResourceService;
public KalturaScheduleResourceService getScheduleResourceService() {
if(this.scheduleResourceService == null)
this.scheduleResourceService = new KalturaScheduleResourceService(this);
return this.scheduleResourceService;
}
protected KalturaScheduleEventResourceService scheduleEventResourceService;
public KalturaScheduleEventResourceService getScheduleEventResourceService() {
if(this.scheduleEventResourceService == null)
this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this);
return this.scheduleEventResourceService;
}
protected KalturaScheduledTaskProfileService scheduledTaskProfileService;
public KalturaScheduledTaskProfileService getScheduledTaskProfileService() {
if(this.scheduledTaskProfileService == null)
this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this);
return this.scheduledTaskProfileService;
}
protected KalturaIntegrationService integrationService;
public KalturaIntegrationService getIntegrationService() {
if(this.integrationService == null)
this.integrationService = new KalturaIntegrationService(this);
return this.integrationService;
}
/**
* @param String $clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return (String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param String $apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return (String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param Integer $partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return (Integer) this.requestConfiguration.get("partnerId");
}
return null;
}
/**
* Kaltura API session
*
* @param String $ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param String $sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param KalturaBaseResponseProfile $responseProfile
*/
public void setResponseProfile(KalturaBaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return KalturaBaseResponseProfile
*/
public KalturaBaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
/**
* Clear all volatile configuration parameters
*/
protected void resetRequest(){
this.requestConfiguration.remove("responseProfile");
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.services.KalturaAccessControlProfileService;
import com.kaltura.client.services.KalturaAccessControlService;
import com.kaltura.client.services.KalturaAdminUserService;
import com.kaltura.client.services.KalturaAppTokenService;
import com.kaltura.client.services.KalturaBaseEntryService;
import com.kaltura.client.services.KalturaBulkUploadService;
import com.kaltura.client.services.KalturaCategoryEntryService;
import com.kaltura.client.services.KalturaCategoryService;
import com.kaltura.client.services.KalturaCategoryUserService;
import com.kaltura.client.services.KalturaConversionProfileAssetParamsService;
import com.kaltura.client.services.KalturaConversionProfileService;
import com.kaltura.client.services.KalturaDataService;
import com.kaltura.client.services.KalturaDeliveryProfileService;
import com.kaltura.client.services.KalturaDocumentService;
import com.kaltura.client.services.KalturaEdgeServerService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
import com.kaltura.client.services.KalturaFileAssetService;
import com.kaltura.client.services.KalturaFlavorAssetService;
import com.kaltura.client.services.KalturaFlavorParamsOutputService;
import com.kaltura.client.services.KalturaFlavorParamsService;
import com.kaltura.client.services.KalturaGroupUserService;
import com.kaltura.client.services.KalturaLiveChannelSegmentService;
import com.kaltura.client.services.KalturaLiveChannelService;
import com.kaltura.client.services.KalturaLiveReportsService;
import com.kaltura.client.services.KalturaLiveStatsService;
import com.kaltura.client.services.KalturaLiveStreamService;
import com.kaltura.client.services.KalturaMediaInfoService;
import com.kaltura.client.services.KalturaMediaServerService;
import com.kaltura.client.services.KalturaMediaService;
import com.kaltura.client.services.KalturaMixingService;
import com.kaltura.client.services.KalturaNotificationService;
import com.kaltura.client.services.KalturaPartnerService;
import com.kaltura.client.services.KalturaPermissionItemService;
import com.kaltura.client.services.KalturaPermissionService;
import com.kaltura.client.services.KalturaPlaylistService;
import com.kaltura.client.services.KalturaReportService;
import com.kaltura.client.services.KalturaResponseProfileService;
import com.kaltura.client.services.KalturaSchemaService;
import com.kaltura.client.services.KalturaSearchService;
import com.kaltura.client.services.KalturaSessionService;
import com.kaltura.client.services.KalturaStatsService;
import com.kaltura.client.services.KalturaStorageProfileService;
import com.kaltura.client.services.KalturaSyndicationFeedService;
import com.kaltura.client.services.KalturaSystemService;
import com.kaltura.client.services.KalturaThumbAssetService;
import com.kaltura.client.services.KalturaThumbParamsOutputService;
import com.kaltura.client.services.KalturaThumbParamsService;
import com.kaltura.client.services.KalturaUiConfService;
import com.kaltura.client.services.KalturaUploadService;
import com.kaltura.client.services.KalturaUploadTokenService;
import com.kaltura.client.services.KalturaUserEntryService;
import com.kaltura.client.services.KalturaUserRoleService;
import com.kaltura.client.services.KalturaUserService;
import com.kaltura.client.services.KalturaWidgetService;
import com.kaltura.client.services.KalturaXInternalService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaSystemPartnerService;
import com.kaltura.client.services.KalturaEntryAdminService;
import com.kaltura.client.services.KalturaUiConfAdminService;
import com.kaltura.client.services.KalturaReportAdminService;
import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService;
import com.kaltura.client.services.KalturaVirusScanProfileService;
import com.kaltura.client.services.KalturaDistributionProfileService;
import com.kaltura.client.services.KalturaEntryDistributionService;
import com.kaltura.client.services.KalturaDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderActionService;
import com.kaltura.client.services.KalturaCuePointService;
import com.kaltura.client.services.KalturaAnnotationService;
import com.kaltura.client.services.KalturaQuizService;
import com.kaltura.client.services.KalturaShortLinkService;
import com.kaltura.client.services.KalturaBulkService;
import com.kaltura.client.services.KalturaDropFolderService;
import com.kaltura.client.services.KalturaDropFolderFileService;
import com.kaltura.client.services.KalturaCaptionAssetService;
import com.kaltura.client.services.KalturaCaptionParamsService;
import com.kaltura.client.services.KalturaCaptionAssetItemService;
import com.kaltura.client.services.KalturaAttachmentAssetService;
import com.kaltura.client.services.KalturaTagService;
import com.kaltura.client.services.KalturaLikeService;
import com.kaltura.client.services.KalturaVarConsoleService;
import com.kaltura.client.services.KalturaEventNotificationTemplateService;
import com.kaltura.client.services.KalturaExternalMediaService;
import com.kaltura.client.services.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaClient extends KalturaClientBase {
public KalturaClient(KalturaConfiguration config) {
super(config);
this.setClientTag("java:15-10-19");
this.setApiVersion("3.3.0");
}
protected KalturaAccessControlProfileService accessControlProfileService;
public KalturaAccessControlProfileService getAccessControlProfileService() {
if(this.accessControlProfileService == null)
this.accessControlProfileService = new KalturaAccessControlProfileService(this);
return this.accessControlProfileService;
}
protected KalturaAccessControlService accessControlService;
public KalturaAccessControlService getAccessControlService() {
if(this.accessControlService == null)
this.accessControlService = new KalturaAccessControlService(this);
return this.accessControlService;
}
protected KalturaAdminUserService adminUserService;
public KalturaAdminUserService getAdminUserService() {
if(this.adminUserService == null)
this.adminUserService = new KalturaAdminUserService(this);
return this.adminUserService;
}
protected KalturaAppTokenService appTokenService;
public KalturaAppTokenService getAppTokenService() {
if(this.appTokenService == null)
this.appTokenService = new KalturaAppTokenService(this);
return this.appTokenService;
}
protected KalturaBaseEntryService baseEntryService;
public KalturaBaseEntryService getBaseEntryService() {
if(this.baseEntryService == null)
this.baseEntryService = new KalturaBaseEntryService(this);
return this.baseEntryService;
}
protected KalturaBulkUploadService bulkUploadService;
public KalturaBulkUploadService getBulkUploadService() {
if(this.bulkUploadService == null)
this.bulkUploadService = new KalturaBulkUploadService(this);
return this.bulkUploadService;
}
protected KalturaCategoryEntryService categoryEntryService;
public KalturaCategoryEntryService getCategoryEntryService() {
if(this.categoryEntryService == null)
this.categoryEntryService = new KalturaCategoryEntryService(this);
return this.categoryEntryService;
}
protected KalturaCategoryService categoryService;
public KalturaCategoryService getCategoryService() {
if(this.categoryService == null)
this.categoryService = new KalturaCategoryService(this);
return this.categoryService;
}
protected KalturaCategoryUserService categoryUserService;
public KalturaCategoryUserService getCategoryUserService() {
if(this.categoryUserService == null)
this.categoryUserService = new KalturaCategoryUserService(this);
return this.categoryUserService;
}
protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService;
public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() {
if(this.conversionProfileAssetParamsService == null)
this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this);
return this.conversionProfileAssetParamsService;
}
protected KalturaConversionProfileService conversionProfileService;
public KalturaConversionProfileService getConversionProfileService() {
if(this.conversionProfileService == null)
this.conversionProfileService = new KalturaConversionProfileService(this);
return this.conversionProfileService;
}
protected KalturaDataService dataService;
public KalturaDataService getDataService() {
if(this.dataService == null)
this.dataService = new KalturaDataService(this);
return this.dataService;
}
protected KalturaDeliveryProfileService deliveryProfileService;
public KalturaDeliveryProfileService getDeliveryProfileService() {
if(this.deliveryProfileService == null)
this.deliveryProfileService = new KalturaDeliveryProfileService(this);
return this.deliveryProfileService;
}
protected KalturaDocumentService documentService;
public KalturaDocumentService getDocumentService() {
if(this.documentService == null)
this.documentService = new KalturaDocumentService(this);
return this.documentService;
}
protected KalturaEdgeServerService edgeServerService;
public KalturaEdgeServerService getEdgeServerService() {
if(this.edgeServerService == null)
this.edgeServerService = new KalturaEdgeServerService(this);
return this.edgeServerService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
protected KalturaFileAssetService fileAssetService;
public KalturaFileAssetService getFileAssetService() {
if(this.fileAssetService == null)
this.fileAssetService = new KalturaFileAssetService(this);
return this.fileAssetService;
}
protected KalturaFlavorAssetService flavorAssetService;
public KalturaFlavorAssetService getFlavorAssetService() {
if(this.flavorAssetService == null)
this.flavorAssetService = new KalturaFlavorAssetService(this);
return this.flavorAssetService;
}
protected KalturaFlavorParamsOutputService flavorParamsOutputService;
public KalturaFlavorParamsOutputService getFlavorParamsOutputService() {
if(this.flavorParamsOutputService == null)
this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this);
return this.flavorParamsOutputService;
}
protected KalturaFlavorParamsService flavorParamsService;
public KalturaFlavorParamsService getFlavorParamsService() {
if(this.flavorParamsService == null)
this.flavorParamsService = new KalturaFlavorParamsService(this);
return this.flavorParamsService;
}
protected KalturaGroupUserService groupUserService;
public KalturaGroupUserService getGroupUserService() {
if(this.groupUserService == null)
this.groupUserService = new KalturaGroupUserService(this);
return this.groupUserService;
}
protected KalturaLiveChannelSegmentService liveChannelSegmentService;
public KalturaLiveChannelSegmentService getLiveChannelSegmentService() {
if(this.liveChannelSegmentService == null)
this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this);
return this.liveChannelSegmentService;
}
protected KalturaLiveChannelService liveChannelService;
public KalturaLiveChannelService getLiveChannelService() {
if(this.liveChannelService == null)
this.liveChannelService = new KalturaLiveChannelService(this);
return this.liveChannelService;
}
protected KalturaLiveReportsService liveReportsService;
public KalturaLiveReportsService getLiveReportsService() {
if(this.liveReportsService == null)
this.liveReportsService = new KalturaLiveReportsService(this);
return this.liveReportsService;
}
protected KalturaLiveStatsService liveStatsService;
public KalturaLiveStatsService getLiveStatsService() {
if(this.liveStatsService == null)
this.liveStatsService = new KalturaLiveStatsService(this);
return this.liveStatsService;
}
protected KalturaLiveStreamService liveStreamService;
public KalturaLiveStreamService getLiveStreamService() {
if(this.liveStreamService == null)
this.liveStreamService = new KalturaLiveStreamService(this);
return this.liveStreamService;
}
protected KalturaMediaInfoService mediaInfoService;
public KalturaMediaInfoService getMediaInfoService() {
if(this.mediaInfoService == null)
this.mediaInfoService = new KalturaMediaInfoService(this);
return this.mediaInfoService;
}
protected KalturaMediaServerService mediaServerService;
public KalturaMediaServerService getMediaServerService() {
if(this.mediaServerService == null)
this.mediaServerService = new KalturaMediaServerService(this);
return this.mediaServerService;
}
protected KalturaMediaService mediaService;
public KalturaMediaService getMediaService() {
if(this.mediaService == null)
this.mediaService = new KalturaMediaService(this);
return this.mediaService;
}
protected KalturaMixingService mixingService;
public KalturaMixingService getMixingService() {
if(this.mixingService == null)
this.mixingService = new KalturaMixingService(this);
return this.mixingService;
}
protected KalturaNotificationService notificationService;
public KalturaNotificationService getNotificationService() {
if(this.notificationService == null)
this.notificationService = new KalturaNotificationService(this);
return this.notificationService;
}
protected KalturaPartnerService partnerService;
public KalturaPartnerService getPartnerService() {
if(this.partnerService == null)
this.partnerService = new KalturaPartnerService(this);
return this.partnerService;
}
protected KalturaPermissionItemService permissionItemService;
public KalturaPermissionItemService getPermissionItemService() {
if(this.permissionItemService == null)
this.permissionItemService = new KalturaPermissionItemService(this);
return this.permissionItemService;
}
protected KalturaPermissionService permissionService;
public KalturaPermissionService getPermissionService() {
if(this.permissionService == null)
this.permissionService = new KalturaPermissionService(this);
return this.permissionService;
}
protected KalturaPlaylistService playlistService;
public KalturaPlaylistService getPlaylistService() {
if(this.playlistService == null)
this.playlistService = new KalturaPlaylistService(this);
return this.playlistService;
}
protected KalturaReportService reportService;
public KalturaReportService getReportService() {
if(this.reportService == null)
this.reportService = new KalturaReportService(this);
return this.reportService;
}
protected KalturaResponseProfileService responseProfileService;
public KalturaResponseProfileService getResponseProfileService() {
if(this.responseProfileService == null)
this.responseProfileService = new KalturaResponseProfileService(this);
return this.responseProfileService;
}
protected KalturaSchemaService schemaService;
public KalturaSchemaService getSchemaService() {
if(this.schemaService == null)
this.schemaService = new KalturaSchemaService(this);
return this.schemaService;
}
protected KalturaSearchService searchService;
public KalturaSearchService getSearchService() {
if(this.searchService == null)
this.searchService = new KalturaSearchService(this);
return this.searchService;
}
protected KalturaSessionService sessionService;
public KalturaSessionService getSessionService() {
if(this.sessionService == null)
this.sessionService = new KalturaSessionService(this);
return this.sessionService;
}
protected KalturaStatsService statsService;
public KalturaStatsService getStatsService() {
if(this.statsService == null)
this.statsService = new KalturaStatsService(this);
return this.statsService;
}
protected KalturaStorageProfileService storageProfileService;
public KalturaStorageProfileService getStorageProfileService() {
if(this.storageProfileService == null)
this.storageProfileService = new KalturaStorageProfileService(this);
return this.storageProfileService;
}
protected KalturaSyndicationFeedService syndicationFeedService;
public KalturaSyndicationFeedService getSyndicationFeedService() {
if(this.syndicationFeedService == null)
this.syndicationFeedService = new KalturaSyndicationFeedService(this);
return this.syndicationFeedService;
}
protected KalturaSystemService systemService;
public KalturaSystemService getSystemService() {
if(this.systemService == null)
this.systemService = new KalturaSystemService(this);
return this.systemService;
}
protected KalturaThumbAssetService thumbAssetService;
public KalturaThumbAssetService getThumbAssetService() {
if(this.thumbAssetService == null)
this.thumbAssetService = new KalturaThumbAssetService(this);
return this.thumbAssetService;
}
protected KalturaThumbParamsOutputService thumbParamsOutputService;
public KalturaThumbParamsOutputService getThumbParamsOutputService() {
if(this.thumbParamsOutputService == null)
this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this);
return this.thumbParamsOutputService;
}
protected KalturaThumbParamsService thumbParamsService;
public KalturaThumbParamsService getThumbParamsService() {
if(this.thumbParamsService == null)
this.thumbParamsService = new KalturaThumbParamsService(this);
return this.thumbParamsService;
}
protected KalturaUiConfService uiConfService;
public KalturaUiConfService getUiConfService() {
if(this.uiConfService == null)
this.uiConfService = new KalturaUiConfService(this);
return this.uiConfService;
}
protected KalturaUploadService uploadService;
public KalturaUploadService getUploadService() {
if(this.uploadService == null)
this.uploadService = new KalturaUploadService(this);
return this.uploadService;
}
protected KalturaUploadTokenService uploadTokenService;
public KalturaUploadTokenService getUploadTokenService() {
if(this.uploadTokenService == null)
this.uploadTokenService = new KalturaUploadTokenService(this);
return this.uploadTokenService;
}
protected KalturaUserEntryService userEntryService;
public KalturaUserEntryService getUserEntryService() {
if(this.userEntryService == null)
this.userEntryService = new KalturaUserEntryService(this);
return this.userEntryService;
}
protected KalturaUserRoleService userRoleService;
public KalturaUserRoleService getUserRoleService() {
if(this.userRoleService == null)
this.userRoleService = new KalturaUserRoleService(this);
return this.userRoleService;
}
protected KalturaUserService userService;
public KalturaUserService getUserService() {
if(this.userService == null)
this.userService = new KalturaUserService(this);
return this.userService;
}
protected KalturaWidgetService widgetService;
public KalturaWidgetService getWidgetService() {
if(this.widgetService == null)
this.widgetService = new KalturaWidgetService(this);
return this.widgetService;
}
protected KalturaXInternalService xInternalService;
public KalturaXInternalService getXInternalService() {
if(this.xInternalService == null)
this.xInternalService = new KalturaXInternalService(this);
return this.xInternalService;
}
protected KalturaMetadataService metadataService;
public KalturaMetadataService getMetadataService() {
if(this.metadataService == null)
this.metadataService = new KalturaMetadataService(this);
return this.metadataService;
}
protected KalturaMetadataProfileService metadataProfileService;
public KalturaMetadataProfileService getMetadataProfileService() {
if(this.metadataProfileService == null)
this.metadataProfileService = new KalturaMetadataProfileService(this);
return this.metadataProfileService;
}
protected KalturaDocumentsService documentsService;
public KalturaDocumentsService getDocumentsService() {
if(this.documentsService == null)
this.documentsService = new KalturaDocumentsService(this);
return this.documentsService;
}
protected KalturaSystemPartnerService systemPartnerService;
public KalturaSystemPartnerService getSystemPartnerService() {
if(this.systemPartnerService == null)
this.systemPartnerService = new KalturaSystemPartnerService(this);
return this.systemPartnerService;
}
protected KalturaEntryAdminService entryAdminService;
public KalturaEntryAdminService getEntryAdminService() {
if(this.entryAdminService == null)
this.entryAdminService = new KalturaEntryAdminService(this);
return this.entryAdminService;
}
protected KalturaUiConfAdminService uiConfAdminService;
public KalturaUiConfAdminService getUiConfAdminService() {
if(this.uiConfAdminService == null)
this.uiConfAdminService = new KalturaUiConfAdminService(this);
return this.uiConfAdminService;
}
protected KalturaReportAdminService reportAdminService;
public KalturaReportAdminService getReportAdminService() {
if(this.reportAdminService == null)
this.reportAdminService = new KalturaReportAdminService(this);
return this.reportAdminService;
}
protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService;
public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() {
if(this.kalturaInternalToolsSystemHelperService == null)
this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this);
return this.kalturaInternalToolsSystemHelperService;
}
protected KalturaVirusScanProfileService virusScanProfileService;
public KalturaVirusScanProfileService getVirusScanProfileService() {
if(this.virusScanProfileService == null)
this.virusScanProfileService = new KalturaVirusScanProfileService(this);
return this.virusScanProfileService;
}
protected KalturaDistributionProfileService distributionProfileService;
public KalturaDistributionProfileService getDistributionProfileService() {
if(this.distributionProfileService == null)
this.distributionProfileService = new KalturaDistributionProfileService(this);
return this.distributionProfileService;
}
protected KalturaEntryDistributionService entryDistributionService;
public KalturaEntryDistributionService getEntryDistributionService() {
if(this.entryDistributionService == null)
this.entryDistributionService = new KalturaEntryDistributionService(this);
return this.entryDistributionService;
}
protected KalturaDistributionProviderService distributionProviderService;
public KalturaDistributionProviderService getDistributionProviderService() {
if(this.distributionProviderService == null)
this.distributionProviderService = new KalturaDistributionProviderService(this);
return this.distributionProviderService;
}
protected KalturaGenericDistributionProviderService genericDistributionProviderService;
public KalturaGenericDistributionProviderService getGenericDistributionProviderService() {
if(this.genericDistributionProviderService == null)
this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this);
return this.genericDistributionProviderService;
}
protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService;
public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() {
if(this.genericDistributionProviderActionService == null)
this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this);
return this.genericDistributionProviderActionService;
}
protected KalturaCuePointService cuePointService;
public KalturaCuePointService getCuePointService() {
if(this.cuePointService == null)
this.cuePointService = new KalturaCuePointService(this);
return this.cuePointService;
}
protected KalturaAnnotationService annotationService;
public KalturaAnnotationService getAnnotationService() {
if(this.annotationService == null)
this.annotationService = new KalturaAnnotationService(this);
return this.annotationService;
}
protected KalturaQuizService quizService;
public KalturaQuizService getQuizService() {
if(this.quizService == null)
this.quizService = new KalturaQuizService(this);
return this.quizService;
}
protected KalturaShortLinkService shortLinkService;
public KalturaShortLinkService getShortLinkService() {
if(this.shortLinkService == null)
this.shortLinkService = new KalturaShortLinkService(this);
return this.shortLinkService;
}
protected KalturaBulkService bulkService;
public KalturaBulkService getBulkService() {
if(this.bulkService == null)
this.bulkService = new KalturaBulkService(this);
return this.bulkService;
}
protected KalturaDropFolderService dropFolderService;
public KalturaDropFolderService getDropFolderService() {
if(this.dropFolderService == null)
this.dropFolderService = new KalturaDropFolderService(this);
return this.dropFolderService;
}
protected KalturaDropFolderFileService dropFolderFileService;
public KalturaDropFolderFileService getDropFolderFileService() {
if(this.dropFolderFileService == null)
this.dropFolderFileService = new KalturaDropFolderFileService(this);
return this.dropFolderFileService;
}
protected KalturaCaptionAssetService captionAssetService;
public KalturaCaptionAssetService getCaptionAssetService() {
if(this.captionAssetService == null)
this.captionAssetService = new KalturaCaptionAssetService(this);
return this.captionAssetService;
}
protected KalturaCaptionParamsService captionParamsService;
public KalturaCaptionParamsService getCaptionParamsService() {
if(this.captionParamsService == null)
this.captionParamsService = new KalturaCaptionParamsService(this);
return this.captionParamsService;
}
protected KalturaCaptionAssetItemService captionAssetItemService;
public KalturaCaptionAssetItemService getCaptionAssetItemService() {
if(this.captionAssetItemService == null)
this.captionAssetItemService = new KalturaCaptionAssetItemService(this);
return this.captionAssetItemService;
}
protected KalturaAttachmentAssetService attachmentAssetService;
public KalturaAttachmentAssetService getAttachmentAssetService() {
if(this.attachmentAssetService == null)
this.attachmentAssetService = new KalturaAttachmentAssetService(this);
return this.attachmentAssetService;
}
protected KalturaTagService tagService;
public KalturaTagService getTagService() {
if(this.tagService == null)
this.tagService = new KalturaTagService(this);
return this.tagService;
}
protected KalturaLikeService likeService;
public KalturaLikeService getLikeService() {
if(this.likeService == null)
this.likeService = new KalturaLikeService(this);
return this.likeService;
}
protected KalturaVarConsoleService varConsoleService;
public KalturaVarConsoleService getVarConsoleService() {
if(this.varConsoleService == null)
this.varConsoleService = new KalturaVarConsoleService(this);
return this.varConsoleService;
}
protected KalturaEventNotificationTemplateService eventNotificationTemplateService;
public KalturaEventNotificationTemplateService getEventNotificationTemplateService() {
if(this.eventNotificationTemplateService == null)
this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this);
return this.eventNotificationTemplateService;
}
protected KalturaExternalMediaService externalMediaService;
public KalturaExternalMediaService getExternalMediaService() {
if(this.externalMediaService == null)
this.externalMediaService = new KalturaExternalMediaService(this);
return this.externalMediaService;
}
protected KalturaScheduledTaskProfileService scheduledTaskProfileService;
public KalturaScheduledTaskProfileService getScheduledTaskProfileService() {
if(this.scheduledTaskProfileService == null)
this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this);
return this.scheduledTaskProfileService;
}
protected KalturaIntegrationService integrationService;
public KalturaIntegrationService getIntegrationService() {
if(this.integrationService == null)
this.integrationService = new KalturaIntegrationService(this);
return this.integrationService;
}
/**
* @param String $clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return (String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param String $apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return (String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param Integer $partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return (Integer) this.requestConfiguration.get("partnerId");
}
return null;
}
/**
* Kaltura API session
*
* @param String $ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param String $sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param KalturaBaseResponseProfile $responseProfile
*/
public void setResponseProfile(KalturaBaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return KalturaBaseResponseProfile
*/
public KalturaBaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
/**
* Clear all volatile configuration parameters
*/
protected void resetRequest(){
this.requestConfiguration.remove("responseProfile");
}
} |
package org.nuxeo.ecm.platform.pictures.tiles.service;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.platform.picture.api.ImageInfo;
import org.nuxeo.ecm.platform.picture.magick.utils.ImageConverter;
import org.nuxeo.ecm.platform.pictures.tiles.api.PictureTiles;
import org.nuxeo.ecm.platform.pictures.tiles.api.PictureTilesImpl;
import org.nuxeo.ecm.platform.pictures.tiles.api.PictureTilingService;
import org.nuxeo.ecm.platform.pictures.tiles.api.imageresource.BlobResource;
import org.nuxeo.ecm.platform.pictures.tiles.api.imageresource.ImageResource;
import org.nuxeo.ecm.platform.pictures.tiles.gimp.tiler.GimpTiler;
import org.nuxeo.ecm.platform.pictures.tiles.magick.tiler.MagickTiler;
import org.nuxeo.ecm.platform.pictures.tiles.tilers.PictureTiler;
import org.nuxeo.runtime.model.ComponentContext;
import org.nuxeo.runtime.model.ComponentInstance;
import org.nuxeo.runtime.model.DefaultComponent;
/**
* Runtime component that expose the PictureTilingService interface. Also
* exposes the configuration Extension Point
*
* @author tiry
*/
public class PictureTilingComponent extends DefaultComponent implements
PictureTilingService {
public static final String ENV_PARAMETERS_EP = "environment";
public static final String BLOB_PROPERTY_EP = "blobProperties";
public static final String IMAGES_TO_CONVERT_EP = "imagesToConvert";
protected static Map<String, PictureTilingCacheInfo> cache = new HashMap<String, PictureTilingCacheInfo>();
protected static List<String> inprocessTiles = Collections.synchronizedList(new ArrayList<String>());
protected static PictureTiler defaultTiler = new MagickTiler();
protected static List<PictureTiler> availableTilers = new ArrayList<PictureTiler>();
protected static Map<String, String> envParameters = new HashMap<String, String>();
protected Map<String, String> blobProperties = new HashMap<String, String>();
protected List<ImageToConvertDescriptor> imagesToConvert = new ArrayList<ImageToConvertDescriptor>();
protected static Thread gcThread;
private String workingDirPath;
private static final Log log = LogFactory.getLog(PictureTilingComponent.class);
@Override
public void activate(ComponentContext context) throws Exception {
defaultTiler = new MagickTiler();
availableTilers.add(defaultTiler);
availableTilers.add(new GimpTiler());
startGC();
}
public static void startGC() {
if (!GCTask.GCEnabled) {
GCTask.GCEnabled = true;
log.debug("PictureTilingComponent activated starting GC thread");
gcThread = new Thread(new GCTask(), "Nuxeo-Tiling-GC");
gcThread.setDaemon(true);
gcThread.start();
log.debug("GC Thread started");
} else {
log.debug("GC Thread is already started");
}
}
public static void endGC() {
if (GCTask.GCEnabled) {
GCTask.GCEnabled = false;
log.debug("Stopping GC Thread");
gcThread.interrupt();
} else {
log.debug("GC Thread is already stopped");
}
}
public void deactivate(ComponentContext context) throws Exception {
endGC();
}
public static Map<String, PictureTilingCacheInfo> getCache() {
return cache;
}
protected String getWorkingDirPath() {
if (workingDirPath != null) {
return workingDirPath;
}
// FIXME: condition always true. What was intended?
if (workingDirPath == null || "".equals(workingDirPath)) {
workingDirPath = getEnvValue("WorkingDirPath",
System.getProperty("java.io.tmpdir")
+ "/nuxeo-tiling-cache");
File workingDir = new File(workingDirPath);
if (!workingDir.exists()) {
workingDir.mkdir();
}
}
if (!workingDirPath.endsWith("/")) {
workingDirPath += "/";
}
log.debug("Setting working dirPath to" + workingDirPath);
return workingDirPath;
}
public void setWorkingDirPath(String path) {
workingDirPath = path;
}
protected String getWorkingDirPathForRessource(ImageResource resource) {
String pathForBlob = getWorkingDirPath();
String digest;
try {
digest = resource.getHash();
} catch (ClientException e) {
digest = "tmp" + System.currentTimeMillis();
}
pathForBlob = pathForBlob + digest + "/";
log.debug("WorkingDirPath for resource=" + pathForBlob);
File wdir = new File(pathForBlob);
if (!wdir.exists()) {
wdir.mkdir();
}
return pathForBlob;
}
@Deprecated
public PictureTiles getTilesFromBlob(Blob blob, int tileWidth,
int tileHeight, int maxTiles) throws ClientException {
return getTilesFromBlob(blob, tileWidth, tileHeight, maxTiles, 0, 0,
false);
}
public PictureTiles getTiles(ImageResource resource, int tileWidth,
int tileHeight, int maxTiles) throws ClientException {
return getTiles(resource, tileWidth, tileHeight, maxTiles, 0, 0, false);
}
public PictureTiles completeTiles(PictureTiles existingTiles, int xCenter,
int yCenter) throws ClientException {
String outputDirPath = existingTiles.getTilesPath();
long lastModificationTime = Long.parseLong(existingTiles.getInfo().get(
PictureTilesImpl.LAST_MODIFICATION_DATE_KEY));
return computeTiles(existingTiles.getSourceImageInfo(), outputDirPath,
existingTiles.getTilesWidth(), existingTiles.getTilesHeight(),
existingTiles.getMaxTiles(), xCenter, yCenter,
lastModificationTime, false);
}
@Deprecated
public PictureTiles getTilesFromBlob(Blob blob, int tileWidth,
int tileHeight, int maxTiles, int xCenter, int yCenter,
boolean fullGeneration) throws ClientException {
ImageResource resource = new BlobResource(blob);
return getTiles(resource, tileWidth, tileHeight, maxTiles, xCenter,
yCenter, fullGeneration);
}
public PictureTiles getTiles(ImageResource resource, int tileWidth,
int tileHeight, int maxTiles, int xCenter, int yCenter,
boolean fullGeneration) throws ClientException {
log.debug("enter getTiles");
String cacheKey = resource.getHash();
if (defaultTiler.needsSync()) {
// some tiler implementation may generate several tiles at once
// in order to be efficient this requires synchronization
while (inprocessTiles.contains(cacheKey)) {
try {
log.debug("Waiting for tiler sync");
Thread.sleep(200);
} catch (InterruptedException e) {
throw new ClientException(
"Error while waiting for another tile processing on the same resource",
e);
}
}
}
PictureTiles tiles = getTilesWithSync(resource, tileWidth, tileHeight,
maxTiles, xCenter, yCenter, fullGeneration);
inprocessTiles.remove(cacheKey);
return tiles;
}
protected PictureTiles getTilesWithSync(ImageResource resource,
int tileWidth, int tileHeight, int maxTiles, int xCenter,
int yCenter, boolean fullGeneration) throws ClientException {
String cacheKey = resource.getHash();
String inputFilePath;
PictureTilingCacheInfo cacheInfo;
if (cache.containsKey(cacheKey)) {
cacheInfo = cache.get(cacheKey);
PictureTiles pt = cacheInfo.getCachedPictureTiles(tileWidth,
tileHeight, maxTiles);
if ((pt != null) && (pt.isTileComputed(xCenter, yCenter))) {
return pt;
}
inputFilePath = cacheInfo.getOriginalPicturePath();
} else {
String wdirPath = getWorkingDirPathForRessource(resource);
inputFilePath = wdirPath;
Blob blob = resource.getBlob();
inputFilePath += Integer.toString(blob.hashCode()) + ".";
if (blob.getFilename() != null) {
inputFilePath += FilenameUtils.getExtension(blob.getFilename());
} else {
inputFilePath += "img";
}
if (needToConvert(blob)) {
inputFilePath = inputFilePath.replaceFirst("\\..*", ".jpg");
}
File inputFile = new File(inputFilePath);
if (!inputFile.exists()) {
try {
// create the empty file ASAP to avoid concurrent transfer
// and conversions
if (inputFile.createNewFile()) {
transferBlob(blob, inputFile);
}
} catch (Exception e) {
String msg = String.format(
"Unable to transfer blob to file at '%s', "
+ "working directory path: '%s'",
inputFilePath, wdirPath);
log.error(msg, e);
throw new ClientException(msg, e);
}
inputFile = new File(inputFilePath);
} else {
while (System.currentTimeMillis() - inputFile.lastModified() < 200) {
try {
log.debug("Waiting concurrent convert / dump");
Thread.sleep(200);
} catch (InterruptedException e) {
throw new ClientException(
"Error while waiting for another converting"
+ " on the same resource", e);
}
}
}
try {
cacheInfo = new PictureTilingCacheInfo(cacheKey, wdirPath,
inputFilePath);
cache.put(cacheKey, cacheInfo);
} catch (Exception e) {
throw new ClientException(e);
}
}
// compute output dir
String outDirPath = cacheInfo.getTilingDir(tileWidth, tileHeight,
maxTiles);
// try to see if a shrinked image can be used
ImageInfo bestImageInfo = cacheInfo.getBestSourceImage(tileWidth,
tileHeight, maxTiles);
inputFilePath = bestImageInfo.getFilePath();
log.debug("input source image path for tile computation="
+ inputFilePath);
long lastModificationTime = resource.getModificationDate().getTimeInMillis();
PictureTiles tiles = computeTiles(bestImageInfo, outDirPath, tileWidth,
tileHeight, maxTiles, xCenter, yCenter, lastModificationTime,
fullGeneration);
tiles.getInfo().put(PictureTilesImpl.MAX_TILES_KEY,
Integer.toString(maxTiles));
tiles.getInfo().put(PictureTilesImpl.TILES_WIDTH_KEY,
Integer.toString(tileWidth));
tiles.getInfo().put(PictureTilesImpl.TILES_HEIGHT_KEY,
Integer.toString(tileHeight));
String lastModificationDate = Long.toString(lastModificationTime);
tiles.getInfo().put(PictureTilesImpl.LAST_MODIFICATION_DATE_KEY,
lastModificationDate);
tiles.setCacheKey(cacheKey);
tiles.setSourceImageInfo(bestImageInfo);
tiles.setOriginalImageInfo(cacheInfo.getOriginalPictureInfos());
cacheInfo.addPictureTilesToCache(tiles);
return tiles;
}
protected void transferBlob(Blob blob, File file) throws Exception {
if (needToConvert(blob)) {
transferAndConvert(blob, file);
} else {
blob.transferTo(file);
}
}
protected boolean needToConvert(Blob blob) {
for (ImageToConvertDescriptor desc : imagesToConvert) {
String extension = getExtension(blob);
if (desc.getMimeType().equalsIgnoreCase(blob.getMimeType())
|| extension.equalsIgnoreCase(desc.getExtension())) {
return true;
}
}
return false;
}
protected String getExtension(Blob blob) {
String filename = blob.getFilename();
if (filename == null) {
return "";
}
int dotIndex = filename.lastIndexOf('.');
if (dotIndex == -1) {
return "";
}
return filename.substring(dotIndex + 1);
}
protected void transferAndConvert(Blob blob, File file) throws Exception {
File tmpFile = new File(file.getAbsolutePath() + ".tmp");
blob.transferTo(tmpFile);
ImageConverter.convert(tmpFile.getAbsolutePath(),
file.getAbsolutePath());
tmpFile.delete();
}
protected PictureTiles computeTiles(ImageInfo input, String outputDirPath,
int tileWidth, int tileHeight, int maxTiles, int xCenter,
int yCenter, long lastModificationTime, boolean fullGeneration)
throws ClientException {
PictureTiler pt = getDefaultTiler();
return pt.getTilesFromFile(input, outputDirPath, tileWidth, tileHeight,
maxTiles, xCenter, yCenter, lastModificationTime,
fullGeneration);
}
protected PictureTiler getDefaultTiler() {
return defaultTiler;
}
// tests
public static void setDefaultTiler(PictureTiler tiler) {
defaultTiler = tiler;
}
// Env setting management
public static Map<String, String> getEnv() {
return envParameters;
}
public static String getEnvValue(String paramName) {
if (envParameters == null) {
return null;
}
return envParameters.get(paramName);
}
public static String getEnvValue(String paramName, String defaultValue) {
String value = getEnvValue(paramName);
if (value == null) {
return defaultValue;
} else {
return value;
}
}
public static void setEnvValue(String paramName, String paramValue) {
envParameters.put(paramName, paramValue);
}
// Blob properties management
public Map<String, String> getBlobProperties() {
return blobProperties;
}
public String getBlobProperty(String docType) {
return blobProperties.get(docType);
}
public String getBlobProperty(String docType, String defaultValue) {
String property = blobProperties.get(docType);
if (property == null) {
return defaultValue;
}
return property;
}
// EP management
public void registerContribution(Object contribution,
String extensionPoint, ComponentInstance contributor)
throws Exception {
if (ENV_PARAMETERS_EP.equals(extensionPoint)) {
TilingConfigurationDescriptor desc = (TilingConfigurationDescriptor) contribution;
envParameters.putAll(desc.getParameters());
} else if (BLOB_PROPERTY_EP.equals(extensionPoint)) {
TilingBlobPropertyDescriptor desc = (TilingBlobPropertyDescriptor) contribution;
blobProperties.putAll(desc.getBlobProperties());
} else if (IMAGES_TO_CONVERT_EP.equals(extensionPoint)) {
ImageToConvertDescriptor desc = (ImageToConvertDescriptor) contribution;
imagesToConvert.add(desc);
}
}
public void unregisterContribution(Object contribution,
String extensionPoint, ComponentInstance contributor)
throws Exception {
// TODO
}
public void removeCacheEntry(ImageResource resource) throws ClientException {
if (cache.containsKey(resource.getHash())) {
PictureTilingCacheInfo cacheInfo = cache.remove(resource.getHash());
cacheInfo.cleanUp();
}
}
} |
package com.safecharge.retail.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Item {
@NotNull(message = "name may not be null!") @Size(min = 1,
max = 255,
message = "name size must be up to 255 characters long!") private String name;
@NotNull(message = "price may not be null!") @Size(min = 1,
max = 10,
message = "price size must be up to 10 characters long!") private String price;
@NotNull(message = "quantity may not be null!") @Size(min = 1,
max = 10,
message = "quantity size must be up to 10 characters long!") private String quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
} |
package org.jboss.hal.testsuite.test.configuration.messaging.remote.activemq.server.connection.factory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeoutException;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.hal.dmr.ModelDescriptionConstants;
import org.jboss.hal.testsuite.Console;
import org.jboss.hal.testsuite.CrudOperations;
import org.jboss.hal.testsuite.Random;
import org.jboss.hal.testsuite.creaper.ManagementClientProvider;
import org.jboss.hal.testsuite.creaper.ResourceVerifier;
import org.jboss.hal.testsuite.dmr.ModelNodeGenerator;
import org.jboss.hal.testsuite.page.configuration.MessagingRemoteActiveMQPage;
import org.jboss.hal.testsuite.test.configuration.jgroups.JGroupsFixtures;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.wildfly.extras.creaper.core.online.OnlineManagementClient;
import org.wildfly.extras.creaper.core.online.operations.Batch;
import org.wildfly.extras.creaper.core.online.operations.OperationException;
import org.wildfly.extras.creaper.core.online.operations.Operations;
import org.wildfly.extras.creaper.core.online.operations.Values;
import org.wildfly.extras.creaper.core.online.operations.admin.Administration;
import static org.jboss.hal.testsuite.test.configuration.messaging.MessagingFixtures.RemoteActiveMQServer;
@RunWith(Arquillian.class)
public class ConnectionFactoryTest {
private static final OnlineManagementClient client = ManagementClientProvider.createOnlineManagementClient();
private static final Operations operations = new Operations(client);
private static final Administration administration = new Administration(client);
private static final String CONNECTION_FACTORY_CREATE = "connection-factory-to-create-" + Random.name();
private static final String CONNECTION_FACTORY_UPDATE = "connection-factory-to-update-" + Random.name();
private static final String CONNECTION_FACTORY_DELETE = "connection-factory-to-delete-" + Random.name();
private static final String DISCOVERY_GROUP_CREATE = "discovery-group-create-" + Random.name();
private static final String DISCOVERY_GROUP_UPDATE = "discovery-group-update-" + Random.name();
private static final String GENERIC_CONNECTOR_UPDATE = "generic-connection-update-" + Random.name();
private static final String JGROUPS_CHANNEL = "jgroups-channel-" + Random.name();
@BeforeClass
public static void setUp() throws IOException, TimeoutException, InterruptedException {
operations.add(JGroupsFixtures.channelAddress(JGROUPS_CHANNEL), Values.of(ModelDescriptionConstants.STACK, "tcp"))
.assertSuccess();
createDiscoveryGroup(DISCOVERY_GROUP_CREATE);
createDiscoveryGroup(DISCOVERY_GROUP_UPDATE);
administration.reloadIfRequired();
createConnectionFactory(CONNECTION_FACTORY_UPDATE, DISCOVERY_GROUP_CREATE);
createConnectionFactory(CONNECTION_FACTORY_DELETE, DISCOVERY_GROUP_CREATE);
createGenericConnector(GENERIC_CONNECTOR_UPDATE);
}
private static void createDiscoveryGroup(String name) throws IOException {
Batch batch = new Batch();
batch.add(RemoteActiveMQServer.discoveryGroupAddress(name));
batch.writeAttribute(RemoteActiveMQServer.discoveryGroupAddress(name), "jgroups-channel", JGROUPS_CHANNEL);
batch.writeAttribute(RemoteActiveMQServer.discoveryGroupAddress(name), "jgroups-cluster", Random.name());
operations.batch(batch).assertSuccess();
}
private static void createConnectionFactory(String name, String discoveryGroup) throws IOException {
operations.add(RemoteActiveMQServer.connectionFactoryAddress(name),
Values.of(ModelDescriptionConstants.DISCOVERY_GROUP, discoveryGroup)
.and("entries",
new ModelNodeGenerator.ModelNodeListBuilder().addAll(Random.name(), Random.name(), Random.name())
.build())).assertSuccess();
}
private static void createGenericConnector(String name) throws IOException {
operations.add(RemoteActiveMQServer.genericConnectorAddress(name), Values.of("factory-class", Random.name()))
.assertSuccess();
}
@AfterClass
public static void tearDown() throws IOException, OperationException {
try {
operations.removeIfExists(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_CREATE));
operations.removeIfExists(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_UPDATE));
operations.removeIfExists(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_DELETE));
operations.removeIfExists(RemoteActiveMQServer.discoveryGroupAddress(DISCOVERY_GROUP_CREATE));
operations.removeIfExists(RemoteActiveMQServer.discoveryGroupAddress(DISCOVERY_GROUP_UPDATE));
operations.removeIfExists(RemoteActiveMQServer.genericConnectorAddress(GENERIC_CONNECTOR_UPDATE));
operations.removeIfExists(JGroupsFixtures.channelAddress(JGROUPS_CHANNEL));
} finally {
client.close();
}
}
@Drone
private WebDriver browser;
@Inject
private Console console;
@Inject
private CrudOperations crudOperations;
@Page
private MessagingRemoteActiveMQPage page;
@Before
public void navigate() {
page.navigate();
console.verticalNavigation().selectPrimary("msg-remote-connection-factory-item");
}
@Test
public void create() throws Exception {
crudOperations.create(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_CREATE),
page.getConnectionFactoryTable(), formFragment -> {
formFragment.text(ModelDescriptionConstants.NAME, CONNECTION_FACTORY_CREATE);
formFragment.list("entries").add(Arrays.asList(Random.name(), Random.name(), Random.name()));
formFragment.text(ModelDescriptionConstants.DISCOVERY_GROUP, DISCOVERY_GROUP_CREATE);
}, ResourceVerifier::verifyExists);
}
@Test
public void remove() throws Exception {
crudOperations.delete(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_DELETE),
page.getConnectionFactoryTable(), CONNECTION_FACTORY_DELETE);
}
@Test
public void editConnectors() throws Exception {
page.getConnectionFactoryTable().select(CONNECTION_FACTORY_UPDATE);
crudOperations.update(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_UPDATE),
page.getConnectionFactoryForm(), formFragment -> {
formFragment.list("connectors").add(Collections.singletonList(GENERIC_CONNECTOR_UPDATE));
formFragment.clear(ModelDescriptionConstants.DISCOVERY_GROUP);
},
resourceVerifier -> resourceVerifier.verifyAttribute("connectors",
new ModelNodeGenerator.ModelNodeListBuilder().addAll(GENERIC_CONNECTOR_UPDATE).build()));
}
@Test
public void editDiscoveryGroup() throws Exception {
page.getConnectionFactoryTable().select(CONNECTION_FACTORY_UPDATE);
crudOperations.update(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_UPDATE),
page.getConnectionFactoryForm(), formFragment -> {
formFragment.text(ModelDescriptionConstants.DISCOVERY_GROUP, DISCOVERY_GROUP_UPDATE);
formFragment.clear("connectors");
}, resourceVerifier -> resourceVerifier.verifyAttribute(ModelDescriptionConstants.DISCOVERY_GROUP,
DISCOVERY_GROUP_UPDATE));
}
@Test
public void editEntries() throws Exception {
page.getConnectionFactoryTable().select(CONNECTION_FACTORY_UPDATE);
crudOperations.update(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_UPDATE),
page.getConnectionFactoryForm(), "entries", Arrays.asList(Random.name(), Random.name()));
}
@Test
public void editFactoryType() throws Exception {
String[] factoryTypes = {"GENERIC", "TOPIC", "QUEUE", "XA_GENERIC", "XA_QUEUE", "XA_TOPIC"};
String factoryType = factoryTypes[Random.number(1, factoryTypes.length)];
page.getConnectionFactoryTable().select(CONNECTION_FACTORY_UPDATE);
crudOperations.update(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_UPDATE),
page.getConnectionFactoryForm(), formFragment -> formFragment.select("factory-type", factoryType),
resourceVerifier -> resourceVerifier.verifyAttribute("factory-type", factoryType));
}
@Test
public void toggleHa() throws Exception {
boolean ha =
operations.readAttribute(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_UPDATE), "ha")
.booleanValue(false);
page.getConnectionFactoryTable().select(CONNECTION_FACTORY_UPDATE);
crudOperations.update(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_UPDATE),
page.getConnectionFactoryForm(), "ha", !ha);
}
@Test
public void toggleAmq1Prefix() throws Exception {
boolean amq1Prefix =
operations.readAttribute(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_UPDATE), "enable-amq1-prefix")
.booleanValue(false);
page.getConnectionFactoryTable().select(CONNECTION_FACTORY_UPDATE);
crudOperations.update(RemoteActiveMQServer.connectionFactoryAddress(CONNECTION_FACTORY_UPDATE),
page.getConnectionFactoryForm(), "enable-amq1-prefix", !amq1Prefix);
}
} |
package com.springapp.batch.bo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* BO used to describe rows found insider the AddressBook
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookEntry {
private String name;
private Gender sex;
private DateTime dateOfBirth;
public BookEntry(String name, String sex, String dateOfBirth) {
this();
setName(name);
setSex(Gender.customValueOf(sex));
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yy");
DateTime parsedDateOfBirth = dateTimeFormatter.parseDateTime(dateOfBirth);
setDateOfBirth(parsedDateOfBirth);
}
} |
package com.timepath.maven;
import com.timepath.IOUtils;
import com.timepath.Utils;
import com.timepath.XMLUtils;
import com.timepath.util.Cache;
import com.timepath.util.concurrent.DaemonThreadFactory;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import java.util.regex.Pattern;
/**
* @author TimePath
*/
public class MavenResolver {
public static final Preferences SETTINGS = Preferences.userRoot().node("timepath");
public static final File CURRENT_FILE = Utils.currentFile(MavenResolver.class);
private static final Collection<String> REPOSITORIES;
private static final String REPO_CENTRAL = "http://repo.maven.apache.org/maven2";
private static final String REPO_JFROG_SNAPSHOTS = "http://oss.jfrog.org/oss-snapshot-local";
private static final String REPO_CUSTOM = "https://dl.dropboxusercontent.com/u/42745598/maven2";
private static final String REPO_JETBRAINS = "http://repository.jetbrains.com/all";
private static final Pattern RE_VERSION = Pattern.compile("(\\d*)\\.(\\d*)\\.(\\d*)");
private static final Logger LOG = Logger.getLogger(MavenResolver.class.getName());
private static final long META_LIFETIME = 7 * 24 * 60 * 60 * 1000; // 1 week
static {
REPOSITORIES = new LinkedHashSet<>();
addRepository(REPO_JFROG_SNAPSHOTS);
addRepository(REPO_CENTRAL);
addRepository(REPO_JETBRAINS);
addRepository(REPO_CUSTOM);
}
/**
* Cache of coordinates to base urls
*/
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection") // Happens behind the scenes
private static final Cache<Coordinate, Future<String>> URL_CACHE = new Cache<Coordinate, Future<String>>() {
@Override
protected Future<String> fill(final Coordinate key) {
LOG.log(Level.INFO, "Resolving baseURL (missed): {0}", key);
final String s = '/' + key.groupId.replace('.', '/') + '/' + key.artifactId + '/' + key.version + '/';
final String classifier = (key.classifier == null || key.classifier.isEmpty()) ? "" : '-' + key.classifier;
return THREAD_POOL.submit(new Callable<String>() {
@Override
public String call() throws Exception {
String url = null;
for (String repository : getRepositories()) {
String base = repository + s;
// TODO: Check version ranges at `new URL(baseArtifact + "maven-metadata.xml")`
if (key.version.endsWith("-SNAPSHOT")) {
try {
if (repository.startsWith("file:"))
continue; // TODO: Handle metadata when using REPO_LOCAL
Node metadata = XMLUtils.rootNode(IOUtils.openStream(base + "maven-metadata.xml"), "metadata");
Node snapshot = XMLUtils.last(XMLUtils.getElements(metadata, "versioning/snapshot"));
String timestamp = XMLUtils.get(snapshot, "timestamp");
String buildNumber = XMLUtils.get(snapshot, "buildNumber");
String versionNumber = key.version.substring(0, key.version.lastIndexOf("-SNAPSHOT"));
String versionSuffix = (buildNumber == null) ? "-SNAPSHOT" : "";
//noinspection ConstantConditions
url = MessageFormat.format("{0}{1}-{2}{3}{4}{5}",
base,
key.artifactId,
versionNumber + versionSuffix,
(timestamp == null) ? "" : ("-" + timestamp),
(buildNumber == null) ? "" : ("-" + buildNumber),
classifier);
} catch (IOException | ParserConfigurationException | SAXException e) {
if (e instanceof FileNotFoundException) {
LOG.log(Level.WARNING,
"Metadata not found for {0} in {1}",
new Object[]{key, repository});
} else {
LOG.log(Level.WARNING, "Unable to resolve " + key, e);
}
}
} else { // Simple string manipulation with a test
String test = MessageFormat.format("{0}{1}-{2}{3}",
base,
key.artifactId,
key.version,
classifier);
if (!POM_CACHE.containsKey(key)) { // Test it with the pom
String pom = IOUtils.requestPage(test + ".pom");
if (pom == null) continue;
// May as well cache the pom while we have it
POM_CACHE.put(key, makeFuture(pom));
}
url = test;
}
if (url != null) break;
}
if (url != null) {
persist(key, url); // Update persistent cache
} else {
LOG.log(Level.WARNING, "Resolving baseURL (failed): {0}", key);
}
return url;
}
});
}
@Override
protected Future<String> expire(Coordinate key, Future<String> value) {
Preferences cached = getCached(key);
boolean expired = System.currentTimeMillis() >= cached.getLong("expires", 0);
if (expired) return null;
if (value == null) {
// Chance to initialize
String url = cached.get("url", null);
if (url != null) return makeFuture(url);
}
return value;
}
};
public static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool(new DaemonThreadFactory());
/**
* Cache of coordinates to pom documents
*/
private static final Map<Coordinate, Future<String>> POM_CACHE = new Cache<Coordinate, Future<String>>() {
@Override
protected Future<String> fill(final Coordinate key) {
LOG.log(Level.INFO, "Resolving POM (missed): {0}", key);
return THREAD_POOL.submit(new Callable<String>() {
@Override
public String call() throws Exception {
String pom = IOUtils.requestPage(resolve(key, "pom"));
if (pom == null) LOG.log(Level.WARNING, "Resolving POM (failed): {0}", key);
return pom;
}
});
}
};
public static final Preferences PREFERENCES = Preferences.userNodeForPackage(MavenResolver.class);
private MavenResolver() {
}
private static FutureTask<String> makeFuture(String s) {
FutureTask<String> future = new FutureTask<>(new Runnable() {
@Override
public void run() {
}
}, s);
future.run();
return future;
}
private static void persist(Coordinate key, String url) {
Preferences cachedNode = getCached(key);
cachedNode.put("url", url);
cachedNode.putLong("expires", System.currentTimeMillis() + META_LIFETIME);
try {
cachedNode.flush();
} catch (BackingStoreException ignored) {
}
}
private static Preferences getCached(Coordinate c) {
Preferences cachedNode = PREFERENCES;
for (String nodeName : c.toString().replaceAll("[.:-]", "/").split("/")) {
cachedNode = cachedNode.node(nodeName);
}
return cachedNode;
}
public static void invalidateCaches() throws BackingStoreException {
PREFERENCES.removeNode();
PREFERENCES.flush();
}
/**
* Adds a repository
*
* @param url the URL
*/
public static void addRepository(String url) {
REPOSITORIES.add(sanitize(url));
}
/**
* Sanitizes a repository URL:
* <ul>
* <li>Drops trailing slash</li>
* </ul>
*
* @param url the URL
* @return the sanitized URL
*/
private static String sanitize(String url) {
return url.replaceAll("/$", "");
}
/**
* Resolves a pom to an InputStream
*
* @param c the maven coordinate
* @return an InputStream for the given coordinates
* @throws MalformedURLException
*/
public static InputStream resolvePomStream(Coordinate c) throws MalformedURLException {
try {
byte[] bytes = resolvePom(c);
if (bytes != null) return new BufferedInputStream(new ByteArrayInputStream(bytes));
} catch (ExecutionException | InterruptedException e) {
LOG.log(Level.SEVERE, null, e);
}
return null;
}
private static byte[] resolvePom(Coordinate c) throws MalformedURLException, ExecutionException, InterruptedException {
LOG.log(Level.INFO, "Resolving POM: {0}", c);
String pom = POM_CACHE.get(c).get();
if (pom != null) return pom.getBytes(StandardCharsets.UTF_8);
return null;
}
/**
* Resolve an artifact with packaging
*
* @param c the maven coordinate
* @param packaging the packaging
* @return the artifact URL ready for download
* @throws FileNotFoundException if unresolvable
*/
public static String resolve(Coordinate c, String packaging) throws FileNotFoundException {
String resolved = resolve(c);
if (resolved == null) return null;
return resolved + '.' + packaging;
}
/**
* @param c the maven coordinate
* @return the absolute basename of the project coordinate (without the packaging element)
* @throws FileNotFoundException if unresolvable
*/
public static String resolve(Coordinate c) throws FileNotFoundException {
LOG.log(Level.INFO, "Resolving baseURL: {0}", c);
try {
Future<String> future = URL_CACHE.get(c);
String base = future.get();
if (base != null) return base;
} catch (InterruptedException | ExecutionException e) {
LOG.log(Level.SEVERE, null, e);
}
throw new FileNotFoundException("Could not resolve " + c);
}
/**
* @return the list of repositories ordered by priority
*/
private static Collection<String> getRepositories() {
LinkedHashSet<String> repositories = new LinkedHashSet<>();
// To allow for changes at runtime, the local repository is not cached
try {
repositories.add(new File(getLocal()).toURI().toURL().toExternalForm());
} catch (MalformedURLException e) {
LOG.log(Level.SEVERE, null, e);
}
repositories.addAll(MavenResolver.REPOSITORIES);
return Collections.unmodifiableCollection(repositories);
}
/**
* @return the local repository location
*/
public static String getLocal() {
String local;
local = SETTINGS.get("progStoreDir", new File(CURRENT_FILE.getParentFile(), "bin").getPath());
// local = System.getProperty("maven.repo.local", System.getProperty("user.home") + "/.m2/repository");
return sanitize(local);
}
} |
package org.springframework.ide.vscode.boot.java.requestmapping;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Annotation;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.lsp4j.Hover;
import org.eclipse.lsp4j.MarkedString;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.springframework.ide.vscode.boot.java.handlers.HoverProvider;
import org.springframework.ide.vscode.boot.java.livehover.LiveHoverUtils;
import org.springframework.ide.vscode.commons.boot.app.cli.SpringBootApp;
import org.springframework.ide.vscode.commons.boot.app.cli.requestmappings.RequestMapping;
import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.util.BadLocationException;
import org.springframework.ide.vscode.commons.util.Log;
import org.springframework.ide.vscode.commons.util.Renderable;
import org.springframework.ide.vscode.commons.util.Renderables;
import org.springframework.ide.vscode.commons.util.text.TextDocument;
import com.google.common.collect.ImmutableList;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
/**
* @author Martin Lippert
*/
public class RequestMappingHoverProvider implements HoverProvider {
@Override
public Hover provideHover(ASTNode node, Annotation annotation,
ITypeBinding type, int offset, TextDocument doc, IJavaProject project, SpringBootApp[] runningApps) {
return provideHover(annotation, doc, runningApps);
}
@Override
public Collection<Range> getLiveHoverHints(IJavaProject project, Annotation annotation, TextDocument doc, SpringBootApp[] runningApps) {
try {
if (runningApps.length > 0) {
List<Tuple2<RequestMapping, SpringBootApp>> val = getRequestMappingMethodFromRunningApp(annotation, runningApps);
if (!val.isEmpty()) {
Range hoverRange = doc.toRange(annotation.getStartPosition(), annotation.getLength());
return ImmutableList.of(hoverRange);
}
}
}
catch (BadLocationException e) {
Log.log(e);
}
return null;
}
private Hover provideHover(Annotation annotation, TextDocument doc, SpringBootApp[] runningApps) {
try {
List<Either<String, MarkedString>> hoverContent = new ArrayList<>();
List<Tuple2<RequestMapping, SpringBootApp>> val = getRequestMappingMethodFromRunningApp(annotation, runningApps);
if (!val.isEmpty()) {
addHoverContent(val, hoverContent);
}
Range hoverRange = doc.toRange(annotation.getStartPosition(), annotation.getLength());
Hover hover = new Hover();
hover.setContents(hoverContent);
hover.setRange(hoverRange);
return hover;
} catch (Exception e) {
Log.log(e);
}
return null;
}
private List<Tuple2<RequestMapping, SpringBootApp>> getRequestMappingMethodFromRunningApp(Annotation annotation,
SpringBootApp[] runningApps) {
List<Tuple2<RequestMapping, SpringBootApp>> results = new ArrayList<>();
try {
for (SpringBootApp app : runningApps) {
Collection<RequestMapping> mappings = app.getRequestMappings();
if (mappings != null && !mappings.isEmpty()) {
mappings.stream()
.filter(rm -> methodMatchesAnnotation(annotation, rm))
.map(rm -> Tuples.of(rm, app))
.findFirst().ifPresent(t -> results.add(t));
}
}
} catch (Exception e) {
Log.log(e);
}
return results;
}
private boolean methodMatchesAnnotation(Annotation annotation, RequestMapping rm) {
String rqClassName = rm.getFullyQualifiedClassName();
if (rqClassName != null) {
int chop = rqClassName.indexOf("$$EnhancerBySpringCGLIB$$");
if (chop >= 0) {
rqClassName = rqClassName.substring(0, chop);
}
rqClassName = rqClassName.replace('$', '.');
ASTNode parent = annotation.getParent();
if (parent instanceof MethodDeclaration) {
MethodDeclaration methodDec = (MethodDeclaration) parent;
IMethodBinding binding = methodDec.resolveBinding();
if (binding != null) {
return binding.getDeclaringClass().getQualifiedName().equals(rqClassName)
&& binding.getName().equals(rm.getMethodName())
&& Arrays.equals(Arrays.stream(binding.getParameterTypes())
.map(t -> t.getTypeDeclaration().getQualifiedName())
.toArray(String[]::new),
rm.getMethodParameters());
}
// } else if (parent instanceof TypeDeclaration) {
// TypeDeclaration typeDec = (TypeDeclaration) parent;
// return typeDec.resolveBinding().getQualifiedName().equals(rqClassName);
}
}
return false;
}
private void addHoverContent(List<Tuple2<RequestMapping, SpringBootApp>> mappingMethods, List<Either<String, MarkedString>> hoverContent) throws Exception {
for (int i = 0; i < mappingMethods.size(); i++) {
Tuple2<RequestMapping, SpringBootApp> mappingMethod = mappingMethods.get(i);
SpringBootApp app = mappingMethod.getT2();
String port = mappingMethod.getT2().getPort();
String host = mappingMethod.getT2().getHost();
String[] paths = mappingMethod.getT1().getSplitPath();
if (paths==null || paths.length==0) {
//Technically, this means the path 'predicate' is unconstrained, meaning any path matches.
//So this is not quite the same as the case where path=""... but...
//It is better for us to show one link where any path is allowed, versus showing no links where any link is allowed.
//So we'll pretend this is the same as path="" as that gives a working link.
paths = new String[] {""};
}
List<Renderable> renderableUrls = Arrays.stream(paths).flatMap(path -> {
String url = UrlUtil.createUrl(host, port, path);
return Stream.of(Renderables.link(url, url), Renderables.lineBreak());
})
.collect(Collectors.toList());
//The renderableUrls can not be empty because, above, we made sure there's at least one path.
renderableUrls.remove(renderableUrls.size() - 1);
hoverContent.add(Either.forLeft(Renderables.concat(renderableUrls).toMarkdown()));
hoverContent.add(Either.forLeft(LiveHoverUtils.niceAppName(app)));
if (i < mappingMethods.size() - 1) {
// Three dashes == line separator in Markdown
hoverContent.add(Either.forLeft("
}
}
}
} |
package crazypants.enderio.config;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import net.minecraftforge.common.config.Configuration;
import cpw.mods.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import crazypants.enderio.EnderIO;
import crazypants.enderio.Log;
import crazypants.vecmath.VecmathUtil;
public final class Config {
public static class Section {
public final String name;
public final String lang;
public Section(String name, String lang) {
this.name = name;
this.lang = lang;
register();
}
private void register() {
sections.add(this);
}
public String lc() {
return name.toLowerCase();
}
}
public static final List<Section> sections;
static {
sections = new ArrayList<Section>();
}
public static Configuration config;
public static final Section sectionPower = new Section("Power Settings", "power");
public static final Section sectionRecipe = new Section("Recipe Settings", "recipe");
public static final Section sectionItems = new Section("Item Enabling", "item");
public static final Section sectionEfficiency = new Section("Efficiency Settings", "efficiency");
public static final Section sectionPersonal = new Section("Personal Settings", "personal");
public static final Section sectionAnchor = new Section("Anchor Settings", "anchor");
public static final Section sectionStaff = new Section("Staff Settings", "staff");
public static final Section sectionDarkSteel = new Section("Dark Steel", "darksteel");
public static final Section sectionFarm = new Section("Farm Settings", "farm");
public static final Section sectionAesthetic = new Section("Aesthetic Settings", "aesthetic");
public static final Section sectionAdvanced = new Section("Advanced Settings", "advanced");
public static final Section sectionMagnet = new Section("Magnet Settings", "magnet");
public static final Section sectionSpawner = new Section("PoweredSpawner Settings", "spawner");
static int BID = 700;
static int IID = 8524;
public static final double DEFAULT_CONDUIT_SCALE = 0.5;
public static boolean useAlternateBinderRecipe;
public static boolean useAlternateTesseractModel;
public static boolean photovoltaicCellEnabled = true;
public static double conduitScale = DEFAULT_CONDUIT_SCALE;
public static int numConduitsPerRecipe = 8;
public static double transceiverEnergyLoss = 0.1;
public static double transceiverUpkeepCost = 0.25;
public static double transceiverBucketTransmissionCost = 1;
public static int transceiverMaxIO = 256;
public static File configDirectory;
public static boolean useHardRecipes = false;
public static boolean useSteelInChassi = false;
public static boolean detailedPowerTrackingEnabled = false;
public static boolean useSneakMouseWheelYetaWrench = true;
public static boolean useSneakRightClickYetaWrench = false;
public static boolean useRfAsDefault = true;
public static boolean itemConduitUsePhyscialDistance = false;
public static int enderFluidConduitExtractRate = 200;
public static int enderFluidConduitMaxIoRate = 800;
public static int advancedFluidConduitExtractRate = 100;
public static int advancedFluidConduitMaxIoRate = 400;
public static int fluidConduitExtractRate = 50;
public static int fluidConduitMaxIoRate = 200;
public static boolean updateLightingWhenHidingFacades = false;
public static boolean travelAnchorEnabled = true;
public static int travelAnchorMaxDistance = 48;
public static int travelStaffMaxDistance = 96;
public static float travelStaffPowerPerBlockRF = 250;
public static int travelStaffMaxBlinkDistance = 16;
public static int travelStaffBlinkPauseTicks = 10;
public static boolean travelStaffEnabled = true;
public static boolean travelStaffBlinkEnabled = true;
public static boolean travelStaffBlinkThroughSolidBlocksEnabled = true;
public static boolean travelStaffBlinkThroughClearBlocksEnabled = true;
public static int enderIoRange = 8;
public static boolean enderIoMeAccessEnabled = true;
public static int darkSteelPowerStorageBase = 100000;
public static int darkSteelPowerStorageLevelOne = 150000;
public static int darkSteelPowerStorageLevelTwo = 250000;
public static int darkSteelPowerStorageLevelThree = 1000000;
public static float darkSteelSpeedOneWalkModifier = 0.1f;
public static float darkSteelSpeedTwoWalkMultiplier = 0.2f;
public static float darkSteelSpeedThreeWalkMultiplier = 0.3f;
public static float darkSteelSpeedOneSprintModifier = 0.1f;
public static float darkSteelSpeedTwoSprintMultiplier = 0.3f;
public static float darkSteelSpeedThreeSprintMultiplier = 0.5f;
public static double darkSteelBootsJumpModifier = 1.5;
public static int darkSteelWalkPowerCost = darkSteelPowerStorageLevelTwo / 3000;
public static int darkSteelSprintPowerCost = darkSteelWalkPowerCost * 4;
public static boolean darkSteelDrainPowerFromInventory = false;
public static int darkSteelBootsJumpPowerCost = 250;
public static float darkSteelSwordWitherSkullChance = 0.05f;
public static float darkSteelSwordWitherSkullLootingModifier = 0.167f / 3f; //at looting 3, have a 1 in 6 chance of getting a skull
public static float darkSteelSwordSkullChance = 0.2f;
public static float darkSteelSwordSkullLootingModifier = 0.15f;
public static float vanillaSwordSkullLootingModifier = 0.1f;
public static int darkSteelSwordPowerUsePerHit = 750;
public static double darkSteelSwordEnderPearlDropChance = 1;
public static double darkSteelSwordEnderPearlDropChancePerLooting = 0.5;
public static int darkSteelPickPowerUseObsidian = 10000;
public static int darkSteelPickEffeciencyObsidian = 50;
public static int darkSteelPickPowerUsePerDamagePoint = 750;
public static float darkSteelPickEffeciencyBoostWhenPowered = 2;
public static int darkSteelAxePowerUsePerDamagePoint = 750;
public static int darkSteelAxePowerUsePerDamagePointMultiHarvest = 1500;
public static float darkSteelAxeEffeciencyBoostWhenPowered = 2;
public static float darkSteelAxeSpeedPenaltyMultiHarvest = 8;
public static int hootchPowerPerCycle = 6;
public static int hootchPowerTotalBurnTime = 6000;
public static int rocketFuelPowerPerCycle = 16;
public static int rocketFuelPowerTotalBurnTime = 7000;
public static int fireWaterPowerPerCycle = 8;
public static int fireWaterPowerTotalBurnTime = 15000;
public static float vatPowerUserPerTick = 2;
public static double maxPhotovoltaicOutput = 1.0;
public static double maxPhotovoltaicAdvancedOutput = 4.0;
public static double zombieGeneratorMjPerTick = 8.0;
public static int zombieGeneratorTicksPerBucketFuel = 10000;
public static boolean combustionGeneratorUseOpaqueModel = true;
public static boolean addFuelTooltipsToAllFluidContainers = true;
public static boolean addFurnaceFuelTootip = true;
public static boolean addDurabilityTootip = true;
public static int darkSteelUpgradeVibrantCost = 20;
public static int darkSteelUpgradePowerOneCost = 10;
public static int darkSteelUpgradePowerTwoCost = 20;
public static int darkSteelUpgradePowerThreeCost = 30;
public static float farmContinuousEnergyUse = 4;
public static float farmActionEnergyUse = 50;
public static int farmDefaultSize = 3;
public static boolean farmAxeDamageOnLeafBreak = false;
public static float farmToolTakeDamageChance = 1;
public static int magnetPowerUsePerSecondRF = 1;
public static int magnetPowerCapacityRF = 100000;
public static int magnetRange = 5;
public static boolean useCombustionGenModel = false;
public static int crafterMjPerCraft = 250;
public static int capacitorBankMaxIoMJ = 100;
public static int capacitorBankMaxStorageMJ = 500000;
public static int poweredSpawnerMinDelayTicks = 200;
public static int poweredSpawnerMaxDelayTicks = 800;
public static float poweredSpawnerLevelOnePowerPerTick = 16;
public static float poweredSpawnerLevelTwoPowerPerTick = 48;
public static float poweredSpawnerLevelThreePowerPerTick = 96;
public static int poweredSpawnerMaxPlayerDistance = 0;
public static boolean poweredSpawnerUseVanillaSpawChecks = false;
public static double brokenSpawnerDropChance = 1;
public static int powerSpawnerAddSpawnerCost = 30;
public static void load(FMLPreInitializationEvent event) {
FMLCommonHandler.instance().bus().register(new Config());
configDirectory = new File(event.getModConfigurationDirectory(), EnderIO.MODID.toLowerCase());
if(!configDirectory.exists()) {
configDirectory.mkdir();
}
File configFile = new File(configDirectory, "EnderIO.cfg");
config = new Configuration(configFile);
syncConfig();
}
public static void syncConfig() {
try {
Config.processConfig(config);
} catch (Exception e) {
Log.error("EnderIO has a problem loading it's configuration");
} finally {
if(config.hasChanged()) {
config.save();
}
}
}
@SubscribeEvent
public void onConfigChanged(OnConfigChangedEvent event) {
if (event.modID.equals(EnderIO.MODID)) {
Log.info("Updating config...");
syncConfig();
}
}
public static void processConfig(Configuration config) {
useRfAsDefault = config.get(sectionPower.name, "displayPowerAsRedstoneFlux", useRfAsDefault, "If true, all power is displayed in RF, otherwise MJ is used.")
.getBoolean(useRfAsDefault);
capacitorBankMaxIoMJ = config.get(sectionPower.name, "capacitorBankMaxIoMJ", capacitorBankMaxIoMJ, "The maximum IO for a single capacitor in MJ/t")
.getInt(capacitorBankMaxIoMJ);
capacitorBankMaxStorageMJ = config.get(sectionPower.name, "capacitorBankMaxStorageMJ", capacitorBankMaxStorageMJ,
"The maximum storage for a single capacitor in MJ")
.getInt(capacitorBankMaxStorageMJ);
useHardRecipes = config.get(sectionRecipe.name, "useHardRecipes", useHardRecipes, "When enabled machines cost significantly more.")
.getBoolean(useHardRecipes);
useSteelInChassi = config.get(sectionRecipe.name, "useSteelInChassi", useSteelInChassi, "When enabled machine chassis will require steel instead of iron.")
.getBoolean(useSteelInChassi);
numConduitsPerRecipe = config.get(sectionRecipe.name, "numConduitsPerRecipe", numConduitsPerRecipe,
"The number of conduits crafted per recipe.").getInt(numConduitsPerRecipe);
photovoltaicCellEnabled = config.get(sectionItems.name, "photovoltaicCellEnabled", photovoltaicCellEnabled,
"If set to false: Photovoltaic Cells will not be craftable.")
.getBoolean(photovoltaicCellEnabled);
maxPhotovoltaicOutput = config.get(sectionPower.name, "maxPhotovoltaicOutput", maxPhotovoltaicOutput,
"Maximum output in MJ/t of the Photovoltaic Panels.").getDouble(maxPhotovoltaicOutput);
maxPhotovoltaicAdvancedOutput = config.get(sectionPower.name, "maxPhotovoltaicAdvancedOutput", maxPhotovoltaicAdvancedOutput,
"Maximum output in MJ/t of the Advanced Photovoltaic Panels.").getDouble(maxPhotovoltaicAdvancedOutput);
useAlternateBinderRecipe = config.get(sectionRecipe.name, "useAlternateBinderRecipe", false, "Create conduit binder in crafting table instead of furnace")
.getBoolean(useAlternateBinderRecipe);
conduitScale = config.get(sectionAesthetic.name, "conduitScale", DEFAULT_CONDUIT_SCALE,
"Valid values are between 0-1, smallest conduits at 0, largest at 1.\n" +
"In SMP, all clients must be using the same value as the server.").getDouble(DEFAULT_CONDUIT_SCALE);
conduitScale = VecmathUtil.clamp(conduitScale, 0, 1);
fluidConduitExtractRate = config.get(sectionEfficiency.name, "fluidConduitExtractRate", fluidConduitExtractRate,
"Number of millibuckects per tick extracted by a fluid conduits auto extracting").getInt(fluidConduitExtractRate);
fluidConduitMaxIoRate = config.get(sectionEfficiency.name, "fluidConduitMaxIoRate", fluidConduitMaxIoRate,
"Number of millibuckects per tick that can pass through a single connection to a fluid conduit.").getInt(fluidConduitMaxIoRate);
advancedFluidConduitExtractRate = config.get(sectionEfficiency.name, "advancedFluidConduitExtractRate", advancedFluidConduitExtractRate,
"Number of millibuckects per tick extracted by pressurised fluid conduits auto extracting").getInt(advancedFluidConduitExtractRate);
advancedFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "advancedFluidConduitMaxIoRate", advancedFluidConduitMaxIoRate,
"Number of millibuckects per tick that can pass through a single connection to an pressurised fluid conduit.").getInt(advancedFluidConduitMaxIoRate);
enderFluidConduitExtractRate = config.get(sectionEfficiency.name, "enderFluidConduitExtractRate", enderFluidConduitExtractRate,
"Number of millibuckects per tick extracted by ender fluid conduits auto extracting").getInt(enderFluidConduitExtractRate);
enderFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "enderFluidConduitMaxIoRate", enderFluidConduitMaxIoRate,
"Number of millibuckects per tick that can pass through a single connection to an ender fluid conduit.").getInt(enderFluidConduitMaxIoRate);
useAlternateTesseractModel = config.get(sectionAesthetic.name, "useAlternateTransceiverModel", useAlternateTesseractModel,
"Use TheKazador's alternatice model for the Dimensional Transceiver")
.getBoolean(false);
transceiverEnergyLoss = config.get(sectionPower.name, "transceiverEnergyLoss", transceiverEnergyLoss,
"Amount of energy lost when transfered by Dimensional Transceiver; 0 is no loss, 1 is 100% loss").getDouble(transceiverEnergyLoss);
transceiverUpkeepCost = config.get(sectionPower.name, "transceiverUpkeepCost", transceiverUpkeepCost,
"Number of MJ/t required to keep a Dimensional Transceiver connection open").getDouble(transceiverUpkeepCost);
transceiverMaxIO = config.get(sectionPower.name, "transceiverMaxIO", transceiverMaxIO,
"Maximum MJ/t sent and recieved by a Dimensional Transceiver per tick. Input and output limits are not cumulative").getInt(transceiverMaxIO);
transceiverBucketTransmissionCost = config.get(sectionEfficiency.name, "transceiverBucketTransmissionCost", transceiverBucketTransmissionCost,
"The cost in MJ of transporting a bucket of fluid via a Dimensional Transceiver.").getDouble(transceiverBucketTransmissionCost);
vatPowerUserPerTick = (float) config.get(sectionPower.name, "vatPowerUserPerTick", vatPowerUserPerTick,
"Power use (MJ/t) used by the vat.").getDouble(vatPowerUserPerTick);
detailedPowerTrackingEnabled = config
.get(
sectionAdvanced.name,
"perInterfacePowerTrackingEnabled",
detailedPowerTrackingEnabled,
"Enable per tick sampling on individual power inputs and outputs. This allows slightly more detailed messages from the MJ Reader but has a negative impact on server performance.")
.getBoolean(detailedPowerTrackingEnabled);
useSneakMouseWheelYetaWrench = config.get(sectionPersonal.name, "useSneakMouseWheelYetaWrench", useSneakMouseWheelYetaWrench,
"If true, shift-mouse wheel will change the conduit display mode when the YetaWrench is eqipped.")
.getBoolean(useSneakMouseWheelYetaWrench);
useSneakRightClickYetaWrench = config.get(sectionPersonal.name, "useSneakRightClickYetaWrench", useSneakRightClickYetaWrench,
"If true, shift-clicking the YetaWrench on a null or non wrenchable object will change the conduit display mode.")
.getBoolean(useSneakRightClickYetaWrench);
itemConduitUsePhyscialDistance = config.get(sectionEfficiency.name, "itemConduitUsePhyscialDistance", itemConduitUsePhyscialDistance, "If true, " +
"'line of sight' distance rather than conduit path distance is used to calculate priorities.")
.getBoolean(itemConduitUsePhyscialDistance);
if(!useSneakMouseWheelYetaWrench && !useSneakRightClickYetaWrench) {
Log.warn("Both useSneakMouseWheelYetaWrench and useSneakRightClickYetaWrench are set to false. Enabling mouse wheel.");
useSneakMouseWheelYetaWrench = true;
}
travelAnchorEnabled = config.get(sectionItems.name, "travelAnchorEnabled", travelAnchorEnabled,
"When set to false: the travel anchor will not be craftable.").getBoolean(travelAnchorEnabled);
travelAnchorMaxDistance = config.get(sectionAnchor.name, "travelAnchorMaxDistance", travelAnchorMaxDistance,
"Maximum number of blocks that can be traveled from one travel anchor to another.").getInt(travelAnchorMaxDistance);
travelStaffMaxDistance = config.get(sectionStaff.name, "travelStaffMaxDistance", travelStaffMaxDistance,
"Maximum number of blocks that can be traveled using the Staff of the Traveling.").getInt(travelStaffMaxDistance);
travelStaffPowerPerBlockRF = (float) config.get(sectionStaff.name, "travelStaffPowerPerBlockRF", travelStaffPowerPerBlockRF,
"Number of MJ required per block travelled using the Staff of the Traveling.").getDouble(travelStaffPowerPerBlockRF);
travelStaffMaxBlinkDistance = config.get(sectionStaff.name, "travelStaffMaxBlinkDistance", travelStaffMaxBlinkDistance,
"Max number of blocks teleported when shift clicking the staff.").getInt(travelStaffMaxBlinkDistance);
travelStaffBlinkPauseTicks = config.get(sectionStaff.name, "travelStaffBlinkPauseTicks", travelStaffBlinkPauseTicks,
"Minimum number of ticks between 'blinks'. Values of 10 or less allow a limited sort of flight.").getInt(travelStaffBlinkPauseTicks);
travelStaffEnabled = config.get(sectionItems.name, "travelStaffEnabled", travelAnchorEnabled,
"If set to false: the travel staff will not be craftable.").getBoolean(travelStaffEnabled);
travelStaffBlinkEnabled = config.get(sectionItems.name, "travelStaffBlinkEnabled", travelStaffBlinkEnabled,
"If set to false: the travel staff can not be used to shift-right click teleport, or blink.").getBoolean(travelStaffBlinkEnabled);
travelStaffBlinkThroughSolidBlocksEnabled = config.get(sectionItems.name, "travelStaffBlinkThroughSolidBlocksEnabled",
travelStaffBlinkThroughSolidBlocksEnabled,
"If set to false: the travel staff can be used to blink through any block.").getBoolean(travelStaffBlinkThroughSolidBlocksEnabled);
travelStaffBlinkThroughClearBlocksEnabled = config
.get(sectionItems.name, "travelStaffBlinkThroughClearBlocksEnabled", travelStaffBlinkThroughClearBlocksEnabled,
"If travelStaffBlinkThroughSolidBlocksEnabled is set to false and this is true: the travel " +
"staff can only be used to blink through transparent or partial blocks (e.g. torches). " +
"If both are false: only air blocks may be teleported through.")
.getBoolean(travelStaffBlinkThroughClearBlocksEnabled);
enderIoRange = config.get(sectionEfficiency.name, "enderIoRange", enderIoRange,
"Range accessable (in blocks) when using the Ender IO.").getInt(enderIoRange);
enderIoMeAccessEnabled = config.get(sectionPersonal.name, "enderIoMeAccessEnabled", enderIoMeAccessEnabled,
"If false: you will not be able to access a ME acess or crafting terminal using the Ender IO.").getBoolean(enderIoMeAccessEnabled);
updateLightingWhenHidingFacades = config.get(sectionEfficiency.name, "updateLightingWhenHidingFacades", updateLightingWhenHidingFacades,
"When true: correct lighting is recalculated (client side) for conduit bundles when transitioning to"
+ " from being hidden behind a facade. This produces "
+ "better quality rendering but can result in frame stutters when switching to/from a wrench.")
.getBoolean(updateLightingWhenHidingFacades);
darkSteelPowerStorageBase = config.get(sectionDarkSteel.name, "darkSteelPowerStorageBase", darkSteelPowerStorageBase,
"Base amount of power stored by dark steel items.").getInt(darkSteelPowerStorageBase);
darkSteelPowerStorageLevelOne = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelOne", darkSteelPowerStorageLevelOne,
"Amount of power stored by dark steel items with a level 1 upgrade.").getInt(darkSteelPowerStorageLevelOne);
darkSteelPowerStorageLevelTwo = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelTwo", darkSteelPowerStorageLevelTwo,
"Amount of power stored by dark steel items with a level 2 upgrade.").getInt(darkSteelPowerStorageLevelTwo);
darkSteelPowerStorageLevelThree = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelThree", darkSteelPowerStorageLevelThree,
"Amount of power stored by dark steel items with a level 3 upgrade.").getInt(darkSteelPowerStorageLevelThree);
darkSteelUpgradeVibrantCost = config.get(sectionDarkSteel.name, "darkSteelUpgradeVibrantCost", darkSteelUpgradeVibrantCost,
"Number of levels required for the 'Vibrant' upgrade.").getInt(darkSteelUpgradeVibrantCost);
darkSteelUpgradePowerOneCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerOneCost", darkSteelUpgradePowerOneCost,
"Number of levels required for the 'Vibrant' upgrade.").getInt(darkSteelUpgradePowerOneCost);
darkSteelUpgradePowerTwoCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerTwoCost", darkSteelUpgradePowerTwoCost,
"Number of levels required for the 'Vibrant' upgrade.").getInt(darkSteelUpgradePowerTwoCost);
darkSteelUpgradePowerThreeCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerThreeCost", darkSteelUpgradePowerThreeCost,
"Number of levels required for the 'Vibrant' upgrade.").getInt(darkSteelUpgradePowerThreeCost);
darkSteelSpeedOneWalkModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedOneWalkModifier", darkSteelSpeedOneWalkModifier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedOneWalkModifier);
darkSteelSpeedTwoWalkMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedTwoWalkMultiplier", darkSteelSpeedTwoWalkMultiplier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedTwoWalkMultiplier);
darkSteelSpeedThreeWalkMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedThreeWalkMultiplier", darkSteelSpeedThreeWalkMultiplier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedThreeWalkMultiplier);
darkSteelSpeedOneSprintModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedOneSprintModifier", darkSteelSpeedOneSprintModifier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedOneSprintModifier);
darkSteelSpeedTwoSprintMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedTwoSprintMultiplier", darkSteelSpeedTwoSprintMultiplier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedTwoSprintMultiplier);
darkSteelSpeedThreeSprintMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedThreeSprintMultiplier", darkSteelSpeedThreeSprintMultiplier,
"Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedThreeSprintMultiplier);
darkSteelBootsJumpModifier = config.get(sectionDarkSteel.name, "darkSteelBootsJumpModifier", darkSteelBootsJumpModifier,
"Jump height modifier applied when jumping with Dark Steel Boots equipped").getDouble(darkSteelBootsJumpModifier);
darkSteelPowerStorageBase = config.get(sectionDarkSteel.name, "darkSteelPowerStorage", darkSteelPowerStorageBase,
"Amount of power stored (RF) per crystal in the armor items recipe.").getInt(darkSteelPowerStorageBase);
darkSteelWalkPowerCost = config.get(sectionDarkSteel.name, "darkSteelWalkPowerCost", darkSteelWalkPowerCost,
"Amount of power stored (RF) per block walked when wearing the dark steel boots.").getInt(darkSteelWalkPowerCost);
darkSteelSprintPowerCost = config.get(sectionDarkSteel.name, "darkSteelSprintPowerCost", darkSteelWalkPowerCost,
"Amount of power stored (RF) per block walked when wearing the dark stell boots.").getInt(darkSteelSprintPowerCost);
darkSteelDrainPowerFromInventory = config.get(sectionDarkSteel.name, "darkSteelDrainPowerFromInventory", darkSteelDrainPowerFromInventory,
"If true, dark steel armor will drain power stored (RF) in power containers in the players invenotry.").getBoolean(darkSteelDrainPowerFromInventory);
darkSteelBootsJumpPowerCost = config.get(sectionDarkSteel.name, "darkSteelBootsJumpPowerCost", darkSteelBootsJumpPowerCost,
"Base amount of power used per jump (RF) dark steel boots. The second jump in a 'double jump' uses 2x this etc").getInt(darkSteelBootsJumpPowerCost);
darkSteelSwordSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullChance", darkSteelSwordSkullChance,
"The base chance that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
darkSteelSwordSkullChance);
darkSteelSwordSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullLootingModifier", darkSteelSwordSkullLootingModifier,
"The chance per looting level that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
darkSteelSwordSkullLootingModifier);
darkSteelSwordWitherSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullChance", darkSteelSwordWitherSkullChance,
"The base chance that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
darkSteelSwordWitherSkullChance);
darkSteelSwordWitherSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullLootingModifie",
darkSteelSwordWitherSkullLootingModifier,
"The chance per looting level that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
darkSteelSwordWitherSkullLootingModifier);
vanillaSwordSkullLootingModifier = (float) config.get(sectionPersonal.name, "vanillaSwordSkullLootingModifier", vanillaSwordSkullLootingModifier,
"The chance per looting level that a skull will be dropped when using a non-dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
vanillaSwordSkullLootingModifier);
darkSteelSwordPowerUsePerHit = config.get(sectionDarkSteel.name, "darkSteelSwordPowerUsePerHit", darkSteelSwordPowerUsePerHit,
"The amount of power (RF) used per hit.").getInt(darkSteelSwordPowerUsePerHit);
darkSteelSwordEnderPearlDropChance = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChance", darkSteelSwordEnderPearlDropChance,
"The chance that an ender pearl will be dropped when using a dark steel sword (0 = no chance, 1 = 100% chance)").getDouble(
darkSteelSwordEnderPearlDropChance);
darkSteelSwordEnderPearlDropChancePerLooting = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChancePerLooting",
darkSteelSwordEnderPearlDropChancePerLooting,
"The chance for each looting level that an additional ender pearl will be dropped when using a dark steel sword (0 = no chance, 1 = 100% chance)")
.getDouble(
darkSteelSwordEnderPearlDropChancePerLooting);
darkSteelPickPowerUseObsidian = config.get(sectionDarkSteel.name, "darkSteelPickPowerUseObsidian", darkSteelPickPowerUseObsidian,
"The amount of power (RF) used to break an obsidian block.").getInt(darkSteelPickPowerUseObsidian);
darkSteelPickEffeciencyObsidian = config.get(sectionDarkSteel.name, "darkSteelPickEffeciencyObsidian", darkSteelPickEffeciencyObsidian,
"The effeciency when breaking obsidian with a powered Dark Pickaxe.").getInt(darkSteelPickEffeciencyObsidian);
darkSteelPickPowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelPickPowerUsePerDamagePoint", darkSteelPickPowerUsePerDamagePoint,
"Power use (RF) per damage/durability point avoided.").getInt(darkSteelPickPowerUsePerDamagePoint);
darkSteelPickEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelPickEffeciencyBoostWhenPowered",
darkSteelPickEffeciencyBoostWhenPowered, "The increase in effciency when powered.").getDouble(darkSteelPickEffeciencyBoostWhenPowered);
darkSteelAxePowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelAxePowerUsePerDamagePoint", darkSteelAxePowerUsePerDamagePoint,
"Power use (RF) per damage/durability point avoided.").getInt(darkSteelAxePowerUsePerDamagePoint);
darkSteelAxePowerUsePerDamagePointMultiHarvest = config.get(sectionDarkSteel.name, "darkSteelPickAxeUsePerDamagePointMultiHarvest",
darkSteelAxePowerUsePerDamagePointMultiHarvest,
"Power use (RF) per damage/durability point avoided when shift-harvesting multiple logs").getInt(darkSteelAxePowerUsePerDamagePointMultiHarvest);
darkSteelAxeSpeedPenaltyMultiHarvest = (float) config.get(sectionDarkSteel.name, "darkSteelAxeSpeedPenaltyMultiHarvest", darkSteelAxeSpeedPenaltyMultiHarvest,
"How much slower shift-harvesting logs is.").getDouble(darkSteelAxeSpeedPenaltyMultiHarvest);
darkSteelAxeEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelAxeEffeciencyBoostWhenPowered",
darkSteelAxeEffeciencyBoostWhenPowered, "The increase in effciency when powered.").getDouble(darkSteelAxeEffeciencyBoostWhenPowered);
hootchPowerPerCycle = config.get(sectionPower.name, "hootchPowerPerCycle", hootchPowerPerCycle,
"The amount of power generated per BC engine cycle. Examples: BC Oil = 3, BC Fuel = 6").getInt(hootchPowerPerCycle);
hootchPowerTotalBurnTime = config.get(sectionPower.name, "hootchPowerTotalBurnTime", hootchPowerTotalBurnTime,
"The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(hootchPowerTotalBurnTime);
rocketFuelPowerPerCycle = config.get(sectionPower.name, "rocketFuelPowerPerCycle", rocketFuelPowerPerCycle,
"The amount of power generated per BC engine cycle. Examples: BC Oil = 3, BC Fuel = 6").getInt(rocketFuelPowerPerCycle);
rocketFuelPowerTotalBurnTime = config.get(sectionPower.name, "rocketFuelPowerTotalBurnTime", rocketFuelPowerTotalBurnTime,
"The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(rocketFuelPowerTotalBurnTime);
fireWaterPowerPerCycle = config.get(sectionPower.name, "fireWaterPowerPerCycle", fireWaterPowerPerCycle,
"The amount of power generated per BC engine cycle. Examples: BC Oil = 3, BC Fuel = 6").getInt(fireWaterPowerPerCycle);
fireWaterPowerTotalBurnTime = config.get(sectionPower.name, "fireWaterPowerTotalBurnTime", fireWaterPowerTotalBurnTime,
"The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(fireWaterPowerTotalBurnTime);
zombieGeneratorMjPerTick = config.get(sectionPower.name, "zombieGeneratorMjPerTick", zombieGeneratorMjPerTick,
"The amount of power generated per tick.").getDouble(zombieGeneratorMjPerTick);
zombieGeneratorTicksPerBucketFuel = config.get(sectionPower.name, "zombieGeneratorTicksPerMbFuel", zombieGeneratorTicksPerBucketFuel,
"The number of ticks one bucket of fuel lasts.").getInt(zombieGeneratorTicksPerBucketFuel);
addFuelTooltipsToAllFluidContainers = config.get(sectionPersonal.name, "addFuelTooltipsToAllFluidContainers", addFuelTooltipsToAllFluidContainers,
"If true, the MJ/t and burn time of the fuel will be displayed in all tooltips for fluid containers with fuel.").getBoolean(
addFuelTooltipsToAllFluidContainers);
addDurabilityTootip = config.get(sectionPersonal.name, "addDurabilityTootip", addFuelTooltipsToAllFluidContainers,
"If true, adds durability tooltips to tools and armor").getBoolean(
addDurabilityTootip);
addFurnaceFuelTootip = config.get(sectionPersonal.name, "addFurnaceFuelTootip", addFuelTooltipsToAllFluidContainers,
"If true, adds burn duration tooltips to furnace fuels").getBoolean(addFurnaceFuelTootip);
farmContinuousEnergyUse = (float) config.get(sectionFarm.name, "farmContinuousEnergyUse", farmContinuousEnergyUse,
"The amount of power used by a farm per tick ").getDouble(farmContinuousEnergyUse);
farmActionEnergyUse = (float) config.get(sectionFarm.name, "farmActionEnergyUse", farmActionEnergyUse,
"The amount of power used by a farm per action (eg plant, till, harvest) ").getDouble(farmActionEnergyUse);
farmDefaultSize = config.get(sectionFarm.name, "farmDefaultSize", farmDefaultSize,
"The number of blocks a farm will extend from its center").getInt(farmDefaultSize);
farmAxeDamageOnLeafBreak = config.get(sectionFarm.name, "farmAxeDamageOnLeafBreak", farmAxeDamageOnLeafBreak,
"Should axes in a farm take damage when breaking leaves?").getBoolean(farmAxeDamageOnLeafBreak);
farmToolTakeDamageChance = (float) config.get(sectionFarm.name, "farmToolTakeDamageChance", farmToolTakeDamageChance,
"The chance that a tool in the farm will take damage.").getDouble(farmToolTakeDamageChance);
combustionGeneratorUseOpaqueModel = config.get(sectionAesthetic.name, "combustionGeneratorUseOpaqueModel", combustionGeneratorUseOpaqueModel,
"If set to true: fluid will not be shown in combustion generator tanks. Improves FPS. ").getBoolean(combustionGeneratorUseOpaqueModel);
magnetPowerUsePerSecondRF = config.get(sectionMagnet.name, "magnetPowerUsePerTickRF", magnetPowerUsePerSecondRF,
"The amount of RF power used per tick when the magnet is active").getInt(magnetPowerUsePerSecondRF);
magnetPowerCapacityRF = config.get(sectionMagnet.name, "magnetPowerCapacityRF", magnetPowerCapacityRF,
"Amount of RF power stored in a fully charged magnet").getInt(magnetPowerCapacityRF);
magnetRange = config.get(sectionMagnet.name, "magnetRange", magnetRange,
"Range of the magnet in blocks.").getInt(magnetRange);
useCombustionGenModel = config.get(sectionAesthetic.name, "useCombustionGenModel", useCombustionGenModel,
"If set to true: WIP Combustion Generator model will be used").getBoolean(useCombustionGenModel);
crafterMjPerCraft = config.get("AutoCrafter Settings", "crafterMjPerCraft", crafterMjPerCraft,
"MJ used per autocrafted recipe").getInt(crafterMjPerCraft);
poweredSpawnerMinDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMinDelayTicks", poweredSpawnerMinDelayTicks,
"Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMinDelayTicks);
poweredSpawnerMaxDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMaxDelayTicks", poweredSpawnerMaxDelayTicks,
"Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMaxDelayTicks);
poweredSpawnerLevelOnePowerPerTick = (float)config.get(sectionSpawner.name, "poweredSpawnerLevelOnePowerPerTick", poweredSpawnerLevelOnePowerPerTick,
"MJ per tick for a level 1 (non-upgraded) spawner").getDouble(poweredSpawnerLevelOnePowerPerTick);
poweredSpawnerLevelTwoPowerPerTick = (float)config.get(sectionSpawner.name, "poweredSpawnerLevelTwoPowerPerTick", poweredSpawnerLevelTwoPowerPerTick,
"MJ per tick for a level 2 spawner").getDouble(poweredSpawnerLevelTwoPowerPerTick);
poweredSpawnerLevelThreePowerPerTick = (float)config.get(sectionSpawner.name, "poweredSpawnerLevelThreePowerPerTick", poweredSpawnerLevelThreePowerPerTick,
"MJ per tick for a level 3 spawner").getDouble(poweredSpawnerLevelThreePowerPerTick);
poweredSpawnerMaxPlayerDistance = config.get(sectionSpawner.name, "poweredSpawnerMaxPlayerDistance", poweredSpawnerMaxPlayerDistance,
"Max distance of the closest player for the spawner to be active. A zero value will remove the player check").getInt(poweredSpawnerMaxPlayerDistance);
poweredSpawnerUseVanillaSpawChecks = config.get(sectionSpawner.name, "poweredSpawnerUseVanillaSpawChecks", poweredSpawnerUseVanillaSpawChecks,
"If true, regular spawn checks such as lighting level and dimension will be made before spawning mobs").getBoolean(poweredSpawnerUseVanillaSpawChecks);
brokenSpawnerDropChance = (float)config.get(sectionSpawner.name, "brokenSpawnerDropChance", brokenSpawnerDropChance,
"The chance a brokne spawner will be dropped when a spawner is broken. 1 = 100% chance, 0 = 0% chance").getDouble(brokenSpawnerDropChance);
powerSpawnerAddSpawnerCost = config.get(sectionSpawner.name, "powerSpawnerAddSpawnerCost", powerSpawnerAddSpawnerCost,
"The number of levels it costs to add a broken spawner").getInt(powerSpawnerAddSpawnerCost);
}
private Config() {
}
} |
package org.safehaus.subutai.core.dispatcher.impl;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Logger;
import org.safehaus.subutai.common.command.AgentRequestBuilder;
import org.safehaus.subutai.common.command.Command;
import org.safehaus.subutai.common.command.CommandCallback;
import org.safehaus.subutai.common.command.RequestBuilder;
import org.safehaus.subutai.common.protocol.Agent;
import org.safehaus.subutai.common.protocol.BatchRequest;
import org.safehaus.subutai.common.protocol.Response;
import org.safehaus.subutai.core.agent.api.AgentManager;
import org.safehaus.subutai.core.command.api.CommandRunner;
import org.safehaus.subutai.core.dispatcher.api.CommandDispatcher;
import com.google.common.base.Preconditions;
/**
* Implementation of CommandDispatcher interface
*/
public class CommandDispatcherImpl implements CommandDispatcher {
private static final Logger LOG = Logger.getLogger( CommandDispatcherImpl.class.getName() );
private AgentManager agentManager;
private CommandRunner commandRunner;
public CommandDispatcherImpl( final AgentManager agentManager, final CommandRunner commandRunner ) {
this.agentManager = agentManager;
this.commandRunner = commandRunner;
}
public void init() {}
public void destroy() {}
public void sendRequests( final Map<UUID, Set<BatchRequest>> requests ) {
//use PeerManager to figure out IP of target peer by UUID
//check if peers are accessible otherwise throw RunCommandException
//send requests in batch to each peer
}
public void processResponse( final Set<Response> responses ) {
//trigger CommandRunner.onResponse
}
public void executeRequests( final UUID initiatorId, final Set<BatchRequest> requests ) {
//execute requests using Command Runner
//upon response in callback, cache response to persistent queue (key => initiator id)
//some background thread should iterate this queue and attempt to send responses back to initiator
}
@Override
public void runCommandAsync( final Command command, final CommandCallback commandCallback ) {
Preconditions.checkNotNull( command, "Command is null" );
Preconditions.checkArgument( command instanceof CommandImpl, "Command is of wrong type" );
Preconditions.checkNotNull( commandCallback, "Callback is null" );
final CommandImpl commandImpl = ( CommandImpl ) command;
//send remote requests
if ( !commandImpl.getRemoteRequests().isEmpty() ) {
sendRequests( commandImpl.getRemoteRequests() );
}
//send local requests
if ( !commandImpl.getRequests().isEmpty() ) {
commandRunner.runCommandAsync( command, commandCallback );
}
}
@Override
public void runCommandAsync( final Command command ) {
runCommandAsync( command, new CommandCallback() );
}
@Override
public void runCommand( final Command command ) {
runCommandAsync( command, new CommandCallback() );
( ( CommandImpl ) command ).waitCompletion();
}
@Override
public void runCommand( final Command command, final CommandCallback commandCallback ) {
runCommandAsync( command, commandCallback );
( ( CommandImpl ) command ).waitCompletion();
}
@Override
public Command createCommand( final RequestBuilder requestBuilder, final Set<Agent> agents ) {
return new CommandImpl( null, requestBuilder, agents );
}
@Override
public Command createCommand( final String description, final RequestBuilder requestBuilder,
final Set<Agent> agents ) {
return new CommandImpl( description, requestBuilder, agents );
}
@Override
public Command createCommand( final Set<AgentRequestBuilder> agentRequestBuilders ) {
return new CommandImpl( null, agentRequestBuilders );
}
@Override
public Command createCommand( final String description, final Set<AgentRequestBuilder> agentRequestBuilders ) {
return new CommandImpl( description, agentRequestBuilders );
}
@Override
public Command createBroadcastCommand( final RequestBuilder requestBuilder ) {
throw new UnsupportedOperationException();
}
} |
package cubicchunks.server;
import static cubicchunks.util.Coords.blockToCube;
import static cubicchunks.util.Coords.blockToLocal;
import static net.minecraft.util.math.MathHelper.clamp;
import com.google.common.base.Predicate;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ComparisonChain;
import cubicchunks.CubicChunks;
import cubicchunks.IConfigUpdateListener;
import cubicchunks.lighting.LightingManager;
import cubicchunks.util.CubePos;
import cubicchunks.util.XYZMap;
import cubicchunks.util.XZMap;
import cubicchunks.visibility.CubeSelector;
import cubicchunks.visibility.CuboidalCubeSelector;
import cubicchunks.world.ICubicWorldServer;
import cubicchunks.world.column.IColumn;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.management.PlayerChunkMap;
import net.minecraft.server.management.PlayerChunkMapEntry;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* A cubic chunks implementation of Player Manager.
* <p>
* This class manages loading and unloading cubes for players.
*/
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class PlayerCubeMap extends PlayerChunkMap implements LightingManager.IHeightChangeListener {
private static final Predicate<EntityPlayerMP> NOT_SPECTATOR = player -> player != null && !player.isSpectator();
private static final Predicate<EntityPlayerMP> CAN_GENERATE_CHUNKS = player -> player != null &&
(!player.isSpectator() || player.getServerWorld().getGameRules().getBoolean("spectatorsGenerateChunks"));
/**
* Comparator that specifies order in which cubes will be generated and sent to clients
*/
private static final Comparator<CubeWatcher> CUBE_ORDER = (watcher1, watcher2) ->
ComparisonChain.start().compare(
watcher1.getClosestPlayerDistance(),
watcher2.getClosestPlayerDistance()
).result();
/**
* Comparator that specifies order in which columns will be generated and sent to clients
*/
private static final Comparator<ColumnWatcher> COLUMN_ORDER = (watcher1, watcher2) ->
ComparisonChain.start().compare(
watcher1.getClosestPlayerDistance(),
watcher2.getClosestPlayerDistance()
).result();
/**
* Cube selector is used to find which cube positions need to be loaded/unloaded
* By default use CuboidalCubeSelector.
*/
private final CubeSelector cubeSelector = new CuboidalCubeSelector();
/**
* Mapping if entityId to PlayerCubeMap.PlayerWrapper objects.
*/
private final TIntObjectMap<PlayerWrapper> players = new TIntObjectHashMap<>();
/**
* Mapping of Cube positions to CubeWatchers (Cube equivalent of PlayerManager.PlayerInstance).
* Contains cube positions of all cubes loaded by players.
*/
private final XYZMap<CubeWatcher> cubeWatchers = new XYZMap<>(0.7f, 25 * 25 * 25);
/**
* Mapping of Column positions to ColumnWatchers.
* Contains column positions of all columns loaded by players.
* Exists for compatibility with vanilla and to send ColumnLoad/Unload packets to clients.
* Columns cannot be managed by client because they have separate data, like heightmap and biome array.
*/
private final XZMap<ColumnWatcher> columnWatchers = new XZMap<>(0.7f, 25 * 25);
/**
* All cubeWatchers that have pending block updates to send.
*/
private final Set<CubeWatcher> cubeWatchersToUpdate = new HashSet<>();
/**
* All columnWatchers that have pending height updates to send.
*/
private final Set<ColumnWatcher> columnWatchersToUpdate = new HashSet<>();
/**
* Contains all CubeWatchers that need to be sent to clients,
* but these cubes are not fully loaded/generated yet.
* <p>
* Note that this is not the same as cubesToGenerate list.
* Cube can be loaded while not being fully generated yet (not in the last GeneratorStageRegistry stage).
*/
private final List<CubeWatcher> cubesToSendToClients = new ArrayList<>();
/**
* Contains all CubeWatchers that still need to be loaded/generated.
* CubeWatcher constructor attempts to load cube from disk, but it won't generate it.
* Technically it can generate it, using the world's IGeneratorPipeline,
* but spectator players can't generate chunks if spectatorsGenerateChunks gamerule is set.
*/
private final List<CubeWatcher> cubesToGenerate = new ArrayList<>();
/**
* Contains all ColumnWatchers that need to be sent to clients,
* but these cubes are not fully loaded/generated yet.
* <p>
* Note that this is not the same as columnsToGenerate list.
* Columns can be loaded while not being fully generated yet
*/
private final List<ColumnWatcher> columnsToSendToClients = new ArrayList<>();
/**
* Contains all ColumnWatchers that still need to be loaded/generated.
* ColumnWatcher constructor attempts to load column from disk, but it won't generate it.
*/
private final List<ColumnWatcher> columnsToGenerate = new ArrayList<>();
private int horizontalViewDistance;
private int verticalViewDistance;
/**
* This is used only to force update of all CubeWatchers every 8000 ticks
*/
private long previousWorldTime = 0;
private boolean toGenerateNeedSort = true;
private boolean toSendToClientNeedSort = true;
@Nonnull private final CubeProviderServer cubeCache;
private volatile int maxGeneratedCubesPerTick = CubicChunks.Config.IntOptions.MAX_GENERATED_CUBES_PER_TICK.getValue();
public PlayerCubeMap(ICubicWorldServer worldServer) {
super((WorldServer) worldServer);
this.cubeCache = getWorld().getCubeCache();
this.setPlayerViewDistance(worldServer.getMinecraftServer().getPlayerList().getViewDistance(),
((ICubicPlayerList) worldServer.getMinecraftServer().getPlayerList()).getVerticalViewDistance());
worldServer.getLightingManager().registerHeightChangeListener(this);
}
/**
* This method exists only because vanilla needs it. It shouldn't be used anywhere else.
*/
// CHECKED: 1.10.2-12.18.1.2092
@Override
@Deprecated // Warning: Hacks! For vanilla use only! (WorldServer.updateBlocks())
public Iterator<Chunk> getChunkIterator() {
// GIVE TICKET SYSTEM FULL CONTROL
Iterator<Chunk> chunkIt = this.cubeCache.getLoadedChunks().iterator();
return new AbstractIterator<Chunk>() {
@Override protected Chunk computeNext() {
while (chunkIt.hasNext()) {
IColumn column = (IColumn) chunkIt.next();
if (column.shouldTick()) { // shouldTick is true when there Cubes with tickets the request to be ticked
return (Chunk) column;
}
}
return this.endOfData();
}
};
}
/**
* Updates all CubeWatchers and ColumnWatchers.
* Also sends packets to clients.
*/
// CHECKED: 1.10.2-12.18.1.2092
@Override
public void tick() {
getWorld().getProfiler().startSection("playerCubeMapTick");
long currentTime = this.getWorldServer().getTotalWorldTime();
getWorld().getProfiler().startSection("tickEntries");
//force update-all every 8000 ticks (400 seconds)
if (currentTime - this.previousWorldTime > 8000L) {
this.previousWorldTime = currentTime;
for (CubeWatcher playerInstance : this.cubeWatchers) {
playerInstance.update();
playerInstance.updateInhabitedTime();
}
}
//process instances to update
this.cubeWatchersToUpdate.forEach(CubeWatcher::update);
this.cubeWatchersToUpdate.clear();
this.columnWatchersToUpdate.forEach(ColumnWatcher::update);
this.columnWatchersToUpdate.clear();
getWorld().getProfiler().endStartSection("sortToGenerate");
//sort toLoadPending if needed, but at most every 4 ticks
if (this.toGenerateNeedSort && currentTime % 4L == 0L) {
this.toGenerateNeedSort = false;
Collections.sort(this.cubesToGenerate, CUBE_ORDER);
Collections.sort(this.columnsToGenerate, COLUMN_ORDER);
}
getWorld().getProfiler().endStartSection("sortToSend");
//sort cubesToSendToClients every other 4 ticks
if (this.toSendToClientNeedSort && currentTime % 4L == 2L) {
this.toSendToClientNeedSort = false;
Collections.sort(this.cubesToSendToClients, CUBE_ORDER);
Collections.sort(this.columnsToSendToClients, COLUMN_ORDER);
}
getWorld().getProfiler().endStartSection("generate");
if (!this.columnsToGenerate.isEmpty()) {
getWorld().getProfiler().startSection("columns");
Iterator<ColumnWatcher> iter = this.columnsToGenerate.iterator();
while (iter.hasNext()) {
ColumnWatcher entry = iter.next();
getWorld().getProfiler().startSection("column[" + entry.getPos().x + "," + entry.getPos().z + "]");
boolean success = entry.getColumn() != null;
if (!success) {
boolean canGenerate = entry.hasPlayerMatching(CAN_GENERATE_CHUNKS);
getWorld().getProfiler().startSection("generate");
success = entry.providePlayerChunk(canGenerate);
getWorld().getProfiler().endSection(); // generate
}
if (success) {
iter.remove();
if (entry.sendToPlayers()) {
this.columnsToSendToClients.remove(entry);
}
}
getWorld().getProfiler().endSection(); // column[x,z]
}
getWorld().getProfiler().endSection(); // columns
}
if (!this.cubesToGenerate.isEmpty()) {
getWorld().getProfiler().startSection("cubes");
long stopTime = System.nanoTime() + 50000000L;
int chunksToGenerate = maxGeneratedCubesPerTick;
Iterator<CubeWatcher> iterator = this.cubesToGenerate.iterator();
while (iterator.hasNext() && chunksToGenerate >= 0 && System.nanoTime() < stopTime) {
CubeWatcher watcher = iterator.next();
CubePos pos = watcher.getCubePos();
getWorld().getProfiler().startSection("chunk=" + pos);
boolean success = watcher.getCube() != null && watcher.getCube().isFullyPopulated() && watcher.getCube().isInitialLightingDone();
if (!success) {
boolean canGenerate = watcher.hasPlayerMatching(CAN_GENERATE_CHUNKS);
getWorld().getProfiler().startSection("generate");
success = watcher.providePlayerCube(canGenerate);
getWorld().getProfiler().endSection();
}
if (success) {
iterator.remove();
if (watcher.sendToPlayers()) {
this.cubesToSendToClients.remove(watcher);
}
--chunksToGenerate;
}
getWorld().getProfiler().endSection();//chunk[x, y, z]
}
getWorld().getProfiler().endSection(); // chunks
}
getWorld().getProfiler().endStartSection("send");
if (!this.columnsToSendToClients.isEmpty()) {
getWorld().getProfiler().startSection("columns");
Iterator<ColumnWatcher> iter = this.columnsToSendToClients.iterator();
while (iter.hasNext()) {
ColumnWatcher next = iter.next();
if (next.sendToPlayers()) {
iter.remove();
}
}
getWorld().getProfiler().endSection(); // columns
}
if (!this.cubesToSendToClients.isEmpty()) {
getWorld().getProfiler().startSection("cubes");
int toSend = 81 * 8;//sending cubes, so send 8x more at once
Iterator<CubeWatcher> it = this.cubesToSendToClients.iterator();
while (it.hasNext() && toSend >= 0) {
CubeWatcher playerInstance = it.next();
if (playerInstance.sendToPlayers()) {
it.remove();
--toSend;
}
}
getWorld().getProfiler().endSection(); // cubes
}
getWorld().getProfiler().endStartSection("unload");
//if there are no players - unload everything
if (this.players.isEmpty()) {
WorldProvider worldprovider = this.getWorldServer().provider;
if (!worldprovider.canRespawnHere()) {
this.getWorldServer().getChunkProvider().queueUnloadAll();
}
}
getWorld().getProfiler().endSection();//unload
getWorld().getProfiler().endSection();//playerCubeMapTick
}
// CHECKED: 1.10.2-12.18.1.2092
@Override
public boolean contains(int cubeX, int cubeZ) {
return this.columnWatchers.get(cubeX, cubeZ) != null;
}
// CHECKED: 1.10.2-12.18.1.2092
@Override
public PlayerChunkMapEntry getEntry(int cubeX, int cubeZ) {
return this.columnWatchers.get(cubeX, cubeZ);
}
/**
* Returns existing CubeWatcher or creates new one if it doesn't exist.
* Attempts to load the cube and send it to client.
* If it can't load it or send it to client - adds it to cubesToGenerate/cubesToSendToClients
*/
private CubeWatcher getOrCreateCubeWatcher(@Nonnull CubePos cubePos) {
CubeWatcher cubeWatcher = this.cubeWatchers.get(cubePos.getX(), cubePos.getY(), cubePos.getZ());
if (cubeWatcher == null) {
// make a new watcher
cubeWatcher = new CubeWatcher(this, cubePos);
this.cubeWatchers.put(cubeWatcher);
if (cubeWatcher.getCube() == null ||
!cubeWatcher.getCube().isFullyPopulated() ||
!cubeWatcher.getCube().isInitialLightingDone()) {
this.cubesToGenerate.add(cubeWatcher);
}
// this ends up being called early enough that client renderers aren't initialized yet and positions are wrong
if (!cubeWatcher.sendToPlayers()) {
this.cubesToSendToClients.add(cubeWatcher);
}
}
return cubeWatcher;
}
/**
* Returns existing ColumnWatcher or creates new one if it doesn't exist.
* Always creates the Column.
*/
private ColumnWatcher getOrCreateColumnWatcher(ChunkPos chunkPos) {
ColumnWatcher columnWatcher = this.columnWatchers.get(chunkPos.x, chunkPos.z);
if (columnWatcher == null) {
columnWatcher = new ColumnWatcher(this, chunkPos);
this.columnWatchers.put(columnWatcher);
if (columnWatcher.getColumn() == null) {
this.columnsToGenerate.add(columnWatcher);
}
if (!columnWatcher.sendToPlayers()) {
this.columnsToSendToClients.add(columnWatcher);
}
}
return columnWatcher;
}
// CHECKED: 1.10.2-12.18.1.2092
@Override
public void markBlockForUpdate(BlockPos pos) {
CubeWatcher cubeWatcher = this.getCubeWatcher(CubePos.fromBlockCoords(pos));
if (cubeWatcher != null) {
int localX = blockToLocal(pos.getX());
int localY = blockToLocal(pos.getY());
int localZ = blockToLocal(pos.getZ());
cubeWatcher.blockChanged(localX, localY, localZ);
}
}
@Override
public void heightUpdated(int blockX, int blockZ) {
ColumnWatcher columnWatcher = this.columnWatchers.get(blockToCube(blockX), blockToCube(blockZ));
if (columnWatcher != null) {
int localX = blockToLocal(blockX);
int localZ = blockToLocal(blockZ);
columnWatcher.heightChanged(localX, localZ);
}
}
// CHECKED: 1.10.2-12.18.1.2092
@Override
public void addPlayer(EntityPlayerMP player) {
PlayerWrapper playerWrapper = new PlayerWrapper(player);
playerWrapper.updateManagedPos();
CubePos playerCubePos = CubePos.fromEntity(player);
this.cubeSelector.forAllVisibleFrom(playerCubePos, horizontalViewDistance, verticalViewDistance, (currentPos) -> {
//create cubeWatcher and chunkWatcher
//order is important
ColumnWatcher chunkWatcher = getOrCreateColumnWatcher(currentPos.chunkPos());
//and add the player to them
if (!chunkWatcher.containsPlayer(player)) {
chunkWatcher.addPlayer(player);
}
CubeWatcher cubeWatcher = getOrCreateCubeWatcher(currentPos);
cubeWatcher.addPlayer(player);
});
this.players.put(player.getEntityId(), playerWrapper);
this.setNeedSort();
}
// CHECKED: 1.10.2-12.18.1.2092
@Override
public void removePlayer(EntityPlayerMP player) {
PlayerWrapper playerWrapper = this.players.get(player.getEntityId());
if (playerWrapper == null) {
CubicChunks.bigWarning("PlayerCubeMap#removePlayer got called when there is no player in this world! Things may break!");
return;
}
// Minecraft does something evil there: this method is called *after* changing the player's position
// so we need to use managerPosition there
CubePos playerCubePos = CubePos.fromEntityCoords(player.managedPosX, playerWrapper.managedPosY, player.managedPosZ);
this.cubeSelector.forAllVisibleFrom(playerCubePos, horizontalViewDistance, verticalViewDistance, (cubePos) -> {
// get the watcher
CubeWatcher watcher = getCubeWatcher(cubePos);
if (watcher != null) {
// remove from the watcher, it also removes the watcher if it becomes empty
watcher.removePlayer(player);
}
// remove column watchers if needed
ColumnWatcher columnWatcher = getColumnWatcher(cubePos.chunkPos());
if (columnWatcher == null) {
return;
}
if (columnWatcher.containsPlayer(player)) {
columnWatcher.removePlayer(player);
}
});
this.players.remove(player.getEntityId());
this.setNeedSort();
}
// CHECKED: 1.10.2-12.18.1.2092
@Override
public void updateMovingPlayer(EntityPlayerMP player) {
// the player moved
// if the player moved into a new chunk, update which chunks the player needs to know about
// then update the list of chunks that need to be sent to the client
// get the player info
PlayerWrapper playerWrapper = this.players.get(player.getEntityId());
if (playerWrapper == null) {
// vanilla sometimes does it, this is normal
return;
}
// did the player move into new cube?
if (!playerWrapper.cubePosChanged()) {
return;
}
this.updatePlayer(playerWrapper, playerWrapper.getManagedCubePos(), CubePos.fromEntity(player));
playerWrapper.updateManagedPos();
this.setNeedSort();
}
private void updatePlayer(PlayerWrapper entry, CubePos oldPos, CubePos newPos) {
getWorld().getProfiler().startSection("updateMovedPlayer");
Set<CubePos> cubesToRemove = new HashSet<>();
Set<CubePos> cubesToLoad = new HashSet<>();
Set<ChunkPos> columnsToRemove = new HashSet<>();
Set<ChunkPos> columnsToLoad = new HashSet<>();
getWorld().getProfiler().startSection("findChanges");
// calculate new visibility
this.cubeSelector.findChanged(oldPos, newPos, horizontalViewDistance, verticalViewDistance, cubesToRemove, cubesToLoad, columnsToRemove,
columnsToLoad);
getWorld().getProfiler().endStartSection("createColumns");
//order is important, columns first
columnsToLoad.forEach(pos -> {
ColumnWatcher columnWatcher = this.getOrCreateColumnWatcher(pos);
assert columnWatcher.getPos().equals(pos);
columnWatcher.addPlayer(entry.playerEntity);
});
getWorld().getProfiler().endStartSection("createCubes");
cubesToLoad.forEach(pos -> {
CubeWatcher cubeWatcher = this.getOrCreateCubeWatcher(pos);
assert cubeWatcher.getCubePos().equals(pos);
cubeWatcher.addPlayer(entry.playerEntity);
});
getWorld().getProfiler().endStartSection("removeCubes");
cubesToRemove.forEach(pos -> {
CubeWatcher cubeWatcher = this.getCubeWatcher(pos);
if (cubeWatcher != null) {
assert cubeWatcher.getCubePos().equals(pos);
cubeWatcher.removePlayer(entry.playerEntity);
}
});
getWorld().getProfiler().endStartSection("removeColumns");
columnsToRemove.forEach(pos -> {
ColumnWatcher columnWatcher = this.getColumnWatcher(pos);
if (columnWatcher != null) {
assert columnWatcher.getPos().equals(pos);
columnWatcher.removePlayer(entry.playerEntity);
}
});
getWorld().getProfiler().endSection();//removeColumns
getWorld().getProfiler().endSection();//updateMovedPlayer
}
// CHECKED: 1.10.2-12.18.1.2092
@Override
public boolean isPlayerWatchingChunk(EntityPlayerMP player, int cubeX, int cubeZ) {
ColumnWatcher columnWatcher = this.getColumnWatcher(new ChunkPos(cubeX, cubeZ));
return columnWatcher != null &&
columnWatcher.containsPlayer(player) &&
columnWatcher.isSentToPlayers();
}
public boolean isPlayerWatchingCube(EntityPlayerMP player, int cubeX, int cubeY, int cubeZ) {
CubeWatcher watcher = this.getCubeWatcher(new CubePos(cubeX, cubeY, cubeZ));
return watcher != null &&
watcher.containsPlayer(player) &&
watcher.isSentToPlayers();
}
// CHECKED: 1.10.2-12.18.1.2092
@Override
@Deprecated
public final void setPlayerViewRadius(int newHorizontalViewDistance) {
this.setPlayerViewDistance(newHorizontalViewDistance, verticalViewDistance);
}
public final void setPlayerViewDistance(int newHorizontalViewDistance, int newVerticalViewDistance) {
//this method is called by vanilla before these fields are initialized.
//and it doesn't really need to be called because in this case
//it reduces to setting the viewRadius field
if (this.players == null) {
return;
}
newHorizontalViewDistance = clamp(newHorizontalViewDistance, 3, 32);
newVerticalViewDistance = clamp(newVerticalViewDistance, 3, 32);
if (newHorizontalViewDistance == this.horizontalViewDistance && newVerticalViewDistance == this.verticalViewDistance) {
return;
}
int oldHorizontalViewDistance = this.horizontalViewDistance;
int oldVerticalViewDistance = this.verticalViewDistance;
// Somehow the view distances went in opposite directions
if ((newHorizontalViewDistance < oldHorizontalViewDistance && newVerticalViewDistance > oldVerticalViewDistance) ||
(newHorizontalViewDistance > oldHorizontalViewDistance && newVerticalViewDistance < oldVerticalViewDistance)) {
// Adjust the values separately to avoid imploding
setPlayerViewDistance(newHorizontalViewDistance, oldVerticalViewDistance);
setPlayerViewDistance(newHorizontalViewDistance, newVerticalViewDistance);
return;
}
for (PlayerWrapper playerWrapper : this.players.valueCollection()) {
EntityPlayerMP player = playerWrapper.playerEntity;
CubePos playerPos = playerWrapper.getManagedCubePos();
if (newHorizontalViewDistance > oldHorizontalViewDistance || newVerticalViewDistance > oldVerticalViewDistance) {
//if newRadius is bigger, we only need to load new cubes
this.cubeSelector.forAllVisibleFrom(playerPos, newHorizontalViewDistance, newVerticalViewDistance, pos -> {
//order is important
ColumnWatcher columnWatcher = this.getOrCreateColumnWatcher(pos.chunkPos());
if (!columnWatcher.containsPlayer(player)) {
columnWatcher.addPlayer(player);
}
CubeWatcher cubeWatcher = this.getOrCreateCubeWatcher(pos);
if (!cubeWatcher.containsPlayer(player)) {
cubeWatcher.addPlayer(player);
}
});
// either both got smaller or only one of them changed
} else {
//if it got smaller...
Set<CubePos> cubesToUnload = new HashSet<>();
Set<ChunkPos> columnsToUnload = new HashSet<>();
this.cubeSelector.findAllUnloadedOnViewDistanceDecrease(playerPos,
oldHorizontalViewDistance, newHorizontalViewDistance,
oldVerticalViewDistance, newVerticalViewDistance, cubesToUnload, columnsToUnload);
cubesToUnload.forEach(pos -> {
CubeWatcher cubeWatcher = this.getCubeWatcher(pos);
if (cubeWatcher != null && cubeWatcher.containsPlayer(player)) {
cubeWatcher.removePlayer(player);
} else {
CubicChunks.LOGGER.warn("cubeWatcher null or doesn't contain player on render distance change");
}
});
columnsToUnload.forEach(pos -> {
ColumnWatcher columnWatcher = this.getColumnWatcher(pos);
if (columnWatcher != null && columnWatcher.containsPlayer(player)) {
columnWatcher.removePlayer(player);
} else {
CubicChunks.LOGGER.warn("cubeWatcher null or doesn't contain player on render distance change");
}
});
}
}
this.horizontalViewDistance = newHorizontalViewDistance;
this.verticalViewDistance = newVerticalViewDistance;
this.setNeedSort();
}
private void setNeedSort() {
this.toGenerateNeedSort = true;
this.toSendToClientNeedSort = true;
}
@Override
public void entryChanged(PlayerChunkMapEntry entry) {
throw new UnsupportedOperationException();
}
@Override
public void removeEntry(PlayerChunkMapEntry entry) {
throw new UnsupportedOperationException();
}
void addToUpdateEntry(CubeWatcher cubeWatcher) {
this.cubeWatchersToUpdate.add(cubeWatcher);
}
void addToUpdateEntry(ColumnWatcher columnWatcher) {
this.columnWatchersToUpdate.add(columnWatcher);
}
// CHECKED: 1.10.2-12.18.1.2092
void removeEntry(CubeWatcher cubeWatcher) {
CubePos cubePos = cubeWatcher.getCubePos();
cubeWatcher.updateInhabitedTime();
this.cubeWatchers.remove(cubePos.getX(), cubePos.getY(), cubePos.getZ());
this.cubeWatchersToUpdate.remove(cubeWatcher);
this.cubesToGenerate.remove(cubeWatcher);
this.cubesToSendToClients.remove(cubeWatcher);
if (cubeWatcher.getCube() != null) {
cubeWatcher.getCube().getTickets().remove(cubeWatcher); // remove the ticket, so this Cube can unload
}
//don't unload, ChunkGc unloads chunks
}
// CHECKED: 1.10.2-12.18.1.2092
public void removeEntry(ColumnWatcher entry) {
ChunkPos pos = entry.getPos();
entry.updateChunkInhabitedTime();
this.columnWatchers.remove(pos.x, pos.z);
this.columnsToGenerate.remove(entry);
this.columnsToSendToClients.remove(entry);
}
@Nullable public CubeWatcher getCubeWatcher(CubePos pos) {
return this.cubeWatchers.get(pos.getX(), pos.getY(), pos.getZ());
}
@Nullable public ColumnWatcher getColumnWatcher(ChunkPos pos) {
return this.columnWatchers.get(pos.x, pos.z);
}
@Nonnull public ICubicWorldServer getWorld() {
return (ICubicWorldServer) this.getWorldServer();
}
public boolean contains(CubePos coords) {
return this.cubeWatchers.get(coords.getX(), coords.getY(), coords.getZ()) != null;
}
private static final class PlayerWrapper {
final EntityPlayerMP playerEntity;
private double managedPosY;
PlayerWrapper(EntityPlayerMP player) {
this.playerEntity = player;
}
void updateManagedPos() {
this.playerEntity.managedPosX = playerEntity.posX;
this.managedPosY = playerEntity.posY;
this.playerEntity.managedPosZ = playerEntity.posZ;
}
int getManagedCubePosX() {
return blockToCube(this.playerEntity.managedPosX);
}
int getManagedCubePosY() {
return blockToCube(this.managedPosY);
}
int getManagedCubePosZ() {
return blockToCube(this.playerEntity.managedPosZ);
}
CubePos getManagedCubePos() {
return new CubePos(getManagedCubePosX(), getManagedCubePosY(), getManagedCubePosZ());
}
boolean cubePosChanged() {
// did the player move far enough to matter?
double blockDX = blockToCube(playerEntity.posX) - this.getManagedCubePosX();
double blockDY = blockToCube(playerEntity.posY) - this.getManagedCubePosY();
double blockDZ = blockToCube(playerEntity.posZ) - this.getManagedCubePosZ();
double distanceSquared = blockDX * blockDX + blockDY * blockDY + blockDZ * blockDZ;
return distanceSquared > 0.9;//0.9 instead of 1 because floating-point numbers may be weird
}
}
/**
* Return iterator over 'CubeWatchers' of all cubes loaded
* by players. Iterator first element defined by seed.
*
* @param seed
*/
public Iterator<CubeWatcher> getRandomWrappedCubeWatcherIterator(int seed) {
return this.cubeWatchers.randomWrappedIterator(seed);
}
} |
package de.hbz.lobid.helper;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeBase;
/**
* @author Jan Schnasse
*
*/
public class EtikettMaker implements EtikettMakerInterface {
private static final String TYPE = "type";
private static final String ID = "id";
final static Logger logger = LoggerFactory.getLogger(EtikettMaker.class);
/**
* A map with URIs as key
*/
Map<String, Etikett> pMap = new HashMap<>();
/**
* A map with Shortnames as key
*/
Map<String, Etikett> nMap = new HashMap<>();
/**
* The context will be loaded on startup. You can reload the context with POST
* /utils/reloadContext
*
*/
Map<String, Object> context = new HashMap<>();
/**
* The labels will be loaded on startup. You can reload the context with POST
* /utils/reloadLabels
*
*/
List<Etikett> labels = new ArrayList<>();
/**
* The profile provides a json context an labels
*
* @param labelIn input stream to a labels file
*/
public EtikettMaker(InputStream labelIn) {
initMaps(labelIn);
initContext();
}
/*
* (non-Javadoc)
*
* @see de.hbz.lobid.helper.EtikettMakerInterface#getContext()
*/
@Override
public Map<String, Object> getContext() {
return context;
}
/*
* (non-Javadoc)
*
* @see de.hbz.lobid.helper.EtikettMakerInterface#getEtikett(java.lang.String)
*/
@Override
public Etikett getEtikett(String uri) {
Etikett e = pMap.get(uri);
if (e == null) {
e = new Etikett(uri);
e.name = getJsonName(uri);
}
if (e.label == null || e.label.isEmpty()) {
e.label = e.uri;
}
logger.debug("Find etikett for " + uri + " : " + e.name);
return e;
}
private void initContext() {
context = createContext();
}
private void initMaps(InputStream labelIn) {
try {
labels = createLabels(labelIn);
for (Etikett etikett : labels) {
pMap.put(etikett.uri, etikett);
nMap.put(etikett.name, etikett);
}
} catch (Exception e) {
logger.error("", e);
}
}
private static List<Etikett> createLabels(InputStream labelIn) {
logger.info("Create labels....");
List<Etikett> result = new ArrayList<>();
result = loadFile(labelIn, new ObjectMapper().getTypeFactory()
.constructCollectionType(List.class, Etikett.class));
if (result == null) {
logger.info("...not succeeded!");
} else {
logger.info("...succeed!");
}
return result;
}
Map<String, Object> createContext() {
Map<String, Object> pmap;
Map<String, Object> cmap = new HashMap<>();
for (Etikett l : labels) {
if ("class".equals(l.referenceType) || l.referenceType == null
|| l.name == null)
continue;
pmap = new HashMap<>();
pmap.put("@id", l.uri);
if (!"String".equals(l.referenceType)) {
pmap.put("@type", l.referenceType);
}
if (l.container != null) {
pmap.put("@container", l.container);
}
cmap.put(l.name, pmap);
}
cmap.put(ID, "@id");
cmap.put(TYPE, "@type");
Map<String, Object> contextObject = new HashMap<>();
contextObject.put("@context", cmap);
return contextObject;
}
private static <T> T loadFile(InputStream labelIn, TypeBase type) {
try (InputStream in = labelIn) {
return new ObjectMapper().readValue(in, type);
} catch (Exception e) {
throw new RuntimeException("Error during initialization!", e);
}
}
/**
* @param predicate
* @return The short name of the predicate uses String.split on first index of
* '#' or last index of '/'
*/
String getJsonName(String predicate) {
Etikett e = pMap.get(predicate);
if (e == null) {
throw new RuntimeException(predicate
+ ": no json name available. Please provide a labels.json file with proper 'name' entry.");
}
return e.name;
}
@Override
public Etikett getEtikettByName(String name) {
return nMap.get(name);
}
@Override
public Collection<Etikett> getValues() {
return pMap.values();
}
@Override
public boolean supportsLabelsForValues() {
return false;
}
@Override
public String getIdAlias() {
return ID;
}
@Override
public String getTypeAlias() {
return TYPE;
}
@Override
public String getLabelKey() {
return null;
}
} |
package org.xwiki.rendering.macro.script;
import org.xwiki.properties.annotation.PropertyDescription;
/**
* Parameters for the Script Macro.
*
* @version $Id$
* @since 1.9M1
*/
public class DefaultScriptMacroParameters extends JSR223ScriptMacroParameters
{
/**
* The identifier of the script language.
*/
private String language;
/**
* @param language the identifier of the script language.
*/
@PropertyDescription("The identifier of the script language (\"groovy\", \"python\", etc)")
public void setLanguage(String language)
{
this.language = language;
}
/**
* @return the identifier of the script language.
*/
public String getLanguage()
{
return this.language;
}
} |
package edu.jhu.hlt.optimize;
import java.util.Arrays;
import org.apache.log4j.Logger;
import cc.mallet.optimize.BackTrackLineSearch;
import cc.mallet.optimize.BetterLimitedMemoryBFGS;
import cc.mallet.optimize.InvalidOptimizableException;
import cc.mallet.optimize.Optimizable;
import edu.jhu.hlt.optimize.function.DifferentiableFunction;
import edu.jhu.hlt.optimize.function.DifferentiableFunctionOpts;
import edu.jhu.prim.vector.IntDoubleDenseVector;
import edu.jhu.prim.vector.IntDoubleVector;
/**
* Wrapper of Mallet's L-BFGS implementation.
* @author mgormley
*/
public class MalletLBFGS implements Optimizer<DifferentiableFunction> {
public static class MalletLBFGSPrm {
/** Max iterations. */
public int maxIterations = 1000;
/** Function value tolerance. */
public double tolerance = .0001;
/** Gradient tolerance.*/
public double gradientTolerance = .001;
/** Number of corrections. */
public int numberOfCorrections = 4;
/** termination conditions: either
* a) abs(delta x/x) < REL_TOLX for all coordinates
* b) abs(delta x) < ABS_TOLX for all coordinates
* c) sufficient function increase (uses ALF)
*/
public double lsRelTolx = 1e-7;
/** tolerance on absolute value difference */
public double lsAbsTolx = 1e-4;
}
/**
* Wrapper of edu.jhu.Function to implement Optimizable.ByGradientValue.
*
* @author mgormley
*
*/
private static class MalletFunction implements Optimizable.ByGradientValue {
private DifferentiableFunction function;
private IntDoubleVector params;
private IntDoubleVector gradient;
private double value;
private boolean areGradientAndValueCached;
public MalletFunction(DifferentiableFunction function, IntDoubleVector point) {
this.function = function;
params = point;
gradient = null;
areGradientAndValueCached = false;
}
@Override
public int getNumParameters() {
return function.getNumDimensions();
}
@Override
public double getParameter(int i) {
return params.get(i);
}
@Override
public void getParameters(double[] buffer) {
// Copy the parameters from params to the buffer.
for (int i=0; i<buffer.length; i++) {
buffer[i] = params.get(i);
}
}
@Override
public void setParameter(int i, double value) {
params.set(i, value);
// Invalidate the cached gradient.
areGradientAndValueCached = false;
}
@Override
public void setParameters(double[] buffer) {
// Copy the parameters from the buffer to params.
for (int i=0; i<buffer.length; i++) {
params.set(i, buffer[i]);
}
// Invalidate the cached gradient.
areGradientAndValueCached = false;
}
@Override
public double getValue() {
maybeUpdateGradientAndValue();
return value;
}
@Override
public void getValueGradient(double[] buffer) {
maybeUpdateGradientAndValue();
// Copy the gradient to the buffer.
for (int i=0; i<buffer.length; i++) {
buffer[i] = gradient.get(i);
}
}
private void maybeUpdateGradientAndValue() {
if (!areGradientAndValueCached) {
// Recompute the value:
value = function.getValue(params);
// Recompute the gradient.
gradient = function.getGradient(params);
areGradientAndValueCached = true;
}
}
}
private static final Logger log = Logger.getLogger(MalletLBFGS.class);
private MalletLBFGSPrm prm;
private boolean converged;
public MalletLBFGS(MalletLBFGSPrm prm) {
this.prm = prm;
}
@Override
public boolean maximize(DifferentiableFunction function, IntDoubleVector point) {
MalletFunction mf = new MalletFunction(function, point);
BetterLimitedMemoryBFGS lbfgs = new BetterLimitedMemoryBFGS(mf);
lbfgs.setTolerance(prm.tolerance);
lbfgs.setGradientTolerance(prm.gradientTolerance);
BackTrackLineSearch btls = new BackTrackLineSearch(mf);
btls.setAbsTolx(prm.lsAbsTolx);
btls.setRelTolx(prm.lsRelTolx);
lbfgs.setLineOptimizer(btls);
try {
converged = lbfgs.optimize(prm.maxIterations);
} catch (InvalidOptimizableException e) {
log.warn("Error during optimization: " + e.getMessage());
log.warn("Continuing as if there were no error.");
converged = false;
}
return converged;
}
@Override
public boolean minimize(DifferentiableFunction function, IntDoubleVector point) {
return maximize(new DifferentiableFunctionOpts.NegateFunction(function), point);
}
} |
package ee.pardiralli.web;
import ee.pardiralli.domain.DonationChart;
import ee.pardiralli.domain.FeedbackType;
import ee.pardiralli.dto.RaceDTO;
import ee.pardiralli.service.RaceService;
import ee.pardiralli.service.StatisticsService;
import ee.pardiralli.util.ControllerUtil;
import ee.pardiralli.util.RaceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@Controller
public class RaceController {
private final RaceService raceService;
private final StatisticsService statisticsService;
@Autowired
public RaceController(RaceService raceService, StatisticsService statisticsService) {
this.raceService = raceService;
this.statisticsService = statisticsService;
}
@GetMapping("/settings")
public String getTemplate(RaceDTO raceDTO, Model model) {
model.addAttribute("races", raceService.getAllRacesAsDtos());
return "settings";
}
@PostMapping("/settingschart")
public
@ResponseBody
DonationChart setSoldItemsAndDonations(@RequestParam("beginning") String start,
@RequestParam("finish") String end) {
try {
return new DonationChart(statisticsService.createDataByRace(
new SimpleDateFormat("yyyy-MM-dd").parse(start),
new SimpleDateFormat("yyyy-MM-dd").parse(end))
);
} catch (ParseException e) {
return new DonationChart(new ArrayList<>());
}
}
@PostMapping("/settings")
public String updateExisting(RaceDTO raceDTO, BindingResult results, Model model) {
if (raceDTO.getIsNew()) {
if (!raceService.hasNoOpenedRaces()) {
ControllerUtil.setFeedback(model, FeedbackType.ERROR, "Korraga saab olla avatud ainult üks Pardiralli!");
} else if (!RaceUtil.raceDatesAreLegal(raceDTO)) {
ControllerUtil.setFeedback(model, FeedbackType.ERROR, "Ebasobivad kuupäevad!");
} else if (!results.hasFieldErrors()) {
raceService.saveNewRace(raceDTO);
ControllerUtil.setFeedback(model, FeedbackType.SUCCESS, "Uus võistlus avatud!");
} else {
ControllerUtil.setFeedback(model, FeedbackType.ERROR, "Viga sisendis!");
}
} else {
if (canManipulateRace(raceDTO)) {
raceService.updateRace(raceDTO);
ControllerUtil.setFeedback(model, FeedbackType.INFO,
raceDTO.getIsOpen() ? "Pardiralli edukalt avatud" : "Pardiralli edukalt suletud!");
} else {
ControllerUtil.setFeedback(model, FeedbackType.ERROR, "Korraga saab olla avatud ainult üks Pardiralli!");
}
}
model.addAttribute("races", raceService.getAllRacesAsDtos());
return "settings";
}
private Boolean canManipulateRace(RaceDTO raceDTO) {
return raceDTO.getId() != null && raceDTO.getIsOpen() != null && raceService.raceExists(raceDTO) &&
(raceService.hasNoOpenedRaces() && raceDTO.getIsOpen() || !raceDTO.getIsOpen());
}
@InitBinder
public void initBinder(WebDataBinder binder) {
CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true);
binder.registerCustomEditor(Date.class, editor);
}
} |
package eme.generator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EGenericType;
import org.eclipse.emf.ecore.EOperation;
import org.eclipse.emf.ecore.ETypeParameter;
import org.eclipse.emf.ecore.ETypedElement;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.EcorePackage;
import eme.generator.hierarchies.ExternalTypeHierarchy;
import eme.model.ExtractedMethod;
import eme.model.ExtractedType;
import eme.model.IntermediateModel;
import eme.model.datatypes.ExtractedDataType;
import eme.model.datatypes.ExtractedTypeParameter;
import eme.model.datatypes.WildcardStatus;
/**
* Generator class for the generation of Ecore data types ({@link EDataType})
* @author Timur Saglam
*/
public class EDataTypeGenerator {
private static final Logger logger = LogManager.getLogger(EDataTypeGenerator.class.getName());
private final Map<String, EDataType> dataTypeMap;
private final Map<String, EClassifier> eClassifierMap;
private final EcoreFactory ecoreFactory;
private final IntermediateModel model;
private final ExternalTypeHierarchy typeHierarchy;
/**
* Basic constructor, builds the type maps.
* @param model is the {@link IntermediateModel}.
* @param eClassifierMap is the list of created {@link EClassifier}s. This is needed to get custom data types.
* @param typeHierarchy is the external type package hierarchy.
*/
public EDataTypeGenerator(IntermediateModel model, Map<String, EClassifier> eClassifierMap, ExternalTypeHierarchy typeHierarchy) {
this.model = model;
this.eClassifierMap = eClassifierMap; // set eClassifier map.
this.typeHierarchy = typeHierarchy;
ecoreFactory = EcoreFactory.eINSTANCE; // get ecore factory.
dataTypeMap = new HashMap<String, EDataType>(); // create type map.
fillMap(); // fill type map.
}
/**
* Adds data type (Either {@link EDataType} or {@link EGenericType}) to an {@link ETypedElement} from an
* {@link ExtractedDataType}.
* @param element is the {@link ETypedElement}.
* @param dataType is the {@link EDataType}.
* @param source is the source of {@link ETypeParameter}s, an {@link TypeParameterSource}.
*/
public void addDataType(ETypedElement element, ExtractedDataType dataType, TypeParameterSource source) {
if (source.containsTypeParameter(dataType)) {
element.setEGenericType(generateGeneric(dataType, source));
} else {
element.setEType(generate(dataType)); // generate data type
}
addGenericArguments(element.getEGenericType(), dataType, source); // add generic
}
/**
* Adds exception (Either {@link EDataType} or {@link EGenericType}) to an {@link EOperation} from an
* {@link ExtractedDataType}.
* @param operation is the {@link EOperation}.
* @param exception is the {@link ExtractedDataType}.
* @param source is the source of {@link ETypeParameter}s, an {@link TypeParameterSource}.
*/
public void addException(EOperation operation, ExtractedDataType exception, TypeParameterSource source) {
if (source.containsTypeParameter(exception)) {
operation.getEGenericExceptions().add(generateGeneric(exception, source));
} else {
operation.getEExceptions().add(generate(exception)); // generate data type
}
}
/**
* Adds all generic arguments from an {@link ExtractedDataType} to an {@link EGenericType}. For all generic
* arguments add their generic arguments recursively.
* @param genericType is the generic type of an attribute, a parameter or a method.
* @param dataType is the extracted data type, an attribute, a parameter or a return type.
* @param source is the source of {@link ETypeParameter}s, an {@link TypeParameterSource}.
*/
public void addGenericArguments(EGenericType genericType, ExtractedDataType dataType, TypeParameterSource source) {
for (ExtractedDataType genericArgument : dataType.getGenericArguments()) { // for every generic argument
EGenericType eArgument = ecoreFactory.createEGenericType(); // create ETypeArgument as EGenericType
if (genericArgument.isWildcard()) { // wildcard argument:
addWildcardBound(eArgument, genericArgument, source);
} else { // normal argument or type parameter
generateBoundType(eArgument, genericArgument, source);
}
addGenericArguments(eArgument, genericArgument, source); // recursively add generic arguments
genericType.getETypeArguments().add(eArgument); // add ETypeArgument to original generic type
}
}
/**
* Adds all generic type parameters from an {@link ExtractedType} to a {@link EClassifier}.
* @param eClassifier is the EClassifier.
* @param type is the extracted type.
*/
public void addTypeParameters(EClassifier eClassifier, ExtractedType type) {
eClassifier.getETypeParameters().addAll(generateETypeParameters(type.getTypeParameters()));
finishTypeParameters(eClassifier.getETypeParameters(), type.getTypeParameters(), new TypeParameterSource(eClassifier));
}
/**
* Adds all generic type parameters from an {@link ExtractedMethod} to a {@link EOperation}.
* @param eOperation is the {@link EOperation}.
* @param method is the {@link ExtractedMethod}.
*/
public void addTypeParameters(EOperation eOperation, ExtractedMethod method) {
eOperation.getETypeParameters().addAll(generateETypeParameters(method.getTypeParameters()));
finishTypeParameters(eOperation.getETypeParameters(), method.getTypeParameters(), new TypeParameterSource(eOperation));
}
/**
* Adds all bounds of an {@link ExtractedTypeParameter} to a {@link ETypeParameter}.
*/
private void addBounds(ETypeParameter eTypeParameter, ExtractedTypeParameter typeParameter, TypeParameterSource source) {
EGenericType eBound; // ecore type parameter bound
for (ExtractedDataType bound : typeParameter.getBounds()) { // for all bounds
if (!Object.class.getName().equals(bound.getFullType())) { // ignore object bound
eBound = ecoreFactory.createEGenericType(); // create object
generateBoundType(eBound, bound, source); // set type of bound
addGenericArguments(eBound, bound, source); // add generic arguments of bound
eTypeParameter.getEBounds().add(eBound); // add bound to type parameter
}
}
}
/**
* Adds a bound to an wild card argument if it has one.
*/
private void addWildcardBound(EGenericType eArgument, ExtractedDataType genericArgument, TypeParameterSource source) {
WildcardStatus status = genericArgument.getWildcardStatus(); // get wild card status
if (status != WildcardStatus.UNBOUND) { // if has bounds:
EGenericType bound = ecoreFactory.createEGenericType(); // create bound
generateBoundType(bound, genericArgument, source); // generate bound type
if (status == WildcardStatus.LOWER_BOUND) {
eArgument.setELowerBound(bound); // add lower bound
} else {
eArgument.setEUpperBound(bound); // add upper bound
}
}
}
/**
* Default data type map entries.
*/
private void fillMap() {
dataTypeMap.put("boolean", EcorePackage.eINSTANCE.getEBoolean());
dataTypeMap.put("byte", EcorePackage.eINSTANCE.getEByte());
dataTypeMap.put("char", EcorePackage.eINSTANCE.getEChar());
dataTypeMap.put("double", EcorePackage.eINSTANCE.getEDouble());
dataTypeMap.put("float", EcorePackage.eINSTANCE.getEFloat());
dataTypeMap.put("int", EcorePackage.eINSTANCE.getEInt());
dataTypeMap.put("long", EcorePackage.eINSTANCE.getELong());
dataTypeMap.put("short", EcorePackage.eINSTANCE.getEShort());
dataTypeMap.put("java.lang.Boolean", EcorePackage.eINSTANCE.getEBooleanObject());
dataTypeMap.put("java.lang.Byte", EcorePackage.eINSTANCE.getEByteObject());
dataTypeMap.put("java.lang.Character", EcorePackage.eINSTANCE.getECharacterObject());
dataTypeMap.put("java.lang.Double", EcorePackage.eINSTANCE.getEDoubleObject());
dataTypeMap.put("java.lang.Float", EcorePackage.eINSTANCE.getEFloatObject());
dataTypeMap.put("java.lang.Integer", EcorePackage.eINSTANCE.getEIntegerObject());
dataTypeMap.put("java.lang.Long", EcorePackage.eINSTANCE.getELongObject());
dataTypeMap.put("java.lang.Short", EcorePackage.eINSTANCE.getEShortObject());
dataTypeMap.put("java.lang.String", EcorePackage.eINSTANCE.getEString());
dataTypeMap.put("java.lang.Object", EcorePackage.eINSTANCE.getEJavaObject());
dataTypeMap.put("java.lang.Class", EcorePackage.eINSTANCE.getEJavaClass());
}
/**
* Adds all bounds for every {@link ETypeParameter} of an {@link EClassifier}.
*/
private void finishTypeParameters(List<ETypeParameter> eTypeParameters, List<ExtractedTypeParameter> typeParameters, TypeParameterSource source) {
Iterator<ExtractedTypeParameter> iterator = typeParameters.iterator();
Iterator<ETypeParameter> ecoreIterator = eTypeParameters.iterator();
while (iterator.hasNext() && ecoreIterator.hasNext()) {
addBounds(ecoreIterator.next(), iterator.next(), source);
}
}
/**
* Returns an {@link EClassifier} for an {@link ExtractedDataType} that can be used as data type for methods and
* attributes. The {@link EClassifier} is either (1.) a custom class from the model, or (2.) or an external class
* that has to be created as data type, or (3.) an already known data type (Basic type or already created)
*/
private EClassifier generate(ExtractedDataType extractedDataType) {
EDataType eDataType;
String fullName = extractedDataType.getFullType();
if (eClassifierMap.containsKey(fullName)) { // if is custom class
return eClassifierMap.get(fullName);
} else if (dataTypeMap.containsKey(fullName)) { // if is basic type or already known
return dataTypeMap.get(fullName); // access EDataType
} else { // if its an external type
eDataType = generateExternalType(extractedDataType); // create new EDataType
typeHierarchy.add(eDataType);
return eDataType;
}
}
/**
* Sets the type of an {@link EGenericType} from a bound {@link ExtractedDataType}. This is either an
* {@link ETypeParameter} if the {@link ExtractedDataType} is a type parameter in the {@link TypeParameterSource} or
* {@link EClassifier} if not.
*/
private void generateBoundType(EGenericType genericType, ExtractedDataType boundType, TypeParameterSource source) {
if (source.containsTypeParameter(boundType)) {
genericType.setETypeParameter(source.getTypeParameter(boundType));
} else {
genericType.setEClassifier(generate(boundType));
}
}
/**
* Generates list of {@link ETypeParameter}s from list of {@link ExtractedTypeParameter}s.
*/
private List<ETypeParameter> generateETypeParameters(List<ExtractedTypeParameter> typeParameters) {
ETypeParameter eTypeParameter; // ecore type parameter
List<ETypeParameter> eTypeParameters = new LinkedList<ETypeParameter>();
for (ExtractedTypeParameter typeParameter : typeParameters) { // for all type parameters
eTypeParameter = ecoreFactory.createETypeParameter(); // create object
eTypeParameter.setName(typeParameter.getIdentifier()); // set name
eTypeParameters.add(eTypeParameter);
}
return eTypeParameters;
}
/**
* Creates a new EDataType from an ExtractedDataType. The new EDataType can then be accessed from the type map or
* array type map.
*/
private EDataType generateExternalType(ExtractedDataType extractedDataType) {
if (dataTypeMap.containsKey(extractedDataType.getFullType())) { // if already created:
throw new IllegalArgumentException("Can't create an already created data type."); // throw exception
}
EDataType eDataType = ecoreFactory.createEDataType();
eDataType.setName(extractedDataType.getType());
eDataType.setInstanceTypeName(extractedDataType.getFullType()); // set full name
String dataTypeName = extractedDataType.getFullArrayType(); // get type name without array brackets.
if (model.containsExternal(dataTypeName)) {
addTypeParameters(eDataType, model.getExternalType(dataTypeName)); // add parameters from external type
} else if (!extractedDataType.getGenericArguments().isEmpty()) { // if external type is unknown
logger.error("Can not resolve type parameters for " + extractedDataType.toString());
}
dataTypeMap.put(extractedDataType.getFullType(), eDataType); // store in map for later use
return eDataType;
}
/**
* Returns an generic type parameter, which is an {@link EGenericType}, for an {@link ExtractedDataType} that can be
* used as generic argument for methods and attributes.
*/
private EGenericType generateGeneric(ExtractedDataType dataType, TypeParameterSource source) {
if (source.containsTypeParameter(dataType)) {
EGenericType genericType = ecoreFactory.createEGenericType();
genericType.setETypeParameter(source.getTypeParameter(dataType));
return genericType;
}
throw new IllegalArgumentException("The data type is not an type parameter: " + dataType.toString());
}
} |
package eu.goodlike.resty.url;
import eu.goodlike.misc.SpecialUtils;
import eu.goodlike.neat.Null;
import eu.goodlike.neat.string.Str;
import eu.goodlike.resty.http.HttpMethod;
import eu.goodlike.resty.http.HttpRequest;
import eu.goodlike.resty.http.steps.BodyTypeStep;
import eu.goodlike.resty.http.steps.QueryParamStep;
import eu.goodlike.resty.http.steps.custom.CustomDynamicStepBuilder;
import eu.goodlike.resty.misc.PathVar;
import java.util.*;
import java.util.stream.Stream;
import static eu.goodlike.misc.Constants.NOT_NULL_NOT_BLANK;
import static eu.goodlike.resty.http.HttpMethod.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
/**
* <pre>
* This class represents an adjustable URL
*
* It consists of:
* 1) protocol - http or https
* 2) IP address - basically any non-null non-blank String is allowed
* 3) port (optional); 1 <= port <= 65535
* 4) path (optional, can have variables) - any strings that are separated by '/', variables start with ':'
*
* Parameters are added as part of HTTP request creation process
*
* Objects of this class are immutable
* </pre>
*/
public final class DynamicURL {
/**
* @return url String made from this DynamicURL
*/
public String getUrl() {
return Str.of(protocol, ":
.andIf(port != null, ":", port)
.andSome("/", path)
.toString();
}
/**
* @return this DynamicURL with given protocol; only constructs a new one if needed
* @throws NullPointerException if protocol is null
*/
public DynamicURL withProtocol(Protocol protocol) {
Null.check(protocol).ifAny("Protocol cannot be null");
return this.protocol == protocol ? this : new DynamicURL(protocol, ip, port, path);
}
/**
* @return this DynamicURL with HTTP protocol; only constructs a new one if needed
*/
public DynamicURL withHTTP() {
return withProtocol(Protocol.http);
}
/**
* @return this DynamicURL with HTTPS protocol; only constructs a new one if needed
*/
public DynamicURL withHTTPS() {
return withProtocol(Protocol.https);
}
public DynamicURL withIP(String ip) {
Null.check(ip).ifAny("IP cannot be null");
NOT_NULL_NOT_BLANK.ifInvalidThrow(ip, DynamicURL::invalidIPMessage);
return this.ip.equals(ip) ? this : new DynamicURL(protocol, ip, port, path);
}
public DynamicURL withPort(int port) {
if (port < MIN_PORT || port > MAX_PORT)
throw new IllegalArgumentException("Port must be between " + MIN_PORT + " and " + MAX_PORT);
return this.port != null && this.port == port ? this : new DynamicURL(protocol, ip, port, path);
}
/**
* @return this DynamicURL without any port; only constructs a new one if needed
*/
public DynamicURL withoutPort() {
return this.port == null ? this : new DynamicURL(protocol, ip, null, path);
}
public DynamicURL withPath(String... path) {
Null.checkAlone(path).ifAny("Path cannot be null");
return withPath(Arrays.asList(path));
}
public DynamicURL withPath(List<String> path) {
Null.checkCollection(path).ifAny("Path cannot be or contain null");
return this.path.equals(path) ? this : new DynamicURL(protocol, ip, null, parsedPath(path));
}
/**
* @return this DynamicURL without any path; only constructs a new one if needed
*/
public DynamicURL withoutPath() {
return this.path.isEmpty() ? this : new DynamicURL(protocol, ip, port, Collections.emptyList());
}
public DynamicURL appendPath(String... path) {
Null.checkAlone(path).ifAny("Path cannot be null");
return path.length == 0 ? this : appendPath(Arrays.asList(path));
}
public DynamicURL appendPath(List<String> path) {
Null.checkCollection(path).ifAny("Path cannot be or contain null");
if (path.size() == 0)
return this;
List<String> newPath = new ArrayList<>(this.path);
newPath.addAll(parsedPath(path));
return new DynamicURL(protocol, ip, port, newPath);
}
/**
* @return true if any of the path parts are variables, false otherwise
*/
public boolean hasVariables() {
return !pathVariables.isEmpty();
}
/**
* The name of the variable can optionally start with ":"
* @return true if the url contains variable with given name, false otherwise
* @throws NullPointerException if name is null
*/
public boolean hasVariable(String name) {
Null.check(name).ifAny("Variable name cannot be null");
return pathVariables.contains(name.startsWith(":") ? name : ":" + name);
}
/**
* @return true if the string representing a path is variable, false otherwise
* @throws NullPointerException if pathPart is null
*/
public static boolean isVariable(String pathPart) {
Null.check(pathPart).ifAny("Variable name cannot be null");
return pathPart.startsWith(":");
}
public DynamicURL withNextValues(Object... variables) {
Null.checkArray(variables).ifAny("Variable array cannot be or contain null");
if (variables.length == 0)
return this;
if (variables.length > pathVariables.size())
throw new IllegalArgumentException("Too many variables passed; current count: "
+ pathVariables.size() + "; passed: " + variables.length);
List<String> newPath = new ArrayList<>(path);
int nextIndex = 0;
for (Object variable : variables) {
String value = SpecialUtils.urlEncode(variable);
PathVar.validateValue(value);
for (int i = nextIndex; i < newPath.size(); i++)
if (isVariable(newPath.get(i))) {
newPath.set(i, value);
nextIndex = i + 1;
break;
}
}
return withPath(newPath);
}
public DynamicURL withNextValue(Object variable) {
Null.check(variable).ifAny("Variable value cannot be null");
if (!hasVariables())
throw new IllegalArgumentException("No more variables left to pass values into");
String value = SpecialUtils.urlEncode(variable);
PathVar.validateValue(value);
List<String> newPath = new ArrayList<>(path);
for (int i = 0; i < newPath.size(); i++)
if (isVariable(newPath.get(i))) {
newPath.set(i, value);
break;
}
return withPath(newPath);
}
public DynamicURL withValues(PathVar... variables) {
Null.checkArray(variables).ifAny("Variable array cannot be or contain null");
if (variables.length == 0)
return this;
if (!Stream.of(variables).map(PathVar::name).allMatch(this::hasVariable))
throw new IllegalArgumentException("Cannot find these variables in the URL: "
+ Stream.of(variables).map(PathVar::name).filter(this::notHasVariable).collect(joining(", ")));
List<String> newPath = new ArrayList<>(path);
for (PathVar variable : variables)
for (int i = 0; i < newPath.size(); i++)
if (newPath.get(i).equals(variable.name())) {
newPath.set(i, variable.value());
break;
}
return withPath(newPath);
}
public DynamicURL withValue(PathVar variable) {
Null.check(variable).ifAny("Variable cannot be null");
if (!hasVariables())
throw new IllegalArgumentException("No more variables left to pass values into");
if (!hasVariable(variable.name()))
throw new IllegalArgumentException("Cannot find variable in the URL: " + variable.name());
List<String> newPath = new ArrayList<>(path);
for (int i = 0; i < newPath.size(); i++)
if (newPath.get(i).equals(variable.name())) {
newPath.set(i, variable.value());
break;
}
return withPath(newPath);
}
public DynamicURL withValue(String name, Object value) {
return withValue(PathVar.of(name, value));
}
public QueryParamStep GET() {
return withGET();
}
public QueryParamStep GET(String... path) {
return withGET(path);
}
public QueryParamStep GET(List<String> path) {
return withGET(path);
}
public BodyTypeStep POST() {
return withPOST();
}
public BodyTypeStep POST(String... path) {
return withPOST(path);
}
public BodyTypeStep POST(List<String> path) {
return withPOST(path);
}
public BodyTypeStep PUT() {
return withPUT();
}
public BodyTypeStep PUT(String... path) {
return withPUT(path);
}
public BodyTypeStep PUT(List<String> path) {
return withPUT(path);
}
public BodyTypeStep DELETE() {
return withDELETE();
}
public BodyTypeStep DELETE(String... path) {
return withDELETE(path);
}
public BodyTypeStep DELETE(List<String> path) {
return withDELETE(path);
}
public HttpRequest sending(HttpMethod httpMethod) {
Null.check(httpMethod).ifAny("HTTP method cannot be null");
if (hasVariables())
throw new IllegalStateException("Cannot send while URL still has variables: " + pathVariables);
return new HttpRequest(httpMethod, getUrl());
}
public HttpRequest sending(HttpMethod httpMethod, String... path) {
return appendPath(path).sending(httpMethod);
}
public HttpRequest sending(HttpMethod httpMethod, List<String> path) {
return appendPath(path).sending(httpMethod);
}
public HttpRequest withGET() {
return sending(GET);
}
public HttpRequest withGET(String... path) {
return sending(GET, path);
}
public HttpRequest withGET(List<String> path) {
return sending(GET, path);
}
public HttpRequest withPOST() {
return sending(POST);
}
public HttpRequest withPOST(String... path) {
return sending(POST, path);
}
public HttpRequest withPOST(List<String> path) {
return sending(POST, path);
}
public HttpRequest withPUT() {
return sending(PUT);
}
public HttpRequest withPUT(String... path) {
return sending(PUT, path);
}
public HttpRequest withPUT(List<String> path) {
return sending(PUT, path);
}
public HttpRequest withDELETE() {
return sending(DELETE);
}
public HttpRequest withDELETE(String... path) {
return sending(DELETE, path);
}
public HttpRequest withDELETE(List<String> path) {
return sending(DELETE, path);
}
public StaticURL toStatic() {
if (hasVariables())
throw new IllegalStateException("Cannot convert to static while URL still has variables: " + pathVariables);
return StaticURL.of(this);
}
/**
* <pre>
* Custom step builder pattern enabling method
*
* By implementing CustomDynamicStepBuilder (or extending AbstractDynamicStepBuilder), you can create a custom
* builder which allows to fluently construct a custom DynamicUrl, HttpRequest (or any of its steps) or even
* get an HttpResponse
*
* The builder should implement FirstStep (which should be an interface) if you are going to use AbstractDynamicStepBuilder
* </pre>
*/
public <FirstStep> FirstStep custom(CustomDynamicStepBuilder<FirstStep> customDynamicStepBuilder) {
return customDynamicStepBuilder.setup(this);
}
// CONSTRUCTORS
/**
* @return step builder for an DynamicURL; has two steps, one for protocol and one for IP, the rest are handled
* directly by DynamicURL
*/
public static ProtocolStep builder() {
return new Builder();
}
/**
* Shorthand for builder().protocol(protocol).IP(ip)
*/
public static DynamicURL of(Protocol protocol, String ip) {
return builder().protocol(protocol).IP(ip);
}
/**
* Shorthand for builder().HTTP().IP(ip)
*/
public static DynamicURL ofHTTP(String ip) {
return builder().HTTP().IP(ip);
}
/**
* Shorthand for builder().HTTPS().IP(ip)
*/
public static DynamicURL ofHTTPS(String ip) {
return builder().HTTPS().IP(ip);
}
/**
* @return DynamicURL version of given StaticURL; uses the underlying url String, which is parsed using of(String)
* @throws NullPointerException if staticURL is null
*/
public static DynamicURL of(StaticURL staticURL) {
Null.check(staticURL).ifAny("StaticURL cannot be null");
return of(staticURL.getUrl());
}
public static DynamicURL of(String url) {
Null.check(url).ifAny("URL cannot be null");
int index = url.indexOf('?');
if (index >= 0)
url = url.substring(0, index);
index = url.indexOf('
if (index >= 0)
url = url.substring(0, index);
if (url.startsWith("http"))
url = url.substring(4);
else
throw new IllegalArgumentException("Invalid URL format; only http and https protocols supported");
Protocol protocol;
if (url.startsWith(":
protocol = Protocol.http;
url = url.substring(3);
} else
if (url.startsWith("s:
protocol = Protocol.https;
url = url.substring(4);
} else
throw new IllegalArgumentException("Invalid URL format; only http and https protocols supported");
index = url.indexOf('/');
if (index < 0)
return of(protocol, url);
String ip = url.substring(0, index);
String path = url.substring(index + 1);
DynamicURL dynamicURL = of(protocol, ip);
return path.isEmpty() ? dynamicURL : dynamicURL.withPath(path);
}
private DynamicURL(Protocol protocol, String ip, Integer port, List<String> path) {
this.protocol = protocol;
this.ip = ip;
this.port = port;
this.path = path;
List<String> pathVariables = path.stream()
.filter(DynamicURL::isVariable)
.peek(DynamicURL::failOnEmptyVariable)
.collect(toList());
this.pathVariables = new HashSet<>(pathVariables);
if (this.pathVariables.size() != pathVariables.size())
throw new IllegalArgumentException("URL cannot have multiple variables with the same name!");
}
// PRIVATE
private final Protocol protocol;
private final String ip;
private final Integer port;
private final List<String> path;
private final Set<String> pathVariables;
/**
* Convenience method for !hasVariable(String) in Predicate lambdas
*/
private boolean notHasVariable(String name) {
return !hasVariable(name);
}
private static final int MIN_PORT = 1;
private static final int MAX_PORT = 65535;
private static final DynamicURL DEFAULT_HTTP_DYNAMIC_URL = new DynamicURL(Protocol.http, "localhost", null, Collections.emptyList());
private static final DynamicURL DEFAULT_HTTPS_DYNAMIC_URL = new DynamicURL(Protocol.https, "localhost", null, Collections.emptyList());
private static IllegalArgumentException invalidIPMessage() {
return new IllegalArgumentException("IP address cannot be blank");
}
/**
* Shorthand for parsedPath(Arrays.asList(path))
*/
private static List<String> parsedPath(String... path) {
return parsedPath(Arrays.asList(path));
}
/**
* Takes every path String, validates it, splits it on '/', concatenates all the resulting lists
*/
private static List<String> parsedPath(List<String> path) {
return path.stream().flatMap(DynamicURL::parsedPathPart).collect(toList());
}
private static Stream<String> parsedPathPart(String pathPart) {
if (pathPart.contains("
throw new IllegalArgumentException("Paths cannot contain '
if (pathPart.startsWith("/"))
pathPart = pathPart.substring(1);
if (pathPart.endsWith("/"))
pathPart = pathPart.substring(0, pathPart.length() - 1);
if (pathPart.isEmpty())
throw new IllegalArgumentException("Empty path parts not allowed");
return Stream.of(pathPart.split("/"))
.peek(DynamicURL::confirmAssertion);
}
/**
* @throws AssertionError if given path part is empty, which should be avoided when constructing DynamicURL
*/
private static void confirmAssertion(String pathPart) {
if (pathPart.isEmpty())
throw new AssertionError("Since there are no '//', no split strings can be empty");
}
private static void failOnEmptyVariable(String variable) {
if (variable.equals(":"))
throw new IllegalArgumentException("Variable must have a name and cannot be empty");
}
// OBJECT OVERRIDES
@Override
public String toString() {
return getUrl();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DynamicURL)) return false;
DynamicURL that = (DynamicURL) o;
return Objects.equals(protocol, that.protocol) &&
Objects.equals(ip, that.ip) &&
Objects.equals(port, that.port) &&
Objects.equals(path, that.path);
}
@Override
public int hashCode() {
return Objects.hash(protocol, ip, port, path);
}
// BUILDER
/**
* First step builder step, defines the protocol
*/
public interface ProtocolStep {
/**
* Sets the protocol of the DynamicURL being built
* @throws NullPointerException if protocol is null
*/
IPStep protocol(Protocol protocol);
/**
* Sets the protocol of the DynamicURL being built to HTTP
*/
IPStep HTTP();
/**
* Sets the protocol of the DynamicURL being built to HTTPS
*/
IPStep HTTPS();
}
/**
* Second step builder step, defines the IP address
*/
public interface IPStep {
DynamicURL IP(String ip);
}
private static final class Builder implements ProtocolStep, IPStep {
@Override
public IPStep protocol(Protocol protocol) {
Null.check(protocol).ifAny("Protocol cannot be null");
if (protocol == Protocol.http)
return HTTP();
if (protocol == Protocol.https)
return HTTPS();
throw new AssertionError("There are only two protocols supported");
}
@Override
public IPStep HTTP() {
this.dynamicURL = DEFAULT_HTTP_DYNAMIC_URL;
return this;
}
@Override
public IPStep HTTPS() {
this.dynamicURL = DEFAULT_HTTPS_DYNAMIC_URL;
return this;
}
@Override
public DynamicURL IP(String ip) {
return dynamicURL.withIP(ip);
}
// PRIVATE
private DynamicURL dynamicURL;
}
} |
package io.quarkus.container.image.buildpack.deployment;
import static io.quarkus.container.util.PathsUtil.findMainSourcesRoot;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import org.jboss.logging.Logger;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.PushResponseItem;
import dev.snowdrop.buildpack.Buildpack;
import dev.snowdrop.buildpack.BuildpackBuilder;
import io.quarkus.container.image.deployment.ContainerImageConfig;
import io.quarkus.container.image.deployment.util.NativeBinaryUtil;
import io.quarkus.container.spi.AvailableContainerImageExtensionBuildItem;
import io.quarkus.container.spi.ContainerImageBuildRequestBuildItem;
import io.quarkus.container.spi.ContainerImageBuilderBuildItem;
import io.quarkus.container.spi.ContainerImageInfoBuildItem;
import io.quarkus.container.spi.ContainerImageLabelBuildItem;
import io.quarkus.container.spi.ContainerImagePushRequestBuildItem;
import io.quarkus.deployment.IsNormalNotRemoteDev;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.MainClassBuildItem;
import io.quarkus.deployment.pkg.PackageConfig;
import io.quarkus.deployment.pkg.builditem.AppCDSResultBuildItem;
import io.quarkus.deployment.pkg.builditem.ArtifactResultBuildItem;
import io.quarkus.deployment.pkg.builditem.CurateOutcomeBuildItem;
import io.quarkus.deployment.pkg.builditem.JarBuildItem;
import io.quarkus.deployment.pkg.builditem.NativeImageBuildItem;
import io.quarkus.deployment.pkg.builditem.OutputTargetBuildItem;
import io.quarkus.deployment.pkg.steps.NativeBuild;
public class BuildpackProcessor {
private static final Logger log = Logger.getLogger(BuildpackProcessor.class);
public static final String BUILDPACK = "buildpack";
private enum ProjectDirs {
TARGET,
SOURCE,
ROOT
};
@BuildStep
public AvailableContainerImageExtensionBuildItem availability() {
return new AvailableContainerImageExtensionBuildItem(BUILDPACK);
}
@BuildStep(onlyIf = { IsNormalNotRemoteDev.class, BuildpackBuild.class }, onlyIfNot = NativeBuild.class)
public void buildFromJar(ContainerImageConfig containerImageConfig, BuildpackConfig buildpackConfig,
PackageConfig packageConfig,
ContainerImageInfoBuildItem containerImage,
JarBuildItem sourceJar,
MainClassBuildItem mainClass,
OutputTargetBuildItem outputTarget,
CurateOutcomeBuildItem curateOutcome,
Optional<ContainerImageBuildRequestBuildItem> buildRequest,
Optional<ContainerImagePushRequestBuildItem> pushRequest,
List<ContainerImageLabelBuildItem> containerImageLabels,
Optional<AppCDSResultBuildItem> appCDSResult,
BuildProducer<ArtifactResultBuildItem> artifactResultProducer,
BuildProducer<ContainerImageBuilderBuildItem> containerImageBuilder) {
if (containerImageConfig.isBuildExplicitlyDisabled()) {
return;
}
if (!containerImageConfig.isBuildExplicitlyEnabled() && !containerImageConfig.isPushExplicitlyEnabled()
&& !buildRequest.isPresent() && !pushRequest.isPresent()) {
return;
}
log.info("Starting (local) container image build for jar using builpack.");
String targetImageName = runBuildpackBuild(buildpackConfig, containerImage, containerImageConfig, pushRequest,
outputTarget, false /* isNative */);
artifactResultProducer.produce(new ArtifactResultBuildItem(null, "jar-container",
Collections.singletonMap("container-image", targetImageName)));
containerImageBuilder.produce(new ContainerImageBuilderBuildItem(BUILDPACK));
}
@BuildStep(onlyIf = { IsNormalNotRemoteDev.class, BuildpackBuild.class, NativeBuild.class })
public void buildFromNative(ContainerImageConfig containerImageConfig, BuildpackConfig buildpackConfig,
ContainerImageInfoBuildItem containerImage,
NativeImageBuildItem nativeImage,
OutputTargetBuildItem outputTarget,
Optional<ContainerImageBuildRequestBuildItem> buildRequest,
Optional<ContainerImagePushRequestBuildItem> pushRequest,
List<ContainerImageLabelBuildItem> containerImageLabels,
BuildProducer<ArtifactResultBuildItem> artifactResultProducer,
BuildProducer<ContainerImageBuilderBuildItem> containerImageBuilder) {
if (containerImageConfig.isBuildExplicitlyDisabled()) {
return;
}
if (!containerImageConfig.isBuildExplicitlyEnabled() && !containerImageConfig.isPushExplicitlyEnabled()
&& !buildRequest.isPresent() && !pushRequest.isPresent()) {
return;
}
if (!NativeBinaryUtil.nativeIsLinuxBinary(nativeImage)) {
throw new RuntimeException(
"The native binary produced by the build is not a Linux binary and therefore cannot be used in a Linux container image. Consider adding \"quarkus.native.container-build=true\" to your configuration");
}
log.info("Starting (local) container image build for native binary using buildpack.");
String targetImageName = runBuildpackBuild(buildpackConfig, containerImage, containerImageConfig, pushRequest,
outputTarget, true /* isNative */);
artifactResultProducer.produce(new ArtifactResultBuildItem(null, "native-container",
Collections.singletonMap("container-image", targetImageName)));
containerImageBuilder.produce(new ContainerImageBuilderBuildItem(BUILDPACK));
}
private Map<ProjectDirs, Path> getPaths(OutputTargetBuildItem outputTarget) {
Path targetDirectory = outputTarget.getOutputDirectory();
Map.Entry<Path, Path> mainSourcesRoot = findMainSourcesRoot(targetDirectory);
if (mainSourcesRoot == null) {
throw new RuntimeException("Buildpack build unable to determine project dir");
}
Path sourceRoot = mainSourcesRoot.getKey();
Path projectRoot = mainSourcesRoot.getValue();
if (!projectRoot.toFile().exists() || !sourceRoot.toFile().exists()) {
throw new RuntimeException("Buildpack build unable to verify project dir");
}
Map<ProjectDirs, Path> result = new HashMap<>();
result.put(ProjectDirs.ROOT, projectRoot);
result.put(ProjectDirs.SOURCE, sourceRoot);
result.put(ProjectDirs.TARGET, targetDirectory);
return result;
}
private String runBuildpackBuild(BuildpackConfig buildpackConfig,
ContainerImageInfoBuildItem containerImage,
ContainerImageConfig containerImageConfig,
Optional<ContainerImagePushRequestBuildItem> pushRequest,
OutputTargetBuildItem outputTarget,
boolean isNativeBuild) {
Map<ProjectDirs, Path> dirs = getPaths(outputTarget);
log.debug("Using target dir of " + dirs.get(ProjectDirs.TARGET));
log.debug("Using source root of " + dirs.get(ProjectDirs.SOURCE));
log.debug("Using project root of " + dirs.get(ProjectDirs.ROOT));
String targetImageName = containerImage.getImage().toString();
log.debug("Using Destination image of " + targetImageName);
Map<String, String> envMap = buildpackConfig.builderEnv;
if (!envMap.isEmpty()) {
log.info("Using builder environment of " + envMap);
}
log.info("Initiating Buildpack build");
Buildpack buildpack = Buildpack.builder()
.addNewFileContent(dirs.get(ProjectDirs.ROOT).toFile())
.withFinalImage(targetImageName)
.withEnvironment(envMap)
.withLogLevel(buildpackConfig.logLevel)
.withPullTimeoutSeconds(buildpackConfig.pullTimeoutSeconds)
.withLogger(new BuildpackLogger())
.accept(BuildpackBuilder.class, b -> {
if (isNativeBuild) {
buildpackConfig.nativeBuilderImage.ifPresent(i -> b.withBuilderImage(i));
} else {
buildpackConfig.jvmBuilderImage.ifPresent(i -> b.withBuilderImage(i));
}
if (buildpackConfig.runImage.isPresent()) {
log.info("Using Run image of " + buildpackConfig.runImage.get());
b.withRunImage(buildpackConfig.runImage.get());
}
if (buildpackConfig.dockerHost.isPresent()) {
log.info("Using DockerHost of " + buildpackConfig.dockerHost.get());
b.withDockerHost(buildpackConfig.dockerHost.get());
}
}).build();
if (buildpack.getExitCode() != 0) {
throw new IllegalStateException("Buildpack build failed");
}
log.info("Buildpack build complete");
if (containerImageConfig.isPushExplicitlyEnabled() || pushRequest.isPresent()) {
if (!containerImageConfig.registry.isPresent()) {
log.info("No container image registry was set, so 'docker.io' will be used");
}
AuthConfig authConfig = new AuthConfig();
authConfig.withRegistryAddress(containerImageConfig.registry.orElse("docker.io"));
containerImageConfig.username.ifPresent(u -> authConfig.withUsername(u));
containerImageConfig.password.ifPresent(p -> authConfig.withPassword(p));
log.info("Pushing image to " + authConfig.getRegistryAddress());
Stream.concat(Stream.of(containerImage.getImage()), containerImage.getAdditionalImageTags().stream()).forEach(i -> {
ResultCallback.Adapter<PushResponseItem> callback = buildpack.getDockerClient().pushImageCmd(i).start();
try {
callback.awaitCompletion();
log.info("Push complete");
} catch (Exception e) {
throw new IllegalStateException(e);
}
});
}
return targetImageName;
}
} |
package eu.lp0.cursus.db.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import eu.lp0.cursus.util.Constants;
@Entity(name = "race_no")
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "series_id", "organisation", "number" }) })
public class RaceNumber extends AbstractEntity implements Comparable<RaceNumber> {
private String organisation;
private Integer number;
RaceNumber() {
}
public RaceNumber(Pilot pilot, String organisation, int number) {
setSeries(pilot.getSeries());
setPilot(pilot);
setOrganisation(organisation);
setNumber(number);
}
private Series series;
@ManyToOne(optional = false)
@JoinColumn(name = "series_id", nullable = false)
public Series getSeries() {
return series;
}
public void setSeries(Series series) {
this.series = series;
}
@Column(nullable = false, length = Constants.MAX_STRING_LEN)
public String getOrganisation() {
return organisation;
}
public void setOrganisation(String organisation) {
this.organisation = organisation;
}
@Column(nullable = false)
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
private Pilot pilot;
@ManyToOne(optional = false)
@JoinColumn(nullable = false)
public Pilot getPilot() {
return pilot;
}
public void setPilot(Pilot pilot) {
this.pilot = pilot;
}
@Override
public int compareTo(RaceNumber o) {
int ret = getOrganisation().compareTo(o.getOrganisation());
if (ret != 0) {
return ret;
}
return ((Integer)getNumber()).compareTo(o.getNumber());
}
@Override
public String toString() {
return String.format("%s%02d", getOrganisation(), getNumber()); //$NON-NLS-1$
}
} |
package fr.openwide.core.jpa.config.spring.provider;
import java.util.List;
import javax.persistence.spi.PersistenceProvider;
import javax.sql.DataSource;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.dialect.Dialect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
public class DefaultJpaConfigurationProvider implements IJpaConfigurationProvider {
@Autowired
private List<JpaPackageScanProvider> jpaPackageScanProviders;
@Value("${${db.type}.db.dialect}")
private Class<Dialect> dialect;
@Value("${hibernate.hbm2ddl.auto}")
private String hbm2Ddl;
@Value("${hibernate.hbm2ddl.import_files}")
private String hbm2DdlImportFiles;
@Value("${hibernate.defaultBatchSize}")
private Integer defaultBatchSize;
@Value("${lucene.index.path}")
private String hibernateSearchIndexBase;
@Value("${hibernate.search.indexing_strategy:}") // Defaults to an empty string
private String hibernateSearchIndexingStrategy;
@Value("#{dataSource}")
private DataSource dataSource;
@Value("${hibernate.ehCache.configurationLocation}")
private String ehCacheConfiguration;
@Value("${hibernate.ehCache.singleton}")
private boolean ehCacheSingleton;
@Value("${hibernate.queryCache.enabled}")
private boolean queryCacheEnabled;
@Autowired(required=false)
private PersistenceProvider persistenceProvider;
@Value("${javax.persistence.validation.mode}")
private String validationMode;
@Value("${hibernate.ejb.naming_strategy}")
private Class<NamingStrategy> namingStrategy;
@Value("${hibernate.create_empty_composites.enabled}")
private boolean createEmptyCompositesEnabled;
@Override
public List<JpaPackageScanProvider> getJpaPackageScanProviders() {
return jpaPackageScanProviders;
}
@Override
public Class<Dialect> getDialect() {
return dialect;
}
@Override
public String getHbm2Ddl() {
return hbm2Ddl;
}
@Override
public String getHbm2DdlImportFiles() {
return hbm2DdlImportFiles;
}
@Override
public Integer getDefaultBatchSize() {
return defaultBatchSize;
}
@Override
public String getHibernateSearchIndexBase() {
return hibernateSearchIndexBase;
}
@Override
public String getHibernateSearchIndexingStrategy() {
return hibernateSearchIndexingStrategy;
}
@Override
public DataSource getDataSource() {
return dataSource;
}
@Override
public String getEhCacheConfiguration() {
return ehCacheConfiguration;
}
@Override
public boolean isEhCacheSingleton() {
return ehCacheSingleton;
}
@Override
public boolean isQueryCacheEnabled() {
return queryCacheEnabled;
}
@Override
public PersistenceProvider getPersistenceProvider() {
return persistenceProvider;
}
@Override
public String getValidationMode() {
return validationMode;
}
@Override
public Class<NamingStrategy> getNamingStrategy() {
return namingStrategy;
}
@Override
public boolean isCreateEmptyCompositesEnabled() {
return createEmptyCompositesEnabled;
}
} |
package fi.eis.libraries.di;
import java.io.PrintStream;
import java.util.Date;
public class SimpleLogger {
private volatile boolean debugFlag = false;
private final String className;
private transient PrintStream printStream = System.out;
public SimpleLogger(Class<?> targetClass) {
this.className = targetClass.getName();
}
public void setDebug(boolean value) {
this.debugFlag = value;
}
public void debugPrint(String message) {
if (this.debugFlag) {
printStream.printf("%s DEBUG %s: %s%n",
new Date(), className, message);
}
}
public void debugPrint(String message, Object... parameters) {
if (this.debugFlag) {
debugPrint(String.format(message, parameters));
}
}
public void setPrintOut(PrintStream stream) {
this.printStream = stream;
}
} |
package org.csstudio.opibuilder.converter.writer;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.csstudio.opibuilder.converter.StringSplitter;
import org.csstudio.opibuilder.converter.model.EdmString;
import org.csstudio.opibuilder.converter.model.Edm_activePipClass;
/**
* XML conversion class for Edm_activePipClass
* @author Lei Hu, Xihui Chen
*/
public class Opi_activePipClass extends OpiWidget {
private static Logger log = Logger.getLogger("org.csstudio.opibuilder.converter.writer.Opi_activePipClass");
private static final String typeId = "linkingContainer";
private static final String name = "EDM linkingContainer";
private static final String version = "1.0";
/**
* Converts the Edm_activeRectangleClass to OPI Rectangle widget XML.
*/
public Opi_activePipClass(Context con, Edm_activePipClass r) {
super(con, r);
setTypeId(typeId);
setVersion(version);
setName(name);
if(r.getDisplaySource()!=null)
{
if(r.getDisplaySource().equals("menu") && r.getDisplayFileName()!=null && r.getFilePv()!=null){
Map<String, EdmString> displayFileMap = r.getDisplayFileName().getEdmAttributesMap();
if(displayFileMap.size()>0){
Map<String, EdmString> symbolsMap=null;
if(r.getSymbols()!=null)
symbolsMap = r.getSymbols().getEdmAttributesMap();
StringBuilder sb = new StringBuilder("importPackage(Packages.org.csstudio.opibuilder.scriptUtil);\n");
sb.append("var pv0 = PVUtil.getLong(pvs[0]);\n");
boolean f= false;
for(String key : displayFileMap.keySet()){
if(f)
sb.append("else ");
f=true;
sb.append("if(pv0=="+key+"){\n");
boolean append = true;
if(r.getReplaceSymbols()!=null&&r.getReplaceSymbols().getEdmAttributesMap().containsKey(key)){
append = !r.getReplaceSymbols().getEdmAttributesMap().get(key).is();
}
sb.append("var macroInput = DataUtil.createMacrosInput("+append+");\n");
if(symbolsMap != null && symbolsMap.containsKey(key)){
try {
EdmString symbols = symbolsMap.get(key);
if (symbols != null) {
for (String s : StringSplitter.splitIgnoreInQuotes(symbols.get(), ',', true)) {
String[] rs = StringSplitter.splitIgnoreInQuotes(s, '=', true);
if (rs.length == 2) {
// EDM treats '' as an empty string.
rs[1] = rs[1].equals("''") ? "" : rs[1];
try {
sb.append("macroInput.put(\"" + rs[0] + "\", \"" + rs[1]+"\");\n");
} catch (Exception e) {
log.log(Level.WARNING, "Parse Macros Error on: " + s, e);
}
}
}
}
} catch (Exception e) {
log.log(Level.WARNING, "Parse Macros Error ", e);
}
}
sb.append("widget.setPropertyValue(\"macros\", macroInput);\n");
sb.append("widget.setPropertyValue(\"opi_file\",\""+
convertFileExtention(displayFileMap.get(key).get()) +"\");\n");
sb.append("}\n");
}
LinkedHashMap<String, Boolean> pvNames = new LinkedHashMap<String, Boolean>();
pvNames.put(convertPVName(r.getFilePv()), true);
new OpiScript(widgetContext, "OPIFileScript", pvNames , sb.toString());
}
}else if (r.getFile() != null) {
String originPath = r.getFile();
originPath = convertFileExtention(originPath);
new OpiString(widgetContext, "opi_file", originPath);
}
}
if(r.getDisplaySource()==null && r.getFilePv()!=null){
createPVOutputRule(r, convertPVName(r.getFilePv()), "opi_file", "pvStr0", "OPIFileFromPVRule");
}
new OpiString(widgetContext, "resize_behaviour", "2");
// No border in EDM embedded window.
new OpiInt(widgetContext, "border_style", 0);
log.config("Edm_activePipClass written.");
}
} |
package gov.nasa.jpl.mbee;
import gov.nasa.jpl.mbee.actions.systemsreasoner.AspectAction;
import gov.nasa.jpl.mbee.actions.systemsreasoner.CreateInstanceMenuAction;
import gov.nasa.jpl.mbee.actions.systemsreasoner.CreateOntoBehaviorBlocks;
import gov.nasa.jpl.mbee.actions.systemsreasoner.CreateSpecificAction;
import gov.nasa.jpl.mbee.actions.systemsreasoner.DespecifyAction;
import gov.nasa.jpl.mbee.actions.systemsreasoner.Instance2BSTAction;
import gov.nasa.jpl.mbee.actions.systemsreasoner.SRAction;
import gov.nasa.jpl.mbee.actions.systemsreasoner.ValidateAction;
import java.util.ArrayList;
import java.util.List;
import com.nomagic.actions.ActionsCategory;
import com.nomagic.actions.ActionsManager;
import com.nomagic.actions.NMAction;
import com.nomagic.magicdraw.actions.ActionsGroups;
import com.nomagic.magicdraw.actions.BrowserContextAMConfigurator;
import com.nomagic.magicdraw.actions.DiagramContextAMConfigurator;
import com.nomagic.magicdraw.actions.MDAction;
import com.nomagic.magicdraw.actions.MDActionsCategory;
import com.nomagic.magicdraw.ui.browser.Node;
import com.nomagic.magicdraw.ui.browser.Tree;
import com.nomagic.magicdraw.uml.symbols.DiagramPresentationElement;
import com.nomagic.magicdraw.uml.symbols.PresentationElement;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Classifier;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceSpecification;
import com.nomagic.uml2.ext.magicdraw.commonbehaviors.mdbasicbehaviors.Behavior;
public class SRConfigurator implements BrowserContextAMConfigurator, DiagramContextAMConfigurator {
public static final String NAME = "Systems Reasoner";
private SRAction validateAction = null, specAction = null, despecAction = null, createSpecificAction = null, ontoBehaviorAction = null, instance2BSTAction = null,
createInstanceMenuAction = null, aspectAction;
private AspectAction mySecondAction;
@Override
public int getPriority() {
return 0; // medium
}
@Override
public void configure(ActionsManager manager, Tree tree) {
final List<Element> elements = new ArrayList<Element>();
for (final Node n : tree.getSelectedNodes()) {
if (n.getUserObject() instanceof Element) {
elements.add((Element) n.getUserObject());
}
}
configure(manager, elements);
}
@Override
public void configure(ActionsManager manager, DiagramPresentationElement diagram, PresentationElement[] selected, PresentationElement requestor) {
final List<Element> elements = new ArrayList<Element>();
for (final PresentationElement pe : selected) {
if (pe.getElement() != null) {
elements.add(pe.getElement());
}
}
configure(manager, elements);
}
protected void configure(ActionsManager manager, List<Element> elements) {
// refresh the actions for every new click (or selection)
validateAction = null;
specAction = null;
despecAction = null;
// copyAction = null;
ontoBehaviorAction = null;
createSpecificAction = null;
createInstanceMenuAction = null;
instance2BSTAction = null;
aspectAction = null;
ActionsCategory category = (ActionsCategory) manager.getActionFor("SRMain");
if (category == null) {
category = new MDActionsCategory("SRMain", "Systems Reasoner", null, ActionsGroups.APPLICATION_RELATED);
category.setNested(true);
// manager.addCategory(0, category);
}
manager.removeCategory(category);
if (elements.size() > 1) {
category = handleMultipleNodes(category, manager, elements);
} else if (elements.size() == 1) {
category = handleSingleNode(category, manager, elements.get(0));
} else {
return;
}
if (category == null) {
return;
}
manager.addCategory(0, category);
category.addAction(validateAction);
// category.addAction(specAction); Taking this one out because all it does is create an inheritance relation ship. This can be done easily through existing means.
if (elements.size() < 2) {
if (elements.get(0) instanceof Behavior) {
category.addAction(ontoBehaviorAction);
}
}
category.addAction(despecAction);
// category.addAction(copyAction);
category.addAction(createSpecificAction);
category.addAction(createInstanceMenuAction);
category.addAction(instance2BSTAction);
category.addAction(aspectAction);
category.addAction(mySecondAction);
// System.out.println("Instance2BST: " + instance2BSTAction.getClass().getCanonicalName());
// Clear out the category of unused actions
// final List<NMAction> clonedActions = Lists.newArrayList(category.getActions());
category.getActions().clear();
category.setUseActionForDisable(true);
if (category.isEmpty()) {
final MDAction mda = new MDAction(null, null, null, "null");
mda.updateState();
mda.setEnabled(false);
category.addAction(mda);
}
}
public ActionsCategory handleMultipleNodes(ActionsCategory category, ActionsManager manager, List<Element> elements) {
// final List<Element> validatableElements = new ArrayList<Element>();
// boolean hasClassifier = false, hasInstance = false;
final List<Classifier> classifiers = new ArrayList<Classifier>();
final List<InstanceSpecification> instances = new ArrayList<InstanceSpecification>();
final List<Element> validatableElements = new ArrayList<Element>();
boolean hasUneditable = false;
for (Element element : elements) {
if (element != null) {
if (element instanceof Classifier) {
classifiers.add((Classifier) element);
validatableElements.add(element);
} else if (element instanceof InstanceSpecification) {
instances.add((InstanceSpecification) element);
validatableElements.add(element);
}
if (!hasUneditable && !element.isEditable()) {
hasUneditable = true;
}
}
}
// if nothing in classes, disable category and return it
if (validatableElements.isEmpty()) {
// category = disableCategory(category);
return null;
}
// otherwise, add the classes to the ValidateAction action
validateAction = new ValidateAction(validatableElements);
// add the action to the actions category
category.addAction(validateAction);
if (!classifiers.isEmpty()) {
despecAction = new DespecifyAction(classifiers);
if (hasUneditable) {
despecAction.disable("Not Editable");
}
boolean hasGeneralization = false;
for (final Classifier classifier : classifiers) {
if (!classifier.getGeneralization().isEmpty()) {
hasGeneralization = true;
break;
}
}
if (!hasGeneralization) {
despecAction.disable("No Generalizations");
}
aspectAction = new AspectAction(classifiers);
}
if (!instances.isEmpty()) {
instance2BSTAction = new Instance2BSTAction(instances);
}
return category;
}
public ActionsCategory handleSingleNode(ActionsCategory category, ActionsManager manager, Element element) {
if (element == null)
return null;
// copyAction = new CopyAction(target);
// check target instanceof
/*
* if (target instanceof Activity) { Activity active = (Activity) target; copyAction = new CopyAction(active); }
*/
if (element instanceof Classifier) {
final Classifier classifier = (Classifier) element;
validateAction = new ValidateAction(classifier);
// specAction = new SpecifyAction(classifier);
despecAction = new DespecifyAction(classifier);
if (!element.isEditable()) {
//specAction.disable("Locked");
despecAction.disable("Locked");
}
// copyAction = new CopyAction(clazz);
ontoBehaviorAction = new CreateOntoBehaviorBlocks(classifier, false);
createSpecificAction = new CreateSpecificAction(classifier, false);
createInstanceMenuAction = new CreateInstanceMenuAction(classifier);
aspectAction = new AspectAction(classifier);
if (despecAction != null && classifier.getGeneralization().isEmpty()) {
despecAction.disable("No Generalizations");
}
if (classifier instanceof Behavior) {
}
} else if (element instanceof InstanceSpecification) {
final InstanceSpecification instance = (InstanceSpecification) element;
validateAction = new ValidateAction(instance);
ArrayList<InstanceSpecification> insts = new ArrayList();
insts.add(instance);
instance2BSTAction = new Instance2BSTAction(insts);
} else {
return null;
}
/*
* if (target instanceof Classifier) { Classifier clazzifier = (Classifier) target; copyAction = new CopyAction(clazzifier); }
*/
return category;
}
public static ActionsCategory disableCategory(ActionsCategory category) {
// once all the categories are disabled, the action category will be disabled
// this is defined in the configure method: category.setNested(true);
for (NMAction s : category.getActions()) {
if (s instanceof SRAction) {
SRAction sra = (SRAction) s;
sra.disable("Not Editable");
}
}
return category;
}
} |
package com.evolveum.midpoint.eclipse.ui.components.browser;
import java.util.List;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;
import com.evolveum.midpoint.eclipse.runtime.api.Constants;
import com.evolveum.midpoint.eclipse.runtime.api.ObjectTypes;
import com.evolveum.midpoint.eclipse.runtime.api.resp.ServerObject;
import com.evolveum.midpoint.eclipse.ui.handlers.sources.SourceObject;
import com.evolveum.midpoint.eclipse.ui.util.Console;
import com.evolveum.midpoint.util.DOMUtil;
public class BulkActionGenerator extends Generator {
public enum Action {
RECOMPUTE("recompute", "recompute", ObjectTypes.FOCUS, false, true, false),
ENABLE("enable", "enable", ObjectTypes.FOCUS, false, true, false),
DISABLE("disable", "disable", ObjectTypes.FOCUS, false, true, false),
DELETE("delete", "delete", ObjectTypes.OBJECT, true, true, true),
MODIFY("modify", "modify", ObjectTypes.OBJECT, true, true, false),
LOG("log", "log", ObjectTypes.OBJECT, false, false, false),
TEST_RESOURCE("test resource", "test-resource", ObjectTypes.RESOURCE, false, false, false),
EXECUTE_SCRIPT("execute script", "execute-script", ObjectTypes.OBJECT, false, false, false);
private final String displayName, actionName;
private final ObjectTypes applicableTo;
private final boolean supportsRaw, supportsDryRun, requiresConfirmation;
private Action(String displayName, String actionName, ObjectTypes applicableTo, boolean supportsRaw, boolean supportsDryRun, boolean requiresConfirmation) {
this.displayName = displayName;
this.actionName = actionName;
this.applicableTo = applicableTo;
this.supportsRaw = supportsRaw;
this.supportsDryRun = supportsDryRun;
this.requiresConfirmation = requiresConfirmation;
}
}
private Action action;
public BulkActionGenerator(Action action) {
this.action = action;
}
@Override
public String getLabel() {
return "Bulk action: " + action.displayName;
}
@Override
public String generate(List<ServerObject> objects, GeneratorOptions options) {
if (objects.isEmpty()) {
return null;
}
Element top = null;
List<Batch> batches = createBatches(objects, options, action.applicableTo);
Element root;
if (batches.size() > 1) {
top = root = DOMUtil.getDocument(new QName(Constants.COMMON_NS, options.isWrapActions() ? "objects" : "actions", "c")).getDocumentElement();
} else {
root = null;
}
for (Batch batch : batches) {
Element batchRoot;
Element task = null;
if (options.isWrapActions()) {
if (root == null) {
task = DOMUtil.getDocument(new QName(Constants.COMMON_NS, "task", "c")).getDocumentElement();
top = task;
} else {
task = DOMUtil.createSubElement(root, new QName(Constants.COMMON_NS, "task", "c"));
}
DOMUtil.createSubElement(task, new QName(Constants.COMMON_NS, "name", "c")).setTextContent("Execute " + action.displayName + " on objects " + (batch.getFirst()+1) + " to " + (batch.getLast()+1));
Element extension = DOMUtil.createSubElement(task, new QName(Constants.COMMON_NS, "extension", "c"));
Element executeScript = DOMUtil.createSubElement(extension, new QName(Constants.SCEXT_NS, "executeScript", "scext"));
batchRoot = executeScript;
} else {
batchRoot = root;
}
Element pipe;
if (batchRoot == null) {
pipe = DOMUtil.getDocument(new QName(Constants.SCRIPT_NS, "pipeline", "s")).getDocumentElement();
top = pipe;
} else {
pipe = DOMUtil.createSubElement(batchRoot, new QName(Constants.SCRIPT_NS, "pipeline", "s"));
}
createOidsSearch(pipe, batch);
createAction(pipe, options);
if (task != null) {
DOMUtil.createSubElement(task, new QName(Constants.COMMON_NS, "taskIdentifier", "c")).setTextContent(generateTaskIdentifier());
DOMUtil.createSubElement(task, new QName(Constants.COMMON_NS, "ownerRef", "c")).setAttribute("oid", "00000000-0000-0000-0000-000000000002");
DOMUtil.createSubElement(task, new QName(Constants.COMMON_NS, "executionStatus", "c")).setTextContent(
options.isCreateSuspended() ? "suspended" : "runnable"
);
DOMUtil.createSubElement(task, new QName(Constants.COMMON_NS, "category", "c")).setTextContent("BulkActions");
DOMUtil.createSubElement(task, new QName(Constants.COMMON_NS, "handlerUri", "c")).setTextContent("http://midpoint.evolveum.com/xml/ns/public/model/scripting/handler-3");
DOMUtil.createSubElement(task, new QName(Constants.COMMON_NS, "recurrence", "c")).setTextContent("single");
}
}
return DOMUtil.serializeDOMToString(top);
}
public static String generateTaskIdentifier() {
return System.currentTimeMillis() + ":" + Math.round(Math.random() * 1000000000.0);
}
public void createOidsSearch(Element root, Batch batch) {
Element search = DOMUtil.createSubElement(root, new QName(Constants.SCRIPT_NS, "expression", "s"));
DOMUtil.setXsiType(search, new QName(Constants.SCRIPT_NS, "SearchExpressionType", "s"));
DOMUtil.createSubElement(search, new QName(Constants.SCRIPT_NS, "type", "s")).setTextContent(action.applicableTo.getTypeName());
Element filter = DOMUtil.createSubElement(search, new QName(Constants.SCRIPT_NS, "searchFilter", "s"));
Element inOid = DOMUtil.createSubElement(filter, Constants.Q_IN_OID_Q);
for (ServerObject o : batch.getObjects()) {
DOMUtil.createSubElement(inOid, Constants.Q_VALUE_Q).setTextContent(o.getOid());
DOMUtil.createComment(inOid, " " + o.getName() + " ");
}
}
public void createSingleSourceSearch(Element root, SourceObject object) {
Element search = DOMUtil.createSubElement(root, new QName(Constants.SCRIPT_NS, "expression", "s"));
DOMUtil.setXsiType(search, new QName(Constants.SCRIPT_NS, "SearchExpressionType", "s"));
DOMUtil.createSubElement(search, new QName(Constants.SCRIPT_NS, "type", "s")).setTextContent(object.getType().getTypeName());
Element filter = DOMUtil.createSubElement(search, new QName(Constants.SCRIPT_NS, "searchFilter", "s"));
if (object.getOid() != null) {
Element inOid = DOMUtil.createSubElement(filter, Constants.Q_IN_OID_Q);
DOMUtil.createSubElement(inOid, Constants.Q_VALUE_Q).setTextContent(object.getOid());
DOMUtil.createComment(inOid, " " + object.getName() + " ");
} else if (object.getName() != null) {
Element equal = DOMUtil.createSubElement(filter, Constants.Q_EQUAL_Q);
DOMUtil.createSubElement(equal, Constants.Q_PATH_Q).setTextContent("name");
DOMUtil.createSubElement(equal, Constants.Q_VALUE_Q).setTextContent(object.getName());
} else {
Console.logWarning("No OID nor name provided; action on this object cannot be executed.");
Element inOid = DOMUtil.createSubElement(filter, Constants.Q_IN_OID_Q);
DOMUtil.createSubElement(inOid, Constants.Q_VALUE_Q).setTextContent("no such object 919432948jkas");
}
}
public void createAction(Element root, GeneratorOptions options) {
Element actionE = DOMUtil.createSubElement(root, new QName(Constants.SCRIPT_NS, "expression", "s"));
DOMUtil.setXsiType(actionE, new QName(Constants.SCRIPT_NS, "ActionExpressionType", "s"));
DOMUtil.createSubElement(actionE, new QName(Constants.SCRIPT_NS, "type", "s")).setTextContent(action.actionName);
if (options.isRaw() && supportsRawOption()) {
Element rawParam = DOMUtil.createSubElement(actionE, new QName(Constants.SCRIPT_NS, "parameter", "s"));
DOMUtil.createSubElement(rawParam, new QName(Constants.SCRIPT_NS, "name", "s")).setTextContent("raw");
DOMUtil.createSubElement(rawParam, new QName(Constants.COMMON_NS, "value", "c")).setTextContent("true");
}
if (options.isDryRun() && supportsDryRunOption()) {
Element rawParam = DOMUtil.createSubElement(actionE, new QName(Constants.SCRIPT_NS, "parameter", "s"));
DOMUtil.createSubElement(rawParam, new QName(Constants.SCRIPT_NS, "name", "s")).setTextContent("dryRun");
DOMUtil.createSubElement(rawParam, new QName(Constants.COMMON_NS, "value", "c")).setTextContent("true");
}
if (action == Action.MODIFY) {
Element deltaParam = DOMUtil.createSubElement(actionE, new QName(Constants.SCRIPT_NS, "parameter", "s"));
DOMUtil.createSubElement(deltaParam, new QName(Constants.SCRIPT_NS, "name", "s")).setTextContent("delta");
Element objectDelta = DOMUtil.createSubElement(deltaParam, new QName(Constants.COMMON_NS, "value", "c"));
DOMUtil.setXsiType(objectDelta, new QName(Constants.TYPES_NS, "ObjectDeltaType", "t"));
Element itemDelta = DOMUtil.createSubElement(objectDelta, new QName(Constants.TYPES_NS, "itemDelta", "t"));
DOMUtil.createSubElement(itemDelta, new QName(Constants.TYPES_NS, "modificationType", "t")).setTextContent("add");
DOMUtil.createSubElement(itemDelta, new QName(Constants.TYPES_NS, "path", "t")).setTextContent("TODO (e.g. displayName)");
Element value = DOMUtil.createSubElement(itemDelta, new QName(Constants.TYPES_NS, "value", "t"));
DOMUtil.setXsiType(value, DOMUtil.XSD_STRING);
value.setTextContent("TODO");
} else if (action == Action.EXECUTE_SCRIPT) {
Element scriptParam = DOMUtil.createSubElement(actionE, new QName(Constants.SCRIPT_NS, "parameter", "s"));
DOMUtil.createSubElement(scriptParam, new QName(Constants.SCRIPT_NS, "name", "s")).setTextContent("script");
Element script = DOMUtil.createSubElement(scriptParam, new QName(Constants.COMMON_NS, "value", "c"));
DOMUtil.setXsiType(script, new QName(Constants.COMMON_NS, "ScriptExpressionEvaluatorType", "c"));
DOMUtil.createSubElement(script, new QName(Constants.COMMON_NS, "code", "c")).setTextContent("\n log.info('{}', input.asPrismObject().debugDump())");
DOMUtil.createComment(actionE, " <s:parameter><s:name>outputItem</s:name><c:value xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3'>UserType</c:value></s:parameter> ");
}
}
@Override
public boolean supportsRawOption() {
return action.supportsRaw;
}
@Override
public boolean supportsDryRunOption() {
return action.supportsDryRun;
}
@Override
public boolean isExecutable() {
return action != Action.MODIFY && action != Action.EXECUTE_SCRIPT;
}
@Override
public boolean supportsWrapIntoTask() {
return true;
}
public String generateFromSourceObject(SourceObject object, GeneratorOptions options) {
Element pipe = DOMUtil.getDocument(new QName(Constants.SCRIPT_NS, "pipeline", "s")).getDocumentElement();
createSingleSourceSearch(pipe, object);
createAction(pipe, options);
return DOMUtil.serializeDOMToString(pipe);
}
@Override
protected boolean requiresExecutionConfirmation() {
return action.requiresConfirmation;
}
public String getActionDescription() {
return action.displayName;
}
} |
package graphql.execution;
import graphql.Assert;
import graphql.Internal;
import graphql.language.Argument;
import graphql.language.ArrayValue;
import graphql.language.NullValue;
import graphql.language.ObjectField;
import graphql.language.ObjectValue;
import graphql.language.Value;
import graphql.language.VariableDefinition;
import graphql.language.VariableReference;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseValueException;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLCodeRegistry;
import graphql.schema.GraphQLEnumType;
import graphql.schema.GraphQLInputObjectField;
import graphql.schema.GraphQLInputObjectType;
import graphql.schema.GraphQLInputType;
import graphql.schema.GraphQLList;
import graphql.schema.GraphQLScalarType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLType;
import graphql.schema.visibility.GraphqlFieldVisibility;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static graphql.Assert.assertShouldNeverHappen;
import static graphql.collect.ImmutableKit.map;
import static graphql.schema.GraphQLTypeUtil.isList;
import static graphql.schema.GraphQLTypeUtil.isNonNull;
import static graphql.schema.GraphQLTypeUtil.unwrapOne;
import static graphql.schema.visibility.DefaultGraphqlFieldVisibility.DEFAULT_FIELD_VISIBILITY;
@SuppressWarnings("rawtypes")
@Internal
public class ValuesResolver {
/**
* This method coerces the "raw" variables values provided to the engine. The coerced values will be used to
* provide arguments to {@link graphql.schema.DataFetchingEnvironment}
* The coercing is ultimately done via {@link Coercing}.
*
* @param schema the schema
* @param variableDefinitions the variable definitions
* @param variableValues the supplied variables
*
* @return coerced variable values as a map
*/
public Map<String, Object> coerceVariableValues(GraphQLSchema schema, List<VariableDefinition> variableDefinitions, Map<String, Object> variableValues) {
GraphqlFieldVisibility fieldVisibility = schema.getCodeRegistry().getFieldVisibility();
Map<String, Object> coercedValues = new LinkedHashMap<>();
for (VariableDefinition variableDefinition : variableDefinitions) {
String variableName = variableDefinition.getName();
Deque<Object> nameStack = new ArrayDeque<>();
GraphQLType variableType = TypeFromAST.getTypeFromAST(schema, variableDefinition.getType());
Assert.assertTrue(variableType instanceof GraphQLInputType);
// can be NullValue
Value defaultValue = variableDefinition.getDefaultValue();
boolean hasValue = variableValues.containsKey(variableName);
Object value = variableValues.get(variableName);
if (!hasValue && defaultValue != null) {
Object coercedDefaultValue = coerceValueAst(fieldVisibility, variableType, defaultValue, null);
coercedValues.put(variableName, coercedDefaultValue);
} else if (isNonNull(variableType) && (!hasValue || value == null)) {
throw new NonNullableValueCoercedAsNullException(variableDefinition, variableType);
} else if (hasValue) {
if (value == null) {
coercedValues.put(variableName, null);
} else {
Object coercedValue = coerceValue(fieldVisibility, variableDefinition, variableDefinition.getName(), variableType, value, nameStack);
coercedValues.put(variableName, coercedValue);
}
} else {
// hasValue = false && no defaultValue for a nullable type
// meaning no value was provided for variableName
}
}
return coercedValues;
}
public Map<String, Object> getArgumentValues(List<GraphQLArgument> argumentTypes, List<Argument> arguments, Map<String, Object> variables) {
GraphQLCodeRegistry codeRegistry = GraphQLCodeRegistry.newCodeRegistry().fieldVisibility(DEFAULT_FIELD_VISIBILITY).build();
return getArgumentValuesImpl(codeRegistry, argumentTypes, arguments, variables);
}
public Map<String, Object> getArgumentValues(GraphQLCodeRegistry codeRegistry, List<GraphQLArgument> argumentTypes, List<Argument> arguments, Map<String, Object> variables) {
return getArgumentValuesImpl(codeRegistry, argumentTypes, arguments, variables);
}
private Map<String, Object> getArgumentValuesImpl(GraphQLCodeRegistry codeRegistry, List<GraphQLArgument> argumentTypes, List<Argument> arguments,
Map<String, Object> coercedVariableValues) {
if (argumentTypes.isEmpty()) {
return Collections.emptyMap();
}
Map<String, Object> coercedValues = new LinkedHashMap<>();
Map<String, Argument> argumentMap = argumentMap(arguments);
for (GraphQLArgument argumentDefinition : argumentTypes) {
GraphQLInputType argumentType = argumentDefinition.getType();
String argumentName = argumentDefinition.getName();
Argument argument = argumentMap.get(argumentName);
Object defaultValue = argumentDefinition.getDefaultValue();
boolean hasValue = argument != null;
Object value;
Value argumentValue = argument != null ? argument.getValue() : null;
if (argumentValue instanceof VariableReference) {
String variableName = ((VariableReference) argumentValue).getName();
hasValue = coercedVariableValues.containsKey(variableName);
value = coercedVariableValues.get(variableName);
} else {
value = argumentValue;
}
if (!hasValue && argumentDefinition.hasSetDefaultValue()) {
//TODO: default value needs to be coerced
coercedValues.put(argumentName, defaultValue);
} else if (isNonNull(argumentType) && (!hasValue || value == null)) {
throw new RuntimeException();
} else if (hasValue) {
if (value == null) {
coercedValues.put(argumentName, null);
} else if (argumentValue instanceof VariableReference) {
coercedValues.put(argumentName, value);
} else {
value = coerceValueAst(codeRegistry.getFieldVisibility(), argumentType, argument.getValue(), coercedVariableValues);
coercedValues.put(argumentName, value);
}
} else {
// nullable type && hasValue == false && hasDefaultValue == false
// meaning no value was provided for argumentName
}
}
return coercedValues;
}
private Map<String, Argument> argumentMap(List<Argument> arguments) {
Map<String, Argument> result = new LinkedHashMap<>(arguments.size());
for (Argument argument : arguments) {
result.put(argument.getName(), argument);
}
return result;
}
@SuppressWarnings("unchecked")
private Object coerceValue(GraphqlFieldVisibility fieldVisibility, VariableDefinition variableDefinition, String inputName, GraphQLType graphQLType, Object value, Deque<Object> nameStack) {
nameStack.addLast(inputName);
try {
if (isNonNull(graphQLType)) {
Object returnValue =
coerceValue(fieldVisibility, variableDefinition, inputName, unwrapOne(graphQLType), value, nameStack);
if (returnValue == null) {
throw new NonNullableValueCoercedAsNullException(variableDefinition, inputName, Arrays.asList(nameStack.toArray()), graphQLType);
}
return returnValue;
}
if (value == null) {
return null;
}
if (graphQLType instanceof GraphQLScalarType) {
return coerceValueForScalar((GraphQLScalarType) graphQLType, value);
} else if (graphQLType instanceof GraphQLEnumType) {
return coerceValueForEnum((GraphQLEnumType) graphQLType, value);
} else if (graphQLType instanceof GraphQLList) {
return coerceValueForList(fieldVisibility, variableDefinition, inputName, (GraphQLList) graphQLType, value, nameStack);
} else if (graphQLType instanceof GraphQLInputObjectType) {
if (value instanceof Map) {
return coerceValueForInputObjectType(fieldVisibility, variableDefinition, (GraphQLInputObjectType) graphQLType, (Map<String, Object>) value, nameStack);
} else {
throw CoercingParseValueException.newCoercingParseValueException()
.message("Expected type 'Map' but was '" + value.getClass().getSimpleName() +
"'. Variables for input objects must be an instance of type 'Map'.")
.path(Arrays.asList(nameStack.toArray()))
.build();
}
} else {
return assertShouldNeverHappen("unhandled type %s", graphQLType);
}
} catch (CoercingParseValueException e) {
if (e.getLocations() != null) {
throw e;
}
throw CoercingParseValueException.newCoercingParseValueException()
.message("Variable '" + inputName + "' has an invalid value : " + e.getMessage())
.extensions(e.getExtensions())
.cause(e.getCause())
.sourceLocation(variableDefinition.getSourceLocation())
.path(Arrays.asList(nameStack.toArray()))
.build();
} finally {
nameStack.removeLast();
}
}
private Object coerceValueForInputObjectType(GraphqlFieldVisibility fieldVisibility,
VariableDefinition variableDefinition,
GraphQLInputObjectType inputObjectType,
Map<String, Object> inputMap,
Deque<Object> nameStack) {
// Map<String, Object> result = new LinkedHashMap<>();
List<GraphQLInputObjectField> fields = fieldVisibility.getFieldDefinitions(inputObjectType);
List<String> fieldNames = map(fields, GraphQLInputObjectField::getName);
for (String inputFieldName : inputMap.keySet()) {
if (!fieldNames.contains(inputFieldName)) {
throw new InputMapDefinesTooManyFieldsException(inputObjectType, inputFieldName);
}
}
Map<String, Object> coercedValues = new LinkedHashMap<>();
List<GraphQLInputObjectField> inputFieldTypes = fieldVisibility.getFieldDefinitions(inputObjectType);
for (GraphQLInputObjectField inputFieldDefinition : inputFieldTypes) {
GraphQLInputType fieldType = inputFieldDefinition.getType();
String fieldName = inputFieldDefinition.getName();
Object defaultValue = inputFieldDefinition.getDefaultValue();
boolean hasValue = inputMap.containsKey(fieldName);
Object value;
Object fieldValue = inputMap.getOrDefault(fieldName, null);
value = fieldValue;
if (!hasValue && inputFieldDefinition.hasSetDefaultValue()) {
//TODO: default value should be coerced
coercedValues.put(fieldName, defaultValue);
} else if (isNonNull(fieldType) && (!hasValue || value == null)) {
nameStack.addLast(fieldName);
throw new NonNullableValueCoercedAsNullException(variableDefinition, fieldName, Arrays.asList(nameStack.toArray()), fieldType);
} else if (hasValue) {
if (value == null) {
coercedValues.put(fieldName, null);
} else if (fieldValue instanceof VariableReference) {
coercedValues.put(fieldName, value);
} else {
value = coerceValue(fieldVisibility,
variableDefinition,
inputFieldDefinition.getName(),
fieldType,
value,
nameStack);
coercedValues.put(fieldName, value);
}
} else {
// nullable type && hasValue == false && hasDefaultValue == false
// meaning no value was provided for this field
}
}
return coercedValues;
// for (GraphQLInputObjectField inputField : fields) {
// if (inputMap.containsKey(inputField.getName()) || alwaysHasValue(inputField)) {
// // getOrDefault will return a null value if its present in the map as null
// // defaulting only applies if the key is missing - we want this
// Object inputValue = inputMap.getOrDefault(inputField.getName(), inputField.getDefaultValue());
// Object coerceValue = coerceValue(fieldVisibility, variableDefinition,
// inputField.getName(),
// inputField.getType(),
// inputValue,
// nameStack);
// result.put(inputField.getName(), coerceValue == null ? inputField.getDefaultValue() : coerceValue);
// return result;
}
private boolean alwaysHasValue(GraphQLInputObjectField inputField) {
return inputField.getDefaultValue() != null
|| isNonNull(inputField.getType());
}
private Object coerceValueForScalar(GraphQLScalarType graphQLScalarType, Object value) {
return graphQLScalarType.getCoercing().parseValue(value);
}
private Object coerceValueForEnum(GraphQLEnumType graphQLEnumType, Object value) {
return graphQLEnumType.parseValue(value);
}
private List coerceValueForList(GraphqlFieldVisibility fieldVisibility, VariableDefinition variableDefinition, String inputName, GraphQLList graphQLList, Object value, Deque<Object> nameStack) {
if (value instanceof Iterable) {
List<Object> result = new ArrayList<>();
for (Object val : (Iterable) value) {
result.add(coerceValue(fieldVisibility, variableDefinition, inputName, graphQLList.getWrappedType(), val, nameStack));
}
return result;
} else {
return Collections.singletonList(coerceValue(fieldVisibility, variableDefinition, inputName, graphQLList.getWrappedType(), value, nameStack));
}
}
private Object coerceValueAst(GraphqlFieldVisibility fieldVisibility, GraphQLType type, Value inputValue, Map<String, Object> variables) {
if (inputValue instanceof VariableReference) {
return variables.get(((VariableReference) inputValue).getName());
}
if (inputValue instanceof NullValue) {
return null;
}
if (type instanceof GraphQLScalarType) {
return parseLiteral(inputValue, ((GraphQLScalarType) type).getCoercing(), variables);
}
if (isNonNull(type)) {
return coerceValueAst(fieldVisibility, unwrapOne(type), inputValue, variables);
}
if (type instanceof GraphQLInputObjectType) {
return coerceValueAstForInputObject(fieldVisibility, (GraphQLInputObjectType) type, (ObjectValue) inputValue, variables);
}
if (type instanceof GraphQLEnumType) {
return ((GraphQLEnumType) type).parseLiteral(inputValue);
}
if (isList(type)) {
return coerceValueAstForList(fieldVisibility, (GraphQLList) type, inputValue, variables);
}
return null;
}
private Object parseLiteral(Value inputValue, Coercing coercing, Map<String, Object> variables) {
// the CoercingParseLiteralException exception that could happen here has been validated earlier via ValidationUtil
return coercing.parseLiteral(inputValue, variables);
}
private Object coerceValueAstForList(GraphqlFieldVisibility fieldVisibility, GraphQLList graphQLList, Value value, Map<String, Object> variables) {
if (value instanceof ArrayValue) {
ArrayValue arrayValue = (ArrayValue) value;
List<Object> result = new ArrayList<>();
for (Value singleValue : arrayValue.getValues()) {
result.add(coerceValueAst(fieldVisibility, graphQLList.getWrappedType(), singleValue, variables));
}
return result;
} else {
return Collections.singletonList(coerceValueAst(fieldVisibility, graphQLList.getWrappedType(), value, variables));
}
}
private Object coerceValueAstForInputObject(GraphqlFieldVisibility fieldVisibility,
GraphQLInputObjectType type,
ObjectValue inputValue,
Map<String, Object> coercedVariableValues) {
Map<String, Object> coercedValues = new LinkedHashMap<>();
Map<String, ObjectField> inputFieldsByName = mapObjectValueFieldsByName(inputValue);
List<GraphQLInputObjectField> inputFieldTypes = fieldVisibility.getFieldDefinitions(type);
for (GraphQLInputObjectField inputFieldType : inputFieldTypes) {
GraphQLInputType fieldType = inputFieldType.getType();
String fieldName = inputFieldType.getName();
ObjectField field = inputFieldsByName.get(fieldName);
Object defaultValue = inputFieldType.getDefaultValue();
boolean hasValue = field != null;
Object value;
Value fieldValue = field != null ? field.getValue() : null;
if (fieldValue instanceof VariableReference) {
String variableName = ((VariableReference) fieldValue).getName();
hasValue = coercedVariableValues.containsKey(variableName);
value = coercedVariableValues.get(variableName);
} else {
value = fieldValue;
}
if (!hasValue && inputFieldType.hasSetDefaultValue()) {
//TODO: default value should be coerced
coercedValues.put(fieldName, defaultValue);
} else if (isNonNull(fieldType) && (!hasValue || value == null)) {
throw new NonNullableValueCoercedAsNullException(inputFieldType);
} else if (hasValue) {
if (value == null) {
coercedValues.put(fieldName, null);
} else if (fieldValue instanceof VariableReference) {
coercedValues.put(fieldName, value);
} else {
value = coerceValueAst(fieldVisibility, fieldType, fieldValue, coercedVariableValues);
coercedValues.put(fieldName, value);
}
} else {
// nullable type && hasValue == false && hasDefaultValue == false
// meaning no value was provided for this field
}
}
return coercedValues;
}
private void assertNonNullInputField(GraphQLInputObjectField inputTypeField) {
if (isNonNull(inputTypeField.getType())) {
throw new NonNullableValueCoercedAsNullException(inputTypeField);
}
}
private Map<String, ObjectField> mapObjectValueFieldsByName(ObjectValue inputValue) {
Map<String, ObjectField> inputValueFieldsByName = new LinkedHashMap<>();
for (ObjectField objectField : inputValue.getObjectFields()) {
inputValueFieldsByName.put(objectField.getName(), objectField);
}
return inputValueFieldsByName;
}
} |
package graphql.schema;
import graphql.introspection.Introspection;
import graphql.util.TraversalControl;
import graphql.util.TraverserContext;
import graphql.util.TraverserVisitor;
import graphql.util.TreeTransformer;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import static graphql.Assert.assertShouldNeverHappen;
import static graphql.schema.GraphQLSchemaElementAdapter.SCHEMA_ELEMENT_ADAPTER;
import static graphql.schema.SchemaElementChildrenContainer.newSchemaElementChildrenContainer;
public class SchemaTransformer {
// artificial schema element which serves as root element for the transformation
private static class DummyRoot implements GraphQLSchemaElement {
static final String QUERY = "query";
static final String MUTATION = "mutation";
static final String SUBSCRIPTION = "subscription";
static final String ADD_TYPES = "addTypes";
static final String DIRECTIVES = "directives";
static final String INTROSPECTION = "introspection";
GraphQLSchema schema;
GraphQLObjectType query;
GraphQLObjectType mutation;
GraphQLObjectType subscription;
Set<GraphQLType> additionalTypes;
Set<GraphQLDirective> directives;
DummyRoot(GraphQLSchema schema) {
this.schema = schema;
query = schema.getQueryType();
mutation = schema.isSupportingMutations() ? schema.getMutationType() : null;
subscription = schema.isSupportingSubscriptions() ? schema.getSubscriptionType() : null;
additionalTypes = schema.getAdditionalTypes();
directives = new LinkedHashSet<>(schema.getDirectives());
}
@Override
public List<GraphQLSchemaElement> getChildren() {
return assertShouldNeverHappen();
}
@Override
public SchemaElementChildrenContainer getChildrenWithTypeReferences() {
SchemaElementChildrenContainer.Builder builder = newSchemaElementChildrenContainer()
.child(QUERY, query);
if (schema.isSupportingMutations()) {
builder.child(MUTATION, mutation);
}
if (schema.isSupportingSubscriptions()) {
builder.child(SUBSCRIPTION, subscription);
}
builder.children(ADD_TYPES, additionalTypes);
builder.children(DIRECTIVES, directives);
builder.child(INTROSPECTION, Introspection.__Schema);
return builder.build();
}
@Override
public GraphQLSchemaElement withNewChildren(SchemaElementChildrenContainer newChildren) {
query = newChildren.getChildOrNull(QUERY);
mutation = newChildren.getChildOrNull(MUTATION);
subscription = newChildren.getChildOrNull(SUBSCRIPTION);
additionalTypes = new LinkedHashSet<>(newChildren.getChildren(ADD_TYPES));
directives = new LinkedHashSet<>(newChildren.getChildren(DIRECTIVES));
return this;
}
@Override
public TraversalControl accept(TraverserContext<GraphQLSchemaElement> context, GraphQLTypeVisitor visitor) {
return assertShouldNeverHappen();
}
}
;
public GraphQLSchema transformWholeSchema(final GraphQLSchema schema, GraphQLTypeVisitor visitor) {
DummyRoot dummyRoot = new DummyRoot(schema);
TraverserVisitor<GraphQLSchemaElement> traverserVisitor = new TraverserVisitor<GraphQLSchemaElement>() {
@Override
public TraversalControl enter(TraverserContext<GraphQLSchemaElement> context) {
if (context.thisNode() == dummyRoot) {
return TraversalControl.CONTINUE;
}
return context.thisNode().accept(context, visitor);
}
@Override
public TraversalControl leave(TraverserContext<GraphQLSchemaElement> context) {
return TraversalControl.CONTINUE;
}
};
TreeTransformer<GraphQLSchemaElement> treeTransformer = new TreeTransformer<>(SCHEMA_ELEMENT_ADAPTER);
treeTransformer.transform(dummyRoot, traverserVisitor);
GraphQLSchema newSchema = GraphQLSchema.newSchema()
.query(dummyRoot.query)
.mutation(dummyRoot.mutation)
.subscription(dummyRoot.subscription)
.additionalTypes(dummyRoot.additionalTypes)
.additionalDirectives(dummyRoot.directives)
.build();
return newSchema;
}
} |
package innovimax.mixthem.arguments;
import java.util.EnumSet;
/**
* <p>This is a detailed enumeration of rules used to mix files.</p>
* <p>Some rules may not be implemented yet.<.p>
* <p>(Also used to print usage.)</p>
* @author Innovimax
* @version 1.0
*/
public enum Rule {
FILE_1("1", "1", "will output file1", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(Mode.CHAR, Mode.BYTE)),
FILE_2("2", "2", "will output file2", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(Mode.CHAR, Mode.BYTE)),
ADD("+", "add", "will output file1+file2+...+fileN", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(Mode.CHAR, Mode.BYTE)),
ALT_LINE("alt-line", "altline", "will output one line of each starting with first line of file1", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(Mode.CHAR)),
ALT_CHAR("alt-char", "altchar", "will output one char of each starting with first char of file1", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(Mode.CHAR)),
ALT_BYTE("alt-byte", "altbyte", "will output one byte of each starting with first byte of file1", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(Mode.BYTE)),
RANDOM_ALT_LINE("random-alt-line", "random-altline", "will output one line of each code randomly based on a seed for reproducability", true, EnumSet.of(RuleParam.RANDOM_SEED), EnumSet.of(Mode.CHAR)),
RANDOM_ALT_CHAR("random-alt-char", "random-altchar", "will output one char of each code randomly based on a seed for reproducability", true, EnumSet.of(RuleParam.RANDOM_SEED), EnumSet.of(Mode.CHAR)),
RANDOM_ALT_BYTE("random-alt-byte", "random-altbyte", "will output one byte of each code randomly based on a seed for reproducability", true, EnumSet.of(RuleParam.RANDOM_SEED), EnumSet.of(Mode.BYTE)),
JOIN("join", "join", "will output merging of lines that have common occurrence", true, EnumSet.of(RuleParam.JOIN_COL1, RuleParam.JOIN_COL2), EnumSet.of(Mode.CHAR)),
ZIP_LINE("zip-line", "zipline", "will output zip of line from file1 and file2 to fileN", true, EnumSet.of(RuleParam.ZIP_SEP), EnumSet.of(Mode.CHAR)),
ZIP_CHAR("zip-char", "zipchar", "will output zip of char from file1 and file2 to fileN", true, EnumSet.of(RuleParam.ZIP_SEP), EnumSet.of(Mode.CHAR)),
ZIP_CELL("zip-cell", "zipcell", "will output zip of cell from file1 and file2 to fileN", true, EnumSet.of(RuleParam.ZIP_SEP), EnumSet.of(Mode.CHAR));
private final String name, extension, description;
private final boolean implemented;
private final EnumSet<RuleParam> params;
private final EnumSet<Mode> modes;
private Rule(final String name, final String extension, final String description, final boolean implemented, final EnumSet<RuleParam> params, final EnumSet<Mode> modes) {
this.name = name;
this.extension = extension;
this.description = description;
this.implemented = implemented;
this.params = params;
this.modes = modes;
}
/**
* Returns true if the rule is currently implemented.
* @return True if the rule is currently implemented
*/
public boolean isImplemented() {
return this.implemented;
}
/**
* Returns the name of this rule on command line.
* @return The name of the rule on command line
*/
public String getName() {
return this.name;
}
/**
* Returns the file extension used for outputting.
* @return The file extension for the rule
*/
public String getExtension() {
return this.extension;
}
/**
* Returns the description of this rule.
* @return The description of the rule
*/
public String getDescription() {
return this.description;
}
/**
* Returns an iterator over the additional parameters in this rule.
* @return An iterator over the additional parameters in this rule
*/
public Iterable<RuleParam> getParams() {
return this.params;
}
/**
* Returns true if the rule accept the running mode.
* @return True if the rule accept the running mode
*/
public boolean acceptMode(final Mode mode) {
return modes.contains(mode);
}
/**
* Finds the Rule object correponding to a name
* @param name The name of the rule in command line
* @param mode The running {@link Mode)
* @return The {@link Rule} object
*/
public static Rule findByName(final String name, final Mode mode) {
for(Rule rule : values()){
if (rule.getName().equals(name) && rule.acceptMode(mode)) {
return rule;
}
}
return null;
}
} |
package org.innovateuk.ifs.management.application.view.populator;
import org.innovateuk.ifs.application.readonly.ApplicationReadOnlySettings;
import org.innovateuk.ifs.application.readonly.populator.ApplicationReadOnlyViewModelPopulator;
import org.innovateuk.ifs.application.readonly.viewmodel.ApplicationReadOnlyViewModel;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.resource.ApplicationState;
import org.innovateuk.ifs.application.resource.FormInputResponseResource;
import org.innovateuk.ifs.application.service.ApplicationRestService;
import org.innovateuk.ifs.application.service.QuestionRestService;
import org.innovateuk.ifs.application.service.SectionService;
import org.innovateuk.ifs.application.summary.populator.InterviewFeedbackViewModelPopulator;
import org.innovateuk.ifs.application.summary.viewmodel.InterviewFeedbackViewModel;
import org.innovateuk.ifs.assessment.service.AssessmentRestService;
import org.innovateuk.ifs.assessment.service.AssessorFormInputResponseRestService;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionAssessmentConfigRestService;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.file.resource.FileEntryResource;
import org.innovateuk.ifs.file.service.FileEntryRestService;
import org.innovateuk.ifs.form.resource.FormInputResource;
import org.innovateuk.ifs.form.service.FormInputResponseRestService;
import org.innovateuk.ifs.form.service.FormInputRestService;
import org.innovateuk.ifs.interview.service.InterviewAssignmentRestService;
import org.innovateuk.ifs.management.application.view.viewmodel.AppendixViewModel;
import org.innovateuk.ifs.management.application.view.viewmodel.ApplicationOverviewIneligibilityViewModel;
import org.innovateuk.ifs.management.application.view.viewmodel.ManagementApplicationViewModel;
import org.innovateuk.ifs.project.ProjectService;
import org.innovateuk.ifs.project.resource.ProjectResource;
import org.innovateuk.ifs.project.service.ProjectRestService;
import org.innovateuk.ifs.user.resource.Authority;
import org.innovateuk.ifs.user.resource.Role;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static org.innovateuk.ifs.application.readonly.ApplicationReadOnlySettings.defaultSettings;
import static org.innovateuk.ifs.application.resource.ApplicationState.SUBMITTED;
import static org.innovateuk.ifs.form.resource.FormInputType.FILEUPLOAD;
import static org.innovateuk.ifs.form.resource.FormInputType.TEMPLATE_DOCUMENT;
import static org.innovateuk.ifs.user.resource.Role.*;
@Component
public class ManagementApplicationPopulator {
@Autowired
private ApplicationOverviewIneligibilityModelPopulator applicationOverviewIneligibilityModelPopulator;
@Autowired
private ApplicationReadOnlyViewModelPopulator applicationSummaryViewModelPopulator;
@Autowired
private ApplicationRestService applicationRestService;
@Autowired
private CompetitionRestService competitionRestService;
@Autowired
private FormInputResponseRestService formInputResponseRestService;
@Autowired
private FormInputRestService formInputRestService;
@Autowired
private FileEntryRestService fileEntryRestService;
@Autowired
private InterviewAssignmentRestService interviewAssignmentRestService;
@Autowired
private InterviewFeedbackViewModelPopulator interviewFeedbackViewModelPopulator;
@Autowired
private ProjectRestService projectRestService;
@Autowired
private ProjectService projectService;
@Autowired
private AssessmentRestService assessmentRestService;
@Autowired
private QuestionRestService questionRestService;
@Autowired
private SectionService sectionService;
@Autowired
private AssessorFormInputResponseRestService assessorFormInputResponseRestService;
@Autowired
private CompetitionAssessmentConfigRestService competitionAssessmentConfigRestService;
public ManagementApplicationViewModel populate(long applicationId,
UserResource user) {
ApplicationResource application = applicationRestService.getApplicationById(applicationId).getSuccess();
CompetitionResource competition = competitionRestService.getCompetitionById(application.getCompetition()).getSuccess();
ApplicationReadOnlySettings settings = defaultSettings()
.setIncludeAllAssessorFeedback(userCanViewFeedback(user, competition, applicationId));
boolean support = user.hasRole(Role.SUPPORT);
if (support && application.isOpen()) {
settings.setIncludeStatuses(true);
}
final InterviewFeedbackViewModel interviewFeedbackViewModel;
if (settings.isIncludeAllAssessorFeedback() && interviewAssignmentRestService.isAssignedToInterview(application.getId()).getSuccess()) {
interviewFeedbackViewModel = interviewFeedbackViewModelPopulator.populate(application.getId(), application.getCompetitionName(), user, application.isFeedbackReleased());
} else {
interviewFeedbackViewModel = null;
}
ApplicationReadOnlyViewModel applicationReadOnlyViewModel = applicationSummaryViewModelPopulator.populate(application, competition, user, settings);
ApplicationOverviewIneligibilityViewModel ineligibilityViewModel = applicationOverviewIneligibilityModelPopulator.populateModel(application);
Long projectId = null;
if (application.getApplicationState() == ApplicationState.APPROVED) {
projectId = projectRestService.getByApplicationId(applicationId).getOptionalSuccessObject().map(ProjectResource::getId).orElse(null);
}
return new ManagementApplicationViewModel(
application,
competition,
ineligibilityViewModel,
applicationReadOnlyViewModel,
getAppendices(applicationId),
canMarkAsIneligible(application, user),
user.hasAuthority(Authority.COMP_ADMIN),
support,
projectId,
user.hasRole(Role.EXTERNAL_FINANCE),
isProjectWithdrawn(applicationId),
interviewFeedbackViewModel
);
}
private boolean userCanViewFeedback(UserResource user, CompetitionResource competition, Long applicationId) {
return (user.hasAuthority(Authority.PROJECT_FINANCE) && competition.isProcurement())
|| interviewAssigned(applicationId, user);
}
private boolean interviewAssigned(Long applicationId, UserResource loggedInUser) {
return loggedInUser.hasAuthority(Authority.COMP_ADMIN) && interviewAssignmentRestService.isAssignedToInterview(applicationId).getSuccess();
}
private boolean isProjectWithdrawn(Long applicationId) {
ProjectResource project = projectService.getByApplicationId(applicationId);
return project != null && project.isWithdrawn();
}
private List<AppendixViewModel> getAppendices(Long applicationId) {
List<FormInputResponseResource> responses = formInputResponseRestService.getResponsesByApplicationId(applicationId).getSuccess();
return responses.stream().filter(fir -> fir.getFileEntries() != null && !fir.getFileEntries().isEmpty())
.flatMap(fir -> fir.getFileEntries().stream()
.map(file -> {
FormInputResource formInputResource = formInputRestService.getById(fir.getFormInput()).getSuccess();
String title = fileTitle(formInputResource, file);
return new AppendixViewModel(applicationId, formInputResource.getId(), title, file);
}))
.collect(Collectors.toList());
}
private static String fileTitle(FormInputResource formInputResource, FileEntryResource fileEntryResource) {
if (TEMPLATE_DOCUMENT.equals(formInputResource.getType())) {
return format("Uploaded %s", formInputResource.getDescription());
} else if (FILEUPLOAD.equals(formInputResource.getType())) {
return "Appendix";
}
return formInputResource.getDescription() != null ? formInputResource.getDescription() : fileEntryResource.getName();
}
private boolean canMarkAsIneligible(ApplicationResource application, UserResource user) {
return !application.isEnabledForExpressionOfInterest() && application.getApplicationState() == SUBMITTED
&& user.hasAnyRoles(IFS_ADMINISTRATOR, PROJECT_FINANCE, COMP_ADMIN, Role.INNOVATION_LEAD);
}
} |
package innovimax.mixthem.io;
import java.io.IOException;
/**
* This interface provides for writing characters in an output stream.
* @author Innovimax
* @version 1.0
*/
public interface IOutputChar {
/**
* Writes a single character.
* @param c The character to be written
* @throws IOException - If an I/O error occurs
*/
void writeCharacter(char c) throws IOException;
/**
* Writes a portion of an array of characters.
* @param buffer Buffer of characters
* @param len Number of characters to write
* @throws IOException - If an I/O error occurs
*/
void writeCharacters(char[] buffer, int len) throws IOException;
/**
* Closes this output and releases any system resources associated with it.
* @throws IOException - If an I/O error occurs
*/
void close() throws IOException;
} |
package org.eclipse.persistence.testing.oxm.mappings.directcollection.typeattribute;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.persistence.testing.oxm.mappings.directcollection.typeattribute.identifiedbyname.withgroupingelement.*;
import org.eclipse.persistence.testing.oxm.mappings.directcollection.typeattribute.identifiedbyname.withoutgroupingelement.*;
public class DirectCollectionTypeAttributeTestCases extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite("DirectCollection Type Attribute Test Cases");
suite.addTestSuite(WithGroupingElementIdentifiedByNameIntegerTestCases.class);
suite.addTestSuite(WithGroupingElementIdentifiedByNameTestCases.class);
suite.addTestSuite(WithoutGroupingElementIdentifiedByNameIntegerTestCases.class);
suite.addTestSuite(WithoutGroupingElementIdentifiedByNameTestCases.class);
return suite;
}
public static void main(String[] args) {
String[] arguments = { "-c", "org.eclipse.persistence.testing.oxm.mappings.directcollection.typeattribute.DirectCollectionTypeAttributeTestCases" };
junit.textui.TestRunner.main(arguments);
}
} |
package fr.openwide.core.jpa.more.business.property.service;
import java.io.File;
import java.math.BigDecimal;
import java.net.URI;
import java.util.Date;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.javatuples.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import com.google.common.base.Converter;
import com.google.common.base.Enums;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.Maps;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Floats;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import fr.openwide.core.commons.util.functional.Suppliers2;
import fr.openwide.core.commons.util.functional.converter.StringBigDecimalConverter;
import fr.openwide.core.commons.util.functional.converter.StringBooleanConverter;
import fr.openwide.core.commons.util.functional.converter.StringDateConverter;
import fr.openwide.core.commons.util.functional.converter.StringDateTimeConverter;
import fr.openwide.core.commons.util.functional.converter.StringDirectoryFileConverter;
import fr.openwide.core.commons.util.functional.converter.StringURIConverter;
import fr.openwide.core.jpa.exception.SecurityServiceException;
import fr.openwide.core.jpa.exception.ServiceException;
import fr.openwide.core.jpa.more.business.parameter.model.Parameter;
import fr.openwide.core.jpa.more.business.parameter.service.IAbstractParameterService;
import fr.openwide.core.jpa.more.business.property.dao.IImmutablePropertyDao;
import fr.openwide.core.jpa.more.business.property.dao.IMutablePropertyDao;
import fr.openwide.core.jpa.more.business.property.model.ImmutablePropertyId;
import fr.openwide.core.jpa.more.business.property.model.ImmutablePropertyRegistryKey;
import fr.openwide.core.jpa.more.business.property.model.MutablePropertyId;
import fr.openwide.core.jpa.more.business.property.model.MutablePropertyRegistryKey;
import fr.openwide.core.jpa.more.business.property.model.PropertyId;
import fr.openwide.core.jpa.more.business.property.model.PropertyRegistryKey;
import fr.openwide.core.jpa.more.config.spring.event.PropertyServiceInitEvent;
import fr.openwide.core.spring.config.CoreConfigurer;
/**
* Use this service to retrieve application properties instead of using {@link CoreConfigurer} or {@link IAbstractParameterService}.
* It handles both mutable and immutable properties ; immutable properties are retrieved from properties resources files
* ({@link IImmutablePropertyDao}) and mutable properties are related to {@link Parameter} ({@link IMutablePropertyDao}).
* @see {@link IPropertyRegistry} to register application properties.
*/
public class PropertyServiceImpl implements IConfigurablePropertyService, ApplicationEventPublisherAware {
private final Map<PropertyRegistryKey<?>, Pair<? extends Converter<String, ?>, ? extends Supplier<?>>> propertyInformationMap = Maps.newHashMap();
@Autowired
private IMutablePropertyDao mutablePropertyDao;
@Autowired
private IImmutablePropertyDao immutablePropertyDao;
private ApplicationEventPublisher applicationEventPublisher;
private TransactionTemplate readOnlyTransactionTemplate;
private TransactionTemplate writeTransactionTemplate;
@PostConstruct
public void init() {
applicationEventPublisher.publishEvent(new PropertyServiceInitEvent(this));
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
@Override
public <T> void register(MutablePropertyRegistryKey<T> propertyId, Converter<String, T> converter) {
register(propertyId, converter, (T) null);
}
@Override
public <T> void register(MutablePropertyRegistryKey<T> propertyId, Converter<String, T> converter, final T defaultValue) {
register(propertyId, converter, Suppliers2.constant(defaultValue));
}
@Override
public <T> void register(MutablePropertyRegistryKey<T> propertyId, Converter<String, T> converter, Supplier<? extends T> defaultValueSupplier) {
registerProperty(propertyId, converter, defaultValueSupplier);
}
@Override
public <T> void register(ImmutablePropertyRegistryKey<T> propertyId, Function<String, ? extends T> function) {
register(propertyId, function, (T) null);
}
@Override
public <T> void register(ImmutablePropertyRegistryKey<T> propertyId, Function<String, ? extends T> function, final T defaultValue) {
register(propertyId, function, Suppliers2.constant(defaultValue));
}
@Override
public <T> void register(ImmutablePropertyRegistryKey<T> propertyId, final Function<String, ? extends T> function, Supplier<? extends T> defaultValueSupplier) {
registerProperty(propertyId, new Converter<String, T>() {
@Override
protected T doForward(String a) {
return function.apply(a);
}
@Override
protected String doBackward(T b) {
throw new IllegalStateException("Unable to update immutable property.");
}
}, defaultValueSupplier);
}
protected <T> void registerProperty(PropertyRegistryKey<T> propertyId, Converter<String, ? extends T> converter) {
registerProperty(propertyId, converter, (T) null);
}
protected <T> void registerProperty(PropertyRegistryKey<T> propertyId, Converter<String, ? extends T> converter, final T defaultValue) {
registerProperty(propertyId, converter, Suppliers2.constant(defaultValue));
}
protected <T> void registerProperty(PropertyRegistryKey<T> propertyId, Converter<String, ? extends T> converter, Supplier<? extends T> defaultValueSupplier) {
Preconditions.checkNotNull(propertyId);
Preconditions.checkNotNull(converter);
Preconditions.checkNotNull(defaultValueSupplier);
if (propertyInformationMap.get(propertyId) != null) {
throw new IllegalStateException(String.format("Property '%1s' already registered.", propertyId));
}
propertyInformationMap.put(propertyId, Pair.with(converter, defaultValueSupplier));
}
@Override
public void registerString(PropertyRegistryKey<String> propertyId) {
registerString(propertyId, null);
}
@Override
public void registerString(PropertyRegistryKey<String> propertyId, String defaultValue) {
registerProperty(propertyId, Converter.<String>identity(), defaultValue);
}
@Override
public void registerLong(PropertyRegistryKey<Long> propertyId) {
registerLong(propertyId, null);
}
@Override
public void registerLong(PropertyRegistryKey<Long> propertyId, Long defaultValue) {
registerProperty(propertyId, Longs.stringConverter(), defaultValue);
}
@Override
public void registerInteger(PropertyRegistryKey<Integer> propertyId) {
registerInteger(propertyId, null);
}
@Override
public void registerInteger(PropertyRegistryKey<Integer> propertyId, Integer defaultValue) {
registerProperty(propertyId, Ints.stringConverter(), defaultValue);
}
@Override
public void registerFloat(PropertyRegistryKey<Float> propertyId) {
registerFloat(propertyId, null);
}
@Override
public void registerFloat(PropertyRegistryKey<Float> propertyId, Float defaultValue) {
registerProperty(propertyId, Floats.stringConverter(), defaultValue);
}
@Override
public void registerDouble(PropertyRegistryKey<Double> propertyId) {
registerDouble(propertyId, null);
}
@Override
public void registerDouble(PropertyRegistryKey<Double> propertyId, Double defaultValue) {
registerProperty(propertyId, Doubles.stringConverter(), defaultValue);
}
@Override
public void registerBigDecimal(PropertyRegistryKey<BigDecimal> propertyId) {
registerBigDecimal(propertyId, null);
}
@Override
public void registerBigDecimal(PropertyRegistryKey<BigDecimal> propertyId, BigDecimal defaultValue) {
registerProperty(propertyId, StringBigDecimalConverter.get(), defaultValue);
}
@Override
public void registerBoolean(PropertyRegistryKey<Boolean> propertyId) {
registerBoolean(propertyId, null);
}
@Override
public void registerBoolean(PropertyRegistryKey<Boolean> propertyId, Boolean defaultValue) {
registerProperty(propertyId, StringBooleanConverter.get(), defaultValue);
}
@Override
public <E extends Enum<E>> void registerEnum(PropertyRegistryKey<E> propertyId, Class<E> clazz) {
registerEnum(propertyId, clazz, null);
}
@Override
public <E extends Enum<E>> void registerEnum(PropertyRegistryKey<E> propertyId, Class<E> clazz, E defaultValue) {
registerProperty(propertyId, Enums.stringConverter(clazz), defaultValue);
}
@Override
public void registerDate(PropertyRegistryKey<Date> propertyId) {
registerDate(propertyId, (Date) null);
}
@Override
public void registerDate(PropertyRegistryKey<Date> propertyId, String defaultValue) {
registerDate(propertyId, StringDateConverter.get().convert(defaultValue));
}
@Override
public void registerDate(PropertyRegistryKey<Date> propertyId, Date defaultValue) {
registerProperty(propertyId, StringDateConverter.get(), defaultValue);
}
@Override
public void registerDateTime(PropertyRegistryKey<Date> propertyId) {
registerDateTime(propertyId, null);
}
@Override
public void registerDateTime(PropertyRegistryKey<Date> propertyId, Date defaultValue) {
registerProperty(propertyId, StringDateTimeConverter.get(), defaultValue);
}
@Override
public void registerDirectoryFile(PropertyRegistryKey<File> propertyId) {
registerDirectoryFile(propertyId, null);
}
@Override
public void registerDirectoryFile(PropertyRegistryKey<File> propertyId, File defaultValue) {
registerProperty(propertyId, StringDirectoryFileConverter.get(), defaultValue);
}
@Override
public void registerURI(PropertyRegistryKey<URI> propertyId) {
registerURI(propertyId, null);
}
@Override
public void registerURI(PropertyRegistryKey<URI> propertyId, URI defaultValue) {
registerProperty(propertyId, StringURIConverter.get(), defaultValue);
}
@Override
public <T> T get(final PropertyId<T> propertyId) {
Preconditions.checkNotNull(propertyId);
@SuppressWarnings("unchecked")
Pair<Converter<String, T>, Supplier<T>> information = (Pair<Converter<String, T>, Supplier<T>>) propertyInformationMap.get(propertyId.getTemplate() != null ? propertyId.getTemplate() : propertyId);
if (information == null || information.getValue0() == null) {
throw new IllegalStateException(String.format("No converter found for the property '%1s'. Undefined property.", propertyId));
}
String valueAsString = null;
if (propertyId instanceof ImmutablePropertyId) {
valueAsString = immutablePropertyDao.get(propertyId.getKey());
} else if (propertyId instanceof MutablePropertyId) {
valueAsString = readOnlyTransactionTemplate.execute(new TransactionCallback<String>() {
@Override
public String doInTransaction(TransactionStatus status) {
return mutablePropertyDao.get(propertyId.getKey());
}
});
} else {
throw new IllegalStateException(String.format("Unknown type of property : '%1s'.", propertyId));
}
return Optional.fromNullable(information.getValue0().convert(valueAsString)).or(Optional.fromNullable(information.getValue1().get())).orNull();
}
@Override
public <T> void set(final MutablePropertyId<T> propertyId, final T value) throws ServiceException, SecurityServiceException {
Preconditions.checkNotNull(propertyId);
@SuppressWarnings("unchecked")
final
Pair<Converter<String, T>, Supplier<T>> information = (Pair<Converter<String, T>, Supplier<T>>) propertyInformationMap.get(propertyId.getTemplate() != null ? propertyId.getTemplate() : propertyId);
if (information == null || information.getValue0() == null) {
throw new IllegalStateException("No converter found for the property. Undefined property.");
}
writeTransactionTemplate.execute(
new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
mutablePropertyDao.set(propertyId.getKey(), information.getValue0().reverse().convert(value));
return;
} catch (Exception e) {
throw new IllegalStateException(String.format("Error while updating property '%1s'.", propertyId), e);
}
}
}
);
}
@Override
public void clean() {
writeTransactionTemplate.execute(
new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
mutablePropertyDao.clean();
}
}
);
}
@Autowired
public void setPlatformTransactionManager(PlatformTransactionManager transactionManager) {
DefaultTransactionAttribute readOnlyTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED);
readOnlyTransactionAttribute.setReadOnly(true);
readOnlyTransactionTemplate = new TransactionTemplate(transactionManager, readOnlyTransactionAttribute);
DefaultTransactionAttribute writeTransactionAttribute = new DefaultTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED);
writeTransactionAttribute.setReadOnly(false);
writeTransactionTemplate = new TransactionTemplate(transactionManager, writeTransactionAttribute);
}
} |
package io.disassemble.asm.util;
import io.disassemble.asm.ClassFactory;
import io.disassemble.asm.ClassField;
import io.disassemble.asm.ClassMethod;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;
import org.objectweb.asm.util.Printer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import static org.objectweb.asm.tree.AbstractInsnNode.*;
/**
* @author Tyler Sedlar
* @since 2/1/16
*/
public class Assembly implements Opcodes {
/**
* Creates a predicate that matches any of the given opcodes.
*
* @param opcodes The opcodes to match.
* @return A predicate that matches any of the given opcodes.
*/
public static Predicate<AbstractInsnNode> createOpcodePredicate(int... opcodes) {
Arrays.sort(opcodes);
return insn -> (Arrays.binarySearch(opcodes, insn.getOpcode()) >= 0);
}
/**
* Gets a list of instructions matching the given predicate.
*
* @param list The list of instructions.
* @param predicate The predicate to match.
* @return A list of instructions matching the given predicate.
*/
@SuppressWarnings("unchecked")
public static <E extends AbstractInsnNode> List<E> findAll(InsnList list, Predicate<AbstractInsnNode> predicate) {
List<E> results = new ArrayList<>();
AbstractInsnNode[] instructions = list.toArray();
for (AbstractInsnNode insn : instructions) {
if (predicate.test(insn)) {
results.add((E) insn);
}
}
return results;
}
/**
* Checks how many instructions from the given list match the given predicate.
*
* @param list The list of instructions.
* @param predicate The predicate to match.
* @return The amount of instructions from the given list matching the given predicate.
*/
public static int count(InsnList list, Predicate<AbstractInsnNode> predicate) {
return findAll(list, predicate).size();
}
/**
* Finds the first occurrence of an instruction matching the given predicate.
*
* @param list The list of instructions.
* @param predicate The predicate to match.
* @return The first occurrence of an instruction matching the given predicate.
*/
@SuppressWarnings("unchecked")
public static <E extends AbstractInsnNode> E findFirst(InsnList list, Predicate<AbstractInsnNode> predicate) {
AbstractInsnNode[] instructions = list.toArray();
for (AbstractInsnNode insn : instructions) {
if (predicate.test(insn)) {
return (E) insn;
}
}
return null;
}
/**
* Finds The first occurrence of an instruction matching the given predicate, occurring after the given instruction.
*
* @param insn The instruction to search after.
* @param predicate The predicate to match.
* @param dist The maximum distance to search.
* @return The first occurrence of an instruction matching the given predicate, occurring after the given instruction.
*/
@SuppressWarnings("unchecked")
public static <E extends AbstractInsnNode> E findNext(AbstractInsnNode insn, Predicate<AbstractInsnNode> predicate,
int dist) {
int jump = 0;
while ((insn = insn.getNext()) != null && (dist == -1 || jump++ < dist)) {
if (predicate.test(insn)) {
return (E) insn;
}
}
return null;
}
/**
* Finds The first occurrence of an instruction matching the given predicate, occurring after the given instruction.
*
* @param insn The instruction to search after.
* @param predicate The predicate to match.
* @return The first occurrence of an instruction matching the given predicate, occurring after the given instruction.
*/
public static <E extends AbstractInsnNode> E findNext(AbstractInsnNode insn, Predicate<AbstractInsnNode> predicate) {
return findNext(insn, predicate, -1);
}
/**
* Finds The first occurrence of an instruction matching the given predicate, occurring before the given instruction.
*
* @param insn The instruction to search after.
* @param predicate The predicate to match.
* @param dist The maximum distance to search.
* @return The first occurrence of an instruction matching the given predicate, occurring before the given instruction.
*/
@SuppressWarnings("unchecked")
public static <E extends AbstractInsnNode> E findPrevious(AbstractInsnNode insn,
Predicate<AbstractInsnNode> predicate, int dist) {
int jump = 0;
while ((insn = insn.getPrevious()) != null && (dist == -1 || jump++ < dist)) {
if (predicate.test(insn)) {
return (E) insn;
}
}
return null;
}
/**
* Finds The first occurrence of an instruction matching the given predicate, occurring before the given instruction.
*
* @param insn The instruction to search after.
* @param predicate The predicate to match.
* @return The first occurrence of an instruction matching the given predicate, occurring before the given instruction.
*/
public static <E extends AbstractInsnNode> E findPrevious(AbstractInsnNode insn,
Predicate<AbstractInsnNode> predicate) {
return findPrevious(insn, predicate, -1);
}
/**
* Gets the name of the given opcode.
*
* @param opcode The opcode.
* @return The name of the given opcode.
*/
public static String opname(int opcode) {
if (opcode >= 0 && opcode < Printer.OPCODES.length) {
return Printer.OPCODES[opcode];
}
return Integer.toString(opcode);
}
/**
* Renames the given field throughout the ClassFactory map with to given name.
*
* @param classes The map of classes to rename within.
* @param fn The field to rename.
* @param newName The name to rename the field to.
*/
public static void rename(Map<String, ClassFactory> classes, ClassField fn, String newName) {
for (ClassFactory factory : classes.values()) {
for (ClassMethod method : factory.methods) {
for (AbstractInsnNode ain : method.instructions().toArray()) {
if (ain instanceof FieldInsnNode) {
FieldInsnNode fin = (FieldInsnNode) ain;
ClassFactory realOwner = classes.get(fin.owner);
while (realOwner != null) {
if (realOwner.findField(cf -> cf.name().equals(fin.name)) != null) {
break;
}
realOwner = classes.get(realOwner.superName());
}
if (realOwner != null && realOwner.name().equals(fn.owner.name()) &&
fin.name.equals(fn.field.name)) {
fin.name = newName;
}
}
}
}
}
fn.field.name = newName;
}
/**
* Renames the given class throughout the ClassFactory map with to given name.
*
* @param classes The map of classes to rename within.
* @param cf The class to rename.
* @param newName The name to rename the class to.
*/
public static void rename(Map<String, ClassFactory> classes, ClassFactory cf, String newName) {
for (ClassFactory factory : classes.values()) {
if (factory.superName().equals(cf.name())) {
factory.setSuperName(newName);
}
if (factory.interfaces().contains(cf.name())) {
factory.interfaces().remove(cf.name());
factory.interfaces().add(newName);
}
for (ClassField field : factory.fields) {
if (field.desc().endsWith("L" + cf.name() + ";")) {
field.setDescriptor(field.desc().replace("L" + cf.name() + ";", "L" + newName + ";"));
}
}
for (ClassMethod method : factory.methods) {
if (method.desc().contains("L" + cf.name() + ";")) {
method.setDescriptor(method.desc().replaceAll("L" + cf.name() + ";", "L" + newName + ";"));
}
for (AbstractInsnNode ain : method.instructions().toArray()) {
if (ain instanceof FieldInsnNode) {
FieldInsnNode fin = (FieldInsnNode) ain;
if (fin.owner.equals(cf.name())) {
fin.owner = newName;
}
if (fin.desc.contains("L" + cf.name() + ";")) {
fin.desc = fin.desc.replace("L" + cf.name() + ";", "L" + newName + ";");
}
} else if (ain instanceof MethodInsnNode) {
MethodInsnNode min = (MethodInsnNode) ain;
if (min.owner.equals(cf.name())) {
min.owner = newName;
}
if (min.desc.contains("L" + cf.name() + ";")) {
min.desc = min.desc.replaceAll("L" + cf.name() + ";", "L" + newName + ";");
}
} else if (ain instanceof TypeInsnNode) {
TypeInsnNode tin = (TypeInsnNode) ain;
if (tin.desc.equals(cf.name())) {
tin.desc = newName;
} else if (tin.desc.contains("L" + cf.name() + ";")) {
tin.desc = tin.desc.replace("L" + cf.name() + ";", "L" + newName + ";");
}
} else if (ain instanceof MultiANewArrayInsnNode) {
MultiANewArrayInsnNode manain = (MultiANewArrayInsnNode) ain;
if (manain.desc.contains("L" + cf.name() + ";")) {
manain.desc = manain.desc.replace("L" + cf.name() + ";", "L" + newName + ";");
}
} else if (ain instanceof LdcInsnNode) {
LdcInsnNode ldc = (LdcInsnNode) ain;
Object cst = ldc.cst;
if (cst != null && cst instanceof String) {
String cstString = (String) cst;
if (cstString.startsWith(cf.name() + ".") && cstString.contains("(")) {
ldc.cst = cstString.replace(cf.name() + ".", newName + ".");
}
}
}
}
}
}
cf.setName(newName);
}
/**
* Checks whether the given instructions are similar to each other.
*
* @param insn1 The first instruction to compare.
* @param insn2 The second instruction to compare.
* @return <t>true</t> if the instructions are similar, otherwise <t>false</t>.
*/
public static boolean instructionsEqual(AbstractInsnNode insn1, AbstractInsnNode insn2) {
if (insn1 == insn2) {
return true;
}
if (insn1 == null || insn2 == null) {
return false;
}
if (insn1.getType() != insn2.getType() || insn1.getOpcode() != insn2.getOpcode()) {
return false;
}
int size;
switch (insn1.getType()) {
case INSN: {
return true;
}
case INT_INSN: {
IntInsnNode iin1 = (IntInsnNode) insn1, iin2 = (IntInsnNode) insn2;
return iin1.operand == iin2.operand;
}
case VAR_INSN: {
VarInsnNode vin1 = (VarInsnNode) insn1, vin2 = (VarInsnNode) insn2;
return vin1.var == vin2.var;
}
case TYPE_INSN: {
TypeInsnNode tin1 = (TypeInsnNode) insn1, tin2 = (TypeInsnNode) insn2;
return tin1.desc.equals(tin2.desc);
}
case FIELD_INSN: {
FieldInsnNode fin1 = (FieldInsnNode) insn1, fin2 = (FieldInsnNode) insn2;
return fin1.desc.equals(fin2.desc) && fin1.name.equals(fin2.name) && fin1.owner.equals(fin2.owner);
}
case METHOD_INSN: {
MethodInsnNode min1 = (MethodInsnNode) insn1, min2 = (MethodInsnNode) insn2;
return min1.desc.equals(min2.desc) && min1.name.equals(min2.name) && min1.owner.equals(min2.owner);
}
case INVOKE_DYNAMIC_INSN: {
InvokeDynamicInsnNode idin1 = (InvokeDynamicInsnNode) insn1, idin2 = (InvokeDynamicInsnNode) insn2;
return idin1.bsm.equals(idin2.bsm) && Arrays.equals(idin1.bsmArgs, idin2.bsmArgs) &&
idin1.desc.equals(idin2.desc) && idin1.name.equals(idin2.name);
}
case JUMP_INSN: {
JumpInsnNode jin1 = (JumpInsnNode) insn1, jin2 = (JumpInsnNode) insn2;
return instructionsEqual(jin1.label, jin2.label);
}
case LABEL: {
Label label1 = ((LabelNode) insn1).getLabel(), label2 = ((LabelNode) insn2).getLabel();
return label1 == null ? label2 == null : label1.info == null ? label2.info == null :
label1.info.equals(label2.info);
}
case LDC_INSN: {
LdcInsnNode lin1 = (LdcInsnNode) insn1, lin2 = (LdcInsnNode) insn2;
return lin1.cst.equals(lin2.cst);
}
case IINC_INSN: {
IincInsnNode iiin1 = (IincInsnNode) insn1, iiin2 = (IincInsnNode) insn2;
return iiin1.incr == iiin2.incr && iiin1.var == iiin2.var;
}
case TABLESWITCH_INSN: {
TableSwitchInsnNode tsin1 = (TableSwitchInsnNode) insn1, tsin2 = (TableSwitchInsnNode) insn2;
size = tsin1.labels.size();
if (size != tsin2.labels.size()) {
return false;
}
for (int i = 0; i < size; i++) {
if (!instructionsEqual((LabelNode) tsin1.labels.get(i), (LabelNode) tsin2.labels.get(i))) {
return false;
}
}
return instructionsEqual(tsin1.dflt, tsin2.dflt) && tsin1.max == tsin2.max && tsin1.min == tsin2.min;
}
case LOOKUPSWITCH_INSN: {
LookupSwitchInsnNode lsin1 = (LookupSwitchInsnNode) insn1, lsin2 = (LookupSwitchInsnNode) insn2;
size = lsin1.labels.size();
if (size != lsin2.labels.size()) {
return false;
}
for (int i = 0; i < size; i++) {
if (!instructionsEqual((LabelNode) lsin1.labels.get(i), (LabelNode) lsin2.labels.get(i))) {
return false;
}
}
return instructionsEqual(lsin1.dflt, lsin2.dflt) && lsin1.keys.equals(lsin2.keys);
}
case MULTIANEWARRAY_INSN: {
MultiANewArrayInsnNode manain1 = (MultiANewArrayInsnNode) insn1, manain2 = (MultiANewArrayInsnNode) insn2;
return manain1.desc.equals(manain2.desc) && manain1.dims == manain2.dims;
}
case FRAME: {
FrameNode fn1 = (FrameNode) insn1, fn2 = (FrameNode) insn2;
return fn1.local.equals(fn2.local) && fn1.stack.equals(fn2.stack);
}
case LINE: {
LineNumberNode lnn1 = (LineNumberNode) insn1, lnn2 = (LineNumberNode) insn2;
return lnn1.line == lnn2.line && instructionsEqual(lnn1.start, lnn2.start);
}
}
return false;
}
/**
* Checks whether the given instruction arrays are similar.
*
* @param insns The first instruction array to compare.
* @param insns2 The second instruction array to compare.
* @return <t>true</t> if the given instruction arrays are similar, otherwise <t>false</t>.
*/
public static boolean instructionsEqual(AbstractInsnNode[] insns, AbstractInsnNode[] insns2) {
if (insns == insns2) {
return true;
}
if (insns == null || insns2 == null) {
return false;
}
int length = insns.length;
if (insns2.length != length) {
return false;
}
for (int i = 0; i < length; i++) {
AbstractInsnNode insn1 = insns[i], insn2 = insns2[i];
if (!(insn1 == null ? insn2 == null : instructionsEqual(insn1, insn2))) {
return false;
}
}
return true;
}
/**
* Gives a string representation of the given instruction.
*
* @param insn The instruction to represent.
* @return A string representation of the given instruction.
*/
public static String toString(AbstractInsnNode insn) {
if (insn == null) {
return "null";
}
int op = insn.getOpcode();
if (op == -1) {
if (insn instanceof LabelNode) {
return (insn.getClass().getSimpleName() + insn.toString().split(insn.getClass().getSimpleName())[1]);
}
return insn.toString();
}
StringBuilder builder = new StringBuilder();
builder.append(Printer.OPCODES[op]);
switch (insn.getType()) {
case INT_INSN: {
builder.append(' ');
builder.append(((IntInsnNode) insn).operand);
break;
}
case VAR_INSN: {
builder.append(' ');
builder.append('
builder.append(((VarInsnNode) insn).var);
break;
}
case TYPE_INSN: {
builder.append(' ');
builder.append(((TypeInsnNode) insn).desc);
break;
}
case FIELD_INSN: {
FieldInsnNode fin = (FieldInsnNode) insn;
builder.append(' ');
builder.append(fin.owner);
builder.append('.');
builder.append(fin.name);
builder.append(' ');
builder.append(fin.desc);
break;
}
case METHOD_INSN: {
MethodInsnNode min = (MethodInsnNode) insn;
builder.append(' ');
builder.append(min.owner);
builder.append('.');
builder.append(min.name);
builder.append(' ');
builder.append(min.desc);
break;
}
case JUMP_INSN:
case TABLESWITCH_INSN:
case LOOKUPSWITCH_INSN: {
break;
}
case LDC_INSN: {
Object cst = ((LdcInsnNode) insn).cst;
builder.append(' ');
builder.append(cst.getClass().getName());
builder.append(' ');
builder.append(cst);
break;
}
case IINC_INSN: {
IincInsnNode iin = (IincInsnNode) insn;
builder.append(' ');
builder.append('
builder.append(iin.var);
builder.append(' ');
builder.append(iin.incr);
break;
}
case MULTIANEWARRAY_INSN: {
MultiANewArrayInsnNode m = (MultiANewArrayInsnNode) insn;
builder.append(' ');
builder.append(m.desc);
builder.append(' ');
builder.append(m.dims);
break;
}
}
return builder.toString();
}
} |
package org.xwiki.url.internal;
import javax.inject.Inject;
import javax.inject.Named;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.util.DefaultParameterizedType;
import org.xwiki.resource.ResourceReference;
import org.xwiki.resource.ResourceReferenceSerializer;
import org.xwiki.resource.SerializeResourceReferenceException;
import org.xwiki.resource.UnsupportedResourceReferenceException;
import org.xwiki.url.ExtendedURL;
/**
* Helper class to implement a Serializer to transform a XWiki Resource into a {@link ExtendedURL} object.
*
* @version $Id$
* @since 7.2M1
*/
public abstract class AbstractExtendedURLResourceReferenceSerializer
implements ResourceReferenceSerializer<ResourceReference, ExtendedURL>
{
@Inject
@Named("context")
private ComponentManager componentManager;
/**
* Transforms a Resource Reference into some other representation.
*
* @param reference the Resource Reference to transform
* @param formatId the id of the URL format to use (e.g. "standard", "reference", etc)
* @return the new representation
* @throws SerializeResourceReferenceException if there was an error while serializing the XWiki Resource object
* @throws UnsupportedResourceReferenceException if the passed representation points to an unsupported Resource
* Reference type that we don't know how to serialize
*/
public ExtendedURL serialize(ResourceReference reference, String formatId)
throws SerializeResourceReferenceException, UnsupportedResourceReferenceException
{
// Step 1: Try to locate a Serializer registered for the specific passed resource type and for the passed URL
// format id
ResourceReferenceSerializer<ResourceReference, ExtendedURL> serializer;
try {
serializer = this.componentManager.getInstance(new DefaultParameterizedType(null,
ResourceReferenceSerializer.class, reference.getClass(), ExtendedURL.class), formatId);
} catch (ComponentLookupException e) {
// Step 2: Try to locate a Serializer registered only for the specific passed resource type and for all URL
// format ids
try {
serializer = this.componentManager.getInstance(new DefaultParameterizedType(null,
ResourceReferenceSerializer.class, reference.getClass(), ExtendedURL.class));
} catch (ComponentLookupException cle) {
throw new UnsupportedResourceReferenceException(String.format(
"Failed to find serializer for Resource Reference [%s] and URL format [%s]", reference, formatId),
cle);
}
}
return serializer.serialize(reference);
}
} |
package io.luna.net;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.gson.JsonObject;
import com.moandjiezana.toml.Toml;
import io.luna.net.session.Session;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import io.netty.util.ResourceLeakDetector.Level;
import java.io.File;
import java.math.BigInteger;
public final class LunaNetworkConstants {
static {
try {
JsonObject reader = new Toml().read(new File("./data/luna.toml")).getTable("settings").to(JsonObject.class);
PORT = reader.get("port").getAsInt();
RSA_MODULUS = new BigInteger(reader.get("rsa_modulus").getAsString());
RSA_EXPONENT = new BigInteger(reader.get("rsa_exponent").getAsString());
RESOURCE_LEAK_DETECTION = Level.valueOf(reader.get("resource_leak_detection_level").getAsString());
CONNECTION_LIMIT = reader.get("connection_threshold").getAsInt();
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* The resource leak detection level, should be {@code PARANOID} in a development environment and {@code DISABLED} in a
* production environment.
*/
public static final Level RESOURCE_LEAK_DETECTION;
/**
* The port that the server will be bound on.
*/
public static final int PORT;
/**
* The public RSA exponent value.
*/
public static final BigInteger RSA_MODULUS;
/**
* The private RSA exponent value.
*/
public static final BigInteger RSA_EXPONENT;
/**
* The maximum amount of connections allowed per channel.
*/
public static final int CONNECTION_LIMIT;
/**
* The amount of {@code SECONDS} that must elapse for a channel to be disconnected after no read operations.
*/
public static final int READ_IDLE_SECONDS = 5;
/**
* The maximum amount of incoming messages per cycle.
*/
public static final int MESSAGE_LIMIT = 15;
/**
* The preferred ports for the user to use, a log message will be printed if none of these ports are used.
*/
public static final ImmutableSet<Integer> PREFERRED_PORTS = ImmutableSet.of(43594, 5555);
/**
* A list of exceptions that are ignored when received from Netty.
*/
public static final ImmutableList<String> IGNORED_EXCEPTIONS = ImmutableList
.of("An existing connection was forcibly closed by the remote host",
"An established connection was aborted by the software in your host machine");
/**
* An {@link AttributeKey} that is used to retrieve the session instance from the attribute map of a {@link Channel}.
*/
public static final AttributeKey<Session> SESSION_KEY = AttributeKey.valueOf("session.KEY");
/**
* A private constructor to discourage external instantiation.
*/
private LunaNetworkConstants() {
}
} |
package cz.cuni.mff.d3s.spl.core.data;
import java.util.Collection;
public class PrecomputedStatistics implements Statistics {
private double mean = 0.0;
private long count = 0;
public static final PrecomputedStatistics empty = PrecomputedStatistics.create(Double.NaN, 0);
public static PrecomputedStatistics create(Collection<Long> samples) {
PrecomputedStatistics result = new PrecomputedStatistics();
result.mean = getSampleMean(samples);
result.count = samples.size();
return result;
}
public static PrecomputedStatistics create(double mean, long count) {
PrecomputedStatistics result = new PrecomputedStatistics();
result.mean = mean;
result.count = count;
return result;
}
@Override
public double getArithmeticMean() {
return mean;
}
@Override
public long getSampleCount() {
return count;
}
@Override
public String toString() {
return String.format("Statistics(size=%d, mean=%2.2f)",
count, mean);
}
/**
* Compute arithmetic mean from given list.
*
* @param samples
* List of samples.
* @return Arithmetic mean.
* @retval 0 When list is empty.
*/
protected static double getSampleMean(Collection<Long> samples) {
if (samples.size() == 0) {
return Double.NaN;
}
double sum = 0.0;
for (Long l : samples) {
sum += (double) l;
}
return sum / (double) samples.size();
}
} |
package jfdi.storage.data;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Objects;
import java.util.TreeSet;
import jfdi.storage.Constants;
import jfdi.storage.exceptions.InvalidIdException;
import jfdi.storage.exceptions.InvalidTaskParametersException;
import jfdi.storage.exceptions.NoAttributesChangedException;
public class TaskAttributes {
private Integer id = null;
private String description = null;
private LocalDateTime startDateTime = null;
private LocalDateTime endDateTime = null;
private HashSet<String> tags = new HashSet<String>();
private TreeSet<Duration> reminders = new TreeSet<Duration>();
private boolean isCompleted = false;
public TaskAttributes() {
}
@SuppressWarnings("unchecked")
public TaskAttributes(Task task) {
this.id = task.getId();
this.description = task.getDescription();
this.startDateTime = task.getStartDateTime();
this.endDateTime = task.getEndDateTime();
this.isCompleted = task.isCompleted();
if (task.getTags() instanceof HashSet<?>) {
this.tags = (HashSet<String>) task.getTags().clone();
}
if (task.getReminders() instanceof TreeSet<?>) {
this.reminders = (TreeSet<Duration>) task.getReminders().clone();
}
}
public Integer getId() {
return id;
}
/**
* This method should only be used internally by the database/test.
*
* @param id
* the id of the task
*/
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(LocalDateTime startDateTime) {
this.startDateTime = startDateTime;
}
public LocalDateTime getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(LocalDateTime endDateTime) {
this.endDateTime = endDateTime;
}
public HashSet<String> getTags() {
return tags;
}
public void setTags(String... tags) {
this.tags = new HashSet<String>();
for (String tag : tags) {
assert tag != null;
this.tags.add(tag);
}
}
public boolean addTag(String tag) {
HashSet<String> tags = this.getTags();
return tags.add(tag);
}
public boolean removeTag(String tag) {
HashSet<String> tags = this.getTags();
return tags.remove(tag);
}
public boolean hasTag(String tag) {
HashSet<String> tags = this.getTags();
return tags.contains(tag);
}
public TreeSet<Duration> getReminders() {
return reminders;
}
public void setReminders(Duration... reminders) {
this.reminders = new TreeSet<Duration>();
for (Duration reminder : reminders) {
assert reminder != null;
this.reminders.add(reminder);
}
}
public boolean addReminder(Duration reminder) {
TreeSet<Duration> reminders = this.getReminders();
return reminders.add(reminder);
}
public boolean isCompleted() {
return isCompleted;
}
public void setCompleted(boolean isCompleted) {
this.isCompleted = isCompleted;
}
/**
* This method saves the attributes object into a data store object in the
* database. The attributes are first validated before the data store object
* is either created or updated.
*
* @throws InvalidTaskParametersException
* if the attributes object contains an invalid attribute (e.g.
* missing description)
* @throws NoAttributesChangedException
* if the save operation does not change the data store object
* in any way
* @throws InvalidIdException
* if the ID stored in the attributes object is invalid (e.g.
* null or does not exist)
*/
public void save() throws InvalidTaskParametersException, NoAttributesChangedException,
InvalidIdException {
validateAttributes();
TaskDb.createOrUpdate(this);
}
public Task toEntity() {
return new Task(id, description, startDateTime, endDateTime, tags, reminders);
}
private void validateAttributes() throws InvalidTaskParametersException {
if (description == null) {
throw new InvalidTaskParametersException(Constants.MESSAGE_MISSING_DESCRIPTION);
}
}
public boolean equalTo(Task task) {
return Objects.equals(this.id, task.getId())
&& Objects.equals(this.description, task.getDescription())
&& Objects.equals(this.startDateTime, task.getStartDateTime())
&& Objects.equals(this.endDateTime, task.getEndDateTime())
&& Objects.equals(this.tags, task.getTags())
&& Objects.equals(this.reminders, task.getReminders())
&& this.isCompleted == task.isCompleted();
}
} |
package jiconfont.swing;
import jiconfont.IconBuilder;
import jiconfont.IconCode;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class IconBuilderSwing
extends IconBuilder<IconBuilderSwing, Color, Float> {
public static IconBuilderSwing newIcon(IconCode icon) {
return new IconBuilderSwing(icon);
}
protected IconBuilderSwing(IconCode icon) {
super(icon);
setColor(Color.BLACK);
}
public final IconBuilderSwing setSize(int size) {
return setSize((float) size);
}
public final Icon buildIcon() {
return new ImageIcon(buildImage());
}
public final Image buildImage() {
return buildImage(Character.toString(getIcon().getUnicode()));
}
private BufferedImage buildImage(String text) {
Font font = buildFont();
JLabel label = new JLabel(text);
label.setFont(font);
Dimension dim = label.getPreferredSize();
label.setSize(dim);
int width = dim.width;
int height = dim.height;
BufferedImage bufImage =
new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bufImage.createGraphics();
label.print(g2d);
g2d.dispose();
bufImage.getWidth();
return bufImage;
}
protected final Font buildFont() {
try {
Font font =
Font.createFont(Font.TRUETYPE_FONT, getIcon().getFontInputStream());
return font.deriveFont(getSize());
}
catch (Exception ex) {
Logger.getLogger(IconBuilderSwing.class.getName()).log(Level.SEVERE,
"Font load failure", ex);
}
return null;
}
@Override
protected Class<IconBuilderSwing> getIconFontClass() {
return IconBuilderSwing.class;
}
} |
package lan.dk.podcastserver.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hibernate.annotations.Type;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.springframework.web.util.UriComponentsBuilder;
import javax.persistence.*;
import javax.validation.constraints.AssertTrue;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.ZonedDateTime;
@Table(name = "item")
@Entity
@Indexed
@JsonIgnoreProperties(ignoreUnknown = true)
public class Item implements Serializable {
public static Path rootFolder;
public static String fileContainer;
private static final String STATUS_NOT_DOWNLOADED = "Not Downloaded";
private static final String PROXY_URL = "/api/podcast/%s/items/%s/download";
private Integer id;
private String title;
private String url;
private Podcast podcast;
private ZonedDateTime pubdate;
private String description;
private String mimeType;
private Long length;
private Cover cover;
private String fileName;
/* Value for the Download */
private String status = STATUS_NOT_DOWNLOADED;
private Integer progression = 0;
private ZonedDateTime downloadDate;
private Integer numberOfTry = 0;
public Item() {
}
@Id
@DocumentId
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
public Integer getId() {
return id;
}
public Item setId(Integer id) {
this.id = id;
return this;
}
@Basic @Column(name = "mimetype")
public String getMimeType() {
return mimeType;
}
public Item setMimeType(String mimeType) {
this.mimeType = mimeType;
return this;
}
@Basic @Column(name = "length")
public Long getLength() {
return length;
}
public Item setLength(Long length) {
this.length = length;
return this;
}
@Basic @Field @Column(name = "title")
public String getTitle() {
return title;
}
public Item setTitle(String title) {
this.title = title;
return this;
}
@Basic @Column(name = "url", length = 65535, unique = true)
public String getUrl() {
return url;
}
public Item setUrl(String url) {
this.url = url;
return this;
}
@Column(name = "pubdate")
@Type(type = "org.jadira.usertype.dateandtime.threeten.PersistentZonedDateTime")
public ZonedDateTime getPubdate() {
return pubdate;
}
public Item setPubdate(ZonedDateTime pubdate) {
this.pubdate = pubdate;
return this;
}
@ManyToOne(cascade={CascadeType.MERGE}, fetch = FetchType.EAGER)
@JoinColumn(name = "podcast_id", referencedColumnName = "id")
@JsonBackReference("podcast-item")
public Podcast getPodcast() {
return podcast;
}
public Item setPodcast(Podcast podcast) {
this.podcast = podcast;
return this;
}
@Basic
@Column(name = "status")
public String getStatus() {
return status;
}
public Item setStatus(String status) {
this.status = status;
return this;
}
@Basic
public String getFileName() {
return fileName;
}
public Item setFileName(String fileName) {
this.fileName = fileName;
return this;
}
@Transient
public Integer getProgression() {
return progression;
}
public Item setProgression(Integer progression) {
this.progression = progression;
return this;
}
@OneToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="cover_id")
public Cover getCover() {
return this.cover;
}
public Item setCover(Cover cover) {
this.cover = cover;
return this;
}
@Column(name = "downloadddate")
@Type(type = "org.jadira.usertype.dateandtime.threeten.PersistentZonedDateTime")
public ZonedDateTime getDownloadDate() {
return downloadDate;
}
public Item setDownloadDate(ZonedDateTime downloaddate) {
this.downloadDate = downloaddate;
return this;
}
@Column(name = "description", length = 65535)
@Basic @Field
public String getDescription() {
return description;
}
public Item setDescription(String description) {
this.description = description;
return this;
}
@Transient @JsonIgnore
public String getLocalUri() {
return (fileName == null) ? null : getLocalPath().toString();
}
public Item setLocalUri(String localUri) {
fileName = FilenameUtils.getName(localUri);
return this;
}
@JsonIgnore
@Transient
public Integer getNumberOfTry() {
return numberOfTry;
}
@JsonIgnore
@Transient
public Item setNumberOfTry(Integer numberOfTry) {
this.numberOfTry = numberOfTry;
return this;
}
@JsonIgnore
@Transient
public Item addATry() {
this.numberOfTry++;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Item)) return false;
Item item = (Item) o;
if (id != null && item.id != null)
return id.equals(item.id);
if (url != null && item.url != null) {
return url.equals(item.url) || FilenameUtils.getName(item.url).equals(FilenameUtils.getName(url));
}
return StringUtils.equals(getLocalUrl(), item.getLocalUrl());
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(url)
.append((pubdate != null) ? pubdate.toInstant() : null)
.toHashCode();
}
@Override
public String toString() {
return "Item{" +
"id=" + id +
", title='" + title + '\'' +
", url='" + url + '\'' +
", pubdate=" + pubdate +
", description='" + description + '\'' +
", mimeType='" + mimeType + '\'' +
", length=" + length +
", cover=" + cover +
", status='" + status + '\'' +
", progression=" + progression +
", downloaddate=" + downloadDate +
", podcast=" + podcast +
", numberOfTry=" + numberOfTry +
'}';
}
/* Helpers */
@Transient
public String getLocalUrl() {
return (fileName == null) ? null : UriComponentsBuilder.fromHttpUrl(fileContainer)
.pathSegment(podcast.getTitle())
.pathSegment(fileName)
.build()
.toString();
}
@Transient @JsonProperty("proxyURL")
public String getProxyURL() {
return String.format(PROXY_URL, podcast.getId(), id);
}
@Transient @JsonProperty("isDownloaded")
public Boolean isDownloaded() {
return StringUtils.isNotEmpty(fileName);
}
//* CallBack Method JPA *//
@PreRemove
public void preRemove() {
if (podcast.getHasToBeDeleted() && isDownloaded()) {
try {
Files.deleteIfExists(getLocalPath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Transient @JsonIgnore
public Path getLocalPath() {
return rootFolder.resolve(podcast.getTitle()).resolve(fileName);
}
@Transient @JsonProperty("cover")
public Cover getCoverOfItemOrPodcast() {
return (this.cover == null) ? podcast.getCover() : this.cover;
}
@Transient @JsonProperty("podcastId")
public Integer getPodcastId() { return (podcast == null) ? null : podcast.getId();}
@Transient @JsonIgnore @AssertTrue
public boolean hasValidURL() {
return (!StringUtils.isEmpty(this.url)) || "send".equals(this.podcast.getType());
}
@Transient @JsonIgnore
public Item reset() {
preRemove();
setStatus(STATUS_NOT_DOWNLOADED);
downloadDate = null;
fileName = null;
return this;
}
} |
package lou.arane.util;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
/**
* Log to either System.err or System.out depending on log level.
* <p>
* NOTE: This handler does not read config from LogManager like ConsoleHandler.
* The rest of the code is similar to ConsoleHandler though.
*
* @author Phuc
*/
public class LogConsoleHandler extends Handler {
private final StreamHandler out;
private final StreamHandler err;
public LogConsoleHandler(Level level) {
out = new StreamHandler(System.out, new SimpleFormatter());
err = new StreamHandler(System.err, new SimpleFormatter());
setLevel(level);
}
@Override
public final void setLevel(Level level) {
super.setLevel(level);
out.setLevel(level);
err.setLevel(level);
}
/**
* Publish logs whose level >= WARNING to System.err and the rest to
* System.out
*/
@Override
public final void publish(LogRecord record) {
if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
err.publish(record);
}
else {
out.publish(record);
}
/* flush since for console we need to see the complete record right away */
flush();
}
/**
* Flush any published (buffered) records to console
*/
@Override
public final void flush() {
out.flush();
err.flush();
}
/**
* Flush, not close, since we do not close System.out and System.err
*/
@Override
public final void close() throws SecurityException {
flush();
}
} |
package org.innovateuk.ifs.management.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.application.resource.ApplicationSummaryPageResource;
import org.innovateuk.ifs.application.resource.ApplicationSummaryResource;
import org.innovateuk.ifs.application.resource.CompetitionSummaryResource;
import org.innovateuk.ifs.management.model.AllApplicationsPageModelPopulator;
import org.innovateuk.ifs.management.model.ApplicationsMenuModelPopulator;
import org.innovateuk.ifs.management.model.IneligibleApplicationsModelPopulator;
import org.innovateuk.ifs.management.model.SubmittedApplicationsModelPopulator;
import org.innovateuk.ifs.management.viewmodel.*;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.test.web.servlet.MvcResult;
import java.math.BigDecimal;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Optional.empty;
import static org.innovateuk.ifs.application.builder.ApplicationSummaryResourceBuilder.newApplicationSummaryResource;
import static org.innovateuk.ifs.application.builder.CompetitionSummaryResourceBuilder.newCompetitionSummaryResource;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.user.builder.RoleResourceBuilder.newRoleResource;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class CompetitionManagementApplicationsControllerTest extends BaseControllerMockMVCTest<CompetitionManagementApplicationsController> {
private long COMPETITION_ID = 1L;
private CompetitionSummaryResource defaultExpectedCompetitionSummary;
@InjectMocks
@Spy
private ApplicationsMenuModelPopulator applicationsMenuModelPopulator;
@InjectMocks
@Spy
private AllApplicationsPageModelPopulator allApplicationsPageModelPopulator;
@InjectMocks
@Spy
private SubmittedApplicationsModelPopulator submittedApplicationsModelPopulator;
@InjectMocks
@Spy
private IneligibleApplicationsModelPopulator ineligibleApplicationsModelPopulator;
@Override
protected CompetitionManagementApplicationsController supplyControllerUnderTest() {
return new CompetitionManagementApplicationsController();
}
@Before
public void setDefaults() {
defaultExpectedCompetitionSummary = newCompetitionSummaryResource()
.withId(COMPETITION_ID)
.withCompetitionName("Test Competition")
.withApplicationsInProgress(10)
.withApplicationsSubmitted(20)
.withIneligibleApplications(5)
.withAssesorsInvited(30)
.build();
}
@Test
public void applicationsMenu() throws Exception {
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID)).thenReturn(restSuccess(defaultExpectedCompetitionSummary));
MvcResult result = mockMvc.perform(get("/competition/{competitionId}/applications", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/applications-menu"))
.andReturn();
ApplicationsMenuViewModel model = (ApplicationsMenuViewModel) result.getModelAndView().getModel().get("model");
verify(applicationSummaryRestService, only()).getCompetitionSummary(COMPETITION_ID);
assertEquals(COMPETITION_ID, model.getCompetitionId());
assertEquals(defaultExpectedCompetitionSummary.getCompetitionName(), model.getCompetitionName());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsInProgress(), model.getApplicationsInProgress());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsSubmitted(), model.getApplicationsSubmitted());
assertEquals(defaultExpectedCompetitionSummary.getIneligibleApplications(), model.getIneligibleApplications());
assertEquals(defaultExpectedCompetitionSummary.getAssessorsInvited(), model.getAssessorsInvited());
}
@Test
public void allApplications() throws Exception {
Long[] ids = {1L, 2L, 3L};
String[] titles = {"Title 1", "Title 2", "Title 3"};
String[] leads = {"Lead 1", "Lead 2", "Lead 3"};
String[] innovationAreas = {"Innovation Area 1", "Innovation Area 1", "Innovation Area 1"};
String[] statuses = {"Submitted", "Started", "Started"};
Integer[] percentages = {100, 70, 20};
List<AllApplicationsRowViewModel> expectedApplicationRows = asList(
new AllApplicationsRowViewModel(ids[0], titles[0], leads[0], innovationAreas[0], statuses[0], percentages[0]),
new AllApplicationsRowViewModel(ids[1], titles[1], leads[1], innovationAreas[1], statuses[1], percentages[1]),
new AllApplicationsRowViewModel(ids[2], titles[2], leads[2], innovationAreas[2], statuses[2], percentages[2])
);
List<ApplicationSummaryResource> expectedSummaries = newApplicationSummaryResource()
.withId(ids)
.withName(titles)
.withLead(leads)
.withInnovationArea(innovationAreas)
.withStatus(statuses)
.withCompletedPercentage(percentages)
.build(3);
ApplicationSummaryPageResource expectedSummaryPageResource = new ApplicationSummaryPageResource();
expectedSummaryPageResource.setContent(expectedSummaries);
when(applicationSummaryRestService.getAllApplications(COMPETITION_ID, "", 0, 20, ""))
.thenReturn(restSuccess(expectedSummaryPageResource));
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID))
.thenReturn(restSuccess(defaultExpectedCompetitionSummary));
MvcResult result = mockMvc.perform(get("/competition/{competitionId}/applications/all", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/all-applications"))
.andExpect(model().attribute("originQuery", "?origin=ALL_APPLICATIONS"))
.andReturn();
AllApplicationsViewModel model = (AllApplicationsViewModel) result.getModelAndView().getModel().get("model");
verify(applicationSummaryRestService).getAllApplications(COMPETITION_ID, "", 0, 20, "");
verify(applicationSummaryRestService).getCompetitionSummary(COMPETITION_ID);
assertEquals(COMPETITION_ID, model.getCompetitionId());
assertEquals(defaultExpectedCompetitionSummary.getCompetitionName(), model.getCompetitionName());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsInProgress(), model.getApplicationsInProgress());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsStarted(), model.getApplicationsStarted());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsSubmitted(), model.getApplicationsSubmitted());
assertEquals(defaultExpectedCompetitionSummary.getTotalNumberOfApplications(), model.getTotalNumberOfApplications());
assertEquals("Applications", model.getBackTitle());
assertEquals("/competition/" + COMPETITION_ID + "/applications", model.getBackURL());
assertEquals(expectedApplicationRows, model.getApplications());
}
@Test
public void allApplicationsPagedSortedFiltered() throws Exception {
Long[] ids = {1L, 2L, 3L};
String[] titles = {"Title 1", "Title 2", "Title 3"};
String[] leads = {"Lead 1", "Lead 2", "Lead 3"};
String[] innovationAreas = {"Innovation Area 1", "Innovation Area 1", "Innovation Area 1"};
String[] statuses = {"Submitted", "Started", "Started"};
Integer[] percentages = {100, 70, 20};
List<AllApplicationsRowViewModel> expectedApplicationRows = asList(
new AllApplicationsRowViewModel(ids[0], titles[0], leads[0], innovationAreas[0], statuses[0], percentages[0]),
new AllApplicationsRowViewModel(ids[1], titles[1], leads[1], innovationAreas[1], statuses[1], percentages[1]),
new AllApplicationsRowViewModel(ids[2], titles[2], leads[2], innovationAreas[2], statuses[2], percentages[2])
);
List<ApplicationSummaryResource> expectedSummaries = newApplicationSummaryResource()
.withId(ids)
.withName(titles)
.withLead(leads)
.withInnovationArea(innovationAreas)
.withStatus(statuses)
.withCompletedPercentage(percentages)
.build(3);
ApplicationSummaryPageResource expectedSummaryPageResource = new ApplicationSummaryPageResource(41, 3,expectedSummaries, 1, 20);
when(applicationSummaryRestService.getAllApplications(COMPETITION_ID, "id", 1, 20, "filter"))
.thenReturn(restSuccess(expectedSummaryPageResource));
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID))
.thenReturn(restSuccess(defaultExpectedCompetitionSummary));
MvcResult result = mockMvc.perform(get("/competition/{competitionId}/applications/all?page=1&sort=id&filterSearch=filter", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/all-applications"))
.andExpect(model().attribute("originQuery", "?origin=ALL_APPLICATIONS&page=1&sort=id&filterSearch=filter"))
.andReturn();
AllApplicationsViewModel model = (AllApplicationsViewModel) result.getModelAndView().getModel().get("model");
verify(applicationSummaryRestService).getAllApplications(COMPETITION_ID, "id", 1, 20, "filter");
verify(applicationSummaryRestService).getCompetitionSummary(COMPETITION_ID);
assertEquals(COMPETITION_ID, model.getCompetitionId());
assertEquals(defaultExpectedCompetitionSummary.getCompetitionName(), model.getCompetitionName());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsInProgress(), model.getApplicationsInProgress());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsStarted(), model.getApplicationsStarted());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsSubmitted(), model.getApplicationsSubmitted());
assertEquals(defaultExpectedCompetitionSummary.getTotalNumberOfApplications(), model.getTotalNumberOfApplications());
PaginationViewModel actualPagination = model.getPagination();
assertEquals(1,actualPagination.getCurrentPage());
assertEquals(20,actualPagination.getPageSize());
assertEquals(3, actualPagination.getTotalPages());
assertEquals("1 to 20", actualPagination.getPageNames().get(0).getTitle());
assertEquals("21 to 40", actualPagination.getPageNames().get(1).getTitle());
assertEquals("41 to 41", actualPagination.getPageNames().get(2).getTitle());
assertEquals("?origin=ALL_APPLICATIONS&sort=id&filterSearch=filter&page=2", actualPagination.getPageNames().get(2).getPath());
assertEquals(expectedApplicationRows, model.getApplications());
}
@Test
public void allApplications_preservesQueryParams() throws Exception {
ApplicationSummaryPageResource expectedSummaryPageResource = new ApplicationSummaryPageResource();
expectedSummaryPageResource.setContent(emptyList());
when(applicationSummaryRestService.getAllApplications(COMPETITION_ID, "", 0, 20, ""))
.thenReturn(restSuccess(expectedSummaryPageResource));
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID))
.thenReturn(restSuccess(defaultExpectedCompetitionSummary));
mockMvc.perform(get("/competition/{competitionId}/applications/all?param1=abc¶m2=def", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/all-applications"))
.andExpect(model().attribute("originQuery", "?origin=ALL_APPLICATIONS¶m1=abc¶m2=def"));
verify(applicationSummaryRestService).getAllApplications(COMPETITION_ID, "", 0, 20, "");
verify(applicationSummaryRestService).getCompetitionSummary(COMPETITION_ID);
}
@Test
public void submittedApplications() throws Exception {
Long[] ids = {1L, 2L, 3L};
String[] titles = {"Title 1", "Title 2", "Title 3"};
String[] leads = {"Lead 1", "Lead 2", "Lead 3"};
String[] innovationAreas = {"Innovation Area 1", "Innovation Area 1", "Innovation Area 1"};
Integer[] numberOfPartners = {5, 10, 12};
BigDecimal[] grantRequested = {BigDecimal.valueOf(1000), BigDecimal.valueOf(2000), BigDecimal.valueOf(3000)};
BigDecimal[] totalProjectCost = {BigDecimal.valueOf(5000), BigDecimal.valueOf(10000), BigDecimal.valueOf(15000)};
Long[] durations = {10L, 20L, 30L};
List<SubmittedApplicationsRowViewModel> expectedApplicationRows = asList(
new SubmittedApplicationsRowViewModel(ids[0], titles[0], leads[0], innovationAreas[0], numberOfPartners[0], grantRequested[0], totalProjectCost[0], durations[0]),
new SubmittedApplicationsRowViewModel(ids[1], titles[1], leads[1], innovationAreas[1], numberOfPartners[1], grantRequested[1], totalProjectCost[1], durations[1]),
new SubmittedApplicationsRowViewModel(ids[2], titles[2], leads[2], innovationAreas[2], numberOfPartners[2], grantRequested[2], totalProjectCost[2], durations[2])
);
List<ApplicationSummaryResource> expectedSummaries = newApplicationSummaryResource()
.withId(ids)
.withName(titles)
.withLead(leads)
.withInnovationArea(innovationAreas)
.withNumberOfPartners(numberOfPartners)
.withGrantRequested(grantRequested)
.withTotalProjectCost(totalProjectCost)
.withDuration(durations)
.build(3);
ApplicationSummaryPageResource expectedSummaryPageResource = new ApplicationSummaryPageResource();
expectedSummaryPageResource.setContent(expectedSummaries);
when(applicationSummaryRestService.getSubmittedApplications(COMPETITION_ID, "", 0, 20, "", empty()))
.thenReturn(restSuccess(expectedSummaryPageResource));
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID))
.thenReturn(restSuccess(defaultExpectedCompetitionSummary));
MvcResult result = mockMvc.perform(get("/competition/{competitionId}/applications/submitted", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/submitted-applications"))
.andExpect(model().attribute("originQuery", "?origin=SUBMITTED_APPLICATIONS"))
.andReturn();
SubmittedApplicationsViewModel model = (SubmittedApplicationsViewModel) result.getModelAndView().getModel().get("model");
verify(applicationSummaryRestService).getSubmittedApplications(COMPETITION_ID, "", 0, 20, "", empty());
verify(applicationSummaryRestService).getCompetitionSummary(COMPETITION_ID);
assertEquals(COMPETITION_ID, model.getCompetitionId());
assertEquals(defaultExpectedCompetitionSummary.getCompetitionName(), model.getCompetitionName());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsSubmitted(), model.getApplicationsSubmitted());
assertEquals(defaultExpectedCompetitionSummary.getAssessorDeadline(), model.getAssessmentDeadline());
assertEquals(expectedApplicationRows, model.getApplications());
}
@Test
public void submittedApplicationsPagedSortedFiltered() throws Exception {
Long[] ids = {1L, 2L, 3L};
String[] titles = {"Title 1", "Title 2", "Title 3"};
String[] leads = {"Lead 1", "Lead 2", "Lead 3"};
String[] innovationAreas = {"Innovation Area 1", "Innovation Area 1", "Innovation Area 1"};
Integer[] numberOfPartners = {5, 10, 12};
BigDecimal[] grantRequested = {BigDecimal.valueOf(1000), BigDecimal.valueOf(2000), BigDecimal.valueOf(3000)};
BigDecimal[] totalProjectCost = {BigDecimal.valueOf(5000), BigDecimal.valueOf(10000), BigDecimal.valueOf(15000)};
Long[] durations = {10L, 20L, 30L};
List<SubmittedApplicationsRowViewModel> expectedApplicationRows = asList(
new SubmittedApplicationsRowViewModel(ids[0], titles[0], leads[0], innovationAreas[0], numberOfPartners[0], grantRequested[0], totalProjectCost[0], durations[0]),
new SubmittedApplicationsRowViewModel(ids[1], titles[1], leads[1], innovationAreas[1], numberOfPartners[1], grantRequested[1], totalProjectCost[1], durations[1]),
new SubmittedApplicationsRowViewModel(ids[2], titles[2], leads[2], innovationAreas[2], numberOfPartners[2], grantRequested[2], totalProjectCost[2], durations[2])
);
List<ApplicationSummaryResource> expectedSummaries = newApplicationSummaryResource()
.withId(ids)
.withName(titles)
.withLead(leads)
.withInnovationArea(innovationAreas)
.withNumberOfPartners(numberOfPartners)
.withGrantRequested(grantRequested)
.withTotalProjectCost(totalProjectCost)
.withDuration(durations)
.build(3);
ApplicationSummaryPageResource expectedSummaryPageResource = new ApplicationSummaryPageResource(50, 3,expectedSummaries, 1, 20);
when(applicationSummaryRestService.getSubmittedApplications(COMPETITION_ID, "id", 1, 20, "filter", empty()))
.thenReturn(restSuccess(expectedSummaryPageResource));
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID))
.thenReturn(restSuccess(defaultExpectedCompetitionSummary));
MvcResult result = mockMvc.perform(get("/competition/{competitionId}/applications/submitted?page=1&sort=id&filterSearch=filter", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/submitted-applications"))
.andExpect(model().attribute("originQuery", "?origin=SUBMITTED_APPLICATIONS&page=1&sort=id&filterSearch=filter"))
.andReturn();
SubmittedApplicationsViewModel model = (SubmittedApplicationsViewModel) result.getModelAndView().getModel().get("model");
verify(applicationSummaryRestService).getSubmittedApplications(COMPETITION_ID, "id", 1, 20, "filter", empty());
verify(applicationSummaryRestService).getCompetitionSummary(COMPETITION_ID);
assertEquals(COMPETITION_ID, model.getCompetitionId());
assertEquals(defaultExpectedCompetitionSummary.getCompetitionName(), model.getCompetitionName());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsSubmitted(), model.getApplicationsSubmitted());
assertEquals(defaultExpectedCompetitionSummary.getAssessorDeadline(), model.getAssessmentDeadline());
PaginationViewModel actualPagination = model.getPagination();
assertEquals(1,actualPagination.getCurrentPage());
assertEquals(20,actualPagination.getPageSize());
assertEquals(3, actualPagination.getTotalPages());
assertEquals("1 to 20", actualPagination.getPageNames().get(0).getTitle());
assertEquals("21 to 40", actualPagination.getPageNames().get(1).getTitle());
assertEquals("41 to 50", actualPagination.getPageNames().get(2).getTitle());
assertEquals("?origin=SUBMITTED_APPLICATIONS&sort=id&filterSearch=filter&page=2", actualPagination.getPageNames().get(2).getPath());
assertEquals(expectedApplicationRows, model.getApplications());
}
@Test
public void submittedApplications_preservesQueryParams() throws Exception {
ApplicationSummaryPageResource expectedSummaryPageResource = new ApplicationSummaryPageResource();
expectedSummaryPageResource.setContent(emptyList());
when(applicationSummaryRestService.getSubmittedApplications(COMPETITION_ID, "", 0, 20, "", empty()))
.thenReturn(restSuccess(expectedSummaryPageResource));
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID))
.thenReturn(restSuccess(defaultExpectedCompetitionSummary));
mockMvc.perform(get("/competition/{competitionId}/applications/submitted?param1=abc¶m2=def", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/submitted-applications"))
.andExpect(model().attribute("originQuery", "?origin=SUBMITTED_APPLICATIONS¶m1=abc¶m2=def"))
.andReturn();
verify(applicationSummaryRestService).getSubmittedApplications(COMPETITION_ID, "", 0, 20, "", empty());
verify(applicationSummaryRestService).getCompetitionSummary(COMPETITION_ID);
}
@Test
public void ineligibleApplications() throws Exception {
Long[] ids = {1L, 2L, 3L};
String[] titles = {"Title 1", "Title 2", "Title 3"};
String[] leads = {"Lead 1", "Lead 2", "Lead 3"};
String[] applicant = {"LeadApplicant 1","LeadApplicant 2","LeadApplicant 3"};
Boolean[] informed = {true, true, false};
List<IneligibleApplicationsRowViewModel> expectedApplicationRows = asList(
new IneligibleApplicationsRowViewModel(ids[0], titles[0], leads[0], applicant[0], informed[0]),
new IneligibleApplicationsRowViewModel(ids[1], titles[1], leads[1], applicant[1], informed[1]),
new IneligibleApplicationsRowViewModel(ids[2], titles[2], leads[2], applicant[2], informed[2])
);
List<ApplicationSummaryResource> expectedSummaries = newApplicationSummaryResource()
.withId(ids)
.withName(titles)
.withLead(leads)
.withLeadApplicant(applicant)
.withIneligibleInformed(informed)
.build(3);
ApplicationSummaryPageResource expectedSummaryPageResource = new ApplicationSummaryPageResource();
expectedSummaryPageResource.setContent(expectedSummaries);
when(applicationSummaryRestService.getIneligibleApplications(COMPETITION_ID, "", 0, 20, "", empty()))
.thenReturn(restSuccess(expectedSummaryPageResource));
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID))
.thenReturn(restSuccess(defaultExpectedCompetitionSummary));
MvcResult result = mockMvc.perform(get("/competition/{competitionId}/applications/ineligible", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/ineligible-applications"))
.andExpect(model().attribute("originQuery", "?origin=INELIGIBLE_APPLICATIONS"))
.andReturn();
IneligibleApplicationsViewModel model = (IneligibleApplicationsViewModel) result.getModelAndView().getModel().get("model");
verify(applicationSummaryRestService).getIneligibleApplications(COMPETITION_ID, "", 0, 20, "", empty());
verify(applicationSummaryRestService).getCompetitionSummary(COMPETITION_ID);
assertEquals(COMPETITION_ID, model.getCompetitionId());
assertEquals(defaultExpectedCompetitionSummary.getCompetitionName(), model.getCompetitionName());
assertEquals(expectedApplicationRows, model.getApplications());
}
@Test
public void ineligibleApplicationsPagedSortedFiltered() throws Exception {
Long[] ids = {1L, 2L, 3L};
String[] titles = {"Title 1", "Title 2", "Title 3"};
String[] leads = {"Lead 1", "Lead 2", "Lead 3"};
String[] applicant = {"LeadApplicant 1","LeadApplicant 2","LeadApplicant 3"};
Boolean[] informed = {true, true, false};
List<IneligibleApplicationsRowViewModel> expectedApplicationRows = asList(
new IneligibleApplicationsRowViewModel(ids[0], titles[0], leads[0], applicant[0], informed[0]),
new IneligibleApplicationsRowViewModel(ids[1], titles[1], leads[1], applicant[1], informed[1]),
new IneligibleApplicationsRowViewModel(ids[2], titles[2], leads[2], applicant[2], informed[2])
);
List<ApplicationSummaryResource> expectedSummaries = newApplicationSummaryResource()
.withId(ids)
.withName(titles)
.withLead(leads)
.withLeadApplicant(applicant)
.withIneligibleInformed(informed)
.build(3);
ApplicationSummaryPageResource expectedSummaryPageResource = new ApplicationSummaryPageResource(50, 3,expectedSummaries, 1, 20);
when(applicationSummaryRestService.getIneligibleApplications(COMPETITION_ID, "id", 1, 20, "filter",empty()))
.thenReturn(restSuccess(expectedSummaryPageResource));
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID))
.thenReturn(restSuccess(defaultExpectedCompetitionSummary));
MvcResult result = mockMvc.perform(get("/competition/{competitionId}/applications/ineligible?page=1&sort=id&filterSearch=filter", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/ineligible-applications"))
.andExpect(model().attribute("originQuery", "?origin=INELIGIBLE_APPLICATIONS&page=1&sort=id&filterSearch=filter"))
.andReturn();
IneligibleApplicationsViewModel model = (IneligibleApplicationsViewModel) result.getModelAndView().getModel().get("model");
verify(applicationSummaryRestService).getIneligibleApplications(COMPETITION_ID, "id", 1, 20, "filter", empty());
verify(applicationSummaryRestService).getCompetitionSummary(COMPETITION_ID);
assertEquals(COMPETITION_ID, model.getCompetitionId());
assertEquals(defaultExpectedCompetitionSummary.getCompetitionName(), model.getCompetitionName());
PaginationViewModel actualPagination = model.getPagination();
assertEquals(1,actualPagination.getCurrentPage());
assertEquals(20,actualPagination.getPageSize());
assertEquals(3, actualPagination.getTotalPages());
assertEquals("1 to 20", actualPagination.getPageNames().get(0).getTitle());
assertEquals("21 to 40", actualPagination.getPageNames().get(1).getTitle());
assertEquals("41 to 50", actualPagination.getPageNames().get(2).getTitle());
assertEquals("?origin=INELIGIBLE_APPLICATIONS&sort=id&filterSearch=filter&page=2", actualPagination.getPageNames().get(2).getPath());
assertEquals(expectedApplicationRows, model.getApplications());
}
@Test
public void ineligibleApplications_preservesQueryParams() throws Exception {
ApplicationSummaryPageResource expectedSummaryPageResource = new ApplicationSummaryPageResource();
expectedSummaryPageResource.setContent(emptyList());
when(applicationSummaryRestService.getIneligibleApplications(COMPETITION_ID, "", 0, 20, "", empty()))
.thenReturn(restSuccess(expectedSummaryPageResource));
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID))
.thenReturn(restSuccess(defaultExpectedCompetitionSummary));
mockMvc.perform(get("/competition/{competitionId}/applications/ineligible?param1=abc¶m2=def", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/ineligible-applications"))
.andExpect(model().attribute("originQuery", "?origin=INELIGIBLE_APPLICATIONS¶m1=abc¶m2=def"))
.andReturn();
verify(applicationSummaryRestService).getIneligibleApplications(COMPETITION_ID, "", 0, 20, "", empty());
verify(applicationSummaryRestService).getCompetitionSummary(COMPETITION_ID);
}
@Test
public void allApplicationsSupportView() throws Exception {
setLoggedInUser(newUserResource().withRolesGlobal(singletonList(newRoleResource().withType(UserRoleType.SUPPORT).build())).build());
Long[] ids = {1L, 2L, 3L};
String[] titles = {"Title 1", "Title 2", "Title 3"};
String[] leads = {"Lead 1", "Lead 2", "Lead 3"};
String[] innovationAreas = {"Innovation Area 1", "Innovation Area 1", "Innovation Area 1"};
String[] statuses = {"Submitted", "Started", "Started"};
Integer[] percentages = {100, 70, 20};
List<AllApplicationsRowViewModel> expectedApplicationRows = asList(
new AllApplicationsRowViewModel(ids[0], titles[0], leads[0], innovationAreas[0], statuses[0], percentages[0]),
new AllApplicationsRowViewModel(ids[1], titles[1], leads[1], innovationAreas[1], statuses[1], percentages[1]),
new AllApplicationsRowViewModel(ids[2], titles[2], leads[2], innovationAreas[2], statuses[2], percentages[2])
);
List<ApplicationSummaryResource> expectedSummaries = newApplicationSummaryResource()
.withId(ids)
.withName(titles)
.withLead(leads)
.withInnovationArea(innovationAreas)
.withStatus(statuses)
.withCompletedPercentage(percentages)
.build(3);
ApplicationSummaryPageResource expectedSummaryPageResource = new ApplicationSummaryPageResource();
expectedSummaryPageResource.setContent(expectedSummaries);
when(applicationSummaryRestService.getAllApplications(COMPETITION_ID, "", 0, 20, ""))
.thenReturn(restSuccess(expectedSummaryPageResource));
when(applicationSummaryRestService.getCompetitionSummary(COMPETITION_ID))
.thenReturn(restSuccess(defaultExpectedCompetitionSummary));
MvcResult result = mockMvc.perform(get("/competition/{competitionId}/applications/all", COMPETITION_ID))
.andExpect(status().isOk())
.andExpect(view().name("competition/all-applications"))
.andExpect(model().attribute("originQuery", "?origin=ALL_APPLICATIONS"))
.andReturn();
AllApplicationsViewModel model = (AllApplicationsViewModel) result.getModelAndView().getModel().get("model");
verify(applicationSummaryRestService).getAllApplications(COMPETITION_ID, "", 0, 20, "");
verify(applicationSummaryRestService).getCompetitionSummary(COMPETITION_ID);
assertEquals(COMPETITION_ID, model.getCompetitionId());
assertEquals(defaultExpectedCompetitionSummary.getCompetitionName(), model.getCompetitionName());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsInProgress(), model.getApplicationsInProgress());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsStarted(), model.getApplicationsStarted());
assertEquals(defaultExpectedCompetitionSummary.getApplicationsSubmitted(), model.getApplicationsSubmitted());
assertEquals(defaultExpectedCompetitionSummary.getTotalNumberOfApplications(), model.getTotalNumberOfApplications());
assertEquals("Dashboard", model.getBackTitle());
assertEquals("/", model.getBackURL());
assertEquals(expectedApplicationRows, model.getApplications());
}
} |
package com.x.organization.assemble.express.jaxrs.unitduty;
import java.util.*;
import com.x.organization.core.entity.*;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonElement;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.cache.Cache.CacheKey;
import com.x.base.core.project.cache.CacheManager;
import com.x.base.core.project.gson.GsonPropertyObject;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.tools.ListTools;
import com.x.organization.assemble.express.Business;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
class ActionListIdentityWithUnitWithNameObject extends BaseAction {
@SuppressWarnings("unchecked")
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
ActionResult<List<Wo>> result = new ActionResult<>();
Business business = new Business(emc);
List<String> names = new ArrayList<>();
List<String> units = new ArrayList<>();
if (StringUtils.isNotEmpty(wi.getName())) {
names.add(wi.getName());
}
if (ListTools.isNotEmpty(wi.getNameList())) {
names.addAll(wi.getNameList());
}
if (StringUtils.isNotEmpty(wi.getUnit())) {
units.add(wi.getUnit());
}
if (ListTools.isNotEmpty(wi.getUnitList())) {
units.addAll(wi.getUnitList());
}
names = ListTools.trim(names, true, true);
units = ListTools.trim(units, true, true);
CacheKey cacheKey = new CacheKey(this.getClass(), names, units, wi.getRecursiveUnit());
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
result.setData((List<Wo>) optional.get());
} else {
List<Wo> wos = this.list(business, names, units, wi.getRecursiveUnit());
CacheManager.put(cacheCategory, cacheKey, wos);
result.setData(wos);
}
return result;
}
}
public static class Wi extends GsonPropertyObject {
@FieldDescribe("")
private String name;
@FieldDescribe("")
private String unit;
@FieldDescribe("()")
private List<String> nameList;
@FieldDescribe("()")
private List<String> unitList;
@FieldDescribe("false")
private Boolean recursiveUnit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public List<String> getNameList() {
return nameList;
}
public void setNameList(List<String> nameList) {
this.nameList = nameList;
}
public List<String> getUnitList() {
return unitList;
}
public void setUnitList(List<String> unitList) {
this.unitList = unitList;
}
public Boolean getRecursiveUnit() {
return recursiveUnit;
}
public void setRecursiveUnit(Boolean recursiveUnit) {
this.recursiveUnit = recursiveUnit;
}
}
public static class Wo extends com.x.base.core.project.organization.Identity {
private String matchUnitName;
private String matchUnitLevelName;
private Integer matchUnitLevel;
private String matchUnitDutyName;
private String matchUnitDutyId;
private Integer matchUnitDutyNumber;
public String getMatchUnitName() {
return matchUnitName;
}
public void setMatchUnitName(String matchUnitName) {
this.matchUnitName = matchUnitName;
}
public String getMatchUnitLevelName() {
return matchUnitLevelName;
}
public void setMatchUnitLevelName(String matchUnitLevelName) {
this.matchUnitLevelName = matchUnitLevelName;
}
public Integer getMatchUnitLevel() {
return matchUnitLevel;
}
public void setMatchUnitLevel(Integer matchUnitLevel) {
this.matchUnitLevel = matchUnitLevel;
}
public String getMatchUnitDutyName() {
return matchUnitDutyName;
}
public void setMatchUnitDutyName(String matchUnitDutyName) {
this.matchUnitDutyName = matchUnitDutyName;
}
public String getMatchUnitDutyId() {
return matchUnitDutyId;
}
public void setMatchUnitDutyId(String matchUnitDutyId) {
this.matchUnitDutyId = matchUnitDutyId;
}
public Integer getMatchUnitDutyNumber() {
return matchUnitDutyNumber;
}
public void setMatchUnitDutyNumber(Integer matchUnitDutyNumber) {
this.matchUnitDutyNumber = matchUnitDutyNumber;
}
}
private List<Wo> list(Business business, List<String> names, List<String> units, Boolean recursiveUnit) throws Exception {
List<Wo> wos = new ArrayList<>();
List<UnitDuty> os = new ArrayList<>();
Map<String, Unit> unitMap = new HashMap<>();
if(units.isEmpty()){
EntityManager em = business.entityManagerContainer().get(UnitDuty.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UnitDuty> cq = cb.createQuery(UnitDuty.class);
Root<UnitDuty> root = cq.from(UnitDuty.class);
Predicate p = root.get(UnitDuty_.name).in(names);
os = em.createQuery(cq.select(root).where(p)).getResultList();
}else{
List<Unit> unitList = business.unit().pick(units);
if(!unitList.isEmpty()){
units.clear();
for(Unit unit : unitList){
units.add(unit.getId());
unitMap.put(unit.getId(), unit);
if(BooleanUtils.isTrue(recursiveUnit)){
List<Unit> subUnitList = business.unit().listSubNestedObject(unit);
for (Unit subunit:subUnitList) {
unitMap.put(subunit.getId(), subunit);
units.add(subunit.getId());
}
}
}
units = ListTools.trim(units, true, true);
EntityManager em = business.entityManagerContainer().get(UnitDuty.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UnitDuty> cq = cb.createQuery(UnitDuty.class);
Root<UnitDuty> root = cq.from(UnitDuty.class);
Predicate p = root.get(UnitDuty_.name).in(names);
p = cb.and(p, root.get(UnitDuty_.unit).in(units));
os = em.createQuery(cq.select(root).where(p)).getResultList();
}
}
for (UnitDuty o : os) {
int i = 0;
for (Identity identity : business.identity().pick(o.getIdentityList())) {
Unit matchUnit = unitMap.get(o.getUnit());
if(matchUnit == null){
matchUnit = business.unit().pick(o.getUnit());
unitMap.put(matchUnit.getId(), matchUnit);
}
Unit unit = unitMap.get(identity.getUnit());
if(unit == null){
unit = business.unit().pick(identity.getUnit());
unitMap.put(unit.getId(), unit);
}
Person person = business.person().pick(identity.getPerson());
Wo wo = this.convertToIdentity(matchUnit, unit, person, identity);
i++;
wo.setMatchUnitDutyNumber(i);
wo.setMatchUnitDutyId(o.getId());
wo.setMatchUnitDutyName(o.getName());
wos.add(wo);
}
}
return wos;
}
private Wo convertToIdentity(Unit matchUnit, Unit unit, Person person, Identity identity) throws Exception {
Wo wo = new Wo();
if (null != matchUnit) {
wo.setMatchUnitLevelName(matchUnit.getLevelName());
wo.setMatchUnitName(matchUnit.getName());
wo.setMatchUnitLevel(matchUnit.getLevel());
}
if (null != unit) {
wo.setUnit(unit.getDistinguishedName());
}else{
wo.setUnit(identity.getUnit());
}
if (null != person) {
wo.setPerson(person.getDistinguishedName());
}else{
wo.setPerson(identity.getPerson());
}
if (null != identity) {
wo.setDescription(identity.getDescription());
wo.setDistinguishedName(identity.getDistinguishedName());
wo.setName(identity.getName());
wo.setOrderNumber(identity.getOrderNumber());
wo.setUnique(identity.getUnique());
wo.setUnitName(identity.getUnitName());
wo.setUnitLevel(identity.getUnitLevel());
wo.setUnitLevelName(identity.getUnitLevelName());
}
return wo;
}
} |
package me.legrange.mikrotik.impl;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import me.legrange.mikrotik.impl.Scanner.Token;
/**
* Parse the pseudo-command line into command objects.
*
* @author GideonLeGrange
*/
class Parser {
/**
* parse the given bit of text into a Command object
*/
static Command parse(String text) throws ParseException {
Parser parser = new Parser(text);
return parser.parse();
}
/**
* run parse on the internal data and return the command object
*/
private Command parse() throws ParseException {
command();
while (!is(Token.WHERE, Token.RETURN, Token.EOL)) {
param();
}
if (token == Token.WHERE) {
where();
}
if (token == Token.RETURN) {
returns();
}
expect(Token.EOL);
return cmd;
}
private void command() throws ParseException {
StringBuilder path = new StringBuilder();
do {
expect(Token.SLASH);
path.append("/");
next();
expect(Token.TEXT);
path.append(text);
next();
} while (token == Token.SLASH);
cmd = new Command(path.toString());
}
private void param() throws ParseException {
String name = text;
next();
if (token == Token.EQUALS) {
next();
StringBuilder val = new StringBuilder();
if (token == Token.PIPE) { // handle cases like hotspot=!auth
val.append(token);
next();
}
expect(Token.TEXT);
val.append(text);
next();
while (is(Token.COMMA, Token.SLASH)) {
val.append(token);
next();
expect(Token.TEXT);
val.append(text);
next();
}
cmd.addParameter(new Parameter(name, val.toString()));
} else {
cmd.addParameter(new Parameter(name));
}
}
private void where() throws ParseException {
next(); // swallow the word "where"
expr();
}
private void expr() throws ParseException {
expect(Token.NOT, Token.TEXT, Token.LEFT_BRACKET);
switch (token) {
case NOT:
notExpr();
break;
case TEXT: {
String name = text;
next();
expect(Token.EQUALS, Token.LESS, Token.MORE, Token.NOT_EQUALS);
switch (token) {
case EQUALS:
eqExpr(name);
break;
case NOT_EQUALS:
notExpr(name);
break;
case LESS:
lessExpr(name);
break;
case MORE:
moreExpr(name);
break;
default:
hasExpr(name);
}
}
break;
case LEFT_BRACKET:
nestedExpr();
break;
}
// if you get here, you had a expression, see if you want more.
switch (token) {
case AND:
andExpr();
break;
case OR:
orExpr();
break;
}
}
private void nestedExpr() throws ParseException {
expect(Token.LEFT_BRACKET);
next();
expr();
expect(Token.RIGHT_BRACKET);
next();
}
private void andExpr() throws ParseException {
next(); // eat and
expr();
cmd.addQuery("?
}
private void orExpr() throws ParseException {
next(); // eat or
expr();
cmd.addQuery("?
}
private void notExpr() throws ParseException {
next(); // eat not
expr();
cmd.addQuery("?#!");
}
private void eqExpr(String name) throws ParseException {
next(); // eat =
expect(Token.TEXT);
cmd.addQuery(String.format("?%s=%s", name, text));
next();
}
private void lessExpr(String name) throws ScanException {
next(); // eat <
cmd.addQuery(String.format("?<%s=%s", name, text));
next();
}
private void notExpr(String name) throws ScanException {
next(); // eat !=
cmd.addQuery(String.format("?%s=%s", name, text));
cmd.addQuery("?#!");
next();
}
private void moreExpr(String name) throws ScanException {
next(); // eat >
cmd.addQuery(String.format("?>%s=%s", name, text));
next();
}
private void hasExpr(String name) {
cmd.addQuery(String.format("?%s", name));
}
private void returns() throws ParseException {
next();
expect(Token.TEXT);
List<String> props = new LinkedList<>();
while (!(token == Token.EOL)) {
if (token != Token.COMMA) {
props.add(text);
}
next();
}
cmd.addProperty(props.toArray(new String[props.size()]));
}
private void expect(Token... tokens) throws ParseException {
if (!is(tokens))
throw new ParseException(String.format("Expected %s but found %s at position %d", Arrays.asList(tokens), this.token, scanner.pos()));
}
private boolean is(Token... tokens) {
for (Token want : tokens) {
if (this.token == want) return true;
}
return false;
}
/**
* move to the next token returned by the scanner
*/
private void next() throws ScanException {
token = scanner.next();
while (token == Token.WS) {
token = scanner.next();
}
text = scanner.text();
}
private Parser(String line) throws ScanException {
line = line.trim();
scanner = new Scanner(line);
next();
}
private final Scanner scanner;
private Token token;
private String text;
private Command cmd;
} |
package edu.psu.compbio.seqcode.gse.viz.metagenes;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import edu.psu.compbio.seqcode.gse.datasets.general.Point;
import edu.psu.compbio.seqcode.gse.datasets.locators.ChipChipLocator;
import edu.psu.compbio.seqcode.gse.datasets.seqdata.SeqLocator;
import edu.psu.compbio.seqcode.gse.datasets.species.Genome;
import edu.psu.compbio.seqcode.gse.datasets.species.Organism;
import edu.psu.compbio.seqcode.gse.deepseq.DeepSeqExpt;
import edu.psu.compbio.seqcode.gse.ewok.verbs.chipseq.SeqExpander;
import edu.psu.compbio.seqcode.gse.tools.utils.Args;
import edu.psu.compbio.seqcode.gse.utils.NotFoundException;
import edu.psu.compbio.seqcode.gse.utils.Pair;
import edu.psu.compbio.seqcode.gse.viz.metagenes.swing.MetaFrame;
import edu.psu.compbio.seqcode.projects.multigps.experiments.Sample;
public class MetaMaker {
private static boolean batchRun = false;
private static boolean cluster = false;
public static void main(String[] args) {
try {
if(args.length < 2){ printError();}
Pair<Organism, Genome> pair = Args.parseGenome(args);
Genome gen = pair.cdr();
int winLen = Args.parseInteger(args,"win", 10000);
int bins = Args.parseInteger(args,"bins", 100);
int readExt = Args.parseInteger(args,"readext", 0);
double lineMin = Args.parseDouble(args,"linemin", 0);
double lineMax = Args.parseDouble(args,"linemax", 100);
int lineThick = Args.parseInteger(args,"linethick", 1);
double pbMax = Args.parseDouble(args,"pbmax", 100);
char strand = Args.parseString(args, "strand", "/").charAt(0);
boolean drawColorBar = !Args.parseFlags(args).contains("nocolorbar");
boolean saveSVG = Args.parseFlags(args).contains("svg");
boolean transparent = Args.parseFlags(args).contains("transparent");
boolean printMatrix = Args.parseFlags(args).contains("printMatrix");
String profilerType = Args.parseString(args, "profiler", "simplechipseq");
String profileStyle = Args.parseString(args, "style", "Line");
List<String> expts = (List<String>) Args.parseStrings(args,"expt");
Collection<String> exptFilenames = Args.parseStrings(args, "exptfile");
String format = Args.parseString(args, "format","SAM");
List<String> backs = (List<String>) Args.parseStrings(args,"back");
List<String> peakFiles = (List<String>)Args.parseStrings(args, "peaks");
String outName = Args.parseString(args, "out", "meta");
if(Args.parseFlags(args).contains("batch")){batchRun=true;}
if(Args.parseFlags(args).contains("cluster")){cluster=true;}
Color c = Color.blue;
String newCol = Args.parseString(args, "color", "blue");
File file_mat = new File(outName+"_matrix.peaks");
if(!file_mat.exists()){
file_mat.createNewFile();
}
FileWriter fw_mat = new FileWriter(file_mat.getAbsoluteFile());
BufferedWriter br_mat = new BufferedWriter(fw_mat);
if(newCol.equals("red"))
c=Color.red;
if(newCol.equals("green"))
c=Color.green;
for(int s=0; s<args.length; s++){
if(args[s].equals("--color4")){
Integer R = new Integer(args[s+1]);
Integer G = new Integer(args[s+2]);
Integer B = new Integer(args[s+3]);
Integer A = new Integer(args[s+4]);
c= new Color(R,G,B,A);
}
}
if(gen==null || (expts.size()==0 && exptFilenames.size()==0)){printError();}
BinningParameters params = new BinningParameters(winLen, bins);
System.out.println("Binding Parameters:\tWindow size: "+params.getWindowSize()+"\tBins: "+params.getNumBins());
PointProfiler profiler=null;
boolean normalizeProfile=false;
if(profilerType.equals("simplechipseq")){
List<SeqLocator> exptlocs = Args.parseSeqExpt(args,"expt");
if(exptlocs.size()>0){
ArrayList<SeqExpander> exptexps = new ArrayList<SeqExpander>();
for(SeqLocator loc : exptlocs){
System.out.println(loc.getExptName()+"\t"+loc.getAlignName());
exptexps.add(new SeqExpander(loc));
}
System.out.println("Loading data...");
profiler = new ChipSeqProfiler(params, exptexps, readExt, pbMax,strand);
}else{
List<File> exptFiles = new ArrayList<File>();
for(String s : exptFilenames)
exptFiles.add(new File(s));
DeepSeqExpt dse = new DeepSeqExpt(gen, exptFiles, false, format, 40);
profiler = new ChipSeqProfiler(params, dse, readExt, pbMax,strand);
}
}else if(profilerType.equals("fiveprime")){
List<SeqLocator> exptlocs = Args.parseSeqExpt(args,"expt");
if(exptlocs.size()>0){
ArrayList<SeqExpander> exptexps = new ArrayList<SeqExpander>();
for(SeqLocator loc : exptlocs)
exptexps.add(new SeqExpander(loc));
System.out.println("Loading data...");
profiler = new Stranded5PrimeProfiler(params, exptexps, strand, pbMax);
}else{
List<File> exptFiles = new ArrayList<File>();
for(String s : exptFilenames)
exptFiles.add(new File(s));
DeepSeqExpt dse = new DeepSeqExpt(gen, exptFiles, false, format, 40);
profiler = new Stranded5PrimeProfiler(params, dse, strand, pbMax);
}
}
if(batchRun){
System.out.println("Batch running...");
if(peakFiles.size()==1 || peakFiles.size()==0){
MetaNonFrame nonframe = new MetaNonFrame(gen, params, profiler, normalizeProfile, saveSVG);
nonframe.setColor(c);
nonframe.setDrawColorBar(drawColorBar);
nonframe.setTransparent(transparent);
MetaProfileHandler handler = nonframe.getHandler();
if(peakFiles.size()==1){
System.out.println("Single set mode...");
String peakFile = peakFiles.get(0);
Vector<Point> points = nonframe.getUtils().loadPoints(new File(peakFile));
if(printMatrix){
double[][] mat_out = null;
for(int k=0; k<points.size(); k++){
if(k==0){
PointProfile temp = (PointProfile) profiler.execute(points.get(k));
mat_out = new double[points.size()][temp.length()];
for(int j=0; j< temp.length(); j++){
mat_out[k][j] = temp.value(j);
}
}
else{
PointProfile temp = (PointProfile) profiler.execute(points.get(k));
for(int j=0; j< temp.length(); j++){
mat_out[k][j] = temp.value(j);
}
}
}
for(int k =0; k< mat_out.length; k++ ){
br_mat.write(points.get(k).getLocationString()+"\t");
for (int j=0; j< mat_out[k].length; j++){
br_mat.write(mat_out[k][j]+"\t");
}
br_mat.write("\n");
}
}
handler.addPoints(points);
}else{
System.out.println("All TSS mode...");
Iterator<Point> points = nonframe.getUtils().loadTSSs();
handler.addPoints(points);
}
while(handler.addingPoints()){}
if(cluster)
nonframe.clusterLinePanel();
//Set the panel sizes here...
nonframe.setStyle(profileStyle);
nonframe.setLineMin(lineMin);
nonframe.setLineMax(lineMax);
nonframe.setLineThick(lineThick);
nonframe.saveImages(outName);
nonframe.savePointsToFile(outName);
}else if(peakFiles.size()>1){
System.out.println("Multiple set mode...");
MetaNonFrameMultiSet multinonframe = new MetaNonFrameMultiSet(peakFiles, gen, params, profiler, true);
for(int x=0; x<peakFiles.size(); x++){
String pf = peakFiles.get(x);
Vector<Point> points = multinonframe.getUtils().loadPoints(new File(pf));
List<MetaProfileHandler> handlers = multinonframe.getHandlers();
handlers.get(x).addPoints(points);
while(handlers.get(x).addingPoints()){}
}
multinonframe.saveImage(outName);
multinonframe.savePointsToFile(outName);
}
System.out.println("Finished");
if(profiler!=null)
profiler.cleanup();
}else{
System.out.println("Initializing Meta-point frame...");
MetaFrame frame = new MetaFrame(gen, params, profiler, normalizeProfile);
frame.setColor(c);
frame.setLineMax(lineMax);
frame.setLineMin(lineMin);
frame.setLineThick(lineThick);
frame.startup();
if(peakFiles.size() > 0){
MetaProfileHandler handler = frame.getHandler();
for(String pf : peakFiles){
Vector<Point> points = frame.getUtils().loadPoints(new File(pf));
handler.addPoints(points);
}
}
frame.setLineMax(lineMax);
frame.setLineMin(lineMin);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void printError(){
System.err.println("Usage: MetaMaker --species <organism;genome> \n" +
"--win <profile width> --bins <num bins> \n" +
"--readext <read extension> \n" +
"--linemin <min> --linemax <max> \n" +
"--pbmax <per base max>\n" +
"--profiler <chipseq/fiveprime> \n" +
"--expt <experiment names> OR --exptfile <file names> AND --format <SAM> \n" +
"--back <control experiment names (only applies to chipseq)> \n" +
"--peaks <peaks file name> --out <output root name> \n" +
"--color <red/green/blue> or --color4 <R G B A>\n" +
"--strand <+-/>\n" +
"--printMatrix [flag to print the matrix of tags] \n"+
"--cluster [flag to cluster in batch mode] \n" +
"--batch [a flag to run without displaying the window]\n" +
"--nocolorbar [flag to turn off colorbar in batch mode]\n" +
"--transparent [flag for transparent background]\n" +
"--style <Line/Histo>\n" +
"--svg [flag to save an SVG image]\n");
System.exit(1);
}
} |
package moe.tristan.easyfxml.util;
import moe.tristan.easyfxml.api.FxmlStylesheet;
import io.vavr.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.util.concurrent.CompletionStage;
/**
* Utility class to perform asynchronous operations on {@link Stage} instance on the JavaFX thread.
*/
public final class Stages {
private static final Logger LOG = LoggerFactory.getLogger(Stages.class);
private Stages() {
}
/**
* Creates a Stage.
*
* @param title The title of the stage
* @param rootPane The scene's base
*
* @return A {@link CompletionStage} to have monitoring over the state of the asynchronous creation. It will
* eventually contain the newly created stage.
*/
public static CompletionStage<Stage> stageOf(final String title, final Pane rootPane) {
return FxAsync.computeOnFxThread(
Tuple.of(title, rootPane),
titleAndPane -> {
final Stage stage = new Stage(StageStyle.DECORATED);
stage.setTitle(title);
stage.setScene(new Scene(rootPane));
return stage;
}
);
}
/**
* Schedules a stage for displaying.
*
* @param stage The stage to schedule displaying of.
*
* @return A {@link CompletionStage} to have monitoring over the state of the asynchronous operation
*/
public static CompletionStage<Stage> scheduleDisplaying(final Stage stage) {
LOG.debug(
"Requested displaying of stage {} with title : \"{}\"",
stage,
stage.getTitle()
);
return FxAsync.doOnFxThread(
stage,
Stage::show
);
}
public static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult) {
return stageCreationResult.whenCompleteAsync((res, err) -> scheduleDisplaying(res));
}
/**
* Schedules a stage for hiding
*
* @param stage The stage to shcedule hiding of.
*
* @return A {@link CompletionStage} to have monitoring over the state of the asynchronous operation
*/
public static CompletionStage<Stage> scheduleHiding(final Stage stage) {
LOG.debug(
"Requested hiding of stage {} with title : \"{}\"",
stage,
stage.getTitle()
);
return FxAsync.doOnFxThread(
stage,
Stage::hide
);
}
public static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult) {
return stageCreationResult.whenCompleteAsync((res, err) -> scheduleHiding(res));
}
/**
* Boilerplate for setting the stylesheet of a given stage via Java rather than FXML.
*
* @param stage The stage whose stylesheet we are changing
* @param stylesheet The new stylesheet in external form. That is, if it is a file, including the protocol info
* "file:/" before the actual path. Use {@link Resources#getResourceURL(String)} and {@link
* java.net.URL#toExternalForm()} if your css file is included in the classpath.
*
* @return A {@link CompletionStage} to have monitoring over the state of the asynchronous operation
*/
public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) {
LOG.info(
"Setting stylesheet {} for stage {}({})",
stylesheet,
stage.toString(),
stage.getTitle()
);
return FxAsync.doOnFxThread(
stage,
theStage -> {
final Scene stageScene = theStage.getScene();
stageScene.getStylesheets().clear();
stageScene.getStylesheets().add(stylesheet);
}
);
}
public static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet) {
return stageCreationResult.whenCompleteAsync((res, err) -> setStylesheet(res, stylesheet));
}
/**
* See {@link #setStylesheet(Stage, String)}
*
* @param stage The stage to apply the style to
* @param stylesheet The {@link FxmlStylesheet} pointing to the stylesheet to apply
*
* @return A {@link CompletionStage} to have monitoring over the state of the asynchronous operation
*/
public static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet) {
return setStylesheet(stage, stylesheet.getExternalForm());
}
public static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet) {
return stageCreationResult.whenCompleteAsync((res, err) -> setStylesheet(res, stylesheet));
}
} |
package edu.rutgers.css.Rutgers.auxiliary;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import edu.rutgers.css.Rutgers2.R;
/**
* Bus Prediction object adapter
* Populates bus arrival time rows for the bus channel.
*/
public class PredictionAdapter extends ArrayAdapter<Prediction> {
private static final String TAG = "PredictionAdapter";
private int layoutResource;
public final class PredictionHolder {
TextView titleTextView;
TextView directionTextView;
TextView minutesTextView;
}
public PredictionAdapter(Context context, int resource, List<Prediction> objects) {
super(context, resource, objects);
this.layoutResource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mLayoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Prediction prediction = this.getItem(position);
PredictionHolder holder = null;
/* Make new data holder or get existing one */
if(convertView == null) {
holder = new PredictionHolder();
convertView = mLayoutInflater.inflate(this.layoutResource, null);
convertView.setTag(holder);
}
else {
holder = (PredictionHolder) convertView.getTag();
}
convertView = mLayoutInflater.inflate(this.layoutResource, null);
convertView.setTag(holder);
/* Populate prediction row layout elements */
holder.titleTextView = (TextView) convertView.findViewById(R.id.title);
holder.directionTextView = (TextView) convertView.findViewById(R.id.direction);
holder.minutesTextView = (TextView) convertView.findViewById(R.id.minutes);
holder.titleTextView.setText(prediction.getTitle());
/* Change color of text based on how much time is remaining before the first bus arrives */
if(prediction.getMinutes().size() > 0) {
int first = prediction.getMinutes().get(0);
if(first < 2) {
holder.minutesTextView.setTextColor(getContext().getResources().getColor(R.color.busSoonest));
}
else if(first < 6) {
holder.minutesTextView.setTextColor(getContext().getResources().getColor(R.color.busSoon));
}
else {
holder.minutesTextView.setTextColor(getContext().getResources().getColor(R.color.busLater));
}
holder.minutesTextView.setText(formatMinutes(prediction.getMinutes()));
}
/* If there's no direction string, don't let that text field take up space */
if(prediction.getDirection() == null || prediction.getDirection().equals("")) {
holder.directionTextView.setVisibility(View.INVISIBLE);
holder.directionTextView.setMaxLines(0);
}
else {
holder.directionTextView.setVisibility(View.VISIBLE);
holder.directionTextView.setMaxLines(1);
holder.directionTextView.setText(prediction.getDirection());
}
return convertView;
}
private String formatMinutes(ArrayList<Integer> minutes) {
StringBuilder result = new StringBuilder("Arriving in ");
for(int i = 0; i < minutes.size(); i++) {
if(i != 0 && i == minutes.size() - 1) result.append("and ");
if(minutes.get(i) < 1) result.append("<1");
else result.append(minutes.get(i));
if(i != minutes.size() - 1) result.append(", ");
}
result.append(" minutes.");
return result.toString();
}
} |
package ninja.sequence.internal.util;
import ninja.sequence.delegate.EqualityComparator;
public class Key<T> {
private final T value;
private final EqualityComparator<? super T> comparator;
public Key(T value, EqualityComparator<? super T> comparator) {
this.value = value;
this.comparator = comparator;
}
public T getValue() {
return this.value;
}
@Override
@SuppressWarnings("unchecked")
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
Key<? extends T> key = (Key<? extends T>)other;
if (this.comparator != null) {
return this.comparator.equals(this.value, key.value);
}
return !(value != null ? !value.equals(key.value) : key.value != null);
}
@Override
public int hashCode() {
return 0;
}
} |
package edu.ucla.cens.awserver.service;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import edu.ucla.cens.awserver.datatransfer.AwRequest;
import edu.ucla.cens.awserver.util.JsonUtils;
/**
* Service for logging details about data uploads.
*
* @author selsky
*/
public class MessageLoggerService implements Service {
private static Logger _uploadLogger = Logger.getLogger("uploadLogger");
private static Logger _logger = Logger.getLogger(MessageLoggerService.class);
/**
* Performs the following tasks: logs the user's upload to the filesystem, logs the failed response message to the filesystem
* (if the request failed), and logs a statistic message to the upload logger.
*/
public void execute(AwRequest awRequest) {
_logger.info("beginning to log files and stats about a device upload");
logUploadToFilesystem(awRequest);
logUploadStats(awRequest);
_logger.info("finished with logging files and stats about a device upload");
}
private void logUploadStats(AwRequest awRequest) {
Object data = awRequest.getAttribute("jsonData");
String totalNumberOfMessages = "unknown";
String numberOfDuplicates = "unknown";
if(data instanceof JSONArray) {
totalNumberOfMessages = String.valueOf(((JSONArray) data).length());
List<Integer> duplicateIndexList = (List<Integer>) awRequest.getAttribute("duplicateIndexList");
if(null != duplicateIndexList && duplicateIndexList.size() > 0) {
numberOfDuplicates = String.valueOf(duplicateIndexList.size());
} else {
numberOfDuplicates = "0";
}
}
long processingTime = System.currentTimeMillis() - (Long) awRequest.getAttribute("startTime");
StringBuilder builder = new StringBuilder();
if(awRequest.isFailedRequest()) {
builder.append("failed_upload");
} else {
builder.append("successful_upload");
}
builder.append(" user=" + awRequest.getUser().getUserName());
builder.append(" requestType=" + (String) awRequest.getAttribute("requestType"));
builder.append(" numberOfRecords=" + totalNumberOfMessages);
builder.append(" numberOfDuplicates=" + numberOfDuplicates);
builder.append(" proccessingTimeMillis=" + processingTime);
_uploadLogger.info(builder.toString());
}
private void logUploadToFilesystem(AwRequest awRequest) {
// Persist the devices's upload to the filesystem
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = awRequest.getUser().getUserName() + "-" + sdf.format(new Date());
String catalinaBase = System.getProperty("catalina.base"); // need a system prop called upload-logging-directory or something like that
Object data = awRequest.getAttribute("jsonData"); // could either be a String or a JSONArray depending on where the main
// application processing ended
try {
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-upload.json"))));
if(null != data) {
printWriter.write(data.toString());
} else {
printWriter.write("no data");
}
close(printWriter);
if(awRequest.isFailedRequest()) {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-failed-upload-response.json"))));
String failedMessage = awRequest.getFailedRequestErrorMessage();
if(null != failedMessage) {
printWriter.write(failedMessage);
} else {
printWriter.write("no failed upload message found");
}
close(printWriter);
}
List<Integer> duplicateIndexList = (List<Integer>) awRequest.getAttribute("duplicateIndexList");
if(null != duplicateIndexList && duplicateIndexList.size() > 0) {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-upload-duplicates.json"))));
for(Integer index : duplicateIndexList) {
printWriter.write(JsonUtils.getJsonObjectFromJsonArray((JSONArray) data, index).toString());
}
close(printWriter);
}
}
catch(IOException ioe) {
_logger.warn("caught IOException when logging upload data to the filesystem. " + ioe.getMessage());
throw new ServiceException(ioe);
}
}
private void close(PrintWriter writer) throws IOException {
writer.flush();
writer.close();
writer = null;
}
} |
package org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.report.designer.internal.ui.editors.parts.event.IFastConsumerProcessor;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.activity.NotificationEvent;
import org.eclipse.birt.report.model.api.command.ContentEvent;
import org.eclipse.birt.report.model.api.command.PropertyEvent;
import org.eclipse.birt.report.model.api.command.ViewsContentEvent;
import org.eclipse.birt.report.model.api.core.IDesignElement;
/**
* Processor the model event for the ReportEditorWithPalette
*/
public class GraphicsViewModelEventProcessor extends AbstractModelEventProcessor implements IFastConsumerProcessor
{
public static String CONTENT_EVENTTYPE = "Content event type"; //$NON-NLS-1$
public static String EVENT_CONTENTS = "Event contents"; //$NON-NLS-1$
/**
* @param factory
*/
public GraphicsViewModelEventProcessor( IModelEventFactory factory )
{
super(factory);
}
/**Filter the event.
* @param type
* @return
*/
protected boolean includeEventType( int type )
{
return type == NotificationEvent.CONTENT_EVENT
| type == NotificationEvent.PROPERTY_EVENT
| type == NotificationEvent.NAME_EVENT
| type == NotificationEvent.STYLE_EVENT
| type == NotificationEvent.EXTENSION_PROPERTY_DEFINITION_EVENT
| type == NotificationEvent.LIBRARY_EVENT
| type == NotificationEvent.THEME_EVENT
| type == NotificationEvent.CONTENT_REPLACE_EVENT
| type == NotificationEvent.TEMPLATE_TRANSFORM_EVENT
| type == NotificationEvent.ELEMENT_LOCALIZE_EVENT
| type == NotificationEvent.LIBRARY_RELOADED_EVENT
| type == NotificationEvent.CSS_EVENT
| type == NotificationEvent.VIEWS_CONTENT_EVENT
| type == NotificationEvent.CSS_RELOADED_EVENT;
}
/**Process the content model event
* ContentModelEventInfo
*/
protected static class ContentModelEventInfo extends ModelEventInfo
{
//private int contentActionType;
private ContentModelEventInfo( DesignElementHandle focus, NotificationEvent ev )
{
super(focus, ev);
assert ev instanceof ContentEvent;
setTarget( focus );
setType( ev.getEventType( ) );
if (ev instanceof ContentEvent)
{
setContentActionType( ((ContentEvent)ev).getAction( ) );
addChangeContents( ((ContentEvent)ev).getContent( ) );
}
else if (ev instanceof ViewsContentEvent)
{
setContentActionType( ((ViewsContentEvent)ev).getAction( ) );
addChangeContents( ((ViewsContentEvent)ev).getContent( ) );
}
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.GraphicsViewModelEventProcessor.ModelEventInfo#canAcceptModelEvent(org.eclipse.birt.report.model.api.DesignElementHandle, org.eclipse.birt.report.model.api.activity.NotificationEvent)
*/
public boolean canAcceptModelEvent( ModelEventInfo info )
{
if (getContentActionType( ) == ContentEvent.REMOVE && getChangeContents( ).contains( info.getTarget( ) ))
{
return true;
}
boolean bool = super.canAcceptModelEvent(info );
if (!(info instanceof ContentModelEventInfo))
{
return false;
}
return bool & ((ContentModelEventInfo)info).getContentActionType( ) == ((ContentModelEventInfo)info).getContentActionType( );
}
/**
* @return
*/
public int getContentActionType( )
{
return ((Integer)getOtherInfo( ).get( CONTENT_EVENTTYPE )).intValue( );
}
/**
* @param contentActionType
*/
public void setContentActionType( int contentActionType )
{
getOtherInfo( ).put(CONTENT_EVENTTYPE ,new Integer(contentActionType));
}
public List getChangeContents()
{
return (List)getOtherInfo( ).get( EVENT_CONTENTS );
}
public void addChangeContents(Object obj)
{
Map map = getOtherInfo( );
if (obj instanceof IDesignElement)
{
obj = ((IDesignElement)obj).getHandle( getTarget( ).getModule( ) );
}
List list= (List)map.get( EVENT_CONTENTS );
if (list == null)
{
list = new ArrayList();
map.put(EVENT_CONTENTS, list);
}
list.add(obj);
}
}
/**Creat the factor to ctreat the report runnable.
* @return
*/
protected ModelEventInfoFactory createModelEventInfoFactory()
{
return new GraphicsModelEventInfoFactory();
}
/**
* ModelEventInfoFactory
*/
protected static class GraphicsModelEventInfoFactory implements ModelEventInfoFactory
{
/**Creat the report runnable for the ReportEditorWithPalette.
* @param focus
* @param ev
* @return
*/
public ModelEventInfo createModelEventInfo(DesignElementHandle focus, NotificationEvent ev)
{
switch ( ev.getEventType( ) )
{
case NotificationEvent.VIEWS_CONTENT_EVENT:
case NotificationEvent.CONTENT_EVENT :
{
return new ContentModelEventInfo(focus, ev);
}
default :
{
return new GraphicsViewModelEventInfo(focus, ev);
}
}
}
}
private static class GraphicsViewModelEventInfo extends ModelEventInfo
{
public GraphicsViewModelEventInfo( DesignElementHandle focus, NotificationEvent ev )
{
super( focus, ev );
if (ev instanceof PropertyEvent)
{
PropertyEvent proEvent = (PropertyEvent)ev;
getOtherInfo( ).put(proEvent.getPropertyName( ), focus);
}
}
@Override
public void addModelEvent( ModelEventInfo info )
{
getOtherInfo( ).putAll( info.getOtherInfo( ) );
}
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.designer.internal.ui.editors.parts.event.IFastConsumerProcessor#isOverdued()
*/
public boolean isOverdued( )
{
return getFactory( ).isDispose( );
}
public void postElementEvent( )
{
try
{
if (getFactory( ) instanceof IAdvanceModelEventFactory)
{
((IAdvanceModelEventFactory)getFactory( )).eventDispathStart();
}
super.postElementEvent( );
}
finally
{
if (getFactory( ) instanceof IAdvanceModelEventFactory)
{
((IAdvanceModelEventFactory)getFactory( )).eventDispathEnd();
}
}
}
} |
package edu.washington.escience.myriad.util;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.LoggerFactory;
import edu.washington.escience.myriad.MyriaConstants;
import edu.washington.escience.myriad.tool.MyriaConfigurationReader;
/**
* Deployment util methods.
* */
public final class DeploymentUtils {
/** usage. */
public static final String USAGE =
"java DeploymentUtils <config_file> <-copy_master_catalog | -copy_worker_catalogs | -copy_distribution | -start_master | -start_workers>";
/** The reader. */
private static final MyriaConfigurationReader READER = new MyriaConfigurationReader();
/** The logger. */
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(DeploymentUtils.class);
/**
* entry point.
*
* @param args args.
* @throws IOException if file system error occurs.
* */
public static void main(final String[] args) throws IOException {
if (args.length != 2) {
System.out.println(USAGE);
}
final String configFileName = args[0];
Map<String, HashMap<String, String>> config = READER.load(configFileName);
String description = config.get("deployment").get("name");
String username = config.get("deployment").get("username");
final String action = args[1];
if (action.equals("-copy_master_catalog")) {
String workingDir = config.get("deployment").get("path");
String remotePath = workingDir + "/" + description + "-files" + "/" + description;
// Although we have only one master now
HashMap<String, String> masters = config.get("master");
for (String masterId : masters.keySet()) {
String hostname = getHostname(masters.get(masterId));
if (username != null) {
hostname = username + "@" + hostname;
}
String localPath = description + "/" + "master.catalog";
mkdir(hostname, remotePath);
rsyncFileToRemote(localPath, hostname, remotePath);
rmFile(hostname, remotePath + "/master.catalog-shm");
rmFile(hostname, remotePath + "/master.catalog-wal");
}
} else if (action.equals("-copy_worker_catalogs")) {
HashMap<String, String> workers = config.get("workers");
for (String workerId : workers.keySet()) {
String workingDir = config.get("paths").get(workerId);
String remotePath = workingDir + "/" + description + "-files" + "/" + description;
String hostname = getHostname(workers.get(workerId));
if (username != null) {
hostname = username + "@" + hostname;
}
String localPath = description + "/" + "worker_" + workerId;
mkdir(hostname, remotePath);
rsyncFileToRemote(localPath, hostname, remotePath);
rmFile(hostname, remotePath + "/worker.catalog-shm");
rmFile(hostname, remotePath + "/worker.catalog-wal");
}
} else if (action.equals("-copy_distribution")) {
String workingDir = config.get("deployment").get("path");
String remotePath = workingDir + "/" + description + "-files";
HashMap<String, String> masters = config.get("master");
for (String masterId : masters.keySet()) {
String hostname = getHostname(masters.get(masterId));
if (username != null) {
hostname = username + "@" + hostname;
}
rsyncFileToRemote("libs", hostname, remotePath);
rsyncFileToRemote("conf", hostname, remotePath);
rsyncFileToRemote("sqlite4java-282", hostname, remotePath);
// server needs the config file to create catalogs for new workers
rsyncFileToRemote(configFileName, hostname, remotePath);
}
HashMap<String, String> workers = config.get("workers");
for (String workerId : workers.keySet()) {
workingDir = config.get("paths").get(workerId);
remotePath = workingDir + "/" + description + "-files";
String hostname = getHostname(workers.get(workerId));
if (username != null) {
hostname = username + "@" + hostname;
}
rsyncFileToRemote("libs", hostname, remotePath);
rsyncFileToRemote("conf", hostname, remotePath);
rsyncFileToRemote("sqlite4java-282", hostname, remotePath);
}
} else if (action.equals("-start_master")) {
String workingDir = config.get("deployment").get("path");
String restPort = config.get("deployment").get("rest_port");
String maxHeapSize = config.get("deployment").get("max_heap_size");
if (maxHeapSize == null) {
maxHeapSize = "";
}
HashMap<String, String> masters = config.get("master");
for (String masterId : masters.keySet()) {
String hostname = getHostname(masters.get(masterId));
if (username != null) {
hostname = username + "@" + hostname;
}
startMaster(hostname, workingDir, description, maxHeapSize, restPort);
}
} else if (action.equals("-start_workers")) {
String maxHeapSize = config.get("deployment").get("max_heap_size");
if (maxHeapSize == null) {
maxHeapSize = "";
}
HashMap<String, String> workers = config.get("workers");
for (String workerId : workers.keySet()) {
String hostname = getHostname(workers.get(workerId));
if (username != null) {
hostname = username + "@" + hostname;
}
String workingDir = config.get("paths").get(workerId);
startWorker(hostname, workingDir, description, maxHeapSize, workerId);
}
} else {
System.out.println(USAGE);
}
}
/**
* start a worker process on a remote machine.
*
* @param address e.g. beijing.cs.washington.edu
* @param workingDir the same meaning as path in deployment.cfg
* @param description the same meaning as name in deployment.cfg
* @param maxHeapSize the same meaning as max_heap_size in deployment.cfg
* @param workerId the worker id.
*/
public static void startWorker(final String address, final String workingDir, final String description,
final String maxHeapSize, final String workerId) {
StringBuilder builder = new StringBuilder();
builder.append("ssh " + address);
builder.append(" cd " + workingDir + "/" + description + "-files;");
/**
* start a master process on a remote machine.
*
* @param address e.g. beijing.cs.washington.edu
* @param workingDir the same meaning as path in deployment.cfg
* @param description the same meaning as name in deployment.cfg
* @param maxHeapSize the same meaning as max_heap_size in deployment.cfg
* @param restPort the port number for restlet.
*/
public static void startMaster(final String address, final String workingDir, final String description,
final String maxHeapSize, final String restPort) {
StringBuilder builder = new StringBuilder();
builder.append("ssh " + address);
builder.append(" cd " + workingDir + "/" + description + "-files;");
/**
* Call mkdir on a remote machine.
*
* @param address e.g. beijing.cs.washington.edu
* @param remotePath e.g. /tmp/test
*/
public static void mkdir(final String address, final String remotePath) {
StringBuilder builder = new StringBuilder();
builder.append("ssh");
builder.append(" " + address);
builder.append(" mkdir -p");
builder.append(" " + remotePath);
startAProcess(builder.toString());
}
/**
* Copy a local file to a location on a remote machine, using rsync.
*
* @param localPath path to the local file that you want to copy from
* @param address e.g. beijing.cs.washington.edu
* @param remotePath e.g. /tmp/test
*/
public static void rsyncFileToRemote(final String localPath, final String address, final String remotePath) {
StringBuilder builder = new StringBuilder();
builder.append("rsync");
builder.append(" -aLvz");
builder.append(" " + localPath);
builder.append(" " + address + ":" + remotePath);
startAProcess(builder.toString());
}
/**
* Remove a file on a remote machine.
*
* @param address e.g. beijing.cs.washington.edu.
* @param path the path to the file.
*/
public static void rmFile(final String address, final String path) {
StringBuilder builder = new StringBuilder();
builder.append("ssh");
builder.append(" " + address);
builder.append(" rm -rf");
builder.append(" " + path);
startAProcess(builder.toString());
}
/**
* start a process by ProcessBuilder.
*
* @param cmd the command.
*/
private static void startAProcess(final String cmd) {
LOGGER.debug(cmd);
try {
new ProcessBuilder().inheritIO().command(cmd.split(" ")).start();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* Helper function to get the hostname from hostname:port.
*
* @param s the string hostname:port
* @return the hostname.
* */
private static String getHostname(final String s) {
return s.split(":")[0];
}
/**
* util classes are not instantiable.
* */
private DeploymentUtils() {
}
} |
package org.deviceconnect.android.deviceplugin.heartrate.ble.adapter;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.Build;
import android.os.ParcelUuid;
import org.deviceconnect.android.deviceplugin.heartrate.ble.BleDeviceAdapter;
import org.deviceconnect.android.deviceplugin.heartrate.ble.BleUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
*
* @author NTT DOCOMO, INC.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class NewBleDeviceAdapterImpl extends BleDeviceAdapter {
private final Context mContext;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBleScanner;
private BleDeviceScanCallback mCallback;
private final UUID[] mServiceUuids = {
UUID.fromString(BleUtils.SERVICE_HEART_RATE_SERVICE)
};
public NewBleDeviceAdapterImpl(final Context context) {
mContext = context;
BluetoothManager manager = BleUtils.getManager(context);
mBluetoothAdapter = manager.getAdapter();
mBleScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
@Override
public void startScan(final BleDeviceScanCallback callback) {
mCallback = callback;
List<ScanFilter> filters = new ArrayList<ScanFilter>();
if (mServiceUuids != null && mServiceUuids.length > 0) {
for (UUID uuid : mServiceUuids) {
ScanFilter filter = new ScanFilter.Builder().setServiceUuid(
new ParcelUuid(uuid)).build();
filters.add(filter);
}
}
ScanSettings settings = new ScanSettings.Builder().build();
mBleScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (mBleScanner != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mBleScanner.startScan(filters, settings, mScanCallback);
} else {
if (BleUtils.isBLEPermission(mContext)) {
mBleScanner.startScan(filters, settings, mScanCallback);
}
}
}
}
@Override
public void stopScan(final BleDeviceScanCallback callback) {
mBleScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (mBleScanner != null) {
mBleScanner.stopScan(mScanCallback);
}
}
@Override
public BluetoothDevice getDevice(final String address) {
return mBluetoothAdapter.getRemoteDevice(address);
}
@Override
public Set<BluetoothDevice> getBondedDevices() {
return mBluetoothAdapter.getBondedDevices();
}
@Override
public boolean isEnabled() {
return mBluetoothAdapter.isEnabled();
}
@Override
public boolean checkBluetoothAddress(final String address) {
return BluetoothAdapter.checkBluetoothAddress(address);
}
private final ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(final int callbackType, final ScanResult result) {
if (mCallback != null) {
mCallback.onLeScan(result.getDevice(), result.getRssi());
}
}
@Override
public void onBatchScanResults(final List<ScanResult> results) {
}
@Override
public void onScanFailed(final int errorCode) {
mCallback.onFail();
}
};
} |
package org.attribyte.wp.model;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import java.text.ParseException;
import java.util.Map;
public class Shortcode {
/**
* Creates a shortcode without content.
* @param name The name.
* @param attributes The attributes.
*/
public Shortcode(final String name, final Map<String, String> attributes) {
this(name, attributes, null);
}
/**
* Creates a shortcode with content.
* @param name The name.
* @param attributes The attributes.
* @param content The content.
*/
public Shortcode(final String name, final Map<String, String> attributes,
final String content) {
this.name = name;
this.attributes = attributes != null ? ImmutableMap.copyOf(attributes) : ImmutableMap.of();
this.content = Strings.emptyToNull(content);
}
/**
* Adds content to a shortcode.
* @param content The content.
* @return The shortcode with content added.
*/
public Shortcode withContent(final String content) {
return new Shortcode(name, attributes, content);
}
/**
* The name.
*/
public final String name;
/**
* The attributes.
*/
public final ImmutableMap<String, String> attributes;
/**
* The content.
*/
public final String content;
/**
* Gets a positional attribute value.
* @param pos The position.
* @return The value, or {@code null} if no value at the position.
*/
public final String positionalValue(final int pos) {
return attributes.get(String.format("$%d", pos));
}
@Override
public final String toString() {
StringBuilder buf = new StringBuilder("[");
buf.append(name);
attributes.entrySet().forEach(kv -> {
if(kv.getKey().startsWith("$")) {
buf.append(" ");
if(kv.getValue().contains(" ")) {
buf.append("\"").append(escapeAttribute(kv.getValue())).append("\"");
} else {
buf.append(kv.getValue());
}
} else {
buf.append(" ").append(kv.getKey()).append("=\"").append(escapeAttribute(kv.getValue())).append("\"");
}
});
buf.append("]");
if(content != null) {
buf.append(content);
buf.append("[/").append(name).append("]");
}
return buf.toString();
}
/**
* Parses a shortcode
* @param shortcode The shortcode string.
* @return The parsed shortcode.
* @throws ParseException on invalid code.
*/
public static Shortcode parse(final String shortcode) throws ParseException {
String exp = shortcode.trim();
if(exp.length() < 3) {
throw new ParseException(String.format("Invalid shortcode ('%s')", exp), 0);
}
if(exp.charAt(0) != '[') {
throw new ParseException("Expecting '['", 0);
}
int end = exp.indexOf(']');
if(end == -1) {
throw new ParseException("Expecting ']", 0);
}
Shortcode startTag = Parser.parseStart(exp.substring(0, end + 1));
end = exp.lastIndexOf("[/");
if(end > 0) {
if(exp.endsWith("[/" + startTag.name + "]")) {
int start = shortcode.indexOf("]");
return startTag.withContent(exp.substring(start + 1, end));
} else {
throw new ParseException("Invalid shortcode end", 0);
}
} else {
return startTag;
}
}
/**
* Escapes an attribute value.
* @param val The value.
* @return The escaped value.
*/
public static String escapeAttribute(final String val) {
return Strings.nullToEmpty(val); //TODO?
}
private static class Parser {
private static boolean isNameCharacter(final char ch) {
return (Character.isLetterOrDigit(ch) || ch == '_' || ch == '-');
}
private static String validateName(final String str) throws ParseException {
for(char ch : str.toCharArray()) {
if(!isNameCharacter(ch)) {
throw new ParseException(String.format("Invalid name ('%s')", str), 0);
}
}
return str;
}
/**
* Parse '[shortcode attr0="val0" attr1="val1"]
* @param str The shortcode string.
* @return The shortcode.
* @throws ParseException on invalid shortcode.
*/
private static Shortcode parseStart(final String str) throws ParseException {
String exp = str.trim();
if(exp.length() < 3) {
throw new ParseException(String.format("Invalid shortcode ('%s')", str), 0);
}
if(exp.charAt(0) != '[') {
throw new ParseException("Expecting '['", 0);
}
if(exp.charAt(exp.length() -1) != ']') {
throw new ParseException("Expecting ']'", exp.length() - 1);
}
exp = exp.substring(1, exp.length() -1).trim();
if(exp.length() == 0) {
throw new ParseException(String.format("Invalid shortcode ('%s')", str), 0);
}
int attrStart = exp.indexOf(' ');
if(attrStart < 0) {
return new Shortcode(validateName(exp), ImmutableMap.of());
} else {
return new Shortcode(validateName(exp.substring(0, attrStart)), parseAttributes(exp.substring(attrStart).trim()));
}
}
/**
* Holds state for parsing attributes.
*/
private static class AttributeString {
AttributeString(final String str) {
this.chars = str.toCharArray();
this.buf = new StringBuilder();
}
/**
* The current state.
*/
enum StringState {
/**
* Before any recognized start character.
*/
BEFORE_START,
/**
* Inside a quoted value.
*/
QUOTED_VALUE,
/**
* A value.
*/
VALUE,
}
private String value() {
String val = buf.toString();
buf.setLength(0);
if(ch == ' ') { //Eat trailing spaces...
int currPos = pos;
while(currPos < chars.length) {
char currChar = chars[currPos];
if(currChar != ' ') {
pos = currPos;
ch = chars[pos];
break;
} else {
currPos++;
}
}
}
return val;
}
String nextString() throws ParseException {
StringState state = StringState.BEFORE_START;
while(pos < chars.length) {
ch = chars[pos++];
switch(ch) {
case '=':
switch(state) {
case BEFORE_START:
state = StringState.VALUE;
break;
case QUOTED_VALUE:
buf.append(ch);
break;
case VALUE:
return value();
}
break;
case ' ':
switch(state) {
case BEFORE_START:
break;
case QUOTED_VALUE:
buf.append(ch);
break;
case VALUE:
return value();
}
break;
case '\"':
case '\'':
switch(state) {
case BEFORE_START:
state = StringState.QUOTED_VALUE;
break;
case QUOTED_VALUE:
return value();
case VALUE:
throw new ParseException("Unexpected '\"'", pos);
}
break;
default:
switch(state) {
case BEFORE_START:
state = StringState.VALUE;
break;
}
buf.append(ch);
break;
}
}
switch(state) {
case VALUE:
return buf.toString();
case QUOTED_VALUE:
throw new ParseException("Expected '\"' or '\''", pos);
default:
return null;
}
}
char ch;
int pos = 0;
String last;
final char[] chars;
final StringBuilder buf;
}
/**
* Parse attributes in a shortcode.
* @param attrString The attribute string.
* @return The map of attributes. Keys are <em>lower-case</em>.
* @throws ParseException on invalid shortcode.
*/
private static Map<String, String> parseAttributes(String attrString) throws ParseException {
AttributeString str = new AttributeString(attrString);
ImmutableMap.Builder<String, String> attributes = ImmutableMap.builder(); //Immutable map preserves entry order.
AttrState state = AttrState.NAME;
String currName = "";
String currString = "";
int currPos = 0;
while((currString = str.nextString()) != null) {
switch(state) {
case NAME:
if(str.ch == '=') {
currName = currString;
state = AttrState.VALUE;
} else {
attributes.put(String.format("$%d", currPos++), currString);
}
break;
case VALUE:
attributes.put(currName.toLowerCase(), currString);
state = AttrState.NAME;
break;
}
}
return attributes.build();
}
/**
* Attribute parse state.
*/
private enum AttrState {
/**
* Parsing a name.
*/
NAME,
/**
* Expecting a value.
*/
VALUE;
}
}
} |
package com.thinkbiganalytics.nifi.v1.rest.client;
import com.thinkbiganalytics.nifi.rest.client.NiFiProcessorsRestClient;
import com.thinkbiganalytics.nifi.rest.client.NifiComponentNotFoundException;
import com.thinkbiganalytics.nifi.rest.support.NifiConstants;
import org.apache.nifi.web.api.dto.ProcessorDTO;
import org.apache.nifi.web.api.dto.RevisionDTO;
import org.apache.nifi.web.api.entity.ProcessorEntity;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.ws.rs.NotFoundException;
/**
* Implements a {@link NiFiProcessorsRestClient} for communicating with NiFi v1.0.
*/
public class NiFiProcessorsRestClientV1 implements NiFiProcessorsRestClient {
/** Base path for processor requests */
private static final String BASE_PATH = "/processors/";
/** REST client for communicating with NiFi */
private final NiFiRestClientV1 client;
/**
* Constructs a {@code NiFiProcessorsRestClientV1} with the specified NiFi REST client.
*
* @param client the REST client
*/
public NiFiProcessorsRestClientV1(@Nonnull final NiFiRestClientV1 client) {
this.client = client;
}
@Nonnull
@Override
public Optional<ProcessorDTO> findById(@Nonnull final String processGroupId, @Nonnull final String processorId) {
return findEntityById(processorId).map(ProcessorEntity::getComponent);
}
@Nonnull
@Override
public ProcessorDTO update(@Nonnull final ProcessorDTO processor) {
return findEntityById(processor.getId())
.flatMap(current -> {
final ProcessorEntity entity = new ProcessorEntity();
entity.setComponent(processor);
final RevisionDTO revision = new RevisionDTO();
revision.setVersion(current.getRevision().getVersion());
entity.setRevision(revision);
try {
return Optional.of(client.put(BASE_PATH + processor.getId(), entity, ProcessorEntity.class).getComponent());
} catch (final NotFoundException e) {
return Optional.empty();
}
})
.orElseThrow(() -> new NifiComponentNotFoundException(processor.getId(), NifiConstants.NIFI_COMPONENT_TYPE.PROCESSOR, null));
}
/**
* Gets a processor entity.
*
* @param id the processor id
* @return the processor entity, if found
*/
@Nonnull
private Optional<ProcessorEntity> findEntityById(@Nonnull final String id) {
try {
return Optional.ofNullable(client.get(BASE_PATH + id, null, ProcessorEntity.class));
} catch (final NotFoundException e) {
return Optional.empty();
}
}
} |
package org.basex.gui.view.info;
import static org.basex.core.Text.*;
import static org.basex.gui.GUIConstants.*;
import java.awt.*;
import java.awt.event.*;
import org.basex.core.*;
import org.basex.core.cmd.*;
import org.basex.gui.GUIConstants.Fill;
import org.basex.gui.*;
import org.basex.gui.layout.*;
import org.basex.gui.view.*;
import org.basex.util.*;
import org.basex.util.list.*;
public final class InfoView extends View {
/** Old text. */
private final TokenBuilder text = new TokenBuilder();
/** Header label. */
private final BaseXLabel header;
/** Timer label. */
private final BaseXLabel timer;
/** North label. */
private final BaseXBack north;
/** Text Area. */
private final BaseXEditor area;
/** Query statistics. */
private IntList stat = new IntList();
/** Query statistics strings. */
private StringList strings;
/** Focused bar. */
private int focus = -1;
/** Panel Width. */
private int w;
/** Panel Height. */
private int h;
/** Bar widths. */
private int bw;
/** Bar size. */
private int bs;
/**
* Default constructor.
* @param man view manager
*/
public InfoView(final ViewNotifier man) {
super(INFOVIEW, man);
border(6, 6, 6, 6).layout(new BorderLayout());
north = new BaseXBack(Fill.NONE).layout(new BorderLayout());
header = new BaseXLabel(QUERY_INFO);
north.add(header, BorderLayout.NORTH);
north.add(header, BorderLayout.NORTH);
timer = new BaseXLabel(" ", true, false);
north.add(timer, BorderLayout.SOUTH);
add(north, BorderLayout.NORTH);
area = new BaseXEditor(false, gui);
add(area, BorderLayout.CENTER);
refreshLayout();
}
@Override
public void refreshInit() { }
@Override
public void refreshFocus() { }
@Override
public void refreshMark() { }
@Override
public void refreshContext(final boolean more, final boolean quick) { }
@Override
public void refreshUpdate() { }
@Override
public void refreshLayout() {
header.setFont(lfont);
timer.setFont(font);
area.setFont(font);
}
@Override
public boolean visible() {
return gui.gprop.is(GUIProp.SHOWINFO);
}
@Override
public void visible(final boolean v) {
gui.gprop.set(GUIProp.SHOWINFO, v);
}
@Override
protected boolean db() {
return false;
}
/**
* Displays the specified information.
* @param info info string
* @param cmd command
* @param time time required
* @param ok flag indicating if command execution was successful
*/
public void setInfo(final String info, final Command cmd, final String time,
final boolean ok) {
final StringList eval = new StringList();
final StringList comp = new StringList();
final StringList plan = new StringList();
final StringList sl = new StringList();
final StringList stats = new StringList();
final IntList il = new IntList();
String err = "";
String qu = "";
String res = "";
final String[] split = info.split(NL);
for(int i = 0; i < split.length; ++i) {
final String line = split[i];
final int s = line.indexOf(':');
if(line.startsWith(PARSING_CC) || line.startsWith(COMPILING_CC) ||
line.startsWith(EVALUATING_CC) || line.startsWith(PRINTING_CC) ||
line.startsWith(TOTAL_TIME_CC)) {
final int t = line.indexOf(" ms");
sl.add(line.substring(0, s).trim());
il.add((int) (Double.parseDouble(line.substring(s + 1, t)) * 100));
} else if(line.startsWith(QUERY_C)) {
qu = line.substring(s + 1).trim();
} else if(line.startsWith(QUERY_PLAN_C)) {
while(++i < split.length && !split[i].isEmpty()) plan.add(split[i]);
--i;
} else if(line.startsWith(COMPILING_C)) {
while(++i < split.length && !split[i].isEmpty()) comp.add(split[i]);
} else if(line.startsWith(RESULT_C)) {
res = line.substring(s + 1).trim();
} else if(line.startsWith(EVALUATING_C)) {
while(++i < split.length && split[i].startsWith(QUERYSEP)) eval.add(split[i]);
--i;
} else if(!ok) {
err += line + NL;
} else if(line.startsWith(HITS_X_CC) || line.startsWith(UPDATED_CC) ||
line.startsWith(PRINTED_CC)) {
stats.add("- " + line);
}
}
stat = il;
strings = sl;
String total = time;
if(ok && cmd instanceof XQuery && !il.isEmpty()) {
text.reset();
add(EVALUATING_C, eval);
add(QUERY_C + ' ', qu);
add(COMPILING_C, comp);
if(!comp.isEmpty()) add(RESULT_C, res);
add(TIMING_C, sl);
add(RESULT_C, stats);
add(QUERY_PLAN_C, plan);
final int runs = Math.max(1, gui.context.prop.num(Prop.RUNS));
total = Performance.getTime(il.get(il.size() - 1) * 10000L * runs, runs);
} else {
if(ok) {
add(cmd);
text.add(info).nline();
} else {
add(ERROR_C, err);
add(cmd);
add(COMPILING_C, comp);
add(QUERY_PLAN_C, plan);
}
}
area.setText(text.finish());
if(total != null) timer.setText(TOTAL_TIME_CC + total);
repaint();
}
/**
* Adds the command representation.
* @param cmd command
*/
private void add(final Command cmd) {
if(cmd instanceof XQuery) {
add(QUERY_C + ' ', cmd.args[0].trim());
} else if(cmd != null) {
text.bold().add(COMMAND + COLS).norm().addExt(cmd).nline();
}
}
/**
* Resets the info string without repainting the view.
*/
public void reset() {
text.reset();
}
/**
* Adds the specified strings.
* @param head string header
* @param list list reference
*/
private void add(final String head, final StringList list) {
final int runs = Math.max(1, gui.context.prop.num(Prop.RUNS));
if(list.isEmpty()) return;
text.bold().add(head).norm().nline();
final int is = list.size();
for(int i = 0; i < is; ++i) {
String line = list.get(i);
if(list == strings) line = ' ' + QUERYSEP + line + ": " +
Performance.getTime(stat.get(i) * 10000L * runs, runs);
text.add(line).nline();
}
text.hline();
}
/**
* Adds a string.
* @param head string header
* @param txt text
*/
private void add(final String head, final String txt) {
if(!txt.isEmpty()) text.bold().add(head).norm().add(txt).nline().hline();
}
@Override
public void mouseMoved(final MouseEvent e) {
final int l = stat.size();
if(l == 0) return;
focus = -1;
if(e.getY() < h) {
for(int i = 0; i < l; ++i) {
final int bx = w - bw + bs * i;
if(e.getX() >= bx && e.getX() < bx + bs) focus = i;
}
}
final int runs = Math.max(1, gui.context.prop.num(Prop.RUNS));
final int f = focus == -1 ? l - 1 : focus;
timer.setText(strings.get(f) + COLS +
Performance.getTime(stat.get(f) * 10000L * runs, runs));
repaint();
}
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
final int l = stat.size();
if(l == 0) return;
h = north.getHeight();
w = getWidth() - 8;
bw = gui.gprop.num(GUIProp.FONTSIZE) * 2 + w / 10;
bs = bw / (l - 1);
// find maximum value
int m = 0;
for(int i = 0; i < l - 1; ++i) m = Math.max(m, stat.get(i));
// draw focused bar
final int by = 10;
final int bh = h - by;
for(int i = 0; i < l - 1; ++i) {
if(i != focus) continue;
final int bx = w - bw + bs * i;
g.setColor(color3);
g.fillRect(bx, by, bs + 1, bh);
}
// draw all bars
for(int i = 0; i < l - 1; ++i) {
final int bx = w - bw + bs * i;
g.setColor(color((i == focus ? 3 : 2) + i * 2));
final int p = Math.max(1, stat.get(i) * bh / m);
g.fillRect(bx, by + bh - p, bs, p);
g.setColor(color(8));
g.drawRect(bx, by + bh - p, bs, p - 1);
}
}
} |
package org.brutusin.wava.core;
import org.brutusin.wava.core.io.Event;
import org.brutusin.wava.core.io.PeerChannel;
import org.brutusin.wava.core.cfg.Config;
import org.brutusin.wava.core.plug.PromiseHandler;
import org.brutusin.wava.core.plug.LinuxCommands;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringUtils;
import org.brutusin.commons.utils.ErrorHandler;
import org.brutusin.commons.utils.Miscellaneous;
import org.brutusin.json.spi.JsonCodec;
import org.brutusin.wava.core.cfg.GroupCfg;
import org.brutusin.wava.core.plug.NicenessHandler;
import org.brutusin.wava.input.CancelInput;
import org.brutusin.wava.input.GroupInput;
import org.brutusin.wava.input.SubmitInput;
import org.brutusin.wava.utils.ANSICode;
import org.brutusin.wava.utils.NonRootUserException;
import org.brutusin.wava.utils.RetCode;
public class Scheduler {
public final static String DEFAULT_GROUP_NAME = "default";
public final static int EVICTION_ETERNAL = -1;
private final static Logger LOGGER = Logger.getLogger(Scheduler.class.getName());
// next four accessed under synchronized(jobSet)
private final JobSet jobSet = new JobSet();
private final Map<Integer, JobInfo> jobMap = new HashMap<>();
private final Map<Integer, ProcessInfo> processMap = new HashMap<>();
private final Map<String, GroupInfo> groupMap = new HashMap<>();
private final ThreadGroup coreGroup = new ThreadGroup(Scheduler.class.getName());
private final ThreadGroup processGroup = new ThreadGroup(Scheduler.class.getName() + " processes");
private final AtomicInteger jobCounter = new AtomicInteger();
private final AtomicInteger groupCounter = new AtomicInteger();
private final Thread processingThread;
private final Thread deadlockThread;
private volatile boolean deadlockFlag;
private volatile boolean closed;
private String jobList;
private final long maxManagedRss;
private final String runningUser;
public Scheduler() throws NonRootUserException, IOException, InterruptedException {
this.runningUser = LinuxCommands.getInstance().getRunningUser();
if (!this.runningUser.equals("root")) {
throw new NonRootUserException();
}
if (Config.getInstance().getSchedulerCfg().getMaxTotalRSSBytes() > 0) {
this.maxManagedRss = Config.getInstance().getSchedulerCfg().getMaxTotalRSSBytes();
} else {
try {
this.maxManagedRss = LinuxCommands.getInstance().getSystemRSSMemory();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
createGroupInfo(DEFAULT_GROUP_NAME, this.runningUser, 0, EVICTION_ETERNAL);
GroupCfg.Group[] predefinedGroups = Config.getInstance().getGroupCfg().getPredefinedGroups();
if (predefinedGroups != null) {
for (GroupCfg.Group group : predefinedGroups) {
createGroupInfo(group.getName(), this.runningUser, group.getPriority(), group.getTimeToIdleSeconds());
}
}
this.processingThread = new Thread(this.coreGroup, "processingThread") {
@Override
public void run() {
while (true) {
if (Thread.interrupted()) {
break;
}
try {
Thread.sleep(Config.getInstance().getSchedulerCfg().getPollingSecs() * 1000);
refresh();
} catch (Throwable th) {
if (th instanceof InterruptedException) {
break;
}
LOGGER.log(Level.SEVERE, null, th);
}
}
}
};
this.processingThread.start();
this.deadlockThread = new Thread(this.coreGroup, "deadlockThread") {
@Override
public void run() {
while (true) {
if (Thread.interrupted()) {
break;
}
try {
synchronized (this) {
while (!deadlockFlag) {
this.wait();
}
deadlockFlag = false;
}
} catch (Throwable th) {
if (th instanceof InterruptedException) {
break;
}
LOGGER.log(Level.SEVERE, null, th);
}
verifyDeadlock(false);
}
}
};
this.deadlockThread.start();
}
private GroupInfo createGroupInfo(String name, String user, int priority, int timetoIdleSeconds) {
synchronized (jobSet) {
if (!groupMap.containsKey(name)) {
GroupInfo gi = new GroupInfo(name, user, timetoIdleSeconds);
gi.setPriority(priority);
groupMap.put(gi.getGroupName(), gi);
return gi;
}
}
return null;
}
private void verifyDeadlock() {
verifyDeadlock(true);
}
private void verifyDeadlock(boolean request) {
if (request) {
synchronized (deadlockThread) {
deadlockFlag = true;
deadlockThread.notifyAll();
}
} else {
System.err.println("Verifying deadlock");
}
}
/**
* Returns pIds of jobs in decreasing priority
*
* @return
*/
private int[] getPIds() {
synchronized (jobSet) {
int[] ret = new int[jobSet.countRunning()];
Iterator<Integer> running = jobSet.getRunning();
int i = 0;
while (running.hasNext()) {
Integer id = running.next();
ProcessInfo pi = processMap.get(id);
if (pi != null) {
ret[i++] = pi.getPid();
} else {
ret[i++] = -1;
}
}
return ret;
}
}
private long getMaxPromisedMemory() {
synchronized (jobSet) {
long sum = 0;
for (ProcessInfo pi : processMap.values()) {
sum += pi.getJobInfo().getSubmitChannel().getRequest().getMaxRSS();
}
return sum;
}
}
private void cleanStalePeers() throws InterruptedException {
synchronized (jobSet) {
Iterator<Integer> it = jobSet.getQueue();
while (it.hasNext()) {
Integer id = it.next();
JobInfo ji = jobMap.get(id);
if (!ji.getSubmitChannel().ping()) {
it.remove();
removeFromJobMap(ji);
GroupInfo gi = groupMap.get(ji.getSubmitChannel().getRequest().getGroupName());
gi.getJobs().remove(id);
try {
ji.getSubmitChannel().close();
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
}
it = jobSet.getRunning();
while (it.hasNext()) {
Integer id = it.next();
ProcessInfo pi = processMap.get(id);
if (pi != null && !pi.getJobInfo().getSubmitChannel().ping()) {
try {
LinuxCommands.getInstance().killTree(pi.getPid());
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
}
}
}
private void refresh() throws IOException, InterruptedException {
synchronized (jobSet) {
if (closed) {
return;
}
cleanStalePeers();
updateNiceness();
long availableMemory = maxManagedRss - getMaxPromisedMemory();
checkPromises(availableMemory);
long freeRSS = LinuxCommands.getInstance().getSystemRSSFreeMemory();
if (availableMemory > freeRSS) {
availableMemory = freeRSS;
}
JobSet.QueueIterator it = jobSet.getQueue();
boolean dequeued = false;
while (it.hasNext()) {
Integer id = it.next();
JobInfo ji = jobMap.get(id);
if (ji.getSubmitChannel().getRequest().getMaxRSS() > availableMemory) {
break;
}
dequeued = true;
it.moveToRunning();
execute(id, ji);
availableMemory -= ji.getSubmitChannel().getRequest().getMaxRSS();
}
if (jobSet.countQueued() > 0 && !dequeued) {
verifyDeadlock();
}
int position = 0;
it = jobSet.getQueue();
while (it.hasNext()) {
position++;
Integer id = it.next();
JobInfo ji = jobMap.get(id);
if (position != ji.getPreviousQueuePosition()) {
ji.getSubmitChannel().sendEvent(Event.queued, position);
ji.setPreviousQueuePosition(position);
}
}
this.jobList = createJobList(false);
}
}
private void updateNiceness() throws IOException, InterruptedException {
updateNiceness(null);
}
private void updateNiceness(Integer pId) throws IOException, InterruptedException {
synchronized (jobSet) {
JobSet.RunningIterator running = jobSet.getRunning();
int i = 0;
while (running.hasNext()) {
Integer id = running.next();
ProcessInfo pi = processMap.get(id);
if (pi != null) {
if (pId == null || pi.getPid() == pId) {
pi.setNiceness(NicenessHandler.getInstance().getNiceness(i, jobSet.countRunning(), Config.getInstance().getProcessCfg().getNicenessRange()[0], Config.getInstance().getProcessCfg().getNicenessRange()[1]));
}
}
i++;
}
}
}
private long checkPromises(long availableMemory) throws IOException, InterruptedException {
synchronized (jobSet) {
long currentRSS = 0;
int[] pIds = getPIds();
if (pIds.length > 0) {
long[] treeRSSs = LinuxCommands.getInstance().getTreeRSS(pIds);
if (treeRSSs != null) {
int i = 0;
{
JobSet.RunningIterator running = jobSet.getRunning();
while (running.hasNext()) {
Integer id = running.next();
ProcessInfo pi = processMap.get(id);
long treeRSS = treeRSSs[i++];
currentRSS += treeRSS;
if (treeRSS != 0) {
if (treeRSS > pi.getMaxSeenRSS()) {
pi.setMaxSeenRSS(treeRSS);
}
if (pi.getMaxRSS() < treeRSS) {
boolean allowed = PromiseHandler.getInstance().promiseFailed(availableMemory, pi, treeRSS);
if (allowed) {
availableMemory = availableMemory + pi.getJobInfo().getSubmitChannel().getRequest().getMaxRSS() - treeRSS;
pi.setMaxRSS(treeRSS);
pi.setAllowed(true);
} else {
LinuxCommands.getInstance().killTree(pi.getPid());
}
}
}
}
}
}
}
return currentRSS;
}
}
public void submit(PeerChannel<SubmitInput> submitChannel) throws IOException, InterruptedException {
if (closed) {
throw new IllegalStateException("Instance is closed");
}
if (submitChannel == null) {
throw new IllegalArgumentException("Request info is required");
}
if (Config.getInstance().getSchedulerCfg().getMaxJobRSSBytes() > 0 && submitChannel.getRequest().getMaxRSS() > Config.getInstance().getSchedulerCfg().getMaxJobRSSBytes() || maxManagedRss < submitChannel.getRequest().getMaxRSS()) {
submitChannel.sendEvent(Event.exceed_global, Config.getInstance().getSchedulerCfg().getMaxJobRSSBytes());
submitChannel.sendEvent(Event.retcode, RetCode.ERROR.getCode());
submitChannel.close();
return;
}
long treeRSS = submitChannel.getRequest().getMaxRSS();
Integer parentId = submitChannel.getRequest().getParentId();
JobInfo parent = null;
while (parentId != null) {
JobInfo ji = jobMap.get(parentId);
if (ji == null) {
break;
}
if (parent == null) {
parent = ji;
}
treeRSS += ji.getSubmitChannel().getRequest().getMaxRSS();
parentId = ji.getSubmitChannel().getRequest().getParentId();
}
if (treeRSS > maxManagedRss) {
submitChannel.sendEvent(Event.exceed_tree, treeRSS);
submitChannel.sendEvent(Event.retcode, RetCode.ERROR.getCode());
submitChannel.close();
return;
}
if (parent != null) {
synchronized (parent) {
parent.setChildCount(parent.getChildCount() + 1);
}
}
if (submitChannel.getRequest().getGroupName() == null) {
submitChannel.getRequest().setGroupName(DEFAULT_GROUP_NAME);
}
int id = jobCounter.incrementAndGet();
synchronized (jobSet) {
GroupInfo gi = groupMap.get(submitChannel.getRequest().getGroupName());
if (gi == null) { // dynamic group
gi = createGroupInfo(submitChannel.getRequest().getGroupName(), submitChannel.getUser(), 0, Config.getInstance().getGroupCfg().getDynamicGroupIdleSeconds());
}
gi.getJobs().add(id);
JobInfo ji = new JobInfo(id, submitChannel);
jobMap.put(id, ji);
submitChannel.sendEvent(Event.id, id);
jobSet.queue(id, gi.getPriority(), gi.getGroupId());
submitChannel.sendEvent(Event.priority, gi.getPriority());
// refresh();
}
}
private String createJobList(boolean noHeaders) {
StringBuilder sb = new StringBuilder(200);
try {
if (!noHeaders) {
sb.append(ANSICode.CLEAR.getCode());
sb.append(ANSICode.MOVE_TO_TOP.getCode());
sb.append(ANSICode.BLACK.getCode());
sb.append(ANSICode.BG_GREEN.getCode());
sb.append(StringUtils.leftPad("ID", 8));
sb.append(" ");
sb.append(StringUtils.leftPad("PID", 8));
sb.append(" ");
sb.append(StringUtils.rightPad("GROUP", 8));
sb.append(" ");
sb.append(StringUtils.rightPad("USER", 8));
sb.append(" ");
sb.append(StringUtils.leftPad("PRIORITY", 8));
sb.append(" ");
sb.append(StringUtils.leftPad("QUEUE", 5));
sb.append(" ");
sb.append(StringUtils.leftPad("PID", 8));
sb.append(" ");
sb.append(StringUtils.leftPad("NICE", 4));
sb.append(" ");
sb.append(StringUtils.leftPad("PROM_RSS", 10));
sb.append(" ");
sb.append(StringUtils.leftPad("SEEN_RSS", 10));
sb.append(" ");
sb.append("CMD");
sb.append(ANSICode.END_OF_LINE.getCode());
sb.append(ANSICode.RESET.getCode());
} else {
ANSICode.setActive(false);
}
synchronized (jobSet) {
JobSet.RunningIterator runningIterator = jobSet.getRunning();
while (runningIterator.hasNext()) {
Integer id = runningIterator.next();
JobInfo ji = jobMap.get(id);
ProcessInfo pi = processMap.get(id);
GroupInfo gi = groupMap.get(ji.getSubmitChannel().getRequest().getGroupName());
sb.append("\n");
sb.append(ANSICode.NO_WRAP.getCode());
if (pi != null) {
if (!ji.getSubmitChannel().getRequest().isIdempotent()) {
sb.append(ANSICode.RED.getCode());
}
sb.append(StringUtils.leftPad(String.valueOf(id), 8));
sb.append(ANSICode.RESET.getCode());
sb.append(" ");
String pId;
if (ji.getSubmitChannel().getRequest().getParentId() != null) {
pId = String.valueOf(ji.getSubmitChannel().getRequest().getParentId());
} else {
pId = "";
}
sb.append(StringUtils.leftPad(pId, 8));
sb.append(" ");
sb.append(StringUtils.rightPad(String.valueOf(gi.getGroupName()), 8));
sb.append(" ");
sb.append(StringUtils.rightPad(ji.getSubmitChannel().getUser(), 8));
sb.append(" ");
sb.append(StringUtils.leftPad(String.valueOf(gi.getPriority()), 8));
sb.append(" ");
sb.append(StringUtils.leftPad("", 5));
sb.append(" ");
sb.append(StringUtils.leftPad(String.valueOf(pi.getPid()), 8));
sb.append(" ");
sb.append(StringUtils.leftPad(String.valueOf(pi.getNiceness()), 4));
sb.append(" ");
String[] mem = Miscellaneous.humanReadableByteCount(ji.getSubmitChannel().getRequest().getMaxRSS(), Config.getInstance().getuICfg().issIMemoryUnits()).split(" ");
sb.append(StringUtils.leftPad(mem[0], 6));
sb.append(" ");
sb.append(StringUtils.rightPad(mem[1], 3));
sb.append(" ");
if (pi.getMaxSeenRSS() > 0.9 * ji.getSubmitChannel().getRequest().getMaxRSS()) {
sb.append(ANSICode.RED.getCode());
}
mem = Miscellaneous.humanReadableByteCount(pi.getMaxSeenRSS(), Config.getInstance().getuICfg().issIMemoryUnits()).split(" ");
sb.append(StringUtils.leftPad(mem[0], 6));
sb.append(" ");
sb.append(StringUtils.rightPad(mem[1], 3));
sb.append(ANSICode.RESET.getCode());
sb.append(" ");
sb.append(Arrays.toString(ji.getSubmitChannel().getRequest().getCommand()));
sb.append(" ");
} else { // process not stated yet
if (!ji.getSubmitChannel().getRequest().isIdempotent()) {
sb.append(ANSICode.RED.getCode());
}
sb.append(StringUtils.leftPad(String.valueOf(id), 8));
sb.append(ANSICode.RESET.getCode());
sb.append(" ");
String pId;
if (ji.getSubmitChannel().getRequest().getParentId() != null) {
pId = String.valueOf(ji.getSubmitChannel().getRequest().getParentId());
} else {
pId = "";
}
sb.append(StringUtils.leftPad(pId, 8));
sb.append(" ");
sb.append(StringUtils.rightPad(String.valueOf(gi.getGroupName()), 8));
sb.append(" ");
sb.append(StringUtils.rightPad(ji.getSubmitChannel().getUser(), 8));
sb.append(" ");
sb.append(StringUtils.leftPad(String.valueOf(gi.getPriority()), 8));
sb.append(" ");
sb.append(StringUtils.leftPad("", 5));
sb.append(" ");
sb.append(StringUtils.leftPad("", 8));
sb.append(" ");
sb.append(StringUtils.leftPad("", 4));
sb.append(" ");
String[] mem = Miscellaneous.humanReadableByteCount(ji.getSubmitChannel().getRequest().getMaxRSS(), Config.getInstance().getuICfg().issIMemoryUnits()).split(" ");
sb.append(StringUtils.leftPad(mem[0], 6));
sb.append(" ");
sb.append(StringUtils.rightPad(mem[1], 3));
sb.append(" ");
sb.append(StringUtils.leftPad("", 10));
sb.append(" ");
sb.append(Arrays.toString(ji.getSubmitChannel().getRequest().getCommand()));
sb.append(" ");
}
sb.append(ANSICode.WRAP.getCode());
}
int position = 0;
JobSet.QueueIterator queueIterator = jobSet.getQueue();
while (queueIterator.hasNext()) {
position++;
Integer id = queueIterator.next();
JobInfo ji = jobMap.get(id);
GroupInfo gi = groupMap.get(ji.getSubmitChannel().getRequest().getGroupName());
sb.append("\n");
sb.append(ANSICode.NO_WRAP.getCode());
if (!ji.getSubmitChannel().getRequest().isIdempotent()) {
sb.append(ANSICode.RED.getCode());
} else {
sb.append(ANSICode.YELLOW.getCode());
}
sb.append(StringUtils.leftPad(String.valueOf(id), 8));
sb.append(ANSICode.YELLOW.getCode());
sb.append(" ");
String pId;
if (ji.getSubmitChannel().getRequest().getParentId() != null) {
pId = String.valueOf(ji.getSubmitChannel().getRequest().getParentId());
} else {
pId = "";
}
sb.append(StringUtils.leftPad(pId, 8));
sb.append(" ");
sb.append(StringUtils.rightPad(String.valueOf(ji.getSubmitChannel().getRequest().getGroupName()), 8));
sb.append(" ");
sb.append(StringUtils.rightPad(ji.getSubmitChannel().getUser(), 8));
sb.append(" ");
sb.append(StringUtils.leftPad(String.valueOf(gi.getPriority()), 8));
sb.append(" ");
sb.append(StringUtils.leftPad(String.valueOf(position), 5));
sb.append(" ");
sb.append(StringUtils.leftPad("", 8));
sb.append(" ");
sb.append(StringUtils.leftPad("", 4));
sb.append(" ");
String[] mem = Miscellaneous.humanReadableByteCount(ji.getSubmitChannel().getRequest().getMaxRSS(), Config.getInstance().getuICfg().issIMemoryUnits()).split(" ");
sb.append(StringUtils.leftPad(mem[0], 6));
sb.append(" ");
sb.append(StringUtils.rightPad(mem[1], 3));
sb.append(" ");
sb.append(StringUtils.leftPad("", 10));
sb.append(" ");
sb.append(Arrays.toString(ji.getSubmitChannel().getRequest().getCommand()));
sb.append(" ");
sb.append(ANSICode.RESET.getCode());
sb.append(ANSICode.WRAP.getCode());
}
}
} finally {
ANSICode.setActive(true);
}
return sb.toString();
}
public void listGroups(PeerChannel<Void> channel, boolean noHeaders) throws IOException, InterruptedException {
try {
if (!noHeaders) {
StringBuilder header = new StringBuilder(ANSICode.CLEAR.getCode());
header.append(ANSICode.MOVE_TO_TOP.getCode());
header.append(ANSICode.BLACK.getCode());
header.append(ANSICode.BG_GREEN.getCode());
header.append(StringUtils.rightPad("GROUP", 8));
header.append(" ");
header.append(StringUtils.rightPad("USER", 8));
header.append(" ");
header.append(StringUtils.leftPad("PRIORITY", 8));
header.append(" ");
header.append(StringUtils.leftPad("IDLE_TIME", 9));
header.append(" ");
header.append(StringUtils.leftPad("JOBS", 5));
header.append(ANSICode.END_OF_LINE.getCode());
header.append(ANSICode.RESET.getCode());
PeerChannel.println(channel.getStdoutOs(), header.toString());
} else {
ANSICode.setActive(false);
}
synchronized (jobSet) {
TreeSet<GroupInfo> groups = new TreeSet<>(groupMap.values());
for (GroupInfo gi : groups) {
StringBuilder line = new StringBuilder();
line.append(StringUtils.rightPad(String.valueOf(gi.getGroupName()), 8));
line.append(" ");
line.append(StringUtils.rightPad(gi.getUser(), 8));
line.append(" ");
line.append(StringUtils.leftPad(String.valueOf(gi.getPriority()), 8));
line.append(" ");
line.append(StringUtils.leftPad(String.valueOf(gi.getTimeToIdelSeconds()), 9));
line.append(" ");
line.append(StringUtils.leftPad(String.valueOf(gi.getJobs().size()), 5));
PeerChannel.println(channel.getStdoutOs(), line.toString());
}
}
} finally {
ANSICode.setActive(true);
channel.sendEvent(Event.retcode, 0);
channel.close();
}
}
public void listJobs(PeerChannel<Void> channel, boolean noHeaders) throws IOException, InterruptedException {
try {
if (noHeaders) {
PeerChannel.println(channel.getStdoutOs(), createJobList(true));
} else {
PeerChannel.println(channel.getStdoutOs(), jobList);
}
} finally {
channel.sendEvent(Event.retcode, 0);
channel.close();
}
}
public void cancel(PeerChannel<CancelInput> cancelChannel) throws IOException, InterruptedException {
try {
if (closed) {
throw new IllegalStateException("Instance is closed");
}
int id = cancelChannel.getRequest().getId();
synchronized (jobSet) {
JobSet.State state = jobSet.getState(id);
if (state == null) {
cancelChannel.log(ANSICode.RED, "job not found");
cancelChannel.sendEvent(Event.retcode, RetCode.ERROR.getCode());
} else if (state == JobSet.State.queued) {
JobInfo ji = jobMap.get(id);
if (ji != null) {
if (!cancelChannel.getUser().equals("root") && !cancelChannel.getUser().equals(ji.getSubmitChannel().getUser())) {
cancelChannel.log(ANSICode.RED, "user '" + cancelChannel.getUser() + "' is not allowed to cancel a job from user '" + ji.getSubmitChannel().getUser() + "'");
cancelChannel.sendEvent(Event.retcode, RetCode.ERROR.getCode());
return;
}
ji.getSubmitChannel().sendEvent(Event.cancelled, cancelChannel.getUser());
ji.getSubmitChannel().sendEvent(Event.retcode, RetCode.ERROR.getCode());
ji.getSubmitChannel().close();
cancelChannel.log(ANSICode.GREEN, "enqueued job sucessfully cancelled");
cancelChannel.sendEvent(Event.retcode, 0);
GroupInfo gi = groupMap.get(ji.getSubmitChannel().getRequest().getGroupName());
gi.getJobs().remove(id);
jobSet.remove(id);
removeFromJobMap(ji);
} else {
throw new AssertionError();
}
} else if (state == JobSet.State.running) {
ProcessInfo pi = processMap.get(id);
if (pi != null) {
if (!cancelChannel.getUser().equals("root") && !cancelChannel.getUser().equals(pi.getJobInfo().getSubmitChannel().getUser())) {
cancelChannel.log(ANSICode.RED, "user '" + cancelChannel.getUser() + "' is not allowed to cancel a job from user '" + pi.getJobInfo().getSubmitChannel().getUser() + "'");
cancelChannel.sendEvent(Event.retcode, RetCode.ERROR.getCode());
return;
}
pi.getJobInfo().getSubmitChannel().sendEvent(Event.cancelled, cancelChannel.getUser());
LinuxCommands.getInstance().killTree(pi.getPid());
cancelChannel.log(ANSICode.GREEN, "running job sucessfully cancelled");
cancelChannel.sendEvent(Event.retcode, 0);
}
}
}
} finally {
cancelChannel.close();
}
}
public void updateGroup(PeerChannel<GroupInput> channel) throws IOException {
try {
if (closed) {
throw new IllegalStateException("Instance is closed");
}
synchronized (jobSet) {
GroupInfo gi = groupMap.get(channel.getRequest().getGroupName());
if (gi == null) {
createGroupInfo(channel.getRequest().getGroupName(), channel.getUser(), channel.getRequest().getPriority(), channel.getRequest().getTimetoIdleSeconds());
channel.log(ANSICode.GREEN, "Group '" + channel.getRequest().getGroupName() + "' created successfully");
channel.sendEvent(Event.retcode, 0);
return;
} else if (channel.getRequest().isDelete()) {
if (!channel.getUser().equals("root") && !channel.getUser().equals(gi.getUser())) {
if (gi.getUser().equals("root")) {
channel.log(ANSICode.RED, "Group '" + channel.getRequest().getGroupName() + "' can only be updated by user 'root'");
} else {
channel.log(ANSICode.RED, "Group '" + channel.getRequest().getGroupName() + "' can only be updated by users 'root' and '" + gi.getUser() + "'");
}
channel.sendEvent(Event.retcode, RetCode.ERROR.getCode());
return;
}
if (gi.getJobs().isEmpty()) {
channel.log(ANSICode.GREEN, "Group '" + channel.getRequest().getGroupName() + "' deleted successfully");
groupMap.remove(channel.getRequest().getGroupName());
channel.sendEvent(Event.retcode, 0);
return;
} else {
channel.log(ANSICode.RED, "Group '" + channel.getRequest().getGroupName() + "' cannot be deleted, since it contains " + gi.getJobs().size() + " active jobs");
channel.sendEvent(Event.retcode, RetCode.ERROR.getCode());
return;
}
}
int newPriority = channel.getRequest().getPriority();
if (newPriority != gi.getPriority()) {
synchronized (gi.getJobs()) {
for (Integer id : gi.getJobs()) {
jobSet.setPriority(id, newPriority, gi.getGroupId());
JobInfo ji = jobMap.get(id);
ji.getSubmitChannel().sendEvent(Event.priority, newPriority);
}
}
gi.setPriority(newPriority);
channel.log(ANSICode.GREEN, "Group '" + channel.getRequest().getGroupName() + "' priority updated successfully");
}
int newTimetoIdleSeconds = channel.getRequest().getTimetoIdleSeconds();
if (newTimetoIdleSeconds != gi.getTimeToIdelSeconds()) {
gi.setTimeToIdelSeconds(newTimetoIdleSeconds);
channel.log(ANSICode.GREEN, "Group '" + channel.getRequest().getGroupName() + "' time-to-idle updated successfully");
}
channel.sendEvent(Event.retcode, 0);
}
} finally {
channel.close();
}
}
private void removeFromJobMap(JobInfo jobInfo) {
jobMap.remove(jobInfo.getId());
Integer parentId = jobInfo.getSubmitChannel().getRequest().getParentId();
if (parentId != null) {
JobInfo parent = jobMap.get(parentId);
if (parent != null) {
synchronized (parent) {
parent.setChildCount(parent.getChildCount() - 1);
}
}
}
}
private void execute(final int id, final JobInfo ji) {
if (ji == null) {
throw new IllegalArgumentException("Id is required");
}
Thread t = new Thread(this.processGroup, "scheduled process " + id) {
@Override
public void run() {
String[] cmd = ji.getSubmitChannel().getRequest().getCommand();
if (Scheduler.this.runningUser.equals("root")) {
cmd = LinuxCommands.getInstance().getRunAsCommand(ji.getSubmitChannel().getUser(), cmd);
}
cmd = LinuxCommands.getInstance().decorateWithCPUAffinity(cmd, Config.getInstance().getProcessCfg().getCpuAfinity());
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.environment().clear();
pb.directory(ji.getSubmitChannel().getRequest().getWorkingDirectory());
if (ji.getSubmitChannel().getRequest().getEnvironment() != null) {
pb.environment().putAll(ji.getSubmitChannel().getRequest().getEnvironment());
}
pb.environment().put(Environment.WAVA_JOB_ID, String.valueOf(id));
ProcessInfo pi;
Process process;
int pId;
try {
try {
process = pb.start();
pId = Miscellaneous.getUnixId(process);
ji.getSubmitChannel().sendEvent(Event.running, pId);
pi = new ProcessInfo(ji, pId);
synchronized (jobSet) {
processMap.put(ji.getId(), pi);
}
updateNiceness(pId);
} catch (Exception ex) {
ji.getSubmitChannel().sendEvent(Event.error, JsonCodec.getInstance().transform(Miscellaneous.getStrackTrace(ex)));
ji.getSubmitChannel().sendEvent(Event.retcode, RetCode.ERROR.getCode());
return;
}
Thread stoutReaderThread = Miscellaneous.pipeAsynchronously(process.getInputStream(), (ErrorHandler) null, true, ji.getSubmitChannel().getStdoutOs());
stoutReaderThread.setName("stdout-pid-" + pId);
Thread sterrReaderThread = Miscellaneous.pipeAsynchronously(process.getErrorStream(), (ErrorHandler) null, true, ji.getSubmitChannel().getStderrOs());
sterrReaderThread.setName("stderr-pid-" + pId);
try {
int code = process.waitFor();
ji.getSubmitChannel().sendEvent(Event.maxrss, pi.getMaxSeenRSS());
ji.getSubmitChannel().sendEvent(Event.retcode, code);
} catch (InterruptedException ex) {
try {
LinuxCommands.getInstance().killTree(pId);
} catch (Throwable th) {
LOGGER.log(Level.SEVERE, th.getMessage());
}
// stoutReaderThread.interrupt();
// sterrReaderThread.interrupt();
// process.destroy();
// channel.log(Event.interrupted, ex.getMessage());
// return;
} finally {
try {
stoutReaderThread.join();
sterrReaderThread.join();
} catch (Throwable th) {
LOGGER.log(Level.SEVERE, th.getMessage());
}
}
} finally {
try {
ji.getSubmitChannel().close();
synchronized (jobSet) {
jobSet.remove(id);
removeFromJobMap(ji);
processMap.remove(id);
final GroupInfo gi = groupMap.get(ji.getSubmitChannel().getRequest().getGroupName());
gi.getJobs().remove(id);
if (gi.getJobs().isEmpty()) {
if (gi.getTimeToIdelSeconds() == 0) {
groupMap.remove(gi.getGroupName());
} else if (gi.getTimeToIdelSeconds() > 0) {
Thread t = new Thread(coreGroup, "group-" + gi.getGroupName() + " idle thread") {
@Override
public void run() {
try {
Thread.sleep(1000 * gi.getTimeToIdelSeconds());
synchronized (jobSet) {
if (gi.getJobs().isEmpty()) {
groupMap.remove(gi.getGroupName());
}
}
} catch (Throwable th) {
if (th instanceof InterruptedException) {
return;
}
Logger.getLogger(Scheduler.class.getName()).log(Level.SEVERE, null, th);
}
}
};
t.setDaemon(true);
t.start();
}
}
}
// refresh();
} catch (Throwable th) {
LOGGER.log(Level.SEVERE, th.getMessage(), th);
}
}
}
};
t.start();
}
public boolean close(PeerChannel<Void> channel) throws IOException {
if (!channel.getUser().equals("root") && !channel.getUser().equals(runningUser)) {
channel.log(ANSICode.RED, "user '" + channel.getUser() + "' is not allowed to stop the core scheduler process");
channel.sendEvent(Event.retcode, RetCode.ERROR.getCode());
channel.close();
return false;
}
channel.log(ANSICode.GREEN, "Stopping scheduler process ...");
channel.sendEvent(Event.retcode, 0);
channel.close();
synchronized (jobSet) {
this.closed = true;
this.coreGroup.interrupt();
Iterator<Integer> it = jobSet.getQueue();
while (it.hasNext()) {
Integer id = it.next();
JobInfo ji = jobMap.get(id);
it.remove();
removeFromJobMap(ji);
GroupInfo gi = groupMap.get(ji.getSubmitChannel().getRequest().getGroupName());
gi.getJobs().remove(id);
try {
ji.getSubmitChannel().sendEvent(Event.shutdown, runningUser);
ji.getSubmitChannel().sendEvent(Event.retcode, RetCode.ERROR.getCode());
ji.getSubmitChannel().close();
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
it = jobSet.getRunning();
while (it.hasNext()) {
Integer id = it.next();
ProcessInfo pi = processMap.get(id);
pi.getJobInfo().getSubmitChannel().sendEvent(Event.shutdown, runningUser);
try {
LinuxCommands.getInstance().killTree(pi.getPid());
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
}
return true;
}
public class GroupInfo implements Comparable<GroupInfo> {
private final String groupName;
private final int groupId;
private final String user;
private final Set<Integer> jobs = Collections.synchronizedNavigableSet(new TreeSet<Integer>());
private int timeToIdelSeconds;
private int priority;
public GroupInfo(String groupName, String user, int timeToIdelSeconds) {
this.groupName = groupName;
this.groupId = groupCounter.incrementAndGet();
this.user = user;
this.timeToIdelSeconds = timeToIdelSeconds;
}
public String getGroupName() {
return groupName;
}
public int getGroupId() {
return groupId;
}
public String getUser() {
return user;
}
public Set<Integer> getJobs() {
return jobs;
}
public void setTimeToIdelSeconds(int timeToIdelSeconds) {
this.timeToIdelSeconds = timeToIdelSeconds;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public int getTimeToIdelSeconds() {
return timeToIdelSeconds;
}
@Override
public int compareTo(GroupInfo o) {
if (o == null) {
return 1;
}
int ret = Integer.compare(priority, o.getPriority());
if (ret == 0) {
ret = Integer.compare(groupId, o.getGroupId());
}
return ret;
}
}
public class JobInfo {
private final int id;
private final PeerChannel<SubmitInput> submitChannel;
private int previousQueuePosition;
private volatile int childCount;
public JobInfo(int id, PeerChannel<SubmitInput> submitChannel) throws IOException, InterruptedException {
this.id = id;
this.submitChannel = submitChannel;
}
public int getPreviousQueuePosition() {
return previousQueuePosition;
}
public void setPreviousQueuePosition(int previousQueuePosition) {
this.previousQueuePosition = previousQueuePosition;
}
public int getId() {
return id;
}
public PeerChannel<SubmitInput> getSubmitChannel() {
return submitChannel;
}
public int getChildCount() {
return childCount;
}
public void setChildCount(int childCount) {
this.childCount = childCount;
}
}
public class ProcessInfo {
private final JobInfo jobInfo;
private final int pId;
private long maxRSS;
private long maxSeenRSS;
private int niceness = Integer.MAX_VALUE;
private boolean allowed;
public ProcessInfo(JobInfo jobInfo, int pId) {
this.jobInfo = jobInfo;
this.pId = pId;
this.maxRSS = jobInfo.getSubmitChannel().getRequest().getMaxRSS();
}
public int getPid() {
return pId;
}
public long getMaxSeenRSS() {
return maxSeenRSS;
}
public void setMaxSeenRSS(long maxSeenRSS) {
this.maxSeenRSS = maxSeenRSS;
}
public int getNiceness() {
return niceness;
}
public JobInfo getJobInfo() {
return jobInfo;
}
public int getpId() {
return pId;
}
public long getMaxRSS() {
return maxRSS;
}
public void setMaxRSS(long maxRSS) {
this.maxRSS = maxRSS;
}
public boolean isAllowed() {
return allowed;
}
public void setAllowed(boolean allowed) {
this.allowed = allowed;
}
public void setNiceness(int niceness) throws IOException, InterruptedException {
if (niceness != this.niceness) {
LinuxCommands.getInstance().setNiceness(pId, niceness);
jobInfo.getSubmitChannel().sendEvent(Event.niceness, niceness);
this.niceness = niceness;
}
}
}
} |
package ucar.nc2.iosp.grid;
import ucar.ma2.*;
import ucar.nc2.*;
import ucar.nc2.dt.fmr.FmrcCoordSys;
import ucar.nc2.iosp.AbstractIOServiceProvider;
import ucar.nc2.util.CancelTask;
import ucar.unidata.io.RandomAccessFile;
import ucar.grid.GridIndex;
import ucar.grid.GridRecord;
import java.io.IOException;
import java.util.List;
/**
* An IOSP for Gempak Grid data
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
public abstract class GridServiceProvider extends AbstractIOServiceProvider {
/** FMRC coordinate system */
protected FmrcCoordSys fmrcCoordSys;
/** The netCDF file */
protected NetcdfFile ncfile;
/** the file we are reading */
protected RandomAccessFile raf;
/** should file be synced or extended */
protected boolean syncExtend = false;
/* to use or not to use cache first */
protected static boolean alwaysInCache = false;
/** place to store debug stuff */
protected StringBuilder parseInfo = new StringBuilder();
/** debug flags */
protected static boolean debugOpen = false,
debugMissing = false,
debugMissingDetails = false,
debugProj = false,
debugTiming = false,
debugVert = false;
/** flag for using maximal coordinate system */
static public boolean useMaximalCoordSys = false;
/**
* Set whether to use the maximal coordinate system or not
*
* @param b true to use
*/
static public void useMaximalCoordSys(boolean b) {
useMaximalCoordSys = b;
}
/**
* Set the debug flags
*
* @param debugFlag debug flags
*/
static public void setDebugFlags(ucar.nc2.util.DebugFlags debugFlag) {
debugOpen = debugFlag.isSet("Grid/open");
debugMissing = debugFlag.isSet("Grid/missing");
debugMissingDetails = debugFlag.isSet("Grid/missingDetails");
debugProj = debugFlag.isSet("Grid/projection");
debugVert = debugFlag.isSet("Grid/vertical");
debugTiming = debugFlag.isSet("Grid/timing");
}
/**
* Open the index and create the netCDF file from that
*
* @param index GridIndex to use
* @param cancelTask cancel task
*
* @throws IOException problem reading the file
*/
protected abstract void open(GridIndex index, CancelTask cancelTask)
throws IOException;
/**
* Open the service provider for reading.
* @param raf file to read from
* @param ncfile netCDF file we are writing to (memory)
* @param cancelTask task for cancelling
*
* @throws IOException problem reading file
*/
public void open(RandomAccessFile raf, NetcdfFile ncfile,
CancelTask cancelTask)
throws IOException {
this.raf = raf;
this.ncfile = ncfile;
}
/**
* Close this IOSP
*
* @throws IOException problem closing file
*/
public void close() throws IOException {
raf.close();
}
/**
* Sync and extend
*
* @return syncExtend
*/
public boolean syncExtend() {
return syncExtend;
}
/**
* Sync and extend
*
* @return syncExtend
*/
public void setSyncExtend( boolean se ) {
syncExtend = se;
}
/**
* alwaysInCache
*
* @return alwaysInCache
*/
public boolean alwaysInCache() {
return alwaysInCache;
}
/**
* alwaysInCache
*
* @param aic
*/
public void setAlwaysInCache( boolean aic ) {
alwaysInCache = aic;
}
/**
* Get the detail information
*
* @return the detail info
*/
public String getDetailInfo() {
return parseInfo.toString();
}
/**
* Send an IOSP message
*
* @param special isn't that special?
*/
public Object sendIospMessage( Object special) {
if (special instanceof FmrcCoordSys) {
fmrcCoordSys = (FmrcCoordSys) special;
}
return null;
}
/**
* Read the data for the variable
* @param v2 Variable to read
* @param section section infomation
* @return Array of data
*
* @throws IOException problem reading from file
* @throws InvalidRangeException invalid Range
*/
public Array readData(Variable v2, Section section)
throws IOException, InvalidRangeException {
long start = System.currentTimeMillis();
Array dataArray = Array.factory(DataType.FLOAT,
section.getShape());
GridVariable pv = (GridVariable) v2.getSPobject();
int count = 0;
Range timeRange = section.getRange(count++);
Range levRange = pv.hasVert()
? section.getRange(count++)
: null;
Range yRange = section.getRange(count++);
Range xRange = section.getRange(count);
IndexIterator ii = dataArray.getIndexIteratorFast();
// loop over time
for (int timeIdx = timeRange.first(); timeIdx <= timeRange.last();
timeIdx += timeRange.stride()) {
if (pv.hasVert()) {
readLevel(v2, timeIdx, levRange, yRange, xRange, ii);
} else {
readXY(v2, timeIdx, 0, yRange, xRange, ii);
}
}
if (debugTiming) {
long took = System.currentTimeMillis() - start;
System.out.println(" read data took=" + took + " msec ");
}
return dataArray;
}
// loop over level
/**
* Read a level
*
* @param v2 variable to put the data into
* @param timeIdx time index
* @param levelRange level range
* @param yRange x range
* @param xRange y range
* @param ii index iterator
*
* @throws IOException problem reading the file
* @throws InvalidRangeException invalid range
*/
private void readLevel(Variable v2, int timeIdx, Range levelRange,
Range yRange, Range xRange, IndexIterator ii)
throws IOException, InvalidRangeException {
for (int levIdx = levelRange.first(); levIdx <= levelRange.last();
levIdx += levelRange.stride()) {
readXY(v2, timeIdx, levIdx, yRange, xRange, ii);
}
}
/**
* read one product
*
* @param v2 variable to put the data into
* @param timeIdx time index
* @param levIdx level index
* @param yRange x range
* @param xRange y range
* @param ii index iterator
*
* @throws IOException problem reading the file
* @throws InvalidRangeException invalid range
*/
private void readXY(Variable v2, int timeIdx, int levIdx, Range yRange,
Range xRange, IndexIterator ii)
throws IOException, InvalidRangeException {
Attribute att = v2.findAttribute("missing_value");
float missing_value = (att == null)
? -9999.0f
: att.getNumericValue()
.floatValue();
GridVariable pv = (GridVariable) v2.getSPobject();
GridHorizCoordSys hsys = pv.getHorizCoordSys();
int nx = hsys.getNx();
GridRecord record = pv.findRecord(timeIdx, levIdx);
if (record == null) {
int xyCount = yRange.length() * xRange.length();
for (int j = 0; j < xyCount; j++) {
ii.setFloatNext(missing_value);
}
return;
}
// otherwise read it
float[] data;
//try {
data = _readData(record);
//} catch (Exception e) {
// e.printStackTrace();
// return;
for (int y = yRange.first(); y <= yRange.last();
y += yRange.stride()) {
for (int x = xRange.first(); x <= xRange.last();
x += xRange.stride()) {
int index = y * nx + x;
ii.setFloatNext(data[index]);
}
}
}
/**
* Is this XY level missing?
*
* @param v2 Variable
* @param timeIdx time index
* @param levIdx level index
*
* @return true if missing
*
* @throws InvalidRangeException invalid range
*/
private boolean isMissingXY(Variable v2, int timeIdx, int levIdx)
throws InvalidRangeException {
GridVariable pv = (GridVariable) v2.getSPobject();
if (null == pv) System.out.println("HEY");
if ((timeIdx < 0) || (timeIdx >= pv.getNTimes())) {
throw new InvalidRangeException("timeIdx=" + timeIdx);
}
if ((levIdx < 0) || (levIdx >= pv.getVertNlevels())) {
throw new InvalidRangeException("levIdx=" + levIdx);
}
return (null == pv.findRecord(timeIdx, levIdx));
}
/**
* Read the data for this GridRecord
*
* @param gr grid identifier
*
* @return the data (or null)
*
* @throws IOException problem reading the data
*/
protected abstract float[] _readData(GridRecord gr) throws IOException;
} // end GribServiceProvider |
package org.voovan.http.message;
import org.voovan.http.message.packet.Cookie;
import org.voovan.http.message.packet.Part;
import org.voovan.tools.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.Map.Entry;
public class HttpParser {
private static final String HTTP_PROTOCOL = "HTTP/";
private static final String FL_METHOD = "FL_Method";
private static final String FL_PATH = "FL_Path";
private static final String FL_PROTOCOL = "FL_Protocol";
private static final String FL_VERSION = "FL_Version";
private static final String FL_STATUS = "FL_Status";
private static final String FL_STATUSCODE = "FL_StatusCode";
private static final String FL_QUERY_STRING = "FL_QueryString";
private static final String HEAD_CONTENT_ENCODING = "Content-Encoding";
private static final String HEAD_CONTENT_TYPE = "Content-Type";
private static final String HEAD_TRANSFER_ENCODING = "Transfer-Encoding";
private static final String HEAD_CONTENT_LENGTH = "Content-Length";
private static final String HEAD_COOKIE = "Cookie";
private static final String BODY_PARTS = "Body_Parts";
private static final String BODY_VALUE = "Body_Value";
private static final String BODY_FILE = "Body_File";
private HttpParser(){
}
/**
*
* http
* @param protocolLine
* Http
* @throws UnsupportedEncodingException
*/
private static Map<String, Object> parseProtocol(String protocolLine) throws UnsupportedEncodingException{
Map<String, Object> protocol = new HashMap<String, Object>();
String[] lineSplit = protocolLine.split(" ");
if(protocolLine.indexOf(HTTP_PROTOCOL) > 0){
protocol.put(FL_METHOD, lineSplit[0]);
String[] pathSplit = lineSplit[1].split("\\?");
protocol.put(FL_PATH, pathSplit[0]);
if(pathSplit.length==2){
protocol.put(FL_QUERY_STRING, pathSplit[1]);
}
String[] protocolSplit= lineSplit[2].split("/");
protocol.put(FL_PROTOCOL, protocolSplit[0]);
protocol.put(FL_VERSION, protocolSplit[1]);
}else if(protocolLine.indexOf(HTTP_PROTOCOL)==0){
String[] protocolSplit= lineSplit[0].split("/");
protocol.put(FL_PROTOCOL, protocolSplit[0]);
protocol.put(FL_VERSION, protocolSplit[1]);
protocol.put(FL_STATUS, lineSplit[1]);
String statusCode = "";
for(int i=2;i<lineSplit.length;i++){
statusCode += lineSplit[i]+" ";
}
statusCode = TString.removeSuffix(statusCode);
protocol.put(FL_STATUSCODE, statusCode);
}
return protocol;
}
/**
* HTTP Header
* @param propertyLine
* Http
* @return
*/
private static Map<String,String> parsePropertyLine(String propertyLine){
Map<String,String> property = new HashMap<String, String>();
String[] propertySplit = propertyLine.split(": ");
if(propertySplit.length==2){
String propertyName = propertySplit[0];
String properyValue = propertySplit[1];
property.put(propertyName, properyValue);
}
return property;
}
/**
* Map
* @param str
*
* @return Map
*/
public static Map<String, String> getEqualMap(String str){
Map<String, String> equalMap = new HashMap<String, String>();
String[] searchedStrings = TString.searchByRegex(str,"([^ ;,]+=[^ ;,]+)");
for(String groupString : searchedStrings){
// split
String[] equalStrings = new String[2];
int equalCharIndex= groupString.indexOf("=");
equalStrings[0] = groupString.substring(0,equalCharIndex);
equalStrings[1] = groupString.substring(equalCharIndex+1,groupString.length());
if(equalStrings.length==2){
String key = equalStrings[0];
String value = equalStrings[1];
if(value.startsWith("\"") && value.endsWith("\"")){
value = value.substring(1,value.length()-1);
}
equalMap.put(key, value);
}
}
return equalMap;
}
/**
* HTTP
* Content-Type: multipart/form-data; boundary=ujjLiiJBznFt70fG1F4EUCkIupn7H4tzm
* boundary.
* :getPerprotyEqualValue(packetMap,"Content-Type","boundary")ujjLiiJBznFt70fG1F4EUCkIupn7H4tzm
* @param propertyName
* @param valueName
* @return
*/
private static String getPerprotyEqualValue(Map<String,Object> packetMap,String propertyName,String valueName){
Object propertyValueObj = packetMap.get(propertyName);
if(propertyValueObj == null){
return null;
}
String propertyValue = propertyValueObj.toString();
Map<String, String> equalMap = getEqualMap(propertyValue);
return equalMap.get(valueName);
}
/**
* Cookie
* @param packetMap MAp
* @param cookieLine Http Cookie
*/
@SuppressWarnings("unchecked")
private static void parseCookie(Map<String, Object> packetMap,String cookieLine){
if(!packetMap.containsKey(HEAD_COOKIE)){
packetMap.put(HEAD_COOKIE, new ArrayList<Map<String, String>>());
}
List<Map<String, String>> cookies = (List<Map<String, String>>) packetMap.get(HEAD_COOKIE);
// Cookie
Map<String, String>cookieMap = getEqualMap(cookieLine);
// response cookie cookie
if(cookieLine.contains("Set-Cookie")){
// cookie
if(cookieLine.toLowerCase().contains("httponly")){
cookieMap.put("httponly", "");
}
if(cookieLine.toLowerCase().contains("secure")){
cookieMap.put("secure", "");
}
cookies.add(cookieMap);
}
// request cookie cookie
else if(cookieLine.contains(HEAD_COOKIE)){
for(Entry<String,String> cookieMapEntry: cookieMap.entrySet()){
HashMap<String, String> cookieOneMap = new HashMap<String, String>();
cookieOneMap.put(cookieMapEntry.getKey(), cookieMapEntry.getValue());
cookies.add(cookieOneMap);
}
}
}
/**
* body
* GZIP ,,
* @param packetMap
* @param contentBytes
* @return
* @throws IOException
*/
private static byte[] dealBodyContent(Map<String, Object> packetMap,byte[] contentBytes) throws IOException{
byte[] bytesValue;
if(contentBytes.length == 0 ){
return contentBytes;
}
// GZip
boolean isGZip = packetMap.get(HEAD_CONTENT_ENCODING)==null ? false : packetMap.get(HEAD_CONTENT_ENCODING).toString().contains("gzip");
// GZip
if(isGZip && contentBytes.length>0){
bytesValue = TZip.decodeGZip(contentBytes);
} else {
bytesValue = contentBytes;
}
return TObject.nullDefault(bytesValue,new byte[0]);
}
/**
* HTTP
* Map ,:
* 1.protocol key/value
* 2.header key/value
* 3.cookie List[Map[String,String]]
* 3.part List[Map[Stirng,Object]](, HTTP )
* 5.body key=BODY_VALUE Map
* @param byteBufferChannel
* @param timeOut
* @return Map
* @throws IOException IO
*/
public static Map<String, Object> parser(ByteBufferChannel byteBufferChannel, int timeOut) throws IOException{
Map<String, Object> packetMap = new HashMap<String, Object>();
int headerLength = 0;
boolean isBodyConent = false;
int lineNum = 0;
//HTTP
for(String currentLine = byteBufferChannel.readLine();
currentLine!=null;
currentLine = byteBufferChannel.readLine()){
currentLine = currentLine.trim();
lineNum++;
if(currentLine.isEmpty()){
isBodyConent = true;
}
// HTTP
if(!isBodyConent && currentLine.contains("HTTP") && lineNum==1){
packetMap.putAll(parseProtocol(currentLine));
}
// cookie header
if(!isBodyConent){
currentLine = fixHeaderLine(currentLine);
if(currentLine.contains(HEAD_COOKIE)){
parseCookie(packetMap,currentLine);
}else{
packetMap.putAll(parsePropertyLine(currentLine));
}
}
// HTTP body
if(isBodyConent){
String contentType =packetMap.get(HEAD_CONTENT_TYPE)==null ? "" : packetMap.get(HEAD_CONTENT_TYPE).toString();
String transferEncoding = packetMap.get(HEAD_TRANSFER_ENCODING)==null ? "" : packetMap.get(HEAD_TRANSFER_ENCODING).toString();
//1. HTTP POST body part
if(contentType.contains("multipart/form-data")){
// Part list
List<Map<String, Object>> bodyPartList = new ArrayList<Map<String, Object>>();
//boundary part
String boundary = "--" + getPerprotyEqualValue(packetMap, HEAD_CONTENT_TYPE, "boundary");
ByteBuffer boundaryEnd = ByteBuffer.allocate(2);
while(true) {
if (!byteBufferChannel.waitData(boundary.getBytes(), timeOut)) {
throw new IOException("Http Parser read data error");
}
int index = byteBufferChannel.indexOf(boundary.getBytes("UTF-8"));
// boundary
byteBufferChannel.shrink((index + boundary.length()));
// boundary
boundaryEnd.clear();
byteBufferChannel.readHead(boundaryEnd);
// boundary , "--"
if (Arrays.equals(boundaryEnd.array(), "--".getBytes())) {
byteBufferChannel.shrink(2);
break;
}
byte[] mark = "\r\n\r\n".getBytes();
if (!byteBufferChannel.waitData(mark, timeOut)) {
throw new IOException("Http Parser read data error");
}
int partHeadEndIndex = byteBufferChannel.indexOf(mark);
//Part
ByteBuffer partHeadBuffer = TByteBuffer.allocateDirect(partHeadEndIndex + 4);
byteBufferChannel.readHead(partHeadBuffer);
// Bytebufer
ByteBufferChannel partByteBufferChannel = new ByteBufferChannel(partHeadEndIndex + 4);
partByteBufferChannel.writeEnd(partHeadBuffer);
Map<String, Object> partMap = parser(partByteBufferChannel, timeOut);
TByteBuffer.release(partHeadBuffer);
partByteBufferChannel.release();
String fileName = getPerprotyEqualValue(partMap, "Content-Disposition", "filename");
// Part
// index
index = -1;
if (fileName == null) {
if (!byteBufferChannel.waitData(boundary.getBytes(), timeOut)) {
throw new IOException("Http Parser read data error");
}
index = byteBufferChannel.indexOf(boundary.getBytes("UTF-8"));
ByteBuffer bodyByteBuffer = ByteBuffer.allocate(index - 2);
int readSize = byteBufferChannel.readHead(bodyByteBuffer);
index = index - readSize;
partMap.put(BODY_VALUE, bodyByteBuffer.array());
} else {
String fileExtName = TFile.getFileExtension(fileName);
fileExtName = fileExtName.equals("") ? ".tmp" : fileExtName;
String localFileName = TFile.assemblyPath(TFile.getTemporaryPath(),
"dd.webserver",
"upload",
"VOOVAN_" + System.currentTimeMillis() + "." + fileExtName);
while (byteBufferChannel.waitData(boundary.getBytes(), timeOut)){
index = byteBufferChannel.indexOf(boundary.getBytes("UTF-8"));
int length = index == -1 ? byteBufferChannel.size() : (index - 2);
if(index > 0 ) {
byteBufferChannel.saveToFile(localFileName, index - 2);
break;
}
}
if(index == -1){
new File(localFileName).delete();
throw new IOException("Http Parser read data error");
}else{
partMap.remove(BODY_VALUE);
partMap.put(BODY_FILE, localFileName.getBytes());
}
}
//bodyPartList
bodyPartList.add(partMap);
}
// part list packetMap
packetMap.put(BODY_PARTS, bodyPartList);
}
//2. HTTP body chunked
else if("chunked".equals(transferEncoding)){
ByteBufferChannel chunkedByteBufferChannel = new ByteBufferChannel(3);
String chunkedLengthLine = "";
while(chunkedLengthLine!=null){
if(!byteBufferChannel.waitData("\r\n".getBytes(), timeOut)){
throw new IOException("Http Parser read data error");
}
String chunkedLengthLine1 = byteBufferChannel.readLine();
chunkedLengthLine = chunkedLengthLine1.trim();
if("0".equals(chunkedLengthLine)){
break;
}
if(chunkedLengthLine.isEmpty()){
continue;
}
int chunkedLength = 0;
//chunked
try {
chunkedLength = Integer.parseInt(chunkedLengthLine, 16);
}catch(Exception e){
e.printStackTrace();
break;
}
if(!byteBufferChannel.waitData(chunkedLength, timeOut)){
throw new IOException("Http Parser read data error");
}
int readSize = 0;
if(chunkedLength > 0) {
//chunked
ByteBuffer byteBuffer = TByteBuffer.allocateDirect(chunkedLength);
readSize = byteBufferChannel.readHead(byteBuffer);
if(readSize != chunkedLength){
throw new IOException("Http Parser read chunked data error");
}
chunkedByteBufferChannel.writeEnd(byteBuffer);
TByteBuffer.release(byteBuffer);
}
byteBufferChannel.shrink(2);
}
byte[] value = dealBodyContent(packetMap, chunkedByteBufferChannel.array());
chunkedByteBufferChannel.release();
packetMap.put(BODY_VALUE, value);
byteBufferChannel.shrink(2);
}
//3. HTTP() Content-Length , body
else if(packetMap.containsKey(HEAD_CONTENT_LENGTH)){
int contentLength = Integer.parseInt(packetMap.get(HEAD_CONTENT_LENGTH).toString());
if(!byteBufferChannel.waitData(contentLength, timeOut)){
throw new IOException("Http Parser read data error");
}
ByteBuffer byteBuffer = ByteBuffer.allocate(contentLength);
byteBufferChannel.readHead(byteBuffer);
byte[] contentBytes = byteBuffer.array();
byte[] value = dealBodyContent(packetMap, contentBytes);
packetMap.put(BODY_VALUE, value);
}
else if(packetMap.get(BODY_VALUE)==null || packetMap.get(BODY_VALUE).toString().isEmpty()){
byte[] contentBytes = byteBufferChannel.array();
if(contentBytes!=null && contentBytes.length>0){
byte[] value = dealBodyContent(packetMap, contentBytes);
packetMap.put(BODY_VALUE, value);
}
}
break;
}else{
headerLength = headerLength+currentLine.length()+2;
}
}
return packetMap;
}
/**
* HttpRequest
* @param byteBufferChannel
* @param timeOut
* @return
* @throws IOException IO
*/
@SuppressWarnings("unchecked")
public static Request parseRequest(ByteBufferChannel byteBufferChannel, int timeOut) throws IOException{
Map<String, Object> parsedPacket = parser(byteBufferChannel, timeOut);
//Map,
if(parsedPacket==null || parsedPacket.isEmpty()){
return null;
}
Request request = new Request();
Set<Entry<String, Object>> parsedItems= parsedPacket.entrySet();
for(Entry<String, Object> parsedPacketEntry: parsedItems){
String key = parsedPacketEntry.getKey();
switch (key) {
case FL_METHOD:
request.protocol().setMethod(parsedPacketEntry.getValue().toString());
break;
case FL_PROTOCOL:
request.protocol().setProtocol(parsedPacketEntry.getValue().toString());
break;
case FL_QUERY_STRING:
request.protocol().setQueryString(parsedPacketEntry.getValue().toString());
break;
case FL_VERSION:
request.protocol().setVersion(Float.valueOf(parsedPacketEntry.getValue().toString()));
break;
case FL_PATH:
request.protocol().setPath(parsedPacketEntry.getValue().toString());
break;
case HEAD_COOKIE:
List<Map<String, String>> cookieMap = (List<Map<String, String>>)parsedPacket.get(HEAD_COOKIE);
// Cookie, Cookie
for(Map<String,String> cookieMapItem : cookieMap){
Cookie cookie = Cookie.buildCookie(cookieMapItem);
request.cookies().add(cookie);
}
cookieMap.clear();
break;
case BODY_VALUE:
byte[] value = (byte[])(parsedPacketEntry.getValue());
request.body().write(value);
break;
case BODY_PARTS:
List<Map<String, Object>> parsedParts = (List<Map<String, Object>>)(parsedPacketEntry.getValue());
// part List, Part
for(Map<String, Object> parsedPartMap : parsedParts){
Part part = new Part();
// part Map, Part
for(Entry<String, Object> parsedPartMapItem : parsedPartMap.entrySet()){
// Value body
if(parsedPartMapItem.getKey().equals(BODY_VALUE)){
part.body().changeToBytes((byte[])parsedPartMapItem.getValue());
} if(parsedPartMapItem.getKey().equals(BODY_FILE)){
String filePath = new String((byte[])parsedPartMapItem.getValue());
part.body().changeToFile(new File(filePath));
} else {
// header
String partedHeaderKey = parsedPartMapItem.getKey();
String partedHeaderValue = parsedPartMapItem.getValue().toString();
part.header().put(partedHeaderKey, partedHeaderValue);
if("Content-Disposition".equals(partedHeaderKey)){
//Content-Disposition"name=xxx",
Map<String, String> contentDispositionValue = HttpParser.getEqualMap(partedHeaderValue);
part.header().putAll(contentDispositionValue);
}
}
}
request.parts().add(part);
parsedPartMap.clear();
}
break;
default:
request.header().put(parsedPacketEntry.getKey(), parsedPacketEntry.getValue().toString());
break;
}
}
parsedPacket.clear();
return request;
}
/**
* Http
* @param headerLine http
* @return http
*/
public static String fixHeaderLine(String headerLine) {
if(headerLine.codePointAt(0) > 96){
String[] headerSplites = headerLine.split(": ");
String key = headerSplites[0];
String[] keySplites = key.split("-");
StringBuilder stringBuilder = new StringBuilder();
for(String keySplite : keySplites){
stringBuilder.append((char)(keySplite.codePointAt(0) - 32));
stringBuilder.append(TString.removePrefix(keySplite));
stringBuilder.append("-");
}
return stringBuilder.substring(0, stringBuilder.length()-1) + ": " + headerSplites[1];
} else {
return headerLine;
}
}
/**
* HttpResponse
* @param byteBufferChannel
* @param timeOut
* @return
* @throws IOException IO
*/
@SuppressWarnings("unchecked")
public static Response parseResponse(ByteBufferChannel byteBufferChannel, int timeOut) throws IOException{
Response response = new Response();
Map<String, Object> parsedPacket = parser(byteBufferChannel, timeOut);
Set<Entry<String, Object>> parsedItems= parsedPacket.entrySet();
for(Entry<String, Object> parsedPacketEntry: parsedItems){
String key = parsedPacketEntry.getKey();
switch (key) {
case FL_PROTOCOL:
response.protocol().setProtocol(parsedPacketEntry.getValue().toString());
break;
case FL_VERSION:
response.protocol().setVersion(Float.parseFloat(parsedPacketEntry.getValue().toString()));
break;
case FL_STATUS:
response.protocol().setStatus(Integer.parseInt(parsedPacketEntry.getValue().toString()));
break;
case FL_STATUSCODE:
response.protocol().setStatusCode(parsedPacketEntry.getValue().toString());
break;
case HEAD_COOKIE:
List<Map<String, String>> cookieMap = (List<Map<String, String>>)parsedPacketEntry.getValue();
// Cookie, Cookie
for(Map<String,String> cookieMapItem : cookieMap){
Cookie cookie = Cookie.buildCookie(cookieMapItem);
response.cookies().add(cookie);
}
break;
case BODY_VALUE:
response.body().write((byte[])parsedPacketEntry.getValue());
break;
default:
response.header().put(parsedPacketEntry.getKey(), parsedPacketEntry.getValue().toString());
break;
}
}
parsedPacket.clear();
return response;
}
} |
// This source code is available under agreement available at
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
package org.talend.components.salesforce.dataset;
import java.io.IOException;
import java.util.List;
import org.talend.components.api.component.runtime.DependenciesReader;
import org.talend.components.api.component.runtime.JarRuntimeInfo;
import org.talend.components.common.SchemaProperties;
import org.talend.components.common.dataset.DatasetProperties;
import org.talend.components.salesforce.common.SalesforceRuntimeSourceOrSink;
import org.talend.components.salesforce.dataprep.SalesforceInputProperties;
import org.talend.components.salesforce.datastore.SalesforceDatastoreDefinition;
import org.talend.components.salesforce.datastore.SalesforceDatastoreProperties;
import org.talend.daikon.NamedThing;
import org.talend.daikon.properties.PropertiesImpl;
import org.talend.daikon.properties.ReferenceProperties;
import org.talend.daikon.properties.presentation.Form;
import org.talend.daikon.properties.presentation.Widget;
import org.talend.daikon.properties.property.Property;
import org.talend.daikon.properties.property.PropertyFactory;
import org.talend.daikon.properties.property.StringProperty;
import org.talend.daikon.runtime.RuntimeInfo;
import org.talend.daikon.runtime.RuntimeUtil;
import org.talend.daikon.sandbox.SandboxedInstance;
public class SalesforceDatasetProperties extends PropertiesImpl implements DatasetProperties<SalesforceDatastoreProperties> {
private static final long serialVersionUID = -8035880860245867110L;
public ReferenceProperties<SalesforceDatastoreProperties> datastore = new ReferenceProperties<>("datastore",
SalesforceDatastoreDefinition.NAME);
public Property<SourceType> sourceType = PropertyFactory.newEnum("sourceType", SourceType.class);
public StringProperty moduleName = PropertyFactory.newString("moduleName");
public Property<String> query = PropertyFactory.newString("query");
public SchemaProperties main = new SchemaProperties("main");
public SalesforceDatasetProperties(String name) {
super(name);
}
public void afterSourceType() throws IOException {
refreshLayout(getForm(Form.MAIN));
// refresh the module list
if (sourceType.getValue() == SourceType.MODULE_SELECTION) {
ClassLoader classLoader = this.getClass().getClassLoader();
RuntimeInfo runtimeInfo = new JarRuntimeInfo("mvn:org.talend.components/components-salesforce-runtime",
DependenciesReader.computeDependenciesFilePath("org.talend.components", "components-salesforce-runtime"),
"org.talend.components.salesforce.runtime.dataprep.SalesforceDataprepSource");
try (SandboxedInstance sandboxedInstance = RuntimeUtil.createRuntimeClass(runtimeInfo, classLoader)) {
SalesforceRuntimeSourceOrSink runtime = (SalesforceRuntimeSourceOrSink) sandboxedInstance.getInstance();
SalesforceInputProperties properties = new SalesforceInputProperties("model");
properties.setDatasetProperties(this);
runtime.initialize(null, properties);
List<NamedThing> moduleNames = runtime.getSchemaNames(null);
moduleName.setPossibleNamedThingValues(moduleNames);
}
}
}
@Override
public void setupProperties() {
sourceType.setValue(SourceType.SOQL_QUERY);
query.setValue("SELECT Id, Name FROM Account");
}
@Override
public void setupLayout() {
Form mainForm = Form.create(this, Form.MAIN);
mainForm.addRow(Widget.widget(sourceType).setWidgetType(Widget.RADIO_WIDGET_TYPE));
mainForm.addRow(Widget.widget(moduleName).setWidgetType(Widget.DATALIST_WIDGET_TYPE));
mainForm.addRow(Widget.widget(query).setWidgetType(Widget.TEXT_AREA_WIDGET_TYPE));
}
/**
* the method is called back at many places, even some strange places, so it should work only for basic layout, not some
* action which need runtime support.
*/
@Override
public void refreshLayout(Form form) {
super.refreshLayout(form);
form.getWidget(moduleName).setVisible(sourceType.getValue() == SourceType.MODULE_SELECTION);
form.getWidget(query).setVisible(sourceType.getValue() == SourceType.SOQL_QUERY);
}
@Override
public SalesforceDatastoreProperties getDatastoreProperties() {
return datastore.getReference();
}
@Override
public void setDatastoreProperties(SalesforceDatastoreProperties datastoreProperties) {
datastore.setReference(datastoreProperties);
}
public enum SourceType {
MODULE_SELECTION,
SOQL_QUERY
}
} |
package coprocessor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import coprocessor.generated.ObserverStatisticsProtos;
import coprocessor.generated.ObserverStatisticsProtos.NameInt32Pair;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Append;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Increment;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Row;
import org.apache.hadoop.hbase.client.RowMutations;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.coprocessor.Batch;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.ipc.BlockingRpcCallback;
import org.apache.hadoop.hbase.util.Bytes;
import util.HBaseHelper;
import static coprocessor.generated.ObserverStatisticsProtos.*;
// cc ObserverStatisticsExample Use an endpoint to query observer statistics
public class ObserverStatisticsExample {
// vv ObserverStatisticsExample
private static Table table = null;
private static void printStatistics(boolean print, boolean clear)
throws Throwable {
final StatisticsRequest request = StatisticsRequest
.newBuilder().setClear(clear).build();
Map<byte[], Map<String, Integer>> results = table.coprocessorService(
ObserverStatisticsService.class,
null, null,
new Batch.Call<ObserverStatisticsProtos.ObserverStatisticsService,
Map<String, Integer>>() {
public Map<String, Integer> call(
ObserverStatisticsService statistics)
throws IOException {
BlockingRpcCallback<StatisticsResponse> rpcCallback =
new BlockingRpcCallback<StatisticsResponse>();
statistics.getStatistics(null, request, rpcCallback);
StatisticsResponse response = rpcCallback.get();
Map<String, Integer> stats = new LinkedHashMap<String, Integer>();
for (NameInt32Pair pair : response.getAttributeList()) {
stats.put(pair.getName(), pair.getValue());
}
return stats;
}
}
);
if (print) {
for (Map.Entry<byte[], Map<String, Integer>> entry : results.entrySet()) {
System.out.println("Region: " + Bytes.toString(entry.getKey()));
for (Map.Entry<String, Integer> call : entry.getValue().entrySet()) {
System.out.println(" " + call.getKey() + ": " + call.getValue());
}
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
Configuration conf = HBaseConfiguration.create();
Connection connection = ConnectionFactory.createConnection(conf);
// vv ObserverStatisticsExample
HBaseHelper helper = HBaseHelper.getHelper(conf);
helper.dropTable("testtable");
helper.createTable("testtable", "colfam1", "colfam2");
helper.put("testtable",
new String[]{"row1", "row2", "row3", "row4", "row5"},
new String[]{"colfam1", "colfam2"}, new String[]{"qual1", "qual1"},
new long[]{1, 2}, new String[]{"val1", "val2"});
System.out.println("Before endpoint call...");
helper.dump("testtable",
new String[]{"row1", "row2", "row3", "row4", "row5"},
null, null);
// vv ObserverStatisticsExample
try {
TableName tableName = TableName.valueOf("testtable");
table = connection.getTable(tableName);
// ^^ ObserverStatisticsExample
printStatistics(false, true);
// vv ObserverStatisticsExample
System.out.println("Apply single put...");
Put put = new Put(Bytes.toBytes("row10"));
put.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual10"),
Bytes.toBytes("val10"));
table.put(put);
printStatistics(true, true);
System.out.println("Do single get...");
Get get = new Get(Bytes.toBytes("row10"));
get.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual10"));
table.get(get);
printStatistics(true, true);
// ^^ ObserverStatisticsExample
System.out.println("Send batch with put and get...");
List<Row> batch = new ArrayList<Row>();
Object[] results = new Object[2];
batch.add(put);
batch.add(get);
table.batch(batch, results);
printStatistics(true, true);
System.out.println("Scan single row...");
Scan scan = new Scan()
.setStartRow(Bytes.toBytes("row10"))
.setStopRow(Bytes.toBytes("row11"));
ResultScanner scanner = table.getScanner(scan);
System.out.println(" -> after getScanner()...");
printStatistics(true, true);
Result result = scanner.next();
System.out.println(" -> after next()...");
printStatistics(true, true);
scanner.close();
System.out.println(" -> after close()...");
printStatistics(true, true);
System.out.println("Scan multiple rows...");
scan = new Scan();
scanner = table.getScanner(scan);
System.out.println(" -> after getScanner()...");
printStatistics(true, true);
result = scanner.next();
System.out.println(" -> after next()...");
printStatistics(true, true);
result = scanner.next();
printStatistics(false, true);
scanner.close();
System.out.println(" -> after close()...");
printStatistics(true, true);
System.out.println("Apply single put with mutateRow()...");
RowMutations mutations = new RowMutations(Bytes.toBytes("row1"));
put = new Put(Bytes.toBytes("row1"));
put.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual10"),
Bytes.toBytes("val10"));
mutations.add(put);
table.mutateRow(mutations);
printStatistics(true, true);
System.out.println("Apply single column increment...");
Increment increment = new Increment(Bytes.toBytes("row10"));
increment.addColumn(Bytes.toBytes("colfam1"),
Bytes.toBytes("qual11"), 1);
table.increment(increment);
printStatistics(true, true);
System.out.println("Apply multi column increment...");
increment = new Increment(Bytes.toBytes("row10"));
increment.addColumn(Bytes.toBytes("colfam1"),
Bytes.toBytes("qual12"), 1);
increment.addColumn(Bytes.toBytes("colfam1"),
Bytes.toBytes("qual13"), 1);
table.increment(increment);
printStatistics(true, true);
System.out.println("Apply single incrementColumnValue...");
table.incrementColumnValue(Bytes.toBytes("row10"),
Bytes.toBytes("colfam1"), Bytes.toBytes("qual12"), 1);
printStatistics(true, true);
System.out.println("Call single exists()...");
table.exists(get);
printStatistics(true, true);
System.out.println("Apply single delete...");
Delete delete = new Delete(Bytes.toBytes("row10"));
delete.addColumn(Bytes.toBytes("colfam1"),
Bytes.toBytes("qual10"));
table.delete(delete);
printStatistics(true, true);
System.out.println("Apply single append...");
Append append = new Append(Bytes.toBytes("row10"));
append.add(Bytes.toBytes("colfam1"), Bytes.toBytes("qual15"),
Bytes.toBytes("-valnew"));
table.append(append);
printStatistics(true, true);
System.out.println("Apply checkAndPut (failing)...");
put = new Put(Bytes.toBytes("row10"));
put.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual17"),
Bytes.toBytes("val17"));
boolean cap = table.checkAndPut(Bytes.toBytes("row10"),
Bytes.toBytes("colfam1"), Bytes.toBytes("qual15"), null, put);
System.out.println(" -> success: " + cap);
printStatistics(true, true);
System.out.println("Apply checkAndPut (succeeding)...");
cap = table.checkAndPut(Bytes.toBytes("row10"),
Bytes.toBytes("colfam1"), Bytes.toBytes("qual16"), null, put);
System.out.println(" -> success: " + cap);
printStatistics(true, true);
System.out.println("Apply checkAndDelete (failing)...");
delete = new Delete(Bytes.toBytes("row10"));
delete.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual17"));
cap = table.checkAndDelete(Bytes.toBytes("row10"),
Bytes.toBytes("colfam1"), Bytes.toBytes("qual15"), null, delete);
System.out.println(" -> success: " + cap);
printStatistics(true, true);
System.out.println("Apply checkAndDelete (succeeding)...");
cap = table.checkAndDelete(Bytes.toBytes("row10"),
Bytes.toBytes("colfam1"), Bytes.toBytes("qual18"), null, delete);
System.out.println(" -> success: " + cap);
printStatistics(true, true);
System.out.println("Apply checkAndMutate (failing)...");
mutations = new RowMutations(Bytes.toBytes("row10"));
put = new Put(Bytes.toBytes("row10"));
put.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual20"),
Bytes.toBytes("val20"));
delete = new Delete(Bytes.toBytes("row10"));
delete.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual17"));
mutations.add(put);
mutations.add(delete);
cap = table.checkAndMutate(Bytes.toBytes("row10"),
Bytes.toBytes("colfam1"), Bytes.toBytes("qual10"),
CompareFilter.CompareOp.GREATER, Bytes.toBytes("val10"), mutations);
System.out.println(" -> success: " + cap);
printStatistics(true, true);
System.out.println("Apply checkAndMutate (succeeding)...");
cap = table.checkAndMutate(Bytes.toBytes("row10"),
Bytes.toBytes("colfam1"), Bytes.toBytes("qual10"),
CompareFilter.CompareOp.EQUAL, Bytes.toBytes("val10"), mutations);
System.out.println(" -> success: " + cap);
printStatistics(true, true);
// vv ObserverStatisticsExample
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
// ^^ ObserverStatisticsExample
} |
package org.springframework.ide.vscode.commons.languageserver.util;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.eclipse.lsp4j.CodeAction;
import org.eclipse.lsp4j.CodeActionParams;
import org.eclipse.lsp4j.CodeLens;
import org.eclipse.lsp4j.CodeLensParams;
import org.eclipse.lsp4j.Command;
import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionList;
import org.eclipse.lsp4j.CompletionParams;
import org.eclipse.lsp4j.Diagnostic;
import org.eclipse.lsp4j.DidChangeTextDocumentParams;
import org.eclipse.lsp4j.DidCloseTextDocumentParams;
import org.eclipse.lsp4j.DidOpenTextDocumentParams;
import org.eclipse.lsp4j.DidSaveTextDocumentParams;
import org.eclipse.lsp4j.DocumentFormattingParams;
import org.eclipse.lsp4j.DocumentHighlight;
import org.eclipse.lsp4j.DocumentOnTypeFormattingParams;
import org.eclipse.lsp4j.DocumentRangeFormattingParams;
import org.eclipse.lsp4j.DocumentSymbol;
import org.eclipse.lsp4j.DocumentSymbolParams;
import org.eclipse.lsp4j.Hover;
import org.eclipse.lsp4j.Location;
import org.eclipse.lsp4j.PublishDiagnosticsParams;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.ReferenceParams;
import org.eclipse.lsp4j.RenameParams;
import org.eclipse.lsp4j.SignatureHelp;
import org.eclipse.lsp4j.SymbolInformation;
import org.eclipse.lsp4j.TextDocumentContentChangeEvent;
import org.eclipse.lsp4j.TextDocumentIdentifier;
import org.eclipse.lsp4j.TextDocumentItem;
import org.eclipse.lsp4j.TextDocumentPositionParams;
import org.eclipse.lsp4j.TextEdit;
import org.eclipse.lsp4j.VersionedTextDocumentIdentifier;
import org.eclipse.lsp4j.WorkspaceEdit;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.lsp4j.services.LanguageClient;
import org.eclipse.lsp4j.services.TextDocumentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ide.vscode.commons.languageserver.quickfix.Quickfix;
import org.springframework.ide.vscode.commons.util.Assert;
import org.springframework.ide.vscode.commons.util.AsyncRunner;
import org.springframework.ide.vscode.commons.util.BadLocationException;
import org.springframework.ide.vscode.commons.util.CollectorUtil;
import org.springframework.ide.vscode.commons.util.ExceptionUtil;
import org.springframework.ide.vscode.commons.util.text.LanguageId;
import org.springframework.ide.vscode.commons.util.text.TextDocument;
import com.google.common.collect.ImmutableList;
public class SimpleTextDocumentService implements TextDocumentService, DocumentEventListenerManager {
private static Logger log = LoggerFactory.getLogger(SimpleTextDocumentService.class);
final private SimpleLanguageServer server;
private Map<String, TrackedDocument> documents = new HashMap<>();
private ListenerList<TextDocumentContentChange> documentChangeListeners = new ListenerList<>();
private ListenerList<TextDocument> documentCloseListeners = new ListenerList<>();
private ListenerList<TextDocument> documentOpenListeners = new ListenerList<>();
private CompletionHandler completionHandler = null;
private CompletionResolveHandler completionResolveHandler = null;
private HoverHandler hoverHandler = null;
private DefinitionHandler definitionHandler;
private ReferencesHandler referencesHandler;
private DocumentSymbolHandler documentSymbolHandler;
private DocumentHighlightHandler documentHighlightHandler;
private CodeLensHandler codeLensHandler;
private CodeLensResolveHandler codeLensResolveHandler;
private List<Consumer<TextDocumentSaveChange>> documentSaveListeners = ImmutableList.of();
private AsyncRunner async;
public SimpleTextDocumentService(SimpleLanguageServer server) {
this.server = server;
this.async = server.getAsync();
}
public synchronized void onHover(HoverHandler h) {
Assert.isNull("A hover handler is already set, multiple handlers not supported yet", hoverHandler);
this.hoverHandler = h;
}
public synchronized void onCodeLens(CodeLensHandler h) {
Assert.isNull("A code lens handler is already set, multiple handlers not supported yet", codeLensHandler);
this.codeLensHandler = h;
}
public synchronized void onCodeLensResolve(CodeLensResolveHandler h) {
Assert.isNull("A code lens resolve handler is already set, multiple handlers not supported yet", codeLensResolveHandler);
this.codeLensResolveHandler = h;
}
public synchronized void onDocumentSymbol(DocumentSymbolHandler h) {
Assert.isNull("A DocumentSymbolHandler is already set, multiple handlers not supported yet", documentSymbolHandler);
this.documentSymbolHandler = h;
}
public synchronized void onDocumentHighlight(DocumentHighlightHandler h) {
Assert.isNull("A DocumentHighlightHandler is already set, multiple handlers not supported yet", documentHighlightHandler);
this.documentHighlightHandler = h;
}
public synchronized void onCompletion(CompletionHandler h) {
Assert.isNull("A completion handler is already set, multiple handlers not supported yet", completionHandler);
this.completionHandler = h;
}
public synchronized void onCompletionResolve(CompletionResolveHandler h) {
Assert.isNull("A completionResolveHandler handler is already set, multiple handlers not supported yet", completionResolveHandler);
this.completionResolveHandler = h;
}
public synchronized void onDefinition(DefinitionHandler h) {
Assert.isNull("A defintion handler is already set, multiple handlers not supported yet", definitionHandler);
this.definitionHandler = h;
}
public synchronized void onReferences(ReferencesHandler h) {
Assert.isNull("A references handler is already set, multiple handlers not supported yet", referencesHandler);
this.referencesHandler = h;
}
/**
* Gets all documents this service is tracking, generally these are the documents that have been opened / changed,
* and not yet closed.
*/
public synchronized Collection<TextDocument> getAll() {
return documents.values().stream()
.map((td) -> td.getDocument())
.collect(Collectors.toList());
}
@Override
public final void didChange(DidChangeTextDocumentParams params) {
async.execute(() -> {
try {
VersionedTextDocumentIdentifier docId = params.getTextDocument();
String url = docId.getUri();
// Log.debug("didChange: "+url);
if (url!=null) {
TextDocument doc = getDocument(url);
List<TextDocumentContentChangeEvent> changes = params.getContentChanges();
doc.apply(params);
didChangeContent(doc, changes);
}
} catch (BadLocationException e) {
log.error("", e);
}
});
}
@Override
public void didOpen(DidOpenTextDocumentParams params) {
async.execute(() -> {
TextDocumentItem docId = params.getTextDocument();
String url = docId.getUri();
//Log.info("didOpen: "+params.getTextDocument().getUri());
LanguageId languageId = LanguageId.of(docId.getLanguageId());
int version = docId.getVersion();
if (url != null) {
String text = params.getTextDocument().getText();
TrackedDocument td = createDocument(url, languageId, version, text).open();
log.debug("Opened " + td.getOpenCount() + " times: " + url);
TextDocument doc = td.getDocument();
documentOpenListeners.fire(doc);
TextDocumentContentChangeEvent change = new TextDocumentContentChangeEvent() {
@Override
public Range getRange() {
return null;
}
@Override
public Integer getRangeLength() {
return null;
}
@Override
public String getText() {
return text;
}
};
TextDocumentContentChange evt = new TextDocumentContentChange(doc, ImmutableList.of(change));
documentChangeListeners.fire(evt);
}
});
}
@Override
public void didClose(DidCloseTextDocumentParams params) {
async.execute(() -> {
//Log.info("didClose: "+params.getTextDocument().getUri());
String url = params.getTextDocument().getUri();
if (url!=null) {
TrackedDocument doc = documents.get(url);
if (doc!=null) {
if (doc.close()) {
log.info("Closed: "+url);
//Clear diagnostics when a file is closed. This makes the errors disapear when the language is changed for
// a document (this resulst in a dicClose even as being sent to the language server if that changes make the
// document go 'out of scope'.
publishDiagnostics(params.getTextDocument(), ImmutableList.of());
documentCloseListeners.fire(doc.getDocument());
documents.remove(url);
} else {
log.warn("Close event ignored! Assuming document still open because openCount = "+doc.getOpenCount());
}
} else {
log.warn("Document closed, but it didn't exist! Close event ignored");
}
}
});
}
void didChangeContent(TextDocument doc, List<TextDocumentContentChangeEvent> changes) {
documentChangeListeners.fire(new TextDocumentContentChange(doc, changes));
}
public void onDidOpen(Consumer<TextDocument> l) {
documentOpenListeners.add(l);
}
public void onDidChangeContent(Consumer<TextDocumentContentChange> l) {
documentChangeListeners.add(l);
}
public void onDidClose(Consumer<TextDocument> l) {
documentCloseListeners.add(l);
}
@Override
public void onDidSave(Consumer<TextDocumentSaveChange> l) {
ImmutableList.Builder<Consumer<TextDocumentSaveChange>> builder = ImmutableList.builder();
builder.addAll(documentSaveListeners);
builder.add(l);
documentSaveListeners = builder.build();
}
public synchronized TextDocument getDocument(String url) {
TrackedDocument doc = documents.get(url);
if (doc==null) {
log.warn("Trying to get document ["+url+"] but it did not exists. Creating it with language-id 'plaintext'");
doc = createDocument(url, LanguageId.PLAINTEXT, 0, "");
}
return doc.getDocument();
}
private synchronized TrackedDocument createDocument(String url, LanguageId languageId, int version, String text) {
TrackedDocument existingDoc = documents.get(url);
if (existingDoc!=null) {
log.warn("Creating document ["+url+"] but it already exists. Reusing existing!");
return existingDoc;
}
TrackedDocument doc = new TrackedDocument(new TextDocument(url, languageId, version, text));
documents.put(url, doc);
return doc;
}
public final static CompletionList NO_COMPLETIONS = new CompletionList(false, Collections.emptyList());
public final static Hover NO_HOVER = new Hover(ImmutableList.of(), null);
public final static List<? extends Location> NO_REFERENCES = ImmutableList.of();
public final static List<? extends SymbolInformation> NO_SYMBOLS = ImmutableList.of();
public final static List<? extends CodeLens> NO_CODELENS = ImmutableList.of();
public final static List<DocumentHighlight> NO_HIGHLIGHTS = ImmutableList.of();
@Override
public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(CompletionParams position) {
log.info("completion request received");
CompletionHandler h = completionHandler;
if (h!=null) {
return completionHandler.handle(position)
.map(Either::<List<CompletionItem>, CompletionList>forRight)
.toFuture();
}
return CompletableFuture.completedFuture(Either.forRight(NO_COMPLETIONS));
}
@Override
public CompletableFuture<CompletionItem> resolveCompletionItem(CompletionItem unresolved) {
log.info("Completion item resolve request received: {}", unresolved.getLabel());
return async.invoke(() -> {
try {
CompletionResolveHandler h = completionResolveHandler;
if (h!=null) {
log.info("Completion item resolve request starting {}", unresolved.getLabel());
return h.handle(unresolved);
}
} finally {
log.info("Completion item resolve request terminated.");
}
return null;
});
}
@Override
public CompletableFuture<Hover> hover(TextDocumentPositionParams position) {
return async.invoke(() -> {
HoverHandler h = hoverHandler;
if (h!=null) {
return hoverHandler.handle(position);
}
return null;
});
}
@Override
public CompletableFuture<SignatureHelp> signatureHelp(TextDocumentPositionParams position) {
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<List<? extends Location>> definition(TextDocumentPositionParams position) {
return async.invoke(() -> {
DefinitionHandler h = this.definitionHandler;
if (h!=null) {
return h.handle(position);
}
return Collections.emptyList();
});
}
@Override
public CompletableFuture<List<? extends Location>> references(ReferenceParams params) {
return async.invoke(() -> {
ReferencesHandler h = this.referencesHandler;
if (h != null) {
List<? extends Location> list = h.handle(params);
return list != null && list.isEmpty() ? null : list;
}
return null;
});
}
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(DocumentSymbolParams params) {
return async.invoke(() -> {
DocumentSymbolHandler h = this.documentSymbolHandler;
if (h!=null) {
server.waitForReconcile();
if (server.hasHierarchicalDocumentSymbolSupport() && h instanceof HierarchicalDocumentSymbolHandler) {
List<? extends DocumentSymbol> r = ((HierarchicalDocumentSymbolHandler)h).handleHierarchic(params);
//handle it when symbolHandler is sloppy and returns null instead of empty list.
return r == null
? ImmutableList.of()
: r.stream().map(symbolInfo -> Either.<SymbolInformation, DocumentSymbol>forRight(symbolInfo))
.collect(Collectors.toList());
} else {
List<? extends SymbolInformation> r = h.handle(params);
//handle it when symbolHandler is sloppy and returns null instead of empty list.
return r == null
? ImmutableList.of()
: r.stream().map(symbolInfo -> Either.<SymbolInformation, DocumentSymbol>forLeft(symbolInfo))
.collect(Collectors.toList());
}
}
return ImmutableList.of();
});
}
@Override
public CompletableFuture<List<Either<Command, CodeAction>>> codeAction(CodeActionParams params) {
return async.invoke(() -> {
TrackedDocument doc = documents.get(params.getTextDocument().getUri());
if (doc!=null) {
ImmutableList<Either<Command,CodeAction>> list = doc.getQuickfixes().stream()
.filter((fix) -> fix.appliesTo(params.getRange(), params.getContext()))
.map(Quickfix::getCodeAction)
.map(command -> Either.<Command, CodeAction>forLeft(command))
.collect(CollectorUtil.toImmutableList());
return list;
} else {
return ImmutableList.of();
}
});
}
@Override
public CompletableFuture<List<? extends CodeLens>> codeLens(CodeLensParams params) {
CodeLensHandler handler = this.codeLensHandler;
if (handler != null) {
return async.invoke(() -> handler.handle(params));
}
return CompletableFuture.completedFuture(Collections.emptyList());
}
@Override
public CompletableFuture<CodeLens> resolveCodeLens(CodeLens unresolved) {
CodeLensResolveHandler handler = this.codeLensResolveHandler;
if (handler != null) {
return async.invoke(() -> handler.handle(unresolved));
}
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
@Override
public CompletableFuture<List<? extends TextEdit>> rangeFormatting(DocumentRangeFormattingParams params) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
@Override
public CompletableFuture<List<? extends TextEdit>> onTypeFormatting(DocumentOnTypeFormattingParams params) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
@Override
public CompletableFuture<WorkspaceEdit> rename(RenameParams params) {
return CompletableFuture.completedFuture(null);
}
@Override
public void didSave(DidSaveTextDocumentParams params) {
// Workaround for PT 147263283, where error markers in STS are lost on document save.
// STS 3.9.0 does not use the LSP4E editor for edit manifest.yml, which correctly retains error markers after save.
// Instead, because the LSP4E editor is missing support for hovers and completions, STS 3.9.0 uses its own manifest editor
// which extends the YEdit editor. This YEdit editor has a problem, where on save, all error markers are deleted.
// When STS uses the LSP4E editor and no longer needs its own YEdit-based editor, the issue with error markers disappearing
// on save should not be a problem anymore, and the workaround below will no longer be needed.
async.execute(() -> {
if (documentSaveListeners != null) {
TextDocumentIdentifier docId = params.getTextDocument();
String url = docId.getUri();
log.debug("didSave: "+url);
if (url!=null) {
TextDocument doc = getDocument(url);
for (Consumer<TextDocumentSaveChange> l : documentSaveListeners) {
l.accept(new TextDocumentSaveChange(doc));
}
}
}
});
}
public void publishDiagnostics(TextDocumentIdentifier docId, Collection<Diagnostic> diagnostics) {
LanguageClient client = server.getClient();
if (client!=null && diagnostics!=null) {
PublishDiagnosticsParams params = new PublishDiagnosticsParams();
params.setUri(docId.getUri());
params.setDiagnostics(ImmutableList.copyOf(diagnostics));
client.publishDiagnostics(params);
}
}
public void setQuickfixes(TextDocumentIdentifier docId, List<Quickfix> quickfixes) {
TrackedDocument td = documents.get(docId.getUri());
if (td!=null) {
td.setQuickfixes(quickfixes);
}
}
public synchronized TextDocument get(TextDocumentPositionParams params) {
return get(params.getTextDocument().getUri());
}
public synchronized TextDocument get(String uri) {
TrackedDocument td = documents.get(uri);
return td == null ? null : td.getDocument();
}
@Override
public CompletableFuture<List<? extends DocumentHighlight>> documentHighlight(TextDocumentPositionParams position) {
return async.invoke(() -> {
DocumentHighlightHandler handler = this.documentHighlightHandler;
if (handler != null) {
return handler.handle(position);
}
return NO_HIGHLIGHTS;
});
}
public boolean hasDefinitionHandler() {
return definitionHandler!=null;
}
public boolean hasReferencesHandler() {
return this.referencesHandler!=null;
}
public boolean hasDocumentSymbolHandler() {
return this.documentSymbolHandler!=null;
}
public boolean hasDocumentHighlightHandler() {
return this.documentHighlightHandler!=null;
}
public boolean hasCodeLensHandler() {
return this.codeLensHandler != null;
}
public boolean hasCodeLensResolveProvider() {
return this.codeLensResolveHandler != null;
}
public TextDocument getDocumentSnapshot(TextDocumentIdentifier textDocumentIdentifier) {
try {
return async.invoke(() -> {
TextDocument doc = get(textDocumentIdentifier.getUri());
if (doc!=null) {
return doc.copy();
}
return null;
}).get();
} catch (Exception e) {
throw ExceptionUtil.unchecked(e);
}
}
} |
package ru.job4j.iterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator for even numbers.
*/
public class EvenIterator implements Iterator {
/**
* input array.
*/
private int[] arr;
/**
* index of current element.
*/
private int index = 0;
/**
* Constructor.
* @param arr - input array.
*/
public EvenIterator(int[] arr) {
this.arr = arr;
}
/**
* @return - next even number and step on next element.
*/
@Override
public Object next() {
if (!hasNext()) {
throw new NoSuchElementException();
} else {
return arr[index++];
}
}
/**
* @return - true, if array has next even element.
*/
@Override
public boolean hasNext() {
boolean flag = false;
for (int i = index; i < arr.length; i++) {
if (arr[i] % 2 == 0 && arr[i] != 1 && arr[i] != 0) {
index = i;
flag = true;
break;
}
}
return flag;
}
} |
package experimentalcode.lisa;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.database.AssociationID;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.math.MinMax;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector;
import de.lmu.ifi.dbs.elki.result.AnnotationFromHashMap;
import de.lmu.ifi.dbs.elki.result.OrderingFromHashMap;
import de.lmu.ifi.dbs.elki.result.outlier.BasicOutlierScoreMeta;
import de.lmu.ifi.dbs.elki.result.outlier.InvertedOutlierScoreMeta;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierScoreMeta;
import de.lmu.ifi.dbs.elki.utilities.DatabaseUtil;
import de.lmu.ifi.dbs.elki.utilities.Description;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Flag;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
/**
* Outlier have smallest GMOD_PROB: the outlier scores is the
* <em>probability density</em> of the assumed distribution.
*
* @author Lisa Reichert
*
* @param <V> Vector type
*/
public class GaussianModelOutlierDetection<V extends NumberVector<V, Double>> extends AbstractAlgorithm<V, OutlierResult> {
/**
* OptionID for {@link #INVERT_FLAG}
*/
public static final OptionID INVERT_ID = OptionID.getOrCreateOptionID("gaussod.invert", "Invert the value range to [0:1], with 1 being outliers instead of 0.");
/**
* Parameter to specify a scaling function to use.
* <p>
* Key: {@code -gaussod.invert}
* </p>
*/
private final Flag INVERT_FLAG = new Flag(INVERT_ID);
/**
* Invert the result
*/
private boolean invert = false;
OutlierResult result;
public static final AssociationID<Double> GMOD_PROB = AssociationID.getOrCreateAssociationID("gmod.prob", Double.class);
public GaussianModelOutlierDetection() {
super();
addOption(INVERT_FLAG);
}
@Override
protected OutlierResult runInTime(Database<V> database) throws IllegalStateException {
MinMax<Double> mm = new MinMax<Double>();
// resulting scores
HashMap<Integer, Double> oscores = new HashMap<Integer, Double>(database.size());
// Compute mean and covariance Matrix
V mean = DatabaseUtil.centroid(database);
// debugFine(mean.toString());
Matrix covarianceMatrix = DatabaseUtil.covarianceMatrix(database, mean);
// debugFine(covarianceMatrix.toString());
Matrix covarianceTransposed = covarianceMatrix.inverse();
// Normalization factors for Gaussian PDF
final double fakt = (1.0 / (Math.sqrt(Math.pow(2 * Math.PI, database.dimensionality()) * covarianceMatrix.det())));
// for each object compute Mahalanobis distance
for(Integer id : database) {
V x = database.get(id);
Vector x_minus_mean = x.minus(mean).getColumnVector();
// Gaussian PDF
final double mDist = x_minus_mean.transposeTimes(covarianceTransposed).times(x_minus_mean).get(0, 0);
final double prob = fakt * Math.exp(-mDist / 2.0);
mm.put(prob);
oscores.put(id, prob);
}
final OutlierScoreMeta meta;
if (invert) {
double max = mm.getMax() != 0 ? mm.getMax() : 1.;
for (Entry<Integer, Double> entry : oscores.entrySet()) {
entry.setValue((max - entry.getValue()) / max);
}
meta = new BasicOutlierScoreMeta(0.0, 1.0);
} else {
meta = new InvertedOutlierScoreMeta(mm.getMin(), mm.getMax(), 0.0, Double.POSITIVE_INFINITY );
}
AnnotationFromHashMap<Double> res1 = new AnnotationFromHashMap<Double>(GMOD_PROB, oscores);
OrderingFromHashMap<Double> res2 = new OrderingFromHashMap<Double>(oscores);
result = new OutlierResult(meta, res1, res2);
return result;
}
@Override
public Description getDescription() {
// TODO Auto-generated method stub
return null;
}
@Override
public OutlierResult getResult() {
return result;
}
@Override
public List<String> setParameters(List<String> args) throws ParameterException {
List<String> remainingParameters = super.setParameters(args);
invert = INVERT_FLAG.getValue();
rememberParametersExcept(args, remainingParameters);
return remainingParameters;
}
} |
package org.firepick.firesight;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.util.Map;
import nu.pattern.OpenCV;
import org.firepick.firesight.utils.OpenCvUtils;
import org.firepick.firesight.utils.SharedLibLoader;
import org.opencv.core.Mat;
public class FireSight {
private final static String[] LIBS = new String[] { "zbar", "_firesight", "firesight-java" };
static {
OpenCV.loadShared();
SharedLibLoader.loadLibraries(LIBS);
}
/**
* Process a buffered image based on a json description
*
* @param image
* the image to process. The original image will be overwritten with the processed one
* @param json
* the processing description
*
* @return json status information from FireSight
*/
public static String process(BufferedImage image, String json) {
return process(image, json, null);
}
/**
* Process a buffered image based on a json description
*
* @param image
* the image to process. The original image will be overwritten with the processed one
* @param json
* the processing description
* @param argMap
* a map with additional arguments for FireSight
*
* @return json status information from FireSight
*/
public static String process(BufferedImage image, String json, Map<String, String> argMap) {
Mat mat = OpenCvUtils.toMat(image);
String[] argNames = null;
String[] argValues = null;
if (argMap != null) {
int index = 0;
argNames = new String[argMap.size()];
argValues = new String[argMap.size()];
for (Map.Entry<String, String> e : argMap.entrySet()) {
argNames[index] = e.getKey();
argValues[index] = e.getValue();
index++;
}
}
String result = process(mat.nativeObj, json, argNames, argValues);
mat.get(0, 0, ((DataBufferByte) image.getRaster().getDataBuffer()).getData());
return result;
}
protected static native String process(long nativeMat, String json, String[] argNames, String[] argValues);
} |
package io.sniffy.tls;
import io.sniffy.*;
import io.sniffy.socket.AddressMatchers;
import io.sniffy.socket.NetworkPacket;
import io.sniffy.socket.SocketMetaData;
import io.sniffy.util.JVMUtil;
import io.sniffy.util.OSUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.*;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
public class DecryptBouncyCastleGoogleTrafficTestHelper {
public static void testGoogleTrafficImpl() throws Exception {
assertTrue(SSLContext.getInstance("Default").getProvider().getName().contains("Sniffy"));
Security.insertProviderAt(new BouncyCastleProvider(), 1);
Security.insertProviderAt(new BouncyCastleJsseProvider(), 1);
SSLContext instance = SSLContext.getInstance("TLSv1.2", "BCJSSE");
instance.init(null, null, new SecureRandom());
assertTrue(instance.getSocketFactory() instanceof SniffySSLSocketFactory);
assertEquals("Sniffy-BCJSSE", SSLContext.getDefault().getProvider().getName());
try (Spy<?> spy = Sniffy.spy(SpyConfiguration.builder().captureNetworkTraffic(true).captureStackTraces(true).build())) {
for (int i = 0; i < 10; i++) {
try {
URL url = new URL("https:
URLConnection urlConnection = url.openConnection();
// On Java 14 with parallel builds sometimes throws SSLException: An established connection was aborted by the software in your host machine
//noinspection ResultOfMethodCallIgnored
urlConnection.getInputStream().read();
break;
} catch (IOException e) {
if (e.getMessage().contains("An established connection was aborted by the software in your host machine") && OSUtil.isWindows() && (JVMUtil.getVersion() == 14 || JVMUtil.getVersion() == 13)) {
e.printStackTrace();
System.err.println("Caught " + e + " exception on Java " + JVMUtil.getVersion() + " running on Windows; retrying in 2 seconds");
Thread.sleep(2000);
} else if (e.getMessage().contains("Broken pipe") && OSUtil.isMac() && (JVMUtil.getVersion() >= 13)) {
e.printStackTrace();
System.err.println("Caught " + e + " exception on Java " + JVMUtil.getVersion() + " running on Mac OS; retrying in 2 seconds");
Thread.sleep(2000);
}{
throw e;
}
}
}
Map<SocketMetaData, List<NetworkPacket>> decryptedNetworkTraffic = spy.getDecryptedNetworkTraffic(
Threads.CURRENT,
AddressMatchers.exactAddressMatcher("www.google.com:443"),
GroupingOptions.builder().
groupByConnection(false).
groupByStackTrace(false).
groupByThread(false).
build()
);
assertEquals(1, decryptedNetworkTraffic.size());
Map.Entry<SocketMetaData, List<NetworkPacket>> entry = decryptedNetworkTraffic.entrySet().iterator().next();
assertNotNull(entry);
assertNotNull(entry.getKey());
assertNotNull(entry.getValue());
assertEquals(2, entry.getValue().size());
NetworkPacket request = entry.getValue().get(0);
NetworkPacket response = entry.getValue().get(1);
//noinspection SimplifiableAssertion
assertEquals(true, request.isSent());
//noinspection SimplifiableAssertion
assertEquals(false, response.isSent());
//noinspection CharsetObjectCanBeUsed
assertTrue(new String(request.getBytes(), Charset.forName("US-ASCII")).contains("Host: www.google.com"));
//noinspection CharsetObjectCanBeUsed
assertTrue(new String(response.getBytes(), Charset.forName("US-ASCII")).contains("200"));
}
}
} |
package com.HRank.String;
import java.util.Scanner;
public class Ex10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
StringBuilder build = new StringBuilder();
StringBuilder temp = new StringBuilder();
int offset = 0;
int n = 0;
int result[] = new int[t];
for(int i = 0; i<t; i++){
build.append(scan.next());
temp.append(build.toString());
n = build.length()/2;
//System.out.println(build);
if(build.toString().equals(build.reverse().toString())){
result[i] = -1;
}else{
build.reverse();
offset = build.length() - 1;
//System.out.println("offset is " + offset);
for(int j = 0; j<n; j++){
if(build.charAt(j) != build.charAt(offset - j)){
if((temp.deleteCharAt(j).toString()).equals(temp.reverse().toString())){
build.deleteCharAt(j);
//System.out.println(j);
result[i] = j;
break;
}else{
build.deleteCharAt(offset - j);
//System.out.println(offset - j);
result[i] = offset - j;
break;
}
}
}
}
build.delete(0, build.length());
temp.delete(0, temp.length());
}
for(int i=0;i < result.length; i++){
System.out.println(result[i]);
}
scan.close();
}
} |
package fi.cie.chiru.servicefusionar.serviceApi;
import util.IO;
import util.Vec;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import fi.cie.chiru.servicefusionar.gdx.GDXLoader;
import fi.cie.chiru.servicefusionar.gdx.GDXMesh;
import fi.cie.chiru.servicefusionar.commands.CommandFactory;
import android.util.Log;
public class SceneParser
{
private static final String LOG_TAG = "SceneParser";
String sceneContent;
private GDXLoader gdxLoader;
public SceneParser()
{
gdxLoader = new GDXLoader();
}
public Vector<ServiceApplication> parseFile(ServiceManager serviceManager, String fileName)
{
Vector<ServiceApplication> serviceApplications = new Vector<ServiceApplication>();
InputStream in = null;
try
{
in = serviceManager.getSetup().myTargetActivity.getAssets().open(fileName);
sceneContent = IO.convertInputStreamToString(in);
}
catch (IOException e)
{
Log.e(LOG_TAG, "Could not read file: " +fileName);
e.printStackTrace();
} finally {
try {
Log.i(LOG_TAG, "Closing scene input stream");
in.close();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
}
}
JSONObject jsonObj = null;
try
{
jsonObj = new JSONObject(sceneContent);
} catch (JSONException e) {
Log.e(LOG_TAG, "parsing failed");
e.printStackTrace();
}
JSONArray entries = null;
try
{
entries = jsonObj.getJSONArray("ServiceApplication");
for(int i=0; i<entries.length(); i++)
{
JSONObject ServiceAppObj = entries.getJSONObject(i);
String name = ServiceAppObj.getString("name");
ServiceApplication serviceApp = new ServiceApplication(serviceManager,name);
String meshName = ServiceAppObj.getString("meshRef");
String textureName = ServiceAppObj.getString("textRef");
if(meshName!=null && textureName!=null)
{
GDXMesh gdxMesh = gdxLoader.loadModelFromFile(meshName, textureName);
gdxMesh.enableMeshPicking();
serviceApp.setMesh(gdxMesh);
JSONObject posObj = ServiceAppObj.getJSONObject("position");
JSONObject rotObj = ServiceAppObj.getJSONObject("rotation");
JSONObject scaleObj = ServiceAppObj.getJSONObject("scale");
serviceApp.setPosition(new Vec((float)posObj.getDouble("x"), (float)posObj.getDouble("y"), (float)posObj.getDouble("z")));
serviceApp.setRotation(new Vec((float)rotObj.getDouble("x"), (float)rotObj.getDouble("y"), (float)rotObj.getDouble("z")));
serviceApp.setScale(new Vec((float)scaleObj.getDouble("x"), (float)scaleObj.getDouble("y"), (float)scaleObj.getDouble("z")));
}
JSONObject commandObj = ServiceAppObj.getJSONObject("commands");
String clickCommand = commandObj.getString("CLICK");
String dropCommand = commandObj.getString("DROP");
String longClickCommand = commandObj.getString("LONG_CLICK");
serviceApp.setOnClickCommand(CommandFactory.createCommand(clickCommand, serviceManager, name));
serviceApp.setOnDoubleClickCommand(CommandFactory.createCommand(dropCommand, serviceManager, name));
serviceApp.setOnLongClickCommand(CommandFactory.createCommand(longClickCommand, serviceManager, name));
boolean visible = ServiceAppObj.getBoolean("visible");
if(!visible)
serviceApp.setvisible(false);
boolean attached = ServiceAppObj.getBoolean("attached");
serviceApp.attachToCamera(attached);
serviceManager.getSetup().world.add(serviceApp);
serviceApplications.add(serviceApp);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "parsing failed");
e.printStackTrace();
}
return serviceApplications;
}
} |
package org.hibernate.example.model;
import java.io.Serializable;
import java.lang.String;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import org.apache.lucene.analysis.core.LowerCaseFilterFactory;
import org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilterFactory;
import org.apache.lucene.analysis.pattern.PatternTokenizerFactory;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.AnalyzerDef;
import org.hibernate.search.annotations.AnalyzerDefs;
import org.hibernate.search.annotations.Boost;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Norms;
import org.hibernate.search.annotations.Parameter;
import org.hibernate.search.annotations.TokenizerDef;
import org.hibernate.search.annotations.TokenFilterDef;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
import org.hibernate.search.annotations.TermVector;
@Entity
@Table(name="cases")
@Indexed(index="cases")
@AnalyzerDefs({ @AnalyzerDef(name="tags",
tokenizer = @TokenizerDef(factory = PatternTokenizerFactory.class,
params = {
@Parameter(name = "pattern", value = "
@Parameter( name = "group", value = "1") } ),
filters = {
@TokenFilterDef(factory = ASCIIFoldingFilterFactory.class),
@TokenFilterDef(factory = LowerCaseFilterFactory.class)
})
})
public class Case implements Serializable {
private String casenumber;
private String subject;
private String description;
private String product;
private String version;
private Date createddate;
// private Date closeddate;
private String severity;
private String case_language;
private String tags;
private String sbr_groups;
private static final long serialVersionUID = 1L;
public Case() {
super();
}
@Id
public String getCasenumber() {
return this.casenumber;
}
public void setCasenumber(String casenumber) {
this.casenumber = casenumber;
}
@Lob @Field(termVector=TermVector.YES, store=Store.YES)
public String getSubject() {
return this.subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
@Lob @Field(termVector=TermVector.YES)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
@Field(termVector=TermVector.YES, norms=Norms.NO, analyze=Analyze.NO, boost=@Boost(1.2f))
public String getProduct() {
return this.product;
}
public void setProduct(String product) {
this.product = product;
}
@Field(termVector=TermVector.YES, norms=Norms.NO, analyze=Analyze.NO, boost=@Boost(0.7f))
public String getVersion() {
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
public Date getCreateddate() {
return this.createddate;
}
public void setCreateddate(Date createddate) {
this.createddate = createddate;
}
/* Ignored for now as there's some problem in fetching this column -> didn't investigate yet
@Field
public Date getCloseddate() {
return this.closeddate;
}
public void setCloseddate(Date closeddate) {
this.closeddate = closeddate;
}
*/
public String getSeverity() {
return this.severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
@Field(termVector=TermVector.YES, norms=Norms.NO, analyze=Analyze.NO, boost=@Boost(0.7f))
public String getCase_language() {
return this.case_language;
}
public void setCase_language(String case_language) {
this.case_language = case_language;
}
@Field(termVector=TermVector.YES, index = Index.YES, name = "tags")
@Analyzer(definition="tags")
@Column(columnDefinition="text")
public String getTags() {
return this.tags;
}
public void setTags(String tags) {
this.tags = tags;
}
@Field(termVector=TermVector.YES)
@Column(columnDefinition="text")
public String getSbr_groups() {
return this.sbr_groups;
}
public void setSbr_groups(String sbr_groups) {
this.sbr_groups = sbr_groups;
}
} |
package com.b2international.snowowl.snomed.api.rest.components;
import static com.b2international.snowowl.snomed.api.rest.CodeSystemRestRequests.createCodeSystem;
import static com.b2international.snowowl.snomed.api.rest.CodeSystemVersionRestRequests.createVersion;
import static com.b2international.snowowl.snomed.api.rest.CodeSystemVersionRestRequests.getNextAvailableEffectiveDateAsString;
import static com.b2international.snowowl.snomed.api.rest.CodeSystemVersionRestRequests.getVersion;
import static com.b2international.snowowl.snomed.api.rest.SnomedComponentRestRequests.createComponent;
import static com.b2international.snowowl.snomed.api.rest.SnomedComponentRestRequests.getComponent;
import static com.b2international.snowowl.snomed.api.rest.SnomedRestFixtures.createConceptRequestBody;
import static com.b2international.snowowl.test.commons.rest.RestExtensions.lastPathSegment;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import java.util.Map;
import org.eclipse.xtext.util.Pair;
import org.eclipse.xtext.util.Tuples;
import org.junit.Test;
import com.b2international.snowowl.core.api.IBranchPath;
import com.b2international.snowowl.core.date.DateFormats;
import com.b2international.snowowl.core.date.EffectiveTimes;
import com.b2international.snowowl.datastore.BranchPathUtils;
import com.b2international.snowowl.snomed.SnomedConstants.Concepts;
import com.b2international.snowowl.snomed.api.rest.AbstractSnomedApiTest;
import com.b2international.snowowl.snomed.api.rest.SnomedApiTestConstants;
import com.b2international.snowowl.snomed.api.rest.SnomedComponentType;
import com.b2international.snowowl.snomed.api.rest.SnomedRestFixtures;
import com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants;
import com.b2international.snowowl.snomed.core.domain.CharacteristicType;
import com.b2international.snowowl.snomed.core.domain.SnomedConcepts;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMembers;
import com.b2international.snowowl.snomed.datastore.SnomedDatastoreActivator;
import com.b2international.snowowl.snomed.datastore.request.SnomedRequests;
import com.google.common.collect.Maps;
public class SnomedModuleDependencyRefsetTest extends AbstractSnomedApiTest {
private static final String NORWEGIAN_MODULE_CONCEPT_ID = "51000202101";
@Test
public void updateExistingModuleDependencyMembers() {
IBranchPath mainPath = BranchPathUtils.createMainPath();
Map<?, ?> conceptRequestBody = createConceptRequestBody(Concepts.MODULE_ROOT, Concepts.MODULE_SCT_CORE, // it must belong to the core module
SnomedApiTestConstants.UK_PREFERRED_MAP)
.put("commitComment", "Created concept with INT core module")
.build();
String conceptId = lastPathSegment(createComponent(mainPath, SnomedComponentType.CONCEPT, conceptRequestBody)
.statusCode(201)
.body(equalTo(""))
.extract().header("Location"));
getComponent(mainPath, SnomedComponentType.CONCEPT, conceptId)
.statusCode(200)
.body("effectiveTime", nullValue());
// version branch
final String versionEffectiveTime = getNextAvailableEffectiveDateAsString(
SnomedTerminologyComponentConstants.SNOMED_SHORT_NAME);
final Date versionEffectiveDate = EffectiveTimes.parse(versionEffectiveTime, DateFormats.SHORT);
final String versionId = "updateExistingModuleDependencyMembers";
createVersion(SnomedTerminologyComponentConstants.SNOMED_SHORT_NAME, versionId, versionEffectiveTime).statusCode(201);
getVersion(SnomedTerminologyComponentConstants.SNOMED_SHORT_NAME, versionId).statusCode(200);
getComponent(mainPath, SnomedComponentType.CONCEPT, conceptId)
.statusCode(200)
.body("effectiveTime", equalTo(versionEffectiveTime));
SnomedReferenceSetMembers coreModuleDependencyMembersAfterVersioning = SnomedRequests.prepareSearchMember()
.all()
.filterByActive(true)
.filterByModule(Concepts.MODULE_SCT_CORE) // filter for members where the module id is the SCT core module
.filterByRefSet(Concepts.REFSET_MODULE_DEPENDENCY_TYPE)
.build(SnomedDatastoreActivator.REPOSITORY_UUID, mainPath.getPath())
.execute(getBus())
.getSync();
coreModuleDependencyMembersAfterVersioning.forEach(member -> {
assertEquals("Effective time must be updated after versioning", versionEffectiveDate, member.getEffectiveTime());
});
}
@Test
public void moduleDependecyDuplicateMemberTest() {
final String shortName = "SNOMEDCT-MODULEDEPENDENCY";
createCodeSystem(branchPath, shortName).statusCode(201);
Map<Pair<String, String>, Date> moduleToReferencedComponentAndEffectiveDateMap = Maps.newHashMap();
SnomedReferenceSetMembers moduleDependencyMembers1 = SnomedRequests.prepareSearchMember()
.all()
.filterByRefSet(Concepts.REFSET_MODULE_DEPENDENCY_TYPE)
.build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath.getPath())
.execute(getBus())
.getSync();
moduleDependencyMembers1.getItems().forEach(member -> {
Pair<String, String> pair = Tuples.pair(member.getModuleId(), member.getReferencedComponent().getId());
moduleToReferencedComponentAndEffectiveDateMap.put(
pair,
member.getEffectiveTime()
);
});
// create Norwegian module
Map<?, ?> norwegianModuleRequestBody = createConceptRequestBody(Concepts.MODULE_ROOT, NORWEGIAN_MODULE_CONCEPT_ID, SnomedApiTestConstants.UK_PREFERRED_MAP)
.put("id", NORWEGIAN_MODULE_CONCEPT_ID)
.put("commitComment", "Created norwegian module concept")
.build();
createComponent(branchPath, SnomedComponentType.CONCEPT, norwegianModuleRequestBody).statusCode(201);
// create both inferred and stated relationships
Map<?, ?> inferredRelationshipRequestBody = SnomedRestFixtures
.createRelationshipRequestBody(NORWEGIAN_MODULE_CONCEPT_ID, Concepts.IS_A, Concepts.MODULE_ROOT, NORWEGIAN_MODULE_CONCEPT_ID, CharacteristicType.INFERRED_RELATIONSHIP, 0)
.put("commitComment", "Created inferred is_a from the norwegian rule to SCT_MODULE_CORE").build();
Map<?, ?> statedRelationshipRequestBody = SnomedRestFixtures
.createRelationshipRequestBody(NORWEGIAN_MODULE_CONCEPT_ID, Concepts.IS_A, Concepts.MODULE_ROOT, NORWEGIAN_MODULE_CONCEPT_ID, CharacteristicType.STATED_RELATIONSHIP, 0)
.put("commitComment", "Created state is_a from the norwegian rule to SCT_MODULE_CORE").build();
createComponent(branchPath, SnomedComponentType.RELATIONSHIP, inferredRelationshipRequestBody).statusCode(201);
createComponent(branchPath, SnomedComponentType.RELATIONSHIP, statedRelationshipRequestBody).statusCode(201);
SnomedConcepts concepts = SnomedRequests.prepareSearchConcept()
.filterById(NORWEGIAN_MODULE_CONCEPT_ID)
.build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath.getPath())
.execute(getBus())
.getSync();
concepts.forEach(c -> assertEquals("Effective time must still be null", null, c.getEffectiveTime()));
// version branch
final String effectiveDate = getNextAvailableEffectiveDateAsString(SnomedTerminologyComponentConstants.SNOMED_SHORT_NAME);
final String versionId = "testForModuleDependencyMembers";
createVersion(shortName, versionId, effectiveDate).statusCode(201);
getVersion(shortName, versionId).statusCode(200);
SnomedReferenceSetMembers moduleDependencyMembersAfterVersioning = SnomedRequests.prepareSearchMember()
.all()
.filterByRefSet(Concepts.REFSET_MODULE_DEPENDENCY_TYPE)
.build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath.getPath())
.execute(getBus())
.getSync();
moduleDependencyMembersAfterVersioning.getItems().forEach(member-> {
final Pair<String, String> pair = Tuples.pair(member.getModuleId(), member.getReferencedComponent().getId());
final Date originalMemberEffectiveTime = moduleToReferencedComponentAndEffectiveDateMap.get(pair);
final Date versionDate = EffectiveTimes.parse(effectiveDate, DateFormats.SHORT);
if(originalMemberEffectiveTime != null) {
assertEquals("Effective dates on existing module dependency members shouldn't be updated after versioning" , originalMemberEffectiveTime, member.getEffectiveTime());
moduleToReferencedComponentAndEffectiveDateMap.remove(pair);
} else {
assertEquals("The new members effective time should match the versionDate", versionDate, member.getEffectiveTime());
}
});
}
} |
package org.iiitb.os.os_proj.commands;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.iiitb.os.os_proj.UserFile;
import org.iiitb.os.os_proj.db.MongoConnectivity;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
public class Mv implements ICommand {
public ArrayList<String> runCommand(ArrayList<String> params) {
ArrayList<String> result=new ArrayList<String>();
//get 1st and 2nd parameter
int i=0;
String source=params.get(0);
String destination=params.get(1);
MongoConnectivity testMongo=new MongoConnectivity();
Map<String, String> constraints = new HashMap<String, String>();
constraints.put("name", source);
Map<String, String> constraints1 = new HashMap<String, String>();
constraints.put("name", destination);
ArrayList<UserFile> files = testMongo.getFiles(constraints);
ArrayList<UserFile> files1 = testMongo.getFiles(constraints1);
if(files.size()>0&&files1.size()>0){
while(i<files.size()){
String sourceData=files.get(i).getData();
String destinationData=sourceData;
//updateCommon(files1);
result.add("success");
}
}
else if(files.size()>0&&files1.size()<0)
{while(i<files.size()){
String sourceData=files.get(i).getData();
String destinationData=sourceData;
UserFile u=new UserFile();
u.setName("destination");
u.setData(destinationData);
u.setDate_created(null);
u.setDate_updated(null);
u.setFile_size(0);
u.setFiletypeId(1);
u.setPath("/kanchu/desktop");
u.setData(sourceData);
WriteResult wr = testMongo.createFile(u);
if(wr.getError().equals(null))
result.add("success");
}
}
else{
result.add("failure");
result.add("file does not located");
}
System.out.println("result");
//search both paths for existence
//If even one doesn't exist, return error
//else
//Update paths with regex, and change parent paths (3:28 PM idea)
return result;
}
} |
package org.jtrfp.trcl.mem;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import javax.media.opengl.GL3;
import org.jtrfp.trcl.core.TRFuture;
import org.jtrfp.trcl.core.ThreadManager;
import org.jtrfp.trcl.gpu.GLExecutor;
import org.jtrfp.trcl.gpu.GLProgram;
import org.jtrfp.trcl.gpu.GLUniform;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.gpu.MemoryUsageHint;
import org.jtrfp.trcl.gpu.ReallocatableGLTextureBuffer;
import org.jtrfp.trcl.gui.Reporter;
import org.jtrfp.trcl.pool.IndexPool;
import org.jtrfp.trcl.pool.IndexPool.GrowthBehavior;
public final class MemoryManager {
private final IndexPool pageIndexPool = new IndexPool();
private final ByteBuffer [] physicalMemory = new ByteBuffer[1];
private final ReallocatableGLTextureBuffer glPhysicalMemory;
private final GPU gpu;
//private final ThreadManager threadManager;
private final BlockingQueue<WeakReference<PagedByteBuffer>>
newPagedByteBuffers = new ArrayBlockingQueue<WeakReference<PagedByteBuffer>>(1024),
newPagedByteBuffersOverflow = new LinkedBlockingQueue<WeakReference<PagedByteBuffer>>(1024),
deletedPagedByteBuffers = new ArrayBlockingQueue<WeakReference<PagedByteBuffer>>(1024),
deletedPagedByteBuffersOverflow = new LinkedBlockingQueue<WeakReference<PagedByteBuffer>>(1024);
private final ArrayList<WeakReference<PagedByteBuffer>>
pagedByteBuffers = new ArrayList<WeakReference<PagedByteBuffer>>(1024);
private final GLExecutor glExecutor;
/**
* 16MB of zeroes. Don't forget to sync to avoid co-modification of the position.
*/
public static final ByteBuffer ZEROES = ByteBuffer.allocate(1024*1024*16);
public MemoryManager(GPU gpu, final Reporter reporter, final GLExecutor glExecutor){
this.gpu=gpu;
this.glExecutor=glExecutor;
try{
glPhysicalMemory = glExecutor.submitToGL(new Callable<ReallocatableGLTextureBuffer>(){
@Override
public ReallocatableGLTextureBuffer call() throws Exception {
ReallocatableGLTextureBuffer tb;
tb=new ReallocatableGLTextureBuffer(MemoryManager.this.gpu,reporter);
tb.reallocate(PagedByteBuffer.PAGE_SIZE_BYTES);
physicalMemory[0] = tb.map();
tb.setUsageHint(MemoryUsageHint.DymamicDraw);
return tb;
}}).get();
}catch(Exception e){throw new RuntimeException(e);}
pageIndexPool.setGrowthBehavior(new GrowthBehavior(){
@Override
public int grow(final int previousMaxCapacity) {
final int newMaxCapacity = previousMaxCapacity!=0?previousMaxCapacity*2:1;
final TRFuture<Integer> ft = glExecutor.submitToGL(new Callable<Integer>(){
@Override
public Integer call(){
glPhysicalMemory.reallocate(newMaxCapacity*PagedByteBuffer.PAGE_SIZE_BYTES);
physicalMemory[0] = glPhysicalMemory.map();
return newMaxCapacity;
}//end call()
});
try{return ft.get();}catch(Exception e){e.printStackTrace();}
return previousMaxCapacity;//Fail by maintaining original size
}//end grow(...)
@Override
public int shrink(final int minDesiredMaxCapacity){
final int currentMaxCapacity = pageIndexPool.getMaxCapacity();
final int proposedMaxCapacity = currentMaxCapacity/2;//TODO: This adjusts by a single power of 2, take arbitrary power of 2 instead
if(proposedMaxCapacity >= minDesiredMaxCapacity){
final TRFuture<Integer> ft = glExecutor.submitToGL(new Callable<Integer>(){
@Override
public Integer call(){
glPhysicalMemory.reallocate(proposedMaxCapacity*PagedByteBuffer.PAGE_SIZE_BYTES);
physicalMemory[0] = glPhysicalMemory.map();
return proposedMaxCapacity;
}//end call()
});
try{return ft.get();}catch(Exception e){e.printStackTrace();return currentMaxCapacity;}
}else return currentMaxCapacity;
}//end shrink
});
}//end constructor
public int getMaxCapacityInBytes(){
return PagedByteBuffer.PAGE_SIZE_BYTES*pageIndexPool.getMaxCapacity();
}
public void map(){
if((physicalMemory[0] = glPhysicalMemory.map())==null)throw new NullPointerException("Failed to map GPU memory. (returned null)");
}
public void flushRange(int startPositionInBytes, int lengthInBytes){
glPhysicalMemory.flushRange(startPositionInBytes, lengthInBytes);
}
public void unmap(){
physicalMemory[0]=null;//Make sure we don't start reading/writing somewhere bad.
glPhysicalMemory.unmap();
}
public PagedByteBuffer createPagedByteBuffer(int initialSizeInBytes, String debugName){
return new PagedByteBuffer(gpu, physicalMemory, pageIndexPool, initialSizeInBytes, debugName);
}
void registerPagedByteBuffer(WeakReference<PagedByteBuffer> b){
try{newPagedByteBuffers.add(b);}
catch(IllegalStateException e){
newPagedByteBuffersOverflow.offer(b);
}
}
void deRegisterPagedByteBuffer(WeakReference<PagedByteBuffer> b){
try{deletedPagedByteBuffers.add(b);}
catch(IllegalStateException e){
deletedPagedByteBuffersOverflow.offer(b);
}
}
private final ArrayList<WeakReference<PagedByteBuffer>> toRemove = new ArrayList<WeakReference<PagedByteBuffer>>();
public void flushStalePages(){
if(!glPhysicalMemory.isMapped())
return;
deletedPagedByteBuffers.drainTo(toRemove);
deletedPagedByteBuffersOverflow.drainTo(toRemove);
pagedByteBuffers.removeAll(toRemove);
toRemove.clear();
newPagedByteBuffers.drainTo(pagedByteBuffers);
newPagedByteBuffersOverflow.drainTo(pagedByteBuffers);
final Iterator<WeakReference<PagedByteBuffer>> it = pagedByteBuffers.iterator();
while(it.hasNext()){
final WeakReference<PagedByteBuffer> r = it.next();
if(r.get()==null)
it.remove();
else{
r.get().flushStalePages();
}//end else{}
}//end while(hasNext)
}//end flushStalePages()
public void bindToUniform(int textureUnit, GLProgram shaderProgram, GLUniform uniform) {
glPhysicalMemory.bindToUniform(textureUnit, shaderProgram, uniform);
}
public void dumpAllGPUMemTo(final ByteBuffer dest) {
if(dest==null)
throw new NullPointerException("Destination intolerably null.");
glExecutor.submitToGL(new Callable<Void>(){
@Override
public Void call() throws Exception {
final GL3 gl = gpu.getGl();
unmap();
glPhysicalMemory.bind();
ByteBuffer bb = gl.glMapBuffer(GL3.GL_TEXTURE_BUFFER, GL3.GL_READ_ONLY);
bb.clear();
dest.clear();
bb.limit(dest.limit());//Avoid overflow
dest.put(bb);
gl.glUnmapBuffer(GL3.GL_TEXTURE_BUFFER);
map();
glPhysicalMemory.unbind();
return null;
}}).get();
dest.clear();
}//end dumpAllGPUMemTo(...)
}//end MemmoryManager |
package org.lightmare.deploy;
import static org.lightmare.cache.MetaContainer.closeConnections;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.Entity;
import org.apache.log4j.Logger;
import org.lightmare.annotations.UnitName;
import org.lightmare.cache.ArchiveData;
import org.lightmare.cache.DeployData;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.TmpResources;
import org.lightmare.config.Configuration;
import org.lightmare.deploy.fs.Watcher;
import org.lightmare.jpa.JPAManager;
import org.lightmare.jpa.datasource.DataSourceInitializer;
import org.lightmare.jpa.datasource.PoolConfig;
import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.remote.rpc.RPCall;
import org.lightmare.remote.rpc.RpcListener;
import org.lightmare.rest.utils.RestUtils;
import org.lightmare.scannotation.AnnotationDB;
import org.lightmare.utils.AbstractIOUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.fs.FileUtils;
import org.lightmare.utils.fs.WatchUtils;
import org.lightmare.utils.reflect.MetaUtils;
import org.lightmare.utils.shutdown.ShutDown;
/**
* Determines and saves in cache ejb beans {@link org.lightmare.cache.MetaData}
* on startup
*
* @author Levan
*
*/
public class MetaCreator {
private static AnnotationDB annotationDB;
private TmpResources tmpResources;
private boolean await;
// Blocker for deployments
private CountDownLatch conn;
// Data for cache at deploy time
private Map<String, AbstractIOUtils> aggregateds = new HashMap<String, AbstractIOUtils>();
private Map<URL, ArchiveData> archivesURLs;
private Map<String, URL> classOwnersURL;
private Map<URL, DeployData> realURL;
private ClassLoader current;
private Configuration config;
private static final Logger LOG = Logger.getLogger(MetaCreator.class);
private MetaCreator() {
tmpResources = new TmpResources();
ShutDown.setHook(tmpResources);
}
private static MetaCreator get() {
MetaCreator creator = MetaContainer.getCreator();
if (creator == null) {
synchronized (MetaCreator.class) {
if (creator == null) {
creator = new MetaCreator();
MetaContainer.setCreator(creator);
}
}
}
return creator;
}
public AnnotationDB getAnnotationDB() {
return annotationDB;
}
/**
* Checks weather {@link javax.persistence.Entity} annotated classes is need
* to be filtered by {@link org.lightmare.annotations.UnitName} value
*
* @param className
* @return boolean
* @throws IOException
*/
private boolean checkForUnitName(String className, Configuration cloneConfig)
throws IOException {
boolean isValid = Boolean.FALSE;
Class<?> entityClass;
entityClass = MetaUtils.initClassForName(className);
UnitName annotation = entityClass.getAnnotation(UnitName.class);
isValid = annotation.value().equals(cloneConfig.getAnnotatedUnitName());
return isValid;
}
private List<String> translateToList(Set<String> classSet) {
String[] classArray = new String[classSet.size()];
classArray = ObjectUtils.toArray(classSet, String.class);
List<String> classList = Arrays.asList(classArray);
return classList;
}
/**
* Defines belonginess of {@link javax.persistence.Entity} annotated classes
* to jar file
*
* @param classSet
* @return {@link List}<String>
*/
private void filterEntitiesForJar(Set<String> classSet,
String fileNameForBean) {
Map<String, String> classOwnersFiles = annotationDB
.getClassOwnersFiles();
String fileNameForEntity;
for (String entityName : classSet) {
fileNameForEntity = classOwnersFiles.get(entityName);
if (ObjectUtils.notNull(fileNameForEntity)
&& ObjectUtils.notNull(fileNameForBean)
&& !fileNameForEntity.equals(fileNameForBean)) {
classSet.remove(entityName);
}
}
}
/**
* Filters {@link javax.persistence.Entity} annotated classes by name or by
* {@link org.lightmare.annotations.UnitName} by configuration
*
* @param classSet
* @return {@link List}<String>
* @throws IOException
*/
private List<String> filterEntities(Set<String> classSet,
Configuration cloneConfig) throws IOException {
List<String> classes;
if (config.getAnnotatedUnitName() == null) {
classes = translateToList(classSet);
} else {
Set<String> filtereds = new HashSet<String>();
for (String className : classSet) {
if (checkForUnitName(className, cloneConfig)) {
filtereds.add(className);
}
}
classes = translateToList(filtereds);
}
return classes;
}
/**
* Creates connection associated with unit name if such does not exists
*
* @param unitName
* @param beanName
* @throws IOException
*/
protected void configureConnection(String unitName, String beanName,
ClassLoader loader, Configuration cloneConfig) throws IOException {
JPAManager.Builder builder = new JPAManager.Builder();
Map<String, String> classOwnersFiles = annotationDB
.getClassOwnersFiles();
AbstractIOUtils ioUtils = aggregateds.get(beanName);
if (ObjectUtils.notNull(ioUtils)) {
URL jarURL = ioUtils.getAppropriatedURL(classOwnersFiles, beanName);
builder.setURL(jarURL);
}
if (cloneConfig.isScanForEntities()) {
Set<String> classSet;
Map<String, Set<String>> annotationIndex = annotationDB
.getAnnotationIndex();
classSet = annotationIndex.get(Entity.class.getName());
String annotatedUnitName = config.getAnnotatedUnitName();
if (annotatedUnitName == null) {
classSet = annotationIndex.get(Entity.class.getName());
} else if (annotatedUnitName.equals(unitName)) {
Set<String> unitNamedSet = annotationIndex.get(UnitName.class
.getName());
classSet.retainAll(unitNamedSet);
}
if (ObjectUtils.notNull(ioUtils)) {
String fileNameForBean = classOwnersFiles.get(beanName);
filterEntitiesForJar(classSet, fileNameForBean);
}
List<String> classes = filterEntities(classSet, cloneConfig);
builder.setClasses(classes);
}
builder.setPath(cloneConfig.getPersXmlPath())
.setProperties(config.getPersistenceProperties())
.setSwapDataSource(cloneConfig.isSwapDataSource())
.setScanArchives(cloneConfig.isScanArchives())
.setClassLoader(loader).build().setConnection(unitName);
}
/**
* Caches each archive by it's {@link URL} for deployment
*
* @param ejbURLs
* @param archiveData
*/
private void fillArchiveURLs(Collection<URL> ejbURLs,
ArchiveData archiveData, DeployData deployData) {
for (URL ejbURL : ejbURLs) {
archivesURLs.put(ejbURL, archiveData);
realURL.put(ejbURL, deployData);
}
}
/**
* Caches each archive by it's {@link URL} for deployment and creates fill
* {@link URL} array for scanning and finding {@link javax.ejb.Stateless}
* annotated classes
*
* @param archive
* @param modifiedArchives
* @throws IOException
*/
private void fillArchiveURLs(URL archive, List<URL> modifiedArchives)
throws IOException {
AbstractIOUtils ioUtils = AbstractIOUtils.getAppropriatedType(archive);
if (ObjectUtils.notNull(ioUtils)) {
ioUtils.scan(config.isPersXmlFromJar());
List<URL> ejbURLs = ioUtils.getEjbURLs();
modifiedArchives.addAll(ejbURLs);
ArchiveData archiveData = new ArchiveData();
archiveData.setIoUtils(ioUtils);
DeployData deployData = new DeployData();
deployData.setType(ioUtils.getType());
deployData.setUrl(archive);
if (ejbURLs.isEmpty()) {
archivesURLs.put(archive, archiveData);
realURL.put(archive, deployData);
} else {
fillArchiveURLs(ejbURLs, archiveData, deployData);
}
}
}
/**
* Gets {@link URL} array for all classes and jar libraries within archive
* file for class loading policy
*
* @param archives
* @return {@link URL}[]
* @throws IOException
*/
private URL[] getFullArchives(URL[] archives) throws IOException {
List<URL> modifiedArchives = new ArrayList<URL>();
for (URL archive : archives) {
fillArchiveURLs(archive, modifiedArchives);
}
return ObjectUtils.toArray(modifiedArchives, URL.class);
}
/**
* Awaits for {@link Future} tasks if it set so by configuration
*
* @param future
*/
private void awaitDeployment(Future<String> future) {
if (await) {
try {
String nameFromFuture = future.get();
LOG.info(String.format("Deploy processing of %s finished",
nameFromFuture));
} catch (InterruptedException ex) {
LOG.error(ex.getMessage(), ex);
} catch (ExecutionException ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
/**
* Awaits for {@link CountDownLatch} of deployments
*/
private void awaitDeployments() {
try {
conn.await();
} catch (InterruptedException ex) {
LOG.error(ex);
}
}
/**
* Starts bean deployment process for bean name
*
* @param beanName
* @throws IOException
*/
private void deployBean(String beanName) throws IOException {
URL currentURL = classOwnersURL.get(beanName);
ArchiveData archiveData = archivesURLs.get(currentURL);
if (archiveData == null) {
archiveData = new ArchiveData();
}
AbstractIOUtils ioUtils = archiveData.getIoUtils();
if (ioUtils == null) {
ioUtils = AbstractIOUtils.getAppropriatedType(currentURL);
archiveData.setIoUtils(ioUtils);
}
ClassLoader loader = archiveData.getLoader();
// Finds appropriated ClassLoader if needed and or creates new one
List<File> tmpFiles = null;
if (ObjectUtils.notNull(ioUtils)) {
if (loader == null) {
if (!ioUtils.isExecuted()) {
ioUtils.scan(config.isPersXmlFromJar());
}
URL[] libURLs = ioUtils.getURLs();
loader = LibraryLoader.initializeLoader(libURLs);
archiveData.setLoader(loader);
}
tmpFiles = ioUtils.getTmpFiles();
aggregateds.put(beanName, ioUtils);
}
// Archive file url which contains this bean
DeployData deployData;
if (ObjectUtils.available(realURL)) {
deployData = realURL.get(currentURL);
} else {
deployData = null;
}
// Initializes and fills BeanLoader.BeanParameters class to deploy
// stateless ejb bean
BeanLoader.BeanParameters parameters = new BeanLoader.BeanParameters();
parameters.creator = this;
parameters.className = beanName;
parameters.loader = loader;
parameters.tmpFiles = tmpFiles;
parameters.conn = conn;
parameters.deployData = deployData;
parameters.config = config;
Future<String> future = BeanLoader.loadBean(parameters);
awaitDeployment(future);
if (ObjectUtils.available(tmpFiles)) {
tmpResources.addFile(tmpFiles);
}
}
/**
* Deploys single bean by class name
*
* @param beanNames
*/
private void deployBeans(Set<String> beanNames) {
conn = new CountDownLatch(beanNames.size());
for (String beanName : beanNames) {
LOG.info(String.format("deploing bean %s", beanName));
try {
deployBean(beanName);
} catch (IOException ex) {
LOG.error(String.format("Could not deploy bean %s", beanName),
ex);
}
}
awaitDeployments();
if (MetaContainer.hasRest()) {
RestUtils.reload();
}
boolean hotDeployment = config.isHotDeployment();
boolean watchStatus = config.isWatchStatus();
if (hotDeployment && ObjectUtils.notTrue(watchStatus)) {
Watcher.startWatch();
watchStatus = Boolean.TRUE;
}
}
/**
* Scan application for find all {@link javax.ejb.Stateless} beans and
* {@link Remote} or {@link Local} proxy interfaces
*
* @param archives
* @throws IOException
* @throws ClassNotFoundException
*/
public void scanForBeans(URL[] archives) throws IOException {
synchronized (this) {
if (config == null && ObjectUtils.available(archives)) {
config = MetaContainer.getConfig(archives);
}
try {
// starts RPC server if configured as remote and server
if (config.isRemote() && Configuration.isServer()) {
RpcListener.startServer(config);
} else if (config.isRemote()) {
RPCall.configure(config);
}
String[] libraryPaths = config.getLibraryPaths();
// Loads libraries from specified path
if (ObjectUtils.notNull(libraryPaths)) {
LibraryLoader.loadLibraries(libraryPaths);
}
// Gets and caches class loader
current = LibraryLoader.getContextClassLoader();
archivesURLs = new HashMap<URL, ArchiveData>();
if (ObjectUtils.available(archives)) {
realURL = new HashMap<URL, DeployData>();
}
URL[] fullArchives = getFullArchives(archives);
annotationDB = new AnnotationDB();
annotationDB.setScanFieldAnnotations(Boolean.FALSE);
annotationDB.setScanParameterAnnotations(Boolean.FALSE);
annotationDB.setScanMethodAnnotations(Boolean.FALSE);
annotationDB.scanArchives(fullArchives);
Set<String> beanNames = annotationDB.getAnnotationIndex().get(
Stateless.class.getName());
classOwnersURL = annotationDB.getClassOwnersURLs();
DataSourceInitializer.initializeDataSources(config);
if (ObjectUtils.available(beanNames)) {
deployBeans(beanNames);
}
} finally {
// Caches configuration
MetaContainer.putConfig(archives, config);
// clears cached resources
clear();
// gets rid from all created temporary files
tmpResources.removeTempFiles();
}
}
}
/**
* Scan application for find all {@link javax.ejb.Stateless} beans and
* {@link Remote} or {@link Local} proxy interfaces
*
* @throws ClassNotFoundException
* @throws IOException
*/
public void scanForBeans(File[] jars) throws IOException {
List<URL> urlList = new ArrayList<URL>();
URL url;
for (File file : jars) {
url = file.toURI().toURL();
urlList.add(url);
}
URL[] archives = ObjectUtils.toArray(urlList, URL.class);
scanForBeans(archives);
}
/**
* Scan application for find all {@link javax.ejb.Stateless} beans and
* {@link Remote} or {@link Local} proxy interfaces
*
* @throws ClassNotFoundException
* @throws IOException
*/
public void scanForBeans(String... paths) throws IOException {
if (ObjectUtils.notAvailable(paths)
&& ObjectUtils.available(config.getDeploymentPath())) {
Set<DeploymentDirectory> deployments = config.getDeploymentPath();
List<String> pathList = new ArrayList<String>();
File deployFile;
for (DeploymentDirectory deployment : deployments) {
deployFile = new File(deployment.getPath());
if (deployment.isScan()) {
String[] subDeployments = deployFile.list();
if (ObjectUtils.available(subDeployments)) {
pathList.addAll(Arrays.asList(subDeployments));
}
}
}
paths = ObjectUtils.toArray(pathList, String.class);
}
List<URL> urlList = new ArrayList<URL>();
List<URL> archive;
for (String path : paths) {
archive = FileUtils.toURLWithClasspath(path);
urlList.addAll(archive);
}
URL[] archives = ObjectUtils.toArray(urlList, URL.class);
scanForBeans(archives);
}
public ClassLoader getCurrent() {
return current;
}
/**
* Closes all existing connections
*/
public static void closeAllConnections() {
closeConnections();
}
public void clear() {
if (ObjectUtils.available(realURL)) {
realURL.clear();
realURL = null;
}
if (ObjectUtils.available(aggregateds)) {
aggregateds.clear();
}
if (ObjectUtils.available(archivesURLs)) {
archivesURLs.clear();
archivesURLs = null;
}
if (ObjectUtils.available(classOwnersURL)) {
classOwnersURL.clear();
classOwnersURL = null;
}
config = null;
}
/**
* Closes all connections clears all caches
*/
public static void close() {
closeConnections();
MetaContainer.clear();
}
/**
* Builder class to provide properties for lightmare
*
* @author levan
*
*/
public static class Builder {
private MetaCreator creator;
public Builder(boolean cloneConfiguration) throws IOException {
creator = MetaCreator.get();
Configuration config = creator.config;
if (cloneConfiguration && ObjectUtils.notNull(config)) {
try {
creator.config = (Configuration) config.clone();
} catch (CloneNotSupportedException ex) {
throw new IOException(ex);
}
} else {
creator.config = new Configuration();
}
}
public Builder() throws IOException {
this(Boolean.FALSE);
}
private void initPoolProperties() {
if (ObjectUtils.notAvailable(PoolConfig.poolProperties)) {
PoolConfig.poolProperties = new HashMap<Object, Object>();
}
}
/**
* Sets additional persistence properties
*
* @param properties
* @return {@link Builder}
*/
public Builder setPersistenceProperties(Map<String, String> properties) {
if (ObjectUtils.available(properties)) {
Map<Object, Object> persistenceProperties = new HashMap<Object, Object>();
persistenceProperties.putAll(properties);
creator.config.setPersistenceProperties(persistenceProperties);
}
return this;
}
/**
* Adds property to scan for {@link javax.persistence.Entity} annotated
* classes from deployed archives
*
* @param scanForEnt
* @return {@link Builder}
*/
public Builder setScanForEntities(boolean scanForEnt) {
creator.config.setScanForEntities(scanForEnt);
return this;
}
/**
* Adds property to use only {@link org.lightmare.annotations.UnitName}
* annotated entities for which
* {@link org.lightmare.annotations.UnitName#value()} matches passed
* unit name
*
* @param unitName
* @return {@link Builder}
*/
public Builder setUnitName(String unitName) {
creator.config.setAnnotatedUnitName(unitName);
return this;
}
/**
* Sets path for persistence.xml file
*
* @param path
* @return {@link Builder}
*/
public Builder setPersXmlPath(String path) {
creator.config.setPersXmlPath(path);
creator.config.setScanArchives(Boolean.FALSE);
return this;
}
/**
* Adds path for additional libraries to load at start time
*
* @param libPaths
* @return {@link Builder}
*/
public Builder setLibraryPath(String... libPaths) {
creator.config.setLibraryPaths(libPaths);
return this;
}
/**
* Additional boolean checker to scan persistence.xml files from
* appropriated jar files
*
* @param xmlFromJar
* @return {@link Builder}
*/
public Builder setXmlFromJar(boolean xmlFromJar) {
creator.config.setPersXmlFromJar(xmlFromJar);
return this;
}
/**
* Additional boolean checker to swap jta data source value with non jta
* data source value
*
* @param swapDataSource
* @return {@link Builder}
*/
public Builder setSwapDataSource(boolean swapDataSource) {
creator.config.setSwapDataSource(swapDataSource);
return this;
}
/**
* Adds path for data source file
*
* @param dataSourcePath
* @return {@link Builder}
*/
public Builder addDataSourcePath(String dataSourcePath) {
creator.config.addDataSourcePath(dataSourcePath);
return this;
}
/**
* This method is deprecated should use
* {@link MetaCreator.Builder#addDataSourcePath(String)} instead
*
* @param dataSourcePath
* @return {@link MetaCreator.Builder}
*/
@Deprecated
public Builder setDataSourcePath(String dataSourcePath) {
creator.config.addDataSourcePath(dataSourcePath);
return this;
}
/**
* Additional boolean checker to scan {@link javax.persistence.Entity}
* annotated classes from appropriated deployed archive files
*
* @param scanArchives
* @return {@link Builder}
*/
public Builder setScanArchives(boolean scanArchives) {
creator.config.setScanArchives(scanArchives);
return this;
}
/**
* Additional boolean checker to block deployment processes
*
* @param await
* @return {@link Builder}
*/
public Builder setAwaitSeploiment(boolean await) {
creator.await = await;
return this;
}
/**
* Sets propert
*
* @param path
* @return {@link Builder}
*/
public Builder setRemote(boolean remote) {
creator.config.setRemote(remote);
return this;
}
public Builder setServer(boolean server) {
Configuration.setServer(server);
creator.config.setClient(!server);
return this;
}
public Builder setClient(boolean client) {
creator.config.setClient(client);
Configuration.setServer(!client);
return this;
}
public Builder setProperty(String key, String property) {
creator.config.putValue(key, property);
return this;
}
public Builder setAdminUsersPth(String property) {
Configuration.setAdminUsersPath(property);
return this;
}
public Builder setIpAddress(String property) {
creator.config.putValue(Configuration.IP_ADDRESS, property);
return this;
}
public Builder setPort(String property) {
creator.config.putValue(Configuration.PORT, property);
return this;
}
public Builder setMasterThreads(String property) {
creator.config.putValue(Configuration.BOSS_POOL, property);
return this;
}
public Builder setWorkerThreads(String property) {
creator.config.putValue(Configuration.WORKER_POOL, property);
return this;
}
public Builder addDeploymentPath(String deploymentPath, boolean scan) {
String clearPath = WatchUtils.clearPath(deploymentPath);
creator.config.addDeploymentPath(clearPath, scan);
return this;
}
public Builder addDeploymentPath(String deploymentPath) {
addDeploymentPath(deploymentPath, Boolean.FALSE);
return this;
}
public Builder setTimeout(String property) {
creator.config.putValue(Configuration.CONNECTION_TIMEOUT, property);
return this;
}
public Builder setDataSourcePooledType(boolean dsPooledType) {
JPAManager.pooledDataSource = dsPooledType;
return this;
}
public Builder setPoolProviderType(PoolProviderType poolProviderType) {
PoolConfig.poolProviderType = poolProviderType;
return this;
}
public Builder setPoolPropertiesPath(String path) {
PoolConfig.poolPath = path;
return this;
}
public Builder setPoolProperties(Properties properties) {
initPoolProperties();
PoolConfig.poolProperties.putAll(properties);
return this;
}
public Builder addPoolProperty(Object key, Object value) {
initPoolProperties();
PoolConfig.poolProperties.put(key, value);
return this;
}
public Builder setHotDeployment(boolean hotDeployment) {
creator.config.setHotDeployment(hotDeployment);
return this;
}
public MetaCreator build() throws IOException {
creator.config.configure();
LOG.info("Lightmare application starts working");
return creator;
}
}
} |
package se.nielstrom.greed;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import se.nielstrom.greed.DieButton.StateChangeListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class GameActivity extends Activity {
public final int minScore = 300;
public final int nrDice = 6;
private DieButton[] diceButtons = new DieButton[nrDice];
private int round = 0;
private int totalScore = 0;
private int previousScore = 0;
private int roundScore = 0;
private int roundScoreBonus = 0;
private boolean firstRoll = true;
private List<Integer> dice = new ArrayList<>(nrDice);
private int nrChecked = nrDice;
private enum Score { OK, LOW, BUST }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
}
@Override
protected void onResume() {
super.onResume();
diceButtons[0] = (DieButton)findViewById(R.id.die_a);
diceButtons[1] = (DieButton)findViewById(R.id.die_b);
diceButtons[2] = (DieButton)findViewById(R.id.die_c);
diceButtons[3] = (DieButton)findViewById(R.id.die_d);
diceButtons[4] = (DieButton)findViewById(R.id.die_e);
diceButtons[5] = (DieButton)findViewById(R.id.die_f);
for(DieButton die : diceButtons) {
die.setEnabled(false);
die.addStateChangeListener(new StateChangeListener() {
@Override
public void onStateChange(DieButton button) {
nrChecked += (button.isChecked()) ? 1 : -1;
checkMinScore();
}
});
}
setRound(0);
setRoundScore(0);
setTotalScore(0);
setFirstRoll(true);
for(DieButton die : diceButtons) {
die.setEnabled(false);
}
}
public void rollDice(View v) {
if (isFirstRoll()) {
for(DieButton die : diceButtons) {
die.setEnabled(true);
die.setChecked(true);
}
nrChecked = nrDice;
previousScore = 0;
} else if (allDiceAreUsed(dice) && nrChecked == 0) {
previousScore = roundScoreBonus = getRoundScore();
for(DieButton die : diceButtons) {
die.setEnabled(true);
die.setChecked(true);
}
nrChecked = nrDice;
enableRollButton(false);
} else {
previousScore = getRoundScore();
}
dice.clear();
for(DieButton die : diceButtons) {
if (die.isChecked()) {
int side = (new Random()).nextInt(5) + 1;
die.setText("" + side);
dice.add(side);
} else {
die.setEnabled(false);
int side = Integer.parseInt((String) die.getText());
dice.add(side);
}
}
int score = calculateScore(dice) + roundScoreBonus;
if (isFirstRoll() && score < minScore) { // Low initial score
setRoundScore(score);
setScoreState(Score.LOW);
claimHelper(0);
enableRollButton(true);
} else if (score <= previousScore) { // No new points, bust
setRoundScore(0);
setScoreState(Score.BUST);
claimRound(null);
enableRollButton(true);
}else {
setRoundScore(score);
setScoreState(Score.OK);
enableRollButton(false);
setFirstRoll(false);
}
}
private boolean allDiceAreUsed(List<Integer> dice) {
Map<Integer, Integer> diceMap = aggregateDice(dice);
if(diceMap.size() != nrDice) { // unless we have a ladder
for(Entry<Integer, Integer> entry : diceMap.entrySet()) {
if(( entry.getKey() != 1 && entry.getKey() != 5) // if side is 2,3,4 or 6
&& entry.getValue() % 3 != 0 ) { // and the number of dice is not a multiple of 3
return false;
}
}
}
return true;
}
private void setScoreState(Score state) {
TextView text = (TextView) findViewById(R.id.round_points);
int color_id;
switch (state) {
case LOW:
color_id = R.color.score_low;
break;
case BUST:
color_id = R.color.score_bust;
break;
case OK:
default:
color_id = R.color.score_ok;
break;
}
text.setTextColor(getResources().getColor(color_id));
}
private void checkMinScore() {
List<Integer> uncheckedDice = new ArrayList<>();
for(DieButton die : diceButtons) {
if (!die.isChecked()) {
int side = Integer.parseInt((String) die.getText());
uncheckedDice.add(side);
}
}
int score = calculateScore(uncheckedDice) + roundScoreBonus;
setRoundScore(score);
enableRollButton(score > Math.max(minScore-1, previousScore));
}
public void claimRound(View v) {
claimHelper(getRoundScore());
setRoundScore(0);
enableRollButton(true);
}
private void enableRollButton(boolean enable) {
Button button = (Button) findViewById(R.id.roll_button);
button.setEnabled(enable);
}
public void claimHelper(int score) {
setTotalScore(getTotalScore() + score);
setRound(getRound() + 1);
setFirstRoll(true);
roundScoreBonus = 0;
for(DieButton die : diceButtons) {
die.setEnabled(false);
}
}
public boolean isFirstRoll() {
return firstRoll;
}
public void setFirstRoll(boolean firstRoll) {
this.firstRoll = firstRoll;
Button button = (Button) findViewById(R.id.claim_button);
button.setEnabled(!firstRoll);
}
public int getRound() {
return round;
}
public void setRound(int round) {
this.round = round;
TextView roundText = (TextView) findViewById(R.id.rounds);
roundText.setText(round + " " + getResources().getString(R.string.rounds));
}
public int getRoundScore() {
return roundScore;
}
public void setRoundScore(int score) {
roundScore = score;
TextView roundText = (TextView) findViewById(R.id.round_points);
roundText.setText(roundScore + " " + getResources().getString(R.string.points));
}
public int getTotalScore() {
return totalScore;
}
public void setTotalScore(int score) {
totalScore = score;
TextView totalText = (TextView) findViewById(R.id.total_points);
totalText.setText((totalScore) + " " + getResources().getString(R.string.total));
}
private int calculateScore(List<Integer> dice) {
int score = 0;
Map<Integer, Integer> diceMap = aggregateDice(dice);
if (diceMap.size() == nrDice) { // 6 different sides means it's a ladder
score = 1000;
} else {
// Calculate the score for each kind of side
for (Entry<Integer, Integer> entry : diceMap.entrySet()){
score += scoreHelper(entry.getKey(), entry.getValue());
}
}
return score;
}
private Map<Integer, Integer> aggregateDice(List<Integer> dice) {
Map<Integer, Integer> diceMap = new HashMap<>(nrDice);
for(Integer side: dice) {
Integer previousNumber = diceMap.get(side);
int newNumber = (previousNumber == null) ? 1 : previousNumber + 1;
diceMap.put(side, newNumber);
}
return diceMap;
}
private int scoreHelper(int side, int number) {
if(number >= 3) {
int score = (side == 1) ? 1000 : 100*side;
return score + scoreHelper(side, number - 3);
} else if (side == 1) {
return number * 100;
} else if (side == 5) {
return number * 50;
} else {
return 0;
}
}
} |
package org.lightmare.deploy;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.Entity;
import org.apache.log4j.Logger;
import org.lightmare.annotations.UnitName;
import org.lightmare.cache.ArchiveData;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.DeployData;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.RestContainer;
import org.lightmare.cache.TmpResources;
import org.lightmare.config.Config;
import org.lightmare.config.Configuration;
import org.lightmare.deploy.fs.Watcher;
import org.lightmare.jpa.JPAManager;
import org.lightmare.jpa.datasource.Initializer;
import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.remote.rpc.RPCall;
import org.lightmare.remote.rpc.RpcListener;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.scannotation.AnnotationDB;
import org.lightmare.utils.AbstractIOUtils;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.fs.FileUtils;
import org.lightmare.utils.fs.WatchUtils;
import org.lightmare.utils.reflect.MetaUtils;
import org.lightmare.utils.shutdown.ShutDown;
/**
* Determines and saves in cache ejb beans {@link org.lightmare.cache.MetaData}
* on startup
*
* @author Levan
*
*/
public class MetaCreator {
private static AnnotationDB annotationDB;
private TmpResources tmpResources;
private boolean await;
// Blocker for deployments connections or beans
private CountDownLatch blocker;
// Data for cache at deploy time
private Map<String, AbstractIOUtils> aggregateds = new HashMap<String, AbstractIOUtils>();
private Map<URL, ArchiveData> archivesURLs;
private Map<String, URL> classOwnersURL;
private Map<URL, DeployData> realURL;
private ClassLoader current;
// Configuration for appropriate archives URLs
private Configuration configuration;
// Lock for deployment and directory scanning
private final Lock scannerLock = new ReentrantLock();
// Lock for MetaCreator initialization
private static final Lock LOCK = new ReentrantLock();
private static final Logger LOG = Logger.getLogger(MetaCreator.class);
private MetaCreator() {
tmpResources = new TmpResources();
ShutDown.setHook(tmpResources);
}
private static MetaCreator get() {
MetaCreator creator = MetaContainer.getCreator();
if (creator == null) {
LOCK.lock();
try {
if (creator == null) {
creator = new MetaCreator();
MetaContainer.setCreator(creator);
}
} finally {
LOCK.unlock();
}
}
return creator;
}
private void configure(URL[] archives) {
if (configuration == null && ObjectUtils.available(archives)) {
configuration = MetaContainer.getConfig(archives);
}
}
public AnnotationDB getAnnotationDB() {
return annotationDB;
}
/**
* Checks weather {@link javax.persistence.Entity} annotated classes is need
* to be filtered by {@link org.lightmare.annotations.UnitName} value
*
* @param className
* @return boolean
* @throws IOException
*/
private boolean checkForUnitName(String className, Configuration cloneConfig)
throws IOException {
boolean isValid = Boolean.FALSE;
Class<?> entityClass;
entityClass = MetaUtils.initClassForName(className);
UnitName annotation = entityClass.getAnnotation(UnitName.class);
isValid = annotation.value().equals(cloneConfig.getAnnotatedUnitName());
return isValid;
}
/**
* Defines belonginess of {@link javax.persistence.Entity} annotated classes
* to jar file
*
* @param classSet
* @return {@link List}<String>
*/
private void filterEntitiesForJar(Set<String> classSet,
String fileNameForBean) {
Map<String, String> classOwnersFiles = annotationDB
.getClassOwnersFiles();
String fileNameForEntity;
for (String entityName : classSet) {
fileNameForEntity = classOwnersFiles.get(entityName);
if (ObjectUtils.notNullAll(fileNameForEntity, fileNameForBean)
&& ObjectUtils.notTrue(fileNameForEntity
.equals(fileNameForBean))) {
classSet.remove(entityName);
}
}
}
/**
* Filters {@link javax.persistence.Entity} annotated classes by name or by
* {@link org.lightmare.annotations.UnitName} by configuration
*
* @param classSet
* @return {@link List}<String>
* @throws IOException
*/
private List<String> filterEntities(Set<String> classSet,
Configuration configClone) throws IOException {
List<String> classes;
if (configClone.getAnnotatedUnitName() == null) {
classes = CollectionUtils.translateToList(classSet);
} else {
Set<String> filtereds = new HashSet<String>();
for (String className : classSet) {
if (checkForUnitName(className, configClone)) {
filtereds.add(className);
}
}
classes = CollectionUtils.translateToList(filtereds);
}
return classes;
}
/**
* Creates connection associated with unit name if such does not exists
*
* @param unitName
* @param beanName
* @throws IOException
*/
protected void configureConnection(String unitName, String beanName,
ClassLoader loader, Configuration configClone) throws IOException {
JPAManager.Builder builder = new JPAManager.Builder();
Map<String, String> classOwnersFiles = annotationDB
.getClassOwnersFiles();
AbstractIOUtils ioUtils = aggregateds.get(beanName);
if (ObjectUtils.notNull(ioUtils)) {
URL jarURL = ioUtils.getAppropriatedURL(classOwnersFiles, beanName);
builder.setURL(jarURL);
}
if (configClone.isScanForEntities()) {
Set<String> classSet;
Map<String, Set<String>> annotationIndex = annotationDB
.getAnnotationIndex();
classSet = annotationIndex.get(Entity.class.getName());
String annotatedUnitName = configClone.getAnnotatedUnitName();
if (annotatedUnitName == null) {
classSet = annotationIndex.get(Entity.class.getName());
} else if (annotatedUnitName.equals(unitName)) {
Set<String> unitNamedSet = annotationIndex.get(UnitName.class
.getName());
// Intersects entities with unit name annotated classes
classSet.retainAll(unitNamedSet);
}
if (ObjectUtils.notNull(ioUtils)) {
String fileNameForBean = classOwnersFiles.get(beanName);
filterEntitiesForJar(classSet, fileNameForBean);
}
List<String> classes = filterEntities(classSet, configClone);
builder.setClasses(classes);
}
// Builds connection for appropriated persistence unit name
builder.setPath(configClone.getPersXmlPath())
.setProperties(configClone.getPersistenceProperties())
.setSwapDataSource(configClone.isSwapDataSource())
.setScanArchives(configClone.isScanArchives())
.setClassLoader(loader).build().setConnection(unitName);
}
/**
* Caches each archive by it's {@link URL} for deployment
*
* @param ejbURLs
* @param archiveData
*/
private void fillArchiveURLs(Collection<URL> ejbURLs,
ArchiveData archiveData, DeployData deployData) {
for (URL ejbURL : ejbURLs) {
archivesURLs.put(ejbURL, archiveData);
realURL.put(ejbURL, deployData);
}
}
/**
* Caches each archive by it's {@link URL} for deployment and creates fill
* {@link URL} array for scanning and finding {@link javax.ejb.Stateless}
* annotated classes
*
* @param archive
* @param modifiedArchives
* @throws IOException
*/
private void fillArchiveURLs(URL archive, List<URL> modifiedArchives)
throws IOException {
AbstractIOUtils ioUtils = AbstractIOUtils.getAppropriatedType(archive);
if (ObjectUtils.notNull(ioUtils)) {
ioUtils.scan(configuration.isPersXmlFromJar());
List<URL> ejbURLs = ioUtils.getEjbURLs();
modifiedArchives.addAll(ejbURLs);
ArchiveData archiveData = new ArchiveData();
archiveData.setIoUtils(ioUtils);
DeployData deployData = new DeployData();
deployData.setType(ioUtils.getType());
deployData.setUrl(archive);
if (ejbURLs.isEmpty()) {
archivesURLs.put(archive, archiveData);
realURL.put(archive, deployData);
} else {
fillArchiveURLs(ejbURLs, archiveData, deployData);
}
}
}
/**
* Gets {@link URL} array for all classes and jar libraries within archive
* file for class loading policy
*
* @param archives
* @return {@link URL}[]
* @throws IOException
*/
private URL[] getFullArchives(URL[] archives) throws IOException {
List<URL> modifiedArchives = new ArrayList<URL>();
for (URL archive : archives) {
fillArchiveURLs(archive, modifiedArchives);
}
return CollectionUtils.toArray(modifiedArchives, URL.class);
}
/**
* Awaits for {@link Future} tasks if it set so by configuration
*
* @param future
*/
private void awaitDeployment(Future<String> future) {
if (await) {
try {
String nameFromFuture = future.get();
LOG.info(String.format("Deploy processing of %s finished",
nameFromFuture));
} catch (InterruptedException ex) {
LOG.error(ex.getMessage(), ex);
} catch (ExecutionException ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
/**
* Awaits for {@link CountDownLatch} of deployments
*/
private void awaitDeployments() {
try {
blocker.await();
} catch (InterruptedException ex) {
LOG.error(ex);
}
}
/**
* Starts bean deployment process for bean name
*
* @param beanName
* @throws IOException
*/
private void deployBean(String beanName) throws IOException {
URL currentURL = classOwnersURL.get(beanName);
ArchiveData archiveData = archivesURLs.get(currentURL);
if (archiveData == null) {
archiveData = new ArchiveData();
}
AbstractIOUtils ioUtils = archiveData.getIoUtils();
if (ioUtils == null) {
ioUtils = AbstractIOUtils.getAppropriatedType(currentURL);
archiveData.setIoUtils(ioUtils);
}
ClassLoader loader = archiveData.getLoader();
// Finds appropriated ClassLoader if needed and or creates new one
List<File> tmpFiles = null;
if (ObjectUtils.notNull(ioUtils)) {
if (loader == null) {
if (ioUtils.notExecuted()) {
ioUtils.scan(configuration.isPersXmlFromJar());
}
URL[] libURLs = ioUtils.getURLs();
loader = LibraryLoader.initializeLoader(libURLs);
archiveData.setLoader(loader);
}
tmpFiles = ioUtils.getTmpFiles();
aggregateds.put(beanName, ioUtils);
}
// Archive file url which contains this bean
DeployData deployData;
if (ObjectUtils.available(realURL)) {
deployData = realURL.get(currentURL);
} else {
deployData = null;
}
// Initializes and fills BeanLoader.BeanParameters class to deploy
// stateless ejb bean
BeanLoader.BeanParameters parameters = new BeanLoader.BeanParameters();
parameters.creator = this;
parameters.className = beanName;
parameters.loader = loader;
parameters.tmpFiles = tmpFiles;
parameters.blocker = blocker;
parameters.deployData = deployData;
parameters.configuration = configuration;
Future<String> future = BeanLoader.loadBean(parameters);
awaitDeployment(future);
if (ObjectUtils.available(tmpFiles)) {
tmpResources.addFile(tmpFiles);
}
}
/**
* Deploys single bean by class name
*
* @param beanNames
*/
private void deployBeans(Set<String> beanNames) {
blocker = new CountDownLatch(beanNames.size());
for (String beanName : beanNames) {
LOG.info(String.format("deploing bean %s", beanName));
try {
deployBean(beanName);
} catch (IOException ex) {
LOG.error(String.format("Could not deploy bean %s", beanName),
ex);
}
}
awaitDeployments();
if (RestContainer.hasRest()) {
RestProvider.reload();
}
boolean hotDeployment = configuration.isHotDeployment();
boolean watchStatus = configuration.isWatchStatus();
if (hotDeployment && ObjectUtils.notTrue(watchStatus)) {
Watcher.startWatch();
watchStatus = Boolean.TRUE;
}
}
/**
* Scan application for find all {@link javax.ejb.Stateless} beans and
* {@link Remote} or {@link Local} proxy interfaces
*
* @param archives
* @throws IOException
* @throws ClassNotFoundException
*/
public void scanForBeans(URL[] archives) throws IOException {
scannerLock.lock();
try {
configure(archives);
// starts RPC server if configured as remote and server
if (configuration.isRemote() && Configuration.isServer()) {
RpcListener.startServer(configuration);
} else if (configuration.isRemote()) {
RPCall.configure(configuration);
}
String[] libraryPaths = configuration.getLibraryPaths();
// Loads libraries from specified path
if (ObjectUtils.notNull(libraryPaths)) {
LibraryLoader.loadLibraries(libraryPaths);
}
// Gets and caches class loader
current = LibraryLoader.getContextClassLoader();
archivesURLs = new HashMap<URL, ArchiveData>();
if (ObjectUtils.available(archives)) {
realURL = new HashMap<URL, DeployData>();
}
URL[] fullArchives = getFullArchives(archives);
annotationDB = new AnnotationDB();
annotationDB.setScanFieldAnnotations(Boolean.FALSE);
annotationDB.setScanParameterAnnotations(Boolean.FALSE);
annotationDB.setScanMethodAnnotations(Boolean.FALSE);
annotationDB.scanArchives(fullArchives);
Set<String> beanNames = annotationDB.getAnnotationIndex().get(
Stateless.class.getName());
classOwnersURL = annotationDB.getClassOwnersURLs();
Initializer.initializeDataSources(configuration);
if (ObjectUtils.available(beanNames)) {
deployBeans(beanNames);
}
} finally {
// Caches configuration
MetaContainer.putConfig(archives, configuration);
// clears cached resources
clear();
// gets rid from all created temporary files
tmpResources.removeTempFiles();
scannerLock.unlock();
}
}
/**
* Scan application for find all {@link javax.ejb.Stateless} beans and
* {@link Remote} or {@link Local} proxy interfaces
*
* @throws ClassNotFoundException
* @throws IOException
*/
public void scanForBeans(File[] jars) throws IOException {
List<URL> urlList = new ArrayList<URL>();
URL url;
for (File file : jars) {
url = file.toURI().toURL();
urlList.add(url);
}
URL[] archives = CollectionUtils.toArray(urlList, URL.class);
scanForBeans(archives);
}
/**
* Scan application for find all {@link javax.ejb.Stateless} beans and
* {@link Remote} or {@link Local} proxy interfaces
*
* @throws ClassNotFoundException
* @throws IOException
*/
public void scanForBeans(String... paths) throws IOException {
if (ObjectUtils.notAvailable(paths)
&& ObjectUtils.available(configuration.getDeploymentPath())) {
Set<DeploymentDirectory> deployments = configuration
.getDeploymentPath();
List<String> pathList = new ArrayList<String>();
File deployFile;
for (DeploymentDirectory deployment : deployments) {
deployFile = new File(deployment.getPath());
if (deployment.isScan()) {
String[] subDeployments = deployFile.list();
if (ObjectUtils.available(subDeployments)) {
pathList.addAll(Arrays.asList(subDeployments));
}
}
}
paths = CollectionUtils.toArray(pathList, String.class);
}
List<URL> urlList = new ArrayList<URL>();
List<URL> archive;
for (String path : paths) {
archive = FileUtils.toURLWithClasspath(path);
urlList.addAll(archive);
}
URL[] archives = CollectionUtils.toArray(urlList, URL.class);
scanForBeans(archives);
}
public ClassLoader getCurrent() {
return current;
}
/**
* Closes all existing connections
*
* @throws IOException
*/
public static void closeAllConnections() throws IOException {
ConnectionContainer.closeConnections();
}
/**
* Clears all locally cached data
*/
public void clear() {
boolean locked = scannerLock.tryLock();
while (ObjectUtils.notTrue(locked)) {
locked = scannerLock.tryLock();
}
if (locked) {
try {
if (ObjectUtils.available(realURL)) {
realURL.clear();
realURL = null;
}
if (ObjectUtils.available(aggregateds)) {
aggregateds.clear();
}
if (ObjectUtils.available(archivesURLs)) {
archivesURLs.clear();
archivesURLs = null;
}
if (ObjectUtils.available(classOwnersURL)) {
classOwnersURL.clear();
classOwnersURL = null;
}
configuration = null;
} finally {
scannerLock.unlock();
}
}
}
/**
* Closes all connections clears all caches
*
* @throws IOException
*/
public static void close() throws IOException {
ShutDown.clearAll();
}
/**
* Builder class to provide properties for lightmare application and
* initialize {@link MetaCreator} instance
*
* @author levan
*
*/
public static class Builder {
private MetaCreator creator;
public Builder(boolean cloneConfiguration) throws IOException {
creator = MetaCreator.get();
Configuration config = creator.configuration;
if (cloneConfiguration && ObjectUtils.notNull(config)) {
try {
creator.configuration = (Configuration) config.clone();
} catch (CloneNotSupportedException ex) {
throw new IOException(ex);
}
} else {
creator.configuration = new Configuration();
}
}
public Builder() throws IOException {
this(Boolean.FALSE);
}
public Builder(Map<Object, Object> configuration) throws IOException {
this();
creator.configuration.configure(configuration);
}
public Builder(String path) throws IOException {
this();
creator.configuration.configure(path);
}
private Map<Object, Object> initPersistenceProperties() {
Map<Object, Object> persistenceProperties = creator.configuration
.getPersistenceProperties();
if (persistenceProperties == null) {
persistenceProperties = new HashMap<Object, Object>();
creator.configuration
.setPersistenceProperties(persistenceProperties);
}
return persistenceProperties;
}
/**
* Sets additional persistence properties
*
* @param properties
* @return {@link Builder}
*/
public Builder setPersistenceProperties(Map<String, String> properties) {
if (ObjectUtils.available(properties)) {
Map<Object, Object> persistenceProperties = initPersistenceProperties();
persistenceProperties.putAll(properties);
}
return this;
}
/**
* Adds instant persistence property
*
* @param key
* @param property
* @return {@link Builder}
*/
public Builder addPersistenceProperty(String key, String property) {
Map<Object, Object> persistenceProperties = initPersistenceProperties();
persistenceProperties.put(key, property);
return this;
}
/**
* Adds property to scan for {@link javax.persistence.Entity} annotated
* classes from deployed archives
*
* @param scanForEnt
* @return {@link Builder}
*/
public Builder setScanForEntities(boolean scanForEnt) {
creator.configuration.setScanForEntities(scanForEnt);
return this;
}
/**
* Adds property to use only {@link org.lightmare.annotations.UnitName}
* annotated entities for which
* {@link org.lightmare.annotations.UnitName#value()} matches passed
* unit name
*
* @param unitName
* @return {@link Builder}
*/
public Builder setUnitName(String unitName) {
creator.configuration.setAnnotatedUnitName(unitName);
return this;
}
/**
* Sets path for persistence.xml file
*
* @param path
* @return {@link Builder}
*/
public Builder setPersXmlPath(String path) {
creator.configuration.setPersXmlPath(path);
creator.configuration.setScanArchives(Boolean.FALSE);
return this;
}
/**
* Adds path for additional libraries to load at start time
*
* @param libPaths
* @return {@link Builder}
*/
public Builder setLibraryPath(String... libPaths) {
creator.configuration.setLibraryPaths(libPaths);
return this;
}
/**
* Sets boolean checker to scan persistence.xml files from appropriated
* jar files
*
* @param xmlFromJar
* @return {@link Builder}
*/
public Builder setXmlFromJar(boolean xmlFromJar) {
creator.configuration.setPersXmlFromJar(xmlFromJar);
return this;
}
/**
* Sets boolean checker to swap jta data source value with non jta data
* source value
*
* @param swapDataSource
* @return {@link Builder}
*/
public Builder setSwapDataSource(boolean swapDataSource) {
creator.configuration.setSwapDataSource(swapDataSource);
return this;
}
/**
* Adds path for data source file
*
* @param dataSourcePath
* @return {@link Builder}
*/
public Builder addDataSourcePath(String dataSourcePath) {
creator.configuration.addDataSourcePath(dataSourcePath);
return this;
}
/**
* This method is deprecated should use
* {@link MetaCreator.Builder#addDataSourcePath(String)} instead
*
* @param dataSourcePath
* @return {@link MetaCreator.Builder}
*/
@Deprecated
public Builder setDataSourcePath(String dataSourcePath) {
creator.configuration.addDataSourcePath(dataSourcePath);
return this;
}
/**
* Sets boolean checker to scan {@link javax.persistence.Entity}
* annotated classes from appropriated deployed archive files
*
* @param scanArchives
* @return {@link Builder}
*/
public Builder setScanArchives(boolean scanArchives) {
creator.configuration.setScanArchives(scanArchives);
return this;
}
/**
* Sets boolean checker to block deployment processes
*
* @param await
* @return {@link Builder}
*/
public Builder setAwaitDeploiment(boolean await) {
creator.await = await;
return this;
}
/**
* Sets property is server or not in embedded mode
*
* @param remote
* @return {@link Builder}
*/
public Builder setRemote(boolean remote) {
creator.configuration.setRemote(remote);
return this;
}
/**
* Sets property is application server or just client for other remote
* server
*
* @param server
* @return {@link Builder}
*/
public Builder setServer(boolean server) {
Configuration.setServer(server);
creator.configuration.setClient(ObjectUtils.notTrue(server));
return this;
}
/**
* Sets boolean check is application in just client mode or not
*
* @param client
* @return {@link Builder}
*/
public Builder setClient(boolean client) {
creator.configuration.setClient(client);
Configuration.setServer(ObjectUtils.notTrue(client));
return this;
}
/**
* To add any additional property
*
* @param key
* @param property
* @return {@link Builder}
*/
public Builder setProperty(String key, String property) {
creator.configuration.putValue(key, property);
return this;
}
/**
* File path for administrator user name and password
*
* @param property
* @return {@link Builder}
*/
public Builder setAdminUsersPth(String property) {
Configuration.setAdminUsersPath(property);
return this;
}
/**
* Sets specific IP address in case when application is in remote server
* mode
*
* @param property
* @return {@link Builder}
*/
public Builder setIpAddress(String property) {
creator.configuration.putValue(Config.IP_ADDRESS.key, property);
return this;
}
/**
* Sets specific port in case when application is in remote server mode
*
* @param property
* @return {@link Builder}
*/
public Builder setPort(String property) {
creator.configuration.putValue(Config.PORT.key, property);
return this;
}
/**
* Sets amount for network master threads in case when application is in
* remote server mode
*
* @param property
* @return {@link Builder}
*/
public Builder setMasterThreads(String property) {
creator.configuration.putValue(Configuration.BOSS_POOL_KEY,
property);
return this;
}
/**
* Sets amount of worker threads in case when application is in remote
* server mode
*
* @param property
* @return {@link Builder}
*/
public Builder setWorkerThreads(String property) {
creator.configuration.putValue(Configuration.WORKER_POOL_KEY,
property);
return this;
}
/**
* Adds deploy file path to application with boolean checker if file is
* directory to scan this directory for deployment files list
*
* @param deploymentPath
* @param scan
* @return {@link Builder}
*/
public Builder addDeploymentPath(String deploymentPath, boolean scan) {
String clearPath = WatchUtils.clearPath(deploymentPath);
creator.configuration.addDeploymentPath(clearPath, scan);
return this;
}
/**
* Adds deploy file path to application
*
* @param deploymentPath
* @return {@link Builder}
*/
public Builder addDeploymentPath(String deploymentPath) {
addDeploymentPath(deploymentPath, Boolean.FALSE);
return this;
}
/**
* Adds timeout for connection in case when application is in remote
* server or client mode
*
* @param property
* @return {@link Builder}
*/
public Builder setTimeout(String property) {
creator.configuration.putValue(
Configuration.CONNECTION_TIMEOUT_KEY, property);
return this;
}
/**
* Adds boolean check if application is using pooled data source
*
* @param dsPooledType
* @return {@link Builder}
*/
public Builder setDataSourcePooledType(boolean dsPooledType) {
creator.configuration.setDataSourcePooledType(dsPooledType);
return this;
}
/**
* Sets which data source pool provider should use application by
* {@link PoolProviderType} parameter
*
* @param poolProviderType
* @return {@link Builder}
*/
public Builder setPoolProviderType(PoolProviderType poolProviderType) {
creator.configuration.setPoolProviderType(poolProviderType);
return this;
}
/**
* Sets path for data source pool additional properties
*
* @param path
* @return {@link Builder}
*/
public Builder setPoolPropertiesPath(String path) {
creator.configuration.setPoolPropertiesPath(path);
return this;
}
/**
* Sets data source pool additional properties
*
* @param properties
* @return {@link Builder}
*/
public Builder setPoolProperties(
Map<? extends Object, ? extends Object> properties) {
creator.configuration.setPoolProperties(properties);
return this;
}
/**
* Adds instance property for pooled data source
*
* @param key
* @param value
* @return {@link Builder}
*/
public Builder addPoolProperty(Object key, Object value) {
creator.configuration.addPoolProperty(key, value);
return this;
}
/**
* Sets boolean check is application in hot deployment (with watch
* service on deployment directories) or not
*
* @param hotDeployment
* @return {@link Builder}
*/
public Builder setHotDeployment(boolean hotDeployment) {
creator.configuration.setHotDeployment(hotDeployment);
return this;
}
/**
* Adds additional parameters from passed {@link Map} to existing
* configuration
*
* @param configuration
* @return
*/
public Builder addConfiguration(Map<Object, Object> configuration) {
creator.configuration.configure(configuration);
return this;
}
public MetaCreator build() throws IOException {
creator.configuration.configure();
LOG.info("Lightmare application starts working");
return creator;
}
}
} |
package org.lightmare.utils.fs;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.AbstractIOUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
/**
* Utility for removing {@link File}s recursively from file system
*
* @author Levan
*
*/
public class FileUtils {
private static File[] listJavaFiles(File file) {
File[] subFiles = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String name) {
return name.endsWith(".jar") || name.endsWith(".class")
|| file.isDirectory();
}
});
return subFiles;
}
private static void addURL(Collection<URL> urls, File file)
throws IOException {
try {
urls.add(file.toURI().toURL());
} catch (MalformedURLException ex) {
throw new IOException(ex);
}
}
private static void addSubDirectory(File[] files, Set<URL> urls)
throws IOException {
for (File subFile : files) {
if (subFile.isDirectory()) {
getSubfiles(subFile, urls);
} else {
addURL(urls, subFile);
}
}
}
/**
* Gets all jar or class subfiles from specified {@link File} recursively
*
* @param file
* @param urls
* @throws IOException
*/
public static void getSubfiles(File file, Set<URL> urls) throws IOException {
if (file.isDirectory()) {
File[] subFiles = listJavaFiles(file);
if (ObjectUtils.available(subFiles)) {
addSubDirectory(subFiles, urls);
}
} else {
addURL(urls, file);
}
}
/**
* Check whether passed {@link URL} is from extracted ear directory
*
* @param url
* @return boolean
* @throws IOException
*/
public static boolean checkOnEarDir(URL url) throws IOException {
File file;
try {
file = new File(url.toURI());
boolean isEarDir = checkOnEarDir(file);
return isEarDir;
} catch (URISyntaxException ex) {
throw new IOException(ex);
}
}
/**
* Check whether passed path is extracted ear directory path
*
* @param file
* @return boolean
*/
public static boolean checkOnEarDir(String path) {
File file = new File(path);
boolean isEarDir = checkOnEarDir(file);
return isEarDir;
}
/**
* Check whether passed file is extracted ear directory
*
* @param file
* @return boolean
*/
public static boolean checkOnEarDir(File file) {
boolean isEarDir = file.isDirectory();
if (isEarDir) {
File[] files = file.listFiles();
isEarDir = ObjectUtils.available(files);
if (isEarDir) {
String path = file.getPath();
String delim;
if (path.endsWith(File.pathSeparator)) {
delim = StringUtils.EMPTY_STRING;
} else {
delim = File.pathSeparator;
}
String appxmlPath = StringUtils.concat(path, delim,
AbstractIOUtils.APPLICATION_XML_PATH);
File appXmlFile = new File(appxmlPath);
isEarDir = appXmlFile.exists();
}
}
return isEarDir;
}
/**
* Removes passed {@link File}s from file system and if
* {@link File#isDirectory()} removes all it's content recursively
*
* @param file
* @return boolean
*/
public static boolean deleteFile(File file) {
if (file.isDirectory()) {
File[] subFiles = file.listFiles();
if (subFiles != null) {
for (File subFile : subFiles) {
deleteFile(subFile);
}
}
}
return file.delete();
}
/**
* Iterates over passed {@link File}s and removes each of them from file
* system and if {@link File#isDirectory()} removes all it's content
* recursively
*
* @param files
*/
public static void deleteFiles(Iterable<File> files) {
for (File fileToDelete : files) {
deleteFile(fileToDelete);
}
}
public static URL toURL(File file) throws IOException {
return file.toURI().toURL();
}
public static URL toURL(String path) throws IOException {
File file = new File(path);
return toURL(file);
}
/**
* Checks passed path and if its empty path for current class directory
*
* @param path
* @return {@link String}
*/
public static List<URL> toURLWithClasspath(String path) throws IOException {
List<URL> urls = new ArrayList<URL>();
URL url;
if (ObjectUtils.available(path)) {
url = toURL(path);
urls.add(url);
} else if (ObjectUtils.notNull(path) && path.isEmpty()) {
Enumeration<URL> urlEnum = LibraryLoader.getContextClassLoader()
.getResources(path);
while (urlEnum.hasMoreElements()) {
url = urlEnum.nextElement();
urls.add(url);
}
}
return urls;
}
} |
package org.mastodon.trackmate;
import java.util.Map;
import org.mastodon.HasErrorMessage;
import org.mastodon.detection.mamut.SpotDetectorOp;
import org.mastodon.graph.algorithm.RootFinder;
import org.mastodon.linking.mamut.SpotLinkerOp;
import org.mastodon.revised.model.mamut.Link;
import org.mastodon.revised.model.mamut.Model;
import org.mastodon.revised.model.mamut.ModelGraph;
import org.mastodon.revised.model.mamut.Spot;
import org.scijava.Cancelable;
import org.scijava.app.StatusService;
import org.scijava.command.ContextCommand;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import bdv.spimdata.SpimDataMinimal;
import net.imagej.ops.Op;
import net.imagej.ops.OpService;
import net.imagej.ops.special.hybrid.Hybrids;
import net.imagej.ops.special.inplace.Inplaces;
public class TrackMate extends ContextCommand implements HasErrorMessage
{
@Parameter
private OpService ops;
@Parameter
private StatusService statusService;
@Parameter
LogService log;
private final Settings settings;
private final Model model;
private Op currentOp;
private boolean succesful;
private String errorMessage;
public TrackMate( final Settings settings )
{
this.settings = settings;
this.model = createModel();
}
public TrackMate( final Settings settings, final Model model )
{
this.settings = settings;
this.model = model;
}
protected Model createModel()
{
return new Model();
}
public Model getModel()
{
return model;
}
public Settings getSettings()
{
return settings;
}
public boolean execDetection()
{
succesful = true;
errorMessage = null;
if ( isCanceled() )
return true;
final ModelGraph graph = model.getGraph();
final SpimDataMinimal spimData = settings.values.getSpimData();
if ( null == spimData )
{
errorMessage = "Cannot start detection: SpimData object is null.\n";
log.error( errorMessage + '\n' );
succesful = false;
return false;
}
/*
* Clear previous content.
*/
for ( final Spot spot : model.getGraph().vertices() )
model.getGraph().remove( spot );
/*
* Exec detection.
*/
final long start = System.currentTimeMillis();
final Class< ? extends SpotDetectorOp > cl = settings.values.getDetector();
final Map< String, Object > detectorSettings = settings.values.getDetectorSettings();
final SpotDetectorOp detector = ( SpotDetectorOp ) Hybrids.unaryCF( ops, cl,
graph, spimData,
detectorSettings );
this.currentOp = detector;
log.info( "Detection with " + cl.getSimpleName() + '\n' );
detector.compute( spimData, graph );
if ( !detector.isSuccessful() )
{
log.error( "Detection failed:\n" + detector.getErrorMessage() + '\n' );
succesful = false;
errorMessage = detector.getErrorMessage();
return false;
}
currentOp = null;
model.getGraphFeatureModel().declareFeature( detector.getQualityFeature() );
final long end = System.currentTimeMillis();
log.info( String.format( "Detection completed in %.1f s.\n", ( end - start ) / 1000. ) );
log.info( "Found " + graph.vertices().size() + " spots.\n" );
model.getGraph().notifyGraphChanged();
return true;
}
public boolean execParticleLinking()
{
succesful = true;
errorMessage = null;
if ( isCanceled() )
return true;
/*
* Clear previous content.
*/
for ( final Link link : model.getGraph().edges() )
model.getGraph().remove( link );
/*
* Exec particle linking.
*/
final long start = System.currentTimeMillis();
final Class< ? extends SpotLinkerOp > linkerCl = settings.values.getLinker();
final Map< String, Object > linkerSettings = settings.values.getLinkerSettings();
final SpotLinkerOp linker =
( SpotLinkerOp ) Inplaces.binary1( ops, linkerCl, model.getGraph(), model.getSpatioTemporalIndex(),
linkerSettings, model.getGraphFeatureModel() );
log.info( "Particle-linking with " + linkerCl.getSimpleName() + '\n' );
this.currentOp = linker;
linker.mutate1( model.getGraph(), model.getSpatioTemporalIndex() );
if ( !linker.isSuccessful() )
{
log.error( "Particle-linking failed:\n" + linker.getErrorMessage() + '\n' );
succesful = false;
errorMessage = linker.getErrorMessage();
return false;
}
currentOp = null;
model.getGraphFeatureModel().declareFeature( linker.getLinkCostFeature() );
final long end = System.currentTimeMillis();
log.info( String.format( "Particle-linking completed in %.1f s.\n", ( end - start ) / 1000. ) );
final int nTracks = RootFinder.getRoots( model.getGraph() ).size();
log.info( String.format( "Found %d tracks.\n", nTracks ) );
model.getGraph().notifyGraphChanged();
return true;
}
@Override
public void run()
{
if ( execDetection() && execParticleLinking() )
;
}
// -- Cancelable methods --
/** Reason for cancelation, or null if not canceled. */
private String cancelReason;
@Override
public void cancel( final String reason )
{
cancelReason = reason;
if ( null != currentOp && ( currentOp instanceof Cancelable ) )
{
final Cancelable cancelable = ( Cancelable ) currentOp;
cancelable.cancel( reason );
}
}
@Override
public boolean isCanceled()
{
return cancelReason != null;
}
@Override
public String getCancelReason()
{
return cancelReason;
}
@Override
public String getErrorMessage()
{
return errorMessage;
}
@Override
public boolean isSuccessful()
{
return succesful;
}
} |
package org.oucs.gaboto.entities;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.oucs.gaboto.entities.pool.GabotoEntityPool;
import org.oucs.gaboto.entities.pool.PassiveEntitiesRequest;
import org.oucs.gaboto.entities.utils.PassiveProperty;
/**
*<p>This class was automatically generated by Gaboto<p>
*/
public class Website extends OxpEntity {
private Collection<OxpEntity> isWeblearnIn;
private Collection<OxpEntity> isITHomepageIn;
private Collection<OxpEntity> isHomepageIn;
private Collection<OxpEntity> isLibraryHomepageIn;
private static Map<String, List<Method>> indirectPropertyLookupTable;
static{
indirectPropertyLookupTable = new HashMap<String, List<Method>>();
List<Method> list;
try{
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String getType(){
return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#Website";
}
@PassiveProperty(
uri = "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasWeblearn",
entity = "OxpEntity"
)
public Collection<OxpEntity> getIsWeblearnIn(){
if(! isPassiveEntitiesLoaded() )
loadPassiveEntities();
return this.isWeblearnIn;
}
@PassiveProperty(
uri = "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasWeblearn",
entity = "OxpEntity"
)
private void setIsWeblearnIn(Collection<OxpEntity> isWeblearnIn){
this.isWeblearnIn = isWeblearnIn;
}
private void addIsWeblearnIn(OxpEntity isWeblearnIn){
if(null == this.isWeblearnIn)
this.isWeblearnIn = new HashSet<OxpEntity>();
this.isWeblearnIn.add(isWeblearnIn);
}
@PassiveProperty(
uri = "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasITHomepage",
entity = "OxpEntity"
)
public Collection<OxpEntity> getIsITHomepageIn(){
if(! isPassiveEntitiesLoaded() )
loadPassiveEntities();
return this.isITHomepageIn;
}
@PassiveProperty(
uri = "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasITHomepage",
entity = "OxpEntity"
)
private void setIsITHomepageIn(Collection<OxpEntity> isITHomepageIn){
this.isITHomepageIn = isITHomepageIn;
}
private void addIsITHomepageIn(OxpEntity isITHomepageIn){
if(null == this.isITHomepageIn)
this.isITHomepageIn = new HashSet<OxpEntity>();
this.isITHomepageIn.add(isITHomepageIn);
}
@PassiveProperty(
uri = "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasHomepage",
entity = "OxpEntity"
)
public Collection<OxpEntity> getIsHomepageIn(){
if(! isPassiveEntitiesLoaded() )
loadPassiveEntities();
return this.isHomepageIn;
}
@PassiveProperty(
uri = "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasHomepage",
entity = "OxpEntity"
)
private void setIsHomepageIn(Collection<OxpEntity> isHomepageIn){
this.isHomepageIn = isHomepageIn;
}
private void addIsHomepageIn(OxpEntity isHomepageIn){
if(null == this.isHomepageIn)
this.isHomepageIn = new HashSet<OxpEntity>();
this.isHomepageIn.add(isHomepageIn);
}
@PassiveProperty(
uri = "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasLibraryHomepage",
entity = "OxpEntity"
)
public Collection<OxpEntity> getIsLibraryHomepageIn(){
if(! isPassiveEntitiesLoaded() )
loadPassiveEntities();
return this.isLibraryHomepageIn;
}
@PassiveProperty(
uri = "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasLibraryHomepage",
entity = "OxpEntity"
)
private void setIsLibraryHomepageIn(Collection<OxpEntity> isLibraryHomepageIn){
this.isLibraryHomepageIn = isLibraryHomepageIn;
}
private void addIsLibraryHomepageIn(OxpEntity isLibraryHomepageIn){
if(null == this.isLibraryHomepageIn)
this.isLibraryHomepageIn = new HashSet<OxpEntity>();
this.isLibraryHomepageIn.add(isLibraryHomepageIn);
}
public Collection<PassiveEntitiesRequest> getPassiveEntitiesRequest(){
Collection<PassiveEntitiesRequest> requests = super.getPassiveEntitiesRequest();
if(null == requests)
requests = new HashSet<PassiveEntitiesRequest>();
requests.add(new PassiveEntitiesRequest(){
public String getType() {
return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#OxpEntity";
}
public String getUri() {
return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasWeblearn";
}
public int getCollectionType() {
return GabotoEntityPool.PASSIVE_PROPERTY_COLLECTION_TYPE_NONE;
}
public void passiveEntityLoaded(GabotoEntity entity) {
addIsWeblearnIn((OxpEntity)entity);
}
});
requests.add(new PassiveEntitiesRequest(){
public String getType() {
return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#OxpEntity";
}
public String getUri() {
return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasITHomepage";
}
public int getCollectionType() {
return GabotoEntityPool.PASSIVE_PROPERTY_COLLECTION_TYPE_NONE;
}
public void passiveEntityLoaded(GabotoEntity entity) {
addIsITHomepageIn((OxpEntity)entity);
}
});
requests.add(new PassiveEntitiesRequest(){
public String getType() {
return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#OxpEntity";
}
public String getUri() {
return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasHomepage";
}
public int getCollectionType() {
return GabotoEntityPool.PASSIVE_PROPERTY_COLLECTION_TYPE_NONE;
}
public void passiveEntityLoaded(GabotoEntity entity) {
addIsHomepageIn((OxpEntity)entity);
}
});
requests.add(new PassiveEntitiesRequest(){
public String getType() {
return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#OxpEntity";
}
public String getUri() {
return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasLibraryHomepage";
}
public int getCollectionType() {
return GabotoEntityPool.PASSIVE_PROPERTY_COLLECTION_TYPE_NONE;
}
public void passiveEntityLoaded(GabotoEntity entity) {
addIsLibraryHomepageIn((OxpEntity)entity);
}
});
return requests;
}
protected List<Method> getIndirectMethodsForProperty(String propertyURI){
List<Method> list = super.getIndirectMethodsForProperty(propertyURI);
if(null == list)
return indirectPropertyLookupTable.get(propertyURI);
else{
List<Method> tmp = indirectPropertyLookupTable.get(propertyURI);
if(null != tmp)
list.addAll(tmp);
}
return list;
}
} |
package org.owasp.esapi;
import org.owasp.esapi.errors.AccessControlException;
public interface AccessController {
/**
* Checks if the current user is authorized to access the referenced URL. Generally, this method should be invoked in the
* application's controller or a filter as follows:
* <PRE>ESAPI.accessController().isAuthorizedForURL(request.getRequestURI().toString());</PRE>
*
* The implementation of this method should call assertAuthorizedForURL(String url), and if an AccessControlException is
* not thrown, this method should return true. This way, if the user is not authorized, false would be returned, and the
* exception would be logged.
*
* @param url
* the URL as returned by request.getRequestURI().toString()
*
* @return
* true, if is authorized for URL
*/
boolean isAuthorizedForURL(String url);
/**
* Checks if the current user is authorized to access the referenced function.
*
* The implementation of this method should call assertAuthorizedForFunction(String functionName), and if an
* AccessControlException is not thrown, this method should return true.
*
* @param functionName
* the name of the function
*
* @return
* true, if is authorized for function
*/
boolean isAuthorizedForFunction(String functionName);
/**
* Checks if the current user is authorized to access the referenced data, represented as an Object.
*
* The implementation of this method should call assertAuthorizedForData(String action, Object data), and if an
* AccessControlException is not thrown, this method should return true.
*
* @param action
* The action to verify for an access control decision, such as a role, or an action being performed on the object
* (e.g., Read, Write, etc.), or the name of the function the data is being passed to.
*
* @param data
* The actual object or object identifier being accessed or a reference to the object being accessed.
*
* @return
* true, if is authorized for the data
*/
boolean isAuthorizedForData(String action, Object data);
/**
* Checks if the current user is authorized to access the referenced file.
*
* The implementation of this method should call assertAuthorizedForFile(String filepath), and if an AccessControlException
* is not thrown, this method should return true.
*
* @param filepath
* the path of the file to be checked, including filename
*
* @return
* true, if is authorized for the file
*/
boolean isAuthorizedForFile(String filepath);
/**
* Checks if the current user is authorized to access the referenced service. This can be used in applications that
* provide access to a variety of back end services.
*
* The implementation of this method should call assertAuthorizedForService(String serviceName), and if an
* AccessControlException is not thrown, this method should return true.
*
* @param serviceName
* the service name
*
* @return
* true, if is authorized for the service
*/
boolean isAuthorizedForService(String serviceName);
/**
* Checks if the current user is authorized to access the referenced URL. The implementation should allow
* access to be granted to any part of the URL. Generally, this method should be invoked in the
* application's controller or a filter as follows:
* <PRE>ESAPI.accessController().assertAuthorizedForURL(request.getRequestURI().toString());</PRE>
*
* This method throws an AccessControlException if access is not authorized, or if the referenced URL does not exist.
* If the User is authorized, this method simply returns.
* <P>
* Specification: The implementation should do the following:
* <ol>
* <li>Check to see if the resource exists and if not, throw an AccessControlException</li>
* <li>Use available information to make an access control decision</li>
* <ol type="a">
* <li>Ideally, this policy would be data driven</li>
* <li>You can use the current User, roles, data type, data name, time of day, etc.</li>
* <li>Access control decisions must deny by default</li>
* </ol>
* <li>If access is not permitted, throw an AccessControlException with details</li>
* </ol>
* @param url
* the URL as returned by request.getRequestURI().toString()
*
* @throws AccessControlException
* if access is not permitted
*/
void assertAuthorizedForURL(String url) throws AccessControlException;
/**
* Checks if the current user is authorized to access the referenced function. The implementation should define the
* function "namespace" to be enforced. Choosing something simple like the class name of action classes or menu item
* names will make this implementation easier to use.
* <P>
* This method throws an AccessControlException if access is not authorized, or if the referenced function does not exist.
* If the User is authorized, this method simply returns.
* <P>
* Specification: The implementation should do the following:
* <ol>
* <li>Check to see if the function exists and if not, throw an AccessControlException</li>
* <li>Use available information to make an access control decision</li>
* <ol type="a">
* <li>Ideally, this policy would be data driven</li>
* <li>You can use the current User, roles, data type, data name, time of day, etc.</li>
* <li>Access control decisions must deny by default</li>
* </ol>
* <li>If access is not permitted, throw an AccessControlException with details</li>
* </ol>
*
* @param functionName
* the function name
*
* @throws AccessControlException
* if access is not permitted
*/
void assertAuthorizedForFunction(String functionName) throws AccessControlException;
/**
* Checks if the current user is authorized to access the referenced data. This method simply returns if access is authorized.
* It throws an AccessControlException if access is not authorized, or if the referenced data does not exist.
* <P>
* Specification: The implementation should do the following:
* <ol>
* <li>Check to see if the resource exists and if not, throw an AccessControlException</li>
* <li>Use available information to make an access control decision</li>
* <ol type="a">
* <li>Ideally, this policy would be data driven</li>
* <li>You can use the current User, roles, data type, data name, time of day, etc.</li>
* <li>Access control decisions must deny by default</li>
* </ol>
* <li>If access is not permitted, throw an AccessControlException with details</li>
* </ol>
*
* @param action
* The action to verify for an access control decision, such as a role, or an action being performed on the object
* (e.g., Read, Write, etc.), or the name of the function the data is being passed to.
*
* @param data
* The actual object or object identifier being accessed or a reference to the object being accessed.
*
* @throws AccessControlException
* if access is not permitted
*/
void assertAuthorizedForData(String action, Object data) throws AccessControlException;
/**
* Checks if the current user is authorized to access the referenced file. The implementation should validate and canonicalize the
* input to be sure the filepath is not malicious.
* <P>
* This method throws an AccessControlException if access is not authorized, or if the referenced File does not exist.
* If the User is authorized, this method simply returns.
* <P>
* Specification: The implementation should do the following:
* <ol>
* <li>Check to see if the File exists and if not, throw an AccessControlException</li>
* <li>Use available information to make an access control decision</li>
* <ol type="a">
* <li>Ideally, this policy would be data driven</li>
* <li>You can use the current User, roles, data type, data name, time of day, etc.</li>
* <li>Access control decisions must deny by default</li>
* </ol>
* <li>If access is not permitted, throw an AccessControlException with details</li>
* </ol>
*
* @param filepath
* Path to the file to be checked
* @throws AccessControlException if access is denied
*/
void assertAuthorizedForFile(String filepath) throws AccessControlException;
/**
* Checks if the current user is authorized to access the referenced service. This can be used in applications that
* provide access to a variety of backend services.
* <P>
* This method throws an AccessControlException if access is not authorized, or if the referenced service does not exist.
* If the User is authorized, this method simply returns.
* <P>
* Specification: The implementation should do the following:
* <ol>
* <li>Check to see if the service exists and if not, throw an AccessControlException</li>
* <li>Use available information to make an access control decision</li>
* <ol type="a">
* <li>Ideally, this policy would be data driven</li>
* <li>You can use the current User, roles, data type, data name, time of day, etc.</li>
* <li>Access control decisions must deny by default</li>
* </ol>
* <li>If access is not permitted, throw an AccessControlException with details</li>
* </ol>
*
* @param serviceName
* the service name
*
* @throws AccessControlException
* if access is not permitted
*/
void assertAuthorizedForService(String serviceName) throws AccessControlException;
} |
package com.psddev.dari.db;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PredicateParserTest {
private static final Logger LOGGER = LoggerFactory.getLogger(PredicateParserTest.class);
private static final String REFLECTIVE_IDENTITY_SYNTAX_STANDARD = "?";
private static final String REFLECTIVE_IDENTITY_DELIMITED_SYNTAX = "?/";
private static final String REFLECTIVE_IDENTITY_REDUNDANT_SYNTAX = "?_id";
private static final String REFLECTIVE_IDENTITY_DELIMITED_REDUNDANT_SYNTAX = "?/_id";
private static final String REFLECTIVE_IDENTITY_INDEXED_SYNTAX = "?0";
private static final String REFLECTIVE_IDENTITY_INDEXED_DELIMITED_SYNTAX = "?0/";
private static final String REFLECTIVE_IDENTITY_INDEXED_REDUNDANT_SYNTAX = "?0_id";
private static final String REFLECTIVE_IDENTITY_INDEXED_DELIMITED_REDUNDANT_SYNTAX = "?0/_id";
private static List<TestDatabase> TEST_DATABASES;
private static List<Database> DATABASES;
PredicateParser parser = new PredicateParser();
static final Queue<Object> EMPTY_OBJECT_QUEUE = new ArrayDeque<Object>();
static final Queue<String> EMPTY_STRING_QUEUE = new ArrayDeque<String>();
@BeforeClass
public static void beforeClass() {
TEST_DATABASES = DatabaseTestUtils.getNewDefaultTestDatabaseInstances();
DATABASES = new ArrayList<Database>();
for (TestDatabase testDb : TEST_DATABASES) {
Database db = testDb.get();
DATABASES.add(db);
}
LOGGER.info("Running tests against " + TEST_DATABASES.size() + " databases.");
}
@AfterClass
public static void afterClass() {
if (TEST_DATABASES != null) for (TestDatabase testDb : TEST_DATABASES) {
testDb.close();
}
}
@Before
public void before() {
}
@After
public void after() {
}
/**
* public Predicate parse(String predicateString, Object... parameters)
*/
@Test
public void parse_empty() {
assertEquals(null, parser.parse(""));
}
@Test
public void parse_empty_2() {
assertEquals(null, parser.parse(" "));
}
@Test
public void parse_null() {
assertEquals(null, parser.parse(null));
}
@Test
public void parse_simple() {
Predicate pred = parser.parse("a = 1");
Predicate expect = new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "a", Arrays.asList("1"));
assertEquals(expect, pred);
}
@Test (expected=IllegalArgumentException.class)
public void parse_nospace() {
parser.parse("a=1");
}
@Test
public void parse_compound() {
Predicate pred = parser.parse("a = 1 and b != 2");
Predicate expect = CompoundPredicate.combine(
PredicateParser.AND_OPERATOR,
new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "a", Arrays.asList("1")),
new ComparisonPredicate(PredicateParser.NOT_EQUALS_ALL_OPERATOR, false, "b", Arrays.asList("2"))
);
assertEquals(expect, pred);
}
@Test // left to right
public void parse_noparens() {
Predicate pred = parser.parse("a = 1 and b = 2 or c = 3");
Predicate expect = CompoundPredicate.combine(
PredicateParser.OR_OPERATOR,
CompoundPredicate.combine(
PredicateParser.AND_OPERATOR,
new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "a", Arrays.asList("1")),
new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "b", Arrays.asList("2"))
),
new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "c", Arrays.asList("3"))
);
assertEquals(expect, pred);
}
@Test // to group
public void parse_parens() {
Predicate pred = parser.parse("a = 1 and (b = 2 or c = 3)");
Predicate expect = CompoundPredicate.combine(
PredicateParser.AND_OPERATOR,
new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "a", Arrays.asList("1")),
CompoundPredicate.combine(
PredicateParser.OR_OPERATOR,
new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "b", Arrays.asList("2")),
new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "c", Arrays.asList("3"))
)
);
assertEquals(expect, pred);
}
/*
* Key handling
*/
@Test
public void parse_key_canonical_id() {
Predicate expect = new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "_id", Arrays.asList("1"));
assertEquals(expect, parser.parse("id = 1"));
}
@Test (expected=IllegalArgumentException.class)
public void parse_key_missing() {
parser.parse(" = 1 ");
}
/*
* Comparison handling
*/
@Test
public void parse_operator_negative() {
Predicate expect = new ComparisonPredicate(PredicateParser.NOT_EQUALS_ALL_OPERATOR, false, "token1", Arrays.asList("1"));
assertEquals(expect, parser.parse("token1 != 1"));
}
@Test (expected=IllegalArgumentException.class)
public void parse_operator_missing() {
parser.parse("a 1");
}
/*
* Value handling
*/
@Test (expected=IllegalArgumentException.class)
public void parse_error_value_missing() {
parser.parse("a = ");
}
@Test
public void parse_value_boolean_true() {
ComparisonPredicate expect = new ComparisonPredicate(
PredicateParser.EQUALS_ANY_OPERATOR,
false,
"token1",
Arrays.asList(true));
assertEquals(expect, parser.parse("token1 = true"));
}
@Test
public void parse_value_boolean_false() {
Predicate expect = new ComparisonPredicate(
PredicateParser.EQUALS_ANY_OPERATOR,
false,
"token1",
Arrays.asList(false));
assertEquals(expect, parser.parse("token1 = false"));
}
@Test
public void parse_value_null() {
Predicate expect = new ComparisonPredicate(
PredicateParser.EQUALS_ANY_OPERATOR,
false,
"token1",
null);
assertEquals(expect, parser.parse("token1 = null"));
}
/*
* Params
*/
@Test
public void parse_params() {
Predicate pred = parser.parse("b = ?", "1");
Predicate expect = new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "b", Arrays.asList("1"));
assertEquals(expect, pred);
}
@Test
public void parse_params_multivalue() {
Predicate pred = parser.parse("a in ?", Arrays.asList(1,2,3));
Predicate expect = new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "a", Arrays.asList(1,2,3));
assertEquals(expect, pred);
}
@Test
public void parse_params_notstring() {
Predicate pred = parser.parse("b = ?", 1);
Predicate expect = new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "b", Arrays.asList(1));
assertEquals(expect, pred);
}
@Test
public void parse_params_null() {
Predicate pred = parser.parse("b = ?", (Object)null);
Predicate expect = new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "b", null);
assertEquals(expect, pred);
}
@Test
public void parse_params_missing() {
Predicate pred = parser.parse("b = ?");
Predicate expect = new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "b", null);
assertEquals(expect, pred);
}
@Test
public void parse_extra() {
Predicate pred = parser.parse("b = ?", "1", "2");
Predicate expect = new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, "b", Arrays.asList("1"));
assertEquals(expect, pred);
}
@Test (expected=IllegalArgumentException.class)
public void parse_parens_empty() {
assertEquals(null, parser.parse(" ( ) "));
}
/** evaluate reflective identity "?" syntax **/
public void evaluate_reflective_syntax(String reflectiveSyntax) {
for (Database database : DATABASES) {
ReflectiveTestRecord current = ReflectiveTestRecord.getInstance(database);
ReflectiveTestRecord other = ReflectiveTestRecord.getInstance(database);
current.setOther(other);
other.setOther(current);
assertTrue("\"" + reflectiveSyntax + "\" was evaluated incorrectly!", PredicateParser.Static.evaluate(other, "other = " + reflectiveSyntax, current));
}
}
public void evaluate_reflective_syntax_state_valued(String reflectiveSyntax) {
for (Database database : DATABASES) {
ReflectiveTestRecord current = ReflectiveTestRecord.getInstance(database);
ReflectiveTestRecord other = ReflectiveTestRecord.getInstance(database);
current.setOther(other);
other.setOther(current);
assertTrue("\"" + reflectiveSyntax + "\" was evaluated incorrectly!", PredicateParser.Static.evaluate(other, "other = " + reflectiveSyntax, current.getState()));
}
}
@Test
public void evaluate_reflective_identity_syntax_standard() {
evaluate_reflective_syntax(REFLECTIVE_IDENTITY_SYNTAX_STANDARD);
}
@Test
public void evaluate_reflective_identity_syntax_standard_state_valued() {
evaluate_reflective_syntax_state_valued(REFLECTIVE_IDENTITY_SYNTAX_STANDARD);
}
/** evaluate reflective identity delimited "?/" syntax **/
@Test
public void evaluate_reflective_identity_delimited_syntax() {
evaluate_reflective_syntax(REFLECTIVE_IDENTITY_DELIMITED_SYNTAX);
}
@Test
public void evaluate_reflective_identity_delimited_syntax_state_valued() {
evaluate_reflective_syntax_state_valued(REFLECTIVE_IDENTITY_DELIMITED_SYNTAX);
}
/** evaluate reflective identity redundant "?_id" syntax **/
@Test
public void evaluate_reflective_identity_redundant_syntax() {
evaluate_reflective_syntax(REFLECTIVE_IDENTITY_REDUNDANT_SYNTAX);
}
@Test
public void evaluate_reflective_identity_redundant_syntax_state_valued() {
evaluate_reflective_syntax_state_valued(REFLECTIVE_IDENTITY_REDUNDANT_SYNTAX);
}
/** evaluate reflective identity delimited redundant "?/_id" syntax **/
@Test
public void evaluate_reflective_identity_delimited_redundant_syntax() {
evaluate_reflective_syntax(REFLECTIVE_IDENTITY_DELIMITED_REDUNDANT_SYNTAX);
}
@Test
public void evaluate_reflective_identity_delimited_redundant_syntax_state_valued() {
evaluate_reflective_syntax_state_valued(REFLECTIVE_IDENTITY_DELIMITED_REDUNDANT_SYNTAX);
}
/** evaluate reflective identity indexed "?0" syntax **/
@Test
public void evaluate_reflective_identity_indexed_syntax() {
evaluate_reflective_syntax(REFLECTIVE_IDENTITY_INDEXED_SYNTAX);
}
@Test
public void evaluate_reflective_identity_indexed_syntax_state_valued() {
evaluate_reflective_syntax_state_valued(REFLECTIVE_IDENTITY_INDEXED_SYNTAX);
}
/** evaluate reflective identity indexed delimited "?0/" syntax **/
@Test
public void evaluate_reflective_identity_indexed_delimited_syntax() {
evaluate_reflective_syntax(REFLECTIVE_IDENTITY_INDEXED_DELIMITED_SYNTAX);
}
@Test
public void evaluate_reflective_identity_indexed_delimited_syntax_state_valued() {
evaluate_reflective_syntax_state_valued(REFLECTIVE_IDENTITY_INDEXED_DELIMITED_SYNTAX);
}
/** evaluate reflective identity indexed redundant "?0_id" syntax **/
@Test
public void evaluate_reflective_identity_indexed_redundant_syntax() {
evaluate_reflective_syntax(REFLECTIVE_IDENTITY_INDEXED_REDUNDANT_SYNTAX);
}
@Test
public void evaluate_reflective_identity_indexed_redundant_syntax_state_valued() {
evaluate_reflective_syntax_state_valued(REFLECTIVE_IDENTITY_INDEXED_REDUNDANT_SYNTAX);
}
/** evaluate reflective identity indexed delimited redundant "?0/_id" syntax **/
@Test
public void evaluate_reflective_identity_indexed_delimited_redundant_syntax() {
evaluate_reflective_syntax(REFLECTIVE_IDENTITY_INDEXED_DELIMITED_REDUNDANT_SYNTAX);
}
@Test
public void evaluate_reflective_identity_indexed_delimited_redundant_syntax_state_valued() {
evaluate_reflective_syntax_state_valued(REFLECTIVE_IDENTITY_INDEXED_DELIMITED_REDUNDANT_SYNTAX);
}
public static class ReflectiveTestRecord extends Record {
public static ReflectiveTestRecord getInstance(Database database) {
ReflectiveTestRecord object = new ReflectiveTestRecord();
object.getState().setDatabase(database);
return object;
}
private ReflectiveTestRecord other;
public ReflectiveTestRecord getOther() {
return other;
}
public void setOther(ReflectiveTestRecord other) {
this.other = other;
}
}
/*
* Options // TODO: Add tests here when we know what this should look like
*/
} |
package de.cooperateproject.modeling.textual.usecase.derivedstate.calculator;
import java.util.Optional;
import org.eclipse.uml2.uml.Classifier;
import de.cooperateproject.modeling.textual.common.metamodel.textualCommons.UMLReferencingElement;
import de.cooperateproject.modeling.textual.usecase.usecase.Generalization;
import de.cooperateproject.modeling.textual.xtext.runtime.derivedstate.initializer.Applicability;
import de.cooperateproject.modeling.textual.xtext.runtime.derivedstate.initializer.AtomicDerivedStateProcessorBase;
import de.cooperateproject.modeling.textual.xtext.runtime.derivedstate.initializer.DerivedStateProcessorApplicability;
/**
* State calculator for generalizations.
*/
@Applicability(applicabilities = DerivedStateProcessorApplicability.CALCULATION)
public class GeneralizationCalculator extends AtomicDerivedStateProcessorBase<Generalization> {
/**
* Constructs the calculator.
*/
public GeneralizationCalculator() {
super(Generalization.class);
}
@Override
protected void applyTyped(Generalization object) {
Optional<Classifier> umlSpecific = Optional.ofNullable(object.getSpecific())
.map(UMLReferencingElement::getReferencedElement);
Optional<Classifier> umlGeneral = Optional.ofNullable(object.getGeneral())
.map(UMLReferencingElement::getReferencedElement);
if (!umlSpecific.isPresent() || !umlGeneral.isPresent()) {
return;
}
org.eclipse.uml2.uml.Generalization umlGeneralization = umlSpecific.get().getGeneralization(umlGeneral.get());
if (umlGeneralization != null) {
object.setReferencedElement(umlGeneralization);
}
}
} |
package org.rhq.maven.plugins;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.AbortableHttpRequest;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.json.JSONException;
import org.json.JSONObject;
import static java.lang.Boolean.TRUE;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.http.HttpHeaders.ACCEPT;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;
import static org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM;
import static org.apache.maven.plugins.annotations.LifecyclePhase.PACKAGE;
import static org.rhq.maven.plugins.Utils.getAgentPluginArchiveFile;
/**
* Upload a freshly built RHQ Agent Plugin to an RHQ container.
*
* @author Thomas Segismont
*/
@Mojo(name = "upload", defaultPhase = PACKAGE, threadSafe = true)
public class UploadMojo extends AbstractMojo {
private static final String REST_CONTEXT_PATH = "/rest";
private static final String REST_CONTENT_URI = REST_CONTEXT_PATH + "/content";
private static final String REST_CONTENT_UPLOAD_URI = REST_CONTENT_URI + "/fresh";
private static final String REST_PLUGINS_URI = REST_CONTEXT_PATH + "/plugins";
private static final String REST_PLUGINS_DEPLOY_URI = REST_PLUGINS_URI + "/deploy";
/**
* The build directory (root of build works).
*/
@Parameter(defaultValue = "${project.build.directory}", required = true, readonly = true)
private File buildDirectory;
/**
* The name of the generated RHQ agent plugin archive.
*/
@Parameter(defaultValue = "${project.build.finalName}", required = true, readonly = true)
private String finalName;
/**
* The scheme to use to communicate with the remote RHQ server.
*/
@Parameter(defaultValue = "http")
private String scheme;
/**
* Remote RHQ server host.
*/
@Parameter(required = true)
private String host;
/**
* Remote RHQ server port.
*/
@Parameter(defaultValue = "7080")
private int port;
@Parameter(required = true)
private String username;
/**
* Authentication password.
*/
@Parameter(required = true)
private String password;
/**
* Whether a plugin scan should be triggered on the server after upload.
*/
@Parameter(defaultValue = "true")
private boolean startScan;
/**
* Whether all agents should update their plugins. <strong>This will make your agents' plugin containers restart
* .</strong>
*/
@Parameter(defaultValue = "false")
private boolean updatePluginsOnAllAgents;
/**
* Whether to wait for the plugins update requests to complete.
*/
@Parameter(defaultValue = "false")
private boolean waitForPluginsUpdateOnAllAgents;
/**
* How long should we wait for the plugins update requests to complete. In seconds.
*/
@Parameter(defaultValue = "300")
private long maxWaitForPluginsUpdateOnAllAgents;
/**
* Whether to fail the build if an error occurs while uploading.
*/
@Parameter(defaultValue = "true")
private boolean failOnError;
/**
* Whether to skip the execution of this mojo.
*/
@Parameter(defaultValue = "false")
private boolean skipUpload;
/**
* In milliseconds.
*/
@Parameter(defaultValue = "60000")
private int socketConnectionTimeout;
/**
* In milliseconds.
*/
@Parameter(defaultValue = "300000")
private int socketReadTimeout;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (skipUpload) {
getLog().info("Skipped execution");
}
File agentPluginArchive = getAgentPluginArchiveFile(buildDirectory, finalName);
if (!agentPluginArchive.exists() && agentPluginArchive.isFile()) {
throw new MojoExecutionException("Agent plugin archive does not exist: " + agentPluginArchive);
}
// Prepare HttpClient
ClientConnectionManager httpConnectionManager = new BasicClientConnectionManager();
DefaultHttpClient httpClient = new DefaultHttpClient(httpConnectionManager);
HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, socketConnectionTimeout);
HttpConnectionParams.setSoTimeout(httpParams, socketReadTimeout);
httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port),
new UsernamePasswordCredentials(username, password));
HttpPost uploadContentRequest = null;
HttpPut moveContentToPluginsDirRequest = null;
HttpPost pluginScanRequest = null;
HttpPost pluginDeployRequest = null;
HttpGet pluginDeployCheckCompleteRequest = null;
try {
// Upload plugin content
URI uploadContentUri = buildUploadContentUri();
uploadContentRequest = new HttpPost(uploadContentUri);
uploadContentRequest.setEntity(new FileEntity(agentPluginArchive, APPLICATION_OCTET_STREAM));
uploadContentRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
HttpResponse uploadContentResponse = httpClient.execute(uploadContentRequest);
if (uploadContentResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
handleProblem(uploadContentResponse.getStatusLine().toString());
return;
}
getLog().info("Uploaded " + agentPluginArchive);
// Read the content handle value in JSON response
JSONObject uploadContentResponseJsonObject = new JSONObject(EntityUtils.toString(uploadContentResponse
.getEntity()));
String contentHandle = (String) uploadContentResponseJsonObject.get("value");
uploadContentRequest.abort();
if (!startScan && !updatePluginsOnAllAgents) {
// Request uploaded content to be moved to the plugins directory but do not trigger a plugin scan
URI moveContentToPluginsDirUri = buildMoveContentToPluginsDirUri(contentHandle);
moveContentToPluginsDirRequest = new HttpPut(moveContentToPluginsDirUri);
moveContentToPluginsDirRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
HttpResponse moveContentToPluginsDirResponse = httpClient.execute(moveContentToPluginsDirRequest);
if (moveContentToPluginsDirResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
handleProblem(moveContentToPluginsDirResponse.getStatusLine().toString());
return;
}
moveContentToPluginsDirRequest.abort();
getLog().info("Moved uploaded content to plugins directory");
return;
}
// Request uploaded content to be moved to the plugins directory and trigger a plugin scan
URI pluginScanUri = buildPluginScanUri(contentHandle);
pluginScanRequest = new HttpPost(pluginScanUri);
pluginScanRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
getLog().info("Moving uploaded content to plugins directory and requesting a plugin scan");
HttpResponse pluginScanResponse = httpClient.execute(pluginScanRequest);
if (pluginScanResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED
&& pluginScanResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
handleProblem(pluginScanResponse.getStatusLine().toString());
return;
}
pluginScanRequest.abort();
getLog().info("Plugin scan complete");
if (updatePluginsOnAllAgents) {
URI pluginDeployUri = buildPluginDeployUri();
pluginDeployRequest = new HttpPost(pluginDeployUri);
pluginDeployRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
getLog().info("Requesting agents to update their plugins");
HttpResponse pluginDeployResponse = httpClient.execute(pluginDeployRequest);
if (pluginDeployResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
handleProblem(pluginDeployResponse.getStatusLine().toString());
return;
}
getLog().info("Plugins update requests sent");
// Read the agent plugins update handle value in JSON response
JSONObject pluginDeployResponseJsonObject = new JSONObject(EntityUtils.toString(pluginDeployResponse
.getEntity()));
String pluginsUpdateHandle = (String) pluginDeployResponseJsonObject.get("value");
pluginDeployRequest.abort();
if (waitForPluginsUpdateOnAllAgents) {
getLog().info("Waiting for plugins update requests to complete");
long start = System.currentTimeMillis();
for (; ; ) {
URI pluginDeployCheckCompleteUri = buildPluginDeployCheckCompleteUri(pluginsUpdateHandle);
pluginDeployCheckCompleteRequest = new HttpGet(pluginDeployCheckCompleteUri);
pluginDeployCheckCompleteRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
HttpResponse pluginDeployCheckCompleteResponse = httpClient.execute
(pluginDeployCheckCompleteRequest);
if (pluginDeployCheckCompleteResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
handleProblem(pluginDeployCheckCompleteResponse.getStatusLine().toString());
return;
}
// Read the agent plugins update handle value in JSON response
JSONObject pluginDeployCheckCompleteResponseJsonObject = new JSONObject(EntityUtils.toString
(pluginDeployCheckCompleteResponse.getEntity()));
Boolean pluginDeployCheckCompleteHandle = (Boolean)
pluginDeployCheckCompleteResponseJsonObject.get("value");
pluginDeployCheckCompleteRequest.abort();
if (pluginDeployCheckCompleteHandle == TRUE) {
getLog().info("All agents updated their plugins");
return;
}
if (SECONDS.toMillis(maxWaitForPluginsUpdateOnAllAgents) < (System.currentTimeMillis() -
start)) {
handleProblem("Not all agents updated their plugins but wait limit has been reached (" +
maxWaitForPluginsUpdateOnAllAgents + " ms)");
return;
}
Thread.sleep(SECONDS.toMillis(5));
getLog().info("Checking plugins update requests status again");
}
}
}
} catch (IOException e) {
handleException(e);
} catch (JSONException e) {
handleException(e);
} catch (URISyntaxException e) {
handleException(e);
} catch (InterruptedException e) {
handleException(e);
} finally {
abortQuietly(uploadContentRequest);
abortQuietly(moveContentToPluginsDirRequest);
abortQuietly(pluginScanRequest);
abortQuietly(pluginDeployRequest);
abortQuietly(pluginDeployCheckCompleteRequest);
httpConnectionManager.shutdown();
}
}
private void abortQuietly(AbortableHttpRequest httpRequest) {
if (httpRequest != null) {
httpRequest.abort();
}
}
private void handleProblem(String message) throws MojoExecutionException {
if (failOnError) {
throw new MojoExecutionException(message);
}
getLog().error(message);
}
private void handleException(Exception e) throws MojoExecutionException {
if (failOnError) {
throw new MojoExecutionException(e.getMessage(), e);
}
getLog().error(e.getMessage(), e);
}
private URI buildUploadContentUri() throws URISyntaxException {
return new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setPort(port)
.setPath(REST_CONTENT_UPLOAD_URI)
.build();
}
private URI buildMoveContentToPluginsDirUri(String contentHandle) throws URISyntaxException {
return new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setPort(port)
.setPath(REST_CONTENT_URI + "/" + contentHandle + "/plugins")
.setParameter("name", getAgentPluginArchiveFile(buildDirectory, finalName).getName())
.setParameter("startScan", String.valueOf(false))
.build();
}
private URI buildPluginScanUri(String contentHandle) throws URISyntaxException {
return new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setPort(port)
.setPath(REST_PLUGINS_URI)
.setParameter("handle", contentHandle)
.setParameter("name", getAgentPluginArchiveFile(buildDirectory, finalName).getName())
.build();
}
private URI buildPluginDeployUri() throws URISyntaxException {
return new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setPort(port)
.setPath(REST_PLUGINS_DEPLOY_URI)
.build();
}
private URI buildPluginDeployCheckCompleteUri(String pluginsUpdateHandle) throws URISyntaxException {
return new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setPort(port)
.setPath(REST_PLUGINS_DEPLOY_URI + "/" + pluginsUpdateHandle)
.build();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.