_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q13000
clusterinstance_stats.get
train
public static clusterinstance_stats[] get(nitro_service service) throws Exception{ clusterinstance_stats obj = new clusterinstance_stats(); clusterinstance_stats[] response = (clusterinstance_stats[])obj.stat_resources(service); return response; }
java
{ "resource": "" }
q13001
clusterinstance_stats.get
train
public static clusterinstance_stats get(nitro_service service, Long clid) throws Exception{ clusterinstance_stats obj = new clusterinstance_stats(); obj.set_clid(clid); clusterinstance_stats response = (clusterinstance_stats) obj.stat_resource(service); return response; }
java
{ "resource": "" }
q13002
Arguments.set
train
public Arguments set(final int index, final Fixed f) { this.argumentRefs.add(f); this.pointer.get(index) .setF(f.getRaw()); return this; }
java
{ "resource": "" }
q13003
ObjectCache.store
train
public static void store(final long pointer, final Object object) { final Object oldValue = MAPPED_OBJECTS.put(pointer, object); if (oldValue != null) { //put it back! MAPPED_OBJECTS.put(pointer, oldValue); throw new IllegalStateException(String.format("Can not re-map existing pointer.\n" + "Pointer=%s\n" + "old value=%s" + "\nnew value=%s", pointer, oldValue, object)); } }
java
{ "resource": "" }
q13004
AbstractParserFactory.mapParserNamespaces
train
public static Optional<Map<QName, XMLElementReader<List<ModelNode>>>> mapParserNamespaces(AbstractParserFactory factory) { Map<QName, XMLElementReader<List<ModelNode>>> result = factory.create().entrySet() .stream() .collect(Collectors.toMap( e -> new QName(e.getKey().getNamespaceURI(), SUBSYSTEM), e -> e.getValue() )); return Optional.of(result); }
java
{ "resource": "" }
q13005
Client.getObject
train
public Resource<?> getObject(final int id) { return ObjectCache.from(WaylandServerCore.INSTANCE() .wl_client_get_object(this.pointer, id)); }
java
{ "resource": "" }
q13006
SimpleSectionAdapter.getIndexForPosition
train
public int getIndexForPosition(int position) { int nSections = 0; Set<Entry<String, Integer>> entrySet = mSections.entrySet(); for(Entry<String, Integer> entry : entrySet) { if(entry.getValue() < position) { nSections++; } } return position - nSections; }
java
{ "resource": "" }
q13007
LogInvocationProcessor.init
train
@Override public void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); trees = Trees.instance(processingEnv); messager = processingEnv.getMessager(); types = processingEnv.getTypeUtils(); elements = processingEnv.getElementUtils(); try { logInvocationScanner = new LogInvocationScanner( processingEnv ); } catch (IOException e) { messager.printMessage( Diagnostic.Kind.ERROR, "IOException caught" ); initFailed = true; } catch (PackageNameException e) { messager.printMessage( Diagnostic.Kind.ERROR, "generatedEventsPackage compiler argument is not valid, either it contains java keyword or subpackage or class name starts with number" ); initFailed = true; } final String schemasRoot = processingEnv.getOptions().get("schemasRoot"); if (schemasRoot != null) { try { new URI(schemasRoot); //check that schemasRoot is valid path } catch (URISyntaxException e) { initFailed = true; messager.printMessage( Diagnostic.Kind.ERROR, format("Provided schemasRoot compiler argument value [%s] is not valid path", schemasRoot) ); } // Used for generating json schemas by {@link SchemaGenerator} SchemaGenerator schemaGenerator = new SchemaGenerator(generatedClassesInfo, schemasRoot); JavacTask.instance(processingEnv).addTaskListener(schemaGenerator); } else { messager.printMessage( Diagnostic.Kind.MANDATORY_WARNING, "schemasRoot compiler argument is not set, no schemas will be created" ); } }
java
{ "resource": "" }
q13008
Proxy.marshalConstructor
train
private <J, T extends Proxy<J>> T marshalConstructor(final int opcode, final J implementation, final int version, final Class<T> newProxyCls, final long argsPointer) { try { final long wlProxy = WaylandClientCore.INSTANCE() .wl_proxy_marshal_array_constructor(this.pointer, opcode, argsPointer, InterfaceMeta.get(newProxyCls).pointer.address); return marshalProxy(wlProxy, implementation, version, newProxyCls); } catch (final NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new RuntimeException("Uh oh, this is a bug!", e); } }
java
{ "resource": "" }
q13009
Proxy.destroy
train
public void destroy() { WaylandClientCore.INSTANCE() .wl_proxy_destroy(this.pointer); ObjectCache.remove(this.pointer); this.jObjectPointer.close(); }
java
{ "resource": "" }
q13010
ContainerOnlySwarm.main
train
public static void main(String... args) throws Exception { if (System.getProperty("boot.module.loader") == null) { System.setProperty("boot.module.loader", "org.wildfly.swarm.bootstrap.modules.BootModuleLoader"); } Module bootstrap = Module.getBootModuleLoader().loadModule(ModuleIdentifier.create("swarm.application")); ServiceLoader<ContainerFactory> factory = bootstrap.loadService(ContainerFactory.class); Iterator<ContainerFactory> factoryIter = factory.iterator(); if (!factoryIter.hasNext()) { simpleMain(args); } else { factoryMain(factoryIter.next(), args); } }
java
{ "resource": "" }
q13011
InstantAdapterCore.bindToView
train
public final void bindToView(final ViewGroup parent, final View view, final T instance, final int position) { SparseArray<Holder> holders = (SparseArray<Holder>) view.getTag(mLayoutResourceId); updateAnnotatedViews(holders, view, instance, position); executeViewHandlers(holders, parent, view, instance, position); }
java
{ "resource": "" }
q13012
InstantAdapterCore.createNewView
train
public final View createNewView(final Context context, final ViewGroup parent) { View view = mLayoutInflater.inflate(mLayoutResourceId, parent, false); SparseArray<Holder> holders = new SparseArray<Holder>(); int size = mViewIdsAndMetaCache.size(); for (int i = 0; i < size; i++) { int viewId = mViewIdsAndMetaCache.keyAt(i); Meta meta = mViewIdsAndMetaCache.get(viewId); View viewFromLayout = view.findViewById(viewId); if (viewFromLayout == null) { String message = String.format("Cannot find View, check the 'viewId' " + "attribute on method %s.%s()", mDataType.getName(), meta.method.getName()); throw new IllegalStateException(message); } holders.append(viewId, new Holder(viewFromLayout, meta)); mAnnotatedViewIds.add(viewId); } view.setTag(mLayoutResourceId, holders); return view; }
java
{ "resource": "" }
q13013
RuntimeServer.visitFractions
train
private <T> void visitFractions(Container container, T context, FractionProcessor<T> fn) { OUTER: for (ServerConfiguration eachConfig : this.configList) { boolean found = false; INNER: for (Fraction eachFraction : container.fractions()) { if (eachConfig.getType().isAssignableFrom(eachFraction.getClass())) { found = true; fn.accept(context, eachConfig, eachFraction); break INNER; } } if (!found && !eachConfig.isIgnorable()) { System.err.println("*** unable to find fraction for: " + eachConfig.getType()); } } }
java
{ "resource": "" }
q13014
LogInvocationScanner.handle
train
private void handle(final JCTree.JCFieldAccess fieldAccess, final Stack<MethodAndParameter> stack, final MethodInvocationTree node, final StatementInfo statementInfo, final ScannerParams scannerParams) { if (fieldAccess.getExpression().getKind().equals( Tree.Kind.MEMBER_SELECT)) { //to handle when structlogger field is referenced through this.field and ClassName.field final MemberSelectTree expression = (MemberSelectTree) fieldAccess.getExpression(); final Name name = expression.getIdentifier(); if (scannerParams.getFields().containsKey(name)) { handleStructLogExpression(stack, node, name, statementInfo, scannerParams); } } else if (fieldAccess.getExpression().getKind().equals( Tree.Kind.IDENTIFIER)) { // to handle when structlogger field is referenced directly final JCTree.JCIdent ident = (JCTree.JCIdent) fieldAccess.getExpression(); final Name name = ident.getName(); if (scannerParams.getFields().containsKey(name)) { handleStructLogExpression(stack, node, name, statementInfo, scannerParams); } } }
java
{ "resource": "" }
q13015
LogInvocationScanner.formatWithStatementLocation
train
private String formatWithStatementLocation(String format, StatementInfo statementInfo, Object... args) { return format(format, args) + format(" [%s:%s]", statementInfo.getSourceFileName(), statementInfo.getLineNumber()); }
java
{ "resource": "" }
q13016
LogInvocationScanner.addVariablesToBuffer
train
private void addVariablesToBuffer(final java.util.List<VariableAndValue> usedVariables, final ListBuffer listBuffer) { for (VariableAndValue variableAndValue : usedVariables) { listBuffer.add(variableAndValue.getValue()); } }
java
{ "resource": "" }
q13017
CommandParser.toArgs
train
public Command[] toArgs(final String line) { if (line == null || line.isEmpty()) { throw new IllegalArgumentException("Empty command."); } final List<Command> commands = new ArrayList<>(); final List<String> result = new ArrayList<>(); final StringBuilder current = new StringBuilder(); char waitChar = ' '; boolean copyNextChar = false; boolean inEscaped = false; for (final char c : line.toCharArray()) { if (copyNextChar) { current.append(c); copyNextChar = false; } else if (waitChar == c) { if (current.length() > 0) { result.add(current.toString()); current.setLength(0); } waitChar = ' '; inEscaped = false; } else { switch (c) { case '"': case '\'': if (!inEscaped) { waitChar = c; inEscaped = true; break; } else { current.append(c); } break; case '\\': copyNextChar = true; break; case '|': flush(commands, result, current); break; default: current.append(c); } } } if (waitChar != ' ') { throw new IllegalStateException("Missing closing " + Character.toString(waitChar)); } flush(commands, result, current); return commands.toArray(new Command[commands.size()]); }
java
{ "resource": "" }
q13018
LoggingFraction.createDefaultLoggingFraction
train
public static LoggingFraction createDefaultLoggingFraction(Level level) { return new LoggingFraction() .defaultColorFormatter() .consoleHandler(level, COLOR_PATTERN) .rootLogger(level, CONSOLE); }
java
{ "resource": "" }
q13019
LoggingFraction.formatter
train
public LoggingFraction formatter(String name, String pattern) { patternFormatter(new PatternFormatter(name).pattern(pattern)); return this; }
java
{ "resource": "" }
q13020
LoggingFraction.consoleHandler
train
public LoggingFraction consoleHandler(Level level, String formatter) { consoleHandler(new ConsoleHandler(CONSOLE) .level(level) .namedFormatter(formatter)); return this; }
java
{ "resource": "" }
q13021
LoggingFraction.fileHandler
train
public LoggingFraction fileHandler(String name, String path, Level level, String formatter) { Map<Object, Object> fileProperties = new HashMap<>(); fileProperties.put("path", path); fileProperties.put("relative-to", "jboss.server.log.dir"); fileHandler(new FileHandler(name) .level(level) .formatter(formatter) .file(fileProperties)); return this; }
java
{ "resource": "" }
q13022
LoggingFraction.customHandler
train
public LoggingFraction customHandler(String name, String module, String className, Properties properties, String formatter) { Map<Object, Object> handlerProperties = new HashMap<>(); final Enumeration<?> names = properties.propertyNames(); while (names.hasMoreElements()) { final String nextElement = (String) names.nextElement(); handlerProperties.put(nextElement, properties.getProperty(nextElement)); } customHandler(new CustomHandler(name) .module(module) .attributeClass(className) .formatter(formatter) .properties(handlerProperties)); return this; }
java
{ "resource": "" }
q13023
LoggingFraction.rootLogger
train
public LoggingFraction rootLogger(Level level, String... handlers) { rootLogger(new RootLogger().level(level) .handlers(handlers)); return this; }
java
{ "resource": "" }
q13024
MongoDBQueryModelDAO.buildIdCondition
train
private Condition buildIdCondition(Object argument) { if (argument instanceof String && ObjectId.isValid((String) argument)) { return new Condition(ID_FIELD, new ObjectId((String) argument)); } else if (Iterable.class.isAssignableFrom(argument.getClass())) { List<Object> objectIds = new ArrayList<Object>(); //noinspection ConstantConditions for (Object argumentItem : (Iterable) argument) { if (argumentItem instanceof String && ObjectId.isValid((String) argumentItem)) { objectIds.add(new ObjectId((String) argumentItem)); } else if (argumentItem instanceof ObjectId) { objectIds.add( argumentItem); } } return new Condition(ID_FIELD, new BasicDBObject("$in", objectIds)); } else { return new Condition(ID_FIELD, argument); } }
java
{ "resource": "" }
q13025
Slf4jLoggingCallback.audit
train
@Override public void audit(final LoggingEvent e) { try { logger.info(MarkerFactory.getMarker(AUDIT), serialize(e)); } catch (Exception ex) { throw new RuntimeException("unable to serialize event", ex); } }
java
{ "resource": "" }
q13026
CmdMethod.getUsage
train
@Override public String getUsage() { String commandName = name; Class<?> declaringClass = method.getDeclaringClass(); Map<String, Cmd> commands = Commands.get(declaringClass); if (commands.size() == 1 && commands.values().iterator().next() instanceof CmdGroup) { final CmdGroup cmdGroup = (CmdGroup) commands.values().iterator().next(); commandName = cmdGroup.getName() + " " + name; } final String usage = usage(); if (usage != null) { if (!usage.startsWith(commandName)) { return commandName + " " + usage; } else { return usage; } } final List<Object> args = new ArrayList<>(); for (final Param parameter : spec.arguments) { boolean skip = Environment.class.isAssignableFrom(parameter.getType()); for (final Annotation a : parameter.getAnnotations()) { final CrestAnnotation crestAnnotation = a.annotationType().getAnnotation(CrestAnnotation.class); if (crestAnnotation != null) { skip = crestAnnotation.skipUsage(); break; } } if (!skip) { skip = parameter.getAnnotation(NotAService.class) == null && Environment.ENVIRONMENT_THREAD_LOCAL.get().findService(parameter.getType()) != null; } if (skip) { continue; } args.add(parameter.getDisplayType().replace("[]", "...")); } return String.format("%s %s %s", commandName, args.size() == method.getParameterTypes().length ? "" : "[options]", Join.join(" ", args)).trim(); }
java
{ "resource": "" }
q13027
BatchFraction.defaultJobRepository
train
public BatchFraction defaultJobRepository(final String name, final DatasourcesFraction datasource) { jdbcJobRepository(name, datasource); return defaultJobRepository(name); }
java
{ "resource": "" }
q13028
BatchFraction.jdbcJobRepository
train
public BatchFraction jdbcJobRepository(final String name, final DatasourcesFraction datasource) { return jdbcJobRepository(new JDBCJobRepository<>(name).dataSource(datasource.getKey())); }
java
{ "resource": "" }
q13029
BatchFraction.defaultThreadPool
train
public BatchFraction defaultThreadPool(final String name, final int maxThreads, final int keepAliveTime, final TimeUnit keepAliveUnits) { threadPool(name, maxThreads, keepAliveTime, keepAliveUnits); return defaultThreadPool(name); }
java
{ "resource": "" }
q13030
BatchFraction.threadPool
train
public BatchFraction threadPool(final String name, final int maxThreads, final int keepAliveTime, final TimeUnit keepAliveUnits) { final ThreadPool<?> threadPool = new ThreadPool<>(name); threadPool.maxThreads(maxThreads) .keepaliveTime("time", Integer.toBinaryString(keepAliveTime)) .keepaliveTime("unit", keepAliveUnits.name().toLowerCase(Locale.ROOT)); return threadPool(threadPool); }
java
{ "resource": "" }
q13031
Slf4jToFileBenchmark.structLoggerLogging1Call
train
@Warmup(iterations = 5) @Measurement(iterations = 5) @Benchmark public void structLoggerLogging1Call() { structLoggerNoMessageParametrization.info("Event with double and boolean") .varDouble(1.2) .varBoolean(false) .log(); }
java
{ "resource": "" }
q13032
Slf4jToFileBenchmark.logstashStructuredParametrizedMessageLogging1Call
train
@Warmup(iterations = 5) @Measurement(iterations = 5) @Benchmark public void logstashStructuredParametrizedMessageLogging1Call() { loggerLogstashParametrizedMessage.info("Event with double={} and boolean={}", value("varDouble", 1.2), value("varBoolean", false)); }
java
{ "resource": "" }
q13033
Slf4jToFileBenchmark.logstashStructuredLogging1Calls
train
@Warmup(iterations = 5) @Measurement(iterations = 5) @Benchmark public void logstashStructuredLogging1Calls() { loggerLogstash.info("Event with double and boolean", keyValue("varDouble", 1.2), keyValue("varBoolean", false)); }
java
{ "resource": "" }
q13034
POJOService.createPojo
train
public JavaFile createPojo(final String name, final JCTree.JCLiteral literal, final List<VariableAndValue> usedVariables) throws PackageNameException { String eventName; String packageName; if (name != null) { //get event name and package name from qualified name final String[] split = name.split("\\."); eventName = split[split.length-1]; checkStringIsValidName(eventName); final StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < split.length - 1; i++) { if (i != 0) { stringBuffer.append("."); } stringBuffer.append(split[i]); checkStringIsValidName(split[i]); } packageName = stringBuffer.toString(); //check that packageName does not contain java keyword } else { eventName = "Event" + hash(literal.getValue().toString()); packageName = generatedEventsPackage; } final TypeSpec.Builder classBuilder = TypeSpec.classBuilder(eventName) .addModifiers(Modifier.PUBLIC) .superclass(TypeName.get(LoggingEvent.class)); final MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC); addCommonLoggingEventFieldsToConstructor(constructorBuilder); for (VariableAndValue variableAndValue : usedVariables) { addPojoField(classBuilder, constructorBuilder, variableAndValue.getVariable().getName().toString(), TypeName.get(variableAndValue.getVariable().getType())); } final TypeSpec build = classBuilder.addMethod(constructorBuilder.build()).build(); return JavaFile.builder(packageName, build).build(); }
java
{ "resource": "" }
q13035
POJOService.checkStringIsValidName
train
private void checkStringIsValidName(final String s) throws PackageNameException { final boolean packageContainsJavaKeyword = javaKeywords.stream().anyMatch(s::equals); if (packageContainsJavaKeyword || s.matches("\\d.*")) { throw new PackageNameException("string is not valid"); } }
java
{ "resource": "" }
q13036
POJOService.addCommonLoggingEventFieldsToConstructor
train
private void addCommonLoggingEventFieldsToConstructor(final MethodSpec.Builder constructorBuilder) { constructorBuilder.addParameter(TypeName.get(String.class), "message", Modifier.FINAL); constructorBuilder.addParameter(TypeName.get(String.class), "sourceFile", Modifier.FINAL); constructorBuilder.addParameter(TypeName.LONG, "lineNumber", Modifier.FINAL); constructorBuilder.addParameter(TypeName.get(String.class), "type", Modifier.FINAL); constructorBuilder.addParameter(TypeName.LONG, "sid", Modifier.FINAL); constructorBuilder.addParameter(TypeName.get(String.class), "logLevel", Modifier.FINAL); constructorBuilder.addParameter(TypeName.LONG, "timestamp", Modifier.FINAL); constructorBuilder.addCode("super(message,sourceFile,lineNumber,type,sid,logLevel,timestamp);"); }
java
{ "resource": "" }
q13037
POJOService.addPojoField
train
private void addPojoField(final TypeSpec.Builder classBuilder, final MethodSpec.Builder constructorBuilder, final String fieldName, final TypeName fieldClass) { classBuilder.addField(fieldClass, fieldName, Modifier.PRIVATE, Modifier.FINAL); addGetter(classBuilder, fieldName, fieldClass); addConstructorParameter(constructorBuilder, fieldName, fieldClass); }
java
{ "resource": "" }
q13038
POJOService.addConstructorParameter
train
private void addConstructorParameter(final MethodSpec.Builder constructorBuilder, final String attributeName, final TypeName type) { constructorBuilder.addParameter(type, attributeName, Modifier.FINAL); constructorBuilder.addCode("this." + attributeName + "=" + attributeName + ";"); }
java
{ "resource": "" }
q13039
POJOService.addGetter
train
private void addGetter(final TypeSpec.Builder classBuilder, final String attributeName, final TypeName type) { final String getterMethodName = "get" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1); final MethodSpec.Builder getterBuilder = MethodSpec.methodBuilder(getterMethodName); getterBuilder.returns(type); getterBuilder.addModifiers(Modifier.PUBLIC); getterBuilder.addCode("return this." + attributeName + ";"); classBuilder.addMethod(getterBuilder.build()); }
java
{ "resource": "" }
q13040
POJOService.hash
train
private String hash(String string) { final String sha1Hex = DigestUtils.sha1Hex(string); return StringUtils.substring(sha1Hex, 0, 8); }
java
{ "resource": "" }
q13041
Enhancer.newInstance
train
public T newInstance() { try { return getEnhancedClass().newInstance(); } catch (Exception e) { logger.error("Could not instantiate enhanced object.", e); throw ExceptionUtil.propagate(e); } }
java
{ "resource": "" }
q13042
Enhancer.enhance
train
public T enhance(T t) { if (!needsEnhancement(t)) { return t; } try { return getEnhancedClass().getConstructor(baseClass).newInstance(t); } catch (Exception e) { throw new RuntimeException(String.format("Could not enhance object %s (%s)", t, t.getClass()), e); } }
java
{ "resource": "" }
q13043
DBObjectUtil.objectIsMutable
train
public static boolean objectIsMutable(Object object) { if (object == null) { return false; } Class<?> clazz = object.getClass(); return Collection.class.isAssignableFrom(clazz); }
java
{ "resource": "" }
q13044
Container.fraction
train
public Container fraction(Fraction fraction) { if (fraction != null) { this.fractions.put(fractionRoot(fraction.getClass()), fraction); this.fractionsBySimpleName.put(fraction.simpleName(), fraction); fraction.initialize(new InitContext()); } return this; }
java
{ "resource": "" }
q13045
Container.iface
train
public Container iface(String name, String expression) { this.interfaces.add(new Interface(name, expression)); return this; }
java
{ "resource": "" }
q13046
Container.createDefaultDeployment
train
public Archive createDefaultDeployment() { try { Iterator<DefaultDeploymentFactory> providerIter = Module.getBootModuleLoader() .loadModule(ModuleIdentifier.create("swarm.application")) .loadService(DefaultDeploymentFactory.class) .iterator(); if (!providerIter.hasNext()) { providerIter = ServiceLoader.load(DefaultDeploymentFactory.class, ClassLoader.getSystemClassLoader()) .iterator(); } final Map<String, DefaultDeploymentFactory> factories = new HashMap<>(); while (providerIter.hasNext()) { final DefaultDeploymentFactory factory = providerIter.next(); final DefaultDeploymentFactory current = factories.get(factory.getType()); if (current == null) { factories.put(factory.getType(), factory); } else { // if this one is high priority than the previously-seen // factory, replace it. if (factory.getPriority() > current.getPriority()) { factories.put(factory.getType(), factory); } } } final DefaultDeploymentFactory factory = factories.get(determineDeploymentType()); return factory != null ? factory.create() : ShrinkWrap.create(JARArchive.class); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q13047
CrestCli.createMainEnvironment
train
protected CliEnvironment createMainEnvironment(final AtomicReference<InputReader> dynamicInputReaderRef, final AtomicReference<History> dynamicHistoryAtomicReference) { final Map<String, ?> data = new HashMap<String, Object>(); return new CliEnv() { @Override public History history() { return dynamicHistoryAtomicReference.get(); } @Override public InputReader reader() { return dynamicInputReaderRef.get(); } @Override public Map<String, ?> userData() { return data; } }; }
java
{ "resource": "" }
q13048
LaconicExplanationGeneratorBasedOnOPlus.getExplanations
train
public Set<Explanation<OWLAxiom>> getExplanations(OWLAxiom entailment) throws ExplanationException { return getExplanations(entailment, Integer.MAX_VALUE); }
java
{ "resource": "" }
q13049
InstantiateOperation.tryInitiatingObject
train
private Object tryInitiatingObject(String targetType, String initMethodName, List<Object> fieldObjects) throws TransformationOperationException { Class<?> targetClass = loadClassByName(targetType); try { if (initMethodName == null) { return initiateByConstructor(targetClass, fieldObjects); } else { return initiateByMethodName(targetClass, initMethodName, fieldObjects); } } catch (Exception e) { String message = "Unable to create the desired object. The instantiate operation will be ignored."; message = String.format(message, targetType); getLogger().error(message); throw new TransformationOperationException(message, e); } }
java
{ "resource": "" }
q13050
InstantiateOperation.initiateByMethodName
train
private Object initiateByMethodName(Class<?> targetClass, String initMethodName, List<Object> objects) throws Exception { Method method = targetClass.getMethod(initMethodName, getClassList(objects)); if (Modifier.isStatic(method.getModifiers())) { return method.invoke(null, objects.toArray()); } else { return method.invoke(targetClass.newInstance(), objects.toArray()); } }
java
{ "resource": "" }
q13051
InstantiateOperation.initiateByConstructor
train
private Object initiateByConstructor(Class<?> targetClass, List<Object> objects) throws Exception { Constructor<?> constr = targetClass.getConstructor(getClassList(objects)); return constr.newInstance(objects.toArray()); }
java
{ "resource": "" }
q13052
InstantiateOperation.getClassList
train
private Class<?>[] getClassList(List<Object> objects) { Class<?>[] classes = new Class<?>[objects.size()]; for (int i = 0; i < objects.size(); i++) { classes[i] = objects.get(i).getClass(); } return classes; }
java
{ "resource": "" }
q13053
InstantiateOperation.loadClassByName
train
private Class<?> loadClassByName(String className) throws TransformationOperationException { Exception e; if (className.contains(";")) { try { String[] parts = className.split(";"); ModelDescription description = new ModelDescription(); description.setModelClassName(parts[0]); if (parts.length > 1) { description.setVersionString(new Version(parts[1]).toString()); } return modelRegistry.loadModel(description); } catch (Exception ex) { e = ex; } } else { try { return this.getClass().getClassLoader().loadClass(className); } catch (Exception ex) { e = ex; } } String message = "The class %s can't be found. The instantiate operation will be ignored."; message = String.format(message, className); getLogger().error(message); throw new TransformationOperationException(message, e); }
java
{ "resource": "" }
q13054
DynamicObject.update
train
public void update(Object target) { if (target == null) { throw new IllegalArgumentException( "Target to update cannot be null"); } BeanWrapper bw = new BeanWrapperImpl(target); bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); for (Map.Entry<String, Object> property : m_properties.entrySet()) { String propertyName = property.getKey(); Object value = property.getValue(); if (value instanceof Map) { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); if (!Map.class.isAssignableFrom(pd.getPropertyType()) || pd.getWriteMethod() == null) { value = new DynamicObject((Map<String, Object>) value); } } if (value instanceof DynamicObject) { ((DynamicObject) value).update(bw.getPropertyValue(propertyName)); } else { bw.setPropertyValue(propertyName, value); } } }
java
{ "resource": "" }
q13055
PlotActivityNetworkGantt.createDataset
train
private IntervalCategoryDataset createDataset() { TaskSeries ts = null; TaskSeriesCollection collection = new TaskSeriesCollection(); if ( solver.getVariables().length == 0) { return collection; } ts = new TaskSeries("All"); for (int i = 0; i < solver.getVariables().length ; i++) { String label = solver.getVariables()[i].getComponent(); //dn.getNodes().elementAt(i).getLabel(); if ( this.selectedVariables == null || this.selectedVariables.contains( label ) ) { SymbolicTimeline tl1 = new SymbolicTimeline(solver,label); for (int j = 0 ; j < tl1.getPulses().length-1 ; j++ ) { if ( tl1.getValues()[j] != null ) { long startTime = tl1.getPulses()[j].longValue(); long endTime = startTime + tl1.getDurations()[j].longValue(); Date startTask = new Date(startTime); Date endTask = new Date(endTime); Task task; String value = tl1.getValues()[j].toString().replace("[", "").replace("]", ""); if ( value.equals("true") ) task = new Task(label, startTask, endTask); else task = new Task(label + " := " + value, startTask, endTask); ts.add(task); } } } } collection.add(ts); return collection; }
java
{ "resource": "" }
q13056
LinePainter.paint
train
public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { try { Rectangle r = c.modelToView(c.getCaretPosition()); g.setColor( color ); g.fillRect(0, r.y, c.getWidth(), r.height); if (lastView == null) lastView = r; } catch(BadLocationException ble) {System.out.println(ble);} }
java
{ "resource": "" }
q13057
FrameManager.closeWindowPerformed
train
public void closeWindowPerformed(SwingFrame frameView) { if (!navigationFrames.contains(frameView)) return; if (navigationFrames.size() == 1 && !askBeforeExit(frameView)) { return; } if (frameView.tryToCloseWindow()) { removeNavigationFrameView(frameView); } }
java
{ "resource": "" }
q13058
FrameManager.askBeforeExit
train
private boolean askBeforeExit(SwingFrame navigationFrameView) { if (Configuration.isDevModeActive()) { return true; } else { int answer = JOptionPane.showConfirmDialog(navigationFrameView, Resources.getString("Exit.confirm"), Resources.getString("Exit.confirm.title"), JOptionPane.YES_NO_OPTION); return answer == JOptionPane.YES_OPTION; } }
java
{ "resource": "" }
q13059
FrameManager.closeAllWindows
train
private boolean closeAllWindows(SwingFrame navigationFrameView) { // Die umgekehrte Reihenfolge fühlt sich beim Schliessen natürlicher an for (int i = navigationFrames.size()-1; i>= 0; i--) { SwingFrame frameView = navigationFrames.get(i); if (!frameView.tryToCloseWindow()) return false; removeNavigationFrameView(frameView); } return true; }
java
{ "resource": "" }
q13060
FrameManager.removeNavigationFrameView
train
private void removeNavigationFrameView(SwingFrame frameView) { navigationFrames.remove(frameView); if (navigationFrames.size() == 0) { System.exit(0); } }
java
{ "resource": "" }
q13061
LeaderService.sleep
train
private synchronized void sleep(long waitNanos) throws InterruptedException { while (waitNanos > 0 && isRunning()) { long start = System.nanoTime(); TimeUnit.NANOSECONDS.timedWait(this, waitNanos); waitNanos -= System.nanoTime() - start; } }
java
{ "resource": "" }
q13062
ObjectDiff.loadKeyList
train
private List<String> loadKeyList() { Set<String> keySet = new HashSet<String>(); for (EDBObjectEntry entry : startState.values()) { keySet.add(entry.getKey()); } for (EDBObjectEntry entry : endState.values()) { keySet.add(entry.getKey()); } return new ArrayList<String>(keySet); }
java
{ "resource": "" }
q13063
OPlusGenerator.getSameSourceAxioms
train
public Set<OWLAxiom> getSameSourceAxioms(OWLAxiom axiom, Set<OWLAxiom> toSearch) { Set<OWLAxiom> axiomSources = axiom2SourceMap.get(axiom); if(axiomSources == null) { return Collections.emptySet(); } Set<OWLAxiom> result = new HashSet<OWLAxiom>(); for(OWLAxiom ax : toSearch) { Set<OWLAxiom> sources = axiom2SourceMap.get(ax); if(sources != null) { for(OWLAxiom axiomSourceAxiom : axiomSources) { if(sources.contains(axiomSourceAxiom)) { result.add(ax); break; } } } } return result; }
java
{ "resource": "" }
q13064
APSPSolver.tpCreate
train
private int[] tpCreate(int n) { if (n > MAX_TPS) return null; int[] ret = new int[n]; for (int i = 0; i < n; i++) ret[i] = tpCreate(); return ret; }
java
{ "resource": "" }
q13065
APSPSolver.tpDelete
train
private void tpDelete(int[] IDtimePoint) { logger.finest("Deleting " + IDtimePoint.length + " TP"); for (int i = 0; i < IDtimePoint.length; i++) { tPoints[IDtimePoint[i]].setUsed(false); if (IDtimePoint[i] == MAX_USED) MAX_USED--; SimpleDistanceConstraint conO = new SimpleDistanceConstraint(); SimpleDistanceConstraint conH = new SimpleDistanceConstraint(); conO.setFrom(this.getVariable(0)); conO.setTo(this.getVariable(IDtimePoint[i])); conH.setFrom(this.getVariable(IDtimePoint[i])); conH.setTo(this.getVariable(1)); conO.setMinimum(0); conO.setMaximum(H-O); conH.setMinimum(0); conH.setMaximum(H-O); conO.addInterval(new Bounds(0,H-O)); conH.addInterval(new Bounds(0,H-O)); //[lb,ub] = [-di0,d0i] tPoints[IDtimePoint[i]].setLowerBound(O); tPoints[IDtimePoint[i]].setUpperBound(H); tPoints[0].setOut(IDtimePoint[i],conO); tPoints[IDtimePoint[i]].setOut(1,conH); } fromScratchDistanceMatrixComputation(); }
java
{ "resource": "" }
q13066
APSPSolver.cDelete
train
private boolean cDelete(Bounds[] in, int[] from, int[] to, boolean canRestore) throws ConstraintNotFound, MalformedSimpleDistanceConstraint { for (int i = 0; i < in.length; i++) { //Conversion long min = in[i].min; long max = in[i].max; if (in[i].max == Long.MAX_VALUE - 1) max = H-O; if (in[i].min == Long.MIN_VALUE + 1) min = -1 * (H - O); in[i] = new Bounds(min,max); SimpleDistanceConstraint con = tPoints[from[i]].getOut(to[i]); if (con == null) { throw new ConstraintNotFound(String.format("Interval %s, from %d, to %d", in[i].toString(), from[i], to[i])); } if (con.getCounter() == 1) { if (con.removeInterval(in[i])) tPoints[from[i]].setOut(to[i],null); else throw new MalformedSimpleDistanceConstraint(con, 1); } else if (!con.removeInterval(in[i])) throw new MalformedSimpleDistanceConstraint(con, 2); } if (!canRestore) fromScratchDistanceMatrixComputation(); else { logger.finest("QuickRestoring distance matrix, no propagation"); if (backupDMatrixSimple) restoreDMatrix(); } for (int j = 0; j < MAX_USED+1; j++) if (tPoints[j].isUsed() == true) { tPoints[j].setLowerBound(sum(-distance[j][0],O)); tPoints[j].setUpperBound(sum(distance[0][j],O)); } return true; }
java
{ "resource": "" }
q13067
APSPSolver.getTimePoint
train
public TimePoint getTimePoint(int Id) { if (Id >= MAX_TPS) return null; if (tPoints[Id] == null) return null; if (!tPoints[Id].isUsed()) return null; return tPoints[Id]; }
java
{ "resource": "" }
q13068
APSPSolver.fromScratchDistanceMatrixComputation
train
private boolean fromScratchDistanceMatrixComputation() { logger.fine("Propagating (cube) with (#TPs,#cons) = (" + this.MAX_USED + "," + this.theNetwork.getConstraints().length + ") (call num.: " + (++cubePropCount) + ")"); //* //This code is not tested thoroughly but seems to work for (int i = 0; i < MAX_USED+1; i++) { for (int j = i; j < MAX_USED+1; j++) { if (i != j) { long dij = H;//APSPSolver.INF; long dji = H;//APSPSolver.INF; if(tPoints[i].getOut(j) != null) { dij = Math.min(dij, +tPoints[i].getOut(j).getMaximum()); dji = Math.min(dji, -tPoints[i].getOut(j).getMinimum()); } if(tPoints[j].getOut(i) != null) { dij = Math.min(dij, -tPoints[j].getOut(i).getMinimum()); dji = Math.min(dji, +tPoints[j].getOut(i).getMaximum()); } if(-dji > +dij) { return false; } distance[i][j] = dij; distance[j][i] = dji; } else distance[i][j] = 0; } } for (int k = 0; k < MAX_USED+1; k++) { if (tPoints[k].isUsed() == true) { for (int i = 0; i < MAX_USED+1; i++) { if (tPoints[i].isUsed() == true) { for (int j = 0; j < MAX_USED+1; j++) { if (tPoints[j].isUsed() == true) { long temp = sum(distance[i][k],distance[k][j]); if (distance[i][j] > temp) distance[i][j] = temp; } if (i == j && distance[i][j] < 0) return false; } } } } } return true; }
java
{ "resource": "" }
q13069
APSPSolver.incrementalDistanceMatrixComputation
train
private boolean incrementalDistanceMatrixComputation(int from,int to,Bounds i) { logger.fine("Propagating (quad) with (#TPs,#cons) = (" + this.MAX_USED + "," + this.theNetwork.getConstraints().length + ") (call num.: " + (++quadPropCount) + ")"); if (distance[to][from] != APSPSolver.INF && sum(i.max,distance[to][from]) < 0) return false; if (distance[from][to] != APSPSolver.INF && sum(-i.min,distance[from][to]) < 0) return false; // System.out.println("a)" + sum(i.max,distance[to][from])); // System.out.println("b)" + sum(-i.min,distance[from][to])); long sum1; long sum2; long sum3; long sum4; long temp; for (int u = 0; u < MAX_USED+1; u++) { if (tPoints[u].isUsed()) { for (int v = 0; v < MAX_USED+1;v++) { if (tPoints[v].isUsed()) { //min{distance[u][v];(distance[u][from]+i.max+distance[to][v]);(distance[u][to]-i.minl+distance[from][v])} sum1 = sum(distance[u][to],-i.min); sum2 = sum(sum1,distance[from][v]); sum3 = sum(distance[u][from],i.max); sum4 = sum(sum3,distance[to][v]); temp = Math.min(sum2,sum4); if (distance[u][v] > temp) { //long oldD = distance[u][v]; distance[u][v] = temp; if (u == v && distance[u][v] != 0) { //logger.info("==================> Updated distance[" + u + "][" + v + "] from " + oldD + " to " + temp); //throw new Error("Found negative cycle in incremental propagation while adding (from,to,i) (" + from + "," + to + "," + i + ")"); return false; } } } } } } return true; }
java
{ "resource": "" }
q13070
APSPSolver.changeHorizon
train
public boolean changeHorizon(long val) { this.removeConstraint(horizonConstraint); SimpleDistanceConstraint sdc = new SimpleDistanceConstraint(); sdc.setFrom(this.getVariable(0)); sdc.setTo(this.getVariable(1)); sdc.setMinimum(val); sdc.setMaximum(val); if (this.addConstraint(sdc)) { this.H = val; horizonConstraint = sdc; return true; } return false; }
java
{ "resource": "" }
q13071
FilterChainFactory.create
train
public FilterChain create() throws FilterConfigurationException { Preconditions.checkState(filters != null, "list of filters must be set"); Preconditions.checkState(inputType != null, "inputType must be set"); Preconditions.checkState(outputType != null, "outputType must be set"); Preconditions.checkState(filters.size() > 0, "need at least one filter"); validateFiltersList(); Iterator<Object> iterator = filters.iterator(); FilterChainElement firstInstance = getInstanceFromListElement(iterator.next()); if (!firstInstance.getSupportedInputType().isAssignableFrom(inputType) || !firstInstance.getSupportedOutputType().isAssignableFrom(outputType)) { throw new FilterConfigurationException(String.format( "incompatible Filtertype (%s) should be (%s->%s) - is (%s->%s)", firstInstance.getClass(), inputType, outputType, firstInstance.getSupportedInputType(), firstInstance.getSupportedOutputType())); } FilterChainElement current = firstInstance; while (iterator.hasNext()) { Object next = iterator.next(); FilterChainElement nextFilterElement = getInstanceFromListElement(next); if (nextFilterElement == null) { current.setNext((FilterAction) next); break; } current.setNext(nextFilterElement); current = nextFilterElement; } return new FilterChain(firstInstance); }
java
{ "resource": "" }
q13072
DateUtils.parseCH
train
public static String parseCH(String inputText, boolean partialAllowed) { if (StringUtils.isEmpty(inputText)) return null; String text = cutNonDigitsAtBegin(inputText); if (StringUtils.isEmpty(text)) return ""; text = cutNonDigitsAtEnd(text); if (StringUtils.isEmpty(text)) return ""; // Nun hat der String sicher keinen Punkt mehr am Anfang oder Ende if (inputText.indexOf(".") > -1) { return parseCHWithDot(inputText, partialAllowed); } else { return parseCHWithoutDot(inputText, partialAllowed); } }
java
{ "resource": "" }
q13073
DateUtils.parse
train
public static LocalDate parse(String date) { if (StringUtils.isEmpty(date)) return null; try { return parse_(date); } catch (DateTimeParseException x) { return InvalidValues.createInvalidLocalDate(date); } }
java
{ "resource": "" }
q13074
DateUtils.parse_
train
public static LocalDate parse_(String date) { DateTimeFormatter dateTimeFormatter = getDateTimeFormatter(); if (germanDateStyle()) { date = parseCH(date, false); return LocalDate.parse(date); } else { return LocalDate.parse(date, dateTimeFormatter); } }
java
{ "resource": "" }
q13075
MenuTemplate.addMenuItem
train
public void addMenuItem(String index, Class<? extends WebPage> linkClass, String langKey, String langDescKey, String... authority) { addMenuItem(index, linkClass, langKey, langDescKey, null, authority); }
java
{ "resource": "" }
q13076
Backend.read
train
public static <T> T read(Class<T> clazz, Object id) { return execute(new ReadEntityTransaction<T>(clazz, id)); }
java
{ "resource": "" }
q13077
ServicesHelper.listRunningServices
train
public void listRunningServices() { try { final List<String> formatedOutput = SecurityContext.executeWithSystemPermissions(new Callable<List<String>>() { @Override public List<String> call() throws Exception { List<String> tmp = new ArrayList<String>(); List<ServiceReference<Domain>> listServiceReferences = osgiUtilsService.listServiceReferences(Domain.class); for (ServiceReference<Domain> ref : listServiceReferences) { Domain service = bundleContext.getService(ref); tmp.add(OutputStreamFormater.formatValues( ref.getProperty(org.osgi.framework.Constants.SERVICE_PID).toString(), service .getAliveState().toString())); } return tmp; } }); for (String s : formatedOutput) { OutputStreamFormater.printValue(s); } } catch (ExecutionException ex) { ex.printStackTrace(); System.err.println("Could not get services"); } }
java
{ "resource": "" }
q13078
ServicesHelper.deleteService
train
public void deleteService(String id, boolean force) { try { if (id == null || id.isEmpty()) { id = selectRunningService(); } final String idFinal = id; int input = 'Y'; if (!force) { OutputStreamFormater.printValue(String.format( "Do you really want to delete the connector: %s (Y/n): ", id)); input = keyboard.read(); } if ('n' != (char) input && 'N' != (char) input) { SecurityContext.executeWithSystemPermissions(new Callable<Object>() { @Override public Object call() throws Exception { serviceManager.delete(idFinal); return null; } }); OutputStreamFormater.printValue(String.format("Service: %s successfully deleted", id)); } } catch (ExecutionException e) { e.printStackTrace(); System.err.println("Could not delete service"); } catch (IOException e) { e.printStackTrace(); System.err.println("Unexpected Error"); } }
java
{ "resource": "" }
q13079
ServicesHelper.selectRunningService
train
private String selectRunningService() { String selectedServiceId; List<String> runningServiceIds = getRunningServiceIds(); for (int i = 0; i < runningServiceIds.size(); i++) { String serviceId = runningServiceIds.get(i); OutputStreamFormater.printTabbedValues(9, String.format("[%s]", i), String.format("%s", serviceId)); } String s = readUserInput(); int pos; try { pos = Integer.parseInt(s); selectedServiceId = runningServiceIds.get(pos); } catch (Exception e) { throw new IllegalArgumentException(String.format("Invalid Input: %s", s)); } return selectedServiceId; }
java
{ "resource": "" }
q13080
ServicesHelper.getRunningServiceIds
train
public List<String> getRunningServiceIds() { List<ServiceReference<Domain>> serviceReferences = osgiUtilsService.listServiceReferences(Domain.class); List<String> result = new ArrayList<String>(); for (ServiceReference<Domain> ref : serviceReferences) { result.add((String) ref.getProperty(org.osgi.framework.Constants.SERVICE_PID)); } return result; }
java
{ "resource": "" }
q13081
ServicesHelper.createService
train
public void createService(String domainProviderName, boolean force, Map<String, String> attributes) { // check if a domain has been chosen if (domainProviderName == null || domainProviderName.isEmpty()) { domainProviderName = selectDomainProvider(); } // get domain provider Id String domainProviderId = ""; List<DomainProvider> domainProvider = getDomainProvider(); for (DomainProvider provider : domainProvider) { if (provider.getName().getString(Locale.getDefault()).equals(domainProviderName)) { domainProviderId = provider.getId(); } } // get the connector which should be created ConnectorProvider connectorProvider = getConnectorToCreate(domainProviderId, attributes.get(ServiceCommands.CONNECTOR_TYPE)); String id; if (attributes.isEmpty() || !attributes.containsKey(org.osgi.framework.Constants.SERVICE_PID)) { OutputStreamFormater.printValue("Please enter an ID"); id = readUserInput(); } else { id = attributes.get(org.osgi.framework.Constants.SERVICE_PID); } ServiceDescriptor descriptor = connectorProvider.getDescriptor(); OutputStreamFormater.printValue(String.format("Please enter the attributes for %s, keep empty for default", descriptor.getName().getString(Locale.getDefault()))); // get attributes for connector Map<String, String> attributeMap = getConnectorAttributes(descriptor.getAttributes(), attributes); Map<String, Object> properties = new HashMap<String, Object>(); ConnectorDescription connectorDescription = new ConnectorDescription(domainProviderId, connectorProvider.getId(), attributeMap, properties); if (force) { if (id != null && !id.isEmpty()) { serviceManager.forceCreateWithId(id, connectorDescription); } else { serviceManager.forceCreate(connectorDescription); } OutputStreamFormater.printValue("Connector successfully created"); } else { OutputStreamFormater.printValue("Do you want to create the connector with the following attributes:", ""); OutputStreamFormater.printValue("Connector ID", id); for (String key : attributeMap.keySet()) { OutputStreamFormater.printValue(key, attributeMap.get(key)); } OutputStreamFormater.printValue("Create connector: (Y/n)"); if (!readUserInput().equalsIgnoreCase("n")) { try { if (id != null && !id.isEmpty()) { serviceManager.createWithId(id, connectorDescription); } else { serviceManager.create(connectorDescription); } OutputStreamFormater.printValue("Connector successfully created"); } catch (RuntimeException e) { e.printStackTrace(); OutputStreamFormater.printValue("Connector validation failed, creation aborted"); } } else { OutputStreamFormater.printValue("Creation aborted"); } } }
java
{ "resource": "" }
q13082
EntryFactory.globalPermissionSetStructure
train
public static List<Entry> globalPermissionSetStructure(String permissionSet) { Entry permissionSetEntry = namedObject(permissionSet, SchemaConstants.ouGlobalPermissionSets()); Entry ouDirect = organizationalUnit("direct", permissionSetEntry.getDn()); Entry ouChildrenSets = organizationalUnit("childrenSets", permissionSetEntry.getDn()); Entry ouAttributes = organizationalUnit("attributes", permissionSetEntry.getDn()); return Arrays.asList(permissionSetEntry, ouAttributes, ouDirect, ouChildrenSets); }
java
{ "resource": "" }
q13083
JdbcIndexEngine.removeUnmappedFields
train
protected void removeUnmappedFields(JdbcIndex<?> index) { Iterator<IndexField<?>> iterator = index.getFields().iterator(); while (iterator.hasNext()) { IndexField<?> field = iterator.next(); if (field.getMappedType() == null) { LOG.info("Removing {} from index {} - no mapped type information", field.getName(), index.getName()); iterator.remove(); } } }
java
{ "resource": "" }
q13084
Project.loadPOM
train
public static Model loadPOM(String pomPath, String localRepo, Collection<RemoteRepository> repositories) throws ProjectException { RepositoryClient repoClient = new RepositoryClient(localRepo); NaetherModelResolver resolver = new NaetherModelResolver(repoClient, repositories); ModelBuildingRequest req = new DefaultModelBuildingRequest(); req.setProcessPlugins( false ); req.setPomFile( new File(pomPath) ); req.setModelResolver( resolver ); req.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); DefaultModelBuilder builder = (new DefaultModelBuilderFactory()).newInstance(); try { return builder.build( req ).getEffectiveModel(); } catch ( ModelBuildingException e ) { throw new ProjectException("Failed to build project from pom", e); } }
java
{ "resource": "" }
q13085
Project.getVersion
train
public String getVersion() { String version = getMavenModel().getVersion(); if ( version == null && getMavenModel().getParent() != null ) { version = getMavenModel().getParent().getVersion(); } return version; }
java
{ "resource": "" }
q13086
Project.addRepository
train
public void addRepository(String url) throws ProjectException { List<Repository> repositories = getRepositories(); if ( repositories == null ) { repositories = new ArrayList<Repository>(); } try { Repository repository = RepoBuilder.repositoryFromUrl( url ); repositories.add( repository ); } catch (MalformedURLException e) { throw new ProjectException( e ); } getMavenModel().setRepositories( repositories ); }
java
{ "resource": "" }
q13087
Project.getRepositoryUrls
train
public List<String> getRepositoryUrls() { List<String> urls = new ArrayList<String>(); for ( Repository repo : getRepositories() ) { urls.add( repo.getUrl() ); } return urls; }
java
{ "resource": "" }
q13088
Project.setProjectNotation
train
public void setProjectNotation(String notation) { Map<String, String> notationMap = Notation.parse(notation); this.setGroupId(notationMap.get("groupId")); this.setArtifactId(notationMap.get("artifactId")); this.setType(notationMap.get("type")); this.setVersion(notationMap.get("version")); }
java
{ "resource": "" }
q13089
Project.addDependency
train
public void addDependency(String notation, String scope ) { Map<String, String> notationMap = Notation.parse(notation); Dependency dependency = new Dependency(); dependency.setGroupId(notationMap.get("groupId")); dependency.setArtifactId(notationMap.get("artifactId")); dependency.setType(notationMap.get("type")); dependency.setVersion(notationMap.get("version")); dependency.setScope( scope ); addDependency(dependency); }
java
{ "resource": "" }
q13090
Project.toXml
train
public String toXml() throws ProjectException { log.debug("Writing xml"); Project copy = this; copy.removeProperty( "project.basedir" ); StringWriter writer = new StringWriter(); MavenXpp3Writer pomWriter = new MavenXpp3Writer(); try { pomWriter.write(writer, copy.mavenModel); } catch (IOException e) { throw new ProjectException("Failed to create pom xml", e); } writer.flush(); return writer.toString(); }
java
{ "resource": "" }
q13091
ExceptionUtils.logReducedStackTrace
train
public static void logReducedStackTrace(Logger logger, Exception exception) { Exception here = new Exception(); String[] hereStrings = getStackFrames(here); String[] throwableStrings = getStackFrames(exception); int linesToSkip = 1; while (throwableStrings.length - linesToSkip > 0 && hereStrings.length - linesToSkip > 0) { if (!StringUtils.equals(hereStrings[hereStrings.length-linesToSkip], throwableStrings[throwableStrings.length-linesToSkip])) { break; } linesToSkip++; } for (int i = 0; i<=throwableStrings.length-linesToSkip; i++) { logger.log(Level.SEVERE, throwableStrings[i]); } }
java
{ "resource": "" }
q13092
ExceptionUtils.getStackTrace
train
private static String getStackTrace(final Throwable throwable) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); throwable.printStackTrace(pw); return sw.getBuffer().toString(); }
java
{ "resource": "" }
q13093
DataSourceFactory.getDataSource
train
public static DataSource getDataSource(final String jndiName) throws FactoryException { Validate.notBlank(jndiName, "The validated character sequence 'jndiName' is null or empty"); // no need for defensive copies of Strings try { // the initial context is created from the provided JNDI settings final Context context = new InitialContext(); // retrieve a data source object, close the context as it is no longer needed, and return the data source final Object namedObject = context.lookup(jndiName); if (DataSource.class.isInstance(namedObject)) { final DataSource dataSource = (DataSource) context.lookup(jndiName); context.close(); return dataSource; } else { final String error = "The JNDI name '" + jndiName + "' does not reference a SQL DataSource." + " This is a configuration issue."; LOG.warn(error); throw new FactoryException(error); } } catch (NamingException e) { final String error = "Error retrieving JDBC date source from JNDI: " + jndiName; LOG.warn(error); throw new FactoryException(error, e); } }
java
{ "resource": "" }
q13094
DataSourceFactory.loadDriver
train
private static void loadDriver(final String driver) throws FactoryException { // assert in private method assert driver != null : "The driver cannot be null"; LOG.debug("Loading the database driver '" + driver + "'"); // make sure the driver is available try { Class.forName(driver); } catch (ClassNotFoundException e) { final String error = "Error loading JDBC driver class: " + driver; LOG.warn(error, e); throw new FactoryException(error, e); } }
java
{ "resource": "" }
q13095
DataSourceFactory.getPoolingDataSource
train
private static PoolingDataSource<PoolableConnection> getPoolingDataSource(final String url, final ConcurrentMap<String, String> properties, final ConnectionProperties poolSpec) { // assert in private method assert url != null : "The url cannot be null"; assert properties != null : "The properties cannot be null"; assert poolSpec != null : "The pol spec cannot be null"; LOG.debug("Creating new pooled data source for '" + url + "'"); // convert the properties hashmap to java properties final Properties props = new Properties(); props.putAll(properties); // create a Apache DBCP pool configuration from the pool spec final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxTotal(poolSpec.getMaxTotal()); poolConfig.setMaxIdle(poolSpec.getMaxIdle()); poolConfig.setMinIdle(poolSpec.getMinIdle()); poolConfig.setMaxWaitMillis(poolSpec.getMaxWaitMillis()); poolConfig.setTestOnCreate(poolSpec.isTestOnCreate()); poolConfig.setTestOnBorrow(poolSpec.isTestOnBorrow()); poolConfig.setTestOnReturn(poolSpec.isTestOnReturn()); poolConfig.setTestWhileIdle(poolSpec.isTestWhileIdle()); poolConfig.setTimeBetweenEvictionRunsMillis(poolSpec.getTimeBetweenEvictionRunsMillis()); poolConfig.setNumTestsPerEvictionRun(poolSpec.getNumTestsPerEvictionRun()); poolConfig.setMinEvictableIdleTimeMillis(poolSpec.getMinEvictableIdleTimeMillis()); poolConfig.setSoftMinEvictableIdleTimeMillis(poolSpec.getSoftMinEvictableIdleTimeMillis()); poolConfig.setLifo(poolSpec.isLifo()); // create the pool and assign the factory to the pool final org.apache.commons.dbcp2.ConnectionFactory connFactory = new DriverManagerConnectionFactory(url, props); final PoolableConnectionFactory poolConnFactory = new PoolableConnectionFactory(connFactory, null); poolConnFactory.setDefaultAutoCommit(poolSpec.isDefaultAutoCommit()); poolConnFactory.setDefaultReadOnly(poolSpec.isDefaultReadOnly()); poolConnFactory.setDefaultTransactionIsolation(poolSpec.getDefaultTransactionIsolation()); poolConnFactory.setCacheState(poolSpec.isCacheState()); poolConnFactory.setValidationQuery(poolSpec.getValidationQuery()); poolConnFactory.setMaxConnLifetimeMillis(poolSpec.getMaxConnLifetimeMillis()); final GenericObjectPool<PoolableConnection> connPool = new GenericObjectPool<>(poolConnFactory, poolConfig); poolConnFactory.setPool(connPool); // create a new pooled data source return new PoolingDataSource<>(connPool); }
java
{ "resource": "" }
q13096
Notation.getLocalPaths
train
public static List<String> getLocalPaths( String localRepoPath, List<String> notations ) throws NaetherException { DefaultServiceLocator locator = new DefaultServiceLocator(); SimpleLocalRepositoryManagerFactory factory = new SimpleLocalRepositoryManagerFactory(); factory.initService( locator ); LocalRepository localRepo = new LocalRepository(localRepoPath); LocalRepositoryManager manager = null; try { manager = factory.newInstance( localRepo ); } catch (NoLocalRepositoryManagerException e) { throw new NaetherException( "Failed to initial local repository manage", e ); } List<String> localPaths = new ArrayList<String>(); for ( String notation : notations ) { Dependency dependency = new Dependency(new DefaultArtifact(notation), "compile"); File path = new File( localRepo.getBasedir(), manager.getPathForLocalArtifact( dependency.getArtifact() ) ); localPaths.add( path.toString() ); } return localPaths; }
java
{ "resource": "" }
q13097
JpaSource.iterator
train
public Iterator iterator() { Query readAll = m_em.createQuery( createReadAllQuery(m_entityClass.getSimpleName())); return new JpaIterator(readAll, m_batchSize); }
java
{ "resource": "" }
q13098
ProcessBag.addProperty
train
public void addProperty(String key, Object value) throws ProcessBagException { if (properties.containsKey(key)) { throw new ProcessBagException(key + " already used!"); } else { properties.put(key, value); } }
java
{ "resource": "" }
q13099
SimpleInterval.compareTo
train
@Override public int compareTo(Object arg0) { if (arg0 instanceof SimpleInterval) { SimpleInterval that = (SimpleInterval)arg0; return intervalName.compareTo(that.getIntervalName()); } return 0; }
java
{ "resource": "" }