_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q18300 | LRActivity.addActor | train | public boolean addActor(String objectType, String displayName, String url, String[] description)
{
Map<String, Object> container = new HashMap<String, Object>();
if (objectType != null)
{
container.put("objectType", objectType);
}
else
{
return false;
}
if (displayName != null)
{
container.put("displayName", displayName);
}
if (url != null)
{
container.put("url", url);
}
if (description != null && description.length > 0)
{
container.put("description", description);
}
return addChild("actor", container, null);
} | java | {
"resource": ""
} |
q18301 | LRActivity.addObject | train | public boolean addObject(String objectType, String id, String content)
{
Map<String, Object> container = new HashMap<String, Object>();
if (objectType != null)
{
container.put("objectType", objectType);
}
if (id != null)
{
container.put("id", id);
}
if (content != null)
{
container.put("content", content);
}
return addChild("object", container, null);
} | java | {
"resource": ""
} |
q18302 | LRActivity.addRelatedObject | train | public boolean addRelatedObject(String objectType, String id, String content)
{
Map<String, Object> container = new HashMap<String, Object>();
if (objectType != null)
{
container.put("objectType", objectType);
}
else
{
return false;
}
if (id != null)
{
container.put("id", id);
}
if (content != null)
{
container.put("content", content);
}
related.add(container);
return true;
} | java | {
"resource": ""
} |
q18303 | LRActivity.getMap | train | private Map<String, Object> getMap(String[] pathKeys)
{
if (pathKeys == null)
{
return (Map<String, Object>)resourceData;
}
Map<String, Object> selected = (Map<String, Object>)resourceData;
for(int i = 0; i < pathKeys.length; i++)
{
if (selected.containsKey(pathKeys[i]) && selected.get(pathKeys[i]).getClass().equals(resourceData.getClass()))
{
selected = (Map<String, Object>) selected.get(pathKeys[i]);
}
else
{
return null;
}
}
return selected;
} | java | {
"resource": ""
} |
q18304 | LRActivity.addChild | train | private boolean addChild(String name, Object value, String[] pathKeys)
{
Map<String, Object> selected = (Map<String, Object>)resourceData;
if (pathKeys != null)
{
selected = getMap(pathKeys);
}
if (selected != null && !selected.containsKey(name))
{
selected.put(name, value);
return true;
}
return false;
} | java | {
"resource": ""
} |
q18305 | StencilInterpreter.process | train | public void process(TemplateImpl template, Writer out) throws IOException {
Environment env = new Environment(template.getPath(), out);
currentScope.declaringEnvironment = env;
Environment prevEnv = switchEnvironment(env);
TemplateContext tmpl = template.getContext();
HeaderContext hdr = tmpl.hdr;
if (hdr != null &&
hdr.hdrSig != null &&
hdr.hdrSig.callSig != null &&
hdr.hdrSig.callSig.paramDecls != null) {
for (ParameterDeclContext paramDecl : hdr.hdrSig.callSig.paramDecls) {
String paramId = paramDecl.id.getText();
if (!currentScope.values.containsKey(paramId)) {
currentScope.declare(paramId, eval(paramDecl.expr));
}
}
}
try {
tmpl.accept(visitor);
}
finally {
switchEnvironment(prevEnv);
}
} | java | {
"resource": ""
} |
q18306 | StencilInterpreter.load | train | private TemplateImpl load(String path, ParserRuleContext errCtx) {
path = Paths.resolvePath(currentEnvironment.path, path);
try {
return (TemplateImpl) engine.load(path);
}
catch (IOException | ParseException e) {
throw new ExecutionException("error importing " + path, e, getLocation(errCtx));
}
} | java | {
"resource": ""
} |
q18307 | StencilInterpreter.switchEnvironment | train | private Environment switchEnvironment(Environment env) {
Environment prev = currentEnvironment;
currentEnvironment = env;
return prev;
} | java | {
"resource": ""
} |
q18308 | StencilInterpreter.switchScope | train | private Scope switchScope(Scope scope) {
Scope prev = currentScope;
currentScope = scope;
return prev;
} | java | {
"resource": ""
} |
q18309 | StencilInterpreter.bindBlocks | train | private Map<String, Object> bindBlocks(PrepareSignatureContext sig, PrepareInvocationContext inv) {
if(inv == null) {
return Collections.emptyMap();
}
BlockDeclContext allDecl = null;
BlockDeclContext unnamedDecl = null;
List<NamedOutputBlockContext> namedBlocks = new ArrayList<>(inv.namedBlocks);
Map<String, Object> blocks = new HashMap<>();
for (BlockDeclContext blockDecl : sig.blockDecls) {
if (blockDecl.flag != null) {
if (blockDecl.flag.getText().equals("*")) {
if (allDecl != null) {
throw new ExecutionException("only a single parameter can be marked with '*'", getLocation(blockDecl));
}
allDecl = blockDecl;
}
else if (blockDecl.flag.getText().equals("+")) {
if (unnamedDecl != null) {
throw new ExecutionException("only a single parameter can be marked with '+'", getLocation(blockDecl));
}
unnamedDecl = blockDecl;
}
else {
throw new ExecutionException("unknown block declaration flag", getLocation(blockDecl));
}
continue;
}
//Find the block
ParserRuleContext paramBlock = findAndRemoveBlock(namedBlocks, name(blockDecl));
//Bind the block
BoundParamOutputBlock boundBlock = bindBlock(paramBlock);
blocks.put(name(blockDecl), boundBlock);
}
//
// Bind unnamed block (if requested)
//
if (unnamedDecl != null) {
UnnamedOutputBlockContext unnamedBlock = inv.unnamedBlock;
BoundParamOutputBlock boundUnnamedBlock = bindBlock(unnamedBlock);
blocks.put(unnamedDecl.id.getText(), boundUnnamedBlock);
}
//
// Bind rest of blocks (if requested)
//
if (allDecl != null) {
Map<String, Block> otherBlocks = new HashMap<>();
// Add unnamed block if it wasn't bound explicitly
if (inv.unnamedBlock != null && unnamedDecl == null) {
UnnamedOutputBlockContext unnamedBlock = inv.unnamedBlock;
BoundParamOutputBlock boundUnnamedBlock = new BoundParamOutputBlock(unnamedBlock, mode(unnamedBlock), currentScope);
otherBlocks.put("", boundUnnamedBlock);
}
// Add all other unbound blocks
for (NamedOutputBlockContext namedBlock : namedBlocks) {
String blockName = nullToEmpty(name(namedBlock));
BoundParamOutputBlock boundNamedBlock = new BoundParamOutputBlock(namedBlock, mode(namedBlock), currentScope);
otherBlocks.put(blockName, boundNamedBlock);
}
blocks.put(allDecl.id.getText(), otherBlocks);
}
return blocks;
} | java | {
"resource": ""
} |
q18310 | StencilInterpreter.findAndRemoveBlock | train | private NamedOutputBlockContext findAndRemoveBlock(List<NamedOutputBlockContext> blocks, String name) {
if(blocks == null) {
return null;
}
Iterator<NamedOutputBlockContext> blockIter = blocks.iterator();
while (blockIter.hasNext()) {
NamedOutputBlockContext block = blockIter.next();
String blockName = name(block);
if(name.equals(blockName)) {
blockIter.remove();
return block;
}
}
return null;
} | java | {
"resource": ""
} |
q18311 | StencilInterpreter.findAndRemoveValue | train | private ExpressionContext findAndRemoveValue(List<NamedValueContext> namedValues, String name) {
Iterator<NamedValueContext> namedValueIter = namedValues.iterator();
while (namedValueIter.hasNext()) {
NamedValueContext namedValue = namedValueIter.next();
if (name.equals(value(namedValue.name))) {
namedValueIter.remove();
return namedValue.expr;
}
}
return null;
} | java | {
"resource": ""
} |
q18312 | StencilInterpreter.eval | train | private Object eval(ExpressionContext expr) {
Object res = expr;
while(res instanceof ExpressionContext)
res = ((ExpressionContext)res).accept(visitor);
if(res instanceof LValue)
res = ((LValue) res).get(expr);
return res;
} | java | {
"resource": ""
} |
q18313 | StencilInterpreter.eval | train | private List<Object> eval(Iterable<ExpressionContext> expressions) {
List<Object> results = new ArrayList<Object>();
for (ExpressionContext expression : expressions) {
results.add(eval(expression));
}
return results;
} | java | {
"resource": ""
} |
q18314 | StencilInterpreter.exec | train | private Object exec(StatementContext statement) {
if (statement == null)
return null;
return statement.accept(visitor);
} | java | {
"resource": ""
} |
q18315 | StencilInterpreter.getLocation | train | ExecutionLocation getLocation(ParserRuleContext object) {
Token start = object.getStart();
return new ExecutionLocation(currentScope.declaringEnvironment.path, start.getLine(), start.getCharPositionInLine() + 1);
} | java | {
"resource": ""
} |
q18316 | EnumPrefixFinder.find | train | public T find(String text)
{
T match = matcher.match(text, true);
if (match != null)
{
String name = match.name();
if (name.substring(0, Math.min(name.length(), text.length())).equalsIgnoreCase(text))
{
return match;
}
}
return null;
} | java | {
"resource": ""
} |
q18317 | JmsHandler.stop | train | public static void stop()
throws EFapsException
{
for (final QueueConnection queCon : JmsHandler.QUEUE2QUECONN.values()) {
try {
queCon.close();
} catch (final JMSException e) {
throw new EFapsException("JMSException", e);
}
}
for (final TopicConnection queCon : JmsHandler.TOPIC2QUECONN.values()) {
try {
queCon.close();
} catch (final JMSException e) {
throw new EFapsException("JMSException", e);
}
}
JmsHandler.TOPIC2QUECONN.clear();
JmsHandler.QUEUE2QUECONN.clear();
JmsHandler.NAME2DEF.clear();
} | java | {
"resource": ""
} |
q18318 | TimeoutException.getTimeoutMessage | train | public static String getTimeoutMessage(long timeout, TimeUnit unit) {
return String.format("Timeout of %d %s reached", timeout, requireNonNull(unit, "unit"));
} | java | {
"resource": ""
} |
q18319 | AbstractDelete.checkAccess | train | protected void checkAccess()
throws EFapsException
{
for (final Instance instance : getInstances()) {
if (!instance.getType().hasAccess(instance, AccessTypeEnums.DELETE.getAccessType(), null)) {
LOG.error("Delete not permitted for Person: {} on Instance: {}", Context.getThreadContext().getPerson(),
instance);
throw new EFapsException(getClass(), "execute.NoAccess", instance);
}
}
} | java | {
"resource": ""
} |
q18320 | Camera.set | train | public void set(double eyeX, double eyeY, double eyeZ,
double centerX, double centerY, double centerZ,
double upX, double upY, double upZ) {
this.eyeX = eyeX;
this.eyeY = eyeY;
this.eyeZ = eyeZ;
this.centerX = centerX;
this.centerY = centerY;
this.centerZ = centerZ;
this.upX = upX;
this.upY = upY;
this.upZ = upZ;
} | java | {
"resource": ""
} |
q18321 | Camera.setEye | train | public void setEye(double eyeX, double eyeY, double eyeZ) {
this.eyeX = eyeX;
this.eyeY = eyeY;
this.eyeZ = eyeZ;
} | java | {
"resource": ""
} |
q18322 | Camera.setCenter | train | public void setCenter(double centerX, double centerY, double centerZ) {
this.centerX = centerX;
this.centerY = centerY;
this.centerZ = centerZ;
} | java | {
"resource": ""
} |
q18323 | Camera.setOrientation | train | public void setOrientation(double upX, double upY, double upZ) {
this.upX = upX;
this.upY = upY;
this.upZ = upZ;
} | java | {
"resource": ""
} |
q18324 | Camera.getCameraDirection | train | public double[] getCameraDirection() {
double[] cameraDirection = new double[3];
double l = Math.sqrt(Math.pow(this.eyeX - this.centerX, 2.0) + Math.pow(this.eyeZ - this.centerZ, 2.0) + Math.pow(this.eyeZ - this.centerZ, 2.0));
cameraDirection[0] = (this.centerX - this.eyeX) / l;
cameraDirection[1] = (this.centerY - this.eyeY) / l;
cameraDirection[2] = (this.centerZ - this.eyeZ) / l;
return cameraDirection;
} | java | {
"resource": ""
} |
q18325 | AbstractRest.hasAccess | train | protected boolean hasAccess()
throws EFapsException
{
//Admin_REST
return Context.getThreadContext().getPerson().isAssigned(Role.get(
UUID.fromString("2d142645-140d-46ad-af67-835161a8d732")));
} | java | {
"resource": ""
} |
q18326 | AbstractRest.getJSONReply | train | protected String getJSONReply(final Object _jsonObject)
{
String ret = "";
final ObjectMapper mapper = new ObjectMapper();
if (LOG.isDebugEnabled()) {
mapper.enable(SerializationFeature.INDENT_OUTPUT);
}
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.registerModule(new JodaModule());
try {
ret = mapper.writeValueAsString(_jsonObject);
} catch (final JsonProcessingException e) {
LOG.error("Catched JsonProcessingException", e);
}
return ret;
} | java | {
"resource": ""
} |
q18327 | JmsSession.login | train | public static String login(final String _userName,
final String _passwd,
final String _applicationKey)
throws EFapsException
{
String ret = null;
if (JmsSession.checkLogin(_userName, _passwd, _applicationKey)) {
final JmsSession session = new JmsSession(_userName);
JmsSession.CACHE.put(session.getSessionKey(), session);
ret = session.getSessionKey();
}
return ret;
} | java | {
"resource": ""
} |
q18328 | ChecksumWrapper.update | train | void update(long index, int b)
{
if (size > 0)
{
assert index <= hi;
if (index < lo)
{
throw new IllegalStateException("lookaheadLength() too small in ChecksumProvider implementation");
}
hi = index;
if ((lo == hi - size))
{
checksum.update(lookahead[(int)(lo % size)]);
lo++;
}
lookahead[(int)(hi++ % size)] = b;
}
else
{
if (index == hi)
{
checksum.update(b);
hi = index+1;
}
else
{
if (index != hi -1)
{
throw new IllegalStateException("lookahead needed for checksum");
}
}
}
} | java | {
"resource": ""
} |
q18329 | AbstractSourceImporter.execute | train | public void execute()
throws InstallationException
{
Instance instance = searchInstance();
if (instance == null) {
instance = createInstance();
}
updateDB(instance);
} | java | {
"resource": ""
} |
q18330 | AbstractSourceImporter.createInstance | train | protected Instance createInstance()
throws InstallationException
{
final Insert insert;
try {
insert = new Insert(getCiType());
insert.add("Name", this.programName);
if (getEFapsUUID() != null) {
insert.add("UUID", getEFapsUUID().toString());
}
insert.execute();
} catch (final EFapsException e) {
throw new InstallationException("Could not create " + getCiType() + " " + getProgramName(), e);
}
return insert.getInstance();
} | java | {
"resource": ""
} |
q18331 | AbstractSourceImporter.updateDB | train | public void updateDB(final Instance _instance)
throws InstallationException
{
try {
final InputStream is = newCodeInputStream();
final Checkin checkin = new Checkin(_instance);
checkin.executeWithoutAccessCheck(getProgramName(), is, is.available());
} catch (final UnsupportedEncodingException e) {
throw new InstallationException("Encoding failed for " + this.programName, e);
} catch (final EFapsException e) {
throw new InstallationException("Could not check in " + this.programName, e);
} catch (final IOException e) {
throw new InstallationException("Reading from inoutstream faild for " + this.programName, e);
}
} | java | {
"resource": ""
} |
q18332 | StartupDatabaseConnection.startup | train | public static void startup(final String _classDBType,
final String _classDSFactory,
final String _propConnection,
final String _classTM,
final String _classTSR,
final String _eFapsProps)
throws StartupException
{
StartupDatabaseConnection.startup(_classDBType,
_classDSFactory,
StartupDatabaseConnection.convertToMap(_propConnection),
_classTM,
_classTSR,
StartupDatabaseConnection.convertToMap(_eFapsProps));
} | java | {
"resource": ""
} |
q18333 | StartupDatabaseConnection.configureEFapsProperties | train | protected static void configureEFapsProperties(final Context _compCtx,
final Map<String, String> _eFapsProps)
throws StartupException
{
try {
Util.bind(_compCtx, "env/" + INamingBinds.RESOURCE_CONFIGPROPERTIES, _eFapsProps);
} catch (final NamingException e) {
throw new StartupException("could not bind eFaps Properties '" + _eFapsProps + "'", e);
// CHECKSTYLE:OFF
} catch (final Exception e) {
// CHECKSTYLE:ON
throw new StartupException("could not bind eFaps Properties '" + _eFapsProps + "'", e);
}
} | java | {
"resource": ""
} |
q18334 | StartupDatabaseConnection.shutdown | train | public static void shutdown()
throws StartupException
{
final Context compCtx;
try {
final InitialContext context = new InitialContext();
compCtx = (javax.naming.Context) context.lookup("java:comp");
} catch (final NamingException e) {
throw new StartupException("Could not initialize JNDI", e);
}
try {
Util.unbind(compCtx, "env/" + INamingBinds.RESOURCE_DATASOURCE);
Util.unbind(compCtx, "env/" + INamingBinds.RESOURCE_DBTYPE);
Util.unbind(compCtx, "env/" + INamingBinds.RESOURCE_CONFIGPROPERTIES);
Util.unbind(compCtx, "env/" + INamingBinds.RESOURCE_TRANSMANAG);
} catch (final NamingException e) {
throw new StartupException("unbind of the database connection failed", e);
}
} | java | {
"resource": ""
} |
q18335 | AbstractSQLInsertUpdate.columnWithCurrentTimestamp | train | @SuppressWarnings("unchecked")
public STMT columnWithCurrentTimestamp(final String _columnName)
{
this.columnWithSQLValues.add(
new AbstractSQLInsertUpdate.ColumnWithSQLValue(_columnName,
Context.getDbType().getCurrentTimeStamp()));
return (STMT) this;
} | java | {
"resource": ""
} |
q18336 | InvokerUtil.getInvoker | train | public static EQLInvoker getInvoker()
{
final EQLInvoker ret = new EQLInvoker()
{
@Override
protected AbstractPrintStmt getPrint()
{
return new PrintStmt();
}
@Override
protected AbstractInsertStmt getInsert()
{
return new InsertStmt();
}
@Override
protected AbstractExecStmt getExec()
{
return new ExecStmt();
}
@Override
protected AbstractUpdateStmt getUpdate()
{
return new UpdateStmt();
}
@Override
protected AbstractDeleteStmt getDelete()
{
return new DeleteStmt();
}
@Override
protected INestedQueryStmtPart getNestedQuery()
{
return super.getNestedQuery();
}
@Override
protected AbstractCIPrintStmt getCIPrint()
{
return new CIPrintStmt();
}
};
ret.getValidator().setDiagnosticClazz(EFapsDiagnostic.class);
ret.getValidator().addValidation("EQLJavaValidator.type", new TypeValidation());
return ret;
} | java | {
"resource": ""
} |
q18337 | Filter.append2SQLSelect | train | public void append2SQLSelect(final SQLSelect _sqlSelect)
{
if (iWhere != null) {
final SQLWhere sqlWhere = _sqlSelect.getWhere();
for (final IWhereTerm<?> term : iWhere.getTerms()) {
if (term instanceof IWhereElementTerm) {
final IWhereElement element = ((IWhereElementTerm) term).getElement();
if (element.getAttribute() != null)
{
final String attrName = element.getAttribute();
for (final Type type : types) {
final Attribute attr = type.getAttribute(attrName);
if (attr != null) {
addAttr(_sqlSelect, sqlWhere, attr, term, element);
break;
}
}
} else if (element.getSelect() != null) {
final IWhereSelect select = element.getSelect();
for (final ISelectElement ele : select.getElements()) {
if (ele instanceof IBaseSelectElement) {
switch (((IBaseSelectElement) ele).getElement()) {
case STATUS:
for (final Type type : types) {
final Attribute attr = type.getStatusAttribute();
if (attr != null) {
addAttr(_sqlSelect, sqlWhere, attr, term, element);
break;
}
}
break;
default:
break;
}
} else if (ele instanceof IAttributeSelectElement) {
final String attrName = ((IAttributeSelectElement) ele).getName();
for (final Type type : types) {
addAttr(_sqlSelect, sqlWhere, type.getAttribute(attrName), term, element);
}
}
}
}
}
}
}
if (iOrder != null) {
final SQLOrder sqlOrder = _sqlSelect.getOrder();
for (final IOrderElement element: iOrder.getElements()) {
for (final Type type : types) {
final Attribute attr = type.getAttribute(element.getKey());
if (attr != null) {
final SQLTable table = attr.getTable();
final String tableName = table.getSqlTable();
final TableIdx tableidx = _sqlSelect.getIndexer().getTableIdx(tableName);
sqlOrder.addElement(tableidx.getIdx(), attr.getSqlColNames(), element.isDesc());
break;
}
}
}
}
} | java | {
"resource": ""
} |
q18338 | PrimeInstance.init | train | void init() {
if (! isEnabled()) {
loggerConfig.info("Ted prime instance check is disabled");
return;
}
this.primeTaskId = context.tedDaoExt.findPrimeTaskId();
int periodMs = context.config.intervalDriverMs();
this.postponeSec = (int)Math.round((1.0 * periodMs * TICK_SKIP_COUNT + 500 + 500) / 1000); // 500ms reserve, 500 for rounding up
becomePrime();
loggerConfig.info("Ted prime instance check is enabled, primeTaskId={} isPrime={} postponeSec={}", primeTaskId, isPrime, postponeSec);
initiated = true;
} | java | {
"resource": ""
} |
q18339 | URLTemplateSourceLoader.find | train | @Override
public TemplateSource find(String path) throws IOException {
return new URLTemplateSource(new URL("file", null, path));
} | java | {
"resource": ""
} |
q18340 | BundleMaker.initialize | train | public static void initialize()
throws CacheReloadException
{
if (InfinispanCache.get().exists(BundleMaker.NAMECACHE)) {
InfinispanCache.get().<UUID, Type>getCache(BundleMaker.NAMECACHE).clear();
InfinispanCache.get().<UUID, Type>getCache(BundleMaker.CACHE4BUNDLE).clear();
InfinispanCache.get().<UUID, Type>getCache(BundleMaker.CACHE4BUNDLEMAP).clear();
} else {
InfinispanCache.get().<UUID, Type>getCache(BundleMaker.NAMECACHE)
.addListener(new CacheLogListener(BundleMaker.LOG));
InfinispanCache.get().<UUID, Type>getCache(BundleMaker.CACHE4BUNDLE)
.addListener(new CacheLogListener(BundleMaker.LOG));
InfinispanCache.get().<UUID, Type>getCache(BundleMaker.CACHE4BUNDLEMAP)
.addListener(new CacheLogListener(BundleMaker.LOG));
}
} | java | {
"resource": ""
} |
q18341 | BundleMaker.containsKey | train | public static boolean containsKey(final String _key)
{
final Cache<String, BundleInterface> cache = InfinispanCache.get()
.<String, BundleInterface>getIgnReCache(BundleMaker.CACHE4BUNDLE);
return cache.containsKey(_key);
} | java | {
"resource": ""
} |
q18342 | BundleMaker.createNewKey | train | private static String createNewKey(final List<String> _names,
final Class<?> _bundleclass)
throws EFapsException
{
final StringBuilder builder = new StringBuilder();
final List<String> oids = new ArrayList<>();
String ret = null;
try {
for (final String name : _names) {
if (builder.length() > 0) {
builder.append("-");
}
final Cache<String, StaticCompiledSource> cache = InfinispanCache.get()
.<String, StaticCompiledSource>getIgnReCache(BundleMaker.NAMECACHE);
if (!cache.containsKey(name)) {
final QueryBuilder queryBldr = new QueryBuilder(CIAdminProgram.StaticCompiled);
queryBldr.addWhereAttrEqValue(CIAdminProgram.StaticCompiled.Name, name);
final MultiPrintQuery multi = queryBldr.getPrint();
multi.addAttribute(CIAdminProgram.StaticCompiled.Name);
multi.execute();
while (multi.next()) {
final String statName = multi.<String>getAttribute(CIAdminProgram.StaticCompiled.Name);
final StaticCompiledSource source = new StaticCompiledSource(multi.getCurrentInstance()
.getOid(),
statName);
cache.put(source.getName(), source);
}
}
if (cache.containsKey(name)) {
final String oid = cache.get(name).getOid();
builder.append(oid);
oids.add(oid);
}
}
ret = builder.toString();
final BundleInterface bundle =
(BundleInterface) _bundleclass.newInstance();
bundle.setKey(ret, oids);
final Cache<String, BundleInterface> cache = InfinispanCache.get()
.<String, BundleInterface>getIgnReCache(BundleMaker.CACHE4BUNDLE);
cache.put(ret, bundle);
} catch (final InstantiationException e) {
throw new EFapsException(BundleMaker.class,
"createNewKey.InstantiationException", e, _bundleclass);
} catch (final IllegalAccessException e) {
throw new EFapsException(BundleMaker.class,
"createNewKey.IllegalAccessException", e, _bundleclass);
}
return ret;
} | java | {
"resource": ""
} |
q18343 | RunLevel.init | train | public static void init(final String _runLevel)
throws EFapsException
{
RunLevel.ALL_RUNLEVELS.clear();
RunLevel.RUNLEVEL = new RunLevel(_runLevel);
} | java | {
"resource": ""
} |
q18344 | RunLevel.getAllInitializers | train | private List<String> getAllInitializers()
{
final List<String> ret = new ArrayList<>();
for (final CacheMethod cacheMethod : this.cacheMethods) {
ret.add(cacheMethod.className);
}
if (this.parent != null) {
ret.addAll(this.parent.getAllInitializers());
}
return ret;
} | java | {
"resource": ""
} |
q18345 | RunLevel.initialize | train | protected void initialize(final String _sql)
throws EFapsException
{
Connection con = null;
try {
con = Context.getConnection();
Statement stmt = null;
long parentId = 0;
try {
stmt = con.createStatement();
// read run level itself
ResultSet rs = stmt.executeQuery(_sql);
if (rs.next()) {
this.id = rs.getLong(1);
parentId = rs.getLong(2);
} else {
RunLevel.LOG.error("RunLevel not found");
}
rs.close();
// read all methods for one run level
rs = stmt.executeQuery(RunLevel.SELECT_DEF_PRE.getCopy()
.addPart(SQLPart.WHERE)
.addColumnPart(0, "RUNLEVELID")
.addPart(SQLPart.EQUAL)
.addValuePart(this.id)
.addPart(SQLPart.ORDERBY)
.addColumnPart(0, "PRIORITY").getSQL());
/**
* Order part of the SQL select statement.
*/
//private static final String SQL_DEF_POST = " order by PRIORITY";
while (rs.next()) {
if (rs.getString(3) != null) {
this.cacheMethods.add(new CacheMethod(rs.getString(1).trim(),
rs.getString(2).trim(),
rs.getString(3).trim()));
} else {
this.cacheMethods.add(new CacheMethod(rs.getString(1).trim(),
rs.getString(2).trim()));
}
}
rs.close();
} finally {
if (stmt != null) {
stmt.close();
}
}
con.commit();
con.close();
RunLevel.ALL_RUNLEVELS.put(this.id, this);
if (parentId != 0) {
this.parent = RunLevel.ALL_RUNLEVELS.get(parentId);
if (this.parent == null) {
this.parent = new RunLevel(parentId);
}
}
} catch (final EFapsException e) {
RunLevel.LOG.error("initialise()", e);
} catch (final SQLException e) {
RunLevel.LOG.error("initialise()", e);
} finally {
try {
if (con != null && !con.isClosed()) {
con.close();
}
} catch (final SQLException e) {
throw new CacheReloadException("Cannot read a type for an attribute.", e);
}
}
} | java | {
"resource": ""
} |
q18346 | ConfigUtils.getInteger | train | static Integer getInteger(Properties properties, String key, Integer defaultValue) {
if (properties == null)
return defaultValue;
String value = properties.getProperty(key);
if (value == null || value.isEmpty())
return defaultValue;
int intVal;
try {
intVal = Integer.parseInt(value);
} catch (NumberFormatException e) {
logger.warn("Cannot read property '" + key + "'. Expected integer, but got '" + value + "'. Setting default value = '" + defaultValue + "'", e.getMessage());
return defaultValue;
}
logger.trace("Read property '" + key + "' value '" + intVal + "'");
return intVal;
} | java | {
"resource": ""
} |
q18347 | DelayedExecutor.execute | train | public void execute(T target) throws Throwable
{
try
{
for (Invokation invokation : queue)
{
invokation.invoke(target);
}
}
catch (InvocationTargetException ex)
{
throw ex.getCause();
}
catch (ReflectiveOperationException ex)
{
throw new RuntimeException(ex);
}
} | java | {
"resource": ""
} |
q18348 | LREnvelope.getSignableData | train | protected Map<String, Object> getSignableData()
{
final Map<String, Object> doc = getSendableData();
// remove node-specific data
for (int i = 0; i < excludedFields.length; i++) {
doc.remove(excludedFields[i]);
}
return doc;
} | java | {
"resource": ""
} |
q18349 | LREnvelope.getSendableData | train | protected Map<String, Object> getSendableData()
{
Map<String, Object> doc = new LinkedHashMap<String, Object>();
MapUtil.put(doc, docTypeField, docType);
MapUtil.put(doc, docVersionField, docVersion);
MapUtil.put(doc, activeField, true);
MapUtil.put(doc, resourceDataTypeField, resourceDataType);
Map<String, Object> docId = new HashMap<String, Object>();
MapUtil.put(docId, submitterTypeField, submitterType);
MapUtil.put(docId, submitterField, submitter);
MapUtil.put(docId, curatorField, curator);
MapUtil.put(docId, ownerField, owner);
MapUtil.put(docId, signerField, signer);
MapUtil.put(doc, identityField, docId);
MapUtil.put(doc, submitterTTLField, submitterTTL);
Map<String, Object> docTOS = new HashMap<String, Object>();
MapUtil.put(docTOS, submissionTOSField, submissionTOS);
MapUtil.put(docTOS, submissionAttributionField, submissionAttribution);
MapUtil.put(doc, TOSField, docTOS);
MapUtil.put(doc, resourceLocatorField, resourceLocator);
MapUtil.put(doc, payloadPlacementField, payloadPlacement);
MapUtil.put(doc, payloadSchemaField, payloadSchema);
MapUtil.put(doc, payloadSchemaLocatorField, payloadSchemaLocator);
MapUtil.put(doc, keysField, tags);
MapUtil.put(doc, resourceDataField, getEncodedResourceData());
MapUtil.put(doc, replacesField, replaces);
if (signed)
{
Map<String, Object> sig = new HashMap<String, Object>();
String[] keys = {publicKeyLocation};
MapUtil.put(sig, keyLocationField, keys);
MapUtil.put(sig, signingMethodField, signingMethod);
MapUtil.put(sig, signatureField, clearSignedMessage);
MapUtil.put(doc, digitalSignatureField, sig);
}
return doc;
} | java | {
"resource": ""
} |
q18350 | LREnvelope.addSigningData | train | public void addSigningData(String signingMethod, String publicKeyLocation, String clearSignedMessage)
{
this.signingMethod = signingMethod;
this.publicKeyLocation = publicKeyLocation;
this.clearSignedMessage = clearSignedMessage;
this.signed = true;
} | java | {
"resource": ""
} |
q18351 | Gravatar.getUrl | train | public String getUrl(String email) {
if (email == null) {
throw new IllegalArgumentException("Email can't be null.");
}
String emailHash = DigestUtils.md5Hex(email.trim().toLowerCase());
boolean firstParameter = true;
// StringBuilder standard capacity is 16 characters while the minimum
// url is 63 characters long. The maximum length without
// customDefaultImage
// is 91.
StringBuilder builder = new StringBuilder(91)
.append(https ? HTTPS_URL : URL)
.append(emailHash)
.append(FILE_TYPE_EXTENSION);
if (size != DEFAULT_SIZE) {
addParameter(builder, "s", Integer.toString(size), firstParameter);
firstParameter = false;
}
if (forceDefault) {
addParameter(builder, "f", "y", firstParameter);
firstParameter = false;
}
if (rating != DEFAULT_RATING) {
addParameter(builder, "r", rating.getKey(), firstParameter);
firstParameter = false;
}
if (customDefaultImage != null) {
addParameter(builder, "d", customDefaultImage, firstParameter);
} else if (standardDefaultImage != null) {
addParameter(builder, "d", standardDefaultImage.getKey(), firstParameter);
}
return builder.toString();
} | java | {
"resource": ""
} |
q18352 | EventDefinition.setProperties | train | private void setProperties(final Instance _instance)
throws EFapsException
{
final QueryBuilder queryBldr = new QueryBuilder(CIAdminCommon.Property);
queryBldr.addWhereAttrEqValue(CIAdminCommon.Property.Abstract, _instance.getId());
final MultiPrintQuery multi = queryBldr.getPrint();
multi.addAttribute(CIAdminCommon.Property.Name, CIAdminCommon.Property.Value);
multi.executeWithoutAccessCheck();
while (multi.next()) {
super.setProperty(multi.<String>getAttribute(CIAdminCommon.Property.Name),
multi.<String>getAttribute(CIAdminCommon.Property.Value));
}
} | java | {
"resource": ""
} |
q18353 | EventDefinition.checkProgramInstance | train | private void checkProgramInstance()
{
try {
if (EventDefinition.LOG.isDebugEnabled()) {
EventDefinition.LOG.debug("checking Instance: {} - {}", this.resourceName, this.methodName);
}
if (!EFapsClassLoader.getInstance().isOffline()) {
final Class<?> cls = Class.forName(this.resourceName, true, EFapsClassLoader.getInstance());
final Method method = cls.getMethod(this.methodName, new Class[] { Parameter.class });
final Object progInstance = cls.newInstance();
if (EventDefinition.LOG.isDebugEnabled()) {
EventDefinition.LOG.debug("found Class: {} and method {}", progInstance, method);
}
}
} catch (final ClassNotFoundException e) {
EventDefinition.LOG.error("could not find Class: '{}'", this.resourceName, e);
} catch (final InstantiationException e) {
EventDefinition.LOG.error("could not instantiat Class: '{}'", this.resourceName, e);
} catch (final IllegalAccessException e) {
EventDefinition.LOG.error("could not access Class: '{}'", this.resourceName, e);
} catch (final SecurityException e) {
EventDefinition.LOG.error("could not access Class: '{}'", this.resourceName, e);
} catch (final NoSuchMethodException e) {
EventDefinition.LOG.error("could not find method: '{}' in class '{}'",
new Object[] { this.methodName, this.resourceName, e });
}
} | java | {
"resource": ""
} |
q18354 | EventDefinition.execute | train | @Override
public Return execute(final Parameter _parameter)
throws EFapsException
{
Return ret = null;
_parameter.put(ParameterValues.PROPERTIES, new HashMap<>(super.evalProperties()));
try {
EventDefinition.LOG.debug("Invoking method '{}' for Resource '{}'", this.methodName, this.resourceName);
final Class<?> cls = Class.forName(this.resourceName, true, EFapsClassLoader.getInstance());
final Method method = cls.getMethod(this.methodName, new Class[] { Parameter.class });
ret = (Return) method.invoke(cls.newInstance(), _parameter);
EventDefinition.LOG.debug("Terminated invokation of method '{}' for Resource '{}'",
this.methodName, this.resourceName);
} catch (final SecurityException e) {
EventDefinition.LOG.error("security wrong: '{}'", this.resourceName, e);
} catch (final IllegalArgumentException e) {
EventDefinition.LOG.error("arguments invalid : '{}'- '{}'", this.resourceName, this.methodName, e);
} catch (final IllegalAccessException e) {
EventDefinition.LOG.error("could not access class: '{}'", this.resourceName, e);
} catch (final InvocationTargetException e) {
EventDefinition.LOG.error("could not invoke method: '{}' in class: '{}'", this.methodName,
this.resourceName, e);
throw (EFapsException) e.getCause();
} catch (final ClassNotFoundException e) {
EventDefinition.LOG.error("class not found: '{}" + this.resourceName, e);
} catch (final NoSuchMethodException e) {
EventDefinition.LOG.error("could not find method: '{}' in class '{}'",
new Object[] { this.methodName, this.resourceName, e });
} catch (final InstantiationException e) {
EventDefinition.LOG.error("could not instantiat Class: '{}'", this.resourceName, e);
}
return ret;
} | java | {
"resource": ""
} |
q18355 | Instance.getOid | train | public String getOid()
{
String ret = null;
if (isValid()) {
ret = getType().getId() + "." + getId();
}
return ret;
} | java | {
"resource": ""
} |
q18356 | MissingEventsTracker.checkEventId | train | public boolean checkEventId(String conversationId, long conversationEventId, MissingEventsListener missingEventsListener) {
if (!idsPerConversation.containsKey(conversationId)) {
TreeSet<Long> ids = new TreeSet<>();
boolean added = ids.add(conversationEventId);
idsPerConversation.put(conversationId, ids);
return !added;
} else {
TreeSet<Long> ids = idsPerConversation.get(conversationId);
long last = ids.last();
boolean added = ids.add(conversationEventId);
if (last < conversationEventId - 1) {
missingEventsListener.missingEvents(conversationId, last + 1, (int) (conversationEventId - last));
}
while (ids.size() > 10) {
ids.pollFirst();
}
return !added;
}
} | java | {
"resource": ""
} |
q18357 | Bad.of | train | public static <G, B> Bad<G, B> of(B value) {
return new Bad<>(value);
} | java | {
"resource": ""
} |
q18358 | LRSigner.sign | train | public LREnvelope sign(LREnvelope envelope) throws LRException
{
// Bencode the document
String bencodedMessage = bencode(envelope.getSignableData());
// Clear sign the bencoded document
String clearSignedMessage = signEnvelopeData(bencodedMessage);
envelope.addSigningData(signingMethod, publicKeyLocation, clearSignedMessage);
return envelope;
} | java | {
"resource": ""
} |
q18359 | LRSigner.normalizeList | train | private List<Object> normalizeList(List<Object> list) {
List<Object> result = new ArrayList<Object>();
for (Object o : list) {
if (o == null) {
result.add(nullLiteral);
} else if (o instanceof Boolean) {
result.add(((Boolean) o).toString());
} else if (o instanceof List<?>) {
result.add(normalizeList((List<Object>) o));
} else if (o instanceof Map<?, ?>) {
result.add(normalizeMap((Map<String, Object>) o));
} else if (!(o instanceof Number)) {
result.add(o);
}
}
return result;
} | java | {
"resource": ""
} |
q18360 | LRSigner.signEnvelopeData | train | private String signEnvelopeData(String message) throws LRException
{
// Throw an exception if any of the required fields are null
if (passPhrase == null || publicKeyLocation == null || privateKey == null)
{
throw new LRException(LRException.NULL_FIELD);
}
// Get an InputStream for the private key
InputStream privateKeyStream = getPrivateKeyStream(privateKey);
// Get an OutputStream for the result
ByteArrayOutputStream result = new ByteArrayOutputStream();
ArmoredOutputStream aOut = new ArmoredOutputStream(result);
// Get the pass phrase
char[] privateKeyPassword = passPhrase.toCharArray();
try
{
// Get the private key from the InputStream
PGPSecretKey sk = readSecretKey(privateKeyStream);
PGPPrivateKey pk = sk.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(privateKeyPassword));
PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(sk.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC"));
PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
// Clear sign the message
java.util.Iterator it = sk.getPublicKey().getUserIDs();
if (it.hasNext()) {
spGen.setSignerUserID(false, (String) it.next());
sGen.setHashedSubpackets(spGen.generate());
}
aOut.beginClearText(PGPUtil.SHA256);
sGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, pk);
byte[] msg = message.getBytes();
sGen.update(msg,0,msg.length);
aOut.write(msg,0,msg.length);
BCPGOutputStream bOut = new BCPGOutputStream(aOut);
aOut.endClearText();
sGen.generate().encode(bOut);
aOut.close();
String strResult = result.toString("utf8");
// for whatever reason, bouncycastle is failing to put a linebreak before "-----BEGIN PGP SIGNATURE"
strResult = strResult.replaceAll("([a-z0-9])-----BEGIN PGP SIGNATURE-----", "$1\n-----BEGIN PGP SIGNATURE-----");
return strResult;
}
catch (Exception e)
{
throw new LRException(LRException.SIGNING_FAILED);
}
finally
{
try
{
if (privateKeyStream != null) {
privateKeyStream.close();
}
result.close();
}
catch (IOException e)
{
//Could not close the streams
}
}
} | java | {
"resource": ""
} |
q18361 | LRSigner.readSecretKey | train | private PGPSecretKey readSecretKey(InputStream input) throws LRException
{
PGPSecretKeyRingCollection pgpSec;
try
{
pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input));
}
catch (Exception e)
{
throw new LRException(LRException.NO_KEY);
}
java.util.Iterator keyRingIter = pgpSec.getKeyRings();
while (keyRingIter.hasNext()) {
PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next();
java.util.Iterator keyIter = keyRing.getSecretKeys();
while (keyIter.hasNext()) {
PGPSecretKey key = (PGPSecretKey) keyIter.next();
if (key.isSigningKey()) {
return key;
}
}
}
throw new LRException(LRException.NO_KEY);
} | java | {
"resource": ""
} |
q18362 | LRSigner.getPrivateKeyStream | train | private InputStream getPrivateKeyStream(String privateKey) throws LRException
{
try
{
// If the private key matches the form of a private key string, treat it as such
if (privateKey.matches(pgpRegex))
{
return new ByteArrayInputStream(privateKey.getBytes());
}
// Otherwise, treat it as a file location on the local disk
else
{
return new FileInputStream(new File(privateKey));
}
}
catch (IOException e)
{
throw new LRException(LRException.NO_KEY_STREAM);
}
} | java | {
"resource": ""
} |
q18363 | ReadableInput.include | train | @Override
public void include(Readable in, String source) throws IOException
{
if (cursor != end)
{
release();
}
if (includeStack == null)
{
includeStack = new ArrayDeque<>();
}
includeStack.push(includeLevel);
includeLevel = new IncludeLevel(in, source);
} | java | {
"resource": ""
} |
q18364 | IndexDefinition.getChildTypes | train | private static Set<Type> getChildTypes(final Type _type)
throws CacheReloadException
{
final Set<Type> ret = new HashSet<Type>();
ret.add(_type);
for (final Type child : _type.getChildTypes()) {
ret.addAll(getChildTypes(child));
}
return ret;
} | java | {
"resource": ""
} |
q18365 | SQLWhere.addCriteria | train | public Criteria addCriteria(final int _idx, final List<String> _sqlColNames, final Comparison _comparison,
final Set<String> _values, final boolean _escape, final Connection _connection)
{
final Criteria criteria = new Criteria()
.tableIndex(_idx)
.colNames(_sqlColNames)
.comparison(_comparison)
.values(_values)
.escape(_escape)
.connection(_connection);
sections.add(criteria);
return criteria;
} | java | {
"resource": ""
} |
q18366 | SQLWhere.appendSQL | train | protected void appendSQL(final String _tablePrefix,
final StringBuilder _cmd)
{
if (sections.size() > 0) {
if (isStarted()) {
new SQLSelectPart(SQLPart.AND).appendSQL(_cmd);
new SQLSelectPart(SQLPart.SPACE).appendSQL(_cmd);
} else {
new SQLSelectPart(SQLPart.WHERE).appendSQL(_cmd);
new SQLSelectPart(SQLPart.SPACE).appendSQL(_cmd);
}
addSectionsSQL(_tablePrefix, _cmd, sections);
}
} | java | {
"resource": ""
} |
q18367 | Configs.getInetAddress | train | public static InetAddress getInetAddress(Config config, String path) {
try {
return InetAddress.getByName(config.getString(path));
} catch (UnknownHostException e) {
throw badValue(e, config, path);
}
} | java | {
"resource": ""
} |
q18368 | Configs.getNetworkInterface | train | public static NetworkInterface getNetworkInterface(Config config, String path) {
NetworkInterface value = getNetworkInterfaceByName(config, path);
if (value == null)
value = getNetworkInterfaceByInetAddress(config, path);
if (value == null)
throw badValue("No network interface for value '" + config.getString(path) + "'", config, path);
return value;
} | java | {
"resource": ""
} |
q18369 | Configs.getPort | train | public static int getPort(Config config, String path) {
try {
return new InetSocketAddress(config.getInt(path)).getPort();
} catch (IllegalArgumentException e) {
throw badValue(e, config, path);
}
} | java | {
"resource": ""
} |
q18370 | ModelAdapter.adaptEvents | train | public List<ChatMessageStatus> adaptEvents(List<DbOrphanedEvent> dbOrphanedEvents) {
List<ChatMessageStatus> statuses = new ArrayList<>();
Parser parser = new Parser();
for (DbOrphanedEvent event : dbOrphanedEvents) {
OrphanedEvent orphanedEvent = parser.parse(event.event(), OrphanedEvent.class);
statuses.add(ChatMessageStatus.builder().populate(orphanedEvent.getConversationId(), orphanedEvent.getMessageId(), orphanedEvent.getProfileId(),
orphanedEvent.isEventTypeRead() ? LocalMessageStatus.read : LocalMessageStatus.delivered,
DateHelper.getUTCMilliseconds(orphanedEvent.getTimestamp()), (long) orphanedEvent.getConversationEventId()).build());
}
return statuses;
} | java | {
"resource": ""
} |
q18371 | ModelAdapter.adaptMessages | train | public List<ChatMessage> adaptMessages(List<MessageReceived> messagesReceived) {
List<ChatMessage> chatMessages = new ArrayList<>();
if (messagesReceived != null) {
for (MessageReceived msg : messagesReceived) {
ChatMessage adaptedMessage = ChatMessage.builder().populate(msg).build();
List<ChatMessageStatus> adaptedStatuses = adaptStatuses(msg.getConversationId(), msg.getMessageId(), msg.getStatusUpdate());
for (ChatMessageStatus s : adaptedStatuses) {
adaptedMessage.addStatusUpdate(s);
}
chatMessages.add(adaptedMessage);
}
}
return chatMessages;
} | java | {
"resource": ""
} |
q18372 | ModelAdapter.adaptStatuses | train | public List<ChatMessageStatus> adaptStatuses(String conversationId, String messageId, Map<String, MessageReceived.Status> statuses) {
List<ChatMessageStatus> adapted = new ArrayList<>();
for (String key : statuses.keySet()) {
MessageReceived.Status status = statuses.get(key);
adapted.add(ChatMessageStatus.builder().populate(conversationId, messageId, key, status.getStatus().compareTo(MessageStatus.delivered) == 0 ? LocalMessageStatus.delivered : LocalMessageStatus.read, DateHelper.getUTCMilliseconds(status.getTimestamp()), null).build());
}
return adapted;
} | java | {
"resource": ""
} |
q18373 | ModelAdapter.adapt | train | public List<ChatParticipant> adapt(List<Participant> participants) {
List<ChatParticipant> result = new ArrayList<>();
if (participants != null && !participants.isEmpty()) {
for (Participant p : participants) {
result.add(ChatParticipant.builder().populate(p).build());
}
}
return result;
} | java | {
"resource": ""
} |
q18374 | RGBColor.setColor | train | private final void setColor(ColorSet colorSet) {
int[] rgb = ColorSet.getRGB(colorSet);
this.red = rgb[0] / 255.0;
this.green = rgb[1] / 255.0;
this.blue = rgb[2] / 255.0;
} | java | {
"resource": ""
} |
q18375 | Quartz.shutDown | train | public static void shutDown()
{
if (Quartz.QUARTZ != null && Quartz.QUARTZ.scheduler != null) {
try {
Quartz.QUARTZ.scheduler.shutdown();
} catch (final SchedulerException e) {
Quartz.LOG.error("Problems on shutdown of QuartsSheduler", e);
}
}
} | java | {
"resource": ""
} |
q18376 | GenClassCompiler.compile | train | public static GenClassCompiler compile(TypeElement superClass, ProcessingEnvironment env) throws IOException
{
GenClassCompiler compiler;
GrammarDef grammarDef = superClass.getAnnotation(GrammarDef.class);
if (grammarDef != null)
{
compiler = new ParserCompiler(superClass);
}
else
{
DFAMap mapDef = superClass.getAnnotation(DFAMap.class);
if (mapDef != null)
{
compiler = new MapCompiler(superClass);
}
else
{
compiler = new GenClassCompiler(superClass);
}
}
compiler.setProcessingEnvironment(env);
compiler.compile();
if (env == null)
{
System.err.println("warning! classes directory not set");
}
else
{
compiler.saveClass();
}
return compiler;
} | java | {
"resource": ""
} |
q18377 | RestClient.refreshAuthToken | train | private synchronized boolean refreshAuthToken(final AuthHandler handler,
final boolean forceRefresh) {
if (handler == null) {
return false;
}
AuthToken token = authToken.get();
if (!forceRefresh && token != null && token.isValid()) {
logger.fine("Auth token is already valid");
return true;
}
try {
handler.setForceRefresh(forceRefresh);
token = handler.call();
authToken.set(token);
if (token != null) {
if (token instanceof UserBearerAuthToken) {
final UserBearerAuthToken bt = (UserBearerAuthToken) token;
logger.info("Acquired auth token. Expires: "
+ bt.getExpires() + " token="
+ bt.getToken());
} else if (token instanceof ProjectBearerAuthToken) {
ProjectBearerAuthToken pt = (ProjectBearerAuthToken) token;
logger.info("Acquired proj token. Expires: " + pt.getExpires() + " token="
+ pt.getToken());
} else {
logger.info("Acquired auth token. Token valid="
+ token.isValid());
}
}
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
if (cause != null) {
logger.warning("Authentication failed: " + cause.getMessage());
} else {
logger.warning("Authentication failed: " + e.getMessage());
}
} catch (Exception e) {
logger.warning("Authentication failed: " + e.getMessage());
} finally {
handler.setForceRefresh(false);
}
return true;
} | java | {
"resource": ""
} |
q18378 | PropertyDescriptorLocator.getPropertyDescriptor | train | public PropertyDescriptor getPropertyDescriptor(String propertyName)
{
final PropertyDescriptor propertyDescriptor = findPropertyDescriptor(propertyName);
if (propertyDescriptor == null) {
throw new PropertyNotFoundException(beanClass, propertyName);
}
return propertyDescriptor;
} | java | {
"resource": ""
} |
q18379 | PropertyDescriptorLocator.findPropertyDescriptor | train | public PropertyDescriptor findPropertyDescriptor(String propertyName) {
for (PropertyDescriptor property : propertyDescriptors) {
if (property.getName().equals(propertyName)) {
return property;
}
}
return null;
} | java | {
"resource": ""
} |
q18380 | Classification.isAssigendTo | train | public boolean isAssigendTo(final Company _company)
throws CacheReloadException
{
final boolean ret;
if (isRoot()) {
ret = this.companies.isEmpty() ? true : this.companies.contains(_company);
} else {
ret = getParentClassification().isAssigendTo(_company);
}
return ret;
} | java | {
"resource": ""
} |
q18381 | ParserCompiler.overrideAbstractMethods | train | private void overrideAbstractMethods() throws IOException
{
for (final ExecutableElement method : El.getEffectiveMethods(superClass))
{
if (method.getModifiers().contains(Modifier.ABSTRACT))
{
if (
method.getAnnotation(Terminal.class) != null ||
method.getAnnotation(Rule.class) != null ||
method.getAnnotation(Rules.class) != null )
{
implementedAbstractMethods.add(method);
MethodCompiler mc = new MethodCompiler()
{
@Override
protected void implement() throws IOException
{
TypeMirror returnType = method.getReturnType();
List<? extends VariableElement> params = method.getParameters();
if (returnType.getKind() != TypeKind.VOID && params.size() == 1)
{
nameArgument(ARG, 1);
try
{
convert(ARG, returnType);
}
catch (IllegalConversionException ex)
{
throw new IOException("bad conversion with "+method, ex);
}
treturn();
}
else
{
if (returnType.getKind() == TypeKind.VOID && params.size() == 0)
{
treturn();
}
else
{
throw new IllegalArgumentException("cannot implement abstract method "+method);
}
}
}
};
subClass.overrideMethod(mc, method, Modifier.PROTECTED);
}
}
}
} | java | {
"resource": ""
} |
q18382 | InfinispanCache.init | train | private void init()
{
this.container = InfinispanCache.findCacheContainer();
if (this.container == null) {
try {
this.container = new DefaultCacheManager(this.getClass().getResourceAsStream(
"/org/efaps/util/cache/infinispan-config.xml"));
if (this.container instanceof EmbeddedCacheManager) {
this.container.addListener(new CacheLogListener(InfinispanCache.LOG));
}
InfinispanCache.bindCacheContainer(this.container);
final Cache<String, Integer> cache = this.container
.<String, Integer>getCache(InfinispanCache.COUNTERCACHE);
cache.put(InfinispanCache.COUNTERCACHE, 1);
} catch (final FactoryConfigurationError e) {
InfinispanCache.LOG.error("FactoryConfigurationError", e);
} catch (final IOException e) {
InfinispanCache.LOG.error("IOException", e);
}
} else {
final Cache<String, Integer> cache = this.container
.<String, Integer>getCache(InfinispanCache.COUNTERCACHE);
Integer count = cache.get(InfinispanCache.COUNTERCACHE);
if (count == null) {
count = 1;
} else {
count = count + 1;
}
cache.put(InfinispanCache.COUNTERCACHE, count);
}
} | java | {
"resource": ""
} |
q18383 | InfinispanCache.terminate | train | private void terminate()
{
if (this.container != null) {
final Cache<String, Integer> cache = this.container
.<String, Integer>getCache(InfinispanCache.COUNTERCACHE);
Integer count = cache.get(InfinispanCache.COUNTERCACHE);
if (count == null || count < 2) {
this.container.stop();
} else {
count = count - 1;
cache.put(InfinispanCache.COUNTERCACHE, count);
}
}
} | java | {
"resource": ""
} |
q18384 | InfinispanCache.getIgnReCache | train | public <K, V> AdvancedCache<K, V> getIgnReCache(final String _cacheName)
{
return this.container.<K, V>getCache(_cacheName, true).getAdvancedCache()
.withFlags(Flag.IGNORE_RETURN_VALUES, Flag.SKIP_REMOTE_LOOKUP, Flag.SKIP_CACHE_LOAD);
} | java | {
"resource": ""
} |
q18385 | InfinispanCache.initCache | train | public <K, V> Cache<K, V> initCache(final String _cacheName)
{
if (!exists(_cacheName)
&& ((EmbeddedCacheManager) getContainer()).getCacheConfiguration(_cacheName) == null) {
((EmbeddedCacheManager) getContainer()).defineConfiguration(_cacheName, "eFaps-Default",
new ConfigurationBuilder().build());
}
return this.container.getCache(_cacheName, true);
} | java | {
"resource": ""
} |
q18386 | Index.getFacetsConfig | train | public static FacetsConfig getFacetsConfig()
{
final FacetsConfig ret = new FacetsConfig();
ret.setHierarchical(Indexer.Dimension.DIMCREATED.name(), true);
return ret;
} | java | {
"resource": ""
} |
q18387 | Index.getAnalyzer | train | public static Analyzer getAnalyzer()
throws EFapsException
{
IAnalyzerProvider provider = null;
if (EFapsSystemConfiguration.get().containsAttributeValue(KernelSettings.INDEXANALYZERPROVCLASS)) {
final String clazzname = EFapsSystemConfiguration.get().getAttributeValue(
KernelSettings.INDEXANALYZERPROVCLASS);
try {
final Class<?> clazz = Class.forName(clazzname, false, EFapsClassLoader.getInstance());
provider = (IAnalyzerProvider) clazz.newInstance();
} catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new EFapsException(Index.class, "Could not instanciate IAnalyzerProvider", e);
}
} else {
provider = new IAnalyzerProvider()
{
@Override
public Analyzer getAnalyzer()
{
return new StandardAnalyzer(SpanishAnalyzer.getDefaultStopSet());
}
};
}
return provider.getAnalyzer();
} | java | {
"resource": ""
} |
q18388 | ApplicationVersion.addScript | train | @CallMethod(pattern = "install/version/script")
public void addScript(@CallParam(pattern = "install/version/script") final String _code,
@CallParam(pattern = "install/version/script", attributeName = "type") final String _type,
@CallParam(pattern = "install/version/script", attributeName = "name") final String _name,
@CallParam(pattern = "install/version/script", attributeName = "function")
final String _function)
{
AbstractScript script = null;
if ("rhino".equalsIgnoreCase(_type)) {
script = new RhinoScript(_code, _name, _function);
} else if ("groovy".equalsIgnoreCase(_type)) {
script = new GroovyScript(_code, _name, _function);
}
if (script != null) {
this.scripts.add(script);
}
} | java | {
"resource": ""
} |
q18389 | ApplicationVersion.appendDescription | train | @CallMethod(pattern = "install/version/description")
public void appendDescription(@CallParam(pattern = "install/version/description") final String _desc)
{
if (_desc != null) {
this.description.append(_desc.trim()).append("\n");
}
} | java | {
"resource": ""
} |
q18390 | ApplicationVersion.addIgnoredStep | train | @CallMethod(pattern = "install/version/lifecyle/ignore")
public void addIgnoredStep(@CallParam(pattern = "install/version/lifecyle/ignore", attributeName = "step")
final String _step)
{
this.ignoredSteps.add(UpdateLifecycle.valueOf(_step.toUpperCase()));
} | java | {
"resource": ""
} |
q18391 | ConnectionResource.freeResource | train | @Override
protected void freeResource()
throws EFapsException
{
try {
if (!getConnection().isClosed()) {
getConnection().close();
}
} catch (final SQLException e) {
throw new EFapsException("Could not close", e);
}
} | java | {
"resource": ""
} |
q18392 | CacheConfiguration.newMutable | train | public static <K, V> Configuration newMutable(TimeUnit expiryTimeUnit, long expiryDurationAmount) {
return new MutableConfiguration<K, V>().setExpiryPolicyFactory(factoryOf(new Duration(expiryTimeUnit, expiryDurationAmount)));
} | java | {
"resource": ""
} |
q18393 | Evaluator.next | train | public boolean next()
throws EFapsException
{
initialize(false);
boolean stepForward = true;
boolean ret = true;
while (stepForward && ret) {
ret = step(this.selection.getAllSelects());
stepForward = !this.access.hasAccess(inst());
}
return ret;
} | java | {
"resource": ""
} |
q18394 | Evaluator.step | train | private boolean step(final Collection<Select> _selects)
{
boolean ret = !CollectionUtils.isEmpty(_selects);
for (final Select select : _selects) {
ret = ret && select.next();
}
return ret;
} | java | {
"resource": ""
} |
q18395 | Evaluator.evalAccess | train | private void evalAccess()
throws EFapsException
{
final List<Instance> instances = new ArrayList<>();
while (step(this.selection.getInstSelects().values())) {
for (final Entry<String, Select> entry : this.selection.getInstSelects().entrySet()) {
final Object object = entry.getValue().getCurrent();
if (object != null) {
if (object instanceof List) {
((List<?>) object).stream()
.filter(Objects::nonNull)
.forEach(e -> instances.add((Instance) e));
} else {
instances.add((Instance) object);
}
}
}
}
for (final Entry<String, Select> entry : this.selection.getInstSelects().entrySet()) {
entry.getValue().reset();
}
this.access = Access.get(AccessTypeEnums.READ.getAccessType(), instances);
} | java | {
"resource": ""
} |
q18396 | Evaluator.getDataList | train | public DataList getDataList()
throws EFapsException
{
final DataList ret = new DataList();
while (next()) {
final ObjectData data = new ObjectData();
int idx = 1;
for (final Select select : this.selection.getSelects()) {
final String key = select.getAlias() == null ? String.valueOf(idx) : select.getAlias();
data.getValues().add(JSONData.getValue(key, get(select)));
idx++;
}
ret.add(data);
}
return ret;
} | java | {
"resource": ""
} |
q18397 | EFapsException.makeInfo | train | protected String makeInfo()
{
final StringBuilder str = new StringBuilder();
if (this.className != null) {
str.append("Thrown within class ").append(this.className.getName()).append('\n');
}
if (this.id != null) {
str.append("Id of Exception is ").append(this.id).append('\n');
}
if (this.args != null && this.args.length > 0) {
str.append("Arguments are:\n");
for (Integer index = 0; index < this.args.length; index++) {
final String arg = this.args[index] == null
? "null"
: this.args[index].toString();
str.append("\targs[").append(index.toString()).append("] = '").append(arg).append("'\n");
}
}
return str.toString();
} | java | {
"resource": ""
} |
q18398 | DBProperties.getValueFromDB | train | private static String getValueFromDB(final String _key,
final String _language)
{
String ret = null;
try {
boolean closeContext = false;
if (!Context.isThreadActive()) {
Context.begin();
closeContext = true;
}
final Connection con = Context.getConnection();
final PreparedStatement stmt = con.prepareStatement(DBProperties.SQLSELECT);
stmt.setString(1, _key);
stmt.setString(2, _language);
final ResultSet resultset = stmt.executeQuery();
if (resultset.next()) {
final String defaultValue = resultset.getString(1);
final String value = resultset.getString(2);
if (value != null) {
ret = value.trim();
} else if (defaultValue != null) {
ret = defaultValue.trim();
}
} else {
final PreparedStatement stmt2 = con.prepareStatement(DBProperties.SQLSELECTDEF);
stmt2.setString(1, _key);
final ResultSet resultset2 = stmt2.executeQuery();
if (resultset2.next()) {
final String defaultValue = resultset2.getString(1);
if (defaultValue != null) {
ret = defaultValue.trim();
}
}
resultset2.close();
stmt2.close();
}
resultset.close();
stmt.close();
con.commit();
con.close();
if (closeContext) {
Context.rollback();
}
} catch (final EFapsException e) {
DBProperties.LOG.error("initialiseCache()", e);
} catch (final SQLException e) {
DBProperties.LOG.error("initialiseCache()", e);
}
return ret;
} | java | {
"resource": ""
} |
q18399 | DBProperties.cacheOnStart | train | private static void cacheOnStart()
{
try {
boolean closeContext = false;
if (!Context.isThreadActive()) {
Context.begin();
closeContext = true;
}
Context.getThreadContext();
final Connection con = Context.getConnection();
final PreparedStatement stmtLang = con.prepareStatement(DBProperties.SQLLANG);
final ResultSet rsLang = stmtLang.executeQuery();
final Set<String> languages = new HashSet<>();
while (rsLang.next()) {
languages.add(rsLang.getString(1).trim());
}
rsLang.close();
stmtLang.close();
final Cache<String, String> cache = InfinispanCache.get().<String, String>getCache(
DBProperties.CACHENAME);
final PreparedStatement stmt = con.prepareStatement(DBProperties.SQLSELECTONSTART);
final ResultSet resultset = stmt.executeQuery();
while (resultset.next()) {
final String propKey = resultset.getString(1).trim();
final String defaultValue = resultset.getString(2);
if (defaultValue != null) {
final String value = defaultValue.trim();
for (final String lang : languages) {
final String cachKey = lang + ":" + propKey;
if (!cache.containsKey(cachKey)) {
cache.put(cachKey, value);
}
}
}
final String value = resultset.getString(3);
final String lang = resultset.getString(4);
if (value != null) {
final String cachKey = lang.trim() + ":" + propKey;
cache.put(cachKey, value.trim());
}
}
resultset.close();
stmt.close();
con.commit();
con.close();
if (closeContext) {
Context.rollback();
}
} catch (final EFapsException e) {
DBProperties.LOG.error("initialiseCache()", e);
} catch (final SQLException e) {
DBProperties.LOG.error("initialiseCache()", e);
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.