id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
---|---|
3430789_14 | public Namespace child(List<String> values) {
ImmutableList<String> child = ImmutableList.<String>builder().addAll(this.values).addAll(values).build();
return Namespace.of(child);
} |
3432124_28 | @Override
lic final int compareTo(
final XTime<F> other)
{
LOGGER.trace("begin {}.compareTo({})", new Object[] {
getClass().getSimpleName(), other });
final int rval;
if (other == null)
{
throw new NullPointerException("cannot compare to a null");
}
rval = new CompareToBuilder() //
.append(_tick, other.getTick()) //
.append(_phase, other.getPhase()) //
.toComparison();
LOGGER.trace("will return: {}", rval);
LOGGER.trace("end {}.compareTo()", getClass().getSimpleName());
return rval;
} |
3433581_0 | public static void loadAll() {
for (AvailableFonts f : AvailableFonts.values()) {
load(f);
}
} |
3438153_3 | public SCIMConfig buildConfigFromInputStream(InputStream inStream) throws CharonException {
try {
StAXOMBuilder omBuilder = new StAXOMBuilder(inStream);
OMElement rootElement = omBuilder.getDocumentElement();
if (inStream != null) {
inStream.close();
}
return buildConfigFromRootElement(rootElement);
} catch (XMLStreamException e) {
throw new CharonException("Error in building the configuration file: " +
SCIMConfigConstants.PROVISIONING_CONFIG_NAME);
} catch (IOException e) {
throw new CharonException("Error in closing the input stream.");
}
} |
3440013_1 | public EpsilonNetwork(){
nodeSelector = new NodeSelector();
network = new Network();
/ processedTriples = Collections.synchronizedList(new ArrayList<Triple>());
processedTriples = new ArrayList<Triple>();
gcTokens = new Hashtable <Triple, List<Token>> ();
} |
3443799_38 | public void checkout(Cart cart, PaymentDetails paymentDetails, boolean notifyCustomer)
{
if (paymentDetails.paymentMethod == PaymentMethod.CreditCard) chargeCard(paymentDetails, cart);
reserveInventory(cart);
if (notifyCustomer) notifyCustomer(cart);
} |
3444675_9 | protected String buildScopeString() {
StringBuilder sb = new StringBuilder();
if (scope.contains(Scope.FLATTR )) sb.append(" flattr");
if (scope.contains(Scope.THING )) sb.append(" thing");
if (scope.contains(Scope.EMAIL )) sb.append(" email");
if (scope.contains(Scope.EXTENDEDREAD)) sb.append(" extendedread");
return sb.toString().trim();
} |
3447638_7 | @Override
public FieldMapping createFieldMapping(EntitySchemaFactory schemaFactory,
Class<?> entityType, String csvFieldName, String objFieldName,
Class<?> objFieldType, boolean required) {
return new DateTimeFieldMapping(entityType, csvFieldName, objFieldName,
required);
} |
3449807_27 | public List<VertexClass> sort() // toplogical sort
{
while (numVerts > 0) // while vertices remain,
{
// get a vertex with no successors, or -1
int currentVertex = noSuccessors();
if (currentVertex == -1) // must be a cycle
{
throw new IllegalStateException("BuildTypes have a cyclical dependencies");
}
// insert vertex label in sorted array (start at end)
sortedArray[numVerts - 1] = vertices[currentVertex];
deleteVertex(currentVertex); // delete vertex
}
ArrayList<VertexClass> result = newArrayList();
for (Vertex vertex : sortedArray)
//noinspection unchecked
result.add((VertexClass) vertex);
return result;
} |
3452904_920 | @Override
public void audit(String principal, String category, String message, SoapEdgeContext properties) {
AuditEvent event = new AuditEvent(category, message);
if (properties == null) {
getAuditor().audit(principal, event);
} else {
getAuditor().audit(principal, event, getContexts(properties));
}
} |
3454599_2 | public static List<String> split(String str, String separator) {
if (str == null) {
throw new IllegalArgumentException("cannot split null string");
}
if (separator == null) {
throw new IllegalArgumentException("separator cannot be null");
}
if (separator.isEmpty()) {
throw new IllegalArgumentException("separator cannot be an empty string");
}
return Arrays.asList(str.split(Pattern.quote(separator)));
} |
3456296_4 | @Override
public ValueResult resolve(MethodParameter methodParameter, List<String> wordsBuffer) {
String prefix = prefixForMethod(methodParameter.getMethod());
List<String> words = wordsBuffer.stream().filter(w -> !w.isEmpty()).collect(Collectors.toList());
CacheKey cacheKey = new CacheKey(methodParameter.getMethod(), wordsBuffer);
parameterCache.clear();
Map<Parameter, ParameterRawValue> resolved = parameterCache.computeIfAbsent(cacheKey, (k) -> {
Map<Parameter, ParameterRawValue> result = new HashMap<>();
Map<String, String> namedParameters = new HashMap<>();
// index of words that haven't yet been used to resolve parameter values
List<Integer> unusedWords = new ArrayList<>();
Set<String> possibleKeys = gatherAllPossibleKeys(methodParameter.getMethod());
// First, resolve all parameters passed by-name
for (int i = 0; i < words.size(); i++) {
int from = i;
String word = words.get(i);
if (possibleKeys.contains(word)) {
String key = word;
Parameter parameter = lookupParameterForKey(methodParameter.getMethod(), key);
int arity = getArity(parameter);
if (i + 1 + arity > words.size()) {
String input = words.subList(i, words.size()).stream().collect(Collectors.joining(" "));
throw new UnfinishedParameterResolutionException(
describe(Utils.createMethodParameter(parameter)).findFirst().get(), input);
}
Assert.isTrue(i + 1 + arity <= words.size(),
String.format("Not enough input for parameter '%s'", word));
String raw = words.subList(i + 1, i + 1 + arity).stream().collect(Collectors.joining(","));
Assert.isTrue(!namedParameters.containsKey(key),
String.format("Parameter for '%s' has already been specified", word));
namedParameters.put(key, raw);
if (arity == 0) {
boolean defaultValue = booleanDefaultValue(parameter);
// Boolean parameter has been specified. Use the opposite of the default value
result.put(parameter,
ParameterRawValue.explicit(String.valueOf(!defaultValue), key, from, from));
}
else {
i += arity;
result.put(parameter, ParameterRawValue.explicit(raw, key, from, i));
}
} // store for later processing of positional params
else {
unusedWords.add(i);
}
}
// Now have a second pass over params and treat them as positional
int offset = 0;
Parameter[] parameters = methodParameter.getMethod().getParameters();
for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
Parameter parameter = parameters[i];
// Compute the intersection between possible keys for the param and what we've already
// seen for named params
Collection<String> keys = getKeysForParameter(methodParameter.getMethod(), i)
.collect(Collectors.toSet());
Collection<String> copy = new HashSet<>(keys);
copy.retainAll(namedParameters.keySet());
if (copy.isEmpty()) { // Was not set via a key (including aliases), must be positional
int arity = getArity(parameter);
if (arity > 0 && (offset + arity) <= unusedWords.size()) {
String raw = unusedWords.subList(offset, offset + arity).stream()
.map(index -> words.get(index))
.collect(Collectors.joining(","));
int from = unusedWords.get(offset);
int to = from + arity - 1;
result.put(parameter, ParameterRawValue.explicit(raw, null, from, to));
offset += arity;
} // No more input. Try defaultValues
else {
Optional<String> defaultValue = defaultValueFor(parameter);
defaultValue.ifPresent(
value -> result.put(parameter, ParameterRawValue.implicit(value, null, null, null)));
}
}
else if (copy.size() > 1) {
throw new IllegalArgumentException(
"Named parameter has been specified multiple times via " + quote(copy));
}
}
Assert.isTrue(offset == unusedWords.size(),
"Too many arguments: the following could not be mapped to parameters: "
+ unusedWords.subList(offset, unusedWords.size()).stream()
.map(index -> words.get(index)).collect(Collectors.joining(" ", "'", "'")));
return result;
});
Parameter param = methodParameter.getMethod().getParameters()[methodParameter.getParameterIndex()];
if (!resolved.containsKey(param)) {
throw new ParameterMissingResolutionException(describe(methodParameter).findFirst().get());
}
ParameterRawValue parameterRawValue = resolved.get(param);
Object value = convertRawValue(parameterRawValue, methodParameter);
BitSet wordsUsed = getWordsUsed(parameterRawValue);
BitSet wordsUsedForValue = getWordsUsedForValue(parameterRawValue);
return new ValueResult(methodParameter, value, wordsUsed, wordsUsedForValue);
} |
3460824_46 | public static <T extends Enum<T>> Pattern createValidationPatternFromEnumType(Class<T> enumType) {
String regEx = Stream.of(enumType.getEnumConstants())
.map(Enum::name)
.collect(Collectors.joining("|", "(?i)", ""));
//Enum constants may contain $ which needs to be escaped
regEx = regEx.replace("$", "\\$");
return Pattern.compile(regEx);
} |
3468420_206 | @Override
public void addObjectAt(RoadUser obj, Point pos) {
if (obj instanceof MovingRoadUser) {
checkArgument(!isOccupied(pos),
"Cannot add an object on an occupied position: %s.", pos);
blockingRegistry.addAt((MovingRoadUser) obj, pos);
}
super.addObjectAt(obj, pos);
} |
3471752_7 | @NotNull
public static String computeSha256Hash(@NotNull final byte[] bytes) throws NoSuchAlgorithmException {
return computeHash(bytes, "SHA-256");
} |
3472718_65 | @Override
; |
3477759_76 | @RequestMapping(params = "resume", method = RequestMethod.GET)
public String resumeGame(Model model) {
timerService.resume();
return getAdminPage(model);
} |
3510405_18 | public void setFullUrl(String fullUrl) {
this.fullUrl = fullUrl;
} |
3513191_127 | public ReportData getDetailedReportData(ReportCriteria reportCriteria) {
return getReportData(reportCriteria);
} |
3513261_56 | public String getProvisioningProfile()
{
return getSettings().getAllSettings().get(Settings.ManagedSetting.PROVISIONING_PROFILE.name());
} |
3523632_78 | public static int hashCode(Object... objects) {
return Arrays.hashCode(objects);
} |
3526892_12 | static public Double calculateLabelCost(String calcLabel,
Map<String, Double> labelProbabilities, CostMatrix<String> costMatrix) {
if (calcLabel == null) {
return Double.NaN;
}
double sum = 0.;
for (String label: costMatrix.getKnownValues()) {
double cost = costMatrix.getCost(label, calcLabel);
double prob = labelProbabilities.get(label);
sum += cost * prob;
}
return sum;
} |
3536819_44 | @Nullable
@Override
public Object getPropertyUnchecked(@NotNull String name) {
try {
return getProperty(name);
} catch (Exception e) {
return null;
}
} |
3548254_1 | public static String convertToWktString(Geoshape fieldValue) throws BackendException {
if (fieldValue.getType() == Geoshape.Type.POINT) {
Geoshape.Point point = fieldValue.getPoint();
return "POINT(" + point.getLongitude() + " " + point.getLatitude() + ")";
} else {
throw new PermanentBackendException("Cannot index " + fieldValue.getType());
}
} |
3551455_26 | public static <T> Function<List<T>, T> firstOfList() {
return list -> list.get(0);
} |
3555504_32 | public byte[] getBuffer() {
int length = getUnsignedInt();
if (pointer + length > data.length) {
throw new IndexOutOfBoundsException("Not enough data");
}
if (length == 0) {
return new byte[0];
}
if (length == -1) {
return null;
}
byte[] ret = Helper.copyOfRange(data, pointer, pointer + length);
pointer += length;
return ret;
} |
3570915_4 | public static int[] parseToHourAndMinutes(final String timeString) throws ParseException {
String time = timeString;
time = Strings.nullToEmpty(time).trim();
if (time.length() == 0) {
throw new ParseException("String is empty", 1);
}
time = normalize(time);
String[] splitted = time.split(":");
if (splitted.length != 2) {
throw new ParseException("String '" + timeString + "' has an unsupported format", 1);
} else {
int[] result = new int[2];
for (int i = 0; i < 2; i++) {
result[i] = Integer.parseInt(splitted[i]);
}
return result;
}
} |
3580492_6 | public void nextCycle() throws GameOfLifeException {
// We initialize the next state as a x + 1, y + 1 of current state
// We do this so next cells can be born around past state
emptyMatrix(auxMatrix, MAX_X, MAX_Y);
for(int i = 0; i < MAX_X; i++) {
for(int j = 0; j < MAX_Y; j++) {
if(matrix[i][j] == 1) {
if(i >= MAX_X - 2 || j >= MAX_Y - 2) {
throw new GameOfLifeException(CauseMessage.GRID_OVERFLOW, states.size(),
"Current state can't be evolved further with a " + MAX_X + "x" + MAX_Y + " grid.");
}
auxMatrix[i + 1][j + 1] = 1;
}
}
}
for(int i = 0; i < MAX_X; i++) {
for(int j = 0; j < MAX_Y; j++) {
matrix[i][j] = auxMatrix[i][j];
auxMatrix[i][j] = 0;
}
}
// Next we calculate whether some cells die or are born
for(int i = 0; i < MAX_X; i++) {
for(int j = 0; j < MAX_Y; j++) {
int nNeighbors = 0;
if(i > 0 && matrix[i - 1][j] == 1) {
nNeighbors++;
}
if(i > 0 && j > 0 && matrix[i - 1][j - 1] == 1) {
nNeighbors++;
}
if(i > 0 && j < MAX_Y - 1 && matrix[i - 1][j + 1] == 1) {
nNeighbors++;
}
if(j > 0 && matrix[i][j - 1] == 1) {
nNeighbors++;
}
if(j < MAX_Y - 1 && matrix[i][j + 1] == 1) {
nNeighbors++;
}
if(i < MAX_X - 1 && j > 0 && matrix[i + 1][j - 1] == 1) {
nNeighbors++;
}
if(i < MAX_X - 1 && matrix[i + 1][j] == 1) {
nNeighbors++;
}
if(i < MAX_X - 1 && j < MAX_Y - 1 && matrix[i + 1][j + 1] == 1) {
nNeighbors++;
}
if(matrix[i][j] == 1) {
if(nNeighbors < 2 || nNeighbors > 3) {
auxMatrix[i][j] = 0;
} else {
auxMatrix[i][j] = 1;
}
} else {
if(nNeighbors == 3) {
auxMatrix[i][j] = 1;
} else {
auxMatrix[i][j] = 0;
}
}
}
}
// Substitute current state with next state
int nAlives = 0;
for(int i = 0; i < MAX_X; i++) {
for(int j = 0; j < MAX_Y; j++) {
matrix[i][j] = auxMatrix[i][j];
if(matrix[i][j] == 1) {
nAlives++;
}
}
}
if(nAlives == 0) {
throw new GameOfLifeException(CauseMessage.NO_ALIVE_CELLS, states.size(), "No alive cells.");
}
// Adjust the current state up-left
// This helps us identify repeated states
emptyMatrix(auxMatrix, MAX_X, MAX_Y);
adjustUpLeft(matrix, auxMatrix, MAX_X, MAX_Y);
saveCurrentState();
} |
3590026_7 | public ServiceMethodHandler getServiceMethodHandler(String methodName, String version) {
return serviceHandlerMap.get(ServiceMethodHandler.methodWithVersion(methodName, version));
} |
3590271_2 | public static PluginManager getInstance() {
if (ourInstance == null) {
ourInstance = new PluginManager();
}
return ourInstance;
} |
3595727_12 | public void postProcessGeneratedCode(@Nonnull final CodeGeneratorContext context) {
postProcessGeneratedCode(
context.getCompileUnit(),
context.getCodePackage(),
context.getGeneratedClass(),
context.getTargetMethod()
);
} |
3603171_2 | CloseableHttpClient getHttpClient(final ProxyConfiguration proxyConfiguration, final HttpClientConfiguration httpClientConfiguration) throws SmartlingApiException {
HttpClientBuilder httpClientBuilder = getHttpClientBuilder();
if (hasActiveProxyConfiguration(proxyConfiguration))
{
HttpHost proxyHost = new HttpHost(proxyConfiguration.getHost(), proxyConfiguration.getPort());
httpClientBuilder.setProxy(proxyHost);
if (proxyAuthenticationRequired(proxyConfiguration))
{
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
new AuthScope(proxyConfiguration.getHost(), proxyConfiguration.getPort()),
new UsernamePasswordCredentials(proxyConfiguration.getUsername(), proxyConfiguration.getPassword()));
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}
httpClientBuilder.setSSLContext(getSSLConfig());
if (httpConfigurationRequired(httpClientConfiguration))
{
final RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(httpClientConfiguration.getSocketTimeout())
.setConnectTimeout(httpClientConfiguration.getConnectionTimeout())
.setConnectionRequestTimeout(httpClientConfiguration.getConnectionRequestTimeout())
.build();
httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig);
}
return httpClientBuilder.build();
} |
3610576_0 | @Override
public int run(String[] args) throws Exception {
if(args.length != 2) {
System.out.println("Invalid number of arguments\n\n" +
"Usage: IdentityJob <input_path> <output_path>\n\n");
return -1;
}
String input = args[0];
String output = args[1];
FileSystem.get(conf).delete(new Path(output), true);
TupleMRBuilder mr = new TupleMRBuilder(conf);
mr.addIntermediateSchema(getSchema());
mr.setGroupByFields("line");
mr.setTupleReducer(new IdentityReducer());
mr.addInput(new Path(input), new HadoopInputFormat(TextInputFormat.class), new IdentityMap());
mr.setOutput(new Path(output), new HadoopOutputFormat(TextOutputFormat.class), Text.class, NullWritable.class);
mr.createJob().waitForCompletion(true);
return 0;
} |
3616673_8 | @Override
public List<C10NUnit> inspect(String... packagePrefixes) {
List<C10NUnit> res = new ArrayList<>();
@SuppressWarnings("deprecation")
C10NMsgFactory c10NMsgFactory = C10N.createMsgFactory(configuredC10NModule);
Set<Class<?>> c10nInterfaces = c10NInterfaceSearch.find(C10NMessages.class, packagePrefixes);
for (Class<?> c10nInterface : c10nInterfaces) {
Set<Map.Entry<Class<? extends Annotation>, Set<Locale>>> annotationEntries =
configuredC10NModule.getAnnotationBindings(c10nInterface).entrySet();
List<C10NUnit> unitsForInterface = new ArrayList<>();
for (Method method : c10nInterface.getDeclaredMethods()) {
String keyAnnotationValue = ReflectionUtils.getKeyAnnotationValue(method);
String bundleKey = ReflectionUtils.getC10NKey(configuredC10NModule.getKeyPrefix(), method);
boolean isCustom = ReflectionUtils.getKeyAnnotationBasedKey(method) != null;
C10NBundleKey key = new C10NBundleKey(isCustom, bundleKey, keyAnnotationValue);
C10NUnit unit = new C10NUnit(c10nInterface, method, key, localesToCheck);
for (Map.Entry<Class<? extends Annotation>, Set<Locale>> entry : annotationEntries) {
Class<? extends Annotation> annotationClass = entry.getKey();
for (Locale locale : entry.getValue()) {
if (localesToCheck.contains(locale)) {
String translatedValue = extractTranslatedValue(c10NMsgFactory,
c10nInterface,
method,
locale);
C10NTranslations trs = addTranslations(unit, locale, translatedValue);
Annotation annotation = method.getAnnotation(annotationClass);
if (null != annotation) {
trs.getAnnotations().add(annotation);
}
}
}
}
unitsForInterface.add(unit);
}
for (Locale locale : localesToCheck) {
List<ResourceBundle> bundles = configuredC10NModule.getBundleBindings(c10nInterface, locale);
for (C10NUnit unit : unitsForInterface) {
String translatedValue = extractTranslatedValue(c10NMsgFactory,
c10nInterface,
unit.getDeclaringMethod(),
locale);
C10NTranslations trs = addTranslations(unit, locale, translatedValue);
for (ResourceBundle bundle : bundles) {
if (bundle.containsKey(unit.getKey().getKey())) {
trs.getBundles().add(bundle);
}
}
}
}
res.addAll(unitsForInterface);
}
return res;
} |
3628180_31 | public User getUserByUsername(String username) {
User currentUser = authenticationService.getCurrentUser();
String domain = DomainUtil.getDomainFromLogin(currentUser.getLogin());
String login = DomainUtil.getLoginFromUsernameAndDomain(username, domain);
return getUserByLogin(login);
} |
3644569_17 | public Fields extractFields(Class<?> type) {
if (type == null) {
throw new NullPointerException("Cannot extract entity mapping, type is null!");
}
final Entity entityAnnotation = type.getAnnotation(Entity.class);
if (entityAnnotation == null) {
throw new MappingException(type, "not annotated with @Entity, cannot extract property mapping");
}
final Set<MappedField> fields = new HashSet<MappedField>();
final FieldMappingExtractorImpl fieldMappingExtractor = new FieldMappingExtractorImpl();
for (final Field field : type.getDeclaredFields()) {
try {
final MappedField mappedField = fieldMappingExtractor.extract(field);
if (mappedField != null) {
fields.add(mappedField);
}
} catch (final MappingException e) {
e.setMappedType(type);
throw e;
}
}
return new ImmutableFields(fields);
} |
3645037_2 | @Override
public String retrieve(final String proxyGrantingTicketIou) {
if (CommonUtils.isBlank(proxyGrantingTicketIou)) {
return null;
}
final ProxyGrantingTicketHolder holder = this.cache.get(proxyGrantingTicketIou);
if (holder == null) {
logger.info("No Proxy Ticket found for [{}].", proxyGrantingTicketIou);
return null;
}
this.cache.remove(proxyGrantingTicketIou);
logger.debug("Returned ProxyGrantingTicket of [{}]", holder.getProxyGrantingTicket());
return holder.getProxyGrantingTicket();
} |
3649012_0 | public Class<?> getClassDecorator(Class<? extends Annotation> clazzPositionalFieldAnnotation){
if (!isFFPojoAnnotationField(clazzPositionalFieldAnnotation)){
throw new FFPojoException(String.format("The class %s not seem a DelimitedField or PositionalField annotation.", clazzPositionalFieldAnnotation));
}
final String dataType = clazzPositionalFieldAnnotation.getSimpleName()
.replaceAll("DelimitedField", "")
.replaceAll("PositionalField", "")
.toLowerCase();
return mapAnnotationDecoratorClass.get(dataType);
} |
3655926_5 | static String extractPersistentId(URI objURI) {
String URIstr = objURI.toString();
Matcher m = genericURIpattern1Pat.matcher(URIstr);
if (m.matches()) {
return m.group(1);
}
else {
return null;
}
} |
3657930_2715 | public static boolean isNodeType(Tree tree, String typeName, Tree typeRoot) {
String primaryName = TreeUtil.getName(tree, JCR_PRIMARYTYPE);
if (typeName.equals(primaryName)) {
return true;
} else if (primaryName != null) {
Tree type = typeRoot.getChild(primaryName);
if (contains(getNames(type, REP_SUPERTYPES), typeName)) {
return true;
}
}
for (String mixinName : getNames(tree, JCR_MIXINTYPES)) {
if (typeName.equals(mixinName)) {
return true;
} else {
Tree type = typeRoot.getChild(mixinName);
if (contains(getNames(type, REP_SUPERTYPES), typeName)) {
return true;
}
}
}
return false;
} |
3661343_12 | public <KeyT> Map<KeyT, ValueT> groupUnique(Function<ValueT, KeyT> keyExtractor) {
Map<KeyT, ValueT> groupedEntities = new HashMap<>();
for (ValueT value : collection) {
final KeyT key = keyExtractor.apply(value);
if (groupedEntities.get(key) != null) {
throw new DuplicateElementException(key, collection);
}
groupedEntities.put(key, value);
}
return groupedEntities;
} |
3662576_1 | public static VaadletsBuilder build(final com.mymita.vaadlets.core.Component aComponent) {
final VaadletsBuilder builder = new VaadletsBuilder();
builder.create(aComponent);
return builder;
} |
3664810_0 | @RequestMapping(value = BASE_MAPPING + "/{id}", method = RequestMethod.GET)
public ResponseEntity<EntityModel<?>> getItemResource(RootResourceInformation resourceInformation,
@BackendId Serializable id, final PersistentEntityResourceAssembler assembler, @RequestHeader HttpHeaders headers)
throws HttpRequestMethodNotSupportedException {
return getItemResource(resourceInformation, id).map(it -> {
PersistentEntity<?, ?> entity = resourceInformation.getPersistentEntity();
return resourceStatus.getStatusAndHeaders(headers, it, entity).toResponseEntity(//
() -> assembler.toFullResource(it));
}).orElseThrow(() -> new ResourceNotFoundException());
} |
3669065_21 | static byte[] encodeLength(int len) {
if (len < 0) {
throw new IllegalArgumentException("length is negative");
} else if (len >= 16777216) {
throw new IllegalArgumentException("length is too big: " + len);
}
byte[] res;
if (len < 128) {
res = new byte[1];
res[0] = (byte) len;
} else if (len < 256) {
res = new byte[2];
res[0] = -127;
res[1] = (byte) len;
} else if (len < 65536) {
res = new byte[3];
res[0] = -126;
res[1] = (byte) (len / 256);
res[2] = (byte) (len % 256);
} else {
res = new byte[4];
res[0] = -125;
res[1] = (byte) (len / 65536);
res[2] = (byte) (len / 256);
res[3] = (byte) (len % 256);
}
return res;
} |
3674743_1 | @Override
public int getDiscardedBucketsCount() {
return outputStream.getDiscardedBucketCount();
} |
3687614_23 | public static EmbedVaadinComponent forComponent(Component component) {
return new EmbedVaadinComponent(component);
} |
3690150_69 | public String pageLink(String providerName, String pageName) {
return pageLink(providerName, pageName, null);
} |
3691193_14 | @Transactional
public void setComponentState(String componentId, ComponentType type, boolean enabled) {
log.debug("Setting Component State : componentId = " + componentId + " type = " + type + " enabled " + enabled);
ComponentState componentState;
synchronized (lockObject) {
componentState = getComponentState(componentId, type);
if (componentState == null) {
componentState = new ComponentState(componentId, type, enabled);
} else {
componentState.setEnabled(enabled);
}
sessionFactory.getCurrentSession().saveOrUpdate(componentState);
}
} |
3699746_62 | @Override
protected void doStop() throws Exception {
ServiceHelper.stopService(processor);
services.stopTracking();
super.doStop();
} |
3706353_2 | @Override
public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks) throws IndexingException {
// Prepare data
String realUrl = new String(url.getBytes()).substring(0, url.getLength());
Metadata metadata = parse.getData().getParseMeta();
if (omitIndexingFilterConfiguration.getFilteringType() == FilteringType.WHITELIST) {
for (OmitIndexingFilterConfigurationEntry omitIndexingFilterConfigurationEntry : omitIndexingFilterConfiguration.getOmitIndexingFilterConfigurationEntryList()) {
switch (omitIndexingFilterConfigurationEntry.getTarget()) {
case URL:
Pattern pattern = Pattern.compile(omitIndexingFilterConfigurationEntry.getRegex());
if (pattern.matcher(realUrl).matches()) {
return doc;
}
break;
case META_FIELD_PRESENT:
if(metadata.get(FilterUtils.getNullSafe(omitIndexingFilterConfigurationEntry.getName(), "")) != null) {
return doc;
}
break;
}
}
return null;
} else if (omitIndexingFilterConfiguration.getFilteringType() == FilteringType.BLACKLIST) {
for (OmitIndexingFilterConfigurationEntry omitIndexingFilterConfigurationEntry : omitIndexingFilterConfiguration.getOmitIndexingFilterConfigurationEntryList()) {
switch (omitIndexingFilterConfigurationEntry.getTarget()) {
case URL:
Pattern pattern = Pattern.compile(omitIndexingFilterConfigurationEntry.getRegex());
if (pattern.matcher(realUrl).matches()) {
return null;
}
break;
case META_FIELD_PRESENT:
if(metadata.get(FilterUtils.getNullSafe(omitIndexingFilterConfigurationEntry.getName(), "")) != null) {
return null;
}
break;
}
}
return doc;
}
return null;
} |
3710234_51 | public List<RobotLine> lex() throws CoreException {
try {
System.out.println("Lexing " + filename);
CountingLineReader contents = new CountingLineReader(filestream);
String line;
int lineNo = 0;
int charPos = 0;
while (null != (line = contents.readLine())) {
if (monitor.isCanceled()) {
return null;
}
try {
lexLine(line, lineNo, charPos);
} catch (CoreException e) {
throw new RuntimeException("Error when lexing line " + lineNo + ": '" + line + "'", e);
} catch (RuntimeException e) {
throw new RuntimeException("Internal error when lexing line " + lineNo + ": '" + line + "'", e);
}
++lineNo;
charPos = contents.getCharPos();
}
// TODO store results
} catch (Exception e) {
throw new RuntimeException("Error lexing robot file " + filename, e);
} finally {
try {
filestream.close();
} catch (IOException e) {
// ignore
}
}
return lexLines;
} |
3713233_87 | public ClassMeta extract(String sourceCodeString) {
Assertion.on("sourceCodeString").mustNotBeNull(sourceCodeString);
ClassMeta meta = new ClassMeta();
String modifiedSourceCodeString = TrimFilterUtil.doAllFilters(sourceCodeString);
// -----------------
// package name
Matcher matcherGroupingPackageName = RegExp.PatternObject.Pacakge_Group.matcher(modifiedSourceCodeString);
if (matcherGroupingPackageName.find()) {
meta.packageName = matcherGroupingPackageName.group(1);
}
String outOfBrace = modifiedSourceCodeString.split("\\{")[0];
int lenForOutOfBrace = outOfBrace.length();
StringBuilder bufForOutOfBrace = new StringBuilder();
boolean isInsideOfGenerics = false;
int depth = 0;
for (int i = 0; i < lenForOutOfBrace; i++) {
char current = outOfBrace.charAt(i);
if (current == '<') {
isInsideOfGenerics = true;
depth++;
}
if (current == '>') {
depth--;
if (depth <= 0) {
isInsideOfGenerics = false;
continue;
}
}
if (!isInsideOfGenerics) {
bufForOutOfBrace.append(current);
}
}
String outOfBraceWithoutGenerics = bufForOutOfBrace.toString();
String[] splittedBySpace = outOfBraceWithoutGenerics.split("\\s+");
boolean isClass = outOfBrace.matches(".*\\s+class\\s+.*") || outOfBrace.matches(".*;class\\s+.*");
meta.isEnum = outOfBrace.matches(".*\\s+enum\\s+.*");
if (!isClass && !meta.isEnum) {
meta.isAbstract = true;
} else {
for (String each : splittedBySpace) {
if (each.equals("abstract") || each.equals("interface") || each.equals("@interface")) {
meta.isAbstract = true;
break;
}
}
}
// -----------------
// class name
meta.name = splittedBySpace[splittedBySpace.length - 1].replaceFirst(RegExp.Generics, StringValue.Empty);
for (int i = 0; i < splittedBySpace.length; i++) {
if (splittedBySpace[i].equals("extends") || splittedBySpace[i].equals("implements")) {
meta.name = splittedBySpace[i - 1].replaceFirst(RegExp.Generics, StringValue.Empty);
break;
}
}
// -----------------
// imported list
meta.importedList = importedListExtractor.extract(modifiedSourceCodeString);
// -----------------
// constructors
constructorMetaExtractor.initialize(meta, modifiedSourceCodeString);
meta.constructors = constructorMetaExtractor.extract(modifiedSourceCodeString);
// -----------------
// methods
methodMetaExtractor.initialize(meta, modifiedSourceCodeString);
meta.methods = methodMetaExtractor.extract(modifiedSourceCodeString);
// check duplicated variable name
if (meta.constructors.size() > 0) {
// constructor arg name is "target"
for (ConstructorMeta cons : meta.constructors) {
int len = cons.argNames.size();
for (int i = 0; i < len; i++) {
if (isDuplicatedVariableName(cons.argNames.get(i))) {
cons.argNames.set(i, cons.argNames.get(i) + "_");
}
}
}
// duplicated to constructor arg names
ConstructorMeta constructor = meta.constructors.get(0);
for (MethodMeta method : meta.methods) {
int len = method.argNames.size();
for (int i = 0; i < len; i++) {
String targetArgName = method.argNames.get(i);
List<String> methodArgNames = new ArrayList<String>();
for (String methodArgName : method.argNames) {
if (!targetArgName.equals(methodArgName)) {
methodArgNames.add(methodArgName);
}
}
method.argNames.set(i, renameIfDuplicatedToConstructorArgNames(targetArgName, constructor.argNames,
methodArgNames));
}
}
}
return meta;
} |
3713238_183 | @Override
public Symbol execute(RhsFunctionContext context, List<Symbol> arguments) throws RhsFunctionException
{
RhsFunctions.checkAllArgumentsAreNumeric(getName(), arguments);
RhsFunctions.checkArgumentCount(this, arguments);
final SymbolFactory syms = context.getSymbols();
Symbol arg = arguments.get(0);
if(arguments.size() == 1)
{
IntegerSymbol i = arg.asInteger();
return i != null ? syms.createInteger(-i.getValue()) :
syms.createDouble(-arg.asDouble().getValue());
}
long i = 0;
double f = 0;
boolean float_found = false;
IntegerSymbol ic = arg.asInteger();
if(ic != null)
{
i = ic.getValue();
}
else
{
float_found = true;
f = arg.asDouble().getValue();
}
for(int index = 1; index < arguments.size(); ++index)
{
arg = arguments.get(index);
ic = arg.asInteger();
if(ic != null)
{
if(float_found)
{
f -= ic.getValue();
}
else
{
i -= ic.getValue();
}
}
else
{
if(float_found)
{
f -= arg.asDouble().getValue();
}
else
{
float_found = true;
f = i - arg.asDouble().getValue();
}
}
}
return float_found ? syms.createDouble(f) : syms.createInteger(i);
} |
3722315_4 | @Override
public String getLocationUrl(Location location, PortletRequest request) {
try {
final String encodedLocation = URLEncoder.encode(location.getIdentifier(), "UTF-8");
return portalContext.concat("/s/location?id=").concat(encodedLocation);
} catch (UnsupportedEncodingException e) {
log.error("Unable to encode location id " + location.getIdentifier());
return null;
}
} |
3724388_103 | public static ByteBuffer readByteBuffer(URL url) throws IOException
{
ByteBuffer byteBuffer = null;
if (URLUtil.isForResourceWithExtension(url, "zip"))
{
//try opening the file as a zip file; if this fails, log a warning and read file directly into the buffer
InputStream is = null;
try
{
is = url.openStream();
ZipRetriever zr = new ZipRetriever(url);
byteBuffer = zr.readZipStream(is, url);
}
catch (Exception e)
{
String message = "Error loading zip file at '" + url + "': " + e.getLocalizedMessage();
Logging.logger().warning(message);
}
finally
{
if (is != null)
is.close();
}
}
if (byteBuffer == null)
{
byteBuffer = readURLContentToBuffer(url);
}
return byteBuffer;
} |
3726486_7 | public HashCalculationResult calculateSuperHash(File file) throws IOException {
// Ignore files smaller than 0.5kb
long fileSize = file.length();
if (fileSize <= FILE_MIN_SIZE_THRESHOLD) {
logger.debug("Ignored file " + file.getName() + " (" + FileUtils.byteCountToDisplaySize(fileSize) + "): minimum file size is 512B");
return null;
}
if (fileSize >= FILE_MAX_SIZE_THRESHOLD){
logger.debug("Ignore file {}, ({}): maximum file size is 2GB", file.getName(), FileUtils.byteCountToDisplaySize(fileSize));
return null;
}
HashCalculationResult result = null;
try {
result = calculateSuperHash(FileUtils.readFileToByteArray(file));
} catch (OutOfMemoryError e) {
logger.debug(MessageFormat.format("Failed calculating SHA-1 for file {0}: size too big {1}",
file.getAbsolutePath(), FileUtils.byteCountToDisplaySize(fileSize)));
}
return result;
} |
3728202_22 | protected void setResultOptions(AbstractEntry entry, Integer count, Integer startIndex, String sortBy) {
entry.setFiltered(false);
entry.setSorted(sortBy != null);
if (sortBy != null) {
entry.sortEntryCollection(sortBy);
}
entry.setUpdatedSince(false);
int entrySize = entry.getEntrySize();
entry.setTotalResults(entrySize);
entry.setStartIndex((startIndex != null && startIndex != 0) ? startIndex : 0);
/*
* Bugfix: https://jira.surfconext.nl/jira/browse/BACKLOG-739
*
* We might get more results then we want, because the result is plus the external group providers
*/
count = (count != null && count != 0) ? count : 0;
startIndex = entry.getStartIndex();
if (startIndex > 0 || count > 0) {
// need sublist
List collection = entry.getEntryCollection();
startIndex = startIndex > entrySize ? entrySize : startIndex;
count = ((startIndex + count) < entrySize && count != 0) ? (startIndex + count) : entrySize;
List subList = collection.subList(startIndex, count);
entry.setEntryCollection(subList);
}
entry.setItemsPerPage(entry.getEntrySize());
} |
3728381_27 | public byte[] encodeSingle(Record record) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
encodeSingle(record, baos);
return baos.toByteArray();
} |
3732883_60 | @Override
public NodePath getNodePath() {
String name = getName();
ApiNode parent = context.getParentNode();
NodePath path = isRoot() ? NodePath.root() : NodePath.path(name);
if (parent != null) {
path = parent.getNodePath().append(path);
}
return path;
} |
3742298_2 | public void collate(DiffCollatorConfiguration config, Comparand base, Comparand witness) throws IOException {
// This amounts to a config for the diff/collation
Comparison comparison = new Comparison(base, witness);
// First find an filter out any transpositions and collate
// the filtered result
final Set<Set<Annotation>> transpositions = config.getTranspositionSource().transpositionsIn(comparison);
for (Comparison filtered : comparison.filter(transpositions)) {
LOG.info("Collating " + filtered);
this.transpositionCollation = false;
collate(config, filtered);
}
// Now take each of the transpositions and perform a
// mini-collation on it
for (Set<Annotation> transposition : transpositions) {
LOG.info("Collating transposition " + Iterables.toString(transposition));
this.transpositionCollation = true;
collate(config, new Comparison(base, witness, transposition));
}
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
} |
3742443_2 | @Override
public Group.Element<Gq> getIdentityElement() {
return element(BigInteger.ONE);
} |
3743376_249 | void setLogo(Bitstream logo) {
this.logo = logo;
setModified();
} |
3743505_14 | public List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted) throws DropboxException {
assertAuthenticated();
if (fileLimit <= 0) {
fileLimit = SEARCH_DEFAULT_LIMIT;
}
String target = "/search/" + session.getAccessType() + path;
String[] params = {
"query", query,
"file_limit", String.valueOf(fileLimit),
"include_deleted", String.valueOf(includeDeleted),
"locale", session.getLocale().toString()
};
Object response = RESTUtility.request(RequestMethod.GET,
session.getAPIServer(), target, VERSION, params, session);
ArrayList<Entry> ret = new ArrayList<Entry>();
if (response instanceof JSONArray) {
JSONArray jresp = (JSONArray)response;
for (Object next: jresp) {
if (next instanceof Map) {
@SuppressWarnings("unchecked")
Entry ent = new Entry((Map<String, Object>)next);
ret.add(ent);
}
}
}
return ret;
} |
3744706_7 | public InputStream getResourceAsStream(String name)
throws IOException
{
if (name.startsWith("classpath:"))
return openClasspathResource(name);
else if (name.startsWith("file:"))
return openFileResource(name);
else
return openWarResource(name);
} |
3748867_0 | @SuppressWarnings("unchecked")
public G readGraph() throws GraphIOException {
try {
// Initialize if not already.
init();
while (xmlEventReader.hasNext()) {
XMLEvent event = xmlEventReader.nextEvent();
if (event.isStartElement()) {
StartElement element = (StartElement) event;
String name = element.getName().getLocalPart();
// The element should be one of: key, graph, graphml
if (GraphMLConstants.KEY_NAME.equals(name)) {
// Parse the key object.
Key key = (Key) parserRegistry.getParser(name).parse(
xmlEventReader, element);
// Add the key to the key map.
document.getKeyMap().addKey(key);
} else if (GraphMLConstants.GRAPH_NAME.equals(name)) {
// Parse the graph.
GraphMetadata graph = (GraphMetadata) parserRegistry
.getParser(name).parse(xmlEventReader, element);
// Add it to the graph metadata list.
document.getGraphMetadata().add(graph);
// Return the graph object.
return (G)graph.getGraph();
} else if (GraphMLConstants.GRAPHML_NAME.equals(name)) {
// Ignore the graphML object.
} else {
// Encounted an unknown element - just skip by it.
parserRegistry.getUnknownElementParser().parse(
xmlEventReader, element);
}
} else if (event.isEndDocument()) {
break;
}
}
} catch (Exception e) {
ExceptionConverter.convert(e);
}
// We didn't read anything from the document.
throw new GraphIOException("Unable to read Graph from document - the document could be empty");
} |
3750999_3 | public XingProfile getUserProfile() {
return getProfileById("me");
} |
3756907_0 | public BackoffSleeper(long minWait, long maxWait, double backoffMultiplier) {
if (minWait <= 0)
{
throw new IllegalArgumentException("Minimum wait must be at least 1 ms");
}
if (maxWait <= minWait)
{
throw new IllegalArgumentException("Maximum wait must be greater than minimum wait");
}
if (backoffMultiplier <= 1.0)
{
throw new IllegalArgumentException("Backoff multiplier must be greater than 1.0");
}
_minWait = minWait;
_maxWait = maxWait;
_backoffMultiplier = backoffMultiplier;
reset();
} |
3765814_1 | public static <T> T getOtherAttribute(Map<QName, String> otherAttributes, String attributeName) {
T otherAttribute = null;
for (QName qname : otherAttributes.keySet()) {
String value = otherAttributes.get(qname);
String key = qname.getLocalPart();
LOG.debug("Attribute: " + key + " : " + value);
if (key.equalsIgnoreCase(attributeName)) {
otherAttribute = (T) value;
}
}
return otherAttribute;
} |
3772264_10 | @Override
public void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String, Timer> timers) {
final long timestamp = clock.getTime() / 1000;
log.debug("Reporting metrics: for {} at {}", timestamp, System.currentTimeMillis());
// oh it'd be lovely to use Java 7 here
try {
riemann.connect();
for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
reportGauge(entry.getKey(), entry.getValue(), timestamp);
}
for (Map.Entry<String, Counter> entry : counters.entrySet()) {
reportCounter(entry.getKey(), entry.getValue(), timestamp);
}
for (Map.Entry<String, Histogram> entry : histograms.entrySet()) {
reportHistogram(entry.getKey(), entry.getValue(), timestamp);
}
for (Map.Entry<String, Meter> entry : meters.entrySet()) {
reportMetered(entry.getKey(), entry.getValue(), timestamp);
}
for (Map.Entry<String, Timer> entry : timers.entrySet()) {
reportTimer(entry.getKey(), entry.getValue(), timestamp);
}
log.trace("Flushing events to riemann");
riemann.client.flush();
log.debug("Completed at {}", System.currentTimeMillis());
} catch (IOException e) {
log.warn("Unable to report to Riemann", riemann, e);
}
} |
3781210_16 | public UserCredentials createUser() {
return createUser(null);
} |
3787360_8 | public static String unescapeHeader(String string) {
if (string == null)
return string;
string = string.replace("\\n", "\n");
string = string.replace("\\c", ":");
string = string.replace("\\\\", "\\");
return string;
} |
3798663_0 | @Override
public Object execute(Object[] parameters) {
Object parameterObject = parametersParsing(parameters);
if (StatementType.SELECT.equals(statementType)) {
if (!queryMethod.isPageQuery() && !queryMethod.isCollectionQuery()) {
return template.queryForObject(queryMethod.getNamedQueryName(), parameterObject);
} else if (queryMethod.isCollectionQuery()) {
return template.queryForList(queryMethod.getNamedQueryName(), parameterObject);
}
} else if (StatementType.INSERT.equals(statementType)) {
template.insert(queryMethod.getNamedQueryName(), parameterObject);
return parameterObject;
} else if (StatementType.UPDATE.equals(statementType)) {
return template.update(queryMethod.getNamedQueryName(), parameterObject);
} else if (StatementType.DELETE.equals(statementType)) {
return template.delete(queryMethod.getNamedQueryName(), parameterObject);
}
throw new UnsupportedOperationException();
} |
3806452_12 | public static String getCurrentJavaVirtualMachineSpecificationVersion() {
return System.getProperty("java.vm.specification.version", "1.8");
} |
3808230_16 | @Override
public boolean deleteDocumentFile(DatabaseDocument<T> d, String fileName) {
return writer.deleteDocumentFile(d, fileName);
} |
3817774_2 | @Override
public Request request(String subject, long timeout, TimeUnit unit, MessageHandler... messageHandlers) {
return request(subject, "", timeout, unit, messageHandlers);
} |
3833897_2 | public <T extends AbstractDomainObject> T allocateObject(Class<T> objClass, Object oid) {
if (objClass == null) {
throw new RuntimeException("Cannot allocate object '" + oid + "'. Class not found");
}
if (Modifier.isAbstract( objClass.getModifiers() )) {
throw new RuntimeException("Cannot allocate object '" + oid + "'. Class is abstract");
}
try {
return getInstantiatorOf(objClass).newInstance(new OID(oid));
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException("Could not allocate object " + oid + " of class " + objClass.getName(), e);
}
} |
3836962_11 | static Double ToNumber(Object arg) {
if (arg == null) {
return 0.0d;
} else if (Boolean.TRUE.equals(arg)) {
return 1.0d;
} else if (Boolean.FALSE.equals(arg)) {
return 0.0d;
} else if (arg instanceof String) {
return ToNumber((String) arg);
} else if (arg instanceof Number) {
return ((Number) arg).doubleValue();
}
Object primValue = ToPrimitive(arg, "Number");
return ToNumber(primValue).doubleValue();
} |
3842880_1 | @Override
public void run(IProgressMonitor monitor) {
Date startTime = new Date();
// Prepare data matrix to combine
IMatrix data = analysis.getData().get();
// Dimension to combine using the module map
MatrixDimensionKey combineDimension = (analysis.isTransposeData() ? ROWS : COLUMNS);
// Dimension to iterate
MatrixDimensionKey iterateDimension = (analysis.isTransposeData() ? COLUMNS : ROWS);
// The module map
IModuleMap moduleMap;
if (analysis.getGroupsMap() == null) {
moduleMap = new HashModuleMap().addMapping("All data " + combineDimension.getLabel(), data.getDimension(combineDimension));
} else {
moduleMap = ModuleMapUtils.filterByItems(analysis.getGroupsMap().get(), data.getDimension(combineDimension));
}
analysis.setGroupsMap(new ResourceReference<>("modules", moduleMap));
// Set size and p-value layers
String sizeLayer = analysis.getSizeLayer();
String pvalueLayer = analysis.getValueLayer();
if (pvalueLayer == null) {
for (IMatrixLayer layer : data.getLayers()) {
pvalueLayer = layer.getId();
}
}
// Prepare results matrix
analysis.setResults(new ResourceReference<>("results",
combine(
monitor,
data,
combineDimension,
iterateDimension,
moduleMap,
sizeLayer,
pvalueLayer)
));
analysis.setStartTime(startTime);
analysis.setElapsedTime(new Date().getTime() - startTime.getTime());
} |
3847504_139 | public SearchQuery withPathPrefix(String path) {
clearExpectations();
if (path.endsWith("/"))
path = path.substring(0, path.length() - 1);
this.pathPrefix = path;
if (pathPrefix == null)
throw new IllegalArgumentException("Path prefix must not be null");
if (!pathPrefix.startsWith(WebUrl.separator))
pathPrefix = WebUrl.separatorChar + pathPrefix;
return this;
} |
3854292_5 | @GetMapping("/")
public String index(Authentication authentication) {
return authentication == null ? "index" : "redirect:/user.html";
} |
3859251_23 | @Override
public synchronized Object remove(final Object key) {
final Object def = preWrite(key);
final Object man = super.remove(key);
return man == null ? def : man;
} |
3869967_60 | @Override
public <S extends AppSession> S add(final S appSession) {
Preconditions.checkNotNull(appSession, "Cannot add null AppSession");
Preconditions.checkNotNull(appSession.getId(), "Cannot add AppSession with null ID");
log.info("Insert AppSession {} for {} with User Agent: {} (dated: {})",
appSession.getId(),
appSession.getPerson() != null ? appSession.getPerson().getId() : null,
appSession.getUserAgent(),
appSession.getCreationTime() );
final DBObject obj = new ToDBObject().apply(appSession);
coll.insert(obj);
return appSession;
} |
3885169_5 | public boolean verifyPassword(String password) {
return new BasicPasswordEncryptor().checkPassword(password,
this.password);
} |
3894929_2 | public HasXPath(String xPathExpression, Matcher<String> valueMatcher) {
this(xPathExpression, NO_NAMESPACE_CONTEXT, valueMatcher);
} |
3900538_7 | @Override
public Decoded<List<String>> decode(Event type, String message) {
if (type.equals(Event.MESSAGE)) {
if (skipFirstMessage.getAndSet(false)) return empty;
Decoded<List<String>> messages = new Decoded<List<String>>(new LinkedList<String>());
message = messagesBuffer.append(message).toString().replace(delimiter, charReplacement);
messagesBuffer.setLength(0);
if (message.indexOf(charReplacement) != -1) {
String[] tokens = message.split(charReplacement);
// Skip first.
int pos = 1;
int length = Integer.valueOf(tokens[0]);
String m;
while (pos < tokens.length) {
m = tokens[pos];
if (m.length() >= length) {
messages.decoded().add(m.substring(0, length));
String t = m.substring(length);
if (t.length() > 0) {
length = Integer.valueOf(t);
}
} else {
if (pos != 1) {
messagesBuffer.append(length).append(delimiter).append(m);
} else {
messagesBuffer.append(message);
}
if (messages.decoded().size() > 0) {
return messages;
} else {
return new Decoded<List<String>>(new LinkedList<String>(), Decoded.ACTION.ABORT);
}
}
pos++;
}
}
return messages;
} else {
return empty;
}
} |
3910894_1 | @Override
public final Collection<Song> getAllSongs() throws IOException,
URISyntaxException
{
final Collection<Song> chunkedCollection = new ArrayList<Song>();
// Map<String, String> fields = new HashMap<String, String>();
// fields.put("json", "{\"continuationToken\":\"" + continuationToken +
// "\"}");
final FormBuilder form = new FormBuilder();
// form.addFields(fields);
form.close();
final String response = client.dispatchPost(new URI(
HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES_LOADALLTRACKS), form);
// extract the JSON from the response
final List<String> jsSongCollectionWrappers = getJsSongCollectionWrappers(response);
final Gson gson = new Gson();
final JsonParser parser = new JsonParser();
for (final String songCollectionWrapperJson : jsSongCollectionWrappers)
{
final JsonArray songCollectionWrapper = parser.parse(
new StringReader(songCollectionWrapperJson))
.getAsJsonArray();
// the song collection is the first element of the "wrapper"
final JsonArray songCollection = songCollectionWrapper.get(0)
.getAsJsonArray();
// each element of the songCollection is an array of song values
for (final JsonElement songValues : songCollection)
{
// retrieve the songValues as an Array for parsing to a Song
// object
final JsonArray values = songValues.getAsJsonArray();
final Song s = new Song();
s.setId(gson.fromJson(values.get(0), String.class));
s.setTitle(gson.fromJson(values.get(1), String.class));
s.setName(gson.fromJson(values.get(1), String.class));
if (!Strings.isNullOrEmpty(gson.fromJson(values.get(2),
String.class)))
{
s.setAlbumArtUrl("https:"
+ gson.fromJson(values.get(2), String.class));
}
s.setArtist(gson.fromJson(values.get(3), String.class));
s.setAlbum(gson.fromJson(values.get(4), String.class));
s.setAlbumArtist(gson.fromJson(values.get(5), String.class));
s.setGenre(gson.fromJson(values.get(11), String.class));
s.setDurationMillis(gson.fromJson(values.get(13), Long.class));
s.setType(gson.fromJson(values.get(16), Integer.class));
s.setYear(gson.fromJson(values.get(18), Integer.class));
s.setPlaycount(gson.fromJson(values.get(22), Integer.class));
s.setRating(gson.fromJson(values.get(23), String.class));
if (!Strings.isNullOrEmpty(gson.fromJson(values.get(24),
String.class)))
{
s.setCreationDate(gson.fromJson(values.get(24), Float.class) / 1000);
}
if (!Strings.isNullOrEmpty(gson.fromJson(values.get(36),
String.class)))
{
s.setUrl("https:"
+ gson.fromJson(values.get(36), String.class));
}
chunkedCollection.add(s);
}
}
return chunkedCollection;
} |
3913468_1 | @Override
public Map<String,String> getProperties() {
Map<String,String> envVars = System.getenv();
if (!Collections.isEmpty(envVars)) {
return new LinkedHashMap<String, String>(envVars);
}
return java.util.Collections.emptyMap();
} |
3933009_4 | @Override
public boolean hasPermission(Identity userIdentity, Group group) {
if (userACL.getSuperUser().equals(userIdentity.getUserId())
|| userIdentity.getMemberships()
.stream()
.anyMatch(userMembership -> userMembership.getGroup().equals(userACL.getAdminGroups()))) {
return true;
}
Collection<MembershipEntry> userMemberships = userIdentity.getMemberships();
if (spacesAdministratorsGroups == null) {
spacesAdministratorsGroups = spacesAdministrationService.getSpacesAdministratorsMemberships()
.stream()
.map(membershipEntry -> membershipEntry.getGroup())
.collect(Collectors.toList());
}
return userMemberships.stream()
.anyMatch(userMembership -> ((group.getId().startsWith("/spaces/")
|| group.getId().equals("/spaces"))
&& (spacesAdministratorsGroups.contains(userMembership.getGroup())
|| userMembership.getGroup().equals(group.getId())
|| userMembership.getGroup().startsWith(group.getId() + "/")))
|| ((userMembership.getGroup().equals(group.getId())
|| userMembership.getGroup().startsWith(group.getId() + "/"))
&& (userMembership.getMembershipType().equals(ANY)
|| userMembership.getMembershipType().equals(MANAGER))));
} |
3934425_27 | public static String getPathOnly(String fullPath)
{
if (fullPath == null || fullPath.isEmpty())
return fullPath;
int index = fullPath.indexOf('?');
if (index == -1)
{
index = fullPath.indexOf('#');
return index == -1 ? fullPath : fullPath.substring(0, index);
}
return fullPath.substring(0, index);
} |
3935296_8 | @SuppressWarnings("unchecked")
public static List<String> getUserPermission(String[] userGroupMembership) throws Exception {
List<String> users = getFromCache(userGroupMembership);
if (users != null) {
return users;
}
users = new ArrayList<String>();
if (userGroupMembership == null || userGroupMembership.length <= 0 || (userGroupMembership.length == 1 && userGroupMembership[0].equals(" ")))
return users;
OrganizationService organizationService = (OrganizationService) ExoContainerContext.getCurrentContainer().getComponentInstanceOfType(OrganizationService.class);
for (String str : userGroupMembership) {
str = str.trim();
if (isMembershipExpression(str)) {
String[] array = str.split(":");
// List<User> userList = organipageListzationService.getUserHandler().findUsersByGroup(array[1]).getAll() ;
PageList pageList = getUserByGroup(organizationService, array[1]);
if (pageList == null)
continue;
if (array[0].length() > 1) {
List<User> userList = new ArrayList<User>();
for (int i = 1; i <= pageList.getAvailablePage(); i++) {
userList.clear();
userList.addAll(pageList.getPage(i));
for (User user : userList) {
if (!users.contains(user.getUserName())) {
Collection<Membership> memberships = organizationService.getMembershipHandler().findMembershipsByUser(user.getUserName());
for (Membership member : memberships) {
if (member.getMembershipType().equals(array[0])) {
users.add(user.getUserName());
break;
}
}
}
}
}
/*
* for(User user: userList) { if(!users.contains(user.getUserName())){ Collection<Membership> memberships = organizationService.getMembershipHandler().findMembershipsByUser(user.getUserName()) ; for(Membership member : memberships){ if(member.getMembershipType().equals(array[0])) { users.add(user.getUserName()) ; break ; } } } }
*/
} else {
if (array[0].charAt(0) == 42) {
pageList = getUserByGroup(organizationService, array[1]);
if (pageList == null)
continue;
List<User> userList = new ArrayList<User>();
for (int i = 1; i <= pageList.getAvailablePage(); i++) {
userList.clear();
userList.addAll(pageList.getPage(i));
for (User user : userList) {
if (!users.contains(user.getUserName())) {
users.add(user.getUserName());
}
}
}
/*
* for(User user: userList) { if(!users.contains(user.getUserName())){ users.add(user.getUserName()) ; } }
*/
}
}
} else if (isGroupExpression(str)) {
PageList pageList = getUserByGroup(organizationService, str);
if (pageList == null)
continue;
List<User> userList = new ArrayList<User>();
for (int i = 1; i <= pageList.getAvailablePage(); i++) {
userList.clear();
userList.addAll(pageList.getPage(i));
for (User user : userList) {
if (!users.contains(user.getUserName())) {
users.add(user.getUserName());
}
}
}
/*
* for(User user: userList) { if(!users.contains(user.getUserName())){ users.add(user.getUserName()) ; } }
*/
} else {
if (!users.contains(str)) {
users.add(str);
}
}
}
storeInCache(userGroupMembership, users);
return users;
} |
3935748_24 | public boolean hasPermission(Identity userIdentity, Group group) {
Collection<MembershipEntry> userMemberships = userIdentity.getMemberships();
return userACL.getSuperUser().equals(userIdentity.getUserId())
|| userMemberships.stream()
.anyMatch(userMembership -> userMembership.getGroup().equals(userACL.getAdminGroups())
|| ((userMembership.getGroup().equals(group.getId())
|| userMembership.getGroup().startsWith(group.getId() + "/"))
&& (group.getId().equals("/spaces")
|| group.getId().startsWith("/spaces/")
|| userMembership.getMembershipType().equals("*")
|| userMembership.getMembershipType().equals("manager"))));
} |
3937364_5 | public boolean mustSkipAccountSetup() {
if (skipSetup == null) {
SettingValue accountSetupNode = settingService.get(Context.GLOBAL, Scope.GLOBAL, ACCOUNT_SETUP_NODE);
String propertySetupSkip = PropertyManager.getProperty(ACCOUNT_SETUP_SKIP_PROPERTY);
if (propertySetupSkip == null) {
LOG.debug("Property accountsetup.skip not found in configuration.properties");
propertySetupSkip = "false";
}
skipSetup = accountSetupNode != null || propertySetupSkip.equals("true") || PropertyManager.isDevelopping();
}
return skipSetup;
} |
3943003_2 | public String filePathFromURL(URL url) {
if (url == null) {
throw new IllegalArgumentException("url is null");
}
// Old solution does not deal well with "<" | ">" | "#" | "%" |
// <"> "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`" since they may occur
// inside an URL but are prohibited for an URI. See
// http://www.faqs.org/rfcs/rfc2396.html Section 2.4.3
// This solution works. See discussion at
// http://stackoverflow.com/questions/4494063/how-to-avoid-java-net-urisyntaxexception-in-url-touri
// we assume url has been properly encoded, so we decode it
try {
URI uri = new File(URLDecoder.decode(url.getPath(), "UTF-8")).toURI();
return uri.getPath();
} catch (UnsupportedEncodingException e) {
// this really shouldn't happen
Assertions.UNREACHABLE();
return null;
}
} |
3946094_2 | @Override
public String sayHello() {
Pojo pojo = new Pojo();
pojo.version();
return "Hello";
} |
3951979_0 | protected List<DataPoint> downsample(long duration, Aggregator aggregator, List<DataPoint> points) {
List<DataPoint> result = Lists.newArrayList();
int offset = 0;
long maxSampleTimestamp = 0;
for (int i = 0; i < points.size(); i++) {
DataPoint dataPoint = points.get(i);
if (dataPoint.getTimestamp() > maxSampleTimestamp) {
if (i > offset) {
result.add(aggregator.aggregate(points, offset, i));
}
offset = i;
long timestampDelta = dataPoint.getTimestamp() - maxSampleTimestamp;
maxSampleTimestamp += Math.ceil((double)timestampDelta / duration) * duration;
}
}
if (points.size() > offset) {
result.add(aggregator.aggregate(points, offset, points.size()));
}
return result;
} |
3978781_357 | @NonNull
public static <T> LiveData<T> fromPublisher(@NonNull Publisher<T> publisher) {
return new PublisherLiveData<>(publisher);
} |
3988459_66 | public boolean isHttpOnly() {
return httpOnly == null ? false : httpOnly;
} |
3993813_9 | public static FindResult findNextRecord(UUID delimiter, ByteBuffer source) {
final byte hook = RECORD_DELIMITER_PREFIX[0];
if (source.hasRemaining()) {
do {
if (source.get() == hook) {
int originalSourcePosition = source.position();
source.position(originalSourcePosition - 1); // reverting the consumption of the hook byte.
final int recordLength = readRecordHeader(source, delimiter);
final ReadStatus readStatus = ReadStatus.decode(recordLength);
switch (readStatus) {
case ReadOk:
final int crc32 = extractCrc32FromRecord(source);
final int position = source.position();
final FindResult findResult = new FindResult(readStatus,
new NioJournalFileRecord(delimiter, (ByteBuffer) source.duplicate().limit(position + recordLength), crc32));
// Advance the position to the next record.
source.position(position + recordLength + RECORD_TRAILER_SIZE);
return findResult;
case FoundPartialRecord:
return new FindResult(readStatus, null);
case FoundHeaderWithDifferentDelimiter:
if (trace) { log.trace("Quickly iterating other log entry."); }
break;
default:
// consuming the byte (that was reset before).
source.position(Math.max(source.position(), originalSourcePosition));
}
}
} while (source.hasRemaining());
}
return new FindResult(ReadStatus.NoHeaderInBuffer, null);
} |
3996100_2 | @Override
public String key() {
return "camel";
} |
3999381_29 | @Override
public int findShortestWord(CharSequence chars, int start, int end, StringBuilder word) {
for(int i = start; i < end; i++){
Iterator<String> it = commonPrefixSearch(chars.subSequence(i, end).toString()).iterator();
/*
if(it.hasNext()){
if(word != null) word.append(it.next());
return i;
}
*/
int len = Integer.MIN_VALUE;
String ret = null;
while(it.hasNext()){
String w = it.next();
if(w.length() > len){
ret = w;
len = w.length();
}
}
if(ret != null){
word.append(ret);
return i;
}
/*/
}
return -1;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.