id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
---|---|
6493570_1
|
public ChannelGroupFuture kill() {
if (serverChannel == null) {
throw new IllegalStateException("Server is not running.");
}
channelGroup.add(serverChannel);
final ChannelGroupFuture future = channelGroup.close();
channelGroup.remove(serverChannel);
serverChannel = null;
return future;
}
|
6500041_18
|
@Override
public void map(LongWritable k, Text v,Context c) throws IOException, InterruptedException {
String line=v.toString();
if (line.startsWith("@prefix")) {
incrementCounter(c,FreebasePrefilterCounter.PREFIX_DECL,1L);
return;
}
try {
List<String> parts = expandTripleParts(line);
line.getBytes();
PrimitiveTriple triple=new PrimitiveTriple(parts.get(0),parts.get(1),parts.get(2));
if(tripleFilter.apply(triple)) {
triple=rewritingFunction.apply(triple);
accept(c,triple);
incrementCounter(c,FreebasePrefilterCounter.ACCEPTED,1L);
} else {
incrementCounter(c,FreebasePrefilterCounter.IGNORED,1L);
}
} catch(InvalidNodeException ex) {
incrementCounter(c,FreebasePrefilterCounter.IGNORED,1L);
logger.warn("Invalid triple: "+line);
}
return;
}
|
6505114_0
|
public static <T> T createInstanceOfGenericType(Class clazz){
return createInstanceOfGenericType(clazz,0);
}
|
6552338_4
|
public RecordFactory getRecordFactory() throws ResourceException {
try {
if (recordFactory == null) {
JCoRepository repository = ((ConnectionImpl)getConnection()).getDestination().getRepository();
recordFactory = CciFactoryImpl.eINSTANCE.createRecordFactory();
((org.jboss.jca.adapters.sap.cci.impl.RecordFactoryImpl)recordFactory).setRepository(repository);
}
return recordFactory;
} catch (JCoException e) {
throw ExceptionBundle.EXCEPTIONS.failedToGetRecordFactory(e);
}
}
|
6563886_6
|
public Object convert(String value) {
return value;
}
|
6603193_10
|
@Override
public boolean remove(@Nullable Object element)
{
int length = array.length;
int index = indexOf(element, array, 0, length);
if (index < 0)
{
return false;
}
Object[] newArray = new Object[length - 1];
System.arraycopy(array, 0, newArray, 0, index);
System.arraycopy(array, index + 1, newArray, index, length - index - 1);
array = newArray;
return true;
}
|
6605842_1
|
@Override
public void stop() {
logger.info("Stopping Topic manager.");
// we just unregister it with zookeeper to make it unavailable from hub servers list
try {
hubManager.unregisterSelf();
} catch (IOException e) {
logger.error("Error unregistering hub server :", e);
}
super.stop();
}
|
6662839_98
|
@Override
public Map<String, Object> parse(Map<String, Object> params) {
String line = (String) params.get("line");
if (line == null)
return null;
try {
Map<String, Object> m = new HashMap<String, Object>();
Scanner scanner = new Scanner(line);
scanner.useDelimiter("`");
// log header
m.put("version", Integer.valueOf(scanner.next()));
m.put("encrypt", Integer.valueOf(scanner.next()));
int type = Integer.valueOf(scanner.next());
m.put("type", type);
m.put("count", Integer.valueOf(scanner.next()));
m.put("utm_id", scanner.next());
if (type == 1) { // kernel log (packet filter)
parseFirewallLog(scanner, m);
} else if (type == 2) { // application log
parseApplicationLog(scanner, m);
}
return m;
} catch (Throwable t) {
logger.warn("kraken syslog parser: cannot parse trusguard log => " + line, t);
return null;
}
}
|
6682280_276
|
public static <T> KijiResult<T> create(
final EntityId entityId,
final KijiDataRequest dataRequest,
final Result unpagedRawResult,
final HBaseKijiTable table,
final KijiTableLayout layout,
final HBaseColumnNameTranslator columnTranslator,
final CellDecoderProvider decoderProvider
) throws IOException {
final Collection<Column> columnRequests = dataRequest.getColumns();
final KijiDataRequestBuilder unpagedRequestBuilder = KijiDataRequest.builder();
final KijiDataRequestBuilder pagedRequestBuilder = KijiDataRequest.builder();
unpagedRequestBuilder.withTimeRange(
dataRequest.getMinTimestamp(),
dataRequest.getMaxTimestamp());
pagedRequestBuilder.withTimeRange(dataRequest.getMinTimestamp(), dataRequest.getMaxTimestamp());
for (Column columnRequest : columnRequests) {
if (columnRequest.isPagingEnabled()) {
pagedRequestBuilder.newColumnsDef(columnRequest);
} else {
unpagedRequestBuilder.newColumnsDef(columnRequest);
}
}
final CellDecoderProvider requestDecoderProvider =
decoderProvider.getDecoderProviderForRequest(dataRequest);
final KijiDataRequest unpagedRequest = unpagedRequestBuilder.build();
final KijiDataRequest pagedRequest = pagedRequestBuilder.build();
if (unpagedRequest.isEmpty() && pagedRequest.isEmpty()) {
return new EmptyKijiResult<T>(entityId, dataRequest);
}
final HBaseMaterializedKijiResult<T> materializedKijiResult;
if (!unpagedRequest.isEmpty()) {
materializedKijiResult =
HBaseMaterializedKijiResult.create(
entityId,
unpagedRequest,
unpagedRawResult,
layout,
columnTranslator,
requestDecoderProvider);
} else {
materializedKijiResult = null;
}
final HBasePagedKijiResult<T> pagedKijiResult;
if (!pagedRequest.isEmpty()) {
pagedKijiResult =
new HBasePagedKijiResult<T>(
entityId,
pagedRequest,
table,
layout,
columnTranslator,
requestDecoderProvider);
} else {
pagedKijiResult = null;
}
if (unpagedRequest.isEmpty()) {
return pagedKijiResult;
} else if (pagedRequest.isEmpty()) {
return materializedKijiResult;
} else {
return DefaultKijiResult.create(dataRequest, materializedKijiResult, pagedKijiResult);
}
}
|
6682435_0
|
void writeTimestamp(File directory, Long timestamp) throws IOException {
File timestampFile = new File(directory, TIMESTAMP_FILE_NAME);
CheckinUtils.writeObjectToFile(timestampFile, timestamp);
}
|
6691222_1119
|
@Override
public DendroNode getRight() {
return right;
}
|
6719207_30
|
public long uniqueVersionId() {
IdGenerator idGenerator = hz.getIdGenerator(CoordinationStructures.VERSION_GENERATOR);
long id = idGenerator.newId();
int timeSeconds = (int) (System.currentTimeMillis() / 1000);
long paddedId = id << 32;
return paddedId + timeSeconds;
}
|
6725438_4
|
public static void transfer(final InputStream input, final OutputStream output, final BuffersPool buffersPool) throws IOException {
final InputStream in = buffersPool == null
? new BufferedInputStream(input, BUFFER_SIZE_8K)
: new PoolableBufferedInputStream(input, BUFFER_SIZE_8K, buffersPool);
final byte[] buffer = buffersPool == null
? new byte[BUFFER_SIZE_8K]
: buffersPool.get(BUFFER_SIZE_8K);
try {
int cnt;
while ((cnt = in.read(buffer)) != EOF) {
output.write(buffer, 0, cnt);
}
output.flush();
} finally {
closeQuietly(in);
if (buffersPool != null) {
buffersPool.release(buffer);
}
}
}
|
6726370_93
|
public boolean isGreaterThan(String version) {
JenkinsVersion create = create(version);
return this.cv.compareTo(create.cv) > 0;
}
|
6733624_195
|
public static List<FunctionSignature> parseFunctionRegistryAndValidateTypes(AptUtils aptUtils, TypeElement elm, GlobalParsingContext context) {
final List<ExecutableElement> methods = ElementFilter.methodsIn(elm.getEnclosedElements());
final Optional<String> keyspace = AnnotationTree.findKeyspaceForFunctionRegistry(aptUtils, elm);
final FunctionParamParser paramParser = new FunctionParamParser(aptUtils);
final TypeName parentType = TypeName.get(aptUtils.erasure(elm));
//Not allow to declare function in system keyspaces
if (keyspace.isPresent()) {
final String keyspaceName = keyspace.get();
aptUtils.validateFalse(FORBIDDEN_KEYSPACES.contains(keyspaceName) || FORBIDDEN_KEYSPACES.contains(keyspaceName.toLowerCase()),
"The provided keyspace '%s' on function registry class '%s' is forbidden because it is a system keyspace",
keyspaceName, parentType);
}
aptUtils.validateFalse(keyspace.isPresent() && isBlank(keyspace.get()),
"The declared keyspace for function registry '%s' should not be blank", elm.getSimpleName().toString());
return methods
.stream()
.map(method -> {
final String methodName = method.getSimpleName().toString();
final List<AnnotationTree> annotationTrees = AnnotationTree.buildFromMethodForParam(aptUtils, method);
final List<? extends VariableElement> parameters = method.getParameters();
final List<FunctionParamSignature> parameterSignatures = new ArrayList<>(parameters.size());
for (int i = 0; i< parameters.size(); i++) {
final VariableElement parameter = parameters.get(i);
context.nestedTypesValidator().validate(aptUtils, annotationTrees.get(i), method.toString(), parentType);
final FunctionParamSignature functionParamSignature = paramParser
.parseParam(context, annotationTrees.get(i), parentType, methodName, parameter.getSimpleName().toString());
parameterSignatures.add(functionParamSignature);
}
//Validate return type
final TypeMirror returnType = method.getReturnType();
aptUtils.validateFalse(returnType.getKind() == TypeKind.VOID,
"The return type for the method '%s' on class '%s' should not be VOID",
method.toString(), elm.getSimpleName().toString());
aptUtils.validateFalse(returnType.getKind().isPrimitive(),
"Due to internal JDK API limitations, UDF/UDA return types cannot be primitive. " +
"Use their Object counterpart instead for method '%s' " +
"in function registry '%s'", method.toString(), elm.getQualifiedName());
final FunctionParamSignature returnTypeSignature = paramParser.parseParam(context,
AnnotationTree.buildFromMethodForReturnType(aptUtils, method),
parentType, methodName, "returnType");
// Validate NOT system function comparing only name lowercase
aptUtils.validateFalse(SYSTEM_FUNCTIONS_NAME.contains(methodName.toLowerCase()),
"The name of the function '%s' in class '%s' is reserved for system functions", method, parentType);
return new FunctionSignature(keyspace, parentType, methodName, returnTypeSignature, parameterSignatures);
})
.collect(toList());
}
|
6752107_4
|
public static long parseDuration(String duration) {
if (duration == null || duration.isEmpty()) {
throw new IllegalArgumentException("duration may not be null");
}
long toAdd = -1;
if (days.matcher(duration).matches()) {
Matcher matcher = days.matcher(duration);
matcher.matches();
toAdd = Long.parseLong(matcher.group(1)) * 60 * 60 * 24 * 1000;
} else if (hours.matcher(duration).matches()) {
Matcher matcher = hours.matcher(duration);
matcher.matches();
toAdd = Long.parseLong(matcher.group(1)) * 60 * 60 * 1000;
} else if (minutes.matcher(duration).matches()) {
Matcher matcher = minutes.matcher(duration);
matcher.matches();
toAdd = Long.parseLong(matcher.group(1)) * 60 * 1000;
} else if (seconds.matcher(duration).matches()) {
Matcher matcher = seconds.matcher(duration);
matcher.matches();
toAdd = Long.parseLong(matcher.group(1)) * 1000;
} else if (milliseconds.matcher(duration).matches()) {
Matcher matcher = milliseconds.matcher(duration);
matcher.matches();
toAdd = Long.parseLong(matcher.group(1));
}
if (toAdd == -1) {
throw new IllegalArgumentException("Invalid duration pattern : " + duration);
}
return toAdd;
}
|
6764581_1
|
@Override
public void destroy(final Object instance) {
if (instance != null) {
try {
invokeAnnotatedLifecycleMethod(instance, instance.getClass(), PreDestroy.class);
} catch (Exception e) {
LOGGER.failToDestroyArtifact(e, instance);
}
}
}
|
6780534_29
|
@Override public Observable<Void> delete(String messageId) {
return apiService.deleteMessage(messageId);
}
|
6791064_5
|
public void triggle(Date now) {
Map<String, Task> tasks = scheduler.getAllRegistedTask();
Transaction t = Cat.newTransaction("Time-2", "CronTabTriggle");
for (Task task : tasks.values()) {
Cat.logEvent("For","");
if (task.getStatus() != TaskStatus.RUNNING) {
continue;
}
// validate the cron-expression
CronExpression ce = null;
try {
ce = new CronExpression(task.getCrontab());
} catch (ParseException e) {
LOG.error("Parse contab error for task id : " + task.getTaskid() + " when crontab string is : " + task.getCrontab());
try {
scheduler.suspendTask(task.getTaskid());
} catch (ScheduleException e1) {
LOG.error("Fail to suspend the task : " + task.getTaskid(), e1);
}
continue;
}
Cat.logEvent("getPreviourFireTime", "");
//get the previous fire time and previous attempt
Date previousFireTime = getPreviousFireTime(task, now);
// for update the crontab expression
if(previousFireTime.before(task.getUpdatetime())){
previousFireTime = task.getUpdatetime();
}
//iterator each fire time from last previousFireTime to current.
Cat.logEvent("Next-Time", "");
Date nextFireTime = ce.getNextValidTimeAfter(previousFireTime);
Cat.logEvent("Next-While", "");
while (nextFireTime.before(now)) {
String instanceID = idFactory.newInstanceID(task.getTaskid());
TaskAttempt attempt = new TaskAttempt();
String attemptID = idFactory.newAttemptID(instanceID);
attempt.setInstanceid(instanceID);
attempt.setTaskid(task.getTaskid());
attempt.setScheduletime(nextFireTime);
attempt.setStatus(AttemptStatus.INITIALIZED);
attempt.setAttemptid(attemptID);
attemptMapper.insert(attempt);
LOG.info(String.format("New attempt (%s) fired.", attemptID));
nextFireTime = ce.getNextValidTimeAfter(nextFireTime);
}
}
t.setStatus(Message.SUCCESS);
t.complete();
}
|
6804081_10
|
Class<?>[] getAllInterfacesAndClasses(Class<?> clazz) {
return getAllInterfacesAndClasses(new Class[] { clazz } );
}
|
6810283_20
|
public void validate(Object obj, Errors errors) {
AppointmentType appointmentType = (AppointmentType) obj;
if (appointmentType == null) {
errors.rejectValue("appointmentType", "error.general");
} else {
validateDurationField(errors, appointmentType);
validateFieldName(errors, appointmentType);
validateDescriptionField(errors, appointmentType.getDescription());
}
}
|
6821657_32
|
@Override
public MatchField matches(StubMessage request) {
String expected = JsonUtils.prettyPrint(pattern);
String actual = JsonUtils.prettyPrint(request.getBody());
MatchResult result = matchResult(request);
MatchField field = new MatchField(FieldType.BODY, "body", expected);
if (result.isMatch()) {
return field.asMatch(actual);
} else {
return field.asMatchFailure(actual, result.message());
}
}
|
6822394_1121
|
public List<Handler> buildHandlerChainFromClass(Class<?> clz, List<Handler> existingHandlers,
QName portQName, QName serviceQName, String bindingID) {
LOG.fine("building handler chain");
classLoader = clz.getClassLoader();
HandlerChainAnnotation hcAnn = findHandlerChainAnnotation(clz, true);
List<Handler> chain = null;
if (hcAnn == null) {
LOG.fine("no HandlerChain annotation on " + clz);
chain = new ArrayList<Handler>();
} else {
hcAnn.validate();
try {
URL handlerFileURL = resolveHandlerChainFile(clz, hcAnn.getFileName());
if (handlerFileURL == null) {
throw new WebServiceException(new Message("HANDLER_CFG_FILE_NOT_FOUND_EXC", BUNDLE, hcAnn
.getFileName()).toString());
}
Document doc = XMLUtils.parse(handlerFileURL.openStream());
Element el = doc.getDocumentElement();
if (!"http://java.sun.com/xml/ns/javaee".equals(el.getNamespaceURI())
|| !"handler-chains".equals(el.getLocalName())) {
String xml = XMLUtils.toString(el);
throw new WebServiceException(
BundleUtils.getFormattedString(BUNDLE,
"NOT_VALID_ROOT_ELEMENT",
"http://java.sun.com/xml/ns/javaee"
.equals(el.getNamespaceURI()),
"handler-chains".equals(el.getLocalName()),
xml, handlerFileURL));
}
chain = new ArrayList<Handler>();
Node node = el.getFirstChild();
while (node != null) {
if (node instanceof Element) {
el = (Element)node;
if (!el.getNamespaceURI().equals("http://java.sun.com/xml/ns/javaee")
|| !el.getLocalName().equals("handler-chain")) {
String xml = XMLUtils.toString(el);
throw new WebServiceException(
BundleUtils.getFormattedString(BUNDLE,
"NOT_VALID_ELEMENT_IN_HANDLER",
xml));
}
processHandlerChainElement(el, chain,
portQName, serviceQName, bindingID);
}
node = node.getNextSibling();
}
} catch (WebServiceException e) {
throw e;
} catch (Exception e) {
throw new WebServiceException(BUNDLE.getString("CHAIN_NOT_SPECIFIED_EXC"), e);
}
}
assert chain != null;
if (existingHandlers != null) {
chain.addAll(existingHandlers);
}
return sortHandlers(chain);
}
|
6827663_4
|
@Override
public long calculate(int order) {
return order < 3 ? 1 : calculate(order-1) + calculate(order-2);
}
|
6830643_0
|
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
|
6833345_0
|
NGSession take() {
synchronized (lock) {
if (done) {
throw new UnsupportedOperationException("NGSession pool is shutting down");
}
NGSession session = idlePool.poll();
if (session == null) {
session = instanceCreator.get();
session.start();
}
workingPool.add(session);
return session;
}
}
|
6848534_3
|
public TopWordCounts findTop(int number, Comparator<Integer> comparator) {
return analyse(new FindTopAnalysis(number, comparator));
}
|
6863498_22
|
public static List<IssueDTO> getIssues(String url, String username, String password, String path, String query) {
WebClient client = createClient(url);
checkAutherization(client, username, password);
// Go to baseURI
client.back(true);
client.path(path);
if ( !query.isEmpty() ) {
client.query("jql", query);
}
client.query("maxResults", MAX_RESULTS);
client.query("fields", StringUtils.deleteWhitespace(FIELDS_TO_INCLUDE_IN_RESPONSE));
SearchResultDTO searchResult = client.get(SearchResultDTO.class);
return searchResult.getIssues();
}
|
6867673_30
|
public Set<String> getKeys() {
@SuppressWarnings("unchecked")
final Set<String> result = new HashSet<String>(this.values.keySet());
return result;
}
|
6872642_22
|
public String edit() {
if (id == null) {
id = new Long(getParameter("id"));
}
person = personManager.get(id);
return "edit";
}
|
6879138_0
|
@Override
public Model open(Assembler a, Resource root, Mode mode) {
List<Statement> lst = root.listProperties().toList();
Resource rootModel = getUniqueResource( root, BASE_MODEL );
if (rootModel == null)
{
throw new AssemblerException( root, String.format( "No %s provided for %s", BASE_MODEL, root ));
}
Model baseModel = a.openModel(rootModel, mode);
Literal modelName = getUniqueLiteral( root, JA.modelName );
if (modelName == null)
{
throw new AssemblerException( root, String.format( "No %s provided for %s", JA.modelName, root ));
}
Literal factoryName = getUniqueLiteral( root, EVALUATOR_FACTORY );
if (factoryName == null)
{
throw new AssemblerException( root, String.format( "No %s provided for %s", EVALUATOR_FACTORY, root ));
}
SecurityEvaluator securityEvaluator = null;
try
{
Class<?> factoryClass = Class.forName( factoryName.getString() );
Method method = factoryClass.getMethod("getInstance" );
if ( ! SecurityEvaluator.class.isAssignableFrom(method.getReturnType()))
{
throw new AssemblerException( root, String.format( "%s (found at %s for %s) getInstance() must return an instance of SecurityEvaluator", factoryName, EVALUATOR_FACTORY, root ));
}
if ( ! Modifier.isStatic( method.getModifiers()))
{
throw new AssemblerException( root, String.format( "%s (found at %s for %s) getInstance() must be a static method", factoryName, EVALUATOR_FACTORY, root ));
}
securityEvaluator = (SecurityEvaluator) method.invoke( null );
}
catch (SecurityException e)
{
throw new AssemblerException( root, String.format( "Error finding factory class %s: %s", factoryName, e.getMessage() ), e);
}
catch (IllegalArgumentException e)
{
throw new AssemblerException( root, String.format( "Error finding factory class %s: %s", factoryName, e.getMessage() ), e);
}
catch (ClassNotFoundException e)
{
throw new AssemblerException( root, String.format( "Class %s (found at %s for %s) could not be loaded", factoryName, EVALUATOR_FACTORY, root ));
}
catch (NoSuchMethodException e)
{
throw new AssemblerException( root, String.format( "%s (found at %s for %s) must implement a static getInstance() that returns an instance of SecurityEvaluator", factoryName, EVALUATOR_FACTORY, root ));
}
catch (IllegalAccessException e)
{
throw new AssemblerException( root, String.format( "Error finding factory class %s: %s", factoryName, e.getMessage() ), e);
}
catch (InvocationTargetException e)
{
throw new AssemblerException( root, String.format( "Error finding factory class %s: %s", factoryName, e.getMessage() ), e);
}
return Factory.getInstance(securityEvaluator, modelName.asLiteral().getString(), baseModel);
}
|
6900541_1
|
public static String readableFileSize(long size) {
if(size <= 0) return "0 KB";
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size)/Math.log10(1000));
return new DecimalFormat("#,##0.#").format(size/Math.pow(1000, digitGroups)) + " " + units[digitGroups];
}
|
6921975_21
|
public static String createRequestSignature(final String method, final String dateHeader, final String requestUri, ByteSource body, final String secretKey) {
final String signatureBase = createSignatureBase(method, dateHeader, requestUri, body);
return createRequestSignature(signatureBase, secretKey);
}
|
6944525_585
|
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback)
{
//This code path cannot accept content types or accept types that contain
//multipart/related. This is because these types of requests will usually have very large payloads and therefore
//would degrade server performance since RestRequest reads everything into memory.
if (!isMultipart(request, callback))
{
_restRestLiServer.handleRequest(request, requestContext, callback);
}
}
|
6946733_5
|
public final byte[] getNextJobHandle() {
String handle = "H:".concat(clusterHostname).concat(":").concat(String.valueOf(jobHandleCounter.incrementAndGet()));
return handle.getBytes();
}
|
6951233_116
|
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
public void post(HttpServletRequest request, @RequestBody Map<String, String> body) {
String localeStr = body.get("locale");
if (localeStr != null) {
Locale locale = null;
try {
locale = LocaleUtils.toLocale(localeStr);
}
catch (IllegalArgumentException e) {
throw new APIException(" '" + localeStr + "' does not represent a valid locale.");
}
Set<Locale> allowedLocales = new HashSet<Locale>(Context.getAdministrationService().getAllowedLocales());
if (allowedLocales.contains(locale)) {
Context.setLocale(locale);
} else {
throw new APIException(" '" + localeStr + "' is not in the list of allowed locales.");
}
}
String locationUuid = body.get("sessionLocation");
if (locationUuid != null) {
Location location = Context.getLocationService().getLocationByUuid(locationUuid);
if (location == null) {
throw new APIException(" '" + locationUuid + "' is not the UUID of any location.");
}
Context.getUserContext().setLocation(location);
{ // for compatability with AppUi session location
request.getSession().setAttribute("emrContext.sessionLocationId", location.getId());
}
}
}
|
6961882_16
|
public static String parseCharset(Map<String, String> headers, String defaultCharset) {
String contentType = headers.get(HTTP.CONTENT_TYPE);
if (contentType != null) {
String[] params = contentType.split(";");
for (int i = 1; i < params.length; i++) {
String[] pair = params[i].trim().split("=");
if (pair.length == 2) {
if (pair[0].equals("charset")) {
return pair[1];
}
}
}
}
return defaultCharset;
}
|
6963527_2
|
@Override
public void validate(Problems problems, String compName, String model) {
if (model.length() == 0) {
problems.add(NbBundle.getMessage(StringValidators.class,
"INVALID_HOST_NAME", compName, model)); //NOI18N
return;
}
if (model.startsWith(".") || model.endsWith(".")) { //NOI18N
problems.add(NbBundle.getMessage(StringValidators.class,
"HOST_STARTS_OR_ENDS_WITH_PERIOD", model)); //NOI18N
return;
}
String[] parts = model.split("\\.");
if (parts.length > 4) {
problems.add(NbBundle.getMessage(StringValidators.class,
"TOO_MANY_LABELS", model)); //NOI18N
return;
}
if (!allowPort && model.contains(":")) { //NOI18N
problems.add(NbBundle.getMessage(StringValidators.class,
"MSG_PORT_NOT_ALLOWED", compName, model)); //NOI18N
return;
}
StringValidators.NO_WHITESPACE.validate(problems, compName, model);
if (model.endsWith("-") || model.startsWith("-")) {
problems.add(NbBundle.getMessage(StringValidators.class,
"INVALID_HOST_NAME", compName, model)); //NOI18N
return;
}
boolean[] numbers = new boolean[parts.length];
for (int i = 0; i < parts.length; i++) {
String label = parts[i];
if (label.length() > 63) {
problems.add(NbBundle.getMessage(StringValidators.class,
"LABEL_TOO_LONG", label)); //NOI18N
return;
}
if (i == parts.length - 1 && label.indexOf(":") > 0) {
String[] labelAndPort = label.split(":");
if (labelAndPort.length > 2) {
problems.add(NbBundle.getMessage(StringValidators.class,
"INVALID_PORT", compName, label)); //NOI18N
return;
}
if (labelAndPort.length == 1) {
problems.add(NbBundle.getMessage(StringValidators.class,
"INVALID_PORT", compName, "''")); //NOI18N
return;
}
if (label.endsWith(":")) {
problems.add(NbBundle.getMessage(StringValidators.class,
"TOO_MANY_COLONS", compName, label)); //NOI18N
return;
}
try {
int port = Integer.parseInt(labelAndPort[1]);
if (port < 0) {
problems.add(NbBundle.getMessage(StringValidators.class,
"NEGATIVE_PORT", port)); //NOI18N
return;
} else if (port >= 65536) {
problems.add(NbBundle.getMessage(StringValidators.class,
"PORT_TOO_HIGH", port)); //NOI18N
return;
}
} catch (NumberFormatException e) {
problems.add(NbBundle.getMessage(StringValidators.class,
"INVALID_PORT", compName, labelAndPort[1])); //NOI18N
return;
}
if(!checkHostPart(labelAndPort[0], problems, compName, i, numbers)){
return;
}
} else {
checkHostPart(label, problems, compName, i, numbers);
}
} // for
if (numbers[numbers.length - 1]) {
problems.add(NbBundle.getMessage(StringValidators.class,
"NUMBER_PART_IN_HOSTNAME", parts[numbers.length - 1])); //NOI18N
}
}
|
6969798_0
|
public static AisStoreQueryBuilder forTime() {
return new AisStoreQueryBuilder(null, null);
}
|
6972004_6
|
public static <T, V> Matcher<T> compose(final Function<T, ? extends V> transformer, final Matcher<V> matcher) {
checkNotNull(transformer, "transformer");
checkNotNull(matcher, "matcher");
return new TypeSafeMatcher<T>() {
@Override
public void describeTo(final Description description) {
description.appendText("a value that when transformed by " + transformer + " is ");
matcher.describeTo(description);
}
@Override
public boolean matchesSafely(final T item) {
V transformed = transformer.apply(item);
return matcher.matches(transformed);
}
};
}
|
7010395_8
|
@JsonCreator
public static Duration valueOf(String text) {
String trimmed = WHITESPACE.removeFrom(text).trim();
return new Duration(quantity(trimmed), unit(trimmed));
}
|
7014975_0
|
@Override
public TimeOut newTimeout(TimerTask task, long delay, TimeUnit unit) {
start();
if (task == null) {
throw new NullPointerException("task");
}
if (unit == null) {
throw new NullPointerException("unit");
}
long deadline = System.nanoTime() + unit.toNanos(delay) - startTime;
// Add the timeout to the wheel.
HashedWheelTimeOut timeout;
lock.readLock().lock();
try {
timeout = new HashedWheelTimeOut(task, deadline);
if (workerState.get() == WORKER_STATE_SHUTDOWN) {
throw new IllegalStateException("Cannot enqueue after shutdown");
}
wheel[timeout.stopIndex].add(timeout);
} finally {
lock.readLock().unlock();
}
return timeout;
}
|
7015517_16
|
public static boolean isValid(String pluginKey) {
return StringUtils.isNotBlank(pluginKey) && StringUtils.isAlphanumeric(pluginKey);
}
|
7022775_194
|
public byte[] getExtensionBytes() {
return Arrays.copyOf(extensionBytes, extensionBytes.length);
}
|
7028076_1
|
public RequestToken getRequestToken() {
final Twitter twitter = factory.getInstance();
try {
return twitter.getOAuthRequestToken();
} catch (TwitterException e) {
throw this.wrapException(e);
}
}
|
7031510_60
|
protected static int maxFileNumber(String baseDir, String database, String date, String prefix, String suffix) {
File[] files = visitFiles(baseDir, database, date, prefix, suffix);
int max = -1;
for (File file : files) {
int number = parseNumber(file, prefix, suffix);
max = number > max ? number : max;
}
return max;
}
|
7033568_0
|
public MinigamePlayerManager getPlayerManager() {
return this.playerManager;
}
|
7043506_11
|
public static Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> aggregateGroupedStreams(Observable<GroupedObservable<InstanceKey, Map<String, Object>>> stream) {
return aggregateUsingFlattenedGroupBy(stream);
}
|
7056723_44
|
public MethodCaller create() {
Object key = KEY_FACTORY.newInstance(callTarget.getTargetMethod(), null);
try {
return (MethodCaller) super.create(key);
}
catch (Mock4AjException error) { // NOPMD
throw error;
}
catch (Exception error) {
throw new Mock4AjException("An error occurs during the creation of the Caller "
+ "class. If you can't find the problem by looking to the "
+ "cause, please contact the mailing list. ", error);
}
}
|
7072487_3
|
public String createEntitlement() {
List<String> entitlementStrings = listEntitlements();
if (entitlementStrings.isEmpty()) {
return null;
}
return StringUtils.join(entitlementStrings, ENTITLEMENT_SEPARATOR);
}
|
7091762_2
|
public static String getDescription(String expression) throws ParseException {
return getDescription(DescriptionTypeEnum.FULL, expression, new Options(), I18nMessages.DEFAULT_LOCALE);
}
|
7095532_15
|
public static final void log() {
log.info("\n{}", asText());
}
|
7109191_7
|
public static final JavaScriptSettingsBuilder newBuilder() {
return new JavaScriptSettingsBuilder() {
private JQueryUiBuilder jqueryUiBuilder;
private BootstrapJsBuilder bootstrapJsBuilder;
@Override
public JQueryUiBuilder withJqueryUi(JQueryUiBuilderFactory factory) {
jqueryUiBuilder = factory.newBuilder(this);
return jqueryUiBuilder;
}
@Override
public BootstrapJsBuilder withBootstrapJs(BootstrapJsBuilderFactory factory) {
bootstrapJsBuilder = factory.newBuilder(this);
return bootstrapJsBuilder;
}
@Override
public JavaScriptSettings build() {
return new JavaScriptSettings(
jqueryUiBuilder == null ? new JQueryUiSettings() : jqueryUiBuilder.build(),
bootstrapJsBuilder == null ? new BootstrapJsSettings() : bootstrapJsBuilder.build());
}
};
}
|
7137340_9
|
public synchronized void add(T item) {
if (item == null) {
throw new IllegalArgumentException("item is null");
}
buffer[tail++] = item;
tail %= buffer.length;
if (tail == head) {
head = (head + 1) % buffer.length;
}
}
|
7139471_49
|
@Override public void onItemSelected(AdapterView<?> viewAdapter, View view, int position, long id) {
if (view == null) {
return;
}
setMultiViewVideoActivity(activity);
findViews();
CategoryInfo item = (CategoryInfo) viewAdapter.getItemAtPosition(position);
if (savedInstanceCategory != null) {
int savedInstancePosition = getSavedInstancePosition(viewAdapter);
item = (CategoryInfo) viewAdapter.getItemAtPosition(savedInstancePosition);
viewAdapter.setSelection(savedInstancePosition);
savedInstanceCategory = null;
if (item.getLevel() == 0) {
createGallery(item);
} else {
populateSecondaryCategory();
return;
}
}
if (isFirstSelection()) {
String filter = prefs.getString("serenity_category_filter", "all");
int count = viewAdapter.getCount();
for (int i = 0; i < count; i++) {
CategoryInfo citem = (CategoryInfo) viewAdapter.getItemAtPosition(i);
if (citem.getCategory().equals(filter)) {
item = citem;
selected = citem.getCategory();
viewAdapter.setSelection(i);
continue;
}
}
createGallery(item);
setFirstSelection(false);
return;
}
if (selected.equalsIgnoreCase(item.getCategory())) {
return;
}
selected = item.getCategory();
category = item.getCategory();
categoryState.setCategory(selected);
if (item.getLevel() == 0) {
secondarySpinner.setVisibility(View.INVISIBLE);
createGallery(item);
} else {
populateSecondaryCategory();
}
}
|
7144342_0
|
Future(MessagePack messagePack, FutureImpl impl) {
this(messagePack, impl, null);
}
|
7170387_1
|
@Override
public void validate(@Nullable String database, String role) throws ConfigurationException {
/*
* Rule only applies to rules in per database policy file
*/
if(database != null) {
Iterable<Authorizable> authorizables = parseRole(role);
/*
* Each permission in a non-global file must have a database
* object except for URIs.
*
* We allow URIs to be specified in the per DB policy file for
* ease of mangeability. URIs will contain to remain server scope
* objects.
*/
boolean foundDatabaseInAuthorizables = false;
boolean foundURIInAuthorizables = false;
boolean allowURIInAuthorizables = false;
if ("true".equalsIgnoreCase(
System.getProperty(SimplePolicyEngine.ACCESS_ALLOW_URI_PER_DB_POLICYFILE))) {
allowURIInAuthorizables = true;
}
for(Authorizable authorizable : authorizables) {
if(authorizable instanceof Database) {
foundDatabaseInAuthorizables = true;
}
if (authorizable instanceof AccessURI) {
if (foundDatabaseInAuthorizables) {
String msg = "URI object is specified at DB scope in " + role;
throw new ConfigurationException(msg);
}
foundURIInAuthorizables = true;
}
}
if(!foundDatabaseInAuthorizables && !(foundURIInAuthorizables && allowURIInAuthorizables)) {
String msg = "Missing database object in " + role;
throw new ConfigurationException(msg);
}
}
}
|
7212262_3
|
@Override
public int getPhase() {
return Integer.MAX_VALUE;
}
|
7220231_1
|
public static TimeZone getTimeZone(int index, boolean observeDaylightSaving, String tzId) throws IOException {
if (index < 0 || index > 59)
return null;
int bias = 0; // UTC offset in minutes
int standardBias = 0; // offset in minutes from bias during standard time.; has a value of 0 in most cases
int daylightBias = 0; // offset in minutes from bias during daylight saving time.
SYSTEMTIME StandardDate = null;
SYSTEMTIME DaylightDate = null;
int startMonth = 0; // 1 - January, 12 - December
int startDayOfWeek = 0; // 0 - Sunday, 6 - Saturday
int startDay = 0; // day of the week within the month, 5 = last occurrence of that day
int startHour = 0;
int endMonth = 0;
int endDayOfWeek = 0;
int endDay = 0;
int endHour = 0;
// get the UTC+12 standard offset in minutes from MS_OXOCAL_STANDARD_OFFSET table!!
int utcPlus12offset = MS_OXOCAL_STANDARD_OFFSET[index][0];
int indexToDaytimeSavingDatesTable = MS_OXOCAL_STANDARD_OFFSET[index][1];
if (utcPlus12offset > 12*60)
bias = (utcPlus12offset - 12*60) * -1;
else if (utcPlus12offset < 12*60)
bias = (12*60 - utcPlus12offset);
if (indexToDaytimeSavingDatesTable == -1 || !observeDaylightSaving) {
int utcOffsetInMilliseconds = bias * 60 * 1000;
return getNoDaylightSavingTimeZoneFromUtcOffset(utcOffsetInMilliseconds);
}
// handle the daylight saving case here...
// HACK!!
// HACK!!
// TZRule.getStandardUtcOffset() always multiply the offset by -1;
// Hence, we are multiplying by -1 in reverse order.
bias = bias * -1;
// If daylight saving time is observed, during the daylight time period,
// an additional -60 offset is added to the standard offset.
daylightBias = -60;
startMonth = MS_OXOCAL_STAN_DST_DATES[indexToDaytimeSavingDatesTable][1][0];
startDayOfWeek = MS_OXOCAL_STAN_DST_DATES[indexToDaytimeSavingDatesTable][1][1];
startDay = MS_OXOCAL_STAN_DST_DATES[indexToDaytimeSavingDatesTable][1][2];
startHour = MS_OXOCAL_STAN_DST_DATES[indexToDaytimeSavingDatesTable][1][3];
endMonth = MS_OXOCAL_STAN_DST_DATES[indexToDaytimeSavingDatesTable][0][0];
endDayOfWeek = MS_OXOCAL_STAN_DST_DATES[indexToDaytimeSavingDatesTable][0][1];
endDay = MS_OXOCAL_STAN_DST_DATES[indexToDaytimeSavingDatesTable][0][2];
endHour = MS_OXOCAL_STAN_DST_DATES[indexToDaytimeSavingDatesTable][0][3];
StandardDate = new SYSTEMTIME(endMonth, endDayOfWeek, endDay, endHour);
DaylightDate = new SYSTEMTIME(startMonth, startDayOfWeek, startDay, startHour);
if (sLog.isDebugEnabled()) {
StringBuilder debugInfo = new StringBuilder();
debugInfo.append(bias * -1 + " " +
"{" + endMonth + "," + endDayOfWeek + "," + endDay + "," + endHour + "} " +
"{" + startMonth + "," + startDayOfWeek + "," + startDay + "," + startHour + "}");
sLog.debug(debugInfo);
}
String timeZoneId;
if (tzId == null || tzId.length() == 0)
timeZoneId = DEFAULT_TNEF_TIMEZONE_ID;
else
timeZoneId = tzId;
TimeZoneDefinition timeZoneDefinition = new TimeZoneDefinition(timeZoneId, bias, standardBias, daylightBias, StandardDate, DaylightDate);
return timeZoneDefinition.getTimeZone();
}
|
7257232_7
|
public static String canonicaliseURL(String url) {
return canonicaliseURL(url, true, true);
}
|
7263059_8
|
static HttpDownloadContinuationMarker validateInitialExchange(final Pair<String, Request> requestHints,
final int responseCode,
final Pair<String, Response> responseFingerprint)
throws ProtocolException {
// there was an if-match header and the response etag does not match
if (requestHints.getLeft() != null && !requestHints.getLeft().equals(responseFingerprint.getLeft())) {
throw new ProtocolException(
String.format(
"ETag does not match If-Match: If-Match [%s], ETag [%s]",
requestHints.getLeft(),
responseFingerprint.getLeft()));
}
final boolean rangeRequest = requestHints.getRight() != null;
// there was a request range and an invalid response range (or none) was returned
// Note: we should use the more complete range (the response range) to invoke match so as many values are
// compared as possible
if (rangeRequest && !requestHints.getRight().matches(responseFingerprint.getRight())) {
throw new ProtocolException(
String.format(
"Content-Range does not match Request range: Range [%s], Content-Range [%s]",
requestHints.getRight(),
responseFingerprint.getRight()));
}
// if there was a request range the response code should be 206
if (rangeRequest && responseCode != SC_PARTIAL_CONTENT) {
throw new ProtocolException(
String.format(
"Unexpected response code for range request: expected [%d], got [%d]",
SC_PARTIAL_CONTENT,
responseCode));
}
// if there was no request range the response code should be 200
if (!rangeRequest && responseCode != SC_OK) {
throw new ProtocolException(
String.format(
"Unexpected response code for non-range request: expected [%d], got [%d]",
SC_OK,
responseCode));
}
return new HttpDownloadContinuationMarker(responseFingerprint.getLeft(), responseFingerprint.getRight());
}
|
7272424_1
|
public void applyShippingPromotions(ShoppingCart shoppingCart) {
if ( shoppingCart != null ) {
//PROMO: if cart total is greater than 75, free shipping
if ( shoppingCart.getCartItemTotal() >= 75) {
shoppingCart.setShippingPromoSavings(shoppingCart.getShippingTotal() * -1);
shoppingCart.setShippingTotal(0);
}
}
}
|
7276954_28
|
public static AlluxioURI getTablePathUdb(String dbName, String tableName, String udbType) {
return new AlluxioURI(PathUtils
.concatPath(ServerConfiguration.get(PropertyKey.TABLE_CATALOG_PATH), dbName, TABLES_ROOT,
tableName, udbType));
}
|
7286420_7
|
public Module wrap(final Module module) {
if (module instanceof PrivateModule) {
return new PrivateModule() {
@Override
protected void configure() {
if (modules.add(module)) {
module.configure(createForwardingBinder(binder()));
install(ProviderMethodsModule.forModule(module));
}
}
};
}
return (Binder binder) -> {
if (modules.add(module)) {
module.configure(createForwardingBinder(binder));
binder.install(ProviderMethodsModule.forModule(module));
}
};
}
|
7308129_2
|
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write(String.valueOf(new Date().getTime()));
}
|
7316492_0
|
public String get(Locale locale) {
return localized.get(locale);
}
|
7321072_139
|
public LinkedList<Token> tokenize(String text) {
if (logger.isDebugEnabled())
logger.debug("Tokenizing text: '" + text + "'");
text = text.replaceAll(" +", " "); // remove multiple consequent space chars
text = text.trim();
final LinkedList<TextBlock> textBlocks = textBlockSplitter.splitToTextParts(text);
this.textBlockSplitter.addTextStartsAndEnds(textBlocks, this.blockSize);
final LinkedList<Token> tokens = new LinkedList<Token>();
StringBuilder currentTokenBuilder = new StringBuilder();
List<TextBlockType> currentBlockTypes = new LinkedList<TextBlockType>();
for (int i = this.blockSize; i <= textBlocks.size() - this.blockSize; i++) {
final TextBlockGroup leftTextBlockGroup = this.textBlockSplitter.getTextBlockGroup(textBlocks, this.blockSize, i - this.blockSize);
final TextBlockGroup rightTextBlockGroup = this.textBlockSplitter.getTextBlockGroup(textBlocks, this.blockSize, i);
if (logger.isDebugEnabled())
logger.debug("Applying rule for left : " + leftTextBlockGroup.getTextBlockTypeGroup() + " right :" + rightTextBlockGroup.getTextBlockTypeGroup());
boolean addSpace;
try {
addSpace = this.graph.isAddSpace(leftTextBlockGroup, rightTextBlockGroup, textBlocks, i);
if (this.stats != null)
this.stats.addSuccess(leftTextBlockGroup, rightTextBlockGroup);
} catch (MissingTokenizationRuleException ex) {
if (strict) {
throw ex;
} else {
addSpace = false;
if (this.stats != null)
this.stats.addFail(ex);
}
}
final TextBlock firstTextBlock = rightTextBlockGroup.getFirstTextBlock();
final String textToAdd = firstTextBlock.getText();
final TextBlockType textBlockType = firstTextBlock.getTextBlockType();
if (addSpace || SPACE.equals(textToAdd)) {
if (currentTokenBuilder.length() > 0){
tokens.add(new Token(currentTokenBuilder.toString(), currentBlockTypes));
}
if (SPACE.equals(textToAdd)){
currentTokenBuilder = new StringBuilder();
currentBlockTypes = new LinkedList<TextBlockType>();
}
else{
currentTokenBuilder = new StringBuilder(textToAdd);
currentBlockTypes.add(textBlockType);
}
} else {
currentTokenBuilder.append(textToAdd);
currentBlockTypes.add(textBlockType);
}
}
if (currentTokenBuilder.length() > 0)
tokens.add(new Token(currentTokenBuilder.toString(), currentBlockTypes));
return tokens;
}
|
7324677_12
|
public static SRTInfo read(File srtFile) throws InvalidSRTException, SRTReaderException {
if (!srtFile.exists()) {
throw new SRTReaderException(srtFile.getAbsolutePath() + " does not exist");
}
if (!srtFile.isFile()) {
throw new SRTReaderException(srtFile.getAbsolutePath() + " is not a regular file");
}
SRTInfo srtInfo = new SRTInfo();
try (BufferedReader br = new BufferedReader(new FileReader(srtFile))) {
BufferedLineReader reader = new BufferedLineReader(br);
while (true) {
srtInfo.add(parse(reader));
}
} catch (EOFException e) {
// Do nothing
} catch (IOException e) {
throw new SRTReaderException(e);
}
return srtInfo;
}
|
7337208_1
|
public static Map<String, Long> readHashes( File file ) throws FileNotFoundException {
return readHashes( new FileInputStream(file) );
}
|
7352878_9
|
static ConfigObject mergeConfigObjects(ConfigObject lowPriorityCO,
ConfigObject highPriorityCO) {
return (ConfigObject) lowPriorityCO.merge(highPriorityCO);
}
|
7386322_2
|
@ResourceMapping(GET_TEMPLATES)
public void getTemplates(ResourceRequest request, ResourceResponse response, @RequestParam("page") int page, @RequestParam("rows") int rows)
throws Exception {
try {
User user = liferayService.getUser(request, response);
if (user == null) return;
List<Long> organizationIds = liferayService.getOrganizationIds(user);
List<ConfigurationTemplate> templates = templateService.loadAllForOrganizations(organizationIds);
createOnePageResponse(response, templates, page, rows);
}
catch (Exception e) {
ExceptionUtil.throwSystemException(e);
}
}
|
7393690_23
|
public static byte[] split(byte[] bytes, int start, int end) {
if (bytes == null) {
return null;
}
if (start < 0) {
throw new IllegalArgumentException("start < 0");
}
if (end > bytes.length) {
throw new IllegalArgumentException("end > size");
}
if (start > end) {
throw new IllegalArgumentException("start > end");
}
int len = end - start;
byte[] dest = new byte[len];
System.arraycopy(bytes, start, dest, 0, len);
return dest;
}
|
7403823_41
|
@SuppressWarnings("rawtypes")
public static List<Class> getCheckClasses() {
return CLASSES;
}
|
7403873_31
|
@Override
public void execute(SensorContext context) {
List<InputFile> inputFiles = new ArrayList<>();
fileSystem.inputFiles(mainFilesPredicate).forEach(inputFiles::add);
if (inputFiles.isEmpty()) {
return;
}
boolean isSonarLintContext = context.runtime().getProduct() == SonarProduct.SONARLINT;
ProgressReport progressReport = new ProgressReport("Report about progress of XML analyzer", TimeUnit.SECONDS.toMillis(10));
progressReport.start(inputFiles.stream().map(InputFile::toString).collect(Collectors.toList()));
boolean cancelled = false;
try {
for (InputFile inputFile : inputFiles) {
if (context.isCancelled()) {
cancelled = true;
break;
}
scanFile(context, inputFile, isSonarLintContext);
progressReport.nextFile();
}
} finally {
if (!cancelled) {
progressReport.stop();
} else {
progressReport.cancel();
}
}
}
|
7410462_0
|
public List<String> extract(String[] tokens) throws IOException {
return extract(parser.parse(tokens));
}
|
7416235_10
|
public static GraphName of(String name) {
return new GraphName(canonicalize(name));
}
|
7416278_0
|
@Override
public synchronized int read(byte[] buffer, int offset, int length) throws IOException {
int bytesRead = 0;
if (length > 0) {
while (available() == 0) {
// Block until there are bytes to read.
Thread.yield();
}
synchronized (readBuffer) {
bytesRead = Math.min(length, available());
System.arraycopy(readBuffer, readPosition, buffer, offset, bytesRead);
readPosition += bytesRead;
}
}
return bytesRead;
}
|
7416746_1
|
public synchronized Channel getFreeChannel() {
for (Channel c : channels) {
if (c.isFree()) {
c.setFree(false);
return c;
}
}
return null;
}
|
7420937_193
|
@Override
public Optional<String> apply(Optional<String> springApplicationName) {
Optional<String> processApplicationName = GetProcessApplicationNameFromAnnotation.getProcessApplicationName.apply(applicationContext);
if (processApplicationName.isPresent()) {
return processApplicationName;
} else if (springApplicationName.isPresent()) {
return springApplicationName;
}
return Optional.empty();
}
|
7422160_52
|
public static String backupFile(File source) {
File backup = new File(source.getParent() + "/~" + source.getName());
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(source)));
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(backup)));
return FileUtil.backupFile(reader, writer, source.getAbsolutePath());
} catch (FileNotFoundException fe) {
String msg = "Failed to find file for backup [" + source.getAbsolutePath() + "].";
_log.error(msg, fe);
throw new InvalidImplementationException(msg, fe);
}
}
|
7436396_4
|
@Override
public User addUser(final User user) {
// create date set to now(), only work for mysql
final String INSERT_SQL = "insert into t_user (imei, imsi, phone_name,createdate) values (?, ?, ?, now())";
/ return this.jdbcTemplate.update(INSERT_SQL, user.getImei(),
/ user.getImsi(), user.getPhoneName());
/*
* refer to Spring Framework Reference Documentation: 14.2.8 Retrieving
* auto-generated keys
*/
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(
Connection connection) throws SQLException {
//the String Array means columns that should be returned from the inserted rows
PreparedStatement ps = connection.prepareStatement(INSERT_SQL,
new String[] { "user_id" });
ps.setString(1, user.getImei());
ps.setString(2, user.getImsi());
ps.setString(3, user.getPhoneName());
return ps;
}
}, keyHolder);
// keyHolder.getKey() now contains the generated key
user.setUserId(keyHolder.getKey().intValue());
return user;
}
|
7438954_5
|
public PlungerArguments merge(String cmdTarget, Config config, CommandLine line, Options options) throws Exception {
PlungerArguments result = new PlungerArguments();
Target commandTarget = new TargetParser().parse(cmdTarget);
Entry entry = config.getEntry(commandTarget.getHost());
if ((entry != null) && (entry.getTarget() != null)) {
result.setTarget(mergeTarget(commandTarget, entry.getTarget())); // merge targets
}
else {
result.setTarget(commandTarget);
}
result.setColors(mergeColors(line, result, entry));
result.setVerbose(line.hasOption("verbose"));
result.setCommand(line.getOptionValue("command"));
for (Object opt: options.getOptions()) {
Option option = (Option)opt;
if (option.getOpt() != null && line.hasOption(option.getOpt())) {
String value = join(line.getOptionValues(option.getOpt()), " ");
result.addCommandArgument(option.getOpt(), value);
result.addCommandArgument(option.getLongOpt(), value);
}
}
return result;
}
|
7450263_2
|
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
if (!(msg instanceof ChannelBuffer)) {
return msg;
}
ChannelBuffer buf = (ChannelBuffer) msg;
if (buf.hasArray()) {
ByteArrayInputStream bis = new ByteArrayInputStream(buf.array(), buf.arrayOffset() + buf.readerIndex(),
buf.readableBytes());
Hessian2Input in = new Hessian2Input(bis);
in.setSerializerFactory(factory);
return in.readObject(Message.class);
} else {
Hessian2Input in = new Hessian2Input(new ChannelBufferInputStream((ChannelBuffer) msg));
in.setSerializerFactory(factory);
return in.readObject(Message.class);
}
}
|
7455819_22
|
@Override
public boolean isApplicable(HandlerContext handlerContext) {
// Retrieves the content type from the filtered response
String mimeType = handlerContext.getResponse().getContentType();
// Required conditions
boolean gzipEnabled = handlerContext.getContext().getConfiguration().isToolGzipEnabled();
boolean requestNotIncluded = !isIncluded(handlerContext.getRequest());
boolean browserAcceptsGzip = acceptsGzip(handlerContext.getRequest());
boolean responseNotCommited = !handlerContext.getResponse().isCommitted();
boolean compatibleMimeType = getSupportedMimeTypes(handlerContext.getContext()).contains(mimeType);
LOG.trace(
"gzipEnabled: {}, requestNotInclude: {}, browserAcceptsGzip: {}, responseNotCommited: {}, compatibleMimeType: {}",
gzipEnabled, requestNotIncluded, browserAcceptsGzip, responseNotCommited, compatibleMimeType);
return gzipEnabled && requestNotIncluded && browserAcceptsGzip && responseNotCommited && compatibleMimeType;
}
|
7465720_23
|
protected static List<AndroidElement> searchViews(AbstractNativeElementContext context, View root,
Predicate predicate, boolean findJustOne) {
List<AndroidElement> elements = new ArrayList<AndroidElement>();
if (root == null) {
return elements;
}
ArrayDeque<View> queue = new ArrayDeque<View>();
queue.add(root);
while (!queue.isEmpty()) {
View view = queue.pop();
if (predicate.apply(view)) {
elements.add(context.newAndroidElement(view));
if (findJustOne) {
break;
}
}
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
int childrenCount = group.getChildCount();
for (int index = 0; index < childrenCount; index++) {
queue.add(group.getChildAt(index));
}
}
}
return elements;
}
|
7480345_95
|
protected static String createCallbackCWrapper(FunctionType functionType, String name, String innerName) {
// We order structs by name in reverse order. The names are constructed
// such that nested structs get names which are naturally ordered after
// their parent struct.
Map<String, String> structs = new TreeMap<String, String>(Collections.reverseOrder());
StringBuilder hiSignature = new StringBuilder();
hiSignature
.append(getHiType(functionType.getReturnType()))
.append(' ')
.append(innerName)
.append('(');
StringBuilder loSignature = new StringBuilder();
String loReturnType = getLoType(functionType.getReturnType(), name, 0, structs);
loSignature
.append(loReturnType)
.append(' ')
.append(name)
.append('(');
StringBuilder body = new StringBuilder(" {\n");
StringBuilder args = new StringBuilder();
for (int i = 0; i < functionType.getParameterTypes().length; i++) {
String arg = "p" + i;
if (i > 0) {
hiSignature.append(", ");
loSignature.append(", ");
args.append(", ");
}
String hiParamType = getHiType(functionType.getParameterTypes()[i]);
hiSignature.append(hiParamType);
String loParamType = getLoType(functionType.getParameterTypes()[i], name, i + 1, structs);
loSignature.append(loParamType).append(' ').append(arg);
if (functionType.getParameterTypes()[i] instanceof StructureType) {
args.append("(void*) &").append(arg);
} else {
args.append(arg);
}
}
if (functionType.getParameterTypes().length == 0) {
hiSignature.append("void");
loSignature.append("void");
}
hiSignature.append(')');
loSignature.append(')');
StringBuilder header = new StringBuilder();
for (Entry<String, String> struct : structs.entrySet()) {
header.append("struct " + struct.getKey() + " " + struct.getValue() + ";\n");
}
header.append(hiSignature + ";\n");
if (functionType.getReturnType() instanceof StructureType) {
body.append(" return *((" + loReturnType + "*) " + innerName + "(" + args + "));\n");
} else if (functionType.getReturnType() != Type.VOID) {
body.append(" return " + innerName + "(" + args + ");\n");
} else {
body.append(" " + innerName + "(" + args + ");\n");
}
body.append("}\n");
return header.toString() + loSignature.toString() + body.toString();
}
|
7481569_302
|
public Set<Project> getUngroupedRepositories() {
return cacheProjects(PROJECT_HELPER_UNGROUPED_REPOSITORIES, ungroupedRepositories);
}
|
7482468_0
|
@Override
public String toString()
{
return Visitors.readable(this);
}
|
7499734_214
|
@Deprecated
public static <E> IList<E> getList(String name) {
return getDefaultInstance().getList(name);
}
|
7506968_32
|
public Class getColumnClass( final int column ) {
if ( column == 2 ) {
return Date.class;
}
return String.class;
}
|
7530419_1
|
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
setContentView(R.layout.directory_chooser_activity);
final DirectoryChooserConfig config = getIntent().getParcelableExtra(EXTRA_CONFIG);
if (config == null) {
throw new IllegalArgumentException(
"You must provide EXTRA_CONFIG when starting the DirectoryChooserActivity.");
}
if (savedInstanceState == null) {
final FragmentManager fragmentManager = getFragmentManager();
final DirectoryChooserFragment fragment = DirectoryChooserFragment.newInstance(config);
fragmentManager.beginTransaction()
.add(R.id.main, fragment)
.commit();
}
}
|
7575297_13
|
public static String removeTag(String html, String tagName) {
Element bodyElement = Jsoup.parse(html).body();
bodyElement.getElementsByTag(tagName).remove();
return bodyElement.html();
}
|
7576522_23
|
public static Consolidator createConsolidator(final Class<? extends Consolidator> type, final int maxSamples) {
Preconditions.checkNotNull(type, "null type");
Preconditions2.checkSize(maxSamples);
try {
//First look for a constructor accepting int as argument
try {
return type.getConstructor(int.class).newInstance(maxSamples);
} catch (NoSuchMethodException e) {
if (Loggers.BASE_LOGGER.isLoggable(Level.FINEST)) {
Loggers.BASE_LOGGER.log(Level.FINEST, "{0} does not define a constructor accepting int", type.getCanonicalName());
}
}
//If we can't find such fallback to defaut constructor
try {
final Constructor<? extends Consolidator> defaultConstructor = type.getConstructor();
return defaultConstructor.newInstance();
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Failed to find int or default constructor for "+type.getCanonicalName(), e);
}
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
|
7589324_102
|
@Transactional
@Override
public void deleteFromIndex(Long id) {
LOGGER.debug("Deleting an existing document with id: {}", id);
repository.delete(id.toString());
}
|
7593542_1
|
public String sayHello(String name, boolean hipster) {
return (hipster) ? ("Yo " + name) : ("Hello " + name);
}
|
7612313_0
|
@Override
public synchronized DerivedKey getKey() throws IOException, GeneralSecurityException {
if (derivedKey == null)
createDerivedKey();
return derivedKey;
}
|
7616158_12
|
public static <T> T newInstance(Class<T> aClass) {
try {
return aClass.newInstance();
} catch (Exception e) {
throw new RibbonProxyException("Cannot instantiate object from class " + aClass, e);
}
}
|
7623114_51
|
public static int acompare(double x1, double x2) {
if (isZero(x1 - x2)) {
return 0;
} else {
return Double.compare(x1, x2);
}
}
|
7638504_10
|
public void addSymbol(String name, SymbolType type, ScopeType scopeType) {
if (scopes.isEmpty()) {
throw new IllegalStateException("Called addSymbol before adding any scope levels");
}
getTop().add(new Symbol(name, type, scopeType));
}
|
7676364_12
|
public static synchronized ThreadPoolExecutor getExecutor(ThreadPoolBuilder builder,
RegionCoprocessorEnvironment env) {
return getExecutor(builder, env.getSharedData());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.