code
stringlengths
73
34.1k
func_name
stringlengths
1
122
public Collection<SerialMessage> initialize() { ArrayList<SerialMessage> result = new ArrayList<SerialMessage>(); if (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) { logger.warn("Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET."); return result; } result.add(this.getSupportedMessage()); return result; }
initialize
public static java.util.Date newDateTime() { return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS); }
newDateTime
public static java.sql.Date newDate() { return new java.sql.Date((System.currentTimeMillis() / DAY_MILLIS) * DAY_MILLIS); }
newDate
public static java.sql.Time newTime() { return new java.sql.Time(System.currentTimeMillis() % DAY_MILLIS); }
newTime
public static int secondsDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; } return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS)); }
secondsDiff
public static int minutesDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; } return (int) ((laterDate.getTime() / MINUTE_MILLIS) - (earlierDate.getTime() / MINUTE_MILLIS)); }
minutesDiff
public static int hoursDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; } return (int) ((laterDate.getTime() / HOUR_MILLIS) - (earlierDate.getTime() / HOUR_MILLIS)); }
hoursDiff
public static int daysDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; } return (int) ((laterDate.getTime() / DAY_MILLIS) - (earlierDate.getTime() / DAY_MILLIS)); }
daysDiff
public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) { GregorianCalendar gc = new GregorianCalendar(); gc.setTime(startDate); gc.add(period, amount); return new java.sql.Time(gc.getTime().getTime()); }
rollTime
public static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) { GregorianCalendar gc = new GregorianCalendar(); gc.setTime(startDate); gc.add(period, amount); return new java.util.Date(gc.getTime().getTime()); }
rollDateTime
public static java.sql.Date rollYears(java.util.Date startDate, int years) { return rollDate(startDate, Calendar.YEAR, years); }
rollYears
@SuppressWarnings("deprecation") public static boolean dateEquals(java.util.Date d1, java.util.Date d2) { if (d1 == null || d2 == null) { return false; } return d1.getDate() == d2.getDate() && d1.getMonth() == d2.getMonth() && d1.getYear() == d2.getYear(); }
dateEquals
@SuppressWarnings("deprecation") public static boolean timeEquals(java.util.Date d1, java.util.Date d2) { if (d1 == null || d2 == null) { return false; } return d1.getHours() == d2.getHours() && d1.getMinutes() == d2.getMinutes() && d1.getSeconds() == d2.getSeconds(); }
timeEquals
@SuppressWarnings("deprecation") public static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) { if (d1 == null || d2 == null) { return false; } return d1.getDate() == d2.getDate() && d1.getMonth() == d2.getMonth() && d1.getYear() == d2.getYear() && d1.getHours() == d2.getHours() && d1.getMinutes() == d2.getMinutes() && d1.getSeconds() == d2.getSeconds(); }
dateTimeEquals
public static Object toObject(Class<?> clazz, Object value) throws ParseException { if (value == null) { return null; } if (clazz == null) { return value; } if (java.sql.Date.class.isAssignableFrom(clazz)) { return toDate(value); } if (java.sql.Time.class.isAssignableFrom(clazz)) { return toTime(value); } if (java.sql.Timestamp.class.isAssignableFrom(clazz)) { return toTimestamp(value); } if (java.util.Date.class.isAssignableFrom(clazz)) { return toDateTime(value); } return value; }
toObject
public static java.util.Date getDateTime(Object value) { try { return toDateTime(value); } catch (ParseException pe) { pe.printStackTrace(); return null; } }
getDateTime
public static java.util.Date toDateTime(Object value) throws ParseException { if (value == null) { return null; } if (value instanceof java.util.Date) { return (java.util.Date) value; } if (value instanceof String) { if ("".equals((String) value)) { return null; } return IN_DATETIME_FORMAT.parse((String) value); } return IN_DATETIME_FORMAT.parse(value.toString()); }
toDateTime
public static java.sql.Date getDate(Object value) { try { return toDate(value); } catch (ParseException pe) { pe.printStackTrace(); return null; } }
getDate
public static java.sql.Date toDate(Object value) throws ParseException { if (value == null) { return null; } if (value instanceof java.sql.Date) { return (java.sql.Date) value; } if (value instanceof String) { if ("".equals((String) value)) { return null; } return new java.sql.Date(IN_DATE_FORMAT.parse((String) value).getTime()); } return new java.sql.Date(IN_DATE_FORMAT.parse(value.toString()).getTime()); }
toDate
public static java.sql.Time getTime(Object value) { try { return toTime(value); } catch (ParseException pe) { pe.printStackTrace(); return null; } }
getTime
public static java.sql.Time toTime(Object value) throws ParseException { if (value == null) { return null; } if (value instanceof java.sql.Time) { return (java.sql.Time) value; } if (value instanceof String) { if ("".equals((String) value)) { return null; } return new java.sql.Time(IN_TIME_FORMAT.parse((String) value).getTime()); } return new java.sql.Time(IN_TIME_FORMAT.parse(value.toString()).getTime()); }
toTime
public static java.sql.Timestamp getTimestamp(Object value) { try { return toTimestamp(value); } catch (ParseException pe) { pe.printStackTrace(); return null; } }
getTimestamp
public static java.sql.Timestamp toTimestamp(Object value) throws ParseException { if (value == null) { return null; } if (value instanceof java.sql.Timestamp) { return (java.sql.Timestamp) value; } if (value instanceof String) { if ("".equals((String) value)) { return null; } return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse((String) value).getTime()); } return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse(value.toString()).getTime()); }
toTimestamp
@SuppressWarnings("deprecation") public static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) { d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds()); if (start == null || end == null) { return false; } if (start.before(end) && (!(d.after(start) && d.before(end)))) { return false; } if (end.before(start) && (!(d.after(end) || d.before(start)))) { return false; } return true; }
isTimeInRange
public static Trajectory combineTrajectory(Trajectory a, Trajectory b){ if(a.getDimension()!=b.getDimension()){ throw new IllegalArgumentException("Combination not possible: The trajectorys does not have the same dimension"); } if(a.size()!=b.size()){ throw new IllegalArgumentException("Combination not possible: The trajectorys does not " + "have the same number of steps a="+a.size() + " b="+b.size()); } Trajectory c = new Trajectory(a.getDimension()); for(int i = 0 ; i < a.size(); i++){ Point3d pos = new Point3d(a.get(i).x+b.get(i).x, a.get(i).y+b.get(i).y, a.get(i).z+b.get(i).z); c.add(pos); } return c; }
combineTrajectory
public static Trajectory concactTrajectorie(Trajectory a, Trajectory b){ if(a.getDimension()!=b.getDimension()){ throw new IllegalArgumentException("Combination not possible: The trajectorys does not have the same dimension"); } Trajectory c = new Trajectory(a.getDimension()); for(int i = 0 ; i < a.size(); i++){ Point3d pos = new Point3d(a.get(i).x, a.get(i).y, a.get(i).z); c.add(pos); } double dx = a.get(a.size()-1).x - b.get(0).x; double dy = a.get(a.size()-1).y - b.get(0).y; double dz = a.get(a.size()-1).z - b.get(0).z; for(int i = 1 ; i < b.size(); i++){ Point3d pos = new Point3d(b.get(i).x+dx, b.get(i).y+dy, b.get(i).z+dz); c.add(pos); } return c; }
concactTrajectorie
public static Trajectory resample(Trajectory t, int n){ Trajectory t1 = new Trajectory(2); for(int i = 0; i < t.size(); i=i+n){ t1.add(t.get(i)); } return t1; }
resample
public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id){ Trajectory track = null; for(int i = 0; i < t.size() ; i++){ if(t.get(i).getID()==id){ track = t.get(i); break; } } return track; }
getTrajectoryByID
public void setPropertyDestinationType(Class<?> clazz, String propertyName, TypeReference<?> destinationType) { propertiesDestinationTypes.put(new ClassProperty(clazz, propertyName), destinationType); }
setPropertyDestinationType
public void addConverter(int index, IConverter converter) { converterList.add(index, converter); if (converter instanceof IContainerConverter) { IContainerConverter containerConverter = (IContainerConverter) converter; if (containerConverter.getElementConverter() == null) { containerConverter.setElementConverter(elementConverter); } } }
addConverter
public static SPIProviderResolver getInstance(ClassLoader cl) { SPIProviderResolver resolver = (SPIProviderResolver)ServiceLoader.loadService(SPIProviderResolver.class.getName(), DEFAULT_SPI_PROVIDER_RESOLVER, cl); return resolver; }
getInstance
static Parameter createParameter(final String name, final String value) { if (value != null && isQuoted(value)) { return new QuotedParameter(name, value); } return new Parameter(name, value); }
createParameter
public static <T, A extends Annotation> String getClassAnnotationValue(Class<T> classType, Class<A> annotationType, String attributeName) { String value = null; Annotation annotation = classType.getAnnotation(annotationType); if (annotation != null) { try { value = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation); } catch (Exception ex) {} } return value; }
getClassAnnotationValue
private Long string2long(String text, DateTimeFormat fmt) { // null or "" returns null if (text == null) return null; text = text.trim(); if (text.length() == 0) return null; Date date = fmt.parse(text); return date != null ? UTCDateBox.date2utc(date) : null; }
string2long
private String long2string(Long value, DateTimeFormat fmt) { // for html5 inputs, use "" for no value if (value == null) return ""; Date date = UTCDateBox.utc2date(value); return date != null ? fmt.format(date) : null; }
long2string
public static RgbaColor from(String color) { if (color.startsWith("#")) { return fromHex(color); } else if (color.startsWith("rgba")) { return fromRgba(color); } else if (color.startsWith("rgb")) { return fromRgb(color); } else if (color.startsWith("hsla")) { return fromHsla(color); } else if (color.startsWith("hsl")) { return fromHsl(color); } else { return getDefaultColor(); } }
from
public static RgbaColor fromHex(String hex) { if (hex.length() == 0 || hex.charAt(0) != '#') return getDefaultColor(); // #rgb if (hex.length() == 4) { return new RgbaColor(parseHex(hex, 1, 2), parseHex(hex, 2, 3), parseHex(hex, 3, 4)); } // #rrggbb else if (hex.length() == 7) { return new RgbaColor(parseHex(hex, 1, 3), parseHex(hex, 3, 5), parseHex(hex, 5, 7)); } else { return getDefaultColor(); } }
fromHex
public static RgbaColor fromRgb(String rgb) { if (rgb.length() == 0) return getDefaultColor(); String[] parts = getRgbParts(rgb).split(","); if (parts.length == 3) { return new RgbaColor(parseInt(parts[0]), parseInt(parts[1]), parseInt(parts[2])); } else { return getDefaultColor(); } }
fromRgb
public static RgbaColor fromRgba(String rgba) { if (rgba.length() == 0) return getDefaultColor(); String[] parts = getRgbaParts(rgba).split(","); if (parts.length == 4) { return new RgbaColor(parseInt(parts[0]), parseInt(parts[1]), parseInt(parts[2]), parseFloat(parts[3])); } else { return getDefaultColor(); } }
fromRgba
private RgbaColor withHsl(int index, float value) { float[] HSL = convertToHsl(); HSL[index] = value; return RgbaColor.fromHsl(HSL); }
withHsl
public RgbaColor adjustHue(float degrees) { float[] HSL = convertToHsl(); HSL[0] = hueCheck(HSL[0] + degrees); // ensure [0-360) return RgbaColor.fromHsl(HSL); }
adjustHue
public RgbaColor opacify(float amount) { return new RgbaColor(r, g, b, alphaCheck(a + amount)); }
opacify
protected static final float[] getSpreadInRange(float member, int count, int max, int offset) { // to find the spread, we first find the min that is a // multiple of max/count away from the member int interval = max / count; float min = (member + offset) % interval; if (min == 0 && member == max) { min += interval; } float[] range = new float[count]; for (int i = 0; i < count; i++) { range[i] = min + interval * i + offset; } return range; }
getSpreadInRange
public static RgbaColor fromHsl(float H, float S, float L) { // convert to [0-1] H /= 360f; S /= 100f; L /= 100f; float R, G, B; if (S == 0) { // grey R = G = B = L; } else { float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S; float m1 = 2f * L - m2; R = hue2rgb(m1, m2, H + 1 / 3f); G = hue2rgb(m1, m2, H); B = hue2rgb(m1, m2, H - 1 / 3f); } // convert [0-1] to [0-255] int r = Math.round(R * 255f); int g = Math.round(G * 255f); int b = Math.round(B * 255f); return new RgbaColor(r, g, b, 1); }
fromHsl
private float max(float x, float y, float z) { if (x > y) { // not y if (x > z) { return x; } else { return z; } } else { // not x if (y > z) { return y; } else { return z; } } }
max
public Constructor<?> getCompatibleConstructor(Class<?> type, Class<?> argumentType) { try { return type.getConstructor(new Class[] { argumentType }); } catch (Exception e) { // get public classes and interfaces Class<?>[] types = type.getClasses(); for (int i = 0; i < types.length; i++) { try { return type.getConstructor(new Class[] { types[i] }); } catch (Exception e1) { } } } return null; }
getCompatibleConstructor
public <T> T convert(Object source, TypeReference<T> typeReference) throws ConverterException { return (T) convert(new ConversionContext(), source, typeReference); }
convert
public <T> T convert(ConversionContext context, Object source, TypeReference<T> destinationType) throws ConverterException { try { return (T) multiConverter.convert(context, source, destinationType); } catch (ConverterException e) { throw e; } catch (Exception e) { // There is a problem with one converter. This should not happen. // Either there is a bug in this converter or it is not properly // configured throw new ConverterException( MessageFormat .format( "Could not convert given object with class ''{0}'' to object with type signature ''{1}''", source == null ? "null" : source.getClass() .getName(), destinationType), e); } }
convert
public static int compare(double a, double b, double delta) { if (equals(a, b, delta)) { return 0; } return Double.compare(a, b); }
compare
public double getValue(int[] batch) { double value = 0.0; for (int i=0; i<batch.length; i++) { value += getValue(i); } return value; }
getValue
public void getGradient(int[] batch, double[] gradient) { for (int i=0; i<batch.length; i++) { addGradient(i, gradient); } }
getGradient
public synchronized static SQLiteDatabase getConnection(Context context) { if (database == null) { // Construct the single helper and open the unique(!) db connection for the app database = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase(); } return database; }
getConnection
@SuppressWarnings("unchecked") public static Type getSuperclassTypeParameter(Class<?> subclass) { Type superclass = subclass.getGenericSuperclass(); if (superclass instanceof Class) { throw new RuntimeException("Missing type parameter."); } return ((ParameterizedType) superclass).getActualTypeArguments()[0]; }
getSuperclassTypeParameter
@Override protected void onLoad() { super.onLoad(); // these styles need to be the same for the box and shadow so // that we can measure properly matchStyles("display"); matchStyles("fontSize"); matchStyles("fontFamily"); matchStyles("fontWeight"); matchStyles("lineHeight"); matchStyles("paddingTop"); matchStyles("paddingRight"); matchStyles("paddingBottom"); matchStyles("paddingLeft"); adjustSize(); }
onLoad
@Override public void onKeyDown(KeyDownEvent event) { char c = MiscUtils.getCharCode(event.getNativeEvent()); onKeyCodeEvent(event, box.getValue()+c); }
onKeyDown
public static void setEnabled(Element element, boolean enabled) { element.setPropertyBoolean("disabled", !enabled); setStyleName(element, "disabled", !enabled); }
setEnabled
private Method getPropertySourceMethod(Object sourceObject, Object destinationObject, String destinationProperty) { BeanToBeanMapping beanToBeanMapping = beanToBeanMappings.get(ClassPair .get(sourceObject.getClass(), destinationObject .getClass())); String sourceProperty = null; if (beanToBeanMapping != null) { sourceProperty = beanToBeanMapping .getSourceProperty(destinationProperty); } if (sourceProperty == null) { sourceProperty = destinationProperty; } return BeanUtils.getGetterPropertyMethod(sourceObject.getClass(), sourceProperty); }
getPropertySourceMethod
protected TypeReference<?> getBeanPropertyType(Class<?> clazz, String propertyName, TypeReference<?> originalType) { TypeReference<?> propertyDestinationType = null; if (beanDestinationPropertyTypeProvider != null) { propertyDestinationType = beanDestinationPropertyTypeProvider .getPropertyType(clazz, propertyName, originalType); } if (propertyDestinationType == null) { propertyDestinationType = originalType; } return propertyDestinationType; }
getBeanPropertyType
public void addBeanToBeanMapping(BeanToBeanMapping beanToBeanMapping) { beanToBeanMappings.put(ClassPair.get(beanToBeanMapping .getSourceClass(), beanToBeanMapping.getDestinationClass()), beanToBeanMapping); }
addBeanToBeanMapping
public static SPIProvider getInstance() { if (me == null) { final ClassLoader cl = ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader(); me = SPIProviderResolver.getInstance(cl).getProvider(); } return me; }
getInstance
public <T> T getSPI(Class<T> spiType) { return getSPI(spiType, SecurityActions.getContextClassLoader()); }
getSPI
public Optional<SoyMsgBundle> resolve(final Optional<Locale> locale) throws IOException { if (!locale.isPresent()) { return Optional.absent(); } synchronized (msgBundles) { SoyMsgBundle soyMsgBundle = null; if (isHotReloadModeOff()) { soyMsgBundle = msgBundles.get(locale.get()); } if (soyMsgBundle == null) { soyMsgBundle = createSoyMsgBundle(locale.get()); if (soyMsgBundle == null) { soyMsgBundle = createSoyMsgBundle(new Locale(locale.get().getLanguage())); } if (soyMsgBundle == null && fallbackToEnglish) { soyMsgBundle = createSoyMsgBundle(Locale.ENGLISH); } if (soyMsgBundle == null) { return Optional.absent(); } if (isHotReloadModeOff()) { msgBundles.put(locale.get(), soyMsgBundle); } } return Optional.fromNullable(soyMsgBundle); } }
resolve
private Optional<? extends SoyMsgBundle> mergeMsgBundles(final Locale locale, final List<SoyMsgBundle> soyMsgBundles) { if (soyMsgBundles.isEmpty()) { return Optional.absent(); } final List<SoyMsg> msgs = Lists.newArrayList(); for (final SoyMsgBundle smb : soyMsgBundles) { for (final Iterator<SoyMsg> it = smb.iterator(); it.hasNext();) { msgs.add(it.next()); } } return Optional.of(new SoyMsgBundleImpl(locale.toString(), msgs)); }
mergeMsgBundles
@Override public Optional<String> hash(final Optional<URL> url) throws IOException { if (!url.isPresent()) { return Optional.absent(); } logger.debug("Calculating md5 hash, url:{}", url); if (isHotReloadModeOff()) { final String md5 = cache.getIfPresent(url.get()); logger.debug("md5 hash:{}", md5); if (md5 != null) { return Optional.of(md5); } } final InputStream is = url.get().openStream(); final String md5 = getMD5Checksum(is); if (isHotReloadModeOff()) { logger.debug("caching url:{} with hash:{}", url, md5); cache.put(url.get(), md5); } return Optional.fromNullable(md5); }
hash
public static String[] allUpperCase(String... strings){ String[] tmp = new String[strings.length]; for(int idx=0;idx<strings.length;idx++){ if(strings[idx] != null){ tmp[idx] = strings[idx].toUpperCase(); } } return tmp; }
allUpperCase
public static String[] allLowerCase(String... strings){ String[] tmp = new String[strings.length]; for(int idx=0;idx<strings.length;idx++){ if(strings[idx] != null){ tmp[idx] = strings[idx].toLowerCase(); } } return tmp; }
allLowerCase
public FullTypeSignature getTypeErasureSignature() { if (typeErasureSignature == null) { typeErasureSignature = new ClassTypeSignature(binaryName, new TypeArgSignature[0], ownerTypeSignature == null ? null : (ClassTypeSignature) ownerTypeSignature .getTypeErasureSignature()); } return typeErasureSignature; }
getTypeErasureSignature
public MIMEType addParameter(String name, String value) { Map<String, String> copy = new LinkedHashMap<>(this.parameters); copy.put(name, value); return new MIMEType(type, subType, copy); }
addParameter
@Override public List<String> contentTypes() { List<String> contentTypes = null; final HttpServletRequest request = getHttpRequest(); if (favorParameterOverAcceptHeader) { contentTypes = getFavoredParameterValueAsList(request); } else { contentTypes = getAcceptHeaderValues(request); } if (isEmpty(contentTypes)) { logger.debug("Setting content types to default: {}.", DEFAULT_SUPPORTED_CONTENT_TYPES); contentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES; } return unmodifiableList(contentTypes); }
contentTypes
public Headers getAllHeaders() { Headers requestHeaders = getHeaders(); requestHeaders = hasPayload() ? requestHeaders.withContentType(getPayload().get().getMimeType()) : requestHeaders; //We don't want to add headers more than once. return requestHeaders; }
getAllHeaders
public static Optimizer<DifferentiableFunction> getRegularizedOptimizer(final Optimizer<DifferentiableFunction> opt, final double l1Lambda, final double l2Lambda) { if (l1Lambda == 0 && l2Lambda == 0) { return opt; } return new Optimizer<DifferentiableFunction>() { @Override public boolean minimize(DifferentiableFunction objective, IntDoubleVector point) { DifferentiableFunction fn = getRegularizedFn(objective, false, l1Lambda, l2Lambda); return opt.minimize(fn, point); } }; }
getRegularizedOptimizer
public String toRomanNumeral() { if (this.romanString == null) { this.romanString = ""; int remainder = this.value; for (int i = 0; i < BASIC_VALUES.length; i++) { while (remainder >= BASIC_VALUES[i]) { this.romanString += BASIC_ROMAN_NUMERALS[i]; remainder -= BASIC_VALUES[i]; } } } return this.romanString; }
toRomanNumeral
public void takeNoteOfGradient(IntDoubleVector gradient) { gradient.iterate(new FnIntDoubleToVoid() { @Override public void call(int index, double value) { gradSumSquares[index] += value * value; assert !Double.isNaN(gradSumSquares[index]); } }); }
takeNoteOfGradient
private ArrayTypeSignature getArrayTypeSignature( GenericArrayType genericArrayType) { FullTypeSignature componentTypeSignature = getFullTypeSignature(genericArrayType .getGenericComponentType()); ArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature( componentTypeSignature); return arrayTypeSignature; }
getArrayTypeSignature
private ClassTypeSignature getClassTypeSignature( ParameterizedType parameterizedType) { Class<?> rawType = (Class<?>) parameterizedType.getRawType(); Type[] typeArguments = parameterizedType.getActualTypeArguments(); TypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArguments.length]; for (int i = 0; i < typeArguments.length; i++) { typeArgSignatures[i] = getTypeArgSignature(typeArguments[i]); } String binaryName = rawType.isMemberClass() ? rawType.getSimpleName() : rawType.getName(); ClassTypeSignature ownerTypeSignature = parameterizedType .getOwnerType() == null ? null : (ClassTypeSignature) getFullTypeSignature(parameterizedType .getOwnerType()); ClassTypeSignature classTypeSignature = new ClassTypeSignature( binaryName, typeArgSignatures, ownerTypeSignature); return classTypeSignature; }
getClassTypeSignature
private FullTypeSignature getTypeSignature(Class<?> clazz) { StringBuilder sb = new StringBuilder(); if (clazz.isArray()) { sb.append(clazz.getName()); } else if (clazz.isPrimitive()) { sb.append(primitiveTypesMap.get(clazz).toString()); } else { sb.append('L').append(clazz.getName()).append(';'); } return TypeSignatureFactory.getTypeSignature(sb.toString(), false); }
getTypeSignature
private TypeArgSignature getTypeArgSignature(Type type) { if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; Type lowerBound = wildcardType.getLowerBounds().length == 0 ? null : wildcardType.getLowerBounds()[0]; Type upperBound = wildcardType.getUpperBounds().length == 0 ? null : wildcardType.getUpperBounds()[0]; if (lowerBound == null && Object.class.equals(upperBound)) { return new TypeArgSignature( TypeArgSignature.UNBOUNDED_WILDCARD, (FieldTypeSignature) getFullTypeSignature(upperBound)); } else if (lowerBound == null && upperBound != null) { return new TypeArgSignature( TypeArgSignature.UPPERBOUND_WILDCARD, (FieldTypeSignature) getFullTypeSignature(upperBound)); } else if (lowerBound != null) { return new TypeArgSignature( TypeArgSignature.LOWERBOUND_WILDCARD, (FieldTypeSignature) getFullTypeSignature(lowerBound)); } else { throw new RuntimeException("Invalid type"); } } else { return new TypeArgSignature(TypeArgSignature.NO_WILDCARD, (FieldTypeSignature) getFullTypeSignature(type)); } }
getTypeArgSignature
public static boolean zipFolder(File folder, String fileName){ boolean success = false; if(!folder.isDirectory()){ return false; } if(fileName == null){ fileName = folder.getAbsolutePath()+ZIP_EXT; } ZipArchiveOutputStream zipOutput = null; try { zipOutput = new ZipArchiveOutputStream(new File(fileName)); success = addFolderContentToZip(folder,zipOutput,""); zipOutput.close(); } catch (IOException e) { e.printStackTrace(); return false; } finally{ try { if(zipOutput != null){ zipOutput.close(); } } catch (IOException e) {} } return success; }
zipFolder
public static boolean unzipFileOrFolder(File zipFile, String unzippedFolder){ InputStream is; ArchiveInputStream in = null; OutputStream out = null; if(!zipFile.isFile()){ return false; } if(unzippedFolder == null){ unzippedFolder = FilenameUtils.removeExtension(zipFile.getAbsolutePath()); } try { is = new FileInputStream(zipFile); new File(unzippedFolder).mkdir(); in = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is); ZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry(); while(entry != null){ if(entry.isDirectory()){ new File(unzippedFolder,entry.getName()).mkdir(); } else{ out = new FileOutputStream(new File(unzippedFolder, entry.getName())); IOUtils.copy(in, out); out.close(); out = null; } entry = (ZipArchiveEntry)in.getNextEntry(); } } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (ArchiveException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally{ if(out != null){ try { out.close(); } catch (IOException e) {} } if(in != null){ try { in.close(); } catch (IOException e) {} } } return true; }
unzipFileOrFolder
protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) { if (value == null) { return ""; } else { // midnight GMT Date date = new Date(0); // offset by timezone and value date.setTime(UTCDateBox.timezoneOffsetMillis(date) + value.longValue()); // format it return fmt.format(date); } }
formatUsingFormat
protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) { if (text.indexOf(':') == -1) { text = text.replace(" ", ""); int numdigits = 0; int lastdigit = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (Character.isDigit(c)) { numdigits++; lastdigit = i; } } if (numdigits == 1 || numdigits == 2) { // insert :00 int colon = lastdigit + 1; text = text.substring(0, colon) + ":00" + text.substring(colon); } else if (numdigits > 2) { // insert : int colon = lastdigit - 1; text = text.substring(0, colon) + ":" + text.substring(colon); } return parseUsingFallbacks(text, timeFormat); } else { return null; } }
parseUsingFallbacksWithColon
public static Class<?> getRawType(Type type) { if (type instanceof Class) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { ParameterizedType actualType = (ParameterizedType) type; return getRawType(actualType.getRawType()); } else if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; Object rawArrayType = Array.newInstance(getRawType(genericArrayType .getGenericComponentType()), 0); return rawArrayType.getClass(); } else if (type instanceof WildcardType) { WildcardType castedType = (WildcardType) type; return getRawType(castedType.getUpperBounds()[0]); } else { throw new IllegalArgumentException( "Type \'" + type + "\' is not a Class, " + "ParameterizedType, or GenericArrayType. Can't extract class."); } }
getRawType
public static boolean isAssignableFrom(TypeReference<?> from, TypeReference<?> to) { if (from == null) { return false; } if (to.equals(from)) { return true; } if (to.getType() instanceof Class) { return to.getRawType().isAssignableFrom(from.getRawType()); } else if (to.getType() instanceof ParameterizedType) { return isAssignableFrom(from.getType(), (ParameterizedType) to .getType(), new HashMap<String, Type>()); } else if (to.getType() instanceof GenericArrayType) { return to.getRawType().isAssignableFrom(from.getRawType()) && isAssignableFrom(from.getType(), (GenericArrayType) to .getType()); } else { throw new AssertionError("Unexpected Type : " + to); } }
isAssignableFrom
private static boolean isAssignableFrom(Type from, ParameterizedType to, Map<String, Type> typeVarMap) { if (from == null) { return false; } if (to.equals(from)) { return true; } // First figure out the class and any type information. Class<?> clazz = getRawType(from); ParameterizedType ptype = null; if (from instanceof ParameterizedType) { ptype = (ParameterizedType) from; } // Load up parameterized variable info if it was parameterized. if (ptype != null) { Type[] tArgs = ptype.getActualTypeArguments(); TypeVariable<?>[] tParams = clazz.getTypeParameters(); for (int i = 0; i < tArgs.length; i++) { Type arg = tArgs[i]; TypeVariable<?> var = tParams[i]; while (arg instanceof TypeVariable) { TypeVariable<?> v = (TypeVariable<?>) arg; arg = typeVarMap.get(v.getName()); } typeVarMap.put(var.getName(), arg); } // check if they are equivalent under our current mapping. if (typeEquals(ptype, to, typeVarMap)) { return true; } } for (Type itype : clazz.getGenericInterfaces()) { if (isAssignableFrom(itype, to, new HashMap<String, Type>( typeVarMap))) { return true; } } // Interfaces didn't work, try the superclass. Type sType = clazz.getGenericSuperclass(); if (isAssignableFrom(sType, to, new HashMap<String, Type>(typeVarMap))) { return true; } return false; }
isAssignableFrom
private static boolean typeEquals(ParameterizedType from, ParameterizedType to, Map<String, Type> typeVarMap) { if (from.getRawType().equals(to.getRawType())) { Type[] fromArgs = from.getActualTypeArguments(); Type[] toArgs = to.getActualTypeArguments(); for (int i = 0; i < fromArgs.length; i++) { if (!matches(fromArgs[i], toArgs[i], typeVarMap)) { return false; } } return true; } return false; }
typeEquals
private static boolean matches(Type from, Type to, Map<String, Type> typeMap) { if (to.equals(from)) return true; if (from instanceof TypeVariable) { return to.equals(typeMap.get(((TypeVariable<?>) from).getName())); } return false; }
matches
private static boolean isAssignableFrom(Type from, GenericArrayType to) { Type toGenericComponentType = to.getGenericComponentType(); if (toGenericComponentType instanceof ParameterizedType) { Type t = from; if (from instanceof GenericArrayType) { t = ((GenericArrayType) from).getGenericComponentType(); } else if (from instanceof Class) { Class<?> classType = (Class<?>) from; while (classType.isArray()) { classType = classType.getComponentType(); } t = classType; } return isAssignableFrom(t, (ParameterizedType) toGenericComponentType, new HashMap<String, Type>()); } // No generic defined on "to"; therefore, return true and let other // checks determine assignability return true; }
isAssignableFrom
@Override public void setValue(String value, boolean fireEvents) { boolean added = setSelectedValue(this, value, addMissingValue); if (added && fireEvents) { ValueChangeEvent.fire(this, getValue()); } }
setValue
public static final String getSelectedValue(ListBox list) { int index = list.getSelectedIndex(); return (index >= 0) ? list.getValue(index) : null; }
getSelectedValue
public static final String getSelectedText(ListBox list) { int index = list.getSelectedIndex(); return (index >= 0) ? list.getItemText(index) : null; }
getSelectedText
public static final int findValueInListBox(ListBox list, String value) { for (int i=0; i<list.getItemCount(); i++) { if (value.equals(list.getValue(i))) { return i; } } return -1; }
findValueInListBox
public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) { if (value == null) { list.setSelectedIndex(0); return false; } else { int index = findValueInListBox(list, value); if (index >= 0) { list.setSelectedIndex(index); return true; } if (addMissingValues) { list.addItem(value, value); // now that it's there, search again index = findValueInListBox(list, value); list.setSelectedIndex(index); return true; } return false; } }
setSelectedValue
public static String capitalizePropertyName(String s) { if (s.length() == 0) { return s; } char[] chars = s.toCharArray(); chars[0] = Character.toUpperCase(chars[0]); return new String(chars); }
capitalizePropertyName
public static Method getGetterPropertyMethod(Class<?> type, String propertyName) { String sourceMethodName = "get" + BeanUtils.capitalizePropertyName(propertyName); Method sourceMethod = BeanUtils.getMethod(type, sourceMethodName); if (sourceMethod == null) { sourceMethodName = "is" + BeanUtils.capitalizePropertyName(propertyName); sourceMethod = BeanUtils.getMethod(type, sourceMethodName); if (sourceMethod != null && sourceMethod.getReturnType() != Boolean.TYPE) { sourceMethod = null; } } return sourceMethod; }
getGetterPropertyMethod
public static Method getSetterPropertyMethod(Class<?> type, String propertyName) { String sourceMethodName = "set" + BeanUtils.capitalizePropertyName(propertyName); Method sourceMethod = BeanUtils.getMethod(type, sourceMethodName); return sourceMethod; }
getSetterPropertyMethod
@Override public Optional<SoyMapData> toSoyMap(@Nullable final Object model) throws Exception { if (model instanceof SoyMapData) { return Optional.of((SoyMapData) model); } if (model instanceof Map) { return Optional.of(new SoyMapData(model)); } return Optional.of(new SoyMapData()); }
toSoyMap
@Override public int getShadowSize() { Element shadowElement = shadow.getElement(); shadowElement.setScrollTop(10000); return shadowElement.getScrollTop(); }
getShadowSize
public Object get(IConverter converter, Object sourceObject, TypeReference<?> destinationType) { return convertedObjects.get(new ConvertedObjectsKey(converter, sourceObject, destinationType)); }
get
public void add(IConverter converter, Object sourceObject, TypeReference<?> destinationType, Object convertedObject) { convertedObjects.put(new ConvertedObjectsKey(converter, sourceObject, destinationType), convertedObject); }
add
public void remove(IConverter converter, Object sourceObject, TypeReference<?> destinationType) { convertedObjects.remove(new ConvertedObjectsKey(converter, sourceObject, destinationType)); }
remove