code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
private static HttpBuilder defaults(HttpBuilder builder) {
if (defaultTimeout != null) {
builder.timeout(defaultTimeout);
}
if (defaultTimeoutConnection != null) {
builder.timeoutConnection(defaultTimeoutConnection);
}
if (defaultTimeoutRead != null) {
builder.timeoutRead(defaultTimeoutRead);
}
i... | java |
public static void printBox(String title, String message) {
printBox(title, Splitter.on(LINEBREAK).splitToList(message));
} | java |
public static void printBox(String title, List<String> messageLines) {
Say.info("{message}", generateBox(title, messageLines));
} | java |
public static void setUtc(Date time) {
setClock(Clock.fixed(time.toInstant(), ZoneId.of("UTC")));
} | java |
public synchronized static void addShutdownHook(Runnable task) {
if (task != null) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
task.run();
}
catch (RuntimeException rex) {
Say.warn("Exception while processing shutdown-hook", rex);
}
}));
}
} | java |
public void finish() {
if (startMeasure == null) {
Say.info("No invokations are measured");
}
else {
long total = System.currentTimeMillis() - startMeasure;
double average = 1d * total / counter;
logFinished(total, average);
}
} | java |
public void run(ExceptionalRunnable runnable) throws Exception {
initStartTotal();
long startInvokation = System.currentTimeMillis();
runnable.run();
invoked(System.currentTimeMillis() - startInvokation);
} | java |
public <V> V call(Callable<V> callable) throws Exception {
initStartTotal();
long startInvokation = System.currentTimeMillis();
V result = callable.call();
invoked(System.currentTimeMillis() - startInvokation);
return result;
} | java |
public static void sleep(long millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
} | java |
public <T> T fallback(T val, T fallback) {
return val != null ? val : fallback;
} | java |
public Iterator<String> getMessages() {
Iterator<SmtpMessage> it = server.getReceivedEmail();
List<String> msgs = new ArrayList<>();
while(it.hasNext()) {
SmtpMessage msg = it.next();
msgs.add(msg.toString());
}
return msgs.iterator();
} | java |
public static void registerMBean(String packageName, String type, String name, Object mbean) {
try {
String pkg = defaultString(packageName, mbean.getClass().getPackage().getName());
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName on = new ObjectName(pkg + ":type=" + type + ",name... | java |
public static Long dehumanize(String time) {
Long result = getHumantimeCache().get(time);
if (result == null) {
if (isNotBlank(time)) {
String input = time.trim();
if (NumberUtils.isDigits(input)) {
result = NumberUtils.toLong(input);
}
else {
Matcher matcher = PATTERN_HUMAN_TIME.matche... | java |
@Override
public final V computeIfPresent(
K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (remappingFunction == null)
throw new NullPointerException();
long hash;
return segment(segmentIndex(hash = keyHashCode(key)))
.comp... | java |
private long nextSegmentIndex(long segmentIndex, Segment segment) {
long segmentsTier = this.segmentsTier;
segmentIndex <<= -segmentsTier;
segmentIndex = Long.reverse(segmentIndex);
int numberOfArrayIndexesWithThisSegment = 1 << (segmentsTier - segment.tier);
segmentIndex += numb... | java |
@Override
public final void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Objects.requireNonNull(function);
int mc = this.modCount;
Segment<K, V> segment;
for (long segmentIndex = 0; segmentIndex >= 0;
segmentIndex = nextSegmentIndex(segmentIndex, ... | java |
public final boolean removeIf(BiPredicate<? super K, ? super V> filter) {
Objects.requireNonNull(filter);
if (isEmpty())
return false;
Segment<K, V> segment;
int mc = this.modCount;
int initialModCount = mc;
for (long segmentIndex = 0; segmentIndex >= 0;
... | java |
private String getJustifiedText(String text) {
String[] words = text.split(NORMAL_SPACE);
for (String word : words) {
boolean containsNewLine = (word.contains("\n") || word.contains("\r"));
if (fitsInSentence(word, currentSentence, true)) {
addWord(word, contain... | java |
private void addWord(String word, boolean containsNewLine) {
currentSentence.add(word);
if (containsNewLine) {
sentences.add(getSentenceFromListCheckingNewLines(currentSentence));
currentSentence.clear();
}
} | java |
private String getSentenceFromList(List<String> strings, boolean addSpaces) {
StringBuilder stringBuilder = new StringBuilder();
for (String string : strings) {
stringBuilder.append(string);
if (addSpaces) {
stringBuilder.append(NORMAL_SPACE);
}
... | java |
private String getSentenceFromListCheckingNewLines(List<String> strings) {
StringBuilder stringBuilder = new StringBuilder();
for (String string : strings) {
stringBuilder.append(string);
//We don't want to add a space next to the word if this one contains a new line character
... | java |
private String fillSentenceWithSpaces(List<String> sentence) {
sentenceWithSpaces.clear();
//We don't need to do this process if the sentence received is a single word.
if (sentence.size() > 1) {
//We fill with normal spaces first, we can do this with confidence because "fitsInSente... | java |
private boolean fitsInSentence(String word, List<String> sentence, boolean addSpaces) {
String stringSentence = getSentenceFromList(sentence, addSpaces);
stringSentence += word;
float sentenceWidth = getPaint().measureText(stringSentence);
return sentenceWidth < viewWidth;
} | java |
@Nonnull
final String writeManifest( @Nonnull final TreeLogger logger,
@Nonnull final Set<String> staticResources,
@Nonnull final Map<String, String> fallbackResources,
@Nonnull final Set<String> cacheResources )
throws Unab... | java |
@Nullable
final Permutation calculatePermutation( @Nonnull final TreeLogger logger,
@Nonnull final LinkerContext context,
@Nonnull final ArtifactSet artifacts )
throws UnableToCompleteException
{
Permutation permutation = nu... | java |
protected boolean handleUnmatchedRequest( final HttpServletRequest request,
final HttpServletResponse response,
final String moduleName,
final String baseUrl,
... | java |
protected final String loadAndMergeManifests( final String baseUrl,
final String moduleName,
final String... permutationNames )
throws ServletException
{
final String cacheKey = toCacheKey( baseUrl, moduleName, per... | java |
protected final void reduceToMatchingDescriptors( @Nonnull final List<BindingProperty> bindings,
@Nonnull final List<SelectionDescriptor> descriptors )
{
final Iterator<BindingProperty> iterator = bindings.iterator();
while ( iterator.hasNext() )
{
... | java |
private BindingProperty findMatchingBindingProperty( final List<BindingProperty> bindings,
final BindingProperty requirement )
{
for ( final BindingProperty candidate : bindings )
{
if ( requirement.getName().equals( candidate.getName() ) )
{
... | java |
private BindingProperty findSatisfiesBindingProperty( final List<BindingProperty> bindings,
final BindingProperty requirement )
{
final BindingProperty property = findMatchingBindingProperty( bindings, requirement );
if ( null != property && property.mat... | java |
protected final String[] selectPermutations( @Nonnull final String baseUrl,
@Nonnull final String moduleName,
@Nonnull final List<BindingProperty> computedBindings )
throws ServletException
{
try
{
final Li... | java |
public static <E> Collector<E, ?, Optional<E>> getOnly() {
return Collector.of(
AtomicReference<E>::new,
(ref, e) -> {
if (!ref.compareAndSet(null, e)) {
throw new IllegalArgumentException("Multiple values");
}
},
(ref1, ref2) -> {
if (ref1.g... | java |
public static Object getSingleResultOrNull(Query query) {
List results = query.getResultList();
if (results.isEmpty()) {
return null;
} else if (results.size() == 1) {
return results.get(0);
}
throw new NonUniqueResultException();
} | java |
public char[] hash(char[] password, byte[] salt) {
checkNotNull(password);
checkArgument(password.length != 0);
checkNotNull(salt);
checkArgument(salt.length != 0);
try {
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey key =
f.generateSecret(... | java |
public boolean check(char[] plain, char[] database, byte[] salt) {
checkNotNull(plain);
checkArgument(plain.length != 0, "Plain must not be empty.");
checkNotNull(database);
checkArgument(database.length != 0, "Database must not be empty.");
checkNotNull(salt);
checkArgument(salt.length != 0, "... | java |
public static double mean(double[] a) {
if (a.length == 0) return Double.NaN;
double sum = sum(a);
return sum / a.length;
} | java |
public static double stdDev(double[] a) {
if(a == null || a.length == 0)
return -1;
return Math.sqrt(varp(a));
} | java |
public void writeFile(String aFileName, String aData) throws IOException
{
Object lock = retrieveLock(aFileName);
synchronized (lock)
{
IO.writeFile(aFileName, aData,IO.CHARSET);
}
} | java |
private Object retrieveLock(String key)
{
Object lock = this.lockMap.get(key);
if(lock == null)
{
lock = key;
this.lockMap.put(key, lock);
}
return lock;
} | java |
protected void formatMessage(String aID, Map<Object,Object> aBindValues)
{
Presenter presenter = Presenter.getPresenter(this.getClass());
message = presenter.getText(aID,aBindValues);
} | java |
@SuppressWarnings({ "rawtypes", "unchecked" })
protected DirContext setupKerberosContext(Hashtable<String,Object> env)
throws NamingException
{
LoginContext lc = null;
try
{
lc = new LoginContext(getClass().getName(), new JXCallbackHandler());
lc.login();
... | java |
public Principal authenicate(String uid, char[] password)
throws SecurityException
{
String rootDN = Config.getProperty(ROOT_DN_PROP);
int timeout = Config.getPropertyInteger(TIMEOUT_SECS_PROP).intValue();
Debugger.println(LDAP.class,"timeout="+timeout);
String uid... | java |
public GenericField[] getFields()
{
Collection<GenericField> values = fieldMap.values();
if(values == null || values.isEmpty())
return null;
GenericField[] fieldMirrors = new GenericField[values.size()];
values.toArray(fieldMirrors);
return fieldMirrors;
} | java |
public void sortRows(Comparator<List<String>> comparator)
{
if(data.isEmpty())
return;
Collections.sort(data, comparator);
} | java |
public JavaBeanGeneratorCreator<T> randomizeProperty(String property)
{
if(property ==null || property.length() == 0)
return this;
this.randomizeProperties.add(property);
return this;
} | java |
public JavaBeanGeneratorCreator<T> fixedProperties(String... fixedPropertyNames)
{
if(fixedPropertyNames == null || fixedPropertyNames.length == 0)
{
return this;
}
HashSet<String> fixSet = new HashSet<>(Arrays.asList(fixedPropertyNames));
Map<Object,Object> map = null;
if(this.prototype != nu... | java |
public void setPrimaryKey(int primaryKey)
throws IllegalArgumentException
{
if (primaryKey <= NULL)
{
this.primaryKey = Data.NULL;
}
else
{
this.primaryKey = primaryKey;
//resetNew();
return;
}
} | java |
public T lookup(String text)
{
if (text == null)
return null;
for (Entry<String,T> entry :lookupMap.entrySet())
{
if (Text.matches(text, entry.getKey()))
return lookupMap.get(entry.getKey());
}
return null;
} | java |
@SuppressWarnings({ "unchecked", "rawtypes" })
public static final <T> Collection<DataRow> constructDataRows(Iterator<T> iterator, QuestCriteria questCriteria, DataRowCreator visitor)
{
if(iterator == null )
return null;
ArrayList<DataRow> dataRows = new ArrayList<DataRow>(BATCH_SIZE);
boolean usePa... | java |
public void rebind(Remote[] remotes)
{
String rmiUrl = null;
//loop thru remote objects
for (int i = 0; i < remotes.length; i++)
{
//use is if instance of Identifier
if(remotes[i] instanceof Identifier
&& !Text.isNull(((Identifier)remotes[i]).getId()))
{
... | java |
public static Registry getRegistry()
throws RemoteException
{
return LocateRegistry.getRegistry(Config.getProperty(RMI.class,"host"),
Config.getPropertyInteger(RMI.class,"port").intValue());
} | java |
public Object restore(String savePoint, Class<?> objClass)
{
String location = whereIs(savePoint, objClass);
Object cacheObject = CacheFarm.getCache().get(location);
if(cacheObject != null)
return cacheObject;
cacheObject = IO.deserialize(new File(location));
CacheFarm.getCache().put(location,... | java |
public void store(String savePoint, Object obj)
{
if (savePoint == null)
throw new RequiredException("savePoint");
if (obj == null)
throw new RequiredException("obj");
String location = whereIs(savePoint, obj.getClass());
Debugger.println(this,"Storing in "+location);
IO.serializeToFi... | java |
static int requireValidExponent(final int exponent) {
if (exponent < MIN_EXPONENT) {
throw new IllegalArgumentException("exponent(" + exponent + ") < " + MIN_EXPONENT);
}
if (exponent > MAX_EXPONENT) {
throw new IllegalArgumentException("exponent(" + exponent + ") > " + M... | java |
public void setLookupTable(Map<String,Map<K,V>> lookupTable)
{
this.lookupTable = new TreeMap<String,Map<K,V>> (lookupTable);
} | java |
@SuppressWarnings("unchecked")
public static <T> T getProperty(Object bean, String name)
throws SystemException
{
try
{
return (T)getNestedProperty(bean, name);
}
catch (Exception e)
{
throw new SystemException("Get property \""+name+"\" ERROR:"+e.... | java |
public static Collection<Object> getCollectionProperties(Collection<?> collection,String name)
throws Exception
{
if(collection == null)
throw new IllegalArgumentException("collection, name");
ArrayList<Object> list = new ArrayList<Object>(collection.size());
for (Object bean : c... | java |
public String getText()
{
//loop thru text
StringText stringText = new StringText();
stringText.setText(this.target.getText());
TextDecorator<Textable> textDecorator = null;
//loop thru decorator and get results from each
for(Iterator<TextDecorator<Textable>> i = textables.iterator();i.hasNe... | java |
public static <T> Collection<T> sortByCriteria(Collection<T> aVOs)
{
final List<T> list;
if (aVOs instanceof List)
list = (List<T>) aVOs;
else
list = new ArrayList<T>(aVOs);
Collections.sort(list, new CriteriaComparator());
return list;
} | java |
@Override
public void bag(Date unBaggedObject)
{
if(unBaggedObject == null)
this.time = 0;
else
this.time = unBaggedObject.getTime();
} | java |
public static Method findMethod(Class<?> objClass, String methodName,
Class<?>[] parameterTypes) throws NoSuchMethodException
{
try
{
return objClass.getDeclaredMethod(methodName, parameterTypes);
}
catch (NoSuchMethodException e)
{
if (Object.class.equals(objClass))
throw e;
try... | java |
@Override
public String getText()
{
if(this.target == null)
return null;
try
{
//Check if load of template needed
if((this.template == null || this.template.length() == 0) && this.templateName != null)
{
try
{
this.template = Text.loadTemplate(templateName);
}
... | java |
public static void addCells(StringBuilder builder, String... cells)
{
if(builder == null || cells == null || cells.length == 0)
return;
for (String cell : cells)
{
addCell(builder,cell);
}
} | java |
public static String toCSV(String... cells)
{
if(cells == null || cells.length == 0)
return null;
StringBuilder builder = new StringBuilder();
addCells(builder, cells);
return builder.toString();
} | java |
public String encryptText(String text)
throws Exception
{
return toByteText(this.encrypt(text.getBytes(IO.CHARSET)));
} | java |
public static void main(String[] args)
{
try
{
if (args.length == 0)
{
System.err.println("Usage java " + Cryption.class.getName()
+ " <text>");
return;
}
final String decryptedPassword;
if (args[0].equals("-d"))
{
if (args.length > 2)
{
StringBuild... | java |
@Override
public int compareTo(Object object)
{
if(!(object instanceof User))
{
return -1;
}
User user = (User)object;
return getLastName().compareTo(user.getLastName());
} | java |
public static Object executeMethod(Object object, MethodCallFact methodCallFact)
throws Exception
{
if (object == null)
throw new RequiredException("object");
if (methodCallFact == null)
throw new RequiredException("methodCallFact");
return executeMethod(object, methodCallFact.getMethodNam... | java |
public synchronized void setUp()
{
if(initialized)
return;
String className = null;
//Load
Map<Object,Object> properties = settings.getProperties();
String key = null;
Object serviceObject = null;
for(Map.Entry<Object,Object> entry : properties.entrySet())
{... | java |
private String getValidURL(String url)
{
if (url != null && url.length() > 0)
{
// XXX really important that this one happens first!!
return url.replaceAll("[%]", "%25")
.replaceAll(" ", "%20")
.replaceAll("[<]", "%3c")
.replaceAll("[>]", "%3e")
.replaceAll("[\"]", "%3f")
.replac... | java |
private static void setupSimpleSecurityProperties(Hashtable<String,Object> env,
String userDn, char[] pwd)
{
// 'simple' = username + password
env.put(Context.SECURITY_AUTHENTICATION, "simple");
// add the full user dn
env.put(Context.SECURITY_PRINCIPAL, userDn);
// set password
env.put(Cont... | java |
private Hashtable<?,?> setupBasicProperties(Hashtable<String,Object> env)
throws NamingException
{
return setupBasicProperties(env,this.fullUrl);
} | java |
public static String getProperty(Class<?> aClass,String key,ResourceBundle resourceBundle)
{
return getSettings().getProperty(aClass, key, resourceBundle);
} | java |
public static String getProperty(String key, String aDefault)
{
return getSettings().getProperty(key, aDefault);
} | java |
public static Integer getPropertyInteger(Class<?> aClass, String key,
int defaultValue)
{
return getSettings().getPropertyInteger(key, defaultValue);
} | java |
public static Character getPropertyCharacter(Class<?> aClass, String key,
char defaultValue)
{
return getSettings().getPropertyCharacter(aClass, key, defaultValue);
} | java |
public static char[] getPropertyPassword(Class<?> aClass, String key,
char[] defaultPassword)
{
return getSettings().getPropertyPassword(aClass, key, defaultPassword);
} | java |
public static <T> void addAll(Collection<T> pagingResults, Collection<T> paging, BooleanExpression<T> filter)
{
if (pagingResults == null || paging == null)
return;
if (filter != null)
{
for (T obj : paging)
{
if (filter.apply(obj))
pagingResults.add(obj);
}
}
else
{
... | java |
public static Object findMapValueByKey(Object key, Map<?, ?> map,
Object defaultValue)
{
if (key == null || map == null)
return defaultValue;
Object value = map.get(key);
if (value == null)
return defaultValue;
return value;
} | java |
public static void addAll(Collection<Object> list, Object[] objects)
{
list.addAll(Arrays.asList(objects));
} | java |
public static void copyToArray(Collection<Object> collection, Object[] objects)
{
System.arraycopy(collection.toArray(), 0, objects, 0, objects.length);
} | java |
public static <K, V> void addMappableCopiesToMap(Collection<Mappable<K, V>> aMappables, Map<K, V> aMap)
{
if (aMappables == null || aMap == null)
return;
Mappable<K, V> mappable = null;
Copier previous = null;
for (Iterator<Mappable<K, V>> i = aMappables.iterator(); i.hasNext();)
{
mappable =... | java |
public static <T, K> Collection<T> findMapValuesByKey(Collection<K> aKeys,
Map<K, T> aMap)
{
if (aKeys == null || aMap == null)
return null;
Object key = null;
ArrayList<T> results = new ArrayList<T>(aMap.size());
for (Iterator<K> i = aKeys.iterator(); i.hasNext();)
{
key = i.next();
re... | java |
public static <T> void addAll(Collection<T> aFrom, Collection<T> aTo)
{
if (aFrom == null || aTo == null)
return; // do nothing
T object = null;
for (Iterator<T> i = aFrom.iterator(); i.hasNext();)
{
object = i.next();
if (object != null)
{
aTo.add(object);
}
}
} | java |
public static Map<String, Criteria> constructCriteriaMap(Collection<Criteria> aCriterias)
{
if (aCriterias == null)
return null;
Map<String, Criteria> map = new HashMap<String, Criteria>(aCriterias.size());
Criteria criteria = null;
for (Iterator<Criteria> i = aCriterias.iterator(); i.hasNext();)
... | java |
public static Map<Integer, PrimaryKey> constructPrimaryKeyMap(Collection<PrimaryKey> aPrimaryKeys)
{
if (aPrimaryKeys == null)
return null;
Map<Integer, PrimaryKey> map = new HashMap<Integer, PrimaryKey>(aPrimaryKeys.size());
PrimaryKey primaryKey = null;
for (Iterator<PrimaryKey> i = aPrimaryKeys.i... | java |
public static <K> void makeAuditableCopies(Map<K, Copier> aFormMap, Map<K, Copier> aToMap,
Auditable aAuditable)
{
if (aFormMap == null || aToMap == null)
return;
// for thru froms
K fromKey = null;
Copier to = null;
Copier from = null;
for (Map.Entry<K, Copier> entry : aFormMap.entrySet()... | java |
public static Object[] toArray(Object obj)
{
if (obj instanceof Object[])
return (Object[]) obj;
else
{
Object[] returnArray =
{ obj };
return returnArray;
}
} | java |
public static <StoredObjectType, ResultSetType> Pagination createPagination(PageCriteria pageCriteria)
{
String id = pageCriteria.getId();
if(id == null || id.length() == 0)
{
return null;
}
Pagination pagination = ClassPath.newInstance(paginationClassName,String.class,pageCrit... | java |
public void loadJar(File fileJar)
throws IOException
{
JarFile jar = null;
try
{
jar = new JarFile(fileJar);
Enumeration<JarEntry> enumerations = jar.entries();
JarEntry entry = null;
byte[] classByte = null;
ByteArrayOutputStream byteStream = null;
String fileName = n... | java |
public Class<?> findClass(String className)
{
Class<?> result = null;
// look in hash map
result = (Class<?>) classes.get(className);
if (result != null)
{
return result;
}
try
{
return findSystemClass(className);
}
catch (Exception e)
{
Debugger.printWarn(e);
}
... | java |
private byte[] loadClassBytes(File classFile) throws IOException
{
int size = (int) classFile.length();
byte buff[] = new byte[size];
FileInputStream fis = new FileInputStream(classFile);
DataInputStream dis = null;
try
{
dis = new DataInputStream(fis);
dis.readFully(buff);
}
fin... | java |
public int compareTo(Day object)
{
if (object == null)
throw new IllegalArgumentException("day cannot be null");
Day day = (Day)object;
return localDate.compareTo(day.localDate);
} | java |
public boolean isAfter(Day day)
{
if (day == null)
throw new IllegalArgumentException("day cannot be null");
return localDate.isAfter(day.localDate);
} | java |
public boolean isBefore(Day day)
{
if (day == null)
throw new IllegalArgumentException("day cannot be null");
return localDate.isBefore(day.localDate);
} | java |
public boolean isSameDay(Day compared)
{
if(compared == null)
return false;
return this.getMonth() == compared.getMonth()
&& this.getDayOfMonth() == compared.getDayOfMonth()
&& this.getYear() == compared.getYear();
} | java |
@Override
public synchronized String lookup(String id)
{
if(this.properties == null)
this.setUp();
String associated = this.properties.getProperty(id);
if(associated == null)
{
associated = this.next();
//Est. new association
register(id,associated);
}
return associated;
} | java |
public void manage(int workersCount)
{
this.workers.clear();
WorkerThread worker = null;
for (int i = 0; i <workersCount; i++)
{
worker = new WorkerThread(this); //TODO expensive use thread pool
this.manage(worker);
}
} | java |
String getMatchingJavaEncoding(String javaEncoding) {
if (javaEncoding != null && this.javaEncodingsUc.contains(javaEncoding.toUpperCase(Locale.ENGLISH))) {
return javaEncoding;
}
return this.javaEncodingsUc.get(0);
} | java |
@Override
public UserProfile convert(String text)
{
if(text == null || text.trim().length() == 0)
return null;
String[] lines = text.split("\\\n");
BiConsumer<String,UserProfile> strategy = null;
UserProfile userProfile = null;
String lineUpper = null;
for (String line : lines)
{
//get first... | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.