code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
public String serialize(Object object) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Serializing object to Json");
}
XStream xstream = new XStream(new JettisonMappedXmlDriver());
String json = xstream.toXML(object);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Object serialized well");
}
r... | java |
public Object deserialize(String jsonObject) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Deserializing Json object");
}
XStream xstream = new XStream(new JettisonMappedXmlDriver());
Object obj = xstream.fromXML(jsonObject);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Object deserialized");
... | java |
private Iterator<String> filterOutEmptyStrings(final Iterator<String> splitted) {
return new Iterator<String>() {
String next = getNext();
@Override
public boolean hasNext() {
return next != null;
}
@Override
public String ... | java |
public static Envelope toJts(Bbox bbox) throws JtsConversionException {
if (bbox == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Envelope(bbox.getX(), bbox.getMaxX(), bbox.getY(), bbox.getMaxY());
} | java |
public static com.vividsolutions.jts.geom.Coordinate toJts(org.geomajas.geometry.Coordinate coordinate)
throws JtsConversionException {
if (coordinate == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new com.vividsolutions.jts.geom.Coordinate(coordinate.getX(), coordina... | java |
public static Geometry fromJts(com.vividsolutions.jts.geom.Geometry geometry) throws JtsConversionException {
if (geometry == null) {
throw new JtsConversionException("Cannot convert null argument");
}
int srid = geometry.getSRID();
int precision = -1;
PrecisionModel precisionmodel = geometry.getPrecision... | java |
public static Bbox fromJts(Envelope envelope) throws JtsConversionException {
if (envelope == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Bbox(envelope.getMinX(), envelope.getMinY(), envelope.getWidth(), envelope.getHeight());
} | java |
public static Coordinate fromJts(com.vividsolutions.jts.geom.Coordinate coordinate) throws JtsConversionException {
if (coordinate == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Coordinate(coordinate.x, coordinate.y);
} | java |
public long writeTo(File fileOrDirectory) throws IOException {
long written = 0;
OutputStream fileOut = null;
try {
// Only do something if this part contains a file
if (fileName != null) {
// Check if user supplied directory
File file;
if (fileOrDirectory.isDirector... | java |
public long writeTo(OutputStream out) throws IOException {
long size=0;
// Only do something if this part contains a file
if (fileName != null) {
// Write it out
size = write( out );
}
return size;
} | java |
long write(OutputStream out) throws IOException {
// decode macbinary if this was sent
if (contentType.equals("application/x-macbinary")) {
out = new MacBinaryDecoderOutputStream(out);
}
long size=0;
int read;
byte[] buf = new byte[8 * 1024];
while((read = partInput.read(buf)) != -1) {... | java |
public static Xml readAllFromResource(String resourceName) {
InputStream is = XmlReader.class.getResourceAsStream(resourceName);
XmlReader reader = new XmlReader(is);
Xml xml = reader.read("node()");
reader.close();
return xml;
} | java |
private void init(InputStream inputStream) {
this.inputStream = inputStream;
currentPath = new LinkedList<Node>();
nodeQueue = new LinkedList<XmlNode>();
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty("javax.xml.stream.isCoalescing", true);
f... | java |
public boolean find(String xmlPathQuery) {
XmlPath xmlPath = XmlPathParser.parse(xmlPathQuery);
XmlNode node;
while((node = pullXmlNode()) != null) {
if(node instanceof XmlStartElement) {
XmlStartElement startElement = (XmlStartElement) node;
Element ... | java |
private XmlNode pullXmlNode() {
// read from queue
if(! nodeQueue.isEmpty()) {
return nodeQueue.poll();
}
// read from stream
try {
while(reader.hasNext()) {
int event = reader.next();
switch(event) {
ca... | java |
private String filterWhitespace(String text) {
text = text.replace("\n", " ");
text = text.replaceAll(" {2,}", " ");
text = XmlEscape.escape(text);
return text.trim();
} | java |
private List<Attribute> getAttributes(XMLStreamReader reader) {
List<Attribute> list = new ArrayList<Attribute>();
for(int i=0; i<reader.getAttributeCount(); i++) {
list.add(new Attribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i)));
}
return list;
} | java |
private static boolean isOverridable(Method method, Class<?> targetClass) {
if (Modifier.isPrivate(method.getModifiers())) {
return false;
}
if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) {
return true;
}
retur... | java |
<I> void register( Method disposeMethod, I injectee )
{
disposables.add( new Disposable( disposeMethod, injectee ) );
} | java |
@Override
public void dispatch(ParameterResolveFactory parameterResolveFactory, ActionParam param, Route route, Object[] args) {
if (!route.isRegex()) return;
Matcher matcher = route.getMatcher();
String[] pathParameters = new String[matcher.groupCount()];
for (int i = 1, len = matc... | java |
public File createDir(File dir) throws DataUtilException {
if(dir == null) {
throw new DataUtilException("Dir parameter can not be a null value");
}
if(dir.exists()) {
throw new DataUtilException("Directory already exists: " + dir.getAbsolutePath());
}
if(... | java |
public void deleteAll() {
if(trackedFiles.size() == 0) {
return;
}
ArrayList<File> files = new ArrayList<File>(trackedFiles);
Collections.sort(files, filePathComparator);
for(File file : files) {
if(file.exists()) {
if(!file.delete()) {
... | java |
public void removeTombstone(final String path) throws FedoraException {
final HttpDelete delete = httpHelper.createDeleteMethod(path + "/fcr:tombstone");
try {
final HttpResponse response = httpHelper.execute( delete );
final StatusLine status = response.getStatusLine();
... | java |
protected Collection<String> getPropertyValues(final Property property) {
final ExtendedIterator<Triple> iterator = graph.find(Node.ANY,
property.asNode(),
Node.ANY);
final Set<Strin... | java |
public static String generateRequestId() {
/* compute a random 256-bit string and hex-encode it */
final SecureRandom sr = new SecureRandom();
final byte[] bytes = new byte[32];
sr.nextBytes(bytes);
return hexEncode(bytes);
} | java |
public final boolean isAssignableTo(MimeType mimeType) {
if (mimeType.getPrimaryType().equals("*")) {
// matches all
return true;
}
if (!mimeType.getPrimaryType().equalsIgnoreCase(getPrimaryType())) {
return false;
}
String mtSec = mimeType.get... | java |
@SuppressWarnings("rawtypes")
public List<ServletDefinition> initJawrSpringServlets(ServletContext servletContext) throws ServletException{
List<ServletDefinition> jawrServletDefinitions = new ArrayList<ServletDefinition>();
ContextLoader contextLoader = new ContextLoader();
WebApplicationContext applicationC... | java |
public static Graph filterTriples (
final Iterator<Triple> triples,
final Node... properties) {
final Graph filteredGraph = new RandomOrderGraph(RandomOrderGraph.createDefaultGraph());
final Sink<Triple> graphOutput = new SinkTriplesToGraph(true, filteredGraph);
final RDF... | java |
@Override
public List<? extends TypeMirror> directSupertypes(TypeMirror t)
{
switch (t.getKind())
{
case DECLARED:
DeclaredType dt = (DeclaredType) t;
TypeElement te = (TypeElement) dt.asElement();
List<TypeMirror> list = new ArrayList<... | java |
protected Provider<ObjectMapper> getJacksonProvider()
{
return new Provider<ObjectMapper>()
{
@Override
public ObjectMapper get()
{
final ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
... | java |
public Injector injector(final ServletContextEvent event)
{
return (Injector) event.getServletContext().getAttribute(Injector.class.getName());
} | java |
private void writeParent(Account account, XmlStreamWriter writer)
throws Exception {
// Sequence block
writer.writeStartElement("RDF:Seq");
writer.writeAttribute("RDF:about", account.getId());
for (Account child : account.getChildren()) {
logger.fine(" Wr... | java |
private void writeFFGlobalSettings(Database db, XmlStreamWriter writer)
throws Exception {
writer.writeStartElement("RDF:Description");
writer.writeAttribute("RDF:about", RDFDatabaseReader.FF_GLOBAL_SETTINGS_URI);
for (String key : db.getGlobalSettings().keySet()) {
... | java |
public static boolean intersectsLineSegment(Coordinate a, Coordinate b, Coordinate c, Coordinate d) {
// check single-point segment: these never intersect
if ((a.getX() == b.getX() && a.getY() == b.getY()) || (c.getX() == d.getX() && c.getY() == d.getY())) {
return false;
}
double c1 = cross(a, c, a, b);
d... | java |
private static double cross(Coordinate a1, Coordinate a2, Coordinate b1, Coordinate b2) {
return (a2.getX() - a1.getX()) * (b2.getY() - b1.getY()) - (a2.getY() - a1.getY()) * (b2.getX() - b1.getX());
} | java |
public static double distance(Coordinate c1, Coordinate c2) {
double a = c1.getX() - c2.getX();
double b = c1.getY() - c2.getY();
return Math.sqrt(a * a + b * b);
} | java |
public static double distance(Coordinate c1, Coordinate c2, Coordinate c) {
return distance(nearest(c1, c2, c), c);
} | java |
public static Coordinate nearest(Coordinate c1, Coordinate c2, Coordinate c) {
double len = distance(c1, c2);
double u = (c.getX() - c1.getX()) * (c2.getX() - c1.getX()) + (c.getY() - c1.getY()) * (c2.getY() - c1.getY());
u = u / (len * len);
if (u < 0.00001 || u > 1) {
// Shortest point not within LineSeg... | java |
public static boolean isXForwardedAllowed(String remoteAddr) {
return isXForwardedAllowed() && (S.eq("all", xForwardedAllowed) || xForwardedAllowed.contains(remoteAddr));
} | java |
public static String createId(Account acc)
throws Exception {
return Account.createId(acc.getName() + acc.getDesc() + (new Random()).nextLong() + Runtime.getRuntime().freeMemory());
} | java |
public Account getChild(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= children.size())
throw new IndexOutOfBoundsException("Illegal child index, " + index);
return children.get(index);
} | java |
public boolean hasChild(Account account) {
for (Account child : children) {
if (child.equals(account))
return true;
}
return false;
} | java |
public int compareTo(Account o) {
if (this.isFolder() && !o.isFolder())
return -1;
else if (!this.isFolder() && o.isFolder())
return 1;
// First ignore case, if they equate, use case.
int result = name.compareToIgnoreCase(o.name);
if (result == 0)
... | java |
@SuppressWarnings("UnusedDeclaration")
public void setPatterns(Iterable<AccountPatternData> patterns) {
this.patterns.clear();
for (AccountPatternData data : patterns) {
this.patterns.add(new AccountPatternData(data));
}
} | java |
public void close() throws DiffException {
try {
if(writer != null) {
writer.flush();
writer.close();
}
} catch (IOException e) {
throw new DiffException("Failed to close report file", e);
}
} | java |
public void swapAccounts(Database other) {
Account otherRoot = other.rootAccount;
other.rootAccount = rootAccount;
rootAccount = otherRoot;
boolean otherDirty = other.dirty;
other.dirty = dirty;
dirty = otherDirty;
HashMap<String, String> otherGlobalSettings = oth... | java |
public void addAccount(Account parent, Account child)
throws Exception {
// Check to see if the account physically already exists - there is something funny with
// some Firefox RDF exports where an RDF:li node gets duplicated multiple times.
for (Account dup : parent.getChildren()) ... | java |
public void removeAccount(Account accountToDelete) {
// Thou shalt not delete root
if (accountToDelete.getId().equals(rootAccount.getId()))
return;
Account parent = findParent(accountToDelete);
if (parent != null) {
removeAccount(parent, accountToDelete);
... | java |
private void removeAccount(Account parent, Account child) {
parent.getChildren().remove(child);
sendAccountRemoved(parent, child);
} | java |
public void setGlobalSetting(String name, String value) {
String oldValue;
// Avoid redundant setting
if (globalSettings.containsKey(name)) {
oldValue = globalSettings.get(name);
if (value.compareTo(oldValue) == 0)
return;
}
globalSettings... | java |
public String getGlobalSetting(GlobalSettingKey key) {
if (globalSettings.containsKey(key.toString()))
return globalSettings.get(key.toString());
return key.getDefault();
} | java |
private void printDatabase(Account acc, int level, PrintStream stream) {
String buf = "";
for (int i = 0; i < level; i++)
buf += " ";
buf += "+";
buf += acc.getName() + "[" + acc.getUrl() + "] (" + acc.getPatterns().size() + " patterns)";
stream.println(buf);
... | java |
private static int checkResult(int result)
{
if (exceptionsEnabled && result != curandStatus.CURAND_STATUS_SUCCESS)
{
throw new CudaException(curandStatus.stringFor(result));
}
return result;
} | java |
public final void nameArgument(String name, int index)
{
VariableElement lv = getLocalVariable(index);
if (lv instanceof UpdateableElement)
{
UpdateableElement ue = (UpdateableElement) lv;
ue.setSimpleName(El.getName(name));
}
else
{
... | java |
public VariableElement getLocalVariable(int index)
{
int idx = 0;
for (VariableElement lv : localVariables)
{
if (idx == index)
{
return lv;
}
if (Typ.isCategory2(lv.asType()))
{
idx += 2;
... | java |
public String getLocalName(int index)
{
VariableElement lv = getLocalVariable(index);
return lv.getSimpleName().toString();
} | java |
public TypeMirror getLocalType(String name)
{
VariableElement lv = getLocalVariable(name);
return lv.asType();
} | java |
public String getLocalDescription(int index)
{
StringWriter sw = new StringWriter();
El.printElements(sw, getLocalVariable(index));
return sw.toString();
} | java |
public void loadDefault(TypeMirror type) throws IOException
{
if (type.getKind() != TypeKind.VOID)
{
if (Typ.isPrimitive(type))
{
tconst(type, 0);
}
else
{
aconst_null();
}
}
... | java |
public void startSubroutine(String target) throws IOException
{
if (subroutine != null)
{
throw new IllegalStateException("subroutine "+subroutine+" not ended when "+target+ "started");
}
subroutine = target;
if (!hasLocalVariable(SUBROUTINERETURNADDRESSNAM... | java |
public TypeMirror typeForCount(int count)
{
if (count <= Byte.MAX_VALUE)
{
return Typ.Byte;
}
if (count <= Short.MAX_VALUE)
{
return Typ.Short;
}
if (count <= Integer.MAX_VALUE)
{
return Typ.Int;
... | java |
@Override
public void fixAddress(String name) throws IOException
{
super.fixAddress(name);
if (debugMethod != null)
{
int position = position();
tload("this");
ldc(position);
ldc(name);
invokevirtual(debugMethod);
... | java |
public Route matchRoute(String url) {
if (hashRoute.containsKey(url)) {
return new Route(hashRoute.get(url).get(0), null);
}
for (RegexRoute route : regexRoute) {
Matcher matcher = route.getPattern().matcher(url);
if (matcher.matches()) {
retu... | java |
public void addAttributes(List<Attribute> attributes) {
for(Attribute attribute : attributes) {
addAttribute(attribute.getName(), attribute.getValue());
}
} | java |
public void addAttribute(String attributeName, String attributeValue) throws XmlModelException {
String name = attributeName.trim();
String value = attributeValue.trim();
if(attributesMap.containsKey(name)) {
throw new XmlModelException("Duplicate attribute: " + name);
}
... | java |
private static void tc(Map<M, Set<M>> index) {
final Map<String, Object[]> warnings = new HashMap<>();
for (Entry<M, Set<M>> entry: index.entrySet()) {
final M src = entry.getKey();
final Set<M> dependents = entry.getValue();
final Queue<M> queue = new LinkedList<M>(... | java |
private <I> void hear( Class<? super I> type, TypeEncounter<I> encounter )
{
if ( type == null || type.getPackage().getName().startsWith( JAVA_PACKAGE ) )
{
return;
}
for ( Method method : type.getDeclaredMethods() )
{
if ( method.isAnnotationPresent(... | java |
public ResultSetStreamer require(String column, Assertion assertion) {
if (_requires == Collections.EMPTY_MAP) _requires = new HashMap<String, Assertion>();
_requires.put(column, assertion);
return this;
} | java |
public ResultSetStreamer exclude(String column, Assertion assertion) {
if (_excludes == Collections.EMPTY_MAP) _excludes = new HashMap<String, Assertion>();
_excludes.put(column, assertion);
return this;
} | java |
public static <T extends Executable> Predicate<T> executableIsSynthetic() {
return candidate -> candidate != null && candidate.isSynthetic();
} | java |
public static <T extends Executable> Predicate<T> executableBelongsToClass(Class<?> reference) {
return candidate -> candidate != null && reference.equals(candidate.getDeclaringClass());
} | java |
public static <T extends Executable> Predicate<T> executableBelongsToClassAssignableTo(Class<?> reference) {
return candidate -> candidate != null && reference.isAssignableFrom(candidate.getDeclaringClass());
} | java |
public static <T extends Executable> Predicate<T> executableIsEquivalentTo(T reference) {
Predicate<T> predicate = candidate -> candidate != null
&& candidate.getName().equals(reference.getName())
&& executableHasSameParameterTypesAs(reference).test(candidate);
if (refere... | java |
public static <T extends Executable> Predicate<T> executableHasSameParameterTypesAs(T reference) {
return candidate -> {
if (candidate == null) {
return false;
}
Class<?>[] candidateParameterTypes = candidate.getParameterTypes();
Class<?>[] referen... | java |
@Override
public void run() {
try {
try {
turnsControl.waitTurns(1, "Robot starting"); // block at the beginning so that all
// robots start at the
// same time
} catch (BankInterruptedException exc) {
log.trace("[run] Interrupted before starting");
}
assert getData().isEnabl... | java |
@Override
public void die(String reason) {
log.info("[die] Robot {} died with reason: {}", serialNumber, reason);
if (alive) { // if not alive it means it was killed at creation
alive = false;
interrupted = true; // to speed up death
world.remove(Robot.this);
}
} | java |
protected List<FileStatus> listStatus(JobContext job) throws IOException
{
List<FileStatus> result = new ArrayList<FileStatus>();
Path[] dirs = getInputPaths(job);
if (dirs.length == 0) {
throw new IOException("No input paths specified in job");
}
// Get tokens f... | java |
protected void checkInputClass(final Object domainObject) {
final Class<?> actualInputType = domainObject.getClass();
if(!(expectedInputType.isAssignableFrom(actualInputType))) {
throw new IllegalArgumentException("The input document is required to be of type: " + expectedInputType.getName()... | java |
public void setTimeout(long timeout, TimeUnit unit)
{
this.timeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
} | java |
public final void sendObjectToSocket(Object o) {
Session sess = this.getSession();
if (sess != null) {
String json;
try {
json = this.mapper.writeValueAsString(o);
} catch (JsonProcessingException e) {
ClientSocketAdapter.LOGGER.error("Failed to serialize object", e);
return;
}
sess.getRe... | java |
protected final <T> T readMessage(String message, Class<T> clazz) {
if ((message == null) || message.isEmpty()) {
ClientSocketAdapter.LOGGER.info("Got empty session data");
return null;
}
try {
return this.mapper.readValue(message, clazz);
} catch (IOException e1) {
ClientSocketAdapter.LOGGER.info("... | java |
public ByteBuffer makeByteBuffer(InputStream in)
throws IOException {
int limit = in.available();
if (limit < 1024) limit = 1024;
ByteBuffer result = byteBufferCache.get(limit);
int position = 0;
while (in.available() != 0) {
if (position >= limit)
... | java |
public void add(Collection<BrowserApplication> browserApplications)
{
for(BrowserApplication browserApplication : browserApplications)
this.browserApplications.put(browserApplication.getId(), browserApplication);
} | java |
public static Object getProperty(Object object, String name) throws NoSuchFieldException {
try {
Matcher matcher = ARRAY_INDEX.matcher(name);
if (matcher.matches()) {
object = getProperty(object, matcher.group(1));
if (object.getClass().isArray()) {
... | java |
@SuppressWarnings("unchecked")
public static void setProperty(Object object, String name, String text) throws NoSuchFieldException {
try {
// need to get to the field for any typeinfo annotation, so here we go ...
int length = name.lastIndexOf('.');
if (length > 0) {
... | java |
@SafeVarargs
public static <T> T[] concat(T[] first, T[]... rest) {
int length = first.length;
for (T[] array : rest) {
length += array.length;
}
T[] result = Arrays.copyOf(first, length);
int offset = first.length;
for (T[] array : rest) {
Sys... | java |
public Iterable<Di18n> queryByBaseBundle(java.lang.String baseBundle) {
return queryByField(null, Di18nMapper.Field.BASEBUNDLE.getFieldName(), baseBundle);
} | java |
public Iterable<Di18n> queryByKey(java.lang.String key) {
return queryByField(null, Di18nMapper.Field.KEY.getFieldName(), key);
} | java |
public Iterable<Di18n> queryByLocale(java.lang.String locale) {
return queryByField(null, Di18nMapper.Field.LOCALE.getFieldName(), locale);
} | java |
public Iterable<Di18n> queryByLocalizedMessage(java.lang.String localizedMessage) {
return queryByField(null, Di18nMapper.Field.LOCALIZEDMESSAGE.getFieldName(), localizedMessage);
} | java |
public static String maskExcept(final String s, final int unmaskedLength, final char maskChar) {
if (s == null) {
return null;
}
final boolean maskLeading = unmaskedLength > 0;
final int length = s.length();
final int maskedLength = Math.max(0, length - Math.abs(unmas... | java |
public static String replaceNonPrintableControlCharacters(final String value) {
if (value == null || value.length() == 0) {
return value;
}
boolean changing = false;
for (int i = 0, length = value.length(); i < length; i++) {
final char ch = value.charAt(i);
... | java |
public static String shortUuid() {
// source: java.util.UUID.randomUUID()
final byte[] randomBytes = new byte[16];
UUID_GENERATOR.nextBytes(randomBytes);
randomBytes[6] = (byte) (randomBytes[6] & 0x0f); // clear version
randomBytes[6] = (byte) (randomBytes[6] | 0x40); // set to v... | java |
public static List<String> splitToList(final String value) {
if (!StringUtils.isEmpty(value)) {
return COMMA_SPLITTER.splitToList(value);
}
return Collections.<String> emptyList();
} | java |
public static String trimWhitespace(final String s) {
if (s == null || s.length() == 0) {
return s;
}
final int length = s.length();
int end = length;
int start = 0;
while (start < end && Character.isWhitespace(s.charAt(start))) {
start++;
... | java |
public static String trimWhitespaceToNull(final String s) {
final String result = trimWhitespace(s);
return StringUtils.isEmpty(result) ? null : s;
} | java |
public List<ServiceReference> getReferences(String resourceType) {
List<ServiceReference> references = new ArrayList<ServiceReference>();
if (containsKey(resourceType)) {
references.addAll(get(resourceType));
Collections.sort(references, new Comparator<ServiceReference>() {
@Override
public int compar... | java |
public void registerComponentBindingsProvider(ServiceReference reference) {
log.info("registerComponentBindingsProvider");
log.info("Registering Component Bindings Provider {} - {}",
new Object[] { reference.getProperty(Constants.SERVICE_ID),
reference.getProperty(Constants.SERVICE_PID) });
String[] res... | java |
public void unregisterComponentBindingsProvider(ServiceReference reference) {
log.info("unregisterComponentBindingsProvider");
String[] resourceTypes = OsgiUtil.toStringArray(reference
.getProperty(ComponentBindingsProvider.RESOURCE_TYPE_PROP),
new String[0]);
for (String resourceType : resourceTypes) {
... | java |
public ComponentFactory<T, E> toCreate(BiFunction<Constructor, Object[], Object>
createFunction) {
return new ComponentFactory<>(this.annotationType, this.classElement, this.contextConsumer, createFunction);
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.