id
stringlengths
7
14
text
stringlengths
1
37.2k
4001968_2
public java.util.Map<String, AnnotationProperty> getProperties() { return properties; }
4016036_0
public List<DeltaSQLStatementSnapshot> getDeltaSqlStatementSnapshots() { return deltaSQLStatementSnapshots; }
4021268_10
public String getName() { return name; }
4023244_0
public static boolean implementsInterface(final Class type, final Class interfaceClass) { return interfaceClass.isAssignableFrom(type); }
4024302_13
public void onStart() { if (target instanceof HazelcastInstanceAware) { ((HazelcastInstanceAware) target).setHazelcastInstance(hazelcastInstance); } if (target instanceof SliceLifecycleListener) { ((SliceLifecycleListener) target).onStart(); } }
4026983_1
public String toJson() { return new Gson().toJson(this); }
4031229_11
public static File getFileOutputDir(final URI baseUri, final File outputDir, final TestRunCoverageStatistics runStats) { final URI relativeTestUri = baseUri.relativize(runStats.test); return new File(outputDir, relativeTestUri.toString()).getParentFile().getAbsoluteFile(); }
4057303_5
public T getAssociatedInstance(final String typeId) throws DempsyException { if(LOGGER.isTraceEnabled()) LOGGER.trace("Trying to find " + clazz.getSimpleName() + " associated with the transport \"{}\"", typeId); T ret = null; synchronized(registered) { ret = registered.get(typeId); if(ret == null) { if(LOGGER.isTraceEnabled()) LOGGER.trace(clazz.getSimpleName() + " associated with the id \"{}\" wasn't already registered. Attempting to create one", typeId); ret = makeInstance(typeId); registered.put(typeId, ret); } } return ret; }
4060867_7
public void getVideos(HttpServletRequest request, HttpServletResponse response) throws Exception { XMLBuilder builder = createXMLBuilder(request, response, true); builder.add("videos", true); builder.endAll(); response.getWriter().print(builder); }
4090170_0
public void generate(Schema schema, Writer output) throws IOException { final VelocityContext context = new VelocityContext(); context.put("schema", schema); context.put("this", this); engine.mergeTemplate(path + "fields.vm", "UTF-8", context, output); }
4101951_1
public List<DtoProperty> getProperties() { if (properties == null) { properties = list(); final List<PropConfig> pcs = getPropertiesConfig(); if (getDomainType() != null) { addPropertiesFromDomainObject(pcs); addChainedPropertiesFromDomainObject(pcs); } addLeftOverExtensionProperties(pcs); sortProperties(pcs, properties); } return properties; }
4103388_44
@Override public OsisWrapper getOsisText(final String version, final String reference) { return getOsisText(version, reference, new ArrayList<LookupOption>(0), null, NONE); }
4106766_6
@Override public User get(String username) throws Exception { return Optional.ofNullable(dynamoDBMapper.load(User.class, username)) .orElseThrow(() -> new Exception(String.format("User for username %s was not found", username))); }
4112450_11
public boolean parse(String input) { String[] split = input.split(" "); if(split.length != 4) { if(LOGGER.isInfoEnabled()) LOGGER.info("Could not parse '"+input+"': 4 tokens expected"); return false; } String u = split[0]; try { units = Units.valueOf(u.toLowerCase()); secondsMultiplier = units.getMultiplier(); } catch (Exception e) { if(LOGGER.isInfoEnabled()) LOGGER.info("Unknown time unit '"+u+"': " + e.getMessage()); return false; } if(! "since".equals(split[1])) { if(LOGGER.isInfoEnabled()) LOGGER.info("Missing 'since' keyword"); return false; } String datetime = split[2] + " " + split[3]; try { date = INPUTFORMAT.parse(datetime); } catch (ParseException ex) { if(LOGGER.isInfoEnabled()) LOGGER.info("Can't parse datetime '"+datetime+"': " + ex.getMessage()); return false; } return true; }
4114494_1
public int getClassId() { return classId; }
4117239_0
public Queue(Variable<ImmutableList<VALUE>> input, Variable<ImmutableList<VALUE>> output, Variable<Boolean> frozen) { super(input, output, frozen); }
4120901_37
public boolean filter(File file) { return file.getParentFile().getAbsolutePath().contains(springHadoopWorkflowDirectoryName); }
4129770_0
public void forUnitTest() { }
4131741_2
@Override public final boolean preHandle( final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { this.assignCacheControlHeader(request, response, handler); return super.preHandle(request, response, handler); }
4138309_2
public static Event<?> fromJson(String json) throws IOException { return JSONUtil.toObject(json, new TypeReference<Event<?>>() {}); }
4139627_0
@Override public StartLetterCountMP clone() throws CloneNotSupportedException { return (StartLetterCountMP)super.clone(); }
4159017_99
;
4167742_80
@Override public AlertType checkValue(BigDecimal value, BigDecimal warn, BigDecimal error) { boolean isHighValueWorse = isTheValueBeingHighWorse(warn, error); if (isBeyondThreshold(value, error, isHighValueWorse)) { return AlertType.ERROR; } else if (isBeyondThreshold(value, warn, isHighValueWorse)) { return AlertType.WARN; } return AlertType.OK; }
4169493_3
public void escapeColNames() throws Exception { ArrayList<String> newColNames = new ArrayList<String>(); for (String s : this.colNames) { newColNames.add(NameConvention.escapeEntityNameStrict(s)); this.colNames = newColNames; } }
4180644_100
@Override public List<DrugGroup> getDrugGroupByName(String name) throws DAOException { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(DrugGroup.class); criteria.add(Restrictions.like("name", name)); criteria.add(Restrictions.like("retired", false)); List<DrugGroup> patients = new ArrayList<DrugGroup>(); patients.addAll(criteria.list()); return patients; }
4182801_87
@Override public int format(FormatterAPI formatter, Object value, Locale locale, String flags, int width, int precision, String formatString, int position) throws IOException { ensureNoWidth(width); ensureNoPrecision(precision); ensureNoFlags(flags); return new Conditional(formatter, value, formatString, position).apply() - position; }
4189503_130
@Override public CalculationResultMap evaluate(Collection<Integer> cohort, Map<String, Object> params, PatientCalculationContext context) { Program program = (params != null && params.containsKey("program")) ? (Program) params.get("program") : null; return passing(Calculations.activeEnrollment(program, Filters.alive(cohort, context), context)); }
4193864_175
void handleSubscriptions() { Set<FeedProvider> requiredSubscriptions = buildRequiredSubscriptions(); List<FeedProvider> newSubscriptions = new ArrayList<FeedProvider>(); List<FeedProvider> removedSubscriptions = new ArrayList<FeedProvider>(); Set<FeedProvider> set = new TreeSet<FeedProvider>(FEED_COMPARATOR); set.addAll(requiredSubscriptions); ComponentModelUtil.computeAsymmetricSetDifferences( requiredSubscriptions, activeSubscriptions, newSubscriptions, removedSubscriptions,set); if (exceededMaxSubscriptions(requiredSubscriptions, newSubscriptions)) return; SubscriptionManager manager = getSubscriptionManager(); if (manager != null) { for (FeedProvider feed:removedSubscriptions) { LOGGER.debug("removing subscription for {0}", feed.getSubscriptionId()); manager.unsubscribe(feed.getSubscriptionId()); activeFeeds.remove(feed); } List<String> newlyAddedSubscriptionIds = new ArrayList<String> (newSubscriptions.size()); for (FeedProvider feed:newSubscriptions) { LOGGER.debug("adding subscription for {0}", feed.getSubscriptionId()); newlyAddedSubscriptionIds.add(feed.getSubscriptionId()); activeFeeds.put(feed, feed.getTimeService().getCurrentTime()); } assert newlyAddedSubscriptionIds.size() == newSubscriptions.size(); if (!newlyAddedSubscriptionIds.isEmpty()) { manager.subscribe(newlyAddedSubscriptionIds.toArray(new String[newlyAddedSubscriptionIds.size()])); } activeSubscriptions = requiredSubscriptions; } else { LOGGER.warn("subscription manager not available, subscriptions not updated"); } }
4195698_13
protected static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (srcDir.exists() == false) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (srcDir.isDirectory() == false) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory // (see IO-141) List<String> exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if ((srcFiles != null) && (srcFiles.length > 0)) { exclusionList = new ArrayList<String>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); }
4214268_3
public static long bin2long(byte[] array, int offset) { return ((array[offset + 0] & 0xffL) << 56) + ((array[offset + 1] & 0xffL) << 48) + ((array[offset + 2] & 0xffL) << 40) + ((array[offset + 3] & 0xffL) << 32) + ((array[offset + 4] & 0xffL) << 24) + ((array[offset + 5] & 0xffL) << 16) + ((array[offset + 6] & 0xffL) << 8) + (array[offset + 7] & 0xffL); }
4233818_4
public DependencyA getDependencyA() { return dependencyA; }
4237245_15
public synchronized E elementAt(int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } return (E) elementData[index]; }
4238016_112
@Override public String getHtml(IMacroContext macroContext) { return "<span class=\"text-error\">{{" + macroContext.getMacroName() + "/}}</span>"; //$NON-NLS-1$ //$NON-NLS-2$ }
4242485_127
@Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BrowserOperatingSystemMapping other = (BrowserOperatingSystemMapping) obj; if (browserId != other.browserId) { return false; } if (operatingSystemId != other.operatingSystemId) { return false; } return true; }
4256066_0
@Override public Void convert(final HttpClientResponse response, final InputStream inputStream) throws IOException { switch(response.getStatusCode()) { case 201: case 204: LOG.debug("Return code is %d, finishing.", response.getStatusCode()); return null; case 200: try (final JsonParser jp = mapper.getFactory().createJsonParser(inputStream)) { expect(jp, jp.nextToken(), JsonToken.START_OBJECT); expect(jp, jp.nextToken(), JsonToken.FIELD_NAME); if (!"results".equals(jp.getCurrentName())) { throw new JsonParseException("expecting results field", jp.getCurrentLocation()); } expect(jp, jp.nextToken(), JsonToken.START_ARRAY); // As noted in a well-hidden comment in the MappingIterator constructor, // readValuesAs requires the parser to be positioned after the START_ARRAY // token with an empty current token jp.clearCurrentToken(); Iterator<T> iter = jp.readValuesAs(typeRef); while (iter.hasNext()) { try { callback.call(iter.next()); } catch (CallbackRefusedException e) { LOG.debug(e, "callback refused execution, finishing."); return null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Callback interrupted", e); } catch (Exception e) { Throwables.propagateIfPossible(e, IOException.class); throw new IOException("Callback failure", e); } } if (jp.nextValue() != JsonToken.VALUE_TRUE || !jp.getCurrentName().equals("success")) { throw new IOException("Streamed receive did not terminate normally; inspect server logs for cause."); } return null; } default: throw throwHttpResponseException(response); } }
4265123_11
public FieldDeclaration generateAttribute(Classifier clazz, AST ast, Property property) { Type type = property.getType(); logger.log(Level.FINE, "Class: " + clazz.getName() + " - " + "Property: " + property.getName() + " - " + "Property Upper: " + property.getUpper() + " - " + "Property Lower: " + property.getLower()); String umlTypeName = type.getName(); String umlQualifiedTypeName = type.getQualifiedName(); // Check whether primitive or array type or simple type? org.eclipse.jdt.core.dom.Type chosenType = jdtHelper.getChosenType(ast, umlTypeName, umlQualifiedTypeName, sourceDirectoryPackageName); VariableDeclarationFragment fragment = ast .newVariableDeclarationFragment(); SimpleName variableName = ast.newSimpleName(property.getName()); fragment.setName(variableName); FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(fragment); fieldDeclaration.setType(chosenType); EList<Comment> comments = property.getOwnedComments(); for (Comment comment : comments) { Javadoc javadoc = ast.newJavadoc(); generateJavadoc(ast, comment, javadoc); fieldDeclaration.setJavadoc(javadoc); } return fieldDeclaration; }
4265955_13
@Override public FeatureReader<SimpleFeatureType, SimpleFeature> getFeatureReader() throws IOException { return new CSVFeatureSource(this).getReader(); }
4276349_2
@Provides @Singleton AnnouncementConfig getAnnouncementConfig(final Config config) { final AnnouncementConfig baseConfig = config.getBean(AnnouncementConfig.class); return new AnnouncementConfig(baseConfig) { @Override public String getServiceName() { return ObjectUtils.toString(super.getServiceName(), serviceName); } @Override public String getServiceType() { return ObjectUtils.toString(super.getServiceType(), serviceType); } }; }
4276357_6
@Override public ThriftStructMetadata build() { // this code assumes that metadata is clean metadataErrors.throwIfHasErrors(); // builder constructor injection ThriftMethodInjection builderMethodInjection = buildBuilderConstructorInjections(); // constructor injection (or factory method for builder) ThriftConstructorInjection constructorInjections = buildConstructorInjection(); // fields injections Iterable<ThriftFieldMetadata> fieldsMetadata = buildFieldInjections(); // methods injections List<ThriftMethodInjection> methodInjections = buildMethodInjections(); return new ThriftStructMetadata( structName, extractStructIdlAnnotations(), structType, builderType, MetadataType.STRUCT, Optional.fromNullable(builderMethodInjection), ImmutableList.copyOf(documentation), ImmutableList.copyOf(fieldsMetadata), Optional.of(constructorInjections), methodInjections ); }
4288215_27
@Override public boolean logout() throws LoginException { LOG.debug("logout"); subject.getPrincipals().clear(); return true; }
4291387_17
void addOrChangeProperty(final String name, final Object newValue, final Configuration config) { // We do not want to abort the operation due to failed validation on one property try { if (!config.containsKey(name)) { logger.debug("adding property key [{}], value [{}]", name, newValue); config.addProperty(name, newValue); } else { Object oldValue = config.getProperty(name); if (newValue != null) { Object newValueArray; if (oldValue instanceof CopyOnWriteArrayList && AbstractConfiguration.getDefaultListDelimiter() != '\0'){ newValueArray = new CopyOnWriteArrayList(); Iterable<String> stringiterator = Splitter.on(AbstractConfiguration.getDefaultListDelimiter()).omitEmptyStrings().trimResults().split((String)newValue); for(String s :stringiterator){ ((CopyOnWriteArrayList) newValueArray).add(s); } } else { newValueArray = newValue; } if (!newValueArray.equals(oldValue)) { logger.debug("updating property key [{}], value [{}]", name, newValue); config.setProperty(name, newValue); } } else if (oldValue != null) { logger.debug("nulling out property key [{}]", name); config.setProperty(name, null); } } } catch (ValidationException e) { logger.warn("Validation failed for property " + name, e); } }
4298283_0
public static void initializeRGBChannels(Jp2_channels channels) throws KduException { final int numColours = 3; channels.Init(numColours); // channels.Set_colour_mapping(0, 0, 0); // channels.Set_colour_mapping(1, 0, 1); // channels.Set_colour_mapping(2, 0, 2); Method setColourMapping; Object[] args1; Object[] args2; Object[] args3; final int major = getKakaduJniMajorVersion(); try { if (major < 7) { setColourMapping = Jp2_channels.class.getMethod("Set_colour_mapping", int.class, int.class, int.class); //int _colour_idx, int _codestream_component, int _lut_idx args1 = new Object[] { 0, 0, 0 }; args2 = new Object[] { 1, 0, 1 }; args3 = new Object[] { 2, 0, 2 }; } else { setColourMapping = Jp2_channels.class.getMethod("Set_colour_mapping", int.class, int.class, int.class, int.class, int.class); //int _colour_idx, int _codestream_component, int _lut_idx, int _codestream_idx, int _data_format final int _codestream_idx = 0; final int _data_format = 0; args1 = new Object[] { 0, 0, 0, _codestream_idx, _data_format }; args2 = new Object[] { 1, 0, 1, _codestream_idx, _data_format }; args3 = new Object[] { 2, 0, 2, _codestream_idx, _data_format }; } } catch (NoSuchMethodException | SecurityException e) { throw new RuntimeException("Unable to acquire method Jp2_channels.Set_colour_mapping reflectively", e); } try { setColourMapping.invoke(channels, args1); setColourMapping.invoke(channels, args2); setColourMapping.invoke(channels, args3); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException("Error calling Jp2_channels.Set_colour_mapping(...)", e); } }
4298401_4
public static void clearCachedResources() { clientStaticResources.invalidateAll(); }
4298676_0
@Override @Transactional(readOnly = true) public List<Customer> findAll() { SQLQuery allCustomersQuery = qdslTemplate.newSqlQuery().from(qCustomer) .leftJoin(qCustomer._addressCustomerRef, qAddress); return qdslTemplate.query(allCustomersQuery, new CustomerListExtractor(), customerAddressProjection); }
4298816_47
public static void listFilesRecursive(File path, List<File> filesArray) { if (path.exists()) { File[] files = path.listFiles(); if (files == null) { Log.fatal("Could not list file " + path.toString() + " you may not have read permissions, skipping it"); Log.stderr("Could not list file " + path.toString() + " you may not have read permissions, skipping it"); } for (int i = 0; files != null && i < files.length; i++) { if (files[i].isDirectory()) { FileTools.listFilesRecursive(files[i], filesArray); } filesArray.add(files[i]); } } }
4300205_7
public List<SessionTicketKey> parse(File file) throws IOException { return parseBytes(Files.toByteArray(file)); }
4315362_26
@SuppressWarnings("unchecked") public <U> Try<U> flatMap(CheckedFunction<? super T, ? extends Try<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); if (isSuccess()) { try { return (Try<U>) mapper.apply(get()); } catch (Throwable t) { return failure(t); } } else { return (Try<U>) this; } }
4327427_3
@Override protected void runProcess() throws Exception { statusString.set("Starting thickness classifier..."); // Change to our process-specific logger log = LoggerFactory.getLogger(getClass().getName() + "." + ProcessManager.uidToString(getUID())); try { super.runProcess(); statusString.set("Completed successfully."); } catch (Exception e) { statusString.set(null); log.error("Error running model", e); throw e; } finally { // Clean up. stdout.finish(); String line; while ((line = stdout.readLine()) != null) { log.info(line); } stderr.finish(); while ((line = stderr.readLine()) != null) { log.warn(line); } } }
4335519_191
public ExpressionStack execute(ExpressionTree expression, ProgramStateConstraints constraints) { Deque<SymbolicValue> newStack = copy(); Kind kind = ((JavaScriptTree) expression).getKind(); switch (kind) { case LOGICAL_COMPLEMENT: SymbolicValue negatedValue = newStack.pop(); newStack.push(LogicalNotSymbolicValue.create(negatedValue)); break; case TYPEOF: newStack.push(new TypeOfSymbolicValue(newStack.pop())); break; case NEW_EXPRESSION: executeNewExpression((NewExpressionTree) expression, newStack); break; case SPREAD_ELEMENT: case VOID: case AWAIT: pop(newStack, 1); pushUnknown(newStack); break; case DELETE: pop(newStack, 1); newStack.push(new SymbolicValueWithConstraint(Constraint.BOOLEAN_PRIMITIVE)); break; case YIELD_EXPRESSION: if (((YieldExpressionTree) expression).argument() != null) { pop(newStack, 1); } pushUnknown(newStack); break; case BITWISE_COMPLEMENT: pop(newStack, 1); newStack.push(new SymbolicValueWithConstraint(Constraint.NUMBER_PRIMITIVE)); break; case CALL_EXPRESSION: executeCallExpression((CallExpressionTree) expression, newStack, constraints); break; case FUNCTION_EXPRESSION: case GENERATOR_FUNCTION_EXPRESSION: case ARROW_FUNCTION: newStack.push(new FunctionWithTreeSymbolicValue((FunctionTree) expression)); break; case THIS: case SUPER: case IMPORT: case NEW_TARGET: case JSX_SELF_CLOSING_ELEMENT: case JSX_STANDARD_ELEMENT: case JSX_SHORT_FRAGMENT_ELEMENT: case FLOW_CASTING_EXPRESSION: pushUnknown(newStack); break; case CLASS_EXPRESSION: newStack.push(new SymbolicValueWithConstraint(Constraint.OTHER_OBJECT)); break; case EXPONENT_ASSIGNMENT: case LEFT_SHIFT_ASSIGNMENT: case RIGHT_SHIFT_ASSIGNMENT: case UNSIGNED_RIGHT_SHIFT_ASSIGNMENT: case AND_ASSIGNMENT: case XOR_ASSIGNMENT: case OR_ASSIGNMENT: case TAGGED_TEMPLATE: case EXPONENT: pop(newStack, 2); pushUnknown(newStack); break; case RELATIONAL_IN: pop(newStack, 2); newStack.push(new SymbolicValueWithConstraint(Constraint.BOOLEAN_PRIMITIVE)); break; case INSTANCE_OF: SymbolicValue constructorValue = newStack.pop(); SymbolicValue objectValue = newStack.pop(); newStack.push(new InstanceOfSymbolicValue(objectValue, constructorValue)); break; case EQUAL_TO: case NOT_EQUAL_TO: case STRICT_EQUAL_TO: case STRICT_NOT_EQUAL_TO: case LESS_THAN: case GREATER_THAN: case LESS_THAN_OR_EQUAL_TO: case GREATER_THAN_OR_EQUAL_TO: SymbolicValue rightOperand = newStack.pop(); SymbolicValue leftOperand = newStack.pop(); newStack.push(RelationalSymbolicValue.create(kind, leftOperand, rightOperand)); break; case COMMA_OPERATOR: SymbolicValue commaResult = newStack.pop(); newStack.pop(); newStack.push(commaResult); break; case ASSIGNMENT: SymbolicValue assignedValue = newStack.pop(); newStack.pop(); newStack.push(assignedValue); break; case ARRAY_ASSIGNMENT_PATTERN: case OBJECT_ASSIGNMENT_PATTERN: newStack.push(UnknownSymbolicValue.UNKNOWN); break; case PLUS_ASSIGNMENT: case PLUS: case MINUS: case DIVIDE: case REMAINDER: case MULTIPLY: case MULTIPLY_ASSIGNMENT: case DIVIDE_ASSIGNMENT: case REMAINDER_ASSIGNMENT: case MINUS_ASSIGNMENT: case BITWISE_AND: case BITWISE_XOR: case BITWISE_OR: case LEFT_SHIFT: case RIGHT_SHIFT: case UNSIGNED_RIGHT_SHIFT: case POSTFIX_DECREMENT: case POSTFIX_INCREMENT: case PREFIX_DECREMENT: case PREFIX_INCREMENT: case UNARY_MINUS: case UNARY_PLUS: case PROPERTY_IDENTIFIER: case BINDING_IDENTIFIER: case CONDITIONAL_AND: case CONDITIONAL_OR: case CONDITIONAL_EXPRESSION: case IDENTIFIER_REFERENCE: case NULL_LITERAL: case NUMERIC_LITERAL: case STRING_LITERAL: case BOOLEAN_LITERAL: case REGULAR_EXPRESSION_LITERAL: case OBJECT_LITERAL: case ARRAY_LITERAL: case TEMPLATE_LITERAL: case BRACKET_MEMBER_EXPRESSION: case DOT_MEMBER_EXPRESSION: break; default: throw new IllegalArgumentException("Unexpected kind of expression to execute: " + kind); } return new ExpressionStack(newStack); }
4336113_33
@Override public AttributeType getType() { return NATSTUNAttributeType.NAT_BEHAVIOR; }
4338484_8
public static void strictAssertEquals(final InputStream dataset, final VaultConnection vault) { final Yaml yaml = new Yaml(); final Object load = yaml.load(dataset); if (areOnlySecrets(load)) { final List<Map<String, Map<String, Object>>> secrets = (List) load; checkSecretsRegisteredByTokens(secrets, vault); assertSecrets(secrets, vault); } }
4340532_4
public List<Accept> getAccepts() { return accepts; }
4341250_102
@Override public int getNumActiveInstances(ServiceEndPoint endPoint) { checkNotNull(endPoint); return _pool.getNumActive(endPoint); }
4346047_4
public void register(URL proxyUrl, Class<?> testClass, OperationalContext context) { if (urlToContext.get(proxyUrl) != null) { throw new IllegalStateException("The OperatiocalContext was already set for URL: " + proxyUrl); } urlToContext.put(proxyUrl, context); Set<URL> urls = testClassToUrls.get(testClass); if (urls == null) { urls = new LinkedHashSet<URL>(); testClassToUrls.put(testClass, urls); } urls.add(proxyUrl); }
4349381_5
public static List<Segment> parseSegments(InputStream in) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); Gson gson = new Gson(); return gson.fromJson(reader, new TypeToken<List<Segment>>() {}.getType()); } catch (UnsupportedEncodingException e) { return new ArrayList<Segment>(); } }
4353723_0
static List<String> splitInput(String input) { if (input.startsWith("{") && input.endsWith("}")) { // Assume we're using JSON IDs List<String> result = new ArrayList<String>(); int openBracket = 0; Integer lastStartIdx = null; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == '{') { openBracket++; if (lastStartIdx == null) { lastStartIdx = i; } } if (c == '}') { openBracket--; if (openBracket == 0) { String substring = input.substring(lastStartIdx, i + 1); result.add(substring); lastStartIdx = null; } } } return result; } return Arrays.asList(input.split(",")); }
4368712_128
@POST @Template(name = "/index.ftl") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Viewable create(@Valid @BeanParam FeedRequestBean request) { String[] urlArray = createUrls(request.getUrls()).stream().toArray(String[]::new); CombinedFeed feed = new CombinedFeed.CombinedFeedBuilder(null, urlArray) .title(request.getTitle()) .description(request.getDescription()) .refreshPeriod(request.getRefreshPeriod()).build(); feedService.save(feed); return new Viewable("/index.ftl", getModel()); }
4368907_40
@Override public void validate(String s) throws ValidationError { try { xv.validate(s); } catch (SAXParseException e) { final String name = e.getSystemId(); final String msg = e.getMessage(); final int line = e.getLineNumber(); final int column = e.getColumnNumber(); throw new ValidationError(name, msg, e, line, column); } catch (SAXException e) { // TODO This isn't the intended design here throw new RuntimeException(e); } catch (IOException e) { // TODO This isn't the intended design here throw new RuntimeException(e); } }
4376619_1
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if(!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory,targetFile); BufferedOutputStream dest = null; while(zis.getNextEntry() != null) { if(!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis,dest); dest.flush(); dest.close(); } zis.close(); if(!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
4387088_1
public static List<File> getBackupList(String bookUID) { File[] backupFiles = new File(getBackupFolderPath(bookUID)).listFiles(); Arrays.sort(backupFiles); List<File> backupFilesList = Arrays.asList(backupFiles); Collections.reverse(backupFilesList); return backupFilesList; }
4389698_31
@Override public int read(char[] cbuf, int off, int len) throws IOException { try { return reader.read(cbuf, off, len); } catch (IOException e) { return handleIOException(e); } }
4390160_3
public int getSize() { return array.length; }
4398263_37
public <RequestType extends ConversationsRequest> Request create(RequestType request) { if (request instanceof ReviewsRequest) { return createFromReviewRequest((ReviewsRequest) request); } else if (request instanceof QuestionAndAnswerRequest) { return createFromQuestionAndAnswerRequest((QuestionAndAnswerRequest) request); }else if (request instanceof ReviewHighlightsRequest) { return createFromReviewHighlightsRequest((ReviewHighlightsRequest) request); } else if (request instanceof CommentsRequest) { return createFromCommentsRequest((CommentsRequest) request); } else if (request instanceof AuthorsRequest) { return createFromAuthorsRequest((AuthorsRequest) request); } else if (request instanceof BulkStoreRequest) { return createFromBulkStoreRequest((BulkStoreRequest) request); } else if (request instanceof BulkRatingsRequest) { return createFromBulkRatingsRequest((BulkRatingsRequest) request); } else if (request instanceof StoreReviewsRequest) { return createFromStoreReviewsRequest((StoreReviewsRequest) request); } else if (request instanceof BulkProductRequest) { return createFromBulkProductRequest((BulkProductRequest) request); } else if (request instanceof ProductDisplayPageRequest) { return createFromProductDisplayPageRequest((ProductDisplayPageRequest) request); } else if (request instanceof FeedbackSubmissionRequest) { return createFromFeedbackSubmissionRequest((FeedbackSubmissionRequest) request); } else if (request instanceof ReviewSubmissionRequest) { return createFromReviewSubmissionRequest((ReviewSubmissionRequest) request); } else if (request instanceof StoreReviewSubmissionRequest) { return createFromStoreReviewSubmissionRequest((StoreReviewSubmissionRequest) request); } else if (request instanceof QuestionSubmissionRequest) { return createFromQuestionSubmissionRequest((QuestionSubmissionRequest) request); } else if (request instanceof AnswerSubmissionRequest) { return createFromAnswerSubmissionRequest((AnswerSubmissionRequest) request); } else if (request instanceof CommentSubmissionRequest) { return createFromCommentSubmissionRequest((CommentSubmissionRequest) request); } else if (request instanceof PhotoUploadRequest) { return createFromPhotoUploadRequest((PhotoUploadRequest) request); } else if (request instanceof UserAuthenticationStringRequest) { return createFromUserAuthenticationStringRequest((UserAuthenticationStringRequest) request); } else if (request instanceof InitiateSubmitRequest) { return createFromInitiateSubmitRequest((InitiateSubmitRequest) request); } else if(request instanceof ProgressiveSubmitRequest) { return createFromProgressiveSubmitRequest((ProgressiveSubmitRequest) request); } throw new IllegalStateException("Unknown request type: " + request.getClass().getCanonicalName()); }
4399205_10
void execute(String... args) throws SignerException, ParseException { DefaultParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help") || args.length == 0) { printHelp(); return; } SignerHelper helper = new SignerHelper(new StdOutConsole(1), "option"); setOption(PARAM_KEYSTORE, helper, cmd); setOption(PARAM_STOREPASS, helper, cmd); setOption(PARAM_STORETYPE, helper, cmd); setOption(PARAM_ALIAS, helper, cmd); setOption(PARAM_KEYPASS, helper, cmd); setOption(PARAM_KEYFILE, helper, cmd); setOption(PARAM_CERTFILE, helper, cmd); setOption(PARAM_ALG, helper, cmd); setOption(PARAM_TSAURL, helper, cmd); setOption(PARAM_TSMODE, helper, cmd); setOption(PARAM_TSRETRIES, helper, cmd); setOption(PARAM_TSRETRY_WAIT, helper, cmd); setOption(PARAM_NAME, helper, cmd); setOption(PARAM_URL, helper, cmd); setOption(PARAM_PROXY_URL, helper, cmd); setOption(PARAM_PROXY_USER, helper, cmd); setOption(PARAM_PROXY_PASS, helper, cmd); helper.replace(cmd.hasOption(PARAM_REPLACE)); setOption(PARAM_ENCODING, helper, cmd); File file = cmd.getArgList().isEmpty() ? null : new File(cmd.getArgList().get(0)); helper.sign(file); }
4406463_75
public void setXmlToParse(String xml) throws SAXException, IOException, ParserConfigurationException { // Create a parsable document out of the xml string DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); documentFactory.setNamespaceAware(false); DocumentBuilder builder = documentFactory.newDocumentBuilder(); xmlDocument = builder.parse(new ByteArrayInputStream(xml.getBytes())); }
4408504_1
public InChI generateInchi(IAtomContainer atc) throws IOException, CDKException { String workingDir=System.getProperty("user.dir")+ System.getProperty("file.separator"); return generateInchi(atc,workingDir); }
4416959_338
public boolean isRootClass() { return parentModel == null; }
4421246_0
@Override public QueryResult getResult() throws Exception { return this.getResult(false); }
4437408_1
@Override public String toString() { return "latitude: " + this.latitude + ", longitude: " + this.longitude; }
4449830_4
@Override public String toString() { return String.format("%s[%s (%s)]", getClass().getSimpleName(), getName(), getMRL()); }
4484894_1
public boolean setException(Throwable e) { return super.setException(e); }
4494450_40
public IParserNode getLastChild() { final IParserNode lastChild = getChild( numChildren() - 1 ); return lastChild != null && lastChild.numChildren() > 0 ? lastChild.getLastChild() : lastChild; }
4514536_390
public void saveNamedClusterRep( NamedCluster namedCluster, NamedClusterService namedClusterService, Repository rep, IMetaStore metaStore, ObjectId id_job, ObjectId objectId, LogChannelInterface logChannelInterface ) throws KettleException { if ( namedCluster != null ) { String namedClusterName = namedCluster.getName(); if ( !Const.isEmpty( namedClusterName ) ) { rep.saveJobEntryAttribute( id_job, objectId, CLUSTER_NAME, namedClusterName ); // $NON-NLS-1$ } try { if ( !StringUtils.isEmpty( namedClusterName ) && namedClusterService.contains( namedClusterName, metaStore ) ) { // pull config from NamedCluster namedCluster = namedClusterService.read( namedClusterName, metaStore ); } } catch ( MetaStoreException e ) { logChannelInterface.logDebug( e.getMessage(), e ); } rep.saveJobEntryAttribute( id_job, objectId, HDFS_HOSTNAME, namedCluster.getHdfsHost() ); // $NON-NLS-1$ rep.saveJobEntryAttribute( id_job, objectId, HDFS_PORT, namedCluster.getHdfsPort() ); // $NON-NLS-1$ rep.saveJobEntryAttribute( id_job, objectId, JOB_TRACKER_HOSTNAME, namedCluster.getJobTrackerHost() ); // $NON-NLS-1$ rep.saveJobEntryAttribute( id_job, objectId, JOB_TRACKER_PORT, namedCluster.getJobTrackerPort() ); // $NON-NLS-1$ } }
4522462_26
public static AbstractResource createResource(Class<?> resourceClass) { final Class<?> annotatedResourceClass = getAnnotatedResourceClass(resourceClass); final Path rPathAnnotation = annotatedResourceClass.getAnnotation(Path.class); final boolean isRootResourceClass = (null != rPathAnnotation); final boolean isEncodedAnotOnClass = (null != annotatedResourceClass.getAnnotation(Encoded.class)); AbstractResource resource; if (isRootResourceClass) { resource = new AbstractResource(resourceClass, new PathValue(rPathAnnotation.value())); } else { // just a subresource class resource = new AbstractResource(resourceClass); } workOutConstructorsList(resource, resourceClass.getConstructors(), isEncodedAnotOnClass); workOutFieldsList(resource, isEncodedAnotOnClass); final MethodList methodList = new MethodList(resourceClass); workOutSetterMethodsList(resource, methodList, isEncodedAnotOnClass); final Consumes classScopeConsumesAnnotation = annotatedResourceClass.getAnnotation(Consumes.class); final Produces classScopeProducesAnnotation = annotatedResourceClass.getAnnotation(Produces.class); workOutResourceMethodsList(resource, methodList, isEncodedAnotOnClass, classScopeConsumesAnnotation, classScopeProducesAnnotation); workOutSubResourceMethodsList(resource, methodList, isEncodedAnotOnClass, classScopeConsumesAnnotation, classScopeProducesAnnotation); workOutSubResourceLocatorsList(resource, methodList, isEncodedAnotOnClass); workOutPostConstructPreDestroy(resource); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest(ImplMessages.NEW_AR_CREATED_BY_INTROSPECTION_MODELER( resource.toString())); } return resource; }
4536629_11
@Override public AuthenticatedPrincipal authenticate(String username, String password) { ResourceOwner user = resourceOwnerRepository.findByUsername(username); if (user == null) { return null; } // Validate password if (!user.checkPassword(password)) { return null; } return new AuthenticatedPrincipal(username); }
4541580_83
public static String wordWrap(final String value, final int len) { if (len < 0 || value.length() <= len) return value; BreakIterator bi = BreakIterator.getWordInstance(currentLocale()); bi.setText(value); return value.substring(0, bi.following(len)); }
4544259_1
@Override public void updateBundleRepositoryDescriptor(String name) throws Exception { if (repositories.get(name) == null) { throw new IllegalArgumentException("Repository " + name + " doesn't exist"); } if (repositories.get(name).getLocation() != null && !repositories.get(name).getLocation().isEmpty()) { Path bundleRepositoryXmlPath = Paths.get(repositories.get(name).getLocation()).resolve("repository.xml"); BundleRepository bundleRepository = new BundleRepository(bundleRepositoryXmlPath.toUri().toString(), name); if (!Files.exists(bundleRepositoryXmlPath)) { // init the repository XML try (Writer writer = Files.newBufferedWriter(bundleRepositoryXmlPath, StandardCharsets.UTF_8)) { bundleRepository.writeRepository(writer); } } List<Resource> resources = new ArrayList<>(); updateBundleRepositoryDescriptor(new File(repositories.get(name).getLocation()), resources, repositories.get(name).getLocation()); addResources(bundleRepository, resources); } }
4544982_100
@Nullable public Symbol getSymbol(String name, Kind... kinds) { List<Kind> kindList = Arrays.asList(kinds); List<Symbol> result = new ArrayList<>(); for (Symbol s : symbols) { if (s.called(name)) { if (kindList.isEmpty() || kindList.contains(s.kind())) { result.add(s); } else if (s.is(Kind.PARAMETER) && kindList.equals(Collections.singletonList(Kind.VARIABLE))) { // parameter of a child scope shadows variable of the outer scope return null; } } } if (result.isEmpty()) { if (superClassScope != null) { return superClassScope.getSymbol(name, kinds); } else if (captureOuterScope) { return outer.getSymbol(name, kinds); } } return result.size() == 1 ? result.get(0) : null; }
4546290_35
@Override public void beforeUpdate(Record record, Record originalRecord, Repository repository, FieldTypes fieldTypes, RecordEvent recordEvent) throws RepositoryException, InterruptedException { Collection<IndexInfo> indexInfos = indexesInfo.getIndexInfos(); if (indexInfos.size() > 0) { TypeManager typeMgr = repository.getTypeManager(); RecordEvent.IndexRecordFilterData idxSel = new RecordEvent.IndexRecordFilterData(); recordEvent.setIndexRecordFilterData(idxSel); idxSel.setOldRecordExists(true); idxSel.setNewRecordExists(true); if (indexesInfo.getRecordFilterDependsOnRecordType()) { // Because record type names can change, this is not guaranteed to be the same as what gets // stored in the repo, but that doesn't matter as it is only for indexing purposes. SchemaId oldRecordTypeId = typeMgr.getRecordTypeByName(originalRecord.getRecordTypeName(), null).getId(); idxSel.setOldRecordType(oldRecordTypeId); // on update, specifying record type is optional idxSel.setNewRecordType(record.getRecordTypeName() != null ? typeMgr.getRecordTypeByName(record.getRecordTypeName(), null).getId() : oldRecordTypeId); } Set<QName> names = indexesInfo.getRecordFilterFieldDependencies(); for (QName name : names) { Object oldValue = null, newValue = null; if (record.hasField(name)) { newValue = record.getField(name); } if (originalRecord.hasField(name)) { oldValue = originalRecord.getField(name); } if (oldValue != null || newValue != null) { FieldType type = fieldTypes.getFieldType(name); addField(type, oldValue, newValue, idxSel); } } calculateIndexInclusion(repository.getRepositoryName(), recordEvent.getTableName(), originalRecord, record, idxSel); } }
4546424_51
@GET @Path (REST_API_VIDEOS) @Produces (MediaType.APPLICATION_JSON) public Response findVideos() { if (isDebugEnabled) { S_LOGGER.debug("Entered into AdminService.findVideos()"); } try { List<VideoInfo> videoList = mongoOperation.getCollection(VIDEOS_COLLECTION_NAME , VideoInfo.class); if (videoList != null) { return Response.status(Response.Status.OK).entity(videoList).build(); } } catch (Exception e) { throw new PhrescoWebServiceException(e, EX_PHEX00005, VIDEOS_COLLECTION_NAME); } return Response.status(Response.Status.OK).entity(ERROR_MSG_NOT_FOUND).build(); }
4570530_3
public boolean areThereImportsWithoutExports() { boolean allImportsHaveExports = false; for (String importedBeanName : imports.keySet()) { if (!exports.containsKey(importedBeanName)) { allImportsHaveExports = true; String location = imports.get(importedBeanName).get(0).getLocation(); log.error("Import without export was found. Bean: {} location: {}", importedBeanName, location); } } return allImportsHaveExports; }
4576305_28
@Override public CheckResult check() { try { start(); CheckResult failure = connection.failure.get(); if (failure != null) return failure; return CheckResult.OK; } catch (Throwable e) { Call.propagateIfFatal(e); return CheckResult.failed(e); } }
4581618_0
public static IType removeQualifiers(IType type) { while (type instanceof IQualifierType) { type = ((IQualifierType) type).getType(); } return type; }
4586516_11
@Override public Response toResponse(NotAuthorizedException exception) { return getDefaultBuilder(exception, Response.Status.UNAUTHORIZED, determineBestMediaType()).build(); }
4597158_1
public static <V, E> double clusteringCoefficient(Graph<V, E> graph) { long numPaths = 0, numClosed = 0; List<V> path = new ArrayList<V>(2); for(V one : graph.getVertices()) { path.clear(); path.add(null); path.add(null); path.add(null); path.set(0, one); for(V two : graph.getNeighbors(one)) { path.set(1, two); for(V three : graph.getNeighbors(two)) { if(!three.equals(one)) { path.set(2, three); numPaths ++; if(graph.isNeighbor(one, three)) numClosed++; } } } } return numClosed / (double) numPaths; }
4597760_91
@Override public FileContent getContent() throws FileSystemException { return new DecoratedFileContent( super.getContent() ) { @Override public InputStream getInputStream() throws FileSystemException { return annotator.getInputStream( super.getInputStream(), annotationsFile.getContent().getInputStream() ); } }; }
4600110_2
public static FsSettings fromJson(String json) throws IOException { return prettyMapper.readValue(json, FsSettings.class); }
4603135_103
public void publish(String subject, java.util.List<? extends java.io.Serializable> events) throws Exception { publish(subject, new EventList(events)); }
4604367_49
public NestedAxis(final Axis parentAxis, final Axis childAxis) { super(parentAxis.getCursor()); mParentAxis = checkNotNull(parentAxis); mChildAxis = checkNotNull(childAxis); mIsFirst = true; }
4605969_0
public static Point2D.Double convertToLatLon(double x, double y) { return convertToLatLon(x, y, new Point2D.Double()); }
4606342_196
public static boolean runSPOnSingleVM(NodeEntity node, Callable<Void> call) { if (node.getMoId() == null) { logger.info("VC vm does not exist for node: " + node.getVmName()); return false; } VcVirtualMachine vcVm = VcCache.getIgnoreMissing(node.getMoId()); if (vcVm == null) { // cannot find VM logger.info("VC vm does not exist for node: " + node.getVmName()); return false; } @SuppressWarnings("unchecked") Callable<Void>[] storeProceduresArray = new Callable[1]; storeProceduresArray[0] = call; NoProgressUpdateCallback callback = new NoProgressUpdateCallback(); try { ExecutionResult[] result = Scheduler .executeStoredProcedures( com.vmware.aurora.composition.concurrent.Priority.BACKGROUND, storeProceduresArray, callback); if (result == null) { logger.error("No result from composition layer"); return false; } else { if (result[0].finished && result[0].throwable == null) { logger.info("successfully run operation on vm for node: " + node.getVmName()); return true; } else { String message = result[0].throwable.getMessage(); throw BddException.VC_EXCEPTION(result[0].throwable, message); } } } catch (InterruptedException e) { logger.error("error in executing store procedure on single node " + node.getVmName(), e); throw BddException.INTERNAL(e, e.getMessage()); } }
4610430_20
@Override public String getReverseRoute( Class<?> controllerClass, String controllerMethodName) { Optional<Map<String, Object>> parameterMap = Optional.empty(); return getReverseRoute(controllerClass, controllerMethodName, parameterMap); }
4614129_29
@Override public CardApplicationDisconnectResponse cardApplicationDisconnect(CardApplicationDisconnect request) { dApplicationDisconnectResponse response = WSHelper.makeResponse(CardApplicationDisconnectResponse.class, Helper.makeResultOK()); { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] slotHandle = connectionHandle.getSlotHandle(); // check existence of required parameters if (slotHandle == null) { turn WSHelper.makeResponse(CardApplicationDisconnectResponse.class, SHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, "ConnectionHandle is null")); } Disconnect disconnect = new Disconnect(); disconnect.setSlotHandle(slotHandle); if (request.getAction() != null) { sconnect.setAction(request.getAction()); } // remove entries associated with this handle states.removeSlotHandleEntry(connectionHandle.getContextHandle(), slotHandle); DisconnectResponse disconnectResponse = (DisconnectResponse) env.getDispatcher().safeDeliver(disconnect); response.setResult(disconnectResponse.getResult()); atch (ECardException e) { response.setResult(e.getResult()); atch (Exception e) { LOG.error(e.getMessage(), e); throwThreadKillException(e); response.setResult(WSHelper.makeResult(e)); urn response; }
4624158_14
public SuccessResponse escalateAlert(String identifier, EscalateAlertToNextRequest body, String identifierType) throws ApiException { Object localVarPostBody = body; // verify the required parameter 'identifier' is set if (identifier == null) { throw new ApiException(400, "Missing the required parameter 'identifier' when calling escalateAlert"); } // verify the required parameter 'body' is set if (body == null) { throw new ApiException(400, "Missing the required parameter 'body' when calling escalateAlert"); } // create path and map variables String localVarPath = "/v2/alerts/{identifier}/escalate" .replaceAll("\\{" + "identifier" + "\\}", apiClient.escapeString(identifier.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); localVarQueryParams.addAll(apiClient.parameterToPairs("", "identifierType", identifierType)); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[]{"GenieKey"}; GenericType<SuccessResponse> localVarReturnType = new GenericType<SuccessResponse>() { }; return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); }
4643211_0
public CountTimestampSamplesWritable(long count, long epochMilliseconds, List<Long> samples) { this.countTimestampWritable = new CountTimestampWritable(count, epochMilliseconds); this.samples = samples; }
4646950_7
public MutableCapabilities getCapabilities() { sauceOptions = getSauceOptions(); setBrowserOptions(browserName); capabilities.setCapability(sauceOptionsTag, sauceOptions); capabilities.setCapability(CapabilityType.BROWSER_NAME, browserName); capabilities.setCapability(CapabilityType.PLATFORM_NAME, operatingSystem); capabilities.setCapability(CapabilityType.BROWSER_VERSION, browserVersion); return capabilities; }
4653065_0
public static byte[] getMessageWithUdhInBytes(String s, byte dataCoding) { final int udhLength = ((byte)s.charAt(0))+1; final byte[] udh = s.substring(0, udhLength).getBytes(); final byte[] content = DataCodingSpecification.getMessageInBytes(s.substring(udhLength), dataCoding); final byte[] contentWithUdh = new byte[udhLength + content.length]; System.arraycopy(udh, 0, contentWithUdh, 0, udhLength); System.arraycopy(content, 0, contentWithUdh, udhLength, content.length); return contentWithUdh; }
4664478_9
public void afterProjectsRead(final MavenSession session) throws MavenExecutionException { try { final int totalModules = session.getProjects().size(); logger.info("Inspecting build with total of " + totalModules + " modules..."); int stagingGoalsFoundInModules = 0; // check do we need to do anything at all? // should not find any nexus-staging-maven-plugin deploy goal executions in any project // otherwise, assume it's "manually done" for (MavenProject project : session.getProjects()) { final Plugin nexusMavenPlugin = getBuildPluginsNexusMavenPlugin(project.getModel()); if (nexusMavenPlugin != null) { if (!nexusMavenPlugin.getExecutions().isEmpty()) { for (PluginExecution pluginExecution : nexusMavenPlugin.getExecutions()) { final List<String> goals = pluginExecution.getGoals(); if (goals.contains("deploy") || goals.contains("deploy-staged") || goals.contains("staging-close") || goals.contains("staging-release") || goals.contains("staging-promote")) { stagingGoalsFoundInModules++; break; } } } } } if (stagingGoalsFoundInModules > 0) { logger.info("Not installing Nexus Staging features:"); if (stagingGoalsFoundInModules > 0) { logger.info(" * Preexisting staging related goal bindings found in " + stagingGoalsFoundInModules + " modules."); } return; } logger.info("Installing Nexus Staging features:"); // make maven-deploy-plugin to be skipped and install us instead int skipped = 0; for (MavenProject project : session.getProjects()) { final Plugin nexusMavenPlugin = getBuildPluginsNexusMavenPlugin(project.getModel()); if (nexusMavenPlugin != null) { // skip the maven-deploy-plugin final Plugin mavenDeployPlugin = getBuildPluginsMavenDeployPlugin(project.getModel()); if (mavenDeployPlugin != null) { // TODO: better would be to remove them targeted? // But this mojo has only 3 goals, but only one of them is usable in builds ("deploy") mavenDeployPlugin.getExecutions().clear(); // add executions to nexus-staging-maven-plugin final PluginExecution execution = new PluginExecution(); execution.setId("injected-nexus-deploy"); execution.getGoals().add("deploy"); execution.setPhase("deploy"); execution.setConfiguration(nexusMavenPlugin.getConfiguration()); nexusMavenPlugin.getExecutions().add(execution); // count this in skipped++; } } } if (skipped > 0) { logger.info(" ... total of " + skipped + " executions of maven-deploy-plugin replaced with " + getPluginArtifactId()); } } catch (IllegalStateException e) { // thrown by getPluginByGAFromContainer throw new MavenExecutionException(e.getMessage(), e); } }
4665987_17
@Override public void updated(final String pid, final Dictionary config) throws ConfigurationException { deleted(pid); if (config == null) { return; } Dictionary<String, Object> loadedConfig = externalConfigLoader.resolve(config); String seFilter = getStringEncryptorFilter(loadedConfig); String dsfFilter = getDSFFilter(loadedConfig); String pdsfFilter = getPooledDSFFilter(loadedConfig); String phFilter = getPreHookFilter(loadedConfig); ServiceTrackerHelper helper = ServiceTrackerHelper.helper(context); ServiceTracker<?, ?> tracker; if (Objects.nonNull(pdsfFilter)) { tracker = helper.track(StringEncryptor.class, seFilter, se -> helper.track(PooledDataSourceFactory.class, pdsfFilter, pdsf -> helper.track(PreHook.class, phFilter, ph -> helper.track(DataSourceFactory.class, dsfFilter, dsf -> new DataSourceRegistration(context, new PoolingWrapper(pdsf, dsf), loadedConfig, new Decryptor(se).decrypt(loadedConfig), ph), DataSourceRegistration::close)))); } else { tracker = helper.track(StringEncryptor.class, seFilter, se -> helper.track(PreHook.class, phFilter, ph -> helper.track(DataSourceFactory.class, dsfFilter, dsf -> new DataSourceRegistration(context, dsf, loadedConfig, new Decryptor(se).decrypt(loadedConfig), ph), DataSourceRegistration::close))); } trackers.put(pid, tracker); }
4668183_0
@Nonnull public T get(String id) throws IllegalArgumentException { T t = map.get(id); if (t == null) { throw new IllegalArgumentException("Unknown id <" + id + ">"); } return t; }