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
|
---|---|---|---|---|---|---|
WhiteBlue/eleme-hackathon | src/main/java/cn/shiroblue/Catch.java | [
"public class ExceptionMapperFactory {\n\n private static ExceptionMapper exceptionMapper = null;\n\n private ExceptionMapperFactory() {\n }\n\n public static ExceptionMapper get() {\n if (exceptionMapper == null) {\n exceptionMapper = new ExceptionMapper();\n }\n return exceptionMapper;\n }\n}",
"public class Request {\n\n private static final String USER_AGENT = \"user-agent\";\n\n private Map<String, String> params;\n\n public HttpServletRequest servletRequest;\n\n /* Lazy loaded stuff */\n private String body = null;\n private byte[] bodyAsBytes = null;\n\n private Set<String> headers = null;\n\n public Request(HttpServletRequest servletRequest) {\n this.servletRequest = servletRequest;\n }\n\n public Request(RouteMatch match, HttpServletRequest request) {\n this.servletRequest = request;\n changeMatch(match);\n }\n\n private static Map<String, String> getParams(List<String> request, List<String> matched) {\n Map<String, String> params = new HashMap<>();\n\n for (int i = 0; (i < request.size()) && (i < matched.size()); i++) {\n String matchedPart = matched.get(i);\n if (TinyUtils.isParam(matchedPart)) {\n params.put(matchedPart.toLowerCase(), request.get(i));\n }\n }\n return params;\n }\n\n /**\n * 更改匹配路径\n *\n * @param match RouteMatch\n */\n private void changeMatch(RouteMatch match) {\n //接受路径和匹配路径转为数组\n List<String> requestList = UrlUtils.convertRouteToList(match.getUrl());\n List<String> matchedList = UrlUtils.convertRouteToList(match.getMatchPath());\n\n params = getParams(requestList, matchedList);\n }\n\n\n public void bind(RouteMatch match) {\n this.clearParam();\n this.changeMatch(match);\n }\n\n /**\n * 得到路径参数的Map\n *\n * @return a map containing all route params\n */\n public Map<String, String> pathParams() {\n return Collections.unmodifiableMap(params);\n }\n\n /**\n * 取得路径参数(空返回null)\n * Example: parameter 'name' from the following pattern: (get '/hello/:name')\n *\n * @param param the param\n * @return null if the given param is null or not found\n */\n public String pathParam(String param) {\n if (param.startsWith(\":\")) {\n return params.get(param.toLowerCase()); // NOSONAR\n } else {\n return params.get(\":\" + param.toLowerCase()); // NOSONAR\n }\n }\n\n /**\n * 请求方法\n *\n * @return request method e.g. GET, POST, PUT, ...\n */\n public String requestMethod() {\n return servletRequest.getMethod();\n }\n\n /**\n * @return the scheme\n */\n public String scheme() {\n return servletRequest.getScheme();\n }\n\n /**\n * @return the host\n */\n public String host() {\n return servletRequest.getHeader(\"host\");\n }\n\n /**\n * @return the user-agent\n */\n public String userAgent() {\n return servletRequest.getHeader(USER_AGENT);\n }\n\n /**\n * @return the server port\n */\n public int port() {\n return servletRequest.getServerPort();\n }\n\n /**\n * @return the path info\n * Example return: \"/example/foo\"\n */\n public String pathInfo() {\n return servletRequest.getPathInfo();\n }\n\n /**\n * @return the servlet path\n */\n public String servletPath() {\n return servletRequest.getServletPath();\n }\n\n /**\n * @return the context path\n */\n public String contextPath() {\n return servletRequest.getContextPath();\n }\n\n /**\n * @return the URL string\n */\n public String url() {\n return servletRequest.getRequestURL().toString();\n }\n\n /**\n * @return the content type of the body\n */\n public String contentType() {\n return servletRequest.getContentType();\n }\n\n /**\n * @return the client's IP address\n */\n public String ip() {\n return servletRequest.getRemoteAddr();\n }\n\n /**\n * @return the request body sent by the client\n */\n public String body() {\n if (body == null) {\n body = new String(bodyAsBytes());\n }\n return body;\n }\n\n public byte[] bodyAsBytes() {\n if (bodyAsBytes == null) {\n readBodyAsBytes();\n }\n return bodyAsBytes;\n }\n\n private void readBodyAsBytes() {\n try {\n byte[] buffer = new byte[1024];\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n InputStream inputStream = this.servletRequest.getInputStream();\n while (-1 != inputStream.read(buffer)) {\n byteArrayOutputStream.write(buffer);\n }\n bodyAsBytes = byteArrayOutputStream.toByteArray();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * @return 请求本体length\n */\n public int contentLength() {\n return servletRequest.getContentLength();\n }\n\n /**\n * 请求参数\n *\n * @param queryParam the query parameter\n * @return the value of the provided queryParam\n * Example: query parameter 'id' from the following request URI: /hello?id=foo\n */\n public String queryParam(String queryParam) {\n return servletRequest.getParameter(queryParam);\n }\n\n /**\n * 得到某一相同参数的所有值\n * Example: query parameter 'id' from the following request URI: /hello?id=foo&id=bar\n *\n * @param queryParam the query parameter\n * @return the values of the provided queryParam, null if it doesn't exists\n */\n public String[] queryParams(String queryParam) {\n return servletRequest.getParameterValues(queryParam);\n }\n\n /**\n * 取得header值\n *\n * @param header the header\n * @return the value of the provided header\n */\n public String headers(String header) {\n return servletRequest.getHeader(header);\n }\n\n /**\n * 得到所有http参数键值\n *\n * @return all query parameters\n */\n public Set<String> queryParams() {\n return servletRequest.getParameterMap().keySet();\n }\n\n /**\n * 返回所有header名\n *\n * @return all headers\n */\n public Set<String> headers() {\n if (headers == null) {\n headers = new TreeSet<>();\n Enumeration<String> enumeration = servletRequest.getHeaderNames();\n while (enumeration.hasMoreElements()) {\n headers.add(enumeration.nextElement());\n }\n }\n return headers;\n }\n\n /**\n * @return the query string\n */\n public String queryString() {\n return servletRequest.getQueryString();\n }\n\n /**\n * Sets an attribute on the request (can be fetched in filters/routes later in the chain)\n *\n * @param attribute The attribute\n * @param value The attribute value\n */\n public void attribute(String attribute, Object value) {\n servletRequest.setAttribute(attribute, value);\n }\n\n /**\n * Gets the value of the provided attribute\n *\n * @param attribute The attribute value or null if not present\n * @param <T> the type parameter.\n * @return the value for the provided attribute\n */\n public <T> T attribute(String attribute) {\n return (T) servletRequest.getAttribute(attribute);\n }\n\n /**\n * @return all attributes\n */\n public Set<String> attributes() {\n Set<String> attrList = new HashSet<String>();\n Enumeration<String> attributes = (Enumeration<String>) servletRequest.getAttributeNames();\n while (attributes.hasMoreElements()) {\n attrList.add(attributes.nextElement());\n }\n return attrList;\n }\n\n /**\n * @return the raw HttpServletRequest object handed in by Jetty\n */\n public HttpServletRequest raw() {\n return servletRequest;\n }\n\n\n /**\n * @return the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.\n */\n public String uri() {\n return servletRequest.getRequestURI();\n }\n\n /**\n * @return Returns the name and version of the protocol the request uses\n */\n public String protocol() {\n return servletRequest.getProtocol();\n }\n\n\n public void clearParam() {\n if (this.params != null) {\n this.params.clear();\n }\n }\n\n\n}",
"public class Response {\n private HttpServletResponse response;\n private String body;\n\n //For wrapper\n protected Response() {\n }\n\n public Response(HttpServletResponse response) {\n this.response = response;\n }\n\n /**\n * 设置http状态码\n *\n * @param statusCode 状态码\n */\n public void status(int statusCode) {\n response.setStatus(statusCode);\n }\n\n /**\n * 设置content-typpe\n *\n * @param contentType content-type\n */\n public void type(String contentType) {\n response.setContentType(contentType);\n }\n\n /**\n * 设置响应本体\n *\n * @param body 本体\n */\n public void body(String body) {\n this.body = body;\n }\n\n /**\n * 得到响应内容\n *\n * @return the body\n */\n public String body() {\n return this.body;\n }\n\n /**\n * @return the raw response object handed in by Jetty\n */\n public HttpServletResponse raw() {\n return response;\n }\n\n /**\n * 发送重定向\n *\n * @param location Where to redirect\n */\n public void redirect(String location) {\n try {\n response.sendRedirect(location);\n } catch (IOException ioException) {\n ioException.printStackTrace();\n }\n }\n\n /**\n * 发送重定向(带状态码)\n *\n * @param location Where to redirect permanently\n * @param httpStatusCode the http status code\n */\n public void redirect(String location, int httpStatusCode) {\n response.setStatus(httpStatusCode);\n response.setHeader(\"Location\", location);\n response.setHeader(\"Connection\", \"close\");\n try {\n response.sendError(httpStatusCode);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * 设置header\n *\n * @param header the header\n * @param value the value\n */\n public void header(String header, String value) {\n response.addHeader(header, value);\n }\n\n}",
"public interface ExceptionHandler {\n\n void handle(Exception exception, Request request, Response response);\n\n}",
"public abstract class ExceptionHandlerImpl {\n\n //Exception class will be handle\n protected Class<? extends Exception> exceptionClass;\n\n\n //constructor\n public ExceptionHandlerImpl(Class<? extends Exception> exceptionClass) {\n this.exceptionClass = exceptionClass;\n }\n\n\n public Class<? extends Exception> exceptionClass() {\n return this.exceptionClass;\n }\n\n\n public void exceptionClass(Class<? extends Exception> exceptionClass) {\n this.exceptionClass = exceptionClass;\n }\n\n\n public abstract void handle(Exception exception, Request request, Response response);\n}"
] | import cn.shiroblue.core.ExceptionMapperFactory;
import cn.shiroblue.http.Request;
import cn.shiroblue.http.Response;
import cn.shiroblue.modules.ExceptionHandler;
import cn.shiroblue.modules.ExceptionHandlerImpl; | package cn.shiroblue;
/**
* Description:
* <p>
* ======================
* by WhiteBlue
* on 15/11/6
*/
public class Catch {
private Catch() {
}
public static void exception(Class<? extends Exception> exceptionClass, final ExceptionHandler handler) {
ExceptionHandlerImpl wrapper = new ExceptionHandlerImpl(exceptionClass) {
@Override | public void handle(Exception exception, Request request, Response response) { | 2 |
dominiks/uristmapsj | src/main/java/org/uristmaps/Uristmaps.java | [
"public class BuildFiles {\n\n /**\n * Return the path to the file-state file.\n * Contains a Map<String, FileInfo> object.\n * @return\n */\n public static File getFileStore() {\n return new File(conf.fetch(\"Paths\", \"build\"), \"files.kryo\");\n }\n\n /**\n * Contains a WorldInfo object.\n * @return\n */\n public static File getWorldFile() {\n return new File(conf.fetch(\"Paths\", \"build\"), \"worldinfo.kryo\");\n }\n\n public static File getSitesFile() {\n return new File(conf.fetch(\"Paths\", \"build\"), \"sites.kryo\");\n }\n\n /**\n * The biome data file. Contains a String[][] array that maps x,y to biome name.\n * @return\n */\n public static File getBiomeInfo() {\n File result = new File(conf.fetch(\"Paths\", \"build\"), \"biomes.kryo\");\n return result;\n }\n\n public static File getStructureGroups() {\n return new File(conf.fetch(\"Paths\", \"build\"), \"struct_groups.kryo\");\n }\n\n public static File getStructureGroupsDefinitions() {\n return new File(conf.fetch(\"Paths\", \"build\"), \"group_types.kryo\");\n }\n\n public static File getSiteCenters() {\n return new File(conf.fetch(\"Paths\", \"build\"), \"site_centers.kryo\");\n }\n\n public static File getTilesetImage(int size) {\n return Paths.get(Uristmaps.conf.fetch(\"Paths\", \"tilesets\"),\n Integer.toString(size) + \".png\").toFile();\n }\n\n public static File getTilesetIndex(int size) {\n return Paths.get(Uristmaps.conf.fetch(\"Paths\", \"tilesets\"),\n Integer.toString(size) + \".kryo\").toFile();\n }\n\n /**\n * Index file that stores information about all detailed site maps.\n * @return\n */\n public static File getSitemapsIndex() {\n return new File(conf.fetch(\"Paths\", \"build\"), \"sitemaps.kryo\");\n }\n\n public static File getTilesetColorFile(int tileSize) {\n return Paths.get(Uristmaps.conf.fetch(\"Paths\", \"tilesets\"),\n Integer.toString(tileSize) + \".kryo\").toFile();\n }\n}",
"public class ExportFiles {\n\n /**\n * The timestamp of the world export found in filenames.\n */\n private static String timeStamp;\n\n /**\n * Retrieve the population report file.\n * The site is named \"`region_name`-*-world_sites_and_pops.txt\".\n * Does not check if the file exists!\n * @return A file reference to the file\n */\n public static File getPopulationFile() {\n File result = new File(conf.fetch(\"Paths\", \"export\"),\n String.format(\"%s-%s-world_sites_and_pops.txt\", conf.get(\"Paths\", \"region_name\"),\n getDate()));\n return result;\n }\n\n /**\n * Find the date of the export files. Either this is set in the config or the latest date\n * is resolved using the legends.xml file with the latest date.\n * @return\n */\n public static String getDate() {\n if (timeStamp == null) {\n String config = conf.get(\"Paths\", \"region_date\");\n if (config.equals(\"@LATEST\")) {\n // Find all *-legends.xml files\n File[] populationFiles = new File(conf.fetch(\"Paths\", \"export\")).listFiles(\n (dir, name) -> name.startsWith(conf.get(\"Paths\", \"region_name\"))\n && name.endsWith(\"-legends.xml\"));\n\n // Find the maximum date string within these filenames\n String maxDate = \"00000-00-00\";\n for (File popFile : populationFiles) {\n String fileName = popFile.getName();\n String date = fileName.replace(conf.get(\"Paths\", \"region_name\") + \"-\", \"\").replace(\"-legends.xml\", \"\");\n if (maxDate.compareTo(date) < 0) maxDate = date;\n }\n timeStamp = maxDate;\n Log.info(\"ExportFiles\", \"Resolved date to \" + maxDate);\n } else {\n // Use the config as provided\n timeStamp = config;\n }\n }\n return timeStamp;\n }\n\n /**\n * Resolve the path to the legends xml file.\n * @return File reference to where this file should be.\n */\n public static File getLegendsXML() {\n File result = new File(conf.fetch(\"Paths\", \"export\"),\n String.format(\"%s-%s-legends.xml\", conf.get(\"Paths\", \"region_name\"),\n getDate()));\n return result;\n }\n\n /**\n * Resolve the path to the biome map image.\n * Does not check if the file exists!\n * @return File reference to where this file should be.\n */\n public static File getBiomeMap() {\n File result = new File(conf.fetch(\"Paths\", \"export\"),\n String.format(\"%s-%s-bm.png\", conf.get(\"Paths\", \"region_name\"),\n getDate()));\n return result;\n }\n\n /**\n * Construct the path to the world_history.txt file.\n * Does not check if the file exists!\n * @return\n */\n public static File getWorldHistory() {\n File result = new File(conf.fetch(\"Paths\", \"export\"),\n String.format(\"%s-%s-world_history.txt\", conf.get(\"Paths\", \"region_name\"),\n getDate()));\n return result;\n }\n\n /**\n * Construct the path to the structures map image file.\n * @return File reference to where this file should be.\n */\n public static File getStructuresMap() {\n File result = new File(conf.fetch(\"Paths\", \"export\"),\n String.format(\"%s-%s-str.png\", conf.get(\"Paths\", \"region_name\"),\n getDate()));\n return result;\n }\n\n /**\n * Construct the path to the hydro map image file.\n * @return File reference to where this file should be.\n */\n public static File getHydroMap() {\n File result = new File(conf.fetch(\"Paths\", \"export\"),\n String.format(\"%s-%s-hyd.png\", conf.get(\"Paths\", \"region_name\"),\n getDate()));\n return result;\n }\n\n /**\n * Find all detailed site maps for the current region & date.\n * @return File reference to where this file should be.\n */\n public static File[] getAllSitemaps() {\n return new File(conf.fetch(\"Paths\", \"export\")).listFiles((dir, name) -> name.startsWith(\n String.format(\"%s-%s-site_map-\", conf.get(\"Paths\", \"region_name\"), getDate()))\n && name.endsWith(\".png\")\n );\n }\n\n /**\n * Construct the path to the detailed site map for a given site.\n * Does not check if the file exists!\n * @param id The id of the site.\n * @return\n */\n public static File getSiteMap(int id) {\n File result = new File(conf.fetch(\"Paths\", \"export\"),\n String.format(\"%s-%s-site_map-%d.png\", conf.get(\"Paths\", \"region_name\"),\n getDate(), id));\n return result;\n }\n}",
"public class FileWatcher {\n\n /**\n * The collection of files and their last known state.\n */\n private Map<String, FileInfo> fileMap;\n\n /**\n * Create a new filewatcher. Will automatically try to read the stored info.\n */\n public FileWatcher() {\n // Try to read the file-info file.\n File storeFile = BuildFiles.getFileStore();\n if (storeFile.exists()) {\n try (Input input = new Input(new FileInputStream(storeFile))) {\n fileMap = Uristmaps.kryo.readObject(input, HashMap.class);\n } catch (Exception e) {\n Log.warn(\"FileWatcher\", \"Error when reading file cache: \" + storeFile);\n if (storeFile.exists()) {\n // This might have happened because an update changed the class and it can no longer be read\n // remove the file and re-generate it in the next run.\n storeFile.delete();\n Log.info(\"FileWatcher\", \"The file has been removed. Please try again.\");\n }\n System.exit(1);\n }\n } else {\n fileMap = new HashMap<>();\n }\n }\n\n /**\n * Check if any of the given files is missing or has no/wrong state info stored.\n * @param files\n * @return\n */\n public boolean allOk(File[] files) {\n for (File f : files) {\n if (!fileOk(f)) return false;\n }\n return true;\n }\n\n /**\n * Check if this single file exists and has (correct) info stored.\n * @param f\n * @return\n */\n public boolean fileOk(File f) {\n if (!fileMap.containsKey(f.getAbsolutePath())) return false;\n if (!f.exists()) return false;\n if (f.length() != fileMap.get(f.getAbsolutePath()).getSize()) return false;\n return true;\n }\n\n /**\n * Filter all \"dirty\" files from the provided files.\n * @param files Files that are to be checked.\n * @return All files that are either missing or have no/wrong data stored.\n */\n public File[] getDirty(File[] files) {\n List<File> result = new LinkedList<>();\n for (File f : files) {\n if (!fileOk(f)) result.add(f);\n }\n Log.debug(\"FileWatcher\", \"From \" + files.length + \" provided files, \" + result.size() + \" were dirty.\");\n return result.toArray(new File[]{});\n }\n\n /**\n * Add the current state of the provided files to the store.\n * @param files\n */\n public void updateFiles(File[] files) {\n for (File f : files) {\n fileMap.put(f.getAbsolutePath(), new FileInfo(f));\n }\n Log.debug(\"FileWatcher\", \"Updated \" + files.length + \" files.\");\n saveFile();\n }\n\n public void saveFile() {\n File storeFile = BuildFiles.getFileStore();\n try (Output output = new Output(new FileOutputStream(storeFile))) {\n Uristmaps.kryo.writeObject(output, fileMap);\n } catch (FileNotFoundException e) {\n Log.warn(\"FileWatcher\", \"Error when writing state file: \" + storeFile);\n if (Log.DEBUG) Log.debug(\"FileWatcher\", \"Exception\", e);\n }\n Log.debug(\"FileWatcher\", \"Saved store.\");\n }\n\n /**\n * Update a single file. Saves the data immediately, don't use this for many files.\n * @param f\n */\n public void updateFile(File f) {\n fileMap.put(f.getAbsolutePath(), new FileInfo(f));\n saveFile();\n }\n\n /**\n * Delete the file store file.\n */\n public void forget() {\n if (!BuildFiles.getFileStore().exists()) return;\n Log.debug(\"FileWatcher\", \"Deleting store file.\");\n BuildFiles.getFileStore().delete();\n }\n}",
"public class OutputFiles {\n\n /**\n * Return the path to the sites geoJson file in the output.\n * @return\n */\n public static File getSitesGeojson() {\n return Paths.get(Uristmaps.conf.fetch(\"Paths\", \"output\"), \"js\", \"sitesgeo.json\").toFile();\n }\n\n public static File getUristJs() {\n return Paths.get(Uristmaps.conf.fetch(\"Paths\", \"output\"), \"js\", \"urist.js\").toFile();\n }\n\n public static File getIndexHtml() {\n return Paths.get(Uristmaps.conf.fetch(\"Paths\", \"output\"), \"urist.js\").toFile();\n }\n\n /**\n * Return pathes for all tile files for a given level.\n * @param tiles The folder where the tile images will be placed.\n * @param level The zoom level for the images.\n * @return\n */\n public static File[] getLayerImages(String tiles, int level) {\n int dimension = (int) Math.pow(2, level);\n List<File> result = new LinkedList<>();\n for (int x = 0; x < dimension; x++) {\n for (int y = 0; y < dimension; y++) {\n result.add(Paths.get(Uristmaps.conf.fetch(\"Paths\", \"output\"),\n tiles, Integer.toString(level), Integer.toString(x), y + \".png\").toFile());\n }\n }\n return result.toArray(new File[0]);\n }\n\n public static File getSiteMap(int id) {\n return Paths.get(Uristmaps.conf.fetch(\"Paths\", \"output\"), \"sites\", id + \".png\").toFile();\n }\n\n public static File[] getAllSiteMaps() {\n File[] allSitemaps = ExportFiles.getAllSitemaps();\n File[] outputFiles = new File[allSitemaps.length];\n for (int i = 0; i < allSitemaps.length; i++) {\n String name = allSitemaps[i].getName();\n String idString = name.substring(name.lastIndexOf(\"-\")+1, name.lastIndexOf(\".\"));\n int id = Integer.parseInt(idString);\n outputFiles[i] = getSiteMap(id);\n }\n return outputFiles;\n }\n\n public static File getPopulationJs() {\n return Paths.get(Uristmaps.conf.fetch(\"Paths\", \"output\"), \"js\", \"urist.populations.js\").toFile();\n }\n}",
"public static final String ANSI_RED = \"\\u001B[31m\";",
"public static final String ANSI_RESET = \"\\u001B[0m\";"
] | import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.minlog.Log;
import org.ini4j.Wini;
import org.uristmaps.data.*;
import org.uristmaps.tasks.*;
import org.uristmaps.util.BuildFiles;
import org.uristmaps.util.ExportFiles;
import org.uristmaps.util.FileWatcher;
import org.uristmaps.util.OutputFiles;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import static org.uristmaps.util.Util.ANSI_RED;
import static org.uristmaps.util.Util.ANSI_RESET; | package org.uristmaps;
/**
* Entry point for uristmaps application
*/
public class Uristmaps {
public static final String VERSION = "0.3.3";
/**
* The global configuration object.
*/
public static Wini conf;
/**
* The global kryo object.
*/
public static Kryo kryo;
/**
* The global file watcher object.
*/
public static FileWatcher files;
/**
* Entry point of the application.
*
* Runs all available tasks.
* @param args
*/
public static void main(String[] args) {
// Load configuration file
Log.info("Uristmaps " + VERSION);
loadConfig(args);
initKryo();
initLogger();
initDirectories();
initFileInfo();
// Set logger to debug if flag is set in config
if (conf.get("App", "debug", Boolean.class)) {
Log.DEBUG();
Log.info("Enabled Debug Logging");
}
// Fill the executor with all available tasks.
TaskExecutor executor = new TaskExecutor();
// No file management for this task until subtasks are possible.
executor.addTaskGroup(new TilesetsTaskGroup());
executor.addTask("BmpConvertTask", () -> BmpConverter.convert());
executor.addTask("SitesGeojson",
new File[]{BuildFiles.getSitesFile(),
BuildFiles.getWorldFile(),
BuildFiles.getSitemapsIndex()},
OutputFiles.getSitesGeojson(),
() -> WorldSites.geoJson());
executor.addTask("Sites", | new File[]{ExportFiles.getLegendsXML(), | 1 |
Gdeeer/deerweather | app/src/main/java/com/deerweather/app/activity/ChooseAreaActivity.java | [
"public class City {\n private int id;\n private String cityName;\n private String cityCode;\n private int provinceId;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getCityName() {\n return cityName;\n }\n public void setCityName(String cityName) {\n this.cityName = cityName;\n }\n public String getCityCode() {\n return cityCode;\n }public void setCityCode(String cityCode) {\n this.cityCode = cityCode;\n }\n public int getProvinceId() {\n return provinceId;\n }\n public void setProvinceId(int provinceId) {\n this.provinceId = provinceId;\n }\n}",
"public class County {\n private int id;\n private String countyName;\n private String countyCode;\n private String mLongitude;\n private String mLatitude;\n\n private int cityId;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getCountyName() {\n return countyName;\n }\n public void setCountyName(String countyName) {\n this.countyName = countyName;\n }\n public String getCountyCode() {\n return countyCode;\n }\n public void setCountyCode(String countyCode) {\n this.countyCode = countyCode;\n }\n public int getCityId() {\n return cityId;\n }\n public void setCityId(int cityId) {\n this.cityId = cityId;\n }\n\n public String getLongitude() {\n return mLongitude;\n }\n\n public void setLongitude(String longitude) {\n mLongitude = longitude;\n }\n\n public String getLatitude() {\n return mLatitude;\n }\n\n public void setLatitude(String latitude) {\n mLatitude = latitude;\n }\n}",
"public class DeerWeatherDB {\n\n public static final String DB_NAME = \"deer_weather\";\n\n public static final int VERSION = 2;\n private static DeerWeatherDB deerWeatherDB;\n private SQLiteDatabase db;\n\n\n private DeerWeatherDB(Context context) {\n DeerWeatherOpenHelper dbHelper = new DeerWeatherOpenHelper(context, DB_NAME, null, VERSION);\n db = dbHelper.getWritableDatabase();\n }\n\n public synchronized static DeerWeatherDB getInstance(Context context) {\n if (deerWeatherDB == null) {\n deerWeatherDB = new DeerWeatherDB(context);\n }\n return deerWeatherDB;\n }\n\n public void saveProvince(Province province) {\n if (province != null) {\n ContentValues values = new ContentValues();\n values.put(\"province_name\", province.getProvinceName());\n values.put(\"province_code\", province.getProvinceCode());\n db.insert(\"Province\", null, values);\n }\n }\n\n public List<Province> loadProvinces() {\n List<Province> list = new ArrayList<>();\n Cursor cursor = db.query(\"Province\", null, null, null, null, null, null);\n if (cursor.moveToFirst()) {\n do {\n Province province = new Province();\n province.setId(cursor.getInt(cursor.getColumnIndex(\"id\")));\n province.setProvinceName(cursor.getString(cursor\n .getColumnIndex(\"province_name\")));\n province.setProvinceCode(cursor.getString(cursor.getColumnIndex(\"province_code\")));\n list.add(province);\n } while (cursor.moveToNext());\n }\n return list;\n }\n\n public void saveCity(City city) {\n if (city != null) {\n ContentValues values = new ContentValues();\n values.put(\"city_name\", city.getCityName());\n values.put(\"city_code\", city.getCityCode());\n values.put(\"province_id\", city.getProvinceId());\n db.insert(\"City\", null, values);\n }\n }\n\n\n public List<City> loadCities(int provinceId) {\n List<City> list = new ArrayList<>();\n Cursor cursor = db.query(\"City\", null, \"province_id = ?\",\n new String[]{String.valueOf(provinceId)}, null, null, null);\n if (cursor.moveToFirst()) {\n do {\n City city = new City();\n city.setId(cursor.getInt(cursor.getColumnIndex(\"id\")));\n city.setCityName(cursor.getString(cursor\n .getColumnIndex(\"city_name\")));\n city.setCityCode(cursor.getString(cursor\n .getColumnIndex(\"city_code\")));\n city.setProvinceId(provinceId);\n list.add(city);\n } while (cursor.moveToNext());\n }\n return list;\n }\n\n\n public void saveCounty(County county) {\n if (county != null) {\n ContentValues values = new ContentValues();\n values.put(\"county_name\", county.getCountyName());\n values.put(\"county_code\", county.getCountyCode());\n values.put(\"city_id\", county.getCityId());\n db.insert(\"County\", null, values);\n }\n }\n\n public List<County> loadCounties(int cityId) {\n List<County> list = new ArrayList<>();\n Cursor cursor = db.query(\"County\", null, \"city_id = ?\",\n new String[]{String.valueOf(cityId)}, null, null, null);\n if (cursor.moveToFirst()) {\n do {\n County county = new County();\n county.setId(cursor.getInt(cursor.getColumnIndex(\"id\")));\n county.setCountyName(cursor.getString(cursor\n .getColumnIndex(\"county_name\")));\n county.setCountyCode(cursor.getString(cursor\n .getColumnIndex(\"county_code\")));\n county.setCityId(cityId);\n list.add(county);\n } while (cursor.moveToNext());\n }\n return list;\n }\n\n\n public void saveMyCounty(County mCounty) {\n if (mCounty != null) {\n ContentValues values = new ContentValues();\n values.put(\"county_name\", mCounty.getCountyName());\n values.put(\"county_code\", mCounty.getCountyCode());\n values.put(\"longitude\", mCounty.getLongitude());\n values.put(\"latitude\", mCounty.getLatitude());\n db.insert(\"MyCounty\", null, values);\n }\n }\n\n public boolean searchMyCounty(County mCounty) {\n Cursor cursor = db.query(\"MyCounty\", null, null, null, null, null, null);\n int flag = 0;\n if (cursor.moveToFirst()) {\n do {\n if (mCounty.getCountyName().equals(cursor.getString(cursor.getColumnIndex(\"county_name\"))))\n return false;\n } while (cursor.moveToNext());\n }\n return true;\n }\n\n public List<County> loadMyCounties() {\n List<County> list = new ArrayList<>();\n Cursor cursor = db.query(\"MyCounty\", null, null,\n null, null, null, null);\n if (cursor.moveToFirst()) {\n do {\n County county = new County();\n county.setId(cursor.getInt(cursor.getColumnIndex(\"id\")));\n county.setCountyName(cursor.getString(cursor\n .getColumnIndex(\"county_name\")));\n county.setCountyCode(cursor.getString(cursor\n .getColumnIndex(\"county_code\")));\n county.setLongitude(cursor.getString(cursor\n .getColumnIndex(\"longitude\")));\n county.setLatitude(cursor.getString(cursor\n .getColumnIndex(\"latitude\")));\n list.add(county);\n } while (cursor.moveToNext());\n }\n return list;\n }\n\n public void deleteMyCounties(String mCountyName) {\n db.delete(\"MyCounty\", \"county_name == ?\", new String[]{mCountyName});\n }\n\n// public void updateMyCounties(String mCountyName, String longitude, String latitude) {\n// ContentValues values = new ContentValues();\n// values.put(\"longitude\", longitude);\n// values.put(\"latitude\", latitude);\n// db.update(\"MyCounty\", values, \"county_name = ?\", new String[]{mCountyName});\n// }\n\n public void saveMyTheme(ItemTheme itemTheme) {\n if (itemTheme != null) {\n ContentValues values = new ContentValues();\n values.put(\"color_0\", itemTheme.getColors().get(0));\n values.put(\"color_1\", itemTheme.getColors().get(1));\n values.put(\"color_2\", itemTheme.getColors().get(2));\n values.put(\"color_3\", itemTheme.getColors().get(3));\n values.put(\"color_4\", itemTheme.getColors().get(4));\n values.put(\"color_5\", itemTheme.getColors().get(5));\n values.put(\"color_6\", itemTheme.getColors().get(6));\n\n if (itemTheme.getPictureUrls() != null) {\n values.put(\"picture_url_0\", itemTheme.getPictureUrls().get(0));\n values.put(\"picture_url_1\", itemTheme.getPictureUrls().get(1));\n values.put(\"picture_url_2\", itemTheme.getPictureUrls().get(2));\n values.put(\"picture_url_3\", itemTheme.getPictureUrls().get(3));\n values.put(\"picture_url_4\", itemTheme.getPictureUrls().get(4));\n values.put(\"picture_url_5\", itemTheme.getPictureUrls().get(5));\n values.put(\"picture_url_6\", itemTheme.getPictureUrls().get(6));\n }\n db.insert(\"MyTheme\", null, values);\n }\n }\n\n public List<ItemTheme> loadMyTheme() {\n List<ItemTheme> list = new ArrayList<>();\n Cursor cursor = db.query(\"MyTheme\", null, null, null, null, null, null);\n if (cursor.moveToFirst()) {\n do {\n\n Integer id = cursor.getInt(cursor.getColumnIndex(\"id\"));\n\n Integer color0 = cursor.getInt(cursor.getColumnIndex(\"color_0\"));\n Integer color1 = cursor.getInt(cursor.getColumnIndex(\"color_1\"));\n Integer color2 = cursor.getInt(cursor.getColumnIndex(\"color_2\"));\n Integer color3 = cursor.getInt(cursor.getColumnIndex(\"color_3\"));\n Integer color4 = cursor.getInt(cursor.getColumnIndex(\"color_4\"));\n Integer color5 = cursor.getInt(cursor.getColumnIndex(\"color_5\"));\n Integer color6 = cursor.getInt(cursor.getColumnIndex(\"color_6\"));\n ArrayList<Integer> colors = new ArrayList<>();\n colors.add(color0);\n colors.add(color1);\n colors.add(color2);\n colors.add(color3);\n colors.add(color4);\n colors.add(color5);\n colors.add(color6);\n\n String pictureUrl0 = cursor.getString(cursor.getColumnIndex(\"picture_url_0\"));\n String pictureUrl1 = cursor.getString(cursor.getColumnIndex(\"picture_url_1\"));\n String pictureUrl2 = cursor.getString(cursor.getColumnIndex(\"picture_url_2\"));\n String pictureUrl3 = cursor.getString(cursor.getColumnIndex(\"picture_url_3\"));\n String pictureUrl4 = cursor.getString(cursor.getColumnIndex(\"picture_url_4\"));\n String pictureUrl5 = cursor.getString(cursor.getColumnIndex(\"picture_url_5\"));\n String pictureUrl6 = cursor.getString(cursor.getColumnIndex(\"picture_url_6\"));\n ArrayList<String> pictureUrls = new ArrayList<>();\n pictureUrls.add(pictureUrl0);\n pictureUrls.add(pictureUrl1);\n pictureUrls.add(pictureUrl2);\n pictureUrls.add(pictureUrl3);\n pictureUrls.add(pictureUrl4);\n pictureUrls.add(pictureUrl5);\n pictureUrls.add(pictureUrl6);\n\n ItemTheme itemTheme = new ItemTheme();\n itemTheme.setId(id);\n itemTheme.setColors(colors);\n itemTheme.setPictureUrls(pictureUrls);\n list.add(itemTheme);\n } while (cursor.moveToNext());\n }\n return list;\n }\n\n public void updateMyTheme(ItemTheme itemTheme) {\n ContentValues values = new ContentValues();\n values.put(\"color_0\", itemTheme.getColors().get(0));\n values.put(\"color_1\", itemTheme.getColors().get(1));\n values.put(\"color_2\", itemTheme.getColors().get(2));\n values.put(\"color_3\", itemTheme.getColors().get(3));\n values.put(\"color_4\", itemTheme.getColors().get(4));\n values.put(\"color_5\", itemTheme.getColors().get(5));\n values.put(\"color_6\", itemTheme.getColors().get(6));\n\n if (itemTheme.getPictureUrls() != null) {\n values.put(\"picture_url_0\", itemTheme.getPictureUrls().get(0));\n values.put(\"picture_url_1\", itemTheme.getPictureUrls().get(1));\n values.put(\"picture_url_2\", itemTheme.getPictureUrls().get(2));\n values.put(\"picture_url_3\", itemTheme.getPictureUrls().get(3));\n values.put(\"picture_url_4\", itemTheme.getPictureUrls().get(4));\n values.put(\"picture_url_5\", itemTheme.getPictureUrls().get(5));\n values.put(\"picture_url_6\", itemTheme.getPictureUrls().get(6));\n }\n db.update(\"MyTheme\", values, \"id = ?\", new String[]{String.valueOf(itemTheme.getId())});\n }\n}",
"public class Province {\n private int id;\n private String provinceName;\n private String provinceCode;\n\n public int getId() {\n return id;\n }\n public void setId(int id){\n this.id = id;\n }\n\n public String getProvinceName() {\n return provinceName;\n }\n public void setProvinceName(String provinceName){\n this.provinceName = provinceName;\n }\n public String getProvinceCode() {\n return provinceCode;\n }\n public void setProvinceCode(String provinceCode) {\n this.provinceCode = provinceCode;\n }\n}",
"public interface HttpCallBackListener {\n void onFinish(String response);\n void onError(Exception e);\n}",
"public class HttpUtil {\n public static void sendHttpRequest(final String address, final HttpCallBackListener listener){\n new Thread(new Runnable() {\n @Override\n public void run() {\n HttpURLConnection connection = null;\n try {\n //String address2 = URLEncoder.encode(address, \"UTF-8\");\n URL url = new URL(address);\n connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"GET\");\n //connection.setRequestProperty(\"Accept-Language\", \"zh-CN\");\n //connection.setConnectTimeout(8000);\n //connection.setReadTimeout(8000);\n InputStream in = connection.getInputStream();\n BufferedReader reader = new BufferedReader(new InputStreamReader(in));\n StringBuilder response = new StringBuilder();\n String line;\n while ((line = reader.readLine()) != null) {\n response.append(line);\n }\n if (listener != null){\n listener.onFinish(response.toString());\n }\n } catch (Exception e) {\n if (listener != null) {\n listener.onError(e);\n }\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n }\n }).start();\n }\n}",
"public class JSONUtility {\n\n\n private static final String TAG = \"hourlyres\";\n\n /**\n * 解析和处理文件中返回的省级数据\n */\n public synchronized static boolean handleProvincesResponse(DeerWeatherDB deerWeatherDB, String response) {\n if (!TextUtils.isEmpty(response)) {\n String[] allProvinces = response.split(\",\");\n if (allProvinces.length > 0) {\n for (String p : allProvinces) {\n String[] array = p.split(\"\\\\|\");\n Province province = new Province();\n province.setProvinceCode(array[0]);\n province.setProvinceName(array[1]);\n deerWeatherDB.saveProvince(province);\n }\n return true;\n }\n }\n return false;\n }\n\n public static boolean handleCitiesResponse(DeerWeatherDB deerWeatherDB, String response, int provinceId) {\n if (!TextUtils.isEmpty(response)) {\n String[] allCities = response.split(\",\");\n if (allCities.length > 0) {\n for (String c : allCities) {\n String[] array = c.split(\"\\\\|\");\n City city = new City();\n city.setCityCode(array[0]);\n city.setCityName(array[1]);\n city.setProvinceId(provinceId);\n deerWeatherDB.saveCity(city);\n }\n return true;\n }\n }\n return false;\n }\n\n\n public static boolean handleCountiesResponse(DeerWeatherDB deerWeatherDB,\n String response, int cityId) {\n if (!TextUtils.isEmpty(response)) {\n String[] allCounties = response.split(\",\");\n if (allCounties.length > 0) {\n for (String c : allCounties) {\n String[] array = c.split(\"\\\\|\");\n County county = new County();\n county.setCountyCode(array[0]);\n county.setCountyName(array[1]);\n county.setCityId(cityId);\n deerWeatherDB.saveCounty(county);\n }\n return true;\n }\n }\n return false;\n }\n\n\n public static String handleNameByLocation(Context context, String response) {\n try {\n String subResponse = response.substring(29, response.length() - 1);\n JSONObject jsonObject = new JSONObject(subResponse);\n if (jsonObject.get(\"status\").toString().equals(\"0\")) {\n JSONObject addressComponent = jsonObject.getJSONObject(\"result\").getJSONObject(\"addressComponent\");\n// String address = addressComponent.getString(\"city\");\n// if (address.equals(\"上海市\") || address.equals(\"北京市\") || address.equals(\"天津市\") || address.equals(\"重庆市\"))\n String address = addressComponent.getString(\"district\");\n address = address.substring(0, address.length() - 1);\n return address;\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n /**\n * 解析服务器返回的JSON数据,并将解析出的数据存储到本地。\n */\n public static void handleWeatherResponse(Context context, String response) {\n try {\n JSONObject jsonObject = new JSONObject(response);\n Log.d(TAG, \"handleWeatherResponse: \" + response);\n JSONArray heWeather = jsonObject.getJSONArray(\"HeWeather data service 3.0\");\n JSONObject heWeatherData = heWeather.getJSONObject(0);\n JSONObject basic = heWeatherData.getJSONObject(\"basic\");\n JSONArray dailyForecast = heWeatherData.getJSONArray(\"daily_forecast\");\n\n JSONObject now = heWeatherData.getJSONObject(\"now\");\n\n String nowWeather = now.getJSONObject(\"cond\").getString(\"txt\");\n String nowWeatherCode = now.getJSONObject(\"cond\").getString(\"code\");\n String nowTemp = now.getString(\"tmp\");\n\n JSONObject todayWeather = dailyForecast.getJSONObject(0);\n String maxTempToday = todayWeather.getJSONObject(\"tmp\").getString(\"max\");\n String minTempToday = todayWeather.getJSONObject(\"tmp\").getString(\"min\");\n\n String countyCode = basic.getString(\"id\");\n String countyName = basic.getString(\"city\");\n String longitude = basic.getString(\"lon\");\n String latitude = basic.getString(\"lat\");\n String publishTime = basic.getJSONObject(\"update\").getString(\"loc\").substring(11, 16) + \" 更新\";\n\n String publishTimeHour = basic.getJSONObject(\"update\").getString(\"loc\").substring(11, 13);\n Log.d(TAG, \"handleWeatherResponse: \" + Integer.valueOf(\"01\"));\n if (Integer.valueOf(publishTimeHour) > 18 || Integer.valueOf(publishTimeHour) < 6) {\n if (nowWeatherCode.equals(\"100\") || nowWeatherCode.equals(\"101\")) {\n nowWeatherCode += \"_n\";\n }\n }\n\n saveWeatherInfo(context, countyCode, countyName, longitude, latitude, publishTime,\n nowTemp, nowWeather, nowWeatherCode, maxTempToday, minTempToday);\n\n JSONObject suggestionJSON = heWeatherData.getJSONObject(\"suggestion\");\n String comfBrf = suggestionJSON.getJSONObject(\"comf\").getString(\"brf\");\n String comfTxt = suggestionJSON.getJSONObject(\"comf\").getString(\"txt\");\n String drsgBrf = suggestionJSON.getJSONObject(\"drsg\").getString(\"brf\");\n String drsgTxt = suggestionJSON.getJSONObject(\"drsg\").getString(\"txt\");\n String fluBre = suggestionJSON.getJSONObject(\"flu\").getString(\"brf\");\n String fluTxt = suggestionJSON.getJSONObject(\"flu\").getString(\"txt\");\n String uvBrf = suggestionJSON.getJSONObject(\"uv\").getString(\"brf\");\n String uvTxt = suggestionJSON.getJSONObject(\"uv\").getString(\"txt\");\n String sportBrf = suggestionJSON.getJSONObject(\"sport\").getString(\"brf\");\n String sportTxt = suggestionJSON.getJSONObject(\"sport\").getString(\"txt\");\n String cwBrf = suggestionJSON.getJSONObject(\"cw\").getString(\"brf\");\n String cwTxt = suggestionJSON.getJSONObject(\"cw\").getString(\"txt\");\n\n saveSuggestion(context, comfBrf, comfTxt, drsgBrf, drsgTxt,\n fluBre, fluTxt, uvBrf, uvTxt, sportBrf, sportTxt, cwBrf, cwTxt);\n\n String str = \"--\";\n saveAqi(context, str, str, str, str, str, str, str, str);\n if (heWeatherData.getJSONObject(\"aqi\") != null) {\n JSONObject aqiJSON = heWeatherData.getJSONObject(\"aqi\");\n JSONObject aqiContent = aqiJSON.getJSONObject(\"city\");\n String aqi = aqiContent.getString(\"aqi\");\n String qlty = aqiContent.getString(\"qlty\");\n String pm25 = aqiContent.getString(\"pm25\");\n String pm10 = aqiContent.getString(\"pm10\");\n String no2 = aqiContent.getString(\"no2\");\n String so2 = aqiContent.getString(\"so2\");\n String co = aqiContent.getString(\"co\");\n String o3 = aqiContent.getString(\"o3\");\n saveAqi(context, aqi, qlty, pm25, pm10, no2, so2, co, o3);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n public static void handleWeatherHourly(Context context, String response) {\n try {\n JSONObject jsonObject = new JSONObject(response);\n JSONObject hourly = jsonObject.getJSONObject(\"result\").getJSONObject(\"hourly\");\n JSONObject daily = jsonObject.getJSONObject(\"result\").getJSONObject(\"daily\");\n JSONArray weatherInfoHourlyJSON = hourly.getJSONArray(\"skycon\");\n JSONArray tempHourlyJSON = hourly.getJSONArray(\"temperature\");\n JSONArray aqiHourlyJSON = hourly.getJSONArray(\"aqi\");\n JSONArray pm25HourlyJSON = hourly.getJSONArray(\"pm25\");\n JSONArray aqiWeeklyJSON = daily.getJSONArray(\"aqi\");\n String description = hourly.getString(\"description\");\n saveDescription(context, description);\n\n for (int i = 0; i < 24; i++) {\n String timeHourly = weatherInfoHourlyJSON.getJSONObject(i).getString(\"datetime\").substring(11, 16);\n String weatherCodeHourlyRaw = weatherInfoHourlyJSON.getJSONObject(i).getString(\"value\");\n String weatherCodeHourly = ViewUtil.getHourlyWeatherCode(weatherCodeHourlyRaw);\n String tempHourlyRaw = tempHourlyJSON.getJSONObject(i).getString(\"value\");\n String tempHourly = tempHourlyRaw.substring(0, tempHourlyRaw.indexOf('.')) + \"°\";\n String aqiHourlyRaw = aqiHourlyJSON.getJSONObject(i).getString(\"value\");\n String aqiHourly = aqiHourlyRaw.substring(0, aqiHourlyRaw.indexOf('.'));\n String pm25Hourly = pm25HourlyJSON.getJSONObject(i).getString(\"value\");\n saveWeatherInfoHourly(context, timeHourly, tempHourly, weatherCodeHourly, aqiHourly, pm25Hourly, i);\n }\n\n for (int i = 0; i < 5; i++) {\n String aqiWeeklyRaw = aqiWeeklyJSON.getJSONObject(i).getString(\"avg\");\n String aqiWeekly = aqiWeeklyRaw.substring(0, aqiWeeklyRaw.indexOf('.'));\n saveAqiWeekly(context, aqiWeekly, i);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n public static void handleWeatherWeekly(Context context, String response) {\n try {\n JSONObject jsonObject = new JSONObject(response);\n JSONArray heWeather = jsonObject.getJSONArray(\"HeWeather data service 3.0\");\n JSONObject heWeatherData = heWeather.getJSONObject(0);\n JSONArray dailyForecast = heWeatherData.getJSONArray(\"daily_forecast\");\n int i;\n for (i = 0; i < 7; i++) {\n JSONObject weatherFutureInfo = dailyForecast.getJSONObject(i);\n String minTempWeekly = weatherFutureInfo.getJSONObject(\"tmp\").getString(\"min\") + \"°\";\n String maxTempWeekly = weatherFutureInfo.getJSONObject(\"tmp\").getString(\"max\") + \"°\";\n String weatherWeekly = weatherFutureInfo.getJSONObject(\"cond\").getString(\"txt_d\");\n String weatherCodeFuture = weatherFutureInfo.getJSONObject(\"cond\").getString(\"code_d\");\n String dayFuture = weatherFutureInfo.getString(\"date\").substring(5, 7) + \"/\"\n + weatherFutureInfo.getString(\"date\").substring(8, 10);\n saveWeatherInfoWeekly(context, minTempWeekly, maxTempWeekly,\n weatherWeekly, weatherCodeFuture, dayFuture, i);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * 将服务器返回的所有天气信息存储到SharedPreferences文件中。\n */\n public static void saveWeatherInfo(Context context, String countyCode, String countyName,\n String longitude, String latitude, String publishTime,\n String nowTemp, String nowWeather, String nowWeatherCode, String maxTemp, String minTemp) {\n\n SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n editor.putBoolean(\"county_selected\", true);\n editor.putString(\"county_code\", countyCode);\n editor.putString(\"county_name\", countyName);\n editor.putString(\"longitude\", longitude);\n editor.putString(\"latitude\", latitude);\n editor.putString(\"publish_time\", publishTime);\n editor.putString(\"temp_now\", nowTemp);\n editor.putString(\"weather_now\", nowWeather);\n editor.putString(\"weather_code_now\", nowWeatherCode);\n editor.putString(\"max_temp_today\", maxTemp);\n editor.putString(\"min_temp_today\", minTemp);\n\n editor.apply();\n }\n\n\n public static void saveWeatherInfoHourly(Context context, String timeHourly, String tempHourly,\n String weatherCodeHourly, String aqiHourly, String pm25Hourly,\n int i) {\n SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n editor.putBoolean(\"county_selected\", true);\n editor.putString(\"time_hourly\" + i, timeHourly);\n editor.putString(\"weather_code_hourly\" + i, weatherCodeHourly);\n editor.putString(\"temp_hourly\" + i, tempHourly);\n editor.putString(\"aqi_hourly\" + i, aqiHourly);\n editor.putString(\"pm25_hourly\" + i, pm25Hourly);\n editor.apply();\n }\n\n public static void saveWeatherInfoWeekly(Context context, String minTempWeekly, String maxTempWeekly,\n String weatherWeekly, String weatherCodeWeekly, String dayWeekly, int i) {\n SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n editor.putBoolean(\"county_selected\", true);\n editor.putString(\"min_temp_weekly\" + i, minTempWeekly);\n editor.putString(\"max_temp_weekly\" + i, maxTempWeekly);\n editor.putString(\"weather_code_weekly\" + i, weatherCodeWeekly);\n editor.putString(\"weather_weekly\" + i, weatherWeekly);\n editor.putString(\"day_weekly\" + i, dayWeekly);\n editor.apply();\n }\n\n public static void saveDescription(Context context, String description) {\n SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n editor.putString(\"description\", description);\n editor.apply();\n }\n\n public static void saveAqiWeekly(Context context, String aqiWeekly, int i) {\n SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n editor.putBoolean(\"county_selected\", true);\n editor.putString(\"aqi_weekly\" + i, aqiWeekly);\n editor.apply();\n }\n\n public static void saveAqi(Context context, String aqi, String qlty, String pm25,\n String pm10, String no2, String so2, String co, String o3) {\n SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n editor.putBoolean(\"county_selected\", true);\n editor.putString(\"aqi_he\", aqi);\n editor.putString(\"qlty\", qlty);\n editor.putString(\"pm25\", pm25);\n editor.putString(\"pm10\", pm10);\n editor.putString(\"no2\", no2);\n editor.putString(\"so2\", so2);\n editor.putString(\"co\", co);\n editor.putString(\"o3\", o3);\n editor.apply();\n }\n\n\n public static void saveSuggestion(Context context, String comfB, String comfT, String drsgB, String drsgT,\n String fluB, String fluT, String uvB, String uvT,\n String sportB, String sprotT, String cwB, String cwT) {\n SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n editor.putBoolean(\"county_selected\", true);\n editor.putString(\"comf_b\", comfB);\n editor.putString(\"comf_t\", comfT);\n editor.putString(\"drsg_b\", drsgB);\n editor.putString(\"drsg_t\", drsgT);\n editor.putString(\"flu_b\", fluB);\n editor.putString(\"flu_t\", fluT);\n editor.putString(\"uv_b\", uvB);\n editor.putString(\"uv_t\", uvT);\n editor.putString(\"sport_b\", sportB);\n editor.putString(\"sport_t\", sprotT);\n editor.putString(\"cw_b\", cwB);\n editor.putString(\"cw_t\", cwT);\n editor.apply();\n }\n}",
"@SuppressLint(\"NewApi\")\npublic class ColorView extends View {\n private ObjectAnimator ainm1;\n private float progress;\n private int mClickX;\n private int mClickY;\n private int x1;\n private int y1;\n private int director;\n private int mColor;\n private int mColorPre;\n private Paint mPaint;\n private int mDuration = 200;\n private boolean mLongClicked = false;\n\n private String mPictureUrl;\n\n public ColorView(Context context) {\n super(context);\n }\n\n //实现在布局文件中使用\n public ColorView(Context context, AttributeSet attrs) {\n super(context, attrs);\n mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n }\n\n public void setDuration(int duration) {\n this.mDuration = duration;\n }\n\n public void setLongClicked(boolean longClicked) {\n this.mLongClicked = longClicked;\n }\n\n public boolean isLongClicked() {\n return mLongClicked;\n }\n\n public int getColorPre() {\n return mColorPre;\n }\n\n public void setColorPre(int colorPre) {\n mColorPre = colorPre;\n }\n\n public int getClickY() {\n return mClickY;\n }\n\n public void setClickY(int clickY) {\n mClickY = clickY;\n }\n\n public int getClickX() {\n return mClickX;\n }\n\n public void setClickX(int clickX) {\n mClickX = clickX;\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n mPaint.setColor(mColor);\n\n if (mClickY < getHeight() / 2 && mClickX > getWidth() / 2) {\n y1 = getHeight() - mClickY;\n director = (int) Math.sqrt(mClickX * mClickX + y1 * y1);\n }\n if (mClickX < getWidth() / 2 && mClickY > getHeight() / 2) {\n x1 = getWidth() - mClickX;\n director = (int) Math.sqrt(x1 * x1 + mClickY * mClickY);\n }\n if (mClickX < getWidth() / 2 && mClickY < getHeight() / 2) {\n y1 = getHeight() - mClickY;\n x1 = getWidth() - mClickX;\n director = (int) Math.sqrt(x1 * x1 + y1 * y1);\n }\n if (mClickX > getWidth() / 2 && mClickY > getHeight() / 2) {\n director = (int) Math.sqrt(mClickX * mClickX + mClickY * mClickY);\n }\n float r = progress * director;\n //画圆\n\n canvas.drawCircle(mClickX, mClickY, r, mPaint);\n }\n\n public void setProgress(float progress) {\n this.progress = progress;\n postInvalidate();\n }\n\n public void setColor(int color) {\n this.mColor = color;\n }\n\n public void start(int width, int height) {\n mClickX = width;\n mClickY = height;\n //属性动画\n ainm1 = ObjectAnimator.ofFloat(this, \"progress\", 0, 1).setDuration(mDuration);\n ainm1.start();\n }\n}"
] | import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.deerweather.app.R;
import com.deerweather.app.model.City;
import com.deerweather.app.model.County;
import com.deerweather.app.model.DeerWeatherDB;
import com.deerweather.app.model.Province;
import com.deerweather.app.util.HttpCallBackListener;
import com.deerweather.app.util.HttpUtil;
import com.deerweather.app.util.JSONUtility;
import com.deerweather.app.view.ColorView;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
mCvToolbar = (ColorView) findViewById(R.id.cv_toolbar_choose);
setWallpaper();
mToolbar = (Toolbar) findViewById(R.id.toolbar_choose);
mToolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(mToolbar);
listView = (ListView) findViewById(R.id.lv_choose);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
deerWeatherDB = DeerWeatherDB.getInstance(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(position);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {
String countyCode = countyList.get(position).getCountyCode();
Intent intent = new Intent();
intent.putExtra("county_code_part", countyCode);
setResult(RESULT_OK, intent);
finish();
}
}
});
queryProvinces();
}
public void setWallpaper() {
String picturePath = getIntent().getStringExtra("picture");
int color = getIntent().getIntExtra("color", 0);
if (picturePath != null && !picturePath.equals("")) {
Uri pictureUri = Uri.parse(picturePath);
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(pictureUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Drawable drawable = Drawable.createFromStream(inputStream, pictureUri.toString());
// mLlToolbar.setBackground(drawable);
mCvToolbar.setBackground(drawable);
} else {
// mLlToolbar.setBackgroundColor(color);
mCvToolbar.setBackgroundColor(color);
}
}
private void queryProvinces() {
provinceList = deerWeatherDB.loadProvinces();
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("中国");
}
currentLevel = LEVEL_PROVINCE;
} else {
queryFromServerCity(null, "province");
}
}
private void queryCities() {
cityList = deerWeatherDB.loadCities(selectedProvince.getId());
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(selectedProvince.getProvinceName());
}
currentLevel = LEVEL_CITY;
} else {
queryFromServerCity(selectedProvince.getProvinceCode(), "city");
}
}
private void queryCounties() {
countyList = deerWeatherDB.loadCounties(selectedCity.getId());
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(selectedCity.getCityName());
}
currentLevel = LEVEL_COUNTY;
} else {
queryFromServerCity(selectedCity.getCityCode(), "county");
}
}
private void queryFromServerCity(final String code, final String type) {
String address;
if (!TextUtils.isEmpty(code)) {
address = "http://www.weather.com.cn/data/list3/city" + code + ".xml";
} else {
address = "http://www.weather.com.cn/data/list3/city.xml";
}
showProgressDialog(); | HttpUtil.sendHttpRequest(address, new HttpCallBackListener() { | 4 |
dropwizard/dropwizard-java8 | dropwizard-java8-example/src/main/java/com/example/helloworld/HelloWorldApplication.java | [
"public class ExampleAuthenticator implements Authenticator<BasicCredentials, User> {\n @Override\n public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {\n if (\"secret\".equals(credentials.getPassword())) {\n return Optional.of(new User(credentials.getUsername()));\n }\n return Optional.empty();\n }\n}",
"public class ExampleAuthorizer implements Authorizer<User> {\n @Override\n public boolean authorize(User user, String role) {\n if (role.equals(\"ADMIN\") && !user.getName().startsWith(\"chief\")) {\n return false;\n }\n return true;\n }\n}",
"public class RenderCommand extends ConfiguredCommand<HelloWorldConfiguration> {\n private static final Logger LOGGER = LoggerFactory.getLogger(RenderCommand.class);\n\n public RenderCommand() {\n super(\"render\", \"Render the template data to console\");\n }\n\n @Override\n public void configure(Subparser subparser) {\n super.configure(subparser);\n subparser.addArgument(\"-i\", \"--include-default\")\n .action(Arguments.storeTrue())\n .dest(\"include-default\")\n .help(\"Also render the template with the default name\");\n subparser.addArgument(\"names\").nargs(\"*\");\n }\n\n @Override\n protected void run(Bootstrap<HelloWorldConfiguration> bootstrap,\n Namespace namespace,\n HelloWorldConfiguration configuration) throws Exception {\n final Template template = configuration.buildTemplate();\n\n if (namespace.getBoolean(\"include-default\")) {\n LOGGER.info(\"DEFAULT => {}\", template.render(Optional.<String>empty()));\n }\n\n for (String name : namespace.<String>getList(\"names\")) {\n for (int i = 0; i < 1000; i++) {\n LOGGER.info(\"{} => {}\", name, template.render(Optional.of(name)));\n Thread.sleep(1000);\n }\n }\n }\n}",
"public class TemplateHealthCheck extends HealthCheck {\n private final Template template;\n\n public TemplateHealthCheck(Template template) {\n this.template = template;\n }\n\n @Override\n protected Result check() throws Exception {\n template.render(Optional.of(\"woo\"));\n template.render(Optional.<String>empty());\n return Result.healthy();\n }\n}",
"@Path(\"/people/{personId}\")\n@Produces(MediaType.APPLICATION_JSON)\npublic class PersonResource {\n\n private final PersonDAO peopleDAO;\n\n public PersonResource(PersonDAO peopleDAO) {\n this.peopleDAO = peopleDAO;\n }\n\n @GET\n @UnitOfWork\n public Person getPerson(@PathParam(\"personId\") LongParam personId) {\n return findSafely(personId.get());\n }\n\n @GET\n @Path(\"/view_freemarker\")\n @UnitOfWork\n @Produces(MediaType.TEXT_HTML)\n public PersonView getPersonViewFreemarker(@PathParam(\"personId\") LongParam personId) {\n return new PersonView(PersonView.Template.FREEMARKER, findSafely(personId.get()));\n }\n\n @GET\n @Path(\"/view_mustache\")\n @UnitOfWork\n @Produces(MediaType.TEXT_HTML)\n public PersonView getPersonViewMustache(@PathParam(\"personId\") LongParam personId) {\n return new PersonView(PersonView.Template.MUSTACHE, findSafely(personId.get()));\n }\n\n private Person findSafely(long personId) {\n final Optional<Person> person = peopleDAO.findById(personId);\n if (!person.isPresent()) {\n throw new NotFoundException(\"No such user.\");\n }\n return person.get();\n }\n}",
"public class Java8Bundle implements Bundle {\n @Override\n public void initialize(final Bootstrap<?> bootstrap) {\n bootstrap.getObjectMapper().registerModules(new Jdk8Module());\n bootstrap.getObjectMapper().registerModules(new JavaTimeModule());\n\n final ValidatorFactory validatorFactory = Validators.newConfiguration()\n .addValidatedValueHandler(new OptionalValidatedValueUnwrapper())\n .buildValidatorFactory();\n bootstrap.setValidatorFactory(validatorFactory);\n }\n\n @Override\n public void run(final Environment environment) {\n environment.jersey().register(OptionalMessageBodyWriter.class);\n environment.jersey().register(OptionalParamFeature.class);\n }\n}",
"public class AuthDynamicFeature implements DynamicFeature {\n\n private final ContainerRequestFilter authFilter;\n\n public AuthDynamicFeature(ContainerRequestFilter authFilter) {\n this.authFilter = authFilter;\n }\n\n @Override\n public void configure(ResourceInfo resourceInfo, FeatureContext context) {\n final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());\n final Annotation[][] parameterAnnotations = am.getParameterAnnotations();\n if (am.isAnnotationPresent(RolesAllowed.class) || am.isAnnotationPresent(DenyAll.class) ||\n am.isAnnotationPresent(PermitAll.class)) {\n context.register(authFilter);\n } else {\n for (Annotation[] annotations : parameterAnnotations) {\n for (Annotation annotation : annotations) {\n if (annotation instanceof Auth) {\n context.register(authFilter);\n return;\n }\n }\n }\n }\n }\n}",
"@Priority(Priorities.AUTHENTICATION)\npublic class BasicCredentialAuthFilter<P extends Principal> extends AuthFilter<BasicCredentials, P> {\n private static final Logger LOGGER = LoggerFactory.getLogger(BasicCredentialAuthFilter.class);\n\n private BasicCredentialAuthFilter() {\n }\n\n @Override\n public void filter(final ContainerRequestContext requestContext) throws IOException {\n final String header = requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);\n try {\n if (header != null) {\n final int space = header.indexOf(' ');\n if (space > 0) {\n final String method = header.substring(0, space);\n if (prefix.equalsIgnoreCase(method)) {\n final String decoded = new String(\n BaseEncoding.base64().decode(header.substring(space + 1)),\n StandardCharsets.UTF_8);\n final int i = decoded.indexOf(':');\n if (i > 0) {\n final String username = decoded.substring(0, i);\n final String password = decoded.substring(i + 1);\n final BasicCredentials credentials = new BasicCredentials(username, password);\n try {\n final Optional<P> principal = authenticator.authenticate(credentials);\n if (principal.isPresent()) {\n requestContext.setSecurityContext(new SecurityContext() {\n @Override\n public Principal getUserPrincipal() {\n return principal.get();\n }\n\n @Override\n public boolean isUserInRole(String role) {\n return authorizer.authorize(principal.get(), role);\n }\n\n @Override\n public boolean isSecure() {\n return requestContext.getSecurityContext().isSecure();\n }\n\n @Override\n public String getAuthenticationScheme() {\n return SecurityContext.BASIC_AUTH;\n }\n });\n return;\n }\n } catch (AuthenticationException e) {\n LOGGER.warn(\"Error authenticating credentials\", e);\n throw new InternalServerErrorException();\n }\n }\n }\n }\n }\n } catch (IllegalArgumentException e) {\n LOGGER.warn(\"Error decoding credentials\", e);\n }\n\n throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm));\n }\n\n\n /**\n * Builder for {@link BasicCredentialAuthFilter}.\n * <p>An {@link io.dropwizard.java8.auth.Authenticator} must be provided during the building process.</p>\n *\n * @param <P> the principal\n */\n public static class Builder<P extends Principal> extends\n AuthFilterBuilder<BasicCredentials, P, BasicCredentialAuthFilter<P>> {\n\n @Override\n protected BasicCredentialAuthFilter<P> newInstance() {\n return new BasicCredentialAuthFilter<>();\n }\n }\n}"
] | import com.example.helloworld.auth.ExampleAuthenticator;
import com.example.helloworld.auth.ExampleAuthorizer;
import com.example.helloworld.cli.RenderCommand;
import com.example.helloworld.core.Person;
import com.example.helloworld.core.Template;
import com.example.helloworld.core.User;
import com.example.helloworld.db.PersonDAO;
import com.example.helloworld.filter.DateRequiredFeature;
import com.example.helloworld.health.TemplateHealthCheck;
import com.example.helloworld.resources.FilteredResource;
import com.example.helloworld.resources.HelloWorldResource;
import com.example.helloworld.resources.PeopleResource;
import com.example.helloworld.resources.PersonResource;
import com.example.helloworld.resources.ProtectedResource;
import com.example.helloworld.resources.ViewResource;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.configuration.EnvironmentVariableSubstitutor;
import io.dropwizard.configuration.SubstitutingSourceProvider;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.hibernate.HibernateBundle;
import io.dropwizard.java8.Java8Bundle;
import io.dropwizard.java8.auth.AuthDynamicFeature;
import io.dropwizard.java8.auth.basic.BasicCredentialAuthFilter;
import io.dropwizard.migrations.MigrationsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.dropwizard.views.ViewBundle;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import java.util.Map; | package com.example.helloworld;
public class HelloWorldApplication extends Application<HelloWorldConfiguration> {
public static void main(String[] args) throws Exception {
new HelloWorldApplication().run(args);
}
private final HibernateBundle<HelloWorldConfiguration> hibernateBundle =
new HibernateBundle<HelloWorldConfiguration>(Person.class) {
@Override
public DataSourceFactory getDataSourceFactory(HelloWorldConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};
@Override
public String getName() {
return "hello-world";
}
@Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {
// Enable variable substitution with environment variables
bootstrap.setConfigurationSourceProvider(
new SubstitutingSourceProvider(
bootstrap.getConfigurationSourceProvider(),
new EnvironmentVariableSubstitutor(false)
)
);
bootstrap.addCommand(new RenderCommand());
bootstrap.addBundle(new Java8Bundle());
bootstrap.addBundle(new AssetsBundle());
bootstrap.addBundle(new MigrationsBundle<HelloWorldConfiguration>() {
@Override
public DataSourceFactory getDataSourceFactory(HelloWorldConfiguration configuration) {
return configuration.getDataSourceFactory();
}
});
bootstrap.addBundle(hibernateBundle);
bootstrap.addBundle(new ViewBundle<HelloWorldConfiguration>() {
@Override
public Map<String, Map<String, String>> getViewConfiguration(HelloWorldConfiguration configuration) {
return configuration.getViewRendererConfiguration();
}
});
}
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) {
final PersonDAO dao = new PersonDAO(hibernateBundle.getSessionFactory());
final Template template = configuration.buildTemplate();
environment.healthChecks().register("template", new TemplateHealthCheck(template));
environment.jersey().register(DateRequiredFeature.class);
environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>()
.setAuthenticator(new ExampleAuthenticator())
.setAuthorizer(new ExampleAuthorizer())
.setRealm("SUPER SECRET STUFF")
.buildAuthFilter()));
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
environment.jersey().register(RolesAllowedDynamicFeature.class);
environment.jersey().register(new HelloWorldResource(template));
environment.jersey().register(new ViewResource());
environment.jersey().register(new ProtectedResource());
environment.jersey().register(new PeopleResource(dao)); | environment.jersey().register(new PersonResource(dao)); | 4 |
6ag/BaoKanAndroid | app/src/main/java/tv/baokan/baokanandroid/ui/activity/ModifySafeInfoActivity.java | [
"public class UserBean {\n\n private static final String TAG = \"UserBean\";\n\n // 用户id\n private String userid;\n\n // token\n private String token;\n\n // 用户名\n private String username;\n\n // 昵称\n private String nickname;\n\n // email\n private String email;\n\n // 用户组\n private String groupName;\n\n // 注册时间\n private String registerTime;\n\n // 头像\n private String avatarUrl;\n\n // qq\n private String qq;\n\n // 电话号码\n private String phone;\n\n // 个性签名\n private String saytext;\n\n // 积分\n private String points;\n\n // 防止外界构建默认对象\n private UserBean() {\n }\n\n public UserBean(JSONObject jsonObject) {\n try {\n userid = jsonObject.getString(\"id\");\n token = jsonObject.getString(\"token\");\n username = jsonObject.getString(\"username\");\n nickname = jsonObject.getString(\"nickname\");\n email = jsonObject.getString(\"email\");\n groupName = jsonObject.getString(\"groupName\");\n registerTime = jsonObject.getString(\"registerTime\");\n avatarUrl = jsonObject.getString(\"avatarUrl\");\n qq = jsonObject.getString(\"qq\");\n phone = jsonObject.getString(\"phone\");\n saytext = jsonObject.getString(\"saytext\");\n points = jsonObject.getString(\"points\");\n } catch (JSONException e) {\n e.printStackTrace();\n LogUtils.d(TAG, \"数据解析异常\");\n }\n }\n\n public String getUserid() {\n return userid;\n }\n\n public void setUserid(String userid) {\n this.userid = userid;\n }\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getNickname() {\n return nickname;\n }\n\n public void setNickname(String nickname) {\n this.nickname = nickname;\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 getGroupName() {\n return groupName;\n }\n\n public void setGroupName(String groupName) {\n this.groupName = groupName;\n }\n\n public String getRegisterTime() {\n return registerTime;\n }\n\n public void setRegisterTime(String registerTime) {\n this.registerTime = registerTime;\n }\n\n public String getAvatarUrl() {\n return avatarUrl;\n }\n\n public void setAvatarUrl(String avatarUrl) {\n this.avatarUrl = avatarUrl;\n }\n\n public String getQq() {\n return qq;\n }\n\n public void setQq(String qq) {\n this.qq = qq;\n }\n\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n public String getSaytext() {\n return saytext;\n }\n\n public void setSaytext(String saytext) {\n this.saytext = saytext;\n }\n\n public String getPoints() {\n return points;\n }\n\n public void setPoints(String points) {\n this.points = points;\n }\n\n public static UserBean getUserAccount() {\n return userAccount;\n }\n\n public static void setUserAccount(UserBean userAccount) {\n UserBean.userAccount = userAccount;\n }\n\n // 防止重复去操作sp 把对象缓存到内存中\n private static UserBean userAccount = null;\n\n /**\n * 获取缓存的对象\n *\n * @return 用户信息模型\n */\n public static UserBean shared() {\n if (userAccount == null) {\n userAccount = new UserBean();\n userAccount.decode();\n }\n return userAccount;\n }\n\n /**\n * 是否已经登录\n *\n * @return true登录\n */\n public static boolean isLogin() {\n return !TextUtils.isEmpty(shared().token);\n }\n\n /**\n * 退出登录\n */\n public void logout() {\n UserBean.userAccount = null;\n SharedPreferences sp = BaoKanApp.getContext().getSharedPreferences(\"userInfo\", Context.MODE_PRIVATE);\n sp.edit().clear().apply();\n }\n\n /**\n * 从本地更新用户信息 - 登录成功后保存到偏好设置\n */\n public void updateUserInfoFromLocal() {\n\n // 移除第三方授权\n Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);\n if (weibo.isAuthValid()) {\n weibo.removeAccount(true);\n }\n Platform qq = ShareSDK.getPlatform(QQ.NAME);\n if (qq.isAuthValid()) {\n qq.removeAccount(true);\n }\n\n // 内存缓存\n UserBean.userAccount = this;\n // 磁盘缓存\n encode();\n }\n\n // 更新用户信息状态监听\n public static class OnUpdatedUserInfoListener {\n public void onError(String tipString) {\n }\n\n public void onSuccess(UserBean userBean) {\n }\n }\n\n /**\n * 从网络更新用户信息\n */\n public static void updateUserInfoFromNetwork(final OnUpdatedUserInfoListener userInfoListener) {\n if (isLogin()) {\n HashMap<String, String> parameters = new HashMap<>();\n parameters.put(\"username\", shared().username);\n parameters.put(\"userid\", shared().userid);\n parameters.put(\"token\", shared().token);\n NetworkUtils.shared.get(APIs.GET_USERINFO, parameters, new NetworkUtils.StringCallback() {\n @Override\n public void onError(Call call, Exception e, int id) {\n userInfoListener.onError(\"您的网络不给力哦\");\n }\n\n @Override\n public void onResponse(String response, int id) {\n try {\n JSONObject jsonObject = new JSONObject(response);\n if (jsonObject.getString(\"err_msg\").equals(\"success\")) {\n UserBean userBean = new UserBean(jsonObject.getJSONObject(\"data\"));\n // 将登录信息保存到数据库\n userBean.updateUserInfoFromLocal();\n userInfoListener.onSuccess(userBean);\n } else {\n String info = jsonObject.getString(\"info\");\n LogUtils.d(TAG, \"更新用户信息失败\" + info);\n UserBean.shared().logout();\n userInfoListener.onError(info);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n userInfoListener.onError(\"数据解析异常\");\n }\n }\n });\n } else {\n userInfoListener.onError(\"未登录\");\n }\n }\n\n /**\n * 编码\n */\n private void encode() {\n LogUtils.d(TAG, this.toString());\n SharedPreferences sp = BaoKanApp.getContext().getSharedPreferences(\"userInfo\", Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = sp.edit();\n editor.putString(\"userid\", userid);\n editor.putString(\"token\", token);\n editor.putString(\"username\", username);\n editor.putString(\"nickname\", nickname);\n editor.putString(\"email\", email);\n editor.putString(\"groupName\", groupName);\n editor.putString(\"registerTime\", registerTime);\n editor.putString(\"avatarUrl\", avatarUrl);\n editor.putString(\"qq\", qq);\n editor.putString(\"phone\", phone);\n editor.putString(\"saytext\", saytext);\n editor.putString(\"points\", points);\n editor.apply();\n }\n\n /**\n * 解码\n */\n private void decode() {\n SharedPreferences sp = BaoKanApp.getContext().getSharedPreferences(\"userInfo\", Context.MODE_PRIVATE);\n userid = sp.getString(\"userid\", \"0\");\n token = sp.getString(\"token\", \"\");\n username = sp.getString(\"username\", \"\");\n nickname = sp.getString(\"nickname\", \"\");\n email = sp.getString(\"email\", \"\");\n groupName = sp.getString(\"groupName\", \"\");\n registerTime = sp.getString(\"registerTime\", \"\");\n avatarUrl = sp.getString(\"avatarUrl\", \"\");\n qq = sp.getString(\"qq\", \"\");\n phone = sp.getString(\"phone\", \"\");\n saytext = sp.getString(\"saytext\", \"\");\n points = sp.getString(\"points\", \"\");\n }\n\n @Override\n public String toString() {\n return \"UserBean{\" +\n \"userid='\" + userid + '\\'' +\n \", token='\" + token + '\\'' +\n \", username='\" + username + '\\'' +\n \", nickname='\" + nickname + '\\'' +\n \", email='\" + email + '\\'' +\n \", groupName='\" + groupName + '\\'' +\n \", registerTime='\" + registerTime + '\\'' +\n \", avatarUrl='\" + avatarUrl + '\\'' +\n \", qq='\" + qq + '\\'' +\n \", phone='\" + phone + '\\'' +\n \", saytext='\" + saytext + '\\'' +\n \", points='\" + points + '\\'' +\n '}';\n }\n}",
"public class APIs {\n\n // 基础url\n public static final String BASE_URL = \"http://www.baokan.tv/\";\n\n // 基础url\n public static final String API_URL = BASE_URL + \"e/bpi/\";\n\n // 版本更新\n public static final String UPDATE = API_URL + \"update.php\";\n\n // 分类\n public static final String GET_CLASS = API_URL + \"getNewsClass.php\";\n\n // 文章列表\n public static final String ARTICLE_LIST = API_URL + \"getNewsList.php\";\n\n // 文章详情\n public static final String ARTICLE_DETAIL = API_URL + \"getNewsContent.php\";\n\n // 获取评论信息\n public static final String GET_COMMENT = API_URL + \"getNewsComment.php\";\n\n // 提交评论\n public static final String SUBMIT_COMMENT = API_URL + \"subPlPost.php\";\n\n // 顶贴踩贴\n public static final String TOP_DOWN = API_URL + \"DoForPl.php\";\n\n // 注册\n public static final String REGISTER = API_URL + \"Register.php\";\n\n // 登录\n public static final String LOGIN = API_URL + \"loginReq.php\";\n\n // 获取用户信息\n public static final String GET_USERINFO = API_URL + \"checkLoginStamp.php\";\n\n // 获取用户收藏夹\n public static final String GET_USER_FAVA = API_URL + \"getUserFava.php\";\n\n // 删除好友、收藏夹\n public static final String DEL_ACTIONS = API_URL + \"dellActions.php\";\n\n // 增加删除收藏\n public static final String ADD_DEL_FAVA = API_URL + \"addFava.php\";\n\n // 修改账号资料/找回密码\n public static final String MODIFY_ACCOUNT_INFO = API_URL + \"publicActions.php\";\n\n // 获取用户评论列表\n public static final String GET_USER_COMMENT = API_URL + \"getUserComment.php\";\n\n // 搜索\n public static final String SEARCH = API_URL + \"search.php\";\n\n // 搜索关键词列表\n public static final String SEARCH_KEY_LIST = API_URL + \"searchKeyboard.php\";\n\n // 更新搜索关键词列表的开关\n public static final String UPDATE_SEARCH_KEY_LIST = API_URL + \"updateKeyboard.php\";\n\n}",
"public class LogUtils {\n\n private static final int VERBOSE = 1;\n private static final int DEBUG = 2;\n private static final int INFO = 3;\n private static final int WARN = 4;\n private static final int ERROR = 5;\n private static final int NOTHING = 6;\n public static int level = VERBOSE;\n\n /**\n * 最低级的日志\n *\n * @param tag tag标签\n * @param msg 日志信息\n */\n public static void v(String tag, String msg) {\n if (level <= VERBOSE) {\n Log.v(tag, msg);\n }\n }\n\n /**\n * debug级别日志,调试用\n *\n * @param tag tag标签\n * @param msg 日志信息\n */\n public static void d(String tag, String msg) {\n if (level <= DEBUG) {\n Log.v(tag, msg);\n }\n }\n\n /**\n * info级别日志,重要信息\n *\n * @param tag tag标签\n * @param msg 日志信息\n */\n public static void i(String tag, String msg) {\n if (level <= INFO) {\n Log.v(tag, msg);\n }\n }\n\n /**\n * warn级别日志,特别需要注意的提示\n *\n * @param tag tag标签\n * @param msg 日志信息\n */\n public static void w(String tag, String msg) {\n if (level <= WARN) {\n Log.v(tag, msg);\n }\n }\n\n /**\n * error级别日志,这个一般在catch块里用\n *\n * @param tag tag标签\n * @param msg 日志信息\n */\n public static void e(String tag, String msg) {\n if (level <= ERROR) {\n Log.v(tag, msg);\n }\n }\n\n}",
"public class NetworkUtils {\n\n private static final String TAG = \"NetworkUtils\";\n\n public static final NetworkUtils shared = new NetworkUtils();\n\n private NetworkUtils() {\n }\n\n public static abstract class StringCallback {\n public abstract void onError(Call call, Exception e, int id);\n\n public abstract void onResponse(String response, int id);\n }\n\n /**\n * get请求\n *\n * @param api api接口\n * @param parameters 参数\n * @param callback 监听接口\n */\n public void get(String api, HashMap<String, String> parameters, final StringCallback callback) {\n\n LogUtils.d(TAG, \"api = \" + api);\n OkHttpUtils\n .get()\n .url(api)\n .params(parameters)\n .build()\n .execute(new com.zhy.http.okhttp.callback.StringCallback() {\n @Override\n public void onError(Call call, Exception e, int id) {\n callback.onError(call, e, id);\n }\n\n @Override\n public void onResponse(String response, int id) {\n callback.onResponse(response, id);\n }\n });\n\n }\n\n /**\n * post请求\n *\n * @param api api接口\n * @param parameters 参数\n * @param callback 监听接口\n */\n public void post(String api, HashMap<String, String> parameters, final StringCallback callback) {\n\n LogUtils.d(TAG, \"api = \" + api);\n OkHttpUtils\n .post()\n .url(api)\n .params(parameters)\n .build()\n .execute(new com.zhy.http.okhttp.callback.StringCallback() {\n @Override\n public void onError(Call call, Exception e, int id) {\n callback.onError(call, e, id);\n }\n\n @Override\n public void onResponse(String response, int id) {\n callback.onResponse(response, id);\n }\n });\n\n }\n\n /**\n * 是否有网络连接\n *\n * @param context 上下文\n * @return true有网络\n */\n public boolean isNetworkConnected(Context context) {\n if (context != null) {\n ConnectivityManager mConnectivityManager = (ConnectivityManager) context\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();\n if (mNetworkInfo != null) {\n return mNetworkInfo.isAvailable();\n }\n }\n return false;\n }\n\n /**\n * 判断WiFi是否可用\n *\n * @param context 上下文\n * @return true可用\n */\n public boolean isWifiConnected(Context context) {\n if (context != null) {\n ConnectivityManager mConnectivityManager = (ConnectivityManager) context\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo mWiFiNetworkInfo = mConnectivityManager\n .getNetworkInfo(ConnectivityManager.TYPE_WIFI);\n if (mWiFiNetworkInfo != null) {\n return mWiFiNetworkInfo.isAvailable();\n }\n }\n return false;\n }\n\n /**\n * 判断MOBILE网络是否可用\n *\n * @param context 上下文\n * @return true可用\n */\n public boolean isMobileConnected(Context context) {\n if (context != null) {\n ConnectivityManager mConnectivityManager = (ConnectivityManager) context\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo mMobileNetworkInfo = mConnectivityManager\n .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);\n if (mMobileNetworkInfo != null) {\n return mMobileNetworkInfo.isAvailable();\n }\n }\n return false;\n }\n\n /**\n * 判断网络类型\n *\n * @param context 上下文\n * @return -1:没有网络 1:WIFI网络 2:wap网络 3:net网络\n */\n public static int getNetworkType(Context context) {\n int netType = -1;\n ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();\n if (networkInfo == null) {\n return netType;\n }\n int nType = networkInfo.getType();\n if (nType == ConnectivityManager.TYPE_MOBILE) {\n if (networkInfo.getExtraInfo().toLowerCase().equals(\"cmnet\")) {\n netType = 3;\n } else {\n netType = 2;\n }\n } else if (nType == ConnectivityManager.TYPE_WIFI) {\n netType = 1;\n }\n return netType;\n }\n\n}",
"public class ProgressHUD {\n\n /**\n * 显示加载HUD 需要手动取消\n *\n * @param context 上下文\n * @return KProgressHUD\n */\n public static KProgressHUD show(Context context) {\n return KProgressHUD.create(context)\n .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)\n .setCancellable(true)\n .setDimAmount(0.5f)\n .show();\n }\n\n /**\n * 显示带文字的加载HUD 需要手动取消\n *\n * @param context 上下文\n * @param tipString 提示文字\n * @return KProgressHUD\n */\n public static KProgressHUD show(Context context, String tipString) {\n return KProgressHUD.create(context)\n .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)\n .setLabel(tipString)\n .setCancellable(true)\n .setDimAmount(0.5f)\n .show();\n }\n\n /**\n * 显示带文字的加载HUD 不需要手动取消\n *\n * @param context 上下文\n * @param tipString 提示文字\n * @return KProgressHUD\n */\n public static void showInfo(Context context, String tipString) {\n Toast.makeText(context, tipString, Toast.LENGTH_SHORT).show();\n }\n\n}",
"public class NavigationViewRed extends RelativeLayout implements View.OnClickListener {\n\n public NavigationViewRed(Context context) {\n this(context, null);\n }\n\n private ImageView backView;\n private TextView titleView;\n private ImageView rightView;\n private OnClickListener callback;\n\n // 从布局文件加载会调用\n public NavigationViewRed(Context context, AttributeSet attrs) {\n super(context, attrs);\n View view = LayoutInflater.from(context).inflate(R.layout.navigation_view_red, this, true);\n backView = (ImageView) view.findViewById(R.id.iv_nav_back);\n titleView = (TextView) view.findViewById(R.id.tv_nav_title);\n rightView = (ImageView) view.findViewById(R.id.iv_nav_right);\n backView.setOnClickListener(this);\n rightView.setOnClickListener(this);\n }\n\n /**\n * 配置导航栏\n *\n * @param isShowLeft 是否显示左边按钮\n * @param isShowRight 是否显示右边按钮\n * @param title 标题\n * @param onClickListener 监听器\n */\n public void setupNavigationView(boolean isShowLeft, boolean isShowRight, String title, OnClickListener onClickListener) {\n backView.setVisibility(isShowLeft ? VISIBLE : GONE);\n rightView.setVisibility(isShowRight ? VISIBLE : GONE);\n titleView.setText(title);\n this.callback = onClickListener;\n }\n\n /**\n * 获取返回按钮\n *\n * @return\n */\n public ImageView getBackView() {\n return backView;\n }\n\n /**\n * 获取标题控件\n *\n * @return\n */\n public TextView getTitleView() {\n return titleView;\n }\n\n /**\n * 获取右侧按钮,默认不显示\n *\n * @return\n */\n public ImageView getRightView() {\n return rightView;\n }\n\n @Override\n public void onClick(View v) {\n switch (v.getId()) {\n case R.id.iv_nav_back:\n if (callback != null) {\n callback.onBackClick(backView);\n }\n break;\n case R.id.iv_nav_right:\n if (callback != null) {\n callback.onRightClick(rightView);\n }\n break;\n }\n }\n\n // 监听点击事件\n public static class OnClickListener {\n public void onBackClick(View v) {\n\n }\n\n public void onRightClick(View v) {\n\n }\n }\n\n}"
] | import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import com.kaopiz.kprogresshud.KProgressHUD;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import okhttp3.Call;
import tv.baokan.baokanandroid.R;
import tv.baokan.baokanandroid.model.UserBean;
import tv.baokan.baokanandroid.utils.APIs;
import tv.baokan.baokanandroid.utils.LogUtils;
import tv.baokan.baokanandroid.utils.NetworkUtils;
import tv.baokan.baokanandroid.utils.ProgressHUD;
import tv.baokan.baokanandroid.widget.NavigationViewRed; | package tv.baokan.baokanandroid.ui.activity;
public class ModifySafeInfoActivity extends BaseActivity implements TextWatcher {
private static final String TAG = "ModifySafeInfoActivity";
private NavigationViewRed mNavigationViewRed;
private EditText mOldPasswordEditText; // 老密码
private EditText mNewPasswordEditText; // 新密码
private EditText mConfirmPasswordEditText; // 确认新密码
private EditText mEmailEditText; // 邮箱
private Button mModifyButton; // 修改按钮
/**
* 便捷启动当前activity
*
* @param activity 启动当前activity的activity
*/
public static void start(Activity activity) {
Intent intent = new Intent(activity, ModifySafeInfoActivity.class);
activity.startActivity(intent);
activity.overridePendingTransition(R.anim.push_enter, R.anim.push_exit);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_safe_info);
prepareUI();
prepareData();
// 更新按钮状态
modifyButtonStateChange();
}
/**
* 准备UI
*/
private void prepareUI() {
mNavigationViewRed = (NavigationViewRed) findViewById(R.id.nav_safe_modify_user_info);
mOldPasswordEditText = (EditText) findViewById(R.id.et_safe_modify_user_info_password);
mNewPasswordEditText = (EditText) findViewById(R.id.et_safe_modify_user_info_new_password);
mConfirmPasswordEditText = (EditText) findViewById(R.id.et_safe_modify_user_info_confirm_password);
mEmailEditText = (EditText) findViewById(R.id.et_safe_modify_user_info_email);
mModifyButton = (Button) findViewById(R.id.btn_safe_modify_user_info_modify);
mNavigationViewRed.setupNavigationView(true, false, "修改安全信息", new NavigationViewRed.OnClickListener() {
@Override
public void onBackClick(View v) {
finish();
}
});
mModifyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveModifyInfo();
}
});
mOldPasswordEditText.addTextChangedListener(this);
mNewPasswordEditText.addTextChangedListener(this);
mConfirmPasswordEditText.addTextChangedListener(this);
mEmailEditText.addTextChangedListener(this);
// 自动弹出键盘
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
InputMethodManager inputManager = (InputMethodManager) mOldPasswordEditText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(mOldPasswordEditText, 0);
}
}, 500);
}
/**
* 准备数据
*/
private void prepareData() { | mEmailEditText.setText(UserBean.shared().getEmail()); | 0 |
shibing624/similarity | src/main/java/org/xm/tendency/word/HownetWordTendency.java | [
"public class Concept implements IHownetMeta {\n // 概念名称\n protected String word;\n // 词性 part of speech\n protected String pos;\n // 定义\n protected String define;\n // 实词(true),虚词(false)\n protected boolean bSubstantive;\n // 主基本义原\n protected String mainSememe;\n // 其他基本义原\n protected String[] secondSememes;\n // 关系义原\n protected String[] relationSememes;\n // 关系符号描述\n protected String[] symbolSememes;\n // 类型\n static String[][] concept_Type = {\n {\"=\", \"事件\"},\n {\"aValue|属性值\", \"属性值\"},\n {\"qValue|数量值\", \"数量值\"},\n {\"attribute|属性\", \"属性\"},\n {\"quantity|数量\", \"数量\"},\n {\"unit|\", \"单位\"},\n {\"%\", \"部件\"}\n };\n\n public Concept(String word, String pos, String define) {\n this.word = word;\n this.pos = pos;\n this.define = (define == null) ? \"\" : define.trim();\n\n // 虚词表示:{***}\n if (define.length() > 0 && define.charAt(0) == '{' && define.charAt(define.length() - 1) == '}') {\n this.bSubstantive = false;\n } else {\n this.bSubstantive = true;\n }\n initDefine();\n }\n\n private void initDefine() {\n List<String> secondList = new ArrayList<>();//求他基本义原\n List<String> relationList = new ArrayList<>();//关系义原\n List<String> symbolList = new ArrayList<>();//符号义原\n String tokenString = this.define;\n if (!this.bSubstantive) {//如果不是实词,则处理“{}”中的内容\n tokenString = define.substring(1, define.length() - 1);\n }\n StringTokenizer token = new StringTokenizer(tokenString, \",\", false);\n\n if (token.hasMoreTokens()) {\n this.mainSememe = token.nextToken();\n }\n main_loop:\n while (token.hasMoreTokens()) {\n String item = token.nextToken();\n if (item.equals(\"\")) continue;\n //判断符号义原\n String symbol = item.substring(0, 1);\n for (int i = 0; i < Symbol_Descriptions.length; i++) {\n if (symbol.equals(Symbol_Descriptions[i][0])) {\n symbolList.add(item);\n continue main_loop;\n }\n }\n //判断第二基本义原\n if (item.indexOf('=') > 0) {\n relationList.add(item);\n } else {\n secondList.add(item);\n }\n }\n this.secondSememes = secondList.toArray(new String[secondList.size()]);\n this.relationSememes = relationList.toArray(new String[relationList.size()]);\n this.symbolSememes = symbolList.toArray(new String[symbolList.size()]);\n }\n\n public String getWord() {\n return word;\n }\n\n public void setWord(String word) {\n this.word = word;\n }\n\n public String getPos() {\n return pos;\n }\n\n public void setPos(String pos) {\n this.pos = pos;\n }\n\n public String getDefine() {\n return define;\n }\n\n public void setDefine(String define) {\n this.define = define;\n }\n\n public boolean isbSubstantive() {\n return bSubstantive;\n }\n\n public void setbSubstantive(boolean bSubstantive) {\n this.bSubstantive = bSubstantive;\n }\n\n public String getMainSememe() {\n return mainSememe;\n }\n\n public void setMainSememe(String mainSememe) {\n this.mainSememe = mainSememe;\n }\n\n public String[] getSecondSememes() {\n return secondSememes;\n }\n\n public void setSecondSememes(String[] secondSememes) {\n this.secondSememes = secondSememes;\n }\n\n public String[] getRelationSememes() {\n return relationSememes;\n }\n\n public void setRelationSememes(String[] relationSememes) {\n this.relationSememes = relationSememes;\n }\n\n public String[] getSymbolSememes() {\n return symbolSememes;\n }\n\n public void setSymbolSememes(String[] symbolSememes) {\n this.symbolSememes = symbolSememes;\n }\n\n public Set<String> getAllSememeNames() {\n Set<String> names = new HashSet<>();\n //主义原\n names.add(getMainSememe());\n //关系义原\n for (String item : getRelationSememes()) {\n names.add(item.substring(item.indexOf(\"=\") + 1));\n }\n //符号义原\n for (String item : getSymbolSememes()) {\n names.add(item.substring(1));\n }\n //其他义原集合\n for (String item : getSecondSememes()) {\n names.add(item);\n }\n return names;\n }\n\n public String getType() {\n for (int i = 0; i < concept_Type.length; i++) {\n if (define.toUpperCase().indexOf(concept_Type[i][0].toUpperCase()) >= 0) {\n return concept_Type[i][1];\n }\n }\n return \"普通\";\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"名称=\");\n sb.append(this.word);\n sb.append(\"; 词性=\");\n sb.append(this.pos);\n sb.append(\"; 定义=\");\n sb.append(this.define);\n sb.append(\"; 第一基本义元:[\" + mainSememe);\n\n sb.append(\"]; 其他基本义元描述:[\");\n for (String sem : secondSememes) {\n sb.append(sem);\n sb.append(\";\");\n }\n\n sb.append(\"]; [关系义元描述:\");\n for (String sem : relationSememes) {\n sb.append(sem);\n sb.append(\";\");\n }\n\n sb.append(\"]; [关系符号描述:\");\n for (String sem : symbolSememes) {\n sb.append(sem);\n sb.append(\";\");\n }\n sb.append(\"]\");\n return sb.toString();\n }\n\n @Override\n public int hashCode() {\n return define == null ? word.hashCode() : define.hashCode();\n }\n\n @Override\n public boolean equals(Object object) {\n if (object instanceof Concept) {\n Concept c = (Concept) object;\n return word.equals(c.word) && define.equals(c.define);\n } else {\n return false;\n }\n }\n}",
"public abstract class ConceptParser implements IHownetMeta, IWordSimilarity {\n private static final Logger logger = LoggerFactory.getLogger(ConceptParser.class);\n private static Multimap<String, Concept> CONCEPTS = null;\n private final static String path = Similarity.Config.ConceptXmlPath;\n protected SememeParser sememeParser = null;\n\n /**\n * 集合运算类型,目前支持均值运算和模糊集运算两种形式\n */\n public enum OPERATE_TYPE {\n AVERAGE,\n FUZZY\n }\n\n private OPERATE_TYPE currentOperateType = OPERATE_TYPE.AVERAGE;\n\n public ConceptParser(SememeParser sememeParser) throws IOException {\n this.sememeParser = sememeParser;\n synchronized (this) {\n if (CONCEPTS == null) {\n loadFile();\n }\n }\n }\n\n\n private static void loadFile() throws IOException {\n CONCEPTS = HashMultimap.create();\n InputStream inputStream = new GZIPInputStream(DicReader.getInputStream(path));\n load(inputStream);\n }\n\n /**\n * 用户自定义概念词典\n *\n * @param xmlFile\n * @throws IOException\n */\n public static void load(File xmlFile) throws IOException {\n if (CONCEPTS == null) {\n loadFile();\n }\n load(new FileInputStream(xmlFile));\n }\n\n private static void load(InputStream inputStream) throws IOException {\n long start = System.currentTimeMillis();\n int count = 0;\n try {\n XMLInputFactory inputFactory = XMLInputFactory.newInstance();\n XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(inputStream);\n while (xmlEventReader.hasNext()) {\n XMLEvent event = xmlEventReader.nextEvent();\n if (event.isStartElement()) {\n StartElement startElement = event.asStartElement();\n if (startElement.getName().toString().equals(\"c\")) {\n String word = startElement.getAttributeByName(QName.valueOf(\"w\")).getValue();\n String define = startElement.getAttributeByName(QName.valueOf(\"d\")).getValue();\n String pos = startElement.getAttributeByName(QName.valueOf(\"p\")).getValue();\n CONCEPTS.put(word, new Concept(word, pos, define));\n count++;\n }\n }\n }\n inputStream.close();\n } catch (Exception e) {\n throw new IOException(e);\n }\n logger.info(\"complete! count num:\" + count + \",time spend:\" + (System.currentTimeMillis() - start) + \"ms\");\n }\n\n /**\n * 获取两个词语的相似度,如果一个词语对应多个概念,则返回相似度最大的一对\n *\n * @param word1\n * @param word2\n * @return\n */\n public abstract double getSimilarity(String word1, String word2);\n\n /**\n * 计算四个组成部分的相似度方式,不同的算法对这四个部分的处理或者说权重分配不同\n *\n * @param sim_v1 主义原的相似度\n * @param sim_v2 其他基本义原的相似度\n * @param sim_v3 关系义原的相似度\n * @param sim_v4 符号义原的相似度\n * @return\n */\n protected abstract double calculate(double sim_v1, double sim_v2, double sim_v3, double sim_v4);\n\n /**\n * 判断一个词语是否是一个概念\n *\n * @param word\n * @return\n */\n public boolean isConcept(String word) {\n return StringUtil.isNotBlank(CONCEPTS.get(word));\n }\n\n /**\n * 根据名称获取对应的概念定义信息,由于一个词语可能对应多个概念,因此返回一个集合\n *\n * @param key\n * @return\n */\n public Collection<Concept> getConcepts(String key) {\n return CONCEPTS.get(key);\n }\n\n public double getSimilarity(Concept concept1, Concept concept2) {\n double similarity = 0.0;\n if (concept1 == null || concept2 == null || !concept1.getPos().equals(concept2.getPos())) {\n return 0.0;\n }\n if (concept1.equals(concept2)) {\n return 1.0;\n }\n // 虚词和实词概念的相似度是0\n if (concept1.isbSubstantive() != concept2.isbSubstantive()) {\n return 0.0;\n }\n // 虚词\n if (concept1.isbSubstantive() == false) {\n similarity = sememeParser.getSimilarity(concept1.getMainSememe(), concept2.getMainSememe());\n } else {// 实词\n double sim1 = sememeParser.getSimilarity(concept1.getMainSememe(), concept2.getMainSememe());\n double sim2 = getSimilarity(concept1.getSecondSememes(), concept2.getSecondSememes());\n double sim3 = getSimilarity(concept1.getRelationSememes(), concept2.getRelationSememes());\n double sim4 = getSimilarity(concept1.getSymbolSememes(), concept2.getSymbolSememes());\n similarity = calculate(sim1, sim2, sim3, sim4);\n }\n return similarity;\n }\n\n /**\n * 计算两个义原集合的相似度\n * 每一个集合都是一个概念的某一类义原集合,如第二基本义原、符号义原、关系义原等\n *\n * @param sememes1\n * @param sememes2\n * @return\n */\n private double getSimilarity(String[] sememes1, String[] sememes2) {\n if (currentOperateType == OPERATE_TYPE.FUZZY) {\n return getSimilarityFuzzy(sememes1, sememes2);\n } else {\n return getSimilarityAVG(sememes1, sememes2);\n }\n }\n\n private double getSimilarityFuzzy(String[] sememes1, String[] sememes2) {\n // TODO\n return 0;\n }\n\n public void setOperateType(OPERATE_TYPE type) {\n this.currentOperateType = type;\n }\n\n private double getSimilarityAVG(String[] sememes1, String[] sememes2) {\n double similarity;\n double scoreArray[][];\n if (StringUtil.isBlank(sememes1) || StringUtil.isBlank(sememes2)) {\n if (StringUtil.isBlank(sememes1) && StringUtil.isBlank(sememes2)) {\n return 1.0;\n } else {\n return delta;// 一个非空值与空值的相似度为一个小的常数\n }\n }\n double score = 0.0;\n int arrayLen = MathUtil.max(sememes1.length, sememes2.length);\n scoreArray = new double[arrayLen][arrayLen];\n // calculate similarity of two set\n for (int i = 0; i < sememes1.length; i++) {\n for (int j = 0; j < sememes2.length; j++) {\n scoreArray[i][j] = sememeParser.getSimilarity(sememes1[i], sememes2[j]);\n }\n }\n\n // get max similarity score\n while (scoreArray.length > 0) {\n double[][] temp;\n int row = 0;\n int column = 0;\n double max = scoreArray[row][column];\n for (int i = 0; i < scoreArray.length; i++) {\n for (int j = 0; j < scoreArray[i].length; j++) {\n if (scoreArray[i][j] > max) {\n row = i;\n column = j;\n max = scoreArray[i][j];\n }\n }\n }\n score += max;\n // 过滤掉该行该列,继续计算\n temp = new double[scoreArray.length - 1][scoreArray.length - 1];\n for (int i = 0; i < scoreArray.length; i++) {\n if (i == row) {\n continue;\n }\n for (int j = 0; j < scoreArray[i].length; j++) {\n if (j == column) {\n continue;\n }\n int tempRow = i;\n int tempColumn = j;\n if (i > row) {\n tempRow--;\n }\n if (j > column) {\n tempColumn--;\n }\n temp[tempRow][tempColumn] = scoreArray[i][j];\n }\n }\n scoreArray = temp;\n }\n similarity = score / arrayLen;\n return similarity;\n }\n\n}",
"public class ConceptSimilarity extends ConceptParser {\n private static final int MAX_COMBINED_COUNT = 12;\n private static ConceptSimilarity instance = null;\n\n public static ConceptSimilarity getInstance() {\n if (instance == null) {\n try {\n instance = new ConceptSimilarity();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return instance;\n }\n\n private ConceptSimilarity() throws IOException {\n super(new SememeSimilarity());\n }\n\n public ConceptSimilarity(SememeSimilarity sememeSimilarity) throws IOException {\n super(sememeSimilarity);\n }\n\n /**\n * 获取两个词语的相似度,如果一个词语对应多个概念,则返回相似度最大的\n *\n * @param word1\n * @param word2\n * @return\n */\n @Override\n public double getSimilarity(String word1, String word2) {\n double similarity = 0.0;\n if (word1.equals(word2)) {\n return 1.0;\n }\n Collection<Concept> concepts1 = getConcepts(word1);\n Collection<Concept> concepts2 = getConcepts(word2);\n // 未登录词需要计算组合概念\n if (StringUtil.isBlank(concepts1) && StringUtil.isNotBlank(concepts2)) {\n concepts1 = autoCombineConcepts(word1, concepts2);\n }\n if (StringUtil.isBlank(concepts2) && StringUtil.isNotBlank(concepts1)) {\n concepts2 = autoCombineConcepts(word2, concepts1);\n }\n if (StringUtil.isBlank(concepts1) && StringUtil.isBlank(concepts2)) {\n concepts1 = autoCombineConcepts(word1, concepts2);\n concepts2 = autoCombineConcepts(word2, concepts1);\n // 修正\n concepts1 = autoCombineConcepts(word1, concepts2);\n concepts2 = autoCombineConcepts(word2, concepts1);\n }\n\n // 处理所有可能组合的相似度\n for (Concept c1 : concepts1) {\n for (Concept c2 : concepts2) {\n double v = getSimilarity(c1, c2);\n if (v > similarity) {\n similarity = v;\n }\n if (similarity == 1.0) {\n break;\n }\n }\n }\n return similarity;\n }\n\n @Override\n protected double calculate(double sim_v1, double sim_v2, double sim_v3, double sim_v4) {\n return beta1 * sim_v1 + beta2 * sim_v1 * sim_v2 + beta3 * sim_v1 * sim_v3 + beta4 * sim_v1 * sim_v4;\n }\n\n public Collection<Concept> getConcepts(String key) {\n Collection<Concept> concepts = super.getConcepts(key);\n if (StringUtil.isBlank(concepts)) {\n concepts = autoCombineConcepts(key, null);\n }\n return concepts;\n }\n\n /**\n * 获取知网本身自带的概念,不组合处理\n *\n * @param key\n * @return\n */\n public Collection<Concept> getInnerConcepts(String key) {\n return super.getConcepts(key);\n }\n\n /**\n * 计算未登录词语\n *\n * @param newWord\n * @param refConcepts\n * @return\n */\n public Collection<Concept> autoCombineConcepts(String newWord, Collection<Concept> refConcepts) {\n ConceptLinkedList newConcepts = new ConceptLinkedList();\n if (StringUtil.isBlank(newWord)) {\n return newConcepts;\n }\n // 取最可能三个\n List<String> segmentNewWords = segmentNewWord(newWord, 3);\n // 过滤未登录单字\n if (segmentNewWords.size() == 1) {\n return newConcepts;\n }\n // 处理未登录组合词\n for (String conceptWord : segmentNewWords) {\n Collection<Concept> concepts = getConcepts(conceptWord);\n if (newConcepts.size() == 0) {\n newConcepts.addAll(concepts);\n continue;\n }\n ConceptLinkedList tempConcepts = new ConceptLinkedList();\n for (Concept head : concepts) {\n for (Concept tail : newConcepts) {\n if (StringUtil.isNotBlank(refConcepts)) {\n for (Concept ref : refConcepts) {\n tempConcepts.addByDefine(autoCombineConcept(head, tail, ref));\n }\n } else {\n tempConcepts.addByDefine(autoCombineConcept(head, tail, null));\n }\n }\n }\n newConcepts = tempConcepts;\n }\n // 过滤删除最后的1/3\n if ((newConcepts.size() > MAX_COMBINED_COUNT)) {\n newConcepts.removeLast(MAX_COMBINED_COUNT / 3);\n }\n return newConcepts;\n }\n\n /**\n * 把未登录词进行概念切分, 形成多个概念的线性链表,并倒排组织\n * 如“娱乐场”切分完毕后存放成: 【场】 → 【娱乐】\n *\n * @param newWord\n * @param top\n * @return\n */\n private List<String> segmentNewWord(String newWord, int top) {\n List<String> results = new LinkedList<>();\n int count = 0;\n String word = newWord;\n while (word != null && !word.equals(\"\")) {\n String token = word;\n while (token.length() > 1 && StringUtil.isBlank(super.getConcepts(token))) {\n token = token.substring(1);\n }\n results.add(token);\n count++;\n if (count >= top) break;\n word = word.substring(0, word.length() - token.length());\n }\n return results;\n\n }\n\n /**\n * 计算两个概念的组合概念\n * 计算过程中根据参照概念修正组合结果, 实际应用中的两个概念应具有一定的先后关系(体现汉语“重心后移”特点),\n * 如对于娱乐场,first=\"娱乐\" second=\"场\", 另外,\n * 还需要修正第一个概念中的符号义原对于第二个概念主义原的实际关系,当参照概念起作用时,\n * 即大于指定的阈值,则需要判断是否把当前义原并入组合概念中,对于第一个概念,还需要同时修正符号关系,\n * 符合关系与参照概念保持一致\n *\n * @param head 第一概念\n * @param tail 第二概念\n * @param ref 参考\n * @return\n */\n public Concept autoCombineConcept(Concept head, Concept tail, Concept ref) {\n // 一个null,一个非null,返回非null的新概念\n if (tail == null && head != null) {\n return new Concept(head.getWord(), head.getPos(), head.getDefine());\n }\n if (head == null && tail != null) {\n return new Concept(tail.getWord(), tail.getPos(), tail.getDefine());\n }\n\n // 第二个概念不是实词,直接返回第一个概念\n if (!tail.isbSubstantive()) {\n return new Concept(head.getWord() + tail.getWord(), head.getPos(), head.getDefine());\n }\n // 如无参照概念,或者参照概念是虚词,则直接相加\n if (ref == null || !ref.isbSubstantive()) {\n String define = tail.getDefine();\n List<String> sememeList = getAllSememes(head, true);\n for (String sememe : sememeList) {\n if (!define.contains(sememe)) {\n define = define + \",\" + sememe;\n }\n }\n return new Concept(head.getWord() + tail.getWord(), tail.getPos(), define);\n }\n // 正常处理,实词概念,参考概念非空\n String define = tail.getMainSememe();\n List<String> refSememes = getAllSememes(ref, false);\n List<String> headSememes = getAllSememes(head, true);\n List<String> tailSememes = getAllSememes(tail, false);\n\n // 如果参照概念与第二个概念的主义原的义原相似度大于阈值THETA,\n // 则限制组合概念定义中与第二个概念相关的义原部分为:\n // 第二个概念的义原集合与参照概念义原集合的模糊交集\n double mainSimilarity = sememeParser.getSimilarity(tail.getMainSememe(), ref.getMainSememe());\n if (mainSimilarity >= PARAM_THETA) {\n // 交集\n for (String tailSememe : tailSememes) {\n double maxSimilarity = 0.0;\n String maxRefSememe = \"\";\n for (String refSememe : refSememes) {\n double value = sememeParser.getSimilarity(tailSememe, refSememe);\n if (value > maxSimilarity) {\n maxSimilarity = value;\n maxRefSememe = refSememe;\n }\n }\n // 如果tail_sememe与参照概念中的相似度最大的义原经theta约束后超过阈值XI,则加入生成的组合概念定义中\n if (maxSimilarity * mainSimilarity >= PARAM_XI) {\n define = define + \",\" + tailSememe;\n refSememes.remove(maxRefSememe);\n }\n }\n } else {\n define = tail.getDefine();\n }\n // 合并第一个概念的义原到组合概念中\n for (String headSememe : headSememes) {\n double maxSimilarity = 0.0;\n String maxRefSememe = \"\";\n for (String refSememe : refSememes) {\n double value = sememeParser.getSimilarity(getPureSememe(headSememe), getPureSememe(refSememe));\n if (value > maxSimilarity) {\n maxSimilarity = value;\n maxRefSememe = refSememe;\n }\n }\n if (mainSimilarity * maxSimilarity >= PARAM_OMEGA) {\n // 调整符号关系, 用参照概念的符号关系替换原符号关系, 通过把参照概念的非符号部分替换成前面义原的非符号内容\n String sememe = maxRefSememe.replace(getPureSememe(maxRefSememe), getPureSememe(headSememe));\n if (!define.contains(sememe)) {\n define = define + \",\" + sememe;\n }\n } else if (!define.contains(headSememe)) {\n define = define + \",\" + headSememe;\n }\n }\n return new Concept(head.getWord() + tail.getWord(), tail.getPos(), define);\n }\n\n /**\n * 获取概念的所有义原\n *\n * @param concept\n * @param includeMainSememe 是否包含主义原\n * @return\n */\n private List<String> getAllSememes(Concept concept, Boolean includeMainSememe) {\n List<String> results = new ArrayList<>();\n if (concept != null) {\n if (includeMainSememe) {\n results.add(concept.getMainSememe());\n }\n for (String sememe : concept.getSecondSememes()) {\n results.add(sememe);\n }\n for (String sememe : concept.getSymbolSememes()) {\n results.add(sememe);\n }\n for (String sememe : concept.getRelationSememes()) {\n results.add(sememe);\n }\n }\n return results;\n }\n\n /**\n * 去掉义原的符号和关系\n *\n * @param sememe\n * @return\n */\n private String getPureSememe(String sememe) {\n String line = sememe.trim();\n if ((line.charAt(0) == '(') && (line.charAt(line.length() - 1) == ')')) {\n line = line.substring(1, line.length() - 1);\n }\n // 符号\n String symbol = line.substring(0, 1);\n for (int i = 0; i < Symbol_Descriptions.length; i++) {\n if (symbol.equals(Symbol_Descriptions[i][0])) {\n return line.substring(1);\n }\n }\n\n // 关系义原、第二基本义原\n int pos = line.indexOf('=');\n if (pos > 0) {\n line = line.substring(pos + 1);\n }\n return line;\n }\n}",
"public abstract class SememeParser implements IHownetMeta, ISimilarity {\n private static final Logger logger = LoggerFactory.getLogger(SememeParser.class);\n /**\n * 所有的义原都存放到一个MultiMap, Key为Sememe的中文定义, Value为义原的Id\n */\n protected static Multimap<String, String> SEMEMES = null;\n private static final String path = Similarity.Config.SememeXmlPath;\n\n public SememeParser() throws IOException {\n if (SEMEMES != null) {\n return;\n }\n SEMEMES = HashMultimap.create();\n InputStream inputStream = new GZIPInputStream(DicReader.getInputStream(path));\n load(inputStream);\n }\n\n /**\n * 文件加载义原\n */\n private void load(InputStream inputStream) throws IOException {\n long time = System.currentTimeMillis();\n int count = 0;\n try {\n XMLInputFactory inputFactory = XMLInputFactory.newInstance();\n XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(inputStream);\n\n while (xmlEventReader.hasNext()) {\n XMLEvent event = xmlEventReader.nextEvent();\n if (event.isStartElement()) {\n StartElement startElement = event.asStartElement();\n if (startElement.getName().toString().equals(\"sememe\")) {\n String cnWord = startElement.getAttributeByName(QName.valueOf(\"cn\")).getValue();\n String id = startElement.getAttributeByName(QName.valueOf(\"id\")).getValue();\n SEMEMES.put(cnWord, id);\n count++;\n }\n }\n }\n inputStream.close();\n } catch (Exception e) {\n logger.error(\"xml err:\" + e.toString());\n e.printStackTrace();\n }\n time = System.currentTimeMillis() - time;\n logger.info(\"complete! count num:\" + count + \". time spend:\" + time + \"ms\");\n }\n\n /**\n * 关联度\n *\n * @param sememeName1\n * @param sememeName2\n * @return\n */\n public double getAssociation(String sememeName1, String sememeName2) {\n return 0.0;\n }\n}",
"public class SememeSimilarity extends SememeParser {\n\n public SememeSimilarity() throws IOException {\n super();\n }\n\n /**\n * 计算两个义原的相似度\n */\n double getSimilarityBySememeId(final String id1, final String id2) {\n\n int position = 0;\n String[] array1 = id1.split(\"-\");\n String[] array2 = id2.split(\"-\");\n for (position = 0; position < array1.length && position < array2.length; position++) {\n if (!array1[position].equals(array2[position])) {\n break;\n }\n }\n\n return 2.0 * position / (array1.length + array2.length);\n }\n\n /**\n * 根据汉语定义计算义原之间的相似度,由于可能多个义元有相同的汉语词语,故计算结果为其中相似度最大者\n *\n * @return\n */\n public double getMaxSimilarity(String sememeName1, String sememeName2) {\n double maxValue = 0.0;\n\n // 如果两个字符串相等,直接返回距离为0\n if (sememeName1.equals(sememeName2)) {\n return 1.0;\n }\n Collection<String> sememeIds1 = SEMEMES.get(sememeName1);\n Collection<String> sememeIds2 = SEMEMES.get(sememeName2);\n // 如果sememe1或者sememe2不是义元,则返回0\n if (sememeIds1.size() == 0 || sememeIds1.size() == 0) {\n return 0.0;\n }\n\n for (String id1 : sememeIds1) {\n for (String id2 : sememeIds2) {\n double value = getSimilarityBySememeId(id1, id2);\n if (value > maxValue) {\n maxValue = value;\n }\n }\n }\n\n return maxValue;\n }\n\n /**\n * 计算两个义元之间的相似度,由于义元可能相同,计算结果为其中相似度最大者 similarity = alpha/(distance+alpha),\n * 如果两个字符串相同或都为空,直接返回1.0\n */\n @Override\n public double getSimilarity(String item1, String item2) {\n if (StringUtil.isBlankAll(item2, item2)) {\n return 1.0;\n } else if (StringUtil.isBlankAtLeastOne(item1, item2)) {\n return 0.0;\n } else if (item1.equals(item2)) {\n return 1.0;\n }\n\n String key1 = item1.trim();\n String key2 = item2.trim();\n\n // 去掉()符号\n if ((key1.charAt(0) == '(') && (key1.charAt(key1.length() - 1) == ')')) {\n\n if (key2.charAt(0) == '(' && key2.charAt(key2.length() - 1) == ')') {\n key1 = key1.substring(1, key1.length() - 1);\n key2 = key2.substring(1, key2.length() - 1);\n } else {\n return 0.0;\n }\n\n }\n\n // 处理关系义元,即x=y的情况\n int pos = key1.indexOf('=');\n if (pos > 0) {\n int pos2 = key2.indexOf('=');\n // 如果是关系义元,则判断前面部分是否相同,如果相同,则转为计算后面部分的相似度,否则为0\n if ((pos == pos2) && key1.substring(0, pos).equals(key2.substring(0, pos2))) {\n key1 = key1.substring(pos + 1);\n key2 = key2.substring(pos2 + 1);\n } else {\n return 0.0;\n }\n }\n\n // 处理符号义元,即前面有特殊符号的义元\n String symbol1 = key1.substring(0, 1);\n String symbol2 = key2.substring(0, 1);\n\n for (int i = 0; i < Symbol_Descriptions.length; i++) {\n if (symbol1.equals(Symbol_Descriptions[i][0])) {\n if (symbol1.equals(symbol2)) {\n key1 = item1.substring(1);\n key2 = item2.substring(1);\n break;\n } else {\n return 0.0; // 如果不是同一关系符号,则相似度直接返回0\n }\n }\n }\n\n if ((pos = key1.indexOf(\"|\")) >= 0) {\n key1 = key1.substring(pos + 1);\n }\n if ((pos = key2.indexOf(\"|\")) >= 0) {\n key2 = key2.substring(pos + 1);\n }\n\n // 如果两个字符串相等,直接返回距离为0\n if (key1.equals(key2)) {\n return 1.0;\n }\n\n return getMaxSimilarity(key1, key2);\n }\n}"
] | import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xm.similarity.word.hownet.concept.Concept;
import org.xm.similarity.word.hownet.concept.ConceptParser;
import org.xm.similarity.word.hownet.concept.ConceptSimilarity;
import org.xm.similarity.word.hownet.sememe.SememeParser;
import org.xm.similarity.word.hownet.sememe.SememeSimilarity;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set; | package org.xm.tendency.word;
/**
* 知网词语倾向性
*
* @author xuming
*/
public class HownetWordTendency implements IWordTendency {
private static final Logger logger = LoggerFactory.getLogger(HownetWordTendency.class); | private ConceptParser conceptParser; | 1 |
tommai78101/PokemonWalking | game/src/main/java/script/Script.java | [
"public class Debug {\n\tstatic class NotYetImplemented {\n\t\tprivate int occurrences = 0;\n\t\tprivate final String location;\n\n\t\tpublic NotYetImplemented(String loc) {\n\t\t\tthis.location = loc;\n\t\t}\n\n\t\tpublic boolean grab(String loc) {\n\t\t\tif (this.location.equals(loc) && !this.hasReachedLimit()) {\n\t\t\t\tthis.increment();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic void increment() {\n\t\t\tthis.occurrences++;\n\t\t}\n\n\t\tpublic boolean hasReachedLimit() {\n\t\t\treturn this.occurrences >= Debug.MaxDuplicateLogOccurrences;\n\t\t}\n\t}\n\n\t/**\n\t * Logs information in yellow text.\n\t * \n\t * @param msg\n\t */\n\tpublic static void warn(String msg) {\n\t\tDebug.printColor(AnsiColors.Yellow, Debug.createString(msg));\n\t}\n\n\t/**\n\t * Prints out information in green text.\n\t * \n\t * @param msg\n\t */\n\tpublic static void info(String msg) {\n\t\tDebug.printColor(AnsiColors.Green, Debug.createString(msg));\n\t}\n\n\t/**\n\t * Displays error in bright red text.\n\t * \n\t * @param msg\n\t */\n\tpublic static void error(String msg) {\n\t\tDebug.printColor(AnsiColors.BrightRed, Debug.createString(msg));\n\t}\n\n\t/**\n\t * Displays error in bright red text, and prints out the exception in dark red text.\n\t * \n\t * @param msg\n\t * @param e\n\t */\n\tpublic static void error(String msg, Exception e) {\n\t\tDebug.printColor(AnsiColors.BrightRed, Debug.createString(msg));\n\t\tDebug.printColor(AnsiColors.Red, Debug.createExceptionString(e));\n\t}\n\n\t/**\n\t * Displays error exception in dark red text.\n\t * \n\t * @param e\n\t */\n\tpublic static void exception(Exception e) {\n\t\tDebug.printColor(AnsiColors.Red, Debug.createExceptionString(e));\n\t}\n\n\t/**\n\t * Displays an alert message box with the error message and line number.\n\t * \n\t * @param e\n\t */\n\tpublic static void showExceptionCause(Exception e) {\n\t\tDebug.showExceptionCause(\"\", e);\n\t}\n\n\t/**\n\t * Displays an alert message box with a customized message, the error message, and the line number.\n\t * \n\t * @param msg\n\t * @param e\n\t */\n\tpublic static void showExceptionCause(String msg, Exception e) {\n\t\tif (msg == null) {\n\t\t\tStackTraceElement threadStack = Thread.currentThread().getStackTrace()[2];\n\t\t\tString threadCause = threadStack.getClassName() + \":\" + threadStack.getLineNumber();\n\t\t\tJOptionPane.showMessageDialog(null, \"Debug.showExceptionCause encountered null message.\\n\" + threadCause);\n\t\t\treturn;\n\t\t}\n\t\tStackTraceElement element = e.getStackTrace()[0];\n\t\tString cause = \"(\" + element.getFileName() + \":\" + element.getLineNumber() + \")\";\n\t\tif (!msg.isBlank()) {\n\t\t\tmsg += \"\\n\";\n\t\t}\n\t\tmsg += e.getMessage() + \" \" + cause;\n\t\tJOptionPane.showMessageDialog(null, msg);\n\t}\n\n\t/**\n\t * Nifty way of marking where in the code, have we not yet implemented any Java code.\n\t */\n\tpublic static void toDo(String msg, int stackTraceIndex) {\n\t\tString key = Debug.createString(\"\", stackTraceIndex);\n\t\tNotYetImplemented nyi = Debug.notYetImplementedTracker.getOrDefault(key, new NotYetImplemented(key));\n\t\tif (nyi.grab(key)) {\n\t\t\tint index = 3;\n\t\t\tdo {\n\t\t\t\tmsg = Debug.createString(msg, index);\n\t\t\t\tindex--;\n\t\t\t}\n\t\t\twhile (msg == null || (msg.contains(\"$\") && index > 0));\n\t\t\tDebug.printColor(AnsiColors.BrightMagenta, msg);\n\t\t\tDebug.notYetImplementedTracker.put(key, nyi);\n\t\t}\n\t}\n\n\tpublic static void toDo(String msg) {\n\t\tDebug.toDo(msg, 5);\n\t}\n\n\tpublic static void notYetImplemented() {\n\t\tDebug.toDo(\"Not yet implemented\", 4);\n\t}\n\n\t// -----------------------------------------------------------------\n\t// Private static methods and class member fields.\n\n\tprivate static final int MinimumStringLength = 17;\n\tprivate static final int TabLength = 8;\n\tprotected static final int MaxDuplicateLogOccurrences = 1;\n\tprivate static Map<String, NotYetImplemented> notYetImplementedTracker = new HashMap<>();\n\n\t/**\n\t * Handles wrapping the input string with ANSI color tags.\n\t * \n\t * @param color\n\t * @param input\n\t */\n\tprivate static void printColor(AnsiColors color, String input) {\n\t\tSystem.out.println(color.getAnsiCode() + input + AnsiColors.Clear.getAnsiCode());\n\t}\n\n\t/**\n\t * Builds the log messages in a readable format for developers.\n\t * \n\t * @param msg\n\t * @param index\n\t * Specify which stack trace element to choose from.\n\t * @return\n\t */\n\tprivate static String createString(String msg, int index) {\n\t\tStackTraceElement[] elements = new Throwable().getStackTrace();\n\t\tStackTraceElement element = elements[index];\n\t\tString className = element.getClassName() + \":\" + element.getLineNumber();\n\t\tString tabs = \"\\t\";\n\t\tint length = className.length();\n\t\twhile (length < Debug.MinimumStringLength) {\n\t\t\ttabs = tabs.concat(\"\\t\");\n\t\t\tlength += Debug.TabLength;\n\t\t}\n\t\treturn className + tabs + \"- \" + msg;\n\t}\n\n\t/**\n\t * Builds the log messages in a readable format for developers.\n\t * \n\t * @param msg\n\t * @return\n\t */\n\tprivate static String createString(String msg) {\n\t\treturn createString(msg, 3);\n\t}\n\n\t/**\n\t * Builds a simplified exception message thrown out by the actual class object containing the bug.\n\t * Does not display anything related with Java SDK internal classes.\n\t * \n\t * @param e\n\t * @return\n\t */\n\tprotected static String createExceptionString(Exception e) {\n\t\tStackTraceElement[] elements = e.getStackTrace();\n\t\tStackTraceElement element = elements[elements.length - 1];\n\t\tString className = element.getClassName() + \":\" + element.getLineNumber();\n\t\tString tabs = \"\\t\";\n\t\tint length = className.length();\n\t\twhile (length < Debug.MinimumStringLength) {\n\t\t\ttabs = tabs.concat(\"\\t\");\n\t\t\tlength += Debug.TabLength;\n\t\t}\n\t\treturn className + tabs + \"- \" + e.getLocalizedMessage();\n\t}\n}",
"public class Dialogue {\n\t// The type value is tied to how the data bits are parsed from the game data.\n\t// TODO(Thompson): Need to uncover the valid range, and whether we can actually determine arbitrary\n\t// values instead?\n\tpublic static enum DialogueType {\n\t\tSPEECH(0x40),\n\t\tQUESTION(0x41),\n\t\tALERT(0x42);\n\n\t\tpublic final int typeValue;\n\n\t\tDialogueType(int value) {\n\t\t\tthis.typeValue = value;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn Integer.toString(this.typeValue);\n\t\t}\n\t}\n\n\tpublic static final int HALF_STRING_LENGTH = 9;\n\n\t// Dialogue max string length per line.\n\tpublic static final int MAX_STRING_LENGTH = 18;\n\n\t// Tick delays\n\tpublic static final byte MAX_TICK_DELAY = 0xE;\n\tpublic static final byte CHARACTER_TICK_DELAY = 0x1;\n\tpublic static final byte ZERO_TICK = 0x0;\n\n\tprivate List<String> completedLines;\n\n\tprivate int lineIterator;\n\tprivate int lineLength;\n\tprivate List<Map.Entry<String, Boolean>> lines;\n\n\tprivate boolean simpleQuestionFlag;\n\tprivate boolean simpleSpeechFlag;\n\tprivate boolean ignoreInputsFlag;\n\n\t/**\n\t * If true, displays the \"down arrow\" inside the dialogue box.\n\t */\n\tprivate boolean nextFlag;\n\n\t/**\n\t * If true, the dialogue is animating a scrolling animation and moving the text upwards.\n\t */\n\tprivate boolean scrollFlag;\n\n\t/**\n\t * Three states: YES, NO, NULL. NULL means the YesNo alert dialogue box does not appear.\n\t */\n\tprivate Boolean yesNoAnswerFlag;\n\tprivate boolean yesNoCursorPosition;\n\n\tprivate byte nextTick;\n\tprivate int scrollDistance;\n\tprivate boolean showDialog;\n\n\tprivate int subStringIterator;\n\tprivate byte tickCount = 0x0;\n\n\tprivate int totalDialogueLength;\n\tprivate DialogueType type;\n\n\tpublic Dialogue() {\n\t\tthis.lines = new ArrayList<>();\n\t\tthis.completedLines = new ArrayList<>();\n\t\tthis.subStringIterator = 0;\n\t\tthis.lineLength = 0;\n\t\tthis.totalDialogueLength = 0;\n\t\tthis.nextFlag = false;\n\t\tthis.simpleQuestionFlag = false;\n\t\tthis.simpleSpeechFlag = false;\n\t\tthis.scrollFlag = false;\n\t\tthis.scrollDistance = 0;\n\t\tthis.nextTick = 0x0;\n\t\tthis.lineIterator = 0;\n\t\tthis.showDialog = false;\n\t\tthis.type = null;\n\t\tthis.yesNoCursorPosition = true;\n\t\tthis.yesNoAnswerFlag = null; // Default\n\t\tthis.ignoreInputsFlag = false; // Default\n\t}\n\n\tpublic Dialogue(Dialogue dialogue) {\n\t\t// Deep copy\n\t\tthis.completedLines = new ArrayList<>();\n\t\tfor (String s : dialogue.completedLines)\n\t\t\tthis.completedLines.add(s);\n\n\t\tthis.lineIterator = dialogue.lineIterator;\n\t\tthis.lineLength = dialogue.lineLength;\n\t\tthis.lines = new ArrayList<>();\n\t\tfor (Map.Entry<String, Boolean> e : dialogue.lines)\n\t\t\tthis.lines.add(e);\n\n\t\tthis.nextFlag = dialogue.nextFlag;\n\t\tthis.simpleQuestionFlag = dialogue.simpleQuestionFlag;\n\t\tthis.simpleSpeechFlag = dialogue.simpleSpeechFlag;\n\t\tthis.yesNoCursorPosition = dialogue.yesNoCursorPosition;\n\t\tthis.yesNoAnswerFlag = dialogue.yesNoAnswerFlag;\n\t\tthis.nextTick = dialogue.nextTick;\n\t\tthis.scrollDistance = dialogue.scrollDistance;\n\t\tthis.scrollFlag = dialogue.scrollFlag;\n\t\tthis.showDialog = dialogue.showDialog;\n\n\t\tthis.subStringIterator = dialogue.subStringIterator;\n\t\tthis.tickCount = dialogue.tickCount;\n\t\tthis.totalDialogueLength = dialogue.totalDialogueLength;\n\t\tthis.type = dialogue.type;\n\t\tthis.ignoreInputsFlag = false;\n\t}\n\n\tpublic Boolean getAnswerToSimpleQuestion() {\n\t\tif (this.yesNoAnswerFlag == null)\n\t\t\treturn null;\n\t\treturn this.yesNoAnswerFlag.booleanValue();\n\t}\n\n\tpublic DialogueType getDialogueType() {\n\t\treturn this.type;\n\t}\n\n\tpublic boolean isDialogueCompleted() {\n\t\treturn (this.lineIterator >= this.lines.size());\n\t}\n\n\tpublic boolean isScrolling() {\n\t\treturn this.scrollFlag;\n\t}\n\n\tpublic void resetDialogue() {\n\t\tthis.subStringIterator = 0;\n\t\tthis.nextFlag = false;\n\t\tthis.simpleQuestionFlag = false;\n\t\tthis.simpleSpeechFlag = false;\n\t\tthis.scrollFlag = false;\n\t\tthis.scrollDistance = 0;\n\t\tthis.nextTick = 0x0;\n\t\tthis.lineIterator = 0;\n\t\tthis.showDialog = true;\n\t\tthis.yesNoCursorPosition = true;\n\t\tthis.yesNoAnswerFlag = null;\n\t\tthis.completedLines.clear();\n\t}\n\n\t/**\n\t * Checks if the dialogues were set / not cleared away.\n\t * \n\t * @return\n\t */\n\tpublic boolean isReady() {\n\t\treturn !this.lines.isEmpty();\n\t}\n\n\tpublic void setShowDialog(boolean showDialog) {\n\t\tthis.showDialog = showDialog;\n\t}\n\n\tpublic boolean isShowingDialog() {\n\t\treturn this.showDialog;\n\t}\n\n\tpublic void render(Scene output, Graphics graphics) {\n\t\tthis.render(output, graphics, 0, 6, 9, 2);\n\t}\n\n\tpublic void render(Scene output, Graphics graphics, int x, int y, int w, int h) {\n\t\tif (x < 0)\n\t\t\tx = 0;\n\t\tif (x > 9)\n\t\t\tx = 9;\n\t\tif (y < 0)\n\t\t\ty = 0;\n\t\tif (y > 8)\n\t\t\ty = 8;\n\t\tif (x + w > 9)\n\t\t\tw = 9 - x;\n\t\tif (y + h > 8)\n\t\t\th = 8 - y;\n\t\tif (this.showDialog) {\n\t\t\tswitch (this.type) {\n\t\t\t\tcase SPEECH: {\n\t\t\t\t\tthis.renderDialogBackground(output, x, y, w, h);\n\t\t\t\t\tthis.renderDialogBorderBox(output, x, y, w, h);\n\t\t\t\t\tif (this.nextFlag && this.nextTick < 0x8)\n\t\t\t\t\t\toutput.blit(Art.dialogue_next, MainComponent.GAME_WIDTH - 16, MainComponent.GAME_HEIGHT - 8);\n\t\t\t\t\tGraphics2D g2d = output.getBufferedImage().createGraphics();\n\t\t\t\t\tthis.renderText(g2d);\n\t\t\t\t\tg2d.dispose();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase QUESTION: {\n\t\t\t\t\tthis.renderDialogBackground(output, x, y, w, h);\n\t\t\t\t\tthis.renderDialogBorderBox(output, x, y, w, h);\n\t\t\t\t\tif (this.simpleQuestionFlag && !this.nextFlag) {\n\t\t\t\t\t\tthis.renderDialogBackground(output, 7, 3, 2, 2);\n\t\t\t\t\t\tthis.renderDialogBorderBox(output, 7, 3, 2, 2);\n\t\t\t\t\t\t// Offset by -3 for the Y axis.\n\t\t\t\t\t\toutput.blit(\n\t\t\t\t\t\t\tArt.dialogue_pointer, MainComponent.GAME_WIDTH - Tileable.WIDTH * 3 + 8,\n\t\t\t\t\t\t\tthis.yesNoCursorPosition ? (Tileable.HEIGHT * 4 - 3) : (Tileable.HEIGHT * 5 - 3)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\telse if (!this.simpleQuestionFlag && (this.nextFlag && this.nextTick < 0x8))\n\t\t\t\t\t\toutput.blit(Art.dialogue_next, MainComponent.GAME_WIDTH - 16, MainComponent.GAME_HEIGHT - 8);\n\t\t\t\t\tGraphics2D g2d = output.getBufferedImage().createGraphics();\n\t\t\t\t\tthis.renderText(g2d);\n\t\t\t\t\tthis.renderYesNoAnswerText(g2d);\n\t\t\t\t\tg2d.dispose();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase ALERT: {\n\t\t\t\t\tthis.renderDialogBackground(output, x, y, w, h);\n\t\t\t\t\tthis.renderDialogBorderBox(output, x, y, w, h);\n\t\t\t\t\tGraphics2D g2d = output.getBufferedImage().createGraphics();\n\t\t\t\t\tthis.renderText(g2d);\n\t\t\t\t\tg2d.dispose();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void renderYesNoAnswerText(Graphics g) {\n\t\tif (this.simpleQuestionFlag) {\n\t\t\tg.setFont(Art.font.deriveFont(8f));\n\t\t\tg.setColor(Color.black);\n\n\t\t\tfinal int X = Tileable.WIDTH * 8;\n\t\t\tfinal int YES_HEIGHT = Tileable.HEIGHT * 4 + 4;\n\t\t\tfinal int NO_HEIGHT = Tileable.HEIGHT * 5 + 4;\n\t\t\ttry {\n\t\t\t\tg.drawString(\"YES\", X, YES_HEIGHT);\n\t\t\t\tg.drawString(\"NO\", X, NO_HEIGHT);\n\t\t\t}\n\t\t\tcatch (Exception e) {}\n\t\t}\n\t}\n\n\t/**\n\t * <p>\n\t * Update method for NewDialogue class.\n\t * </p>\n\t * \n\t * <p>\n\t * <b>WARNING</b> : The code content of this tick() method is deliberately setup and designed in\n\t * such a way that it replicates the dialogues in Gen 1 and Gen 2 Pokémon games. May require a heavy\n\t * amount of refactoring/rewriting.\n\t * </p>\n\t */\n\tpublic void tick() {\n\t\tthis.handleDialogueUpdate();\n\n\t\ttry {\n\t\t\tif (this.simpleQuestionFlag) {\n\t\t\t\tif (!this.nextFlag && !this.scrollFlag) {\n\t\t\t\t\t// Making sure this doesn't trigger the \"Next\" arrow.\n\t\t\t\t\tthis.nextFlag = false;\n\n\t\t\t\t\tif (Game.keys.isUpPressed()) {\n\t\t\t\t\t\tGame.keys.upReceived();\n\t\t\t\t\t\t// Made it consistent with Inventory's menu selection, where it doesn't wrap\n\t\t\t\t\t\t// around.\n\t\t\t\t\t\tthis.yesNoCursorPosition = !this.yesNoCursorPosition;\n\t\t\t\t\t}\n\t\t\t\t\telse if (Game.keys.isDownPressed()) {\n\t\t\t\t\t\tGame.keys.downReceived();\n\t\t\t\t\t\t// Made it consistent with Inventory's menu selection, where it doesn't wrap\n\t\t\t\t\t\t// around.\n\t\t\t\t\t\tthis.yesNoCursorPosition = !this.yesNoCursorPosition;\n\t\t\t\t\t}\n\t\t\t\t\tif (Game.keys.isPrimaryPressed()) {\n\t\t\t\t\t\tGame.keys.primaryReceived();\n\t\t\t\t\t\t// The answer to simple questions have already been set by UP and DOWN.\n\t\t\t\t\t\tthis.yesNoAnswerFlag = this.yesNoCursorPosition;\n\t\t\t\t\t\tthis.simpleQuestionFlag = false;\n\t\t\t\t\t\tthis.closeDialog();\n\t\t\t\t\t}\n\t\t\t\t\telse if (Game.keys.isSecondaryPressed()) {\n\t\t\t\t\t\tGame.keys.secondaryReceived();\n\t\t\t\t\t\t// Always negative for cancel button.\n\t\t\t\t\t\tthis.yesNoAnswerFlag = false;\n\t\t\t\t\t\tthis.yesNoCursorPosition = false;\n\t\t\t\t\t\tthis.simpleQuestionFlag = false;\n\t\t\t\t\t\tthis.closeDialog();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (this.simpleSpeechFlag) {\n\t\t\t\tif (!this.nextFlag && !this.scrollFlag) {\n\t\t\t\t\tif (this.tickCount == 0x0) {\n\t\t\t\t\t\t// If the dialogue is not set to start scrolling, continue to increment the subStringIterator.\n\t\t\t\t\t\tif (!this.scrollFlag)\n\t\t\t\t\t\t\tthis.subStringIterator++;\n\n\t\t\t\t\t\t// Checks if the subStringIterator has encountered more than 2 whitespaces\n\t\t\t\t\t\tif (this.isLineBreak(this.subStringIterator)) {\n\t\t\t\t\t\t\t// We jump straight to the end of the line.\n\t\t\t\t\t\t\tthis.subStringIterator = this.lineLength;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (this.subStringIterator >= this.lineLength) {\n\t\t\t\t\t\t\tthis.subStringIterator %= this.lineLength;\n\t\t\t\t\t\t\tMap.Entry<String, Boolean> entry = this.lines.get(this.lineIterator);\n\t\t\t\t\t\t\tthis.completedLines.add(entry.getKey());\n\t\t\t\t\t\t\tthis.lineIterator++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (this.completedLines.size() == 2) {\n\t\t\t\t\t\t\tif (!this.scrollFlag) {\n\t\t\t\t\t\t\t\tswitch (this.type) {\n\t\t\t\t\t\t\t\t\tcase SPEECH:\n\t\t\t\t\t\t\t\t\t\tthis.nextFlag = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase QUESTION:\n\t\t\t\t\t\t\t\t\t\t// Must get to the end of the entire dialogue before asking for answers.\n\t\t\t\t\t\t\t\t\t\tif (this.lineIterator >= this.lines.size()) {\n\t\t\t\t\t\t\t\t\t\t\tthis.simpleQuestionFlag = true;\n\t\t\t\t\t\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tthis.nextFlag = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase ALERT:\n\t\t\t\t\t\t\t\t\t\tthis.nextFlag = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\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}\n\n\t\t\t\t\t// Speeds up text speed.\n\t\t\t\t\tif (this.type != DialogueType.ALERT) {\n\t\t\t\t\t\tif (Game.keys.isPrimaryPressed()) {\n\t\t\t\t\t\t\tGame.keys.primaryReceived();\n\t\t\t\t\t\t\tif (!this.ignoreInputsFlag && this.subStringIterator < this.lineLength) {\n\t\t\t\t\t\t\t\tthis.subStringIterator++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (Game.keys.isSecondaryPressed()) {\n\t\t\t\t\t\t\tGame.keys.secondaryReceived();\n\t\t\t\t\t\t\tif (!this.ignoreInputsFlag && this.subStringIterator < this.lineLength - 1) {\n\t\t\t\t\t\t\t\tthis.subStringIterator = this.lineLength - 1;\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}\n\n\t\t\t\t// Handles only the simplest forms of dialogues.\n\t\t\t\telse if (Game.keys.isPrimaryPressed()) {\n\t\t\t\t\tGame.keys.primaryReceived();\n\t\t\t\t\tthis.closeDialog();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Does not belong in either Speech dialogue or Question dialogue.\n\t\t\telse {\n\t\t\t\tif (!this.nextFlag && !this.scrollFlag) {\n\t\t\t\t\tif (this.tickCount == 0x0) {\n\t\t\t\t\t\tif (!this.scrollFlag)\n\t\t\t\t\t\t\tthis.subStringIterator++;\n\n\t\t\t\t\t\t// Checks if the subStringIterator has encountered more than 2 whitespaces\n\t\t\t\t\t\tif (this.isLineBreak(this.subStringIterator)) {\n\t\t\t\t\t\t\t// We jump straight to the end of the line.\n\t\t\t\t\t\t\tthis.subStringIterator = this.lineLength;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (this.subStringIterator >= this.lineLength) {\n\t\t\t\t\t\t\tthis.subStringIterator %= this.lineLength;\n\t\t\t\t\t\t\tMap.Entry<String, Boolean> entry = this.lines.get(this.lineIterator);\n\t\t\t\t\t\t\tthis.completedLines.add(entry.getKey());\n\t\t\t\t\t\t\tthis.lineIterator++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (this.completedLines.size() == 2) {\n\t\t\t\t\t\t\tif (!this.scrollFlag) {\n\t\t\t\t\t\t\t\tswitch (this.type) {\n\t\t\t\t\t\t\t\t\tcase SPEECH:\n\t\t\t\t\t\t\t\t\t\tthis.nextFlag = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase QUESTION:\n\t\t\t\t\t\t\t\t\t\t// Must get to the end of the entire dialogue before asking for answers.\n\t\t\t\t\t\t\t\t\t\tif (this.lineIterator >= this.lines.size()) {\n\t\t\t\t\t\t\t\t\t\t\tthis.simpleQuestionFlag = true;\n\t\t\t\t\t\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tthis.nextFlag = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase ALERT:\n\t\t\t\t\t\t\t\t\t\tthis.nextFlag = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\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}\n\n\t\t\t\t\t// Speeds up text speed.\n\t\t\t\t\tif (this.type != DialogueType.ALERT) {\n\t\t\t\t\t\tif (Game.keys.isPrimaryPressed()) {\n\t\t\t\t\t\t\tGame.keys.primaryReceived();\n\t\t\t\t\t\t\tif (!this.ignoreInputsFlag && this.subStringIterator < this.lineLength) {\n\t\t\t\t\t\t\t\tthis.subStringIterator++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (Game.keys.isSecondaryPressed()) {\n\t\t\t\t\t\t\tGame.keys.secondaryReceived();\n\t\t\t\t\t\t\tif (!this.ignoreInputsFlag && this.subStringIterator < this.lineLength - 1) {\n\t\t\t\t\t\t\t\tthis.subStringIterator = this.lineLength - 1;\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}\n\n\t\t\t\tif (Game.keys.isPrimaryPressed() || Game.keys.isSecondaryPressed()) {\n\t\t\t\t\tif (Game.keys.isPrimaryPressed())\n\t\t\t\t\t\tGame.keys.primaryReceived();\n\t\t\t\t\tif (Game.keys.isSecondaryPressed())\n\t\t\t\t\t\tGame.keys.secondaryReceived();\n\t\t\t\t\tswitch (this.type) {\n\t\t\t\t\t\tcase SPEECH:\n\t\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\t\tthis.scrollFlag = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase QUESTION:\n\t\t\t\t\t\t\t// Must get to the end of the entire dialogue before asking questions.\n\t\t\t\t\t\t\tthis.simpleQuestionFlag = false;\n\t\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\t\tthis.scrollFlag = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase ALERT:\n\t\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\t\tthis.scrollFlag = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (this.scrollFlag) {\n\t\t\t\t\tif (this.lineIterator >= this.lines.size()) {\n\t\t\t\t\t\tswitch (this.type) {\n\t\t\t\t\t\t\tcase QUESTION:\n\t\t\t\t\t\t\t\tthis.simpleQuestionFlag = true;\n\t\t\t\t\t\t\t\tthis.scrollFlag = false;\n\t\t\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase SPEECH:\n\t\t\t\t\t\t\t\tthis.closeDialog();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\tcase ALERT:\n\t\t\t\t\t\t\t\tthis.closeDialog();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tthis.scrollDistance += 8;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tif (this.lineIterator >= this.lines.size()) {\n\t\t\t\tif (this.scrollFlag) {\n\t\t\t\t\tthis.closeDialog();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tswitch (this.type) {\n\t\t\t\t\t\tcase SPEECH:\n\t\t\t\t\t\tcase ALERT:\n\t\t\t\t\t\t\tthis.nextFlag = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase QUESTION:\n\t\t\t\t\t\t\tthis.simpleQuestionFlag = true;\n\t\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean yesNoQuestionHasBeenAnswered() {\n\t\treturn this.yesNoAnswerFlag != null;\n\t}\n\n\tpublic void closeDialog() {\n\t\tthis.showDialog = false;\n\t}\n\n\t/**\n\t * Clears dialogues and unsets the dialogue flag.\n\t */\n\tpublic void clearDialogueLines() {\n\t\tif (!this.lines.isEmpty())\n\t\t\tthis.lines.clear();\n\t}\n\n\tprivate void renderText(Graphics g) {\n\t\tfinal int X = 8;\n\t\tfinal int Y1 = 120;\n\t\tfinal int Y2 = 136;\n\t\tfinal Rectangle rect = new Rectangle(X, Y1 - Tileable.HEIGHT, MainComponent.GAME_WIDTH - 16, Tileable.HEIGHT * 2);\n\n\t\tg.setFont(Art.font.deriveFont(8f));\n\t\tg.setColor(Color.black);\n\n\t\tString string = null;\n\t\ttry {\n\t\t\tswitch (this.completedLines.size()) {\n\t\t\t\tcase 0:\n\t\t\t\t\t// None completed.\n\t\t\t\t\tstring = this.lines.get(this.lineIterator).getKey();\n\t\t\t\t\tif (this.subStringIterator > string.length()) {\n\t\t\t\t\t\tg.drawString(string.substring(0, string.length()), X, Y1);\n\t\t\t\t\t\tthis.subStringIterator = this.lineLength;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tg.drawString(string.substring(0, this.subStringIterator), X, Y1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\t// One line completed.\n\t\t\t\t\tg.drawString(this.completedLines.get(0), X, Y1);\n\t\t\t\t\tstring = this.lines.get(this.lineIterator).getKey();\n\t\t\t\t\tif (this.subStringIterator > string.length()) {\n\t\t\t\t\t\tg.drawString(string.substring(0, string.length()), X, Y2);\n\t\t\t\t\t\tthis.subStringIterator = this.lineLength;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tg.drawString(string.substring(0, this.subStringIterator), X, Y2);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\t// Two lines completed.\n\t\t\t\t\tif (!this.scrollFlag) {\n\t\t\t\t\t\tg.drawString(this.completedLines.get(0), X, Y1);\n\t\t\t\t\t\tg.drawString(this.completedLines.get(1), X, Y2);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// Time to scroll.\n\t\t\t\t\t\t// DEBUG: Needs testing to see if there's any problem with\n\t\t\t\t\t\t// it.\n\t\t\t\t\t\tGraphics g_clipped = g.create();\n\t\t\t\t\t\tg_clipped.setClip(rect.x, rect.y, rect.width, rect.height);\n\t\t\t\t\t\tg_clipped.drawString(this.completedLines.get(0), X, Y1 - this.scrollDistance);\n\t\t\t\t\t\tg_clipped.drawString(this.completedLines.get(1), X, Y2 - this.scrollDistance);\n\t\t\t\t\t\tif (this.tickCount == 0x0) {\n\t\t\t\t\t\t\tif (this.scrollDistance >= Y2 - Y1) {\n\t\t\t\t\t\t\t\tthis.scrollFlag = false;\n\t\t\t\t\t\t\t\tthis.scrollDistance = 0;\n\t\t\t\t\t\t\t\tthis.subStringIterator = 0;\n\t\t\t\t\t\t\t\tthis.completedLines.remove(0);\n\t\t\t\t\t\t\t\tthis.lines.get(this.lineIterator).setValue(true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tg_clipped.dispose();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {}\n\t}\n\n\t/**\n\t * This is to render the information dialogue box that will appear in the lower left corner when the\n\t * Main Menu is displayed.\n\t * \n\t * @param output\n\t * @param x\n\t * @param y\n\t * @param centerWidth\n\t * @param centerHeight\n\t */\n\tpublic void renderInformationBox(Scene output, int x, int y, int centerWidth, int centerHeight) {\n\t\toutput.blit(Art.dialogue_top_left, x * Tileable.WIDTH, y * Tileable.HEIGHT);\n\t\tfor (int i = 0; i < centerWidth - 1; i++) {\n\t\t\toutput.blit(Art.dialogue_top, ((x + 1) * Tileable.WIDTH) + (i * Tileable.WIDTH), y * Tileable.HEIGHT);\n\t\t}\n\t\toutput.blit(Art.dialogue_top_right, (x + centerWidth) * Tileable.WIDTH, y * Tileable.HEIGHT);\n\n\t\tfor (int j = 0; j < centerHeight - 1; j++) {\n\t\t\toutput.blit(Art.dialogue_left, x * Tileable.WIDTH, ((y + 1) * Tileable.HEIGHT) + j * Tileable.HEIGHT);\n\t\t\tfor (int i = 0; i < centerWidth - 1; i++) {\n\t\t\t\toutput.blit(\n\t\t\t\t\tArt.dialogue_background, ((x + 1) * Tileable.WIDTH) + (i * Tileable.WIDTH),\n\t\t\t\t\t((y + 1) * Tileable.HEIGHT) + j * Tileable.HEIGHT\n\t\t\t\t);\n\t\t\t}\n\t\t\toutput.blit(Art.dialogue_right, (x + centerWidth) * Tileable.WIDTH, ((y + 1) * Tileable.HEIGHT) + j * Tileable.HEIGHT);\n\t\t}\n\n\t\toutput.blit(Art.dialogue_bottom_left, x * Tileable.WIDTH, ((y + centerHeight) * Tileable.HEIGHT));\n\t\tfor (int i = 0; i < centerWidth - 1; i++) {\n\t\t\toutput.blit(\n\t\t\t\tArt.dialogue_bottom, ((x + 1) * Tileable.WIDTH) + (i * Tileable.WIDTH),\n\t\t\t\t((y + centerHeight) * Tileable.HEIGHT)\n\t\t\t);\n\t\t}\n\t\toutput.blit(Art.dialogue_bottom_right, (x + centerWidth) * Tileable.WIDTH, ((y + centerHeight) * Tileable.HEIGHT));\n\t}\n\n\t/**\n\t * This is to render the information dialogue box that will appear in the lower left corner when the\n\t * Main Menu is displayed.\n\t * \n\t * This method uses the default X, Y, center width, and center height values.\n\t * \n\t * @param output\n\t */\n\tpublic void renderInformationBox(Scene output) {\n\t\tthis.renderInformationBox(output, 0, 6, 9, 2);\n\t}\n\n\t// ======================================================\n\t// Private methods\n\t// ======================================================\n\n\tprivate void handleDialogueUpdate() {\n\t\tint count = 0;\n\t\ttry {\n\t\t\tfor (int i = 0; i < this.lineIterator; i++) {\n\t\t\t\tcount += this.lines.get(i).getKey().length();\n\t\t\t\tif (i != this.lines.size() - 1)\n\t\t\t\t\tcount += 1;\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tcount = 0;\n\t\t}\n\n\t\tif (this.nextFlag) {\n\t\t\tswitch (this.type) {\n\t\t\t\tcase QUESTION: {\n\t\t\t\t\tif (count >= this.totalDialogueLength) {\n\t\t\t\t\t\tthis.simpleQuestionFlag = true;\n\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\tthis.scrollFlag = false;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.nextTick++;\n\t\t\t\t\t\tif (this.nextTick > Dialogue.MAX_TICK_DELAY)\n\t\t\t\t\t\t\tthis.nextTick = Dialogue.ZERO_TICK;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase SPEECH: {\n\t\t\t\t\tthis.nextTick++;\n\t\t\t\t\tif (this.nextTick > Dialogue.MAX_TICK_DELAY)\n\t\t\t\t\t\tthis.nextTick = Dialogue.ZERO_TICK;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase ALERT: {\n\t\t\t\t\tthis.nextTick++;\n\t\t\t\t\tif (this.nextTick > Dialogue.MAX_TICK_DELAY)\n\t\t\t\t\t\tthis.nextTick = Dialogue.ZERO_TICK;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (count < this.totalDialogueLength) {\n\t\t\tif (!this.scrollFlag) {\n\t\t\t\tthis.tickCount++;\n\t\t\t\tif (this.tickCount > Dialogue.CHARACTER_TICK_DELAY)\n\t\t\t\t\tthis.tickCount = Dialogue.ZERO_TICK;\n\t\t\t}\n\t\t\t// else {\n\t\t\t// //Just speed up the dialogue.\n\t\t\t// this.tickCount = Dialogue.CHARACTER_TICK_DELAY;\n\t\t\t// }\n\t\t}\n\t\telse {\n\t\t\tif (this.lineIterator >= this.lines.size()) {\n\t\t\t\tswitch (this.type) {\n\t\t\t\t\tcase QUESTION:\n\t\t\t\t\t\tthis.simpleQuestionFlag = true;\n\t\t\t\t\t\tthis.scrollFlag = false;\n\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase SPEECH:\n\t\t\t\t\t\tthis.simpleSpeechFlag = true;\n\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase ALERT:\n\t\t\t\t\t\tthis.simpleSpeechFlag = true;\n\t\t\t\t\t\tthis.nextFlag = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tMap.Entry<String, Boolean> entry = this.lines.get(this.lineIterator);\n\t\t\t\tthis.completedLines.add(entry.getKey());\n\t\t\t\tthis.lineIterator++;\n\t\t\t\tswitch (this.type) {\n\t\t\t\t\tcase SPEECH:\n\t\t\t\t\t\tthis.nextFlag = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase QUESTION:\n\t\t\t\t\t\tthis.simpleQuestionFlag = true;\n\t\t\t\t\t\tthis.nextFlag = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase ALERT:\n\t\t\t\t\t\tthis.nextFlag = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void renderDialogBackground(Scene output, int x, int y, int centerWidth, int centerHeight) {\n\t\tfor (int j = 0; j < centerHeight - 1; j++) {\n\t\t\tfor (int i = 0; i < centerWidth - 1; i++) {\n\t\t\t\toutput.blit(\n\t\t\t\t\tArt.dialogue_background, ((x + 1) * Tileable.WIDTH) + (i * Tileable.WIDTH),\n\t\t\t\t\t((y + 1) * Tileable.HEIGHT) + j * Tileable.HEIGHT\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void renderDialogBorderBox(Scene output, int x, int y, int centerWidth, int centerHeight) {\n\t\toutput.blit(Art.dialogue_top_left, x * Tileable.WIDTH, y * Tileable.HEIGHT);\n\t\tfor (int i = 0; i < centerWidth - 1; i++) {\n\t\t\toutput.blit(Art.dialogue_top, ((x + 1) * Tileable.WIDTH) + (i * Tileable.WIDTH), y * Tileable.HEIGHT);\n\t\t}\n\t\toutput.blit(Art.dialogue_top_right, (x + centerWidth) * Tileable.WIDTH, y * Tileable.HEIGHT);\n\n\t\tfor (int j = 0; j < centerHeight - 1; j++) {\n\t\t\toutput.blit(Art.dialogue_left, x * Tileable.WIDTH, ((y + 1) * Tileable.HEIGHT) + j * Tileable.HEIGHT);\n\t\t\toutput.blit(Art.dialogue_right, (x + centerWidth) * Tileable.WIDTH, ((y + 1) * Tileable.HEIGHT) + j * Tileable.HEIGHT);\n\t\t}\n\n\t\toutput.blit(Art.dialogue_bottom_left, x * Tileable.WIDTH, ((y + centerHeight) * Tileable.HEIGHT));\n\t\tfor (int i = 0; i < centerWidth - 1; i++) {\n\t\t\toutput.blit(\n\t\t\t\tArt.dialogue_bottom, ((x + 1) * Tileable.WIDTH) + (i * Tileable.WIDTH),\n\t\t\t\t((y + centerHeight) * Tileable.HEIGHT)\n\t\t\t);\n\t\t}\n\t\toutput.blit(Art.dialogue_bottom_right, (x + centerWidth) * Tileable.WIDTH, ((y + centerHeight) * Tileable.HEIGHT));\n\t}\n\n\tpublic List<String> getCompletedLines() {\n\t\treturn this.completedLines;\n\t}\n\n\tpublic void setCompletedLines(ArrayList<String> completedLines) {\n\t\tthis.completedLines = completedLines;\n\t}\n\n\tpublic int getLineIterator() {\n\t\treturn this.lineIterator;\n\t}\n\n\tpublic void setLineIterator(int lineIterator) {\n\t\tthis.lineIterator = lineIterator;\n\t}\n\n\tpublic int getLineLength() {\n\t\treturn this.lineLength;\n\t}\n\n\tpublic void setLineLength(int lineLength) {\n\t\tthis.lineLength = lineLength;\n\t}\n\n\tpublic List<Map.Entry<String, Boolean>> getLines() {\n\t\treturn this.lines;\n\t}\n\n\tpublic void setLines(List<Map.Entry<String, Boolean>> lines) {\n\t\tthis.lines = lines;\n\t}\n\n\tpublic boolean isSimpleQuestionFlag() {\n\t\treturn this.simpleQuestionFlag;\n\t}\n\n\tpublic void setSimpleQuestionFlag(boolean simpleQuestionFlag) {\n\t\tthis.simpleQuestionFlag = simpleQuestionFlag;\n\t}\n\n\tpublic boolean isSimpleSpeechFlag() {\n\t\treturn this.simpleSpeechFlag;\n\t}\n\n\tpublic void setSimpleSpeechFlag(boolean simpleSpeechFlag) {\n\t\tthis.simpleSpeechFlag = simpleSpeechFlag;\n\t}\n\n\tpublic boolean isNextFlag() {\n\t\treturn this.nextFlag;\n\t}\n\n\tpublic void setNextFlag(boolean nextFlag) {\n\t\tthis.nextFlag = nextFlag;\n\t}\n\n\tpublic boolean isScrollFlag() {\n\t\treturn this.scrollFlag;\n\t}\n\n\tpublic void setScrollFlag(boolean scrollFlag) {\n\t\tthis.scrollFlag = scrollFlag;\n\t}\n\n\tpublic Boolean getYesNoAnswerFlag() {\n\t\treturn this.yesNoAnswerFlag;\n\t}\n\n\tpublic void setYesNoAnswerFlag(Boolean yesNoAnswerFlag) {\n\t\tthis.yesNoAnswerFlag = yesNoAnswerFlag;\n\t}\n\n\tpublic boolean isYesNoCursorPosition() {\n\t\treturn this.yesNoCursorPosition;\n\t}\n\n\tpublic void setYesNoCursorPosition(boolean yesNoCursorPosition) {\n\t\tthis.yesNoCursorPosition = yesNoCursorPosition;\n\t}\n\n\tpublic byte getNextTick() {\n\t\treturn this.nextTick;\n\t}\n\n\tpublic void setNextTick(byte nextTick) {\n\t\tthis.nextTick = nextTick;\n\t}\n\n\tpublic int getScrollDistance() {\n\t\treturn this.scrollDistance;\n\t}\n\n\tpublic void setScrollDistance(int scrollDistance) {\n\t\tthis.scrollDistance = scrollDistance;\n\t}\n\n\tpublic int getSubStringIterator() {\n\t\treturn this.subStringIterator;\n\t}\n\n\tpublic void setSubStringIterator(int subStringIterator) {\n\t\tthis.subStringIterator = subStringIterator;\n\t}\n\n\tpublic byte getTickCount() {\n\t\treturn this.tickCount;\n\t}\n\n\tpublic void setTickCount(byte tickCount) {\n\t\tthis.tickCount = tickCount;\n\t}\n\n\tpublic int getTotalDialogueLength() {\n\t\treturn this.totalDialogueLength;\n\t}\n\n\tpublic void setTotalDialogueLength(int totalDialogueLength) {\n\t\tthis.totalDialogueLength = totalDialogueLength;\n\t}\n\n\tpublic DialogueType getType() {\n\t\treturn this.type;\n\t}\n\n\tpublic void setType(DialogueType type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic void setIgnoreInputs(boolean flag) {\n\t\tthis.ignoreInputsFlag = flag;\n\t}\n\n\tpublic boolean getIgnoreInputs() {\n\t\treturn this.ignoreInputsFlag;\n\t}\n\n\tpublic String getCurrentLine() {\n\t\tMap.Entry<String, Boolean> entry = this.getLines().get(this.lineIterator);\n\t\treturn entry.getKey();\n\t}\n\n\t/**\n\t * This checks to see if there is a line break in the dialogue.\n\t * <p>\n\t * A line break is defined to be \"two whitespaces inside the dialogue's line\".\n\t * \n\t * @param subStringIterator\n\t * - The string iterator marking where the game must render text to, on the current line.\n\t * @return\n\t */\n\tpublic boolean isLineBreak(int subStringIterator) {\n\t\tString currentLine = this.getCurrentLine();\n\t\ttry {\n\t\t\tchar previousChar = currentLine.charAt(subStringIterator - 1);\n\t\t\tchar currentChar = currentLine.charAt(subStringIterator);\n\t\t\tif (previousChar == ' ' && currentChar == ' ') {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tcatch (IndexOutOfBoundsException e) {\n\t\t\t// The substring iterator is at position 0, or it is at the end of the current line.\n\t\t\t// We do actually expect an exception to be thrown.\n\t\t}\n\t\treturn false;\n\t}\n}",
"public class Player extends Character {\n\tpublic static boolean isMovementsLocked() {\n\t\treturn Player.movementLock;\n\t}\n\n\tpublic static void lockMovements() {\n\t\tPlayer.movementLock = true;\n\t}\n\n\tpublic static void unlockMovements() {\n\t\tPlayer.movementLock = false;\n\t}\n\n\tpublic Keys keys;\n\tprivate Entity interactingEntity = null;\n\tprivate Inventory inventory;\n\n\t// These are based on the art sprite in the resource folder. The numbers are\n\t// used to get elements from a 2D array.\n\tprivate int walking = 0;\n\n\t// These are animation-related locks specific to the player.\n\tprivate boolean isLockedJumping;\n\n\tprivate boolean isInWater;\n\tprivate boolean isOnBicycle;\n\tprivate boolean isSprinting;\n\tprivate boolean isColliding;\n\n\t// This is a player character lock.\n\tprivate static boolean movementLock;\n\n\tprivate boolean isInteractionEnabled;\n\tprivate boolean jumpHeightSignedFlag = false;\n\tprivate int varyingJumpHeight = 0;\n\tprivate boolean automaticMode;\n\n\t// This variable is set to true, no matter what, in the Player class if the\n\t// player tries to do action that's not allowed.\n\t// It must be turned off (set to False) somewhere else in other classes. By\n\t// design!\n\tpublic boolean warningsTriggered;\n\n\t/**\n\t * Constructs a Player object in the game. This must be loaded in ONCE.\n\t *\n\t * @param Keys\n\t * Takes in the Keys object the input handler is controlling. It must not take in an\n\t * uncontrolled Keys object.\n\t */\n\tpublic Player(Game game) {\n\t\tthis.keys = Game.keys;\n\t\tthis.automaticMode = false;\n\t\tthis.setCharacterPlayable(true);\n\t\tthis.setCenterCamPosition(game.getBaseScreen());\n\t\tthis.setInventory(game.getInventory());\n\t}\n\n\t/**\n\t * Forces the player to continue to walk for more than 1 tile.\n\t *\n\t * Used when the player has entered an entrance.\n\t *\n\t * @return Nothing.\n\t */\n\tpublic void forceLockWalking() {\n\t\tthis.keys.resetInputs();\n\t\tthis.isLockedWalking = true;\n\t\tthis.isFacingBlocked[0] = this.isFacingBlocked[1] = this.isFacingBlocked[2] = this.isFacingBlocked[3] = false;\n\t\tif (this.xAccel == 0 && this.yAccel == 0) {\n\t\t\tswitch (this.getFacing()) {\n\t\t\t\tcase UP:\n\t\t\t\t\tthis.yAccel--;\n\t\t\t\t\tbreak;\n\t\t\t\tcase DOWN:\n\t\t\t\t\tthis.yAccel++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LEFT:\n\t\t\t\t\tthis.xAccel--;\n\t\t\t\t\tbreak;\n\t\t\t\tcase RIGHT:\n\t\t\t\t\tthis.xAccel++;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Changes the player's state to Walking.\n\t */\n\tpublic void getsOffBicycle() {\n\t\tPlayer.lockMovements();\n\t\tnew Thread(() -> {\n\t\t\ttry {\n\t\t\t\tThread.sleep(250);\n\t\t\t}\n\t\t\tcatch (final InterruptedException e1) {}\n\t\t\tPlayer.this.isOnBicycle = false;\n\t\t\ttry {\n\t\t\t\tThread.sleep(250);\n\t\t\t}\n\t\t\tcatch (final InterruptedException e2) {}\n\t\t\tPlayer.unlockMovements();\n\t\t}).start();\n\t}\n\n\t@Override\n\tpublic int getXInArea() {\n\t\t// Returns area position X.\n\t\tint result = (this.xAreaPosition / Tileable.WIDTH);\n\t\tif (this.isLockedWalking)\n\t\t\tswitch (this.getFacing()) {\n\t\t\t\tcase LEFT:\n\t\t\t\t\tbreak;\n\t\t\t\tcase RIGHT:\n\t\t\t\t\tresult += 1;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic int getYInArea() {\n\t\t// Returns area position Y.\n\t\tint result = (this.yAreaPosition / Tileable.HEIGHT);\n\t\tif (this.isLockedWalking)\n\t\t\tswitch (this.getFacing()) {\n\t\t\t\tcase UP:\n\t\t\t\t\tbreak;\n\t\t\t\tcase DOWN:\n\t\t\t\t\tresult += 1;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Changes the player's state to Surfing.\n\t */\n\tpublic void goesInWater() {\n\t\tthis.isInWater = true;\n\t\tthis.isOnBicycle = false;\n\t\tthis.isSprinting = false;\n\t}\n\n\t/**\n\t * Changes the player's state to Riding.\n\t */\n\tpublic void hopsOnBike() {\n\t\tthis.isInWater = false;\n\t\tthis.isOnBicycle = true;\n\t\tthis.isSprinting = false;\n\t}\n\n\t/**\n\t * Lets the player interact with the data tile ID.\n\t *\n\t * @param dataColor\n\t * The tile ID's full data (the color of the tile).\n\t */\n\t@Override\n\tpublic void interact(Area area, Entity entity) {\n\t\tPixelData data = entity.getPixelData();\n\t\tfinal int dataColor = data.getColor();\n\t\tfinal int alpha = (dataColor >> 24) & 0xFF;\n\n\t\t// Entity pixel data identification check.\n\t\tswitch (alpha) {\n\t\t\tcase 0x03: {\n\t\t\t\t// Obstacles\n\t\t\t\t// Red color values indicate the type of obstacles to filter:\n\t\t\t\t/*\n\t\t\t\tint red = (dataColor >> 16) & 0xFF;\n\t\t\t\tswitch (red) {\n\t\t\t\t\tcase 0x00: // Small tree\n\t\t\t\t\tcase 0x01: // Logs\n\t\t\t\t\tcase 0x02: // Planks\n\t\t\t\t\tcase 0x03: // Scaffolding Left\n\t\t\t\t\tcase 0x04: // Scaffolding Right\n\t\t\t\t\tcase 0x05: // Sign\n\t\t\t\t}\n\t\t\t\t*/\n\t\t\t\tif (!(entity instanceof Obstacle)) {\n\t\t\t\t\tDebug.error(\"This shouldn't be happening. Obstacle is not an instanceof Entity.\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// Common player-obstacle interaction code logic.\n\t\t\t\tif (this.isInteracting() && entity.isInteracting()) {\n\t\t\t\t\tthis.startInteraction(entity);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.stopInteraction();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 0x0A: {// Item\n\t\t\t\tif (!(entity instanceof Item item)) {\n\t\t\t\t\tDebug.error(\"This shouldn't be happening. Item is not an instanceof Entity.\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// Common player-item interaction code logic.\n\t\t\t\tif (this.isInteracting() && item.isInteracting()) {\n\t\t\t\t\tthis.startInteraction(item);\n\t\t\t\t\tif (!item.isPickedUp()) {\n\t\t\t\t\t\t// Order of operations is important here. Pick the item up, then check if the item has finished\n\t\t\t\t\t\t// being picked up, then add the item and set the changed pixel data in the area once detected.\n\t\t\t\t\t\titem.pick();\n\t\t\t\t\t\tif (item.isFinishedPickingUp()) {\n\t\t\t\t\t\t\tthis.inventory.addItem(item);\n\t\t\t\t\t\t\tarea.updateItem(item);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.stopInteraction();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.stopInteraction();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 0x0E: {// Characters/NPCs\n\t\t\t\tCharacter character = (Character) entity;\n\t\t\t\tif (this.isInteracting() && character.isInteracting()) {\n\t\t\t\t\tthis.startInteraction(character);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.stopInteraction();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Stop the player from interacting with anything.\n\t\t\t\tif (this.isInteracting()) {\n\t\t\t\t\tthis.stopInteraction();\n\t\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean isColliding() {\n\t\treturn this.isColliding;\n\t}\n\n\tpublic boolean isFacingAt(final int x, final int y) {\n\t\tint xTgt = 0, yTgt = 0;\n\t\tswitch (this.getFacing()) {\n\t\t\tcase Character.UP:\n\t\t\t\txTgt = this.getXInArea();\n\t\t\t\tyTgt = this.getYInArea() - 1;\n\t\t\t\tbreak;\n\t\t\tcase Character.DOWN:\n\t\t\t\txTgt = this.getXInArea();\n\t\t\t\tyTgt = this.getYInArea() + 1;\n\t\t\t\tbreak;\n\t\t\tcase Character.LEFT:\n\t\t\t\txTgt = this.getXInArea() - 1;\n\t\t\t\tyTgt = this.getYInArea();\n\t\t\t\tbreak;\n\t\t\tcase Character.RIGHT:\n\t\t\t\txTgt = this.getXInArea() + 1;\n\t\t\t\tyTgt = this.getYInArea();\n\t\t\t\tbreak;\n\t\t}\n\t\treturn ((x == xTgt) && (y == yTgt));\n\t}\n\n\t@Override\n\tpublic boolean isInteracting() {\n\t\treturn this.isInteractionEnabled;\n\t}\n\n\t/**\n\t * Returns the player's state (Surfing or Walking).\n\t *\n\t * @return True, if player is surfing. False, if player is walking on land.\n\t */\n\tpublic boolean isInWater() {\n\t\treturn this.isInWater;\n\t}\n\n\tpublic boolean isLockedJumping() {\n\t\treturn this.isLockedJumping;\n\t}\n\n\t/**\n\t * Checks to see if the player is currently locked to walking.\n\t *\n\t * @return True, if the player is walking right now. False, otherwise.\n\t */\n\t@Override\n\tpublic boolean isLockedWalking() {\n\t\treturn this.isLockedWalking;\n\t}\n\n\t/**\n\t * Returns the player's state (Riding or Not Riding Bicycle).\n\t *\n\t * @return True, if player is riding. False, if player is not.\n\t */\n\tpublic boolean isRidingBicycle() {\n\t\treturn this.isOnBicycle;\n\t}\n\n\t/**\n\t * Returns the player's state (Running or not running).\n\t *\n\t * @return True, if player is running/sprinting. False, if player is not.\n\t */\n\tpublic boolean isSprinting() {\n\t\treturn this.isSprinting;\n\t}\n\n\t/**\n\t * <p>\n\t * Handles the 4 surrounding tiles around the player character, in the cardinal directions of north,\n\t * west, south, and east. Once the player is interacting with one of the tiles, the area will\n\t * remember and mark the tile's interaction ID, and pass it to the OverWorld to handle.\n\t * </p>\n\t *\n\t * @return Nothing.\n\t */\n\tpublic void handleSurroundingTiles(Area area) {\n\t\tthis.setAllBlockingDirections(false, false, false, false);\n\t\tboolean upDirection = this.checkSurroundingData(area, 0, -1);\n\t\tboolean downDirection = this.checkSurroundingData(area, 0, 1);\n\t\tboolean leftDirection = this.checkSurroundingData(area, -1, 0);\n\t\tboolean rightDirection = this.checkSurroundingData(area, 1, 0);\n\t\tthis.setAllBlockingDirections(upDirection, downDirection, leftDirection, rightDirection);\n\n\t\tint playerAreaX = this.getXInArea();\n\t\tint playerAreaY = this.getYInArea();\n\t\ttry {\n\t\t\tif (this.isInteracting()) {\n\t\t\t\tEntity entity = null;\n\t\t\t\tswitch (this.getFacing()) {\n\t\t\t\t\tcase Character.UP:\n\t\t\t\t\t\tentity = area.getEntity(playerAreaX, playerAreaY - 1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Character.DOWN:\n\t\t\t\t\t\tentity = area.getEntity(playerAreaX, playerAreaY + 1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Character.LEFT:\n\t\t\t\t\t\tentity = area.getEntity(playerAreaX - 1, playerAreaY);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Character.RIGHT:\n\t\t\t\t\t\tentity = area.getEntity(playerAreaX + 1, playerAreaY);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (entity != null) {\n\t\t\t\t\tthis.interact(area, entity);\n\t\t\t\t}\n\t\t\t\tif (entity == null && this.interactingEntity != null && this.isInteractionEnabled) {\n\t\t\t\t\tif (this.interactingEntity instanceof Obstacle o) {\n\t\t\t\t\t\tTriggerData data = this.interactingEntity.getTriggerData();\n\t\t\t\t\t\tif (data.hasFinishedInteracting())\n\t\t\t\t\t\t\tthis.stopInteraction();\n\t\t\t\t\t}\n\t\t\t\t\telse if (this.interactingEntity instanceof Character c) {\n\t\t\t\t\t\tthis.stopInteraction();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tDebug.error(\"Encountered an error while handling surrounding tiles.\", e);\n\t\t\tthis.stopInteraction();\n\t\t}\n\t}\n\n\t/**\n\t * Checks the pixel data and sets properties according to the documentation provided. The tile the\n\t * pixel data is representing determines whether it should allow or block the player from walking\n\t * towards it.\n\t * <p>\n\t * If it's intended for the interacting entity to respond to key presses while dialogues are shown,\n\t * you must put a {@linkplain Player#isInteracting isInteracting()} boolean check before checking to\n\t * see if the entity is being interacted.\n\t * <p>\n\t * In short, this is the method call that works out the collision detection/response in the game.\n\t *\n\t * @param xOffset\n\t * Sets the offset of the PixelData it should check by the X axis.\n\t * @param yOffset\n\t * Sets the offset of the PixelData it should check by the Y axis.\n\t * @return The value determining if this PixelData is to block or allow the player to pass/walk/jump\n\t * through. Returns true to block the player from walking from the player's last position to\n\t * this tile. Returns false to allow player to walk from the player's last position to this\n\t * tile.\n\t */\n\tprivate boolean checkSurroundingData(Area area, int xOffset, int yOffset) {\n\t\tPixelData data = null;\n\t\tEntity entity = null;\n\t\tint playerAreaX = this.getXInArea();\n\t\tint playerAreaY = this.getYInArea();\n\t\ttry {\n\t\t\tdata = area.getPixelData(playerAreaX + xOffset, playerAreaY + yOffset);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\t// This means it is out of the area boundaries.\n\t\t\treturn true;\n\t\t}\n\n\t\t// Characters / NPCs - Has a higher priority over tilesets.\n\t\ttry {\n\t\t\tif (this.isInteracting())\n\t\t\t\treturn true;\n\t\t\tentity = area.findCharacterAt(playerAreaX + xOffset, playerAreaY + yOffset);\n\t\t\tif (entity != null && entity instanceof Character c) {\n\t\t\t\tboolean result = false;\n\t\t\t\tif (this.isFacingAt(playerAreaX + xOffset, playerAreaY + yOffset) && Game.keys.isPrimaryPressed()) {\n\t\t\t\t\tGame.keys.primaryReceived();\n\t\t\t\t\tif (!c.isLockedWalking())\n\t\t\t\t\t\tthis.startInteraction(entity);\n\t\t\t\t}\n\n\t\t\t\t// Since characters can move, we need to check for the entity's current and old positions.\n\t\t\t\tint oldX = c.getOldX();\n\t\t\t\tint oldY = c.getOldY();\n\t\t\t\tint preX = c.getPredictedX();\n\t\t\t\tint preY = c.getPredictedY();\n\t\t\t\tint x = playerAreaX + xOffset;\n\t\t\t\tint y = playerAreaY + yOffset;\n\t\t\t\tif ((oldX == x && oldY == y) || (oldX == x && preY == y) || (preX == x && oldY == y) || (preX == x && preY == y)) {\n\t\t\t\t\tresult = true;\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tentity = null;\n\t\t}\n\n\t\tint color = data.getColor();\n\t\tint alpha = (color >> 24) & 0xFF;\n\t\tint red = (color >> 16) & 0xFF;\n\t\t// int green = (color >> 8) & 0xFF;\n\t\t// int blue = color & 0xFF;\n\t\tswitch (alpha) {\n\t\t\tcase 0x01: // Paths\n\t\t\t\treturn false;\n\t\t\tcase 0x02: // Ledge\n\t\t\t{\n\t\t\t\tswitch (red) {\n\t\t\t\t\t/*\n\t\t\t\t\t * TODO: Incorporate pixel data facingsBlocked variable to this section.\n\t\t\t\t\t * Currently, the facingsBlocked[] variable for each pixel data isn't used.\n\t\t\t\t\t */\n\t\t\t\t\tcase 0x00: { // Bottom\n\t\t\t\t\t\tint y = playerAreaY + yOffset;\n\t\t\t\t\t\tif (area.checkIfValuesAreAllowed((area.getTileColor(0, 2) >> 24) & 0xFF, 0x02, 0x03))\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\tif (playerAreaY < y)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tcase 0x01: // Bottom Left\n\t\t\t\t\t\treturn true;\n\t\t\t\t\tcase 0x02: {// Left\n\t\t\t\t\t\tint x = playerAreaX + xOffset;\n\t\t\t\t\t\tif (area.checkIfValuesAreAllowed((area.getTileColor(-2, 0) >> 24) & 0xFF, 0x02, 0x03))\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\tif (playerAreaX > x)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tcase 0x03: // Top Left\n\t\t\t\t\t\treturn true;\n\t\t\t\t\tcase 0x04: {// Top\n\t\t\t\t\t\tint y = playerAreaY + yOffset;\n\t\t\t\t\t\tif (playerAreaY > y)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tif (area.checkIfValuesAreAllowed((area.getTileColor(0, -2) >> 24) & 0xFF, 0x02))\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\tif (area.checkIfValuesAreAllowed((area.getTileColor(-1, 0) >> 16) & 0xFF, 0x04) || area.checkIfValuesAreAllowed((area.getTileColor(1, 0) >> 16) & 0xFF, 0x04))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tif (area.checkIfValuesAreAllowed((area.getTileColor(0, -2) >> 24) & 0xFF, 0x03)) {}\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tcase 0x05: // Top Right\n\t\t\t\t\t\treturn true;\n\t\t\t\t\tcase 0x06: { // Right\n\t\t\t\t\t\tint x = playerAreaX + xOffset;\n\t\t\t\t\t\tif (area.checkIfValuesAreAllowed((area.getTileColor(2, 0) >> 24) & 0xFF, 0x02, 0x03))\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\tif (playerAreaX < x)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tcase 0x07: // Bottom Right\n\t\t\t\t\t\t// TODO: DO SOMETHING WITH WATER, MAKE PLAYER SURF!\n\t\t\t\t\t\treturn true;\n\t\t\t\t\tcase 0x18: // Inner bottom left\n\t\t\t\t\tcase 0x19: // Inner bottom right\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t\t// ------------------------- MOUNTAIN LEDGES ------------------------\n\t\t\t\t\tcase 0x0C:\n\t\t\t\t\t\tint y = playerAreaY + yOffset;\n\t\t\t\t\t\tif ((playerAreaY > y) || area.checkIfValuesAreAllowed((area.getTileColor(-1, 0) >> 16) & 0xFF, 0x0C) || area.checkIfValuesAreAllowed((area.getTileColor(1, 0) >> 16) & 0xFF, 0x0C))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 0x03: // Obstacle\n\t\t\t\tswitch (red) {\n\t\t\t\t\t// Item types\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif (data.isHidden())\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tif (this.isInteracting())\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\tif (this.isFacingAt(playerAreaX + xOffset, playerAreaY + yOffset) && Game.keys.isPrimaryPressed()) {\n\t\t\t\t\t\t\tGame.keys.primaryReceived();\n\t\t\t\t\t\t\tentity = area.getEntity(playerAreaX + xOffset, playerAreaY + yOffset);\n\t\t\t\t\t\t\tthis.startInteraction(entity);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\tcase 0x04: // Warp point\n\t\t\t\treturn false;\n\t\t\tcase 0x05: // Area Connection point.\n\t\t\t\treturn false;\n\t\t\tcase 0x06: // Stairs\n\t\t\t\treturn false;\n\t\t\tcase 0x07: // Water\n\t\t\t\t// TODO: Add something that detects a special boolean value in order to let the\n\t\t\t\t// player move on water.\n\t\t\t\treturn false;\n\t\t\tcase 0x08: // House\n\t\t\t\treturn true;\n\t\t\tcase 0x09: // House Door\n\t\t\t\t// TODO (6/18/2015): Door needs to be checked for null areas. If null areas are\n\t\t\t\t// found, default to locked doors.\n\t\t\t\treturn false;\n\t\t\tcase 0x0A: // Item\n\t\t\t\tif (data.isHidden())\n\t\t\t\t\treturn false;\n\t\t\t\tif (this.isInteracting())\n\t\t\t\t\treturn true;\n\t\t\t\tif (this.isFacingAt(playerAreaX + xOffset, playerAreaY + yOffset) && Game.keys.isPrimaryPressed()) {\n\t\t\t\t\tGame.keys.primaryReceived();\n\t\t\t\t\tentity = area.getEntity(playerAreaX + xOffset, playerAreaY + yOffset);\n\t\t\t\t\tthis.startInteraction(entity);\n\t\t\t\t}\n\t\t\t\treturn true; // Cannot go through items on the ground.\n\t\t\tcase 0x0B: // Carpet (Indoors)\n\t\t\tcase 0x0C: // Carpet (Outdoors)\n\t\t\tcase 0x0D: // Triggers\n\t\t\t\treturn false;\n\t\t\tdefault: // Any other type of tiles should be walkable, for no apparent reasons.\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Changes the player's state to Walking.\n\t */\n\tpublic void startsWalking() {\n\t\tthis.isInWater = false;\n\t\tthis.isOnBicycle = false;\n\t\tthis.isSprinting = false;\n\t}\n\n\tpublic void reload() {\n\t\tthis.isLockedWalking = false;\n\t\tthis.isLockedJumping = false;\n\t\tthis.isInteractionEnabled = false;\n\t\tthis.animationTick = 0x7;\n\t\tthis.setFacing(Character.DOWN);\n\t}\n\n\t/**\n\t * Blits the entity onto the screen, being offsetted to the left, which fits snugly in the world\n\t * grids.\n\t *\n\t * @param output\n\t * Where the bitmap is to be blitted.\n\t * @param x\n\t * Pixel X offset.\n\t * @param y\n\t * Pixel Y offset.\n\t * @return Nothing.\n\t *\n\t */\n\t@Override\n\tpublic void render(final Scene output, final Graphics graphics, final int x, final int y) {\n\t\t// Key press detection. (It's short-circuited via inputs first, before checking the lock.)\n\t\tboolean canUserMove = Game.keys.isDpadPressed() && !Player.movementLock;\n\t\tif (this.isLockedJumping) {\n\t\t\t// Jumping has a higher priority than walking.\n\t\t\toutput.blit(Art.shadow, this.xOffset + x, this.yOffset + y + 4);\n\t\t\t// Walking animation while in the air. Shouldn't jump when in water.\n\t\t\tif (this.isOnBicycle)\n\t\t\t\toutput.npcBlit(Art.player_bicycle[this.walking][this.animationPointer], this.xOffset + x, this.yOffset + y - this.varyingJumpHeight);\n\t\t\telse\n\t\t\t\toutput.npcBlit(Art.player[this.walking][this.animationPointer], this.xOffset + x, this.yOffset + y - this.varyingJumpHeight);\n\t\t}\n\t\telse if (this.isLockedWalking) {\n\t\t\t// Walking animation\n\t\t\tif (this.isInWater)\n\t\t\t\toutput.npcBlit(Art.player_surf[this.walking][this.animationPointer], this.xOffset + x, this.yOffset + y);\n\t\t\telse if (this.isOnBicycle)\n\t\t\t\toutput.npcBlit(Art.player_bicycle[this.walking][this.animationPointer], this.xOffset + x, this.yOffset + y);\n\t\t\telse\n\t\t\t\toutput.npcBlit(Art.player[this.walking][this.animationPointer], this.xOffset + x, this.yOffset + y);\n\t\t}\n\t\telse {\n\t\t\t// Idle animation. Best for rendering things when the character is not moving.\n\n\t\t\t// Check for player state's validity.\n\t\t\tif (this.isInWater && this.isOnBicycle) {\n\t\t\t\t// Player has entered an impossible state.\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Blocking animation. Animation pointer index is reset to zero, to create a perfect loop.\n\t\t\tif (this.isInWater) {\n\t\t\t\t// Surfing (has higher priority than bicycling)\n\t\t\t\tif (canUserMove)\n\t\t\t\t\toutput.npcBlit(Art.player_surf[this.getFacing()][this.animationPointer], this.xOffset + x, this.yOffset + y);\n\t\t\t\telse\n\t\t\t\t\toutput.npcBlit(Art.player_surf[this.getFacing()][0], this.xOffset + x, this.yOffset + y);\n\t\t\t}\n\t\t\telse if (this.isOnBicycle) {\n\t\t\t\t// Riding (has lower priority than surfing)\n\t\t\t\tif (canUserMove)\n\t\t\t\t\toutput.npcBlit(Art.player_bicycle[this.getFacing()][this.animationPointer], this.xOffset + x, this.yOffset + y);\n\t\t\t\telse\n\t\t\t\t\toutput.npcBlit(Art.player_bicycle[this.getFacing()][0], this.xOffset + x, this.yOffset + y);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Walking\n\t\t\t\tif (canUserMove)\n\t\t\t\t\toutput.npcBlit(Art.player[this.getFacing()][this.animationPointer], this.xOffset + x, this.yOffset + y);\n\t\t\t\telse\n\t\t\t\t\toutput.npcBlit(Art.player[this.getFacing()][0], this.xOffset + x, this.yOffset + y);\n\t\t\t}\n\t\t\t// Interacting with another entity.\n\t\t\tif (this.isInteractionEnabled && this.interactingEntity != null) {\n\t\t\t\t// Dialogues can be rendered at this point here.\n\t\t\t\tthis.interactingEntity.render(output, graphics, this.xOffset, this.yOffset);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Sets the player's current area position to the corresponding X and Y coordinates given.\n\t *\n\t * <p>\n\t * It uses the 2D Cartesian coordinates used in bitmaps. Positive X: Right. Positive Y: Down.\n\t *\n\t * <p>\n\t * <i>Note that the player's X and Y positions are overwritten by the loading system.</i>\n\t *\n\t * @param x\n\t * The X coordinate the player is to be positioned at.\n\t * @param y\n\t * The Y coordinate the player is to be positioned at.\n\t * @return Nothing.\n\t */\n\tpublic void setAreaPosition(final int x, final int y) {\n\t\tthis.setPosition(x * Tileable.WIDTH, y * Tileable.HEIGHT);\n\t}\n\n\t/**\n\t * Same with \"setAreaPosition(int x, int y)\", but only setting the X position.\n\t *\n\t * @param x\n\t * The X coordinate the player is to be positioned at.\n\t * @return Nothing.\n\t */\n\tpublic void setAreaX(final int x) {\n\t\tthis.xAreaPosition = x * Tileable.WIDTH;\n\t}\n\n\t/**\n\t * Same with \"setAreaPosition(int x, int y)\", but only setting the Y position.\n\t *\n\t * @param y\n\t * The Y coordinate the player is to be positioned at.\n\t * @return Nothing.\n\t */\n\tpublic void setAreaY(final int y) {\n\t\tthis.yAreaPosition = y * Tileable.HEIGHT;\n\t}\n\n\t/**\n\t * Moves the Player object to the center of the screen.\n\t *\n\t * @param Scene\n\t * Pans the screen immediately so that the Player object is in the center of the screen.\n\t * @return Nothing.\n\t */\n\tpublic void setCenterCamPosition(final Scene screen) {\n\t\tthis.setRenderOffset(screen.getWidth() / 2 - Tileable.WIDTH, (screen.getHeight() - Tileable.HEIGHT) / 2);\n\t}\n\n\t/**\n\t * Locks the player into a jumping state. In this state, the Player cannot listen to any key inputs\n\t * received during the jump.\n\t * <p>\n\t *\n\t * Note: An example on how to determine player direction for the tile to allow and block:\n\t * <ul>\n\t * Let's say the tile, X, is located at (1, 1), if using bitmap coordinates. If the tile allows the\n\t * player to jump from top to bottom, the parameters, \"from\" and \"to\" would be Player.UP and\n\t * Player.DOWN respectively, which is the UP tile at (1, 0) and DOWN tile at (1, 2). It means, the\n\t * tile above X is the UP position of X, and the tile below X is the DOWN position of X. Therefore,\n\t * X allows the player on the tile above X (the UP tile) to jump across to the tile below X, but not\n\t * the other way around.\n\t * </ul>\n\t *\n\t * Parameters must be either Player.UP, Player.DOWN, Player.LEFT, or Player.RIGHT.\n\t * <p>\n\t *\n\t * @param red\n\t * The red value of the pixel color.\n\t * @param green\n\t * The green value of the pixel color.\n\t * @param blue\n\t * The blue value of the pixel color.\n\t * @param from\n\t * The player direction the tile allows the player to jump from. Player direction is\n\t * determined from where the tile is located. The player direction must not be the same\n\t * as the \"to\" parameter.\n\t * @param to\n\t * The player direction the tile allows the player to jump to. Player direction is\n\t * determined from where the tile is located. The player direction must not be the same\n\t * as the \"from\" parameter.\n\t * @return Nothing.\n\t */\n\tpublic void setLockJumping(final int red, final int green, final int blue, final int from, final int to) {\n\t\tif (from == to)\n\t\t\tthrow new IllegalArgumentException(\"The parameters, from and to, must not be the same.\");\n\t\tswitch (red) {\n\t\t\tcase 0x00: // Bottom\n\t\t\t\t// this.facingsBlocked[0] = this.facingsBlocked[1] = this.facingsBlocked[2] =\n\t\t\t\t// this.facingsBlocked[3] = true;\n\t\t\t\tthis.isFacingBlocked[Character.DOWN] = this.isFacingBlocked[Character.LEFT] = this.isFacingBlocked[Character.RIGHT] = true;\n\t\t\t\tthis.isFacingBlocked[Character.UP] = false;\n\t\t\t\tthis.isLockedJumping = true;\n\t\t\t\tbreak;\n\t\t\tcase 0x01: // Bottom Left\n\t\t\t\tthis.isFacingBlocked[Character.DOWN] = this.isFacingBlocked[Character.LEFT] = this.isFacingBlocked[Character.RIGHT] = this.isFacingBlocked[Character.UP] = true;\n\t\t\t\tbreak;\n\t\t\tcase 0x02: // Left\n\t\t\t\tthis.isFacingBlocked[Character.DOWN] = this.isFacingBlocked[Character.LEFT] = this.isFacingBlocked[Character.UP] = true;\n\t\t\t\tthis.isFacingBlocked[Character.LEFT] = false;\n\t\t\t\tthis.isLockedJumping = true;\n\t\t\t\tbreak;\n\t\t\tcase 0x03: // Top Left\n\t\t\t\tthis.isFacingBlocked[Character.DOWN] = this.isFacingBlocked[Character.LEFT] = this.isFacingBlocked[Character.RIGHT] = this.isFacingBlocked[Character.UP] = true;\n\t\t\t\tbreak;\n\t\t\tcase 0x04: // Top\n\t\t\t\tthis.isFacingBlocked[Character.UP] = this.isFacingBlocked[Character.LEFT] = this.isFacingBlocked[Character.RIGHT] = true;\n\t\t\t\tthis.isFacingBlocked[Character.DOWN] = false;\n\t\t\t\tthis.isLockedJumping = true;\n\t\t\t\tbreak;\n\t\t\tcase 0x05: // Top Right\n\t\t\t\tthis.isFacingBlocked[Character.DOWN] = this.isFacingBlocked[Character.LEFT] = this.isFacingBlocked[Character.RIGHT] = this.isFacingBlocked[Character.UP] = true;\n\t\t\t\tbreak;\n\t\t\tcase 0x06: // Right\n\t\t\t\tthis.isFacingBlocked[Character.DOWN] = this.isFacingBlocked[Character.UP] = this.isFacingBlocked[Character.LEFT] = true;\n\t\t\t\tthis.isFacingBlocked[Character.RIGHT] = false;\n\t\t\t\tthis.isLockedJumping = true;\n\t\t\t\tbreak;\n\t\t\tcase 0x07: // Bottom Right\n\t\t\t\tthis.isFacingBlocked[Character.DOWN] = this.isFacingBlocked[Character.LEFT] = this.isFacingBlocked[Character.RIGHT] = this.isFacingBlocked[Character.UP] = true;\n\t\t\t\tbreak;\n\t\t\tdefault: // Any other tiles should not cause the player to jump.\n\t\t\t\tthis.isFacingBlocked[0] = this.isFacingBlocked[1] = this.isFacingBlocked[2] = this.isFacingBlocked[3] = true;\n\t\t\t\tthis.isLockedJumping = false;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tpublic void setName(final String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic void setRenderOffset(final int x, final int y) {\n\t\tthis.xOffset = x;\n\t\tthis.yOffset = y;\n\t}\n\n\t/**\n\t * Handles setting the entity's facing towards the player once the player starts interacting with\n\t * it. with.\n\t *\n\t * @param entity\n\t */\n\tpublic void startInteraction(Entity entity) {\n\t\tif (this.isInteractionEnabled)\n\t\t\treturn;\n\t\tthis.isInteractionEnabled = true;\n\t\tthis.interactingEntity = entity;\n\t\tthis.interactingEntity.setInteractingState(true);\n\t\tif (this.interactingEntity instanceof Character c) {\n\t\t\t// Need to pause the character from walking.\n\t\t\tc.setLockedWalking(false);\n\t\t\tc.stopAutoWalking();\n\n\t\t\t// Need to set the character entity facing towards the Player.\n\t\t\tint facingTowardsPlayer = -1;\n\t\t\tswitch (this.getFacing()) {\n\t\t\t\tcase Character.DOWN:\n\t\t\t\t\tfacingTowardsPlayer = Character.UP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase Character.LEFT:\n\t\t\t\t\tfacingTowardsPlayer = Character.RIGHT;\n\t\t\t\t\tbreak;\n\t\t\t\tcase Character.UP:\n\t\t\t\t\tfacingTowardsPlayer = Character.DOWN;\n\t\t\t\t\tbreak;\n\t\t\t\tcase Character.RIGHT:\n\t\t\t\t\tfacingTowardsPlayer = Character.LEFT;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tc.setFacing(facingTowardsPlayer);\n\t\t}\n\t}\n\n\t// -------------------------------------------------------------------------------------\n\t// Private methods\n\n\t/**\n\t * Changes the player's state to Riding.\n\t */\n\tpublic void startsRidingBicycle() {\n\t\tif (!this.isInWater) {\n\t\t\tPlayer.lockMovements();\n\t\t\tnew Thread(() -> {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(250);\n\t\t\t\t}\n\t\t\t\tcatch (final InterruptedException e1) {}\n\t\t\t\tPlayer.this.isOnBicycle = true;\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(250);\n\t\t\t\t}\n\t\t\t\tcatch (final InterruptedException e2) {}\n\t\t\t\tPlayer.unlockMovements();\n\t\t\t}).start();\n\t\t}\n\t\telse\n\t\t\tthis.warningsTriggered = true;\n\t}\n\n\tpublic void stopInteraction() {\n\t\tthis.isInteractionEnabled = false;\n\t\tthis.interactingEntity.setInteractingState(false);\n\t\tthis.interactingEntity = null;\n\t}\n\n\tpublic void enableAutomaticMode() {\n\t\tthis.automaticMode = true;\n\t}\n\n\tpublic void disableAutomaticMode() {\n\t\tthis.automaticMode = false;\n\t}\n\n\tpublic boolean isInAutomaticMode() {\n\t\treturn this.automaticMode;\n\t}\n\n\t// ---------------------------------------------------------------------\n\t// Override methods\n\n\t@Override\n\tpublic void tick() {\n\t\tif (this.automaticMode) {\n\t\t\tthis.keys.resetInputs();\n\t\t\tthis.handleFacingCheck();\n\t\t}\n\t\tif (!this.isLockedJumping) {\n\t\t\tif (!this.isInteractionEnabled) {\n\t\t\t\tthis.input();\n\t\t\t\tthis.handleMovement();\n\t\t\t\tthis.controlTick();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.stopAnimation();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tthis.jump();\n\t}\n\n\t@Override\n\tpublic int getAutoWalkTickFrequency() {\n\t\treturn Character.AUTO_WALK_DISABLE;\n\t}\n\n\t// ---------------------------------------------------------------------\n\t// Private methods\n\n\tprivate void checkFacingInput() {\n\t\tif (this.keys.up.isTappedDown || this.keys.up.isPressedDown || this.keys.W.isTappedDown || this.keys.W.isPressedDown) {\n\t\t\tthis.setFacing(Character.UP);\n\t\t}\n\t\telse if (this.keys.down.isTappedDown || this.keys.down.isPressedDown || this.keys.S.isTappedDown || this.keys.S.isPressedDown) {\n\t\t\tthis.setFacing(Character.DOWN);\n\t\t}\n\t\telse if (this.keys.left.isTappedDown || this.keys.left.isPressedDown || this.keys.A.isTappedDown || this.keys.A.isPressedDown) {\n\t\t\tthis.setFacing(Character.LEFT);\n\t\t}\n\t\telse if (this.keys.right.isTappedDown || this.keys.right.isPressedDown || this.keys.D.isTappedDown || this.keys.D.isPressedDown) {\n\t\t\tthis.setFacing(Character.RIGHT);\n\t\t}\n\t\telse {\n\t\t\t// Intentionally doing nothing here.\n\t\t}\n\t}\n\n\t@Override\n\tprotected void controlTick() {\n\t\tif (!this.isLockedWalking || !this.isLockedJumping) {\n\t\t\tthis.animationTick++;\n\t\t\tif ((this.getFacing() == Character.UP && this.isFacingBlocked[Character.UP]) || (this.getFacing() == Character.DOWN && this.isFacingBlocked[Character.DOWN])) {\n\t\t\t\tif (this.animationTick >= 10) {\n\t\t\t\t\tthis.animationTick = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ((this.getFacing() == Character.LEFT && this.isFacingBlocked[Character.LEFT]) || (this.getFacing() == Character.RIGHT && this.isFacingBlocked[Character.RIGHT])) {\n\t\t\t\tif (this.animationTick >= 10) {\n\t\t\t\t\tthis.animationTick = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (this.animationTick >= 4)\n\t\t\t\t\tthis.animationTick = 0;\n\t\t\t}\n\t\t\tif (this.animationTick == 0) {\n\t\t\t\tthis.animationPointer++;\n\t\t\t\tif (this.animationPointer > 3)\n\t\t\t\t\tthis.animationPointer = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void handleFacingCheck() {\n\t\tif (this.walking != this.getFacing()) {\n\t\t\tthis.walking = this.getFacing();\n\t\t}\n\t}\n\n\t/**\n\t * Makes adjustments to the player's position when the player is walking.\n\t *\n\t * <p>\n\t * If the conditions are met, such as a tile has been fully moved to, it will check to make sure the\n\t * player has stopped walking, until the player wanted to walk.\n\t *\n\t * @return Nothing.\n\t */\n\t@Override\n\tprotected void handleMovement() {\n\t\t// Check if player is currently locked to walking.\n\t\tif (this.isLockedWalking) {\n\t\t\t// Order of operations, the fastest goes first.\n\t\t\tif (this.isOnBicycle)\n\t\t\t\tthis.ride();\n\t\t\telse if (this.isSprinting)\n\t\t\t\tthis.sprint();\n\t\t\telse\n\t\t\t\tthis.walk();\n\t\t}\n\t\telse {\n\t\t\t// Before we walk, check to see if the oldX and oldY are up-to-date with the\n\t\t\t// latest X and Y.\n\t\t\tif (this.oldXAreaPosition != this.xAreaPosition)\n\t\t\t\tthis.oldXAreaPosition = this.xAreaPosition;\n\t\t\tif (this.oldYAreaPosition != this.yAreaPosition)\n\t\t\t\tthis.oldYAreaPosition = this.yAreaPosition;\n\n\t\t\t// Reset the acceleration values, since we're not really walking.\n\t\t\tthis.xAccel = 0;\n\t\t\tthis.yAccel = 0;\n\n\t\t\t// Check for inputs the player wants to face. Tapping in a direction turns the\n\t\t\t// player around.\n\t\t\tif (!Player.movementLock)\n\t\t\t\tthis.checkFacingInput();\n\n\t\t\t// Now about to walk. First, check to see if there's an obstacle blocking the\n\t\t\t// path.\n\t\t\tif (this.isFacingBlocked[this.getFacing()]) {\n\t\t\t\tthis.isLockedWalking = false;\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void jump() {\n\t\tif (this.isLockedJumping) {\n\t\t\t// When being locked to walking, facing must stay constant.\n\t\t\tif (this.walking != this.getFacing())\n\t\t\t\tthis.walking = this.getFacing();\n\n\t\t\t// Also make sure it's currently not being blocked by anything (You're in the\n\t\t\t// air)\n\t\t\tthis.isFacingBlocked[0] = this.isFacingBlocked[1] = this.isFacingBlocked[2] = this.isFacingBlocked[3] = false;\n\n\t\t\t// Makes sure the acceleration stays limited to 1 pixel/tick.\n\t\t\tif (this.xAccel > 1)\n\t\t\t\tthis.xAccel = 1;\n\t\t\tif (this.xAccel < -1)\n\t\t\t\tthis.xAccel = -1;\n\t\t\tif (this.yAccel > 1)\n\t\t\t\tthis.yAccel = 1;\n\t\t\tif (this.yAccel < -1)\n\t\t\t\tthis.yAccel = -1;\n\n\t\t\tthis.xAreaPosition += this.xAccel * 2;\n\t\t\tthis.yAreaPosition += this.yAccel * 2;\n\n\t\t\t// Jumping stuffs go here.\n\t\t\tif (!this.jumpHeightSignedFlag)\n\t\t\t\tthis.varyingJumpHeight++;\n\t\t\telse\n\t\t\t\tthis.varyingJumpHeight--;\n\t\t\tif (this.varyingJumpHeight >= 10.0)\n\t\t\t\tthis.jumpHeightSignedFlag = true;\n\n\t\t\t// Needs to get out of being locked to walking/jumping.\n\t\t\t// Note that we cannot compare using ||, what if the player is moving in one\n\t\t\t// direction? What about the other axis?\n\t\t\tif ((this.xAreaPosition % Tileable.WIDTH == 0 && this.yAreaPosition % Tileable.HEIGHT == 0)) {\n\t\t\t\t// Resets every flag that locks the player.\n\t\t\t\tthis.isLockedWalking = false;\n\t\t\t\tthis.isLockedJumping = false;\n\t\t\t\tif (this.jumpHeightSignedFlag) {\n\t\t\t\t\tthis.jumpHeightSignedFlag = false;\n\t\t\t\t\tthis.varyingJumpHeight = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.controlTick();\n\t}\n\n\tprivate void pressed() {\n\t\tthis.xAccel = this.yAccel = 0;\n\t\tif (this.keys.up.isPressedDown || this.keys.W.isPressedDown) {\n\t\t\tif (this.getFacing() != Character.UP) {\n\t\t\t\tthis.setFacing(Character.UP);\n\t\t\t}\n\t\t\tif (!this.isFacingBlocked[Character.UP]) {\n\t\t\t\tthis.isLockedWalking = true;\n\t\t\t\tthis.yAccel--;\n\t\t\t}\n\t\t}\n\t\telse if (this.keys.down.isPressedDown || this.keys.S.isPressedDown) {\n\t\t\tif (this.getFacing() != Character.DOWN) {\n\t\t\t\tthis.setFacing(Character.DOWN);\n\t\t\t}\n\t\t\tif (!this.isFacingBlocked[Character.DOWN]) {\n\t\t\t\tthis.isLockedWalking = true;\n\t\t\t\tthis.yAccel++;\n\t\t\t}\n\t\t}\n\t\telse if (this.keys.left.isPressedDown || this.keys.A.isPressedDown) {\n\t\t\tif (this.getFacing() != Character.LEFT) {\n\t\t\t\tthis.setFacing(Character.LEFT);\n\t\t\t}\n\t\t\tif (!this.isFacingBlocked[Character.LEFT]) {\n\t\t\t\tthis.isLockedWalking = true;\n\t\t\t\tthis.xAccel--;\n\t\t\t}\n\t\t}\n\t\telse if (this.keys.right.isPressedDown || this.keys.D.isPressedDown) {\n\t\t\tif (this.getFacing() != Character.RIGHT) {\n\t\t\t\tthis.setFacing(Character.RIGHT);\n\t\t\t}\n\t\t\tif (!this.isFacingBlocked[Character.RIGHT]) {\n\t\t\t\tthis.isLockedWalking = true;\n\t\t\t\tthis.xAccel++;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void tapped() {\n\t\tthis.animationTick = 0;\n\t\tthis.animationPointer = 0;\n\t\tif (this.keys.up.isTappedDown || this.keys.W.isTappedDown) {\n\t\t\tif (this.getFacing() != Character.UP) {\n\t\t\t\tthis.setFacing(Character.UP);\n\t\t\t}\n\t\t}\n\t\telse if (this.keys.down.isTappedDown || this.keys.S.isTappedDown) {\n\t\t\tif (this.getFacing() != Character.DOWN) {\n\t\t\t\tthis.setFacing(Character.DOWN);\n\t\t\t}\n\t\t}\n\t\telse if (this.keys.left.isTappedDown || this.keys.A.isTappedDown) {\n\t\t\tif (this.getFacing() != Character.LEFT) {\n\t\t\t\tthis.setFacing(Character.LEFT);\n\t\t\t}\n\t\t}\n\t\telse if ((this.keys.right.isTappedDown || this.keys.D.isTappedDown) && (this.getFacing() != Character.RIGHT)) {\n\t\t\tthis.setFacing(Character.RIGHT);\n\t\t}\n\t}\n\n\tpublic void input() {\n\t\tthis.isColliding = false;\n\t\tif (!this.isLockedWalking) {\n\t\t\t// Up\n\t\t\tif (!this.isFacingBlocked[Character.UP] && !Player.movementLock) {\n\t\t\t\tif (this.keys.up.isTappedDown || this.keys.W.isTappedDown)\n\t\t\t\t\tthis.tapped();\n\t\t\t\telse if (this.keys.up.isPressedDown || this.keys.W.isPressedDown) {\n\t\t\t\t\tthis.pressed();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (this.keys.up.isPressedDown || this.keys.W.isPressedDown) {\n\t\t\t\tthis.isColliding = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Down\n\t\t\tif (!this.isFacingBlocked[Character.DOWN] && !Player.movementLock) {\n\t\t\t\tif (this.keys.down.isTappedDown || this.keys.S.isTappedDown)\n\t\t\t\t\tthis.tapped();\n\t\t\t\telse if (this.keys.down.isPressedDown || this.keys.S.isPressedDown) {\n\t\t\t\t\tthis.pressed();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (this.keys.down.isPressedDown || this.keys.S.isPressedDown) {\n\t\t\t\tthis.isColliding = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Left\n\t\t\tif (!this.isFacingBlocked[Character.LEFT] && !Player.movementLock) {\n\t\t\t\tif (this.keys.left.isTappedDown || this.keys.A.isTappedDown)\n\t\t\t\t\tthis.tapped();\n\t\t\t\telse if (this.keys.left.isPressedDown || this.keys.A.isPressedDown) {\n\t\t\t\t\tthis.pressed();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (this.keys.left.isPressedDown || this.keys.A.isPressedDown) {\n\t\t\t\tthis.isColliding = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Right\n\t\t\tif (!this.isFacingBlocked[Character.RIGHT] && !Player.movementLock) {\n\t\t\t\tif (this.keys.right.isTappedDown || this.keys.D.isTappedDown)\n\t\t\t\t\tthis.tapped();\n\t\t\t\telse if (this.keys.right.isPressedDown || this.keys.D.isPressedDown) {\n\t\t\t\t\tthis.pressed();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (this.keys.right.isPressedDown || this.keys.D.isPressedDown) {\n\t\t\t\tthis.isColliding = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param inventoryManager\n\t */\n\tpublic void setInventory(Inventory inventoryManager) {\n\t\tthis.inventory = inventoryManager;\n\t}\n\n\t@Override\n\tpublic void walk() {\n\t\t// When being locked to walking, facing must stay constant.\n\t\tthis.handleFacingCheck();\n\n\t\t// Makes sure the acceleration stays limited to 1 pixel/tick.\n\t\tif (this.xAccel > 1)\n\t\t\tthis.xAccel = 1;\n\t\tif (this.xAccel < -1)\n\t\t\tthis.xAccel = -1;\n\t\tif (this.yAccel > 1)\n\t\t\tthis.yAccel = 1;\n\t\tif (this.yAccel < -1)\n\t\t\tthis.yAccel = -1;\n\t\tif (!this.isOnBicycle && !Player.isMovementsLocked()) {\n\t\t\tthis.xAreaPosition += this.xAccel * 2;\n\t\t\tthis.yAreaPosition += this.yAccel * 2;\n\t\t}\n\t\t// Needs to get out of being locked to walking/jumping.\n\t\t// Note that we cannot compare using ||, what if the player is moving in one\n\t\t// direction? What about the other axis?\n\t\tif ((this.xAreaPosition % Tileable.WIDTH == 0 && this.yAreaPosition % Tileable.HEIGHT == 0)) {\n\t\t\t// Resets every flag that locks the player.\n\t\t\tthis.isLockedWalking = false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void sprint() {\n\t\t// When being locked to walking, facing must stay constant.\n\t\tthis.handleFacingCheck();\n\n\t\t// Makes sure the acceleration stays limited to 1 pixel/tick.\n\t\tif (this.xAccel > 1)\n\t\t\tthis.xAccel = 1;\n\t\tif (this.xAccel < -1)\n\t\t\tthis.xAccel = -1;\n\t\tif (this.yAccel > 1)\n\t\t\tthis.yAccel = 1;\n\t\tif (this.yAccel < -1)\n\t\t\tthis.yAccel = -1;\n\t\tif (!this.isOnBicycle && !Player.isMovementsLocked()) {\n\t\t\tthis.xAreaPosition += this.xAccel * 4;\n\t\t\tthis.yAreaPosition += this.yAccel * 4;\n\t\t}\n\t\t// Needs to get out of being locked to walking/jumping.\n\t\t// Note that we cannot compare using ||, what if the player is moving in one\n\t\t// direction? What about the other axis?\n\t\tif ((this.xAreaPosition % Tileable.WIDTH == 0 && this.yAreaPosition % Tileable.HEIGHT == 0)) {\n\t\t\t// Resets every flag that locks the player.\n\t\t\tthis.isLockedWalking = false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void ride() {\n\t\t// When being locked to walking, facing must stay constant.\n\t\tthis.handleFacingCheck();\n\n\t\t// Makes sure the acceleration stays limited to 1 pixel/tick.\n\t\tif (this.xAccel > 1)\n\t\t\tthis.xAccel = 1;\n\t\tif (this.xAccel < -1)\n\t\t\tthis.xAccel = -1;\n\t\tif (this.yAccel > 1)\n\t\t\tthis.yAccel = 1;\n\t\tif (this.yAccel < -1)\n\t\t\tthis.yAccel = -1;\n\t\tif (this.isOnBicycle && !Player.isMovementsLocked()) {\n\t\t\tthis.xAreaPosition += this.xAccel * 8;\n\t\t\tthis.yAreaPosition += this.yAccel * 8;\n\t\t}\n\t\t// Needs to get out of being locked to walking/jumping.\n\t\t// Note that we cannot compare using ||, what if the player is moving in one\n\t\t// direction? What about the other axis?\n\t\tif ((this.xAreaPosition % Tileable.WIDTH == 0 && this.yAreaPosition % Tileable.HEIGHT == 0)) {\n\t\t\t// Resets every flag that locks the player.\n\t\t\tthis.isLockedWalking = false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void swim() {}\n}",
"public enum ScriptTags {\n\t/**\n\t * @\n\t */\n\tScriptName(\"@\", \"NAME\", \"Script name\"),\n\n\t/**\n\t * &\n\t */\n\tChecksum(\"&\", \"CHKSUM\", \"Script checksum\"),\n\n\t/**\n\t * /\n\t */\n\tComment(\"/\", \"REM\", \"Comment\"),\n\n\t/**\n\t * $\n\t */\n\tBeginScript(\"$\", \"BEGIN\", \"Trigger Script begins\"),\n\n\t/**\n\t * !\n\t */\n\tNpcScript(\"!\", \"NPC\", \"NPC Script begins\"),\n\n\t/**\n\t * ^\n\t */\n\tPathData(\"^\", \"PATH\", \"Scripted path data\"),\n\n\t/**\n\t * %\n\t */\n\tEndScript(\"%\", \"END\", \"Script ends\"),\n\n\t/**\n\t * #\n\t */\n\tSpeech(\"#\", \"SPEAK\", \"A normal speech dialogue\"),\n\n\t/**\n\t * ?\n\t */\n\tQuestion(\"?\", \"ASK\", \"A question dialogue asking for the player's response to YES or NO.\", \"A single question must be followed by an Affirmative and a Negative Dialogue.\"),\n\n\t/**\n\t * +\n\t */\n\tAffirm(\"+\", \"AFFIRM\", \"Affirm a question dialogue with a positive answer. If a question dialogue has been asked, and the player reponded to YES, this and similar consecutive dialogues will be shown.\"),\n\n\t/**\n\t * -\n\t */\n\tReject(\"-\", \"REJECT\", \"Reject a question dialogue with a negative answer. If a question dialogue has been asked, and the player reponded to NO, this and similar consecutive dialogues will be shown.\"),\n\n\t/**\n\t * [\n\t */\n\tConfirm(\"[\", \"CONFIRM\", \"Asking the player to confirm an option. If a confirm dialogue has been selected, this and similar consecutive dialogues will be shown.\"),\n\n\t/**\n\t * ]\n\t */\n\tCancel(\"]\", \"DENY\", \"Asking the player to deny or cancel an option. If a denial dialogue has been selected, this and similar consecutive dialogues will be shown.\"),\n\n\t/**\n\t * ;\n\t */\n\tRepeat(\";\", \"LOOP\", \"Repeat the script\"),\n\n\t/**\n\t * |\n\t */\n\tCounter(\"|\", \"COUNTER\", \"Script can only be repeated for a limited time\"),\n\n\t/**\n\t * ~\n\t */\n\tCondition(\"~\", \"CONDITION\", \"Conditions that are to be met to complete the script\");\n\n\tprivate final String symbol;\n\tprivate final String uppercaseSymbolName;\n\tprivate final String capitalizedSymbolName;\n\tprivate final String lowercaseSymbolName;\n\tprivate final String description;\n\tprivate final String note;\n\n\tScriptTags(String sym, String alternate, String description) {\n\t\tthis(sym, alternate, description, null);\n\t}\n\n\tScriptTags(String sym, String alternate, String description, String note) {\n\t\tthis.symbol = sym;\n\t\tthis.uppercaseSymbolName = alternate.toUpperCase();\n\t\tthis.lowercaseSymbolName = alternate.toLowerCase();\n\t\tthis.capitalizedSymbolName = StringUtils.capitalize(this.lowercaseSymbolName);\n\t\tthis.description = description;\n\t\tthis.note = (note != null && !note.isBlank()) ? note : \"\";\n\t}\n\n\t/**\n\t * Checks if the line starts with either the symbol representation, or the tag name.\n\t *\n\t * @param line\n\t * @return True if either the symbol or the tag name matches. False, if otherwise.\n\t */\n\tpublic boolean beginsAt(String line) {\n\t\tif (line == null || line.isEmpty() || line.isBlank())\n\t\t\treturn false;\n\t\tif (this.startsWithUpperCase(line) || line.startsWith(this.symbol))\n\t\t\treturn true;\n\t\tString upper = line.toUpperCase().trim();\n\t\tString lower = line.toLowerCase().trim();\n\t\tif (upper.startsWith(this.uppercaseSymbolName) || lower.startsWith(this.lowercaseSymbolName))\n\t\t\treturn true;\n\t\treturn line.regionMatches(true, 0, this.name(), 0, this.name().length());\n\t}\n\n\t/**\n\t * Replaces the first occurrence of the tag name with the equivalent symbol representation.\n\t * <p>\n\t * Otherwise, if the line already has the symbol representation, then it does nothing.\n\t *\n\t * @param line\n\t * @return The replaced line.\n\t */\n\tpublic String replace(String line) {\n\t\tif (line.startsWith(this.symbol))\n\t\t\treturn line;\n\t\treturn line.replaceFirst(Pattern.quote(this.name()), Matcher.quoteReplacement(this.symbol));\n\t}\n\n\tpublic boolean startsWithUpperCase(String line) {\n\t\tString[] tokens = line.toUpperCase().split(\":=\");\n\t\tif (tokens.length > 0) {\n\t\t\tString uppercase = tokens[0];\n\t\t\treturn (uppercase.trim().equals(this.uppercaseSymbolName));\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Removes the script tag or script symbol from the given line, and returns the result.\n\t *\n\t * @param line\n\t * The line that contains the script tag or symbol.\n\t * @return The resulting string value after the script tag or symbol has been removed.\n\t */\n\tpublic String removeScriptTag(String line) {\n\t\tif (line.startsWith(this.symbol))\n\t\t\treturn line.substring(this.symbol.length());\n\t\telse if (line.toUpperCase().startsWith(this.uppercaseSymbolName) || line.toLowerCase().startsWith(this.lowercaseSymbolName)) {\n\t\t\t// We ignore anything that comes before the script tag. We're not doing anything complicated here.\n\t\t\tint endOfIndex = line.indexOf(this.uppercaseSymbolName) + this.uppercaseSymbolName.length();\n\t\t\treturn line.substring(endOfIndex).trim();\n\t\t}\n\t\t// Cannot remove any script tags or symbols.\n\t\treturn line;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn this.description;\n\t}\n\n\tpublic String getPrettyDescription() {\n\t\treturn this.description + \".\";\n\t}\n\n\tpublic String getSymbolName() {\n\t\treturn this.uppercaseSymbolName;\n\t}\n\n\tpublic String getLowercaseSymbolName() {\n\t\treturn this.lowercaseSymbolName;\n\t}\n\n\tpublic String getCapitalizedSymbolName() {\n\t\treturn this.capitalizedSymbolName;\n\t}\n\n\tpublic String getSymbol() {\n\t\treturn this.symbol;\n\t}\n\n\tpublic String getAdditionalNote() {\n\t\treturn this.note;\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// Static methods\n\n\tpublic static ScriptTags parse(String actionCommand) {\n\t\tScriptTags[] values = ScriptTags.values();\n\t\tfor (ScriptTags tag : values) {\n\t\t\tif (tag.getSymbol().equals(actionCommand))\n\t\t\t\treturn tag;\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unknown script tag action command symbol.\");\n\t}\n}",
"public class Area implements Tileable, UpdateRenderable {\n\tprivate final int width;\n\tprivate final int height;\n\tprivate final int[] pixels;\n\n\tprivate int xPlayerPosition;\n\tprivate int yPlayerPosition;\n\tprivate int oldXTriggerPosition;\n\tprivate int oldYTriggerPosition;\n\tprivate Player player;\n\n\tprivate boolean isInWarpZone;\n\tprivate boolean isInSectorPoint;\n\tprivate PixelData currentPixelData;\n\tprivate final int areaID;\n\tprivate int sectorID;\n\tprivate String areaName;\n\tprivate String checksum;\n\t// TODO: Add area type.\n\t// private int areaType;\n\n\tprivate boolean isExitArrowDisplayed;\n\tprivate boolean isTriggerTriggered;\n\tprivate TriggerData trigger;\n\n\tprivate final List<List<PixelData>> areaData = new ArrayList<>();\n\tprivate final Set<PixelData> modifiedAreaData = new HashSet<>();\n\n\t// Area data hash maps.\n\tprivate final Map<Map.Entry<Integer, Integer>, Obstacle> areaObstacles = new HashMap<>();\n\tprivate final Map<Map.Entry<Integer, Integer>, Character> areaCharacters = new HashMap<>();\n\tprivate final Map<Map.Entry<Integer, Integer>, Item> areaItems = new HashMap<>();\n\tprivate final Map<Map.Entry<Integer, Integer>, TriggerData> triggerDatas = new HashMap<>();\n\n\tpublic Area(Bitmap bitmap) {\n\t\tint[] tempPixels = bitmap.getPixels();\n\t\tint pixelIterator = 0;\n\n\t\t// Step 1 - Get all the important information\n\t\tfinal int areaInfo = tempPixels[pixelIterator++];\n\t\tthis.areaID = (areaInfo >> 16) & 0xFFFF;\n\t\tfinal int triggerSize = areaInfo & 0xFFFF;\n\t\tfinal int areaSize = tempPixels[pixelIterator++];\n\t\tthis.width = (areaSize >> 16) & 0xFFFF;\n\t\tthis.height = areaSize & 0xFFFF;\n\t\tfinal int pixelSize = tempPixels[pixelIterator++];\n\n\t\t// Step 2 - Get checksum first. Checksum is set immediately after the first pixel.\n\t\tfinal int checksumPixelsCount = WorldConstants.CHECKSUM_MAX_BYTES_LENGTH / 4;\n\t\tStringBuilder checksumBuilder = new StringBuilder();\n\t\tfor (int i = 0; i < checksumPixelsCount; i++) {\n\t\t\tint pixel = tempPixels[pixelIterator++];\n\t\t\t// There are a total of 4 bytes in an \"int\" type.\n\t\t\tchar ch1 = (char) ((pixel & 0xFF000000) >> 24);\n\t\t\tchar ch2 = (char) ((pixel & 0x00FF0000) >> 16);\n\t\t\tchar ch3 = (char) ((pixel & 0x0000FF00) >> 8);\n\t\t\tchar ch4 = (char) (pixel & 0x000000FF);\n\t\t\tchecksumBuilder.append(ch1).append(ch2).append(ch3).append(ch4);\n\t\t}\n\t\tthis.checksum = checksumBuilder.toString();\n\n\t\t// Step 3 - Get any triggers and put them into a triggers list.\n\t\t// If the trigger size is larger than 1 (meaning there are triggers other than Eraser), we parse the\n\t\t// trigger data.\n\t\tif (triggerSize > 0) {\n\t\t\t// Ignoring Eraser trigger.\n\t\t\tpixelIterator++;\n\t\t\tpixelIterator++;\n\n\t\t\tfor (int i = 0; i < triggerSize; i++) {\n\t\t\t\t// The \"color\" is the ID.\n\t\t\t\t// ID must not be negative. ID = 0 is reserved.\n\t\t\t\tint color = tempPixels[pixelIterator++];\n\t\t\t\tint npcInfo = tempPixels[pixelIterator++];\n\t\t\t\tif (color - npcInfo != 0 || color + npcInfo != 0) {\n\t\t\t\t\tint xPosition = (color >> 24) & 0xFF;\n\t\t\t\t\tint yPosition = (color >> 16) & 0xFF;\n\t\t\t\t\tthis.triggerDatas.put(Map.entry(xPosition, yPosition), new TriggerData().loadTriggerData(color, npcInfo));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tpixelIterator++;\n\t\t\tpixelIterator++;\n\t\t}\n\n\t\t// Step 4 - Get the NPCs data.\n\t\tfinal int npcSize = tempPixels[pixelIterator++];\n\t\tfor (int i = 0; i < npcSize; i++) {\n\t\t\tint triggerInfo = tempPixels[pixelIterator++];\n\t\t\tint data = tempPixels[pixelIterator++];\n\t\t\tint x = (triggerInfo >> 24) & 0xFF;\n\t\t\tint y = (triggerInfo >> 16) & 0xFF;\n\t\t\tthis.areaCharacters.put(Map.entry(x, y), Character.build(this, data, x, y));\n\t\t}\n\n\t\t// Step 5 - Get obstacles\n\t\tfinal int obstaclesSize = tempPixels[pixelIterator++];\n\t\tfor (int i = 0; i < obstaclesSize; i++) {\n\t\t\tint triggerInfo = tempPixels[pixelIterator++];\n\t\t\tint data = tempPixels[pixelIterator++];\n\t\t\tint x = (triggerInfo >> 24) & 0xFF;\n\t\t\tint y = (triggerInfo >> 16) & 0xFF;\n\t\t\tthis.areaObstacles.put(Map.entry(x, y), Obstacle.build(this, data, x, y));\n\t\t}\n\n\t\t// Step 6 - Get items\n\t\tfinal int itemsSize = tempPixels[pixelIterator++];\n\t\tfor (int i = 0; i < itemsSize; i++) {\n\t\t\tint triggerInfo = tempPixels[pixelIterator++];\n\t\t\tint data = tempPixels[pixelIterator++];\n\t\t\tint x = (triggerInfo >> 24) & 0xFF;\n\t\t\tint y = (triggerInfo >> 16) & 0xFF;\n\t\t\tthis.areaItems.put(Map.entry(x, y), Item.build(data, x, y));\n\t\t}\n\n\t\t// Step 6 - Skip the padding\n\t\tint col = pixelIterator % this.width;\n\t\tfor (; pixelIterator % this.width != 0 && col < this.width; pixelIterator++)\n\t\t\t;\n\n\t\t// Step 7 - Get the tiles\n\t\tthis.pixels = new int[pixelSize];\n\t\tSystem.arraycopy(tempPixels, pixelIterator, this.pixels, 0, pixelSize);\n\t\tpixelIterator += pixelSize;\n\n\t\t// Step 8 - Get and fill in the area data.\n\t\tfor (int y = 0; y < this.height; y++) {\n\t\t\tthis.areaData.add(new ArrayList<PixelData>());\n\t\t\tfor (int x = 0; x < this.width; x++) {\n\t\t\t\tint pixel = this.pixels[y * this.width + x];\n\t\t\t\tthis.areaData.get(y).add(new PixelData(pixel, x, y));\n\t\t\t}\n\t\t}\n\t\tthis.isInWarpZone = false;\n\t\tthis.isInSectorPoint = false;\n\t\tthis.isExitArrowDisplayed = false;\n\t\tthis.isTriggerTriggered = false;\n\t\tthis.areaName = \"\";\n\t}\n\n\tpublic Area(Bitmap bitmap, final String areaName) {\n\t\tthis(bitmap);\n\t\tthis.areaName = areaName;\n\t}\n\n\tpublic void setPlayer(Player player) {\n\t\tthis.player = player;\n\t}\n\n\tpublic int getWidth() {\n\t\treturn this.width;\n\t}\n\n\tpublic int getHeight() {\n\t\treturn this.height;\n\t}\n\n\tpublic void setAreaName(String name) {\n\t\tthis.areaName = name;\n\t}\n\n\tpublic String getAreaName() {\n\t\treturn this.areaName;\n\t}\n\n\t/**\n\t * Updates the area.\n\t *\n\t * @return Nothing.\n\t */\n\t@Override\n\tpublic void tick() {\n\t\t// Since \"setPlayer\" method isn't always set, there should be checks everywhere\n\t\t// to make sure \"player\" isn't null.\n\t\tif (this.player == null)\n\t\t\treturn;\n\n\t\t// PixelData data = null;\n\t\tif (this.isTriggerBeingTriggered()) {\n\t\t\tthis.xPlayerPosition = this.player.getXInArea();\n\t\t\tthis.yPlayerPosition = this.player.getYInArea();\n\n\t\t\t// Do some bounds checking on the X and Y player positions.\n\t\t\tboolean isXOutOfBounds = this.xPlayerPosition < 0 || this.xPlayerPosition >= this.width;\n\t\t\tboolean isYOutOfBounds = this.yPlayerPosition < 0 || this.yPlayerPosition >= this.height;\n\t\t\tif (isXOutOfBounds || isYOutOfBounds)\n\t\t\t\treturn;\n\n\t\t\tthis.currentPixelData = this.areaData.get(this.yPlayerPosition).get(this.xPlayerPosition);\n\t\t\tthis.checkCurrentPositionDataAndSetProperties(this.currentPixelData);\n\t\t}\n\t\telse {\n\t\t\tif (!this.player.isLockedWalking()) {\n\t\t\t\tthis.trigger = this.checkForTrigger(this.xPlayerPosition, this.yPlayerPosition);\n\t\t\t\tif (this.trigger != null) {\n\t\t\t\t\tthis.setTriggerBeingTriggered();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (this.isTriggerBeingTriggered() && this.trigger != null)\n\t\t\tthis.handleTriggerActions();\n\t\telse if ((this.isTriggerBeingTriggered() && this.trigger == null) || !this.isTriggerBeingTriggered()) {\n\t\t\tthis.unsetTriggerBeingTriggered();\n\t\t\tthis.handlePlayerActions();\n\t\t}\n\n\t\t// Area specific entities are updated at the end.\n\t\tthis.areaObstacles.forEach(\n\t\t\t(key, obstacleValue) -> {\n\t\t\t\tobstacleValue.tick();\n\t\t\t}\n\t\t);\n\n\t\tthis.areaCharacters.forEach(\n\t\t\t(key, character) -> {\n\t\t\t\tcharacter.tick();\n\t\t\t}\n\t\t);\n\t}\n\n\tprivate void handleTriggerActions() {\n\t\tif (this.trigger.hasActiveScript(this)) {\n\t\t\tthis.trigger.prepareActiveScript();\n\t\t\tthis.player.enableAutomaticMode();\n\t\t\tthis.trigger.tick(this);\n\t\t}\n\t\telse {\n\t\t\tthis.player.disableAutomaticMode();\n\t\t\tthis.unsetTriggerBeingTriggered();\n\t\t\tthis.trigger = null;\n\t\t}\n\t}\n\n\tprivate void handlePlayerActions() {\n\t\tif (!this.player.isLockedWalking()) {\n\t\t\t// Update the area's X and Y player position from the Player object.\n\t\t\tthis.xPlayerPosition = this.player.getXInArea();\n\t\t\tthis.yPlayerPosition = this.player.getYInArea();\n\n\t\t\t// Do some bounds checking on the X and Y player positions.\n\t\t\tboolean isXOutOfBounds = this.xPlayerPosition < 0 || this.xPlayerPosition >= this.width;\n\t\t\tboolean isYOutOfBounds = this.yPlayerPosition < 0 || this.yPlayerPosition >= this.height;\n\t\t\tif (isXOutOfBounds || isYOutOfBounds)\n\t\t\t\treturn;\n\n\t\t\t// Target pixel is used to determine what pixel the player is currently standing\n\t\t\t// on (or what pixel the player is currently on top of).\n\t\t\tthis.player.handleSurroundingTiles(this);\n\t\t\tthis.checkCurrentPositionDataAndSetProperties(this.getPixelData(this.xPlayerPosition, this.yPlayerPosition));\n\t\t}\n\t\telse {\n\t\t\tif (!this.player.isLockedJumping() && this.player.isLockedWalking()) {\n\t\t\t\t// It may be possible the player is still in the air, and hasn't done checking\n\t\t\t\t// if the current pixel data is a ledge or not. This continues the data checking. It's required.\n\t\t\t\tthis.xPlayerPosition = this.player.getXInArea();\n\t\t\t\tthis.yPlayerPosition = this.player.getYInArea();\n\n\t\t\t\t// Do some bounds checking on the X and Y player positions.\n\t\t\t\tboolean isXOutOfBounds = this.xPlayerPosition < 0 || this.xPlayerPosition >= this.width;\n\t\t\t\tboolean isYOutOfBounds = this.yPlayerPosition < 0 || this.yPlayerPosition >= this.height;\n\t\t\t\tif (isXOutOfBounds || isYOutOfBounds)\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.currentPixelData = this.areaData.get(this.yPlayerPosition).get(this.xPlayerPosition);\n\t\t\tthis.checkCurrentPositionDataAndSetProperties(this.getCurrentPixelData());\n\t\t}\n\t}\n\n\tprivate TriggerData checkForTrigger(int playerX, int playerY) {\n\t\tif (this.triggerDatas.isEmpty())\n\t\t\treturn null;\n\t\tTriggerData data = this.triggerDatas.get(Map.entry(playerX, playerY));\n\t\tTriggerData oldData = this.triggerDatas.get(Map.entry(this.oldXTriggerPosition, this.oldYTriggerPosition));\n\t\tif (oldData != null && !oldData.isNpcTrigger() && oldData.isPaused() && (playerX != this.oldXTriggerPosition || playerY != this.oldYTriggerPosition)) {\n\t\t\t// Need to unpause old trigger data if the trigger data was previously paused and the player has\n\t\t\t// left the trigger tile.\n\t\t\toldData.setPaused(false);\n\t\t\tthis.oldXTriggerPosition = -1;\n\t\t\tthis.oldYTriggerPosition = -1;\n\t\t}\n\t\tif (data != null && !data.isNpcTrigger() && data.getXAreaPosition() == playerX && data.getYAreaPosition() == playerY) {\n\t\t\tthis.oldXTriggerPosition = data.getXAreaPosition();\n\t\t\tthis.oldYTriggerPosition = data.getYAreaPosition();\n\t\t\treturn data;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Checks the pixel data the player is currently on, and sets the tile properties according to the\n\t * documentation provided. The tile the pixel data is representing determines the properties this\n\t * will set, and will affect how the game interacts with the player.\n\t *\n\t * @return Nothing.\n\t */\n\tpublic void checkCurrentPositionDataAndSetProperties(PixelData data) {\n\t\t// TODO: Fix this checkup.\n\t\tint pixel = data.getColor();\n\t\tint alpha = (pixel >> 24) & 0xFF;\n\t\tint red = (pixel >> 16) & 0xFF;\n\t\tint green = (pixel >> 8) & 0xFF;\n\t\tint blue = pixel & 0xFF;\n\t\tswitch (alpha) {\n\t\t\tcase 0x02: // Ledges\n\t\t\t{\n\t\t\t\tswitch (red) {\n\t\t\t\t\tcase 0x00: // Bottom\n\t\t\t\t\t\tthis.player.setLockJumping(red, green, blue, Character.UP, Character.DOWN);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x01: // Bottom Left\n\t\t\t\t\t\t// this.player.setLockJumping(red, green, blue, Player.UP, Player.DOWN);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x02: // left\n\t\t\t\t\t\tthis.player.setLockJumping(red, green, blue, Character.LEFT, Character.RIGHT);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x03: // top left\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x04: // top\n\t\t\t\t\t\tif (this.checkIfValuesAreAllowed(this.getSurroundingTileID(0, -1), 0x01))\n\t\t\t\t\t\t\tthis.player.setLockJumping(red, green, blue, Character.DOWN, Character.UP);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x05: // top right\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x06: // right\n\t\t\t\t\t\tthis.player.setLockJumping(red, green, blue, Character.RIGHT, Character.LEFT);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x07: // bottom right\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 0x04: // Determines warp zone.\n\t\t\t\tif (!this.player.isLockedWalking()) {\n\t\t\t\t\tthis.isInWarpZone = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 0x05: // Area Connection Point.\n\t\t\t\tif (!this.player.isLockedWalking() && !this.isInWarpZone) {\n\t\t\t\t\tthis.isInSectorPoint = true;\n\t\t\t\t\tthis.sectorID = this.currentPixelData.getTargetSectorID();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 0x07: // Water tiles. Checks to see if player is in the water.\n\t\t\t\tif (!this.player.isInWater())\n\t\t\t\t\tthis.player.goesInWater();\n\t\t\t\tbreak;\n\t\t\tcase 0x09: // House Doors are a type of warp zones.\n\t\t\t\tif (!this.player.isLockedWalking()) {\n\t\t\t\t\tthis.isInWarpZone = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 0x0B: // Carpet Indoors\n\t\t\t\t// this.displayExitArrow = true;\n\t\t\t\tbreak;\n\t\t\tcase 0x0C: // Carpet Outdoors\n\t\t\t\t// this.displayExitArrow = true;\n\t\t\t\tbreak;\n\t\t\tcase 0x0D: // Triggers\n\t\t\t\tif (red == 0x00) { // Default starting Point\n\t\t\t\t\tthis.setPixelData(\n\t\t\t\t\t\tnew PixelData(0x01000000, this.currentPixelData.xPosition, this.currentPixelData.yPosition),\n\t\t\t\t\t\tthis.currentPixelData.xPosition, this.currentPixelData.yPosition\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t// If no special tiles, then it will keep reseting the flags.\n\t\t\t\tif (!this.player.isLockedWalking() || !this.player.isLockedJumping()) {\n\t\t\t\t\tthis.isInWarpZone = false;\n\t\t\t\t\tthis.isInSectorPoint = false;\n\t\t\t\t}\n\t\t\t\t// This is to check to see if player has left the water.\n\t\t\t\tif (this.player.isInWater())\n\t\t\t\t\tthis.player.startsWalking();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/**\n\t * Renders the bitmap tiles based on the given pixel data.\n\t *\n\t * <p>\n\t * Note that this is where the bitmap animation works by updating the bitmap after it has been\n\t * rendered to the screen.\n\t *\n\t * @param screen\n\t * The screen display where the bitmaps are to output to.\n\t * @param xOff\n\t * The X offset based on the player's X position in absolute world coordinates. The\n\t * absolute world coordinates mean the precise X position on the Canvas.\n\t * @param yOff\n\t * The Y offset based on the player's Y position in absolute world coordinates. The\n\t * absolute world coordinates mean the precise Y position on the Canvas.\n\t * @return Nothing.\n\t *\n\t */\n\t@Override\n\tpublic void render(Scene screen, Graphics graphics, int xOff, int yOff) {\n\t\t// Rendering area background tiles.\n\t\tfor (int y = 0; y < this.height; y++) {\n\t\t\tfor (int x = 0; x < this.width; x++) {\n\t\t\t\tPixelData data = this.areaData.get(y).get(x);\n\t\t\t\tscreen.blitBiome(data.getBiomeBitmap(), x * Tileable.WIDTH - xOff, y * Tileable.HEIGHT - yOff, data);\n\n\t\t\t\t// We do not render the pixel data if the pixel data is hidden from view.\n\t\t\t\tif (!data.isHidden()) {\n\t\t\t\t\tscreen.blitBiome(data.getBitmap(), x * Tileable.WIDTH - xOff, y * Tileable.HEIGHT - yOff, data);\n\t\t\t\t}\n\t\t\t\t// This is for rendering exit arrows when you are in front of the exit/entrance doors.\n\t\t\t\tif (x == this.player.getXInArea() && y == this.player.getYInArea()\n\t\t\t\t\t&& ((((data.getColor() >> 24) & 0xFF) == 0x0B) || (((data.getColor() >> 24) & 0xFF) == 0x04)))\n\t\t\t\t\tthis.renderExitArrow(screen, xOff, yOff, data, x, y);\n\n\t\t\t\t// Each time the area background tile is rendered, it also updates the bitmap tick updates.\n\t\t\t\tdata.renderTick();\n\t\t\t}\n\t\t}\n\n\t\t// Obstacle dialogues are rendered on top of the area background tiles.\n\t\tthis.areaObstacles.forEach(\n\t\t\t(k, obstacle) -> {\n\t\t\t\tobstacle.dialogueRender(screen);\n\t\t\t}\n\t\t);\n\n\t\t// Entities are rendered here.\n\t\tthis.areaCharacters.forEach(\n\t\t\t(k, character) -> {\n\t\t\t\tcharacter.render(screen, graphics, xOff, yOff);\n\t\t\t}\n\t\t);\n\n\t\tif (this.trigger != null) {\n\t\t\tscreen.setOffset(0, 0);\n\t\t\tthis.trigger.render(screen, screen.getBufferedImage().createGraphics());\n\t\t\tscreen.setOffset(screen.getWidth() / 2 - Tileable.WIDTH, (screen.getHeight() - Tileable.HEIGHT) / 2);\n\t\t}\n\t}\n\n\t// Getters/Setters\n\tpublic int getPlayerX() {\n\t\treturn this.player.getX();\n\t}\n\n\tpublic int getPlayerXInArea() {\n\t\tthis.xPlayerPosition = this.player.getXInArea();\n\t\treturn this.xPlayerPosition;\n\t}\n\n\tpublic void setPlayerX(int x) {\n\t\tthis.xPlayerPosition = x;\n\t\tthis.player.setAreaX(x);\n\t}\n\n\tpublic void setSectorID(int value) {\n\t\tthis.sectorID = value;\n\t}\n\n\tpublic int getPlayerY() {\n\t\treturn this.player.getY();\n\t}\n\n\tpublic int getPlayerYInArea() {\n\t\tthis.yPlayerPosition = this.player.getYInArea();\n\t\treturn this.yPlayerPosition;\n\t}\n\n\tpublic void setPlayerY(int y) {\n\t\tthis.yPlayerPosition = y;\n\t\tthis.player.setAreaY(y);\n\t}\n\n\tpublic void setDebugDefaultPosition() {\n\t\t// When the game starts from the very beginning, the player must always start\n\t\t// from the very first way point.\n\t\tSET_LOOP:\n\t\tfor (List<PixelData> pixelDataRow : this.areaData) {\n\t\t\tfor (PixelData pixelData : pixelDataRow) {\n\t\t\t\tif (((pixelData.getColor() >> 24) & 0xFF) == 0x0D) {\n\t\t\t\t\tthis.setPlayerX(pixelData.xPosition);\n\t\t\t\t\tthis.setPlayerY(pixelData.yPosition);\n\t\t\t\t\tthis.currentPixelData = this.areaData.get(pixelData.yPosition).get(pixelData.xPosition);\n\t\t\t\t\tbreak SET_LOOP;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Sets the player's position according to the given warp point pixel data.\n\t *\n\t * It's mostly used in conjunction with initializing the area with the player position set.\n\t *\n\t * @param data\n\t * The pixel data used to set the default player's position.\n\t */\n\tpublic void setDefaultPosition(PixelData data) {\n\t\tint color = data.getColor();\n\t\tint alpha = (color >> 24) & 0xFF;\n\t\tswitch (alpha) {\n\t\t\tcase 0x04: // Warp point\n\t\t\tcase 0x09: // Door\n\t\t\tcase 0x0B: // Carpet (Indoors)\n\t\t\tcase 0x0C: // Carpet (Outdoors)\n\t\t\tcase 0x0D: // Default starting point.\n\t\t\t{\n\t\t\t\tint green = (color >> 8) & 0xFF;\n\t\t\t\tint blue = color & 0xFF;\n\t\t\t\tthis.setPlayerX(green);\n\t\t\t\tthis.setPlayerY(blue);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean playerIsInWarpZone() {\n\t\treturn this.isInWarpZone;\n\t}\n\n\tpublic void playerWentPastWarpZone() {\n\t\tthis.isInWarpZone = false;\n\t}\n\n\tpublic PixelData getCurrentPixelData() {\n\t\t// Return the pixel data the player is currently on top of.\n\t\tif (this.currentPixelData != null)\n\t\t\treturn this.currentPixelData;\n\n\t\t// If current pixel data is null, it means the player has not moved off the tile after the area has\n\t\t// been loaded in, and did not trigger an update to set this variable to be the current pixel data\n\t\t// tile. So, we need to fetch the current pixel data from the \"pool of area pixel data\" using the\n\t\t// current X and Y player positions to handle this edge case.\n\t\tthis.currentPixelData = this.areaData.get(this.yPlayerPosition).get(this.xPlayerPosition);\n\t\treturn this.currentPixelData;\n\t}\n\n\tpublic int getAreaID() {\n\t\treturn this.areaID;\n\t}\n\n\tpublic boolean playerIsInConnectionPoint() {\n\t\treturn this.isInSectorPoint;\n\t}\n\n\tpublic boolean playerHasLeftConnectionPoint() {\n\t\tif (this.isInSectorPoint && this.player.isLockedWalking()) {\n\t\t\t// Leaving\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic int getSectorID() {\n\t\treturn this.sectorID;\n\t}\n\n\t/**\n\t * Obtains the tile ID of the tile being offset by the player's position.\n\t *\n\t * @param xOffset\n\t * The X value offset from the player's X position.\n\t * @param yOffset\n\t * The Y value offset from the player's Y position.\n\t * @return The tile ID of the tile chosen.\n\t */\n\tpublic int getSurroundingTileID(int xOffset, int yOffset) {\n\t\tPixelData data;\n\t\ttry {\n\t\t\tdata = this.areaData.get(this.yPlayerPosition + yOffset).get(this.xPlayerPosition + xOffset);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (data != null) {\n\t\t\treturn (data.getColor() >> 24) & 0xFF;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/**\n\t * Obtains the tile ID of the tile being offset by the Character's position.\n\t *\n\t * @param xOffset\n\t * The X value offset from the player's X position.\n\t * @param yOffset\n\t * The Y value offset from the player's Y position.\n\t * @return The tile ID of the tile chosen.\n\t */\n\tpublic int getCharacterSurroundingTileID(Character entity, int xOffset, int yOffset) {\n\t\tPixelData data;\n\t\ttry {\n\t\t\tdata = this.areaData.get(entity.getY() + yOffset).get(entity.getX() + xOffset);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (data != null) {\n\t\t\treturn (data.getColor() >> 24) & 0xFF;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/**\n\t * Compares target tile ID with other multiple tile IDs to see if they are one of many tiles that\n\t * the player is allowed to walk on, or when the conditions are right for the player to move on the\n\t * tile.\n\t *\n\t * @param targetIDToCompare\n\t * The target tile ID used to test and see if it's allowable for the player to move/walk\n\t * on. Use getSurroundingTileID() to fetch the target tile ID.\n\t * @param multipleTileIDs\n\t * The many tile IDs that are to be compared to the target tile ID to see if the target\n\t * tile ID is one of the allowed tile IDs. You may use as many tile IDs for comparison as\n\t * you wished.\n\t * @return True, if the target tile ID is one of the many tile IDs that's allowable. False, if none\n\t * of the tile IDs match the target tile ID.\n\t *\n\t */\n\tpublic boolean checkIfValuesAreAllowed(int targetIDToCompare, int... multipleTileIDs) {\n\t\tboolean result = false;\n\t\tfor (int a : multipleTileIDs) {\n\t\t\tif (targetIDToCompare == a) {\n\t\t\t\tresult = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic int getTileColor(int xOffset, int yOffset) {\n\t\tPixelData data;\n\t\ttry {\n\t\t\tdata = this.areaData.get(this.yPlayerPosition + yOffset).get(this.xPlayerPosition + xOffset);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\treturn 0;\n\t\t}\n\t\tif (data != null) {\n\t\t\treturn (data.getColor());\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic void setPixelData(PixelData data, int xPosition, int yPosition) {\n\t\tdata.xPosition = xPosition;\n\t\tdata.yPosition = yPosition;\n\t\tthis.areaData.get(yPosition).set(xPosition, data);\n\t\tthis.modifiedAreaData.add(data);\n\t}\n\n\tpublic void updateItem(Item item) {\n\t\tPixelData data = item.getPixelData();\n\t\t// It is written like this to prevent possible exceptions complaining about \"cannot modify list\n\t\t// while it is reading data.\"\n\t\tfinal int x = data.xPosition;\n\t\tfinal int y = data.yPosition;\n\t\tthis.areaData.get(y).set(x, data);\n\t\tthis.modifiedAreaData.add(data);\n\t}\n\n\tpublic void loadModifiedPixelDataList() {\n\t\tfor (PixelData px : this.modifiedAreaData) {\n\t\t\tthis.areaData.get(px.yPosition).set(px.xPosition, px);\n\t\t}\n\t\tthis.modifiedAreaData.clear();\n\t}\n\n\tpublic Set<PixelData> getModifiedPixelDataList() {\n\t\treturn this.modifiedAreaData;\n\t}\n\n\t/**\n\t * This is the main function that determines whether the pixel data is walkable, or it is occupied\n\t * by an entity.\n\t *\n\t * @param x\n\t * @param y\n\t * @return\n\t */\n\tpublic PixelData getPixelData(int x, int y) {\n\t\t// These objects have the same higher priority over tileset data.\n\n\t\t// NPC data has higher priority over obstacles and items.\n\t\tCharacter npcData = this.areaCharacters.get(Map.entry(x, y));\n\t\tif (npcData != null) {\n\t\t\treturn npcData.getPixelData();\n\t\t}\n\t\t// Obstacles and items are both on the same priority.\n\t\tObstacle obstacleData = this.areaObstacles.get(Map.entry(x, y));\n\t\tItem itemData = this.areaItems.get(Map.entry(x, y));\n\t\tif (obstacleData != null || itemData != null) {\n\t\t\treturn (obstacleData != null ? obstacleData : itemData).getPixelData();\n\t\t}\n\t\t// If nothing else, tileset data is the final priority.\n\t\treturn this.areaData.get(y).get(x);\n\t}\n\n\tpublic List<List<PixelData>> getAllPixelDatas() {\n\t\treturn this.areaData;\n\t}\n\n\tpublic Map<Map.Entry<Integer, Integer>, Character> getCharactersMap() {\n\t\treturn this.areaCharacters;\n\t}\n\n\tpublic Map<Map.Entry<Integer, Integer>, Obstacle> getObstaclesMap() {\n\t\treturn this.areaObstacles;\n\t}\n\n\tpublic Map<Map.Entry<Integer, Integer>, TriggerData> getTriggerDatasMap() {\n\t\treturn this.triggerDatas;\n\t}\n\n\tpublic boolean isDisplayingExitArrow() {\n\t\treturn this.isExitArrowDisplayed;\n\t}\n\n\tpublic Player getPlayer() {\n\t\treturn this.player;\n\t}\n\n\tpublic TriggerData getTriggerData() {\n\t\treturn this.trigger;\n\t}\n\n\tpublic boolean isTriggerBeingTriggered() {\n\t\treturn this.isTriggerTriggered;\n\t}\n\n\tpublic void setTriggerBeingTriggered() {\n\t\tthis.isTriggerTriggered = true;\n\t}\n\n\tpublic void unsetTriggerBeingTriggered() {\n\t\tthis.isTriggerTriggered = false;\n\t}\n\n\tpublic Entity getEntity(int x, int y) {\n\t\t// Characters are movable entities, so it needs a different method of fetching them.\n\t\tCharacter character = this.findCharacterAt(x, y);\n\t\tif (character != null)\n\t\t\treturn character;\n\n\t\t// Only obstacles and items are immovable entities.\n\t\tPixelData data = this.getPixelData(x, y);\n\t\tif (Entity.isObstacle(data)) {\n\t\t\tObstacle obstacle = this.areaObstacles.get(Map.entry(x, y));\n\t\t\tif (obstacle != null && obstacle.getPixelData().equals(data)) {\n\t\t\t\treturn obstacle;\n\t\t\t}\n\t\t\telse if (obstacle == null) {\n\t\t\t\tthis.areaObstacles.put(Map.entry(x, y), (obstacle = Obstacle.build(this, data, x, y)));\n\t\t\t}\n\t\t}\n\t\telse if (Entity.isItem(data)) {\n\t\t\tItem item = this.areaItems.get(Map.entry(x, y));\n\t\t\tif (item != null && item.getPixelData().equals(data)) {\n\t\t\t\treturn item;\n\t\t\t}\n\t\t\telse if (item == null) {\n\t\t\t\tthis.areaItems.put(Map.entry(x, y), (item = Item.build(data, x, y)));\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Character findCharacterAt(int x, int y) {\n\t\tList<Character> npcs = this.areaCharacters.entrySet().parallelStream().map(Map.Entry::getValue).collect(Collectors.toList());\n\t\tfor (Character c : npcs) {\n\t\t\tif (c.isLockedWalking()) {\n\t\t\t\tint oldX = c.getOldX();\n\t\t\t\tint oldY = c.getOldY();\n\t\t\t\tint newX = c.getPredictedX();\n\t\t\t\tint newY = c.getPredictedY();\n\t\t\t\tif ((x == oldX && y == oldY) || (x == newX && y == newY) || (x == newX && y == oldY) || (x == oldX && y == newY)) {\n\t\t\t\t\treturn c;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (x == c.getX() && y == c.getY()) {\n\t\t\t\treturn c;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic final String getChecksum() {\n\t\treturn this.checksum;\n\t}\n\n\t// --------------------- STATIC METHODS -----------------------\n\n\tpublic static int getAreaIDFromBitmap(Bitmap bitmap) {\n\t\tif (bitmap == null) {\n\t\t\tthrow new IllegalArgumentException(\"Bitmap is null. Cannot identify area ID from null bitmap.\");\n\t\t}\n\t\tint[] pixels = bitmap.getPixels();\n\t\treturn (pixels[0] >> 16) & 0xFFFF;\n\t}\n\n\t// --------------------- OVERRIDDEN METHODS -------------------\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj != null && obj instanceof String str) {\n\t\t\tif (!(this.areaName.equals(str))) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\telse if (obj != null && obj instanceof Integer BigInt) {\n\t\t\tif (!(this.areaID == BigInt.intValue())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tbyte[] bytes = this.areaName.getBytes();\n\t\tint hash = 1;\n\t\tfor (int i = 0; i < bytes.length; i++) {\n\t\t\thash = hash * 3 + bytes[i];\n\t\t}\n\t\treturn hash;\n\t}\n\n\t// --------------------- PRIVATE METHODS ----------------------\n\n\tprivate void renderExitArrow(Scene screen, int xOff, int yOff, PixelData data, int x, int y) {\n\t\tint height = this.getHeight();\n\t\tif (y + 1 == height && this.player.getFacing() == Character.DOWN) {\n\t\t\tscreen.blitBiome(data.getBiomeBitmap(), x * Tileable.WIDTH - xOff + 4, (y + 1) * Tileable.HEIGHT - yOff + 2, data);\n\t\t\tthis.isExitArrowDisplayed = true;\n\t\t}\n\t\telse if (y == 0 && this.player.getFacing() == Character.UP) {\n\t\t\t// TODO: Draw exit arrow point upwards.\n\t\t}\n\t\telse\n\t\t\tthis.isExitArrowDisplayed = false;\n\t}\n}",
"public class WorldConstants {\n\tprivate WorldConstants() {\n\t\t// Add/delete a map area, update everything shown below.\n\t}\n\n\t// Item IDs\n\tpublic static final int ITEM_RETURN = 0;\n\tpublic static final int ITEM_TEST = 1;\n\tpublic static final int ITEM_3_OPTIONS = 2;\n\tpublic static final int ITEM_BICYCLE = 3;\n\n\t// Entity Types\n\tpublic static final int ENTITY_TYPE_OBSTACLE = 0x03;\n\tpublic static final int ENTITY_TYPE_CHARACTER = 0x0E;\n\tpublic static final int ENTITY_TYPE_ITEM = 0x0A;\n\n\t// Biome Colors\n\tpublic static final int GRASS_GREEN = 0xFFA4E767;\n\tpublic static final int MOUNTAIN_BROWN = 0xFFD5B23B;\n\n\t// Building Roof Colors / Main Area Color Theme\n\tpublic static final int AREA_1_COLOR = 0xFFC495B0;\n\tpublic static final int AREA_2_COLOR = 0xFF345CBD;\n\n\t// World IDs\n\tpublic static final int OVERWORLD = 0x0A000001;\n\n\t// Dialogues\n\tpublic static List<Map.Entry<Dialogue, Integer>> signTexts = DialogueBuilder.loadDialogues(\"art/dialogue/dialogue.txt\");\n\n\t// NOTE(Thompson): We're going to start building items instead of loading items from script files.\n\t// Items\n\t// public static HashMap<Integer, ItemText> itemms = Item.loadItemResources(\"item/items.txt\");\n\t// public static List<Map.Entry<ItemText, Item>> items =\n\t// ItemBuilder.loadItems(\"art/item/items.txt\");\n\n\t// Areas\n\tpublic static final int CHECKSUM_MAX_BYTES_LENGTH = 16;\n\tpublic static List<Area> areas = new ArrayList<>(0);\n\tpublic static List<Area> moddedAreas = new ArrayList<>(0);\n\n\t// Main Menu Item Names\n\tpublic static final String MENU_ITEM_NAME_EXIT = \"EXIT\";\n\tpublic static final String MENU_ITEM_NAME_INVENTORY = \"PACK\";\n\tpublic static final String MENU_ITEM_NAME_SAVE = \"SAVE\";\n\n\t// Main Menu Item Descriptions\n\tpublic static final String MENU_ITEM_DESC_EXIT = \"Exit the menu.\";\n\tpublic static final String MENU_ITEM_DESC_INVENTORY = \"Open the pack.\";\n\tpublic static final String MENU_ITEM_DESC_SAVE = \"Save the game.\";\n\n\t// Default scripts path. For internal use only.\n\tpublic static final String ScriptsDefaultPath = \"/art/script\";\n\n\t// Modded maps enabled?\n\tpublic static Boolean isModsEnabled = null;\n\n\t// Movement\n\t// TODO (11/24/2014): Make map more flexible by allowing scripting files of\n\t// different filenames to be loaded. Not sure where it was being loaded.\n\tpublic static List<Script> scripts = new ArrayList<>(0);\n\tpublic static List<Script> moddedScripts = new ArrayList<>(0);\n\t// public static ArrayList<Script> gameScripts =\n\t// Script.loadScript(\"script/aas.script\"); // TODO (6/19/2015): Check to see why\n\t// there's a need to load \"aas.script\".\n\n\t// Custom scripts\n\t// This array list is made for a script + area file name. They both go together.\n\t// public static ArrayList<Map.Entry<Script, String>> customScripts = new\n\t// ArrayList<Map.Entry<Script, String>>();\n\n\t// All bitmaps\n\tpublic static List<Bitmap> bitmaps = new ArrayList<>();\n\n\t/**\n\t * Returns the area matching the given area ID value.\n\t * \n\t * @param areaID\n\t * The area ID value.\n\t * @return The Area object with the matching area ID value. If no matching value exists, it returns\n\t * null.\n\t */\n\tpublic static Area convertToArea(List<Area> areas, int areaID) {\n\t\tfor (int i = 0; i < areas.size(); i++) {\n\t\t\tArea area = areas.get(i);\n\t\t\tif (area != null && area.getAreaID() == areaID)\n\t\t\t\treturn area;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * <p>\n\t * Checks to see if there exists custom maps in the \"mod\" folder.\n\t * </p>\n\t * \n\t * @return Nothing\n\t */\n\tpublic static void checkForMods() {\n\t\tif (WorldConstants.isModsEnabled == null) {\n\t\t\tif (Mod.moddedAreas.isEmpty()) {\n\t\t\t\tWorldConstants.isModsEnabled = Boolean.FALSE;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tWorldConstants.isModsEnabled = Boolean.TRUE;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns all available areas defined.\n\t * \n\t * @return A List<Area> object containing all available areas in specified order defined.\n\t */\n\tpublic static List<Area> getAllNewAreas() {\n\t\t// List<Area> result = new ArrayList<Area>();\n\t\tif (WorldConstants.isModsEnabled == Boolean.FALSE || WorldConstants.isModsEnabled == null) {\n\t\t\tif (WorldConstants.areas.isEmpty()) {\n\t\t\t\tWorldConstants.areas.add(new Area(Art.testArea));\n\t\t\t\tWorldConstants.areas.add(new Area(Art.testArea2));\n\t\t\t\tWorldConstants.areas.add(new Area(Art.debugArea));\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// WorldConstants.addNewArea(Art.testArea);\n\t\t\t\t// WorldConstants.addNewArea(Art.testArea2);\n\t\t\t}\n\t\t\t// result.add(new Area(Art.testArea3, TEST_WORLD_3));\n\t\t\t// result.add(new Area(Art.testArea4, TEST_WORLD_4));\n\t\t\t// result.add(new Area(Art.testArea_debug, Debug));\n\t\t\treturn WorldConstants.areas;\n\t\t}\n\t\telse {\n\t\t\tfor (int i = 0; i < Mod.moddedAreas.size(); i++) {\n\t\t\t\tMap.Entry<Bitmap, Integer> entry = Mod.moddedAreas.get(i);\n\t\t\t\tWorldConstants.moddedAreas.add(new Area(entry.getKey()));\n\t\t\t}\n\t\t\treturn WorldConstants.moddedAreas;\n\t\t}\n\t}\n\n\t/**\n\t * Returns all available scripts defined.\n\t * \n\t * @return A List<Script> object containing all available scripts in specified order defined.\n\t */\n\tpublic static List<Script> getAllNewScripts() {\n\t\tif (WorldConstants.isModsEnabled == null) {\n\t\t\tif (Mod.moddedAreas.isEmpty()) {\n\t\t\t\tWorldConstants.isModsEnabled = Boolean.FALSE;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tWorldConstants.isModsEnabled = Boolean.TRUE;\n\t\t\t}\n\t\t}\n\t\tif (WorldConstants.isModsEnabled.booleanValue()) {\n\t\t\tWorldConstants.moddedScripts = Script.loadModdedScriptsNew();\n\t\t\treturn WorldConstants.moddedScripts;\n\t\t}\n\t\telse {\n\t\t\tWorldConstants.scripts = Script.loadDefaultScripts();\n\t\t\treturn WorldConstants.scripts;\n\t\t}\n\t}\n\n\t/**\n\t * Goes with the static method, \"getAllNewAreas()\".\n\t */\n\t@SuppressWarnings(\"unused\")\n\tprivate static void addNewArea(Bitmap bitmap) {\n\t\tDebug.toDo(\"Utilize this method when the opportunity arises.\");\n\t\tint areaID = Area.getAreaIDFromBitmap(bitmap);\n\t\t// Java 8 feature\n\t\tboolean exists = WorldConstants.areas.stream()\n\t\t\t.filter(chosenArea -> chosenArea.getAreaID() == areaID)\n\t\t\t.findFirst()\n\t\t\t.isPresent();\n\t\tif (!exists) {\n\t\t\tWorldConstants.areas.add(new Area(bitmap));\n\t\t}\n\t}\n\n\t/**\n\t * Returns the area color theme of the given area ID.\n\t * \n\t * @param areaID\n\t * The area ID value.\n\t * @return The primary area color of full opacity.\n\t */\n\tpublic static int convertToAreaColor(int areaID) {\n\t\tswitch (areaID % 2) {\n\t\t\tcase 0x01:\n\t\t\t\treturn WorldConstants.AREA_1_COLOR;\n\t\t\tcase 0x00:\n\t\t\t\treturn WorldConstants.AREA_2_COLOR;\n\t\t\tdefault:\n\t\t\t\treturn 0;\n\t\t}\n\t}\n}",
"public class Scene extends Bitmap {\n\tpublic enum FlashingType {\n\t\tNORMAL,\n\t\tBURST\n\t}\n\n\t// TODO: Add more drawing functions that enable more controls when it comes to\n\t// rendering assets.\n\n\tprotected BufferedImage image;\n\tprotected Graphics graphics;\n\tprotected int xOffset;\n\tprotected int yOffset;\n\n\tprivate static final byte MAX_TICK_LIMIT = 0x7;\n\tprivate byte tick = Scene.MAX_TICK_LIMIT;\n\n\t// private boolean cutScreen;\n\n\tpublic Scene(int w, int h) {\n\t\tsuper(w, h);\n\t\tthis.image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n\t\tthis.pixels = ((DataBufferInt) this.image.getRaster().getDataBuffer()).getData();\n\t\tthis.graphics = this.image.getGraphics();\n\t}\n\n\tpublic void loadResources() {\n\t\tArt.loadAllResources(this);\n\t\tMod.loadModdedResources();\n\t}\n\n\tpublic BufferedImage getBufferedImage() {\n\t\treturn this.image;\n\t}\n\n\tpublic Graphics getGraphics() {\n\t\treturn this.graphics;\n\t}\n\n\tpublic void clear(int color) {\n\t\tArrays.fill(this.pixels, color);\n\t}\n\n\tpublic void blit(Bitmap bitmap, int x, int y) {\n\t\tif (bitmap != null)\n\t\t\tthis.blit(bitmap, x + this.xOffset, y + this.yOffset, bitmap.width, bitmap.height);\n\t}\n\n\tpublic void blitBiome(Bitmap bitmap, int x, int y, PixelData data) {\n\t\tif (bitmap != null) {\n\t\t\tthis.blitBiome(bitmap, x + this.xOffset, y + this.yOffset, bitmap.width, bitmap.height, data);\n\t\t}\n\t}\n\n\tpublic void npcBlit(Bitmap bitmap, int x, int y) {\n\t\tif (bitmap != null)\n\t\t\tthis.blit(bitmap, x + this.xOffset, y + this.yOffset - 4, bitmap.width, bitmap.height);\n\t}\n\n\tpublic void blit(Bitmap bitmap, int x, int y, int w, int h) {\n\t\t// This directly blits the bitmap to the X and Y coordinates within the screen\n\t\t// area.\n\t\t// The Rect adjusts the blitting area to within the screen area.\n\t\tif (w <= -1)\n\t\t\tw = bitmap.width;\n\t\tif (h <= -1)\n\t\t\th = bitmap.height;\n\t\tRect blitArea = new Rect(x, y, w, h).adjust(this);\n\t\tint blitWidth = blitArea.bottomRightCorner_X - blitArea.topLeftCorner_X;\n\n\t\tfor (int yy = blitArea.topLeftCorner_Y; yy < blitArea.bottomRightCorner_Y; yy++) {\n\t\t\tint tgt = yy * this.width + blitArea.topLeftCorner_X;\n\t\t\tint src = (yy - y) * bitmap.width + (blitArea.topLeftCorner_X - x);\n\t\t\ttgt -= src;\n\t\t\tfor (int xx = src; xx < src + blitWidth; xx++) {\n\t\t\t\tint color = bitmap.pixels[xx];\n\t\t\t\tint alpha = (color >> 24) & 0xFF;\n\t\t\t\tif (alpha == 0xFF) {\n\t\t\t\t\tthis.pixels[tgt + xx] = color;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void blitBiome(Bitmap bitmap, int x, int y, int w, int h, PixelData data) {\n\t\t// This directly blits the bitmap to the X and Y coordinates within the screen\n\t\t// area.\n\t\t// The Rect adjusts the blitting area to within the screen area.\n\t\tif (w <= -1)\n\t\t\tw = bitmap.width;\n\t\tif (h <= -1)\n\t\t\th = bitmap.height;\n\t\tRect blitArea = new Rect(x, y, w, h).adjust(this);\n\t\tint blitWidth = blitArea.bottomRightCorner_X - blitArea.topLeftCorner_X;\n\n\t\tint dataColor = data.getColor();\n\t\tint tileID = (dataColor >> 24) & 0xFF;\n\t\tint red = (dataColor >> 16) & 0xFF;\n\t\tint green = (dataColor >> 8) & 0xFF;\n\t\tint blue = dataColor & 0xFF;\n\t\tint biomeColor = this.getBiomeBaseColor(tileID, red, green, blue);\n\t\tint tick = 0;\n\n\t\tfor (int yy = blitArea.topLeftCorner_Y; yy < blitArea.bottomRightCorner_Y; yy++) {\n\t\t\tint tgt = yy * this.width + blitArea.topLeftCorner_X;\n\t\t\tint src = (yy - y) * bitmap.width + (blitArea.topLeftCorner_X - x);\n\t\t\ttgt -= src;\n\t\t\tfor (int xx = src; xx < src + blitWidth; xx++) {\n\t\t\t\tint color = bitmap.pixels[xx];\n\t\t\t\tint alpha = (color >> 24) & 0xFF;\n\t\t\t\t// This alpha value determines the areas in the bitmap what to draw.\n\t\t\t\t// Has nothing to do with pixel data properties.\n\n\t\t\t\tswitch (alpha) {\n\t\t\t\t\tcase 0x0:\n\t\t\t\t\t\t// Biome Color with a bit of speckled light/dark patches.\n\t\t\t\t\t\tif ((tick++ % 17 < 7) && (tick++ % 21 < 2))\n\t\t\t\t\t\t\tthis.pixels[tgt + xx] = Scene.lighten(biomeColor, 0.07f);\n\t\t\t\t\t\telse if ((tick++ % 23 < 4) && (tick++ % 19 < 3))\n\t\t\t\t\t\t\tthis.pixels[tgt + xx] = Scene.darken(biomeColor, 0.07f);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tthis.pixels[tgt + xx] = biomeColor;\n\t\t\t\t\t\ttick++;\n\t\t\t\t\t\tif (tick > w * w)\n\t\t\t\t\t\t\ttick = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x32:\n\t\t\t\t\t\tthis.pixels[tgt + xx] = Scene.lighten(biomeColor, 0.003f);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x64:\n\t\t\t\t\t\tthis.pixels[tgt + xx] = Scene.lighten(biomeColor, 0.006f);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthis.pixels[tgt + xx] = color;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setOffset(int xOff, int yOff) {\n\t\tthis.xOffset = xOff;\n\t\tthis.yOffset = yOff;\n\t}\n\n\tpublic void createStaticNoise(Random r) {\n\t\tfor (int p = 0; p < this.pixels.length; p++)\n\t\t\tthis.pixels[p] = r.nextInt();\n\t}\n\n\tpublic int getXOffset() {\n\t\treturn this.xOffset;\n\t}\n\n\tpublic int getYOffset() {\n\t\treturn this.yOffset;\n\t}\n\n\tpublic boolean invert() {\n\t\tif (this.tick < 0x2) {\n\t\t\tfor (int i = 0; i < this.pixels.length; i++)\n\t\t\t\tthis.pixels[i] = 0xFF000000 | (0xAAAAAA - (this.pixels[i] & 0xFFFFFF));\n\t\t\tthis.tick++;\n\t\t\treturn true;\n\t\t}\n\t\tif (this.tick < 0x6) {\n\t\t\tfor (int i = 0; i < this.pixels.length; i++)\n\t\t\t\tthis.pixels[i] = 0xFFAAAAAA;\n\t\t\tthis.tick++;\n\t\t\treturn true;\n\t\t}\n\t\tthis.tick = Scene.MAX_TICK_LIMIT;\n\t\treturn false;\n\t}\n\n\tpublic boolean renderEffectFlashing(FlashingType speed) {\n\t\tswitch (speed) {\n\t\t\tcase NORMAL:\n\t\t\tdefault: {\n\t\t\t\tif (this.tick < Scene.MAX_TICK_LIMIT) {\n\t\t\t\t\tfor (int i = 0; i < this.pixels.length; i++)\n\t\t\t\t\t\tthis.pixels[i] = 0xFFFFFFFF;\n\t\t\t\t\tthis.tick++;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tthis.tick = Scene.MAX_TICK_LIMIT;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcase BURST: {\n\t\t\t\tif (this.tick < 0x2) {\n\t\t\t\t\tfor (int i = 0; i < this.pixels.length; i++)\n\t\t\t\t\t\tthis.pixels[i] = 0xFFAAAAAA;\n\t\t\t\t\tthis.tick++;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if (this.tick < 0x4) {\n\t\t\t\t\tfor (int i = 0; i < this.pixels.length; i++)\n\t\t\t\t\t\tthis.pixels[i] = 0xFFF7F7F7;\n\t\t\t\t\tthis.tick++;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if (this.tick < 0x6) {\n\t\t\t\t\tfor (int i = 0; i < this.pixels.length; i++)\n\t\t\t\t\t\tthis.pixels[i] = 0xFFAAAAAA;\n\t\t\t\t\tthis.tick++;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tthis.tick = Scene.MAX_TICK_LIMIT;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setRenderingEffectTick(byte value) {\n\t\tthis.tick = value;\n\t}\n\n\tpublic byte getRenderingEffectTick() {\n\t\treturn this.tick;\n\t}\n\n\tpublic boolean isRenderingEffect() {\n\t\treturn (this.tick < Scene.MAX_TICK_LIMIT);\n\t}\n\n\tpublic void resetRenderingEffect() {\n\t\tthis.tick = Scene.MAX_TICK_LIMIT;\n\t}\n\n\t// -------------------------------------------\n\t// Private methods\n\n\tprivate int getBiomeBaseColor(int tileID, int red, int green, int blue) {\n\t\tint color = WorldConstants.GRASS_GREEN;\n\t\tswitch (tileID) {\n\t\t\tcase 0x01: // Grass\n\t\t\t\tswitch (red) {\n\t\t\t\t\tcase 0x00:\n\t\t\t\t\t\tswitch (green) {\n\t\t\t\t\t\t\tcase 0x00:\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x01: // Mountain ground\n\t\t\t\t\t\tfor (int i = 0; i < blue; i++) {\n\t\t\t\t\t\t\tcolor = Scene.lighten(color, 0.1f);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 0x02: // Ledges\n\t\t\t\tswitch (green) {\n\t\t\t\t\tcase 0x00:\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x01:\n\t\t\t\t\t\tcolor = WorldConstants.MOUNTAIN_BROWN;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 0x06: // Stairs\n\t\t\t\tswitch (green) {\n\t\t\t\t\tcase 0x00:\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x01:\n\t\t\t\t\t\tcolor = WorldConstants.MOUNTAIN_BROWN;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t\treturn color;\n\t}\n\n\t// -------------------------------------------\n\t// Public static methods\n\n\tpublic static int lighten(int color, float amount) {\n\t\t// int a = (color >> 24) & 0xFF;\n\t\tint r = (color >> 16) & 0xFF;\n\t\tint g = (color >> 8) & 0xFF;\n\t\tint b = color & 0xFF;\n\t\treturn 0xFF000000 | ((int) Math.min(255, r + 255 * amount) & 0xFF) << 16\n\t\t\t| ((int) Math.min(255, g + 255 * amount) & 0xFF) << 8 | (int) Math.min(255, b + 255 * amount) & 0xFF;\n\t}\n\n\tpublic static int darken(int color, float amount) {\n\t\tint r = (color >> 16) & 0xFF;\n\t\tint g = (color >> 8) & 0xFF;\n\t\tint b = color & 0xFF;\n\t\treturn 0xFF000000 | ((int) Math.min(255, r - 255 * amount) & 0xFF) << 16\n\t\t\t| ((int) Math.min(255, g - 255 * amount) & 0xFF) << 8 | (int) Math.min(255, b - 255 * amount) & 0xFF;\n\t}\n}",
"public class DialogueBuilder {\n\tpublic static Dialogue createText(String dialogue, DialogueType type) {\n\t\treturn DialogueBuilder.createText(dialogue, Dialogue.MAX_STRING_LENGTH, type, true);\n\t}\n\n\t/**\n\t * \n\t * @param dialogue\n\t * @param length\n\t * - The max length of 1 line in the in-game dialogue box.\n\t * @param type\n\t * @param lock\n\t * @return\n\t */\n\tpublic static Dialogue createText(String dialogue, int length, DialogueType type, boolean lock) {\n\t\tDialogue dialogues = new Dialogue();\n\t\tdialogues.setLines(DialogueBuilder.toLines(dialogue, length));\n\t\tdialogues.setLineLength(length);\n\t\tdialogues.setTotalDialogueLength(dialogue.length());\n\t\tdialogues.setType(type);\n\t\tdialogues.setShowDialog(true);\n\t\tif (lock) {\n\t\t\tif (!Player.isMovementsLocked())\n\t\t\t\tPlayer.lockMovements();\n\t\t}\n\t\treturn dialogues;\n\t}\n\n\tpublic static Dialogue createText(String dialogue, int length, DialogueType type, boolean lock, boolean ignoreInputs) {\n\t\tDialogue dialogues = DialogueBuilder.createText(dialogue, length, type, lock);\n\t\tdialogues.setIgnoreInputs(ignoreInputs);\n\t\treturn dialogues;\n\t}\n\n\tpublic static List<Map.Entry<Dialogue, Integer>> loadDialogues(String filename) {\n\t\tList<Map.Entry<Dialogue, Integer>> result = new ArrayList<>();\n\t\ttry {\n\t\t\tBufferedReader reader = new BufferedReader(\n\t\t\t\tnew InputStreamReader(Dialogue.class.getClassLoader().getResourceAsStream(filename))\n\t\t\t);\n\t\t\tString line;\n\t\t\tint dialogueID = 0;\n\t\t\tDialogue temp = null;\n\t\t\twhile ((line = reader.readLine()) != null) {\n\t\t\t\tif (ScriptTags.Speech.beginsAt(line)) {\n\t\t\t\t\t// Dialogue ID\n\t\t\t\t\tdialogueID = Integer.valueOf(ScriptTags.Speech.removeScriptTag(line));\n\t\t\t\t}\n\t\t\t\telse if (ScriptTags.ScriptName.beginsAt(line)) {\n\t\t\t\t\t// Dialogue message\n\t\t\t\t\tline = line.replaceAll(\"_\", \" \");\n\t\t\t\t\ttemp = DialogueBuilder.createText(\n\t\t\t\t\t\tScriptTags.ScriptName.removeScriptTag(line),\n\t\t\t\t\t\tDialogue.MAX_STRING_LENGTH, DialogueType.SPEECH,\n\t\t\t\t\t\tfalse\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\telse if (ScriptTags.Reject.beginsAt(line)) {\n\t\t\t\t\t// Dialogue delimiter\n\t\t\t\t\tMap.Entry<Dialogue, Integer> entry = new AbstractMap.SimpleEntry<>(\n\t\t\t\t\t\ttemp,\n\t\t\t\t\t\tdialogueID\n\t\t\t\t\t);\n\t\t\t\t\tresult.add(entry);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\treturn null;\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static List<Map.Entry<String, Boolean>> toLines(String all, final int regex) {\n\t\tList<Map.Entry<String, Boolean>> lines = new ArrayList<>();\n\t\tString[] words = all.split(\"\\\\s\");\n\t\tString line = \"\";\n\t\tint length = 0;\n\t\tfor (String w : words) {\n\t\t\tif (length + w.length() + 1 > regex) {\n\t\t\t\tif (w.length() >= regex) {\n\t\t\t\t\tline += w;\n\t\t\t\t\tlines.add(new AbstractMap.SimpleEntry<>(line, false));\n\t\t\t\t\tline = \"\";\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlines.add(new AbstractMap.SimpleEntry<>(line, false));\n\t\t\t\tline = \"\";\n\t\t\t\tlength = 0;\n\t\t\t}\n\t\t\tif (length > 0) {\n\t\t\t\tline += \" \";\n\t\t\t\tlength += 1;\n\t\t\t}\n\t\t\tline += w;\n\t\t\tlength += w.length();\n\t\t}\n\t\tif (line.length() > 0)\n\t\t\tlines.add(new AbstractMap.SimpleEntry<>(line, false));\n\t\treturn lines;\n\t}\n}"
] | import java.awt.Graphics2D;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import common.Debug;
import dialogue.Dialogue;
import entity.Player;
import enums.ScriptTags;
import level.Area;
import level.WorldConstants;
import screen.Scene;
import utility.DialogueBuilder; | this.affirmativeMoves
.add(Map.entry(e.getKey(), new MovementData(e.getValue())));
this.negativeMoves = new ArrayList<>();
for (Map.Entry<Integer, MovementData> e : s.negativeMoves)
this.negativeMoves
.add(Map.entry(e.getKey(), new MovementData(e.getValue())));
this.dialogues = new ArrayList<>();
for (Map.Entry<Integer, Dialogue> e : s.dialogues)
this.dialogues
.add(Map.entry(e.getKey(), new Dialogue(e.getValue())));
this.affirmativeDialogues = new ArrayList<>();
for (Map.Entry<Integer, Dialogue> e : s.affirmativeDialogues)
this.affirmativeDialogues
.add(Map.entry(e.getKey(), new Dialogue(e.getValue())));
this.negativeDialogues = new ArrayList<>();
for (Map.Entry<Integer, Dialogue> e : s.negativeDialogues)
this.negativeDialogues
.add(Map.entry(e.getKey(), new Dialogue(e.getValue())));
this.scriptIteration = s.scriptIteration;
this.affirmativeIteration = s.affirmativeIteration;
this.negativeIteration = s.negativeIteration;
this.questionResponse = s.questionResponse;
this.repeat = s.repeat;
this.countdown = s.countdown;
this.finished = s.finished;
this.enabled = s.enabled;
}
// --------------------------------------------------------------------------------------
// Public methods.
/**
* Returns the current scripted movement action depending on what type of response the player has
* given in the game.
*
* @return
*/
public MovementData getIteratedMoves() {
if (this.questionResponse == null) {
for (Map.Entry<Integer, MovementData> entry : this.moves) {
if (entry.getKey() == this.scriptIteration)
return entry.getValue();
}
}
else if (this.questionResponse == Boolean.TRUE) {
for (Map.Entry<Integer, MovementData> entry : this.affirmativeMoves) {
if (entry.getKey() == this.affirmativeIteration)
return entry.getValue();
}
}
else if (this.questionResponse == Boolean.FALSE) {
for (Map.Entry<Integer, MovementData> entry : this.negativeMoves) {
if (entry.getKey() == this.negativeIteration)
return entry.getValue();
}
}
return null;
}
/**
* Returns the current scripted dialogue depending on what type of response the player has given in
* the game.
*
* @return
*/
public Dialogue getIteratedDialogues() {
if (this.questionResponse == null) {
for (Map.Entry<Integer, Dialogue> entry : this.dialogues) {
if (entry.getKey() == this.scriptIteration) {
return entry.getValue();
}
}
}
else if (this.questionResponse == Boolean.TRUE) {
for (Map.Entry<Integer, Dialogue> entry : this.affirmativeDialogues) {
if (entry.getKey() == this.affirmativeIteration) {
return entry.getValue();
}
}
}
else if (this.questionResponse == Boolean.FALSE) {
for (Map.Entry<Integer, Dialogue> entry : this.negativeDialogues) {
if (entry.getKey() == this.negativeIteration) {
return entry.getValue();
}
}
}
return null;
}
/**
* Sets the script to execute a positive dialogue option route when the flag is set.
*/
public void setAffirmativeFlag() {
this.questionResponse = Boolean.TRUE;
}
/**
* Sets the script to execute a negative dialogue option route when the flag is set.
*/
public void setNegativeFlag() {
this.questionResponse = Boolean.FALSE;
}
/**
* Updates the script.
*
* @param area
* @param entityX
* @param entityY
*/
public void tick(Area area) {
MovementData moves = this.getIteratedMoves();
Dialogue dialogue = this.getIteratedDialogues();
| Player player = area.getPlayer(); | 2 |
PeterCxy/BlackLight | src/us/shandian/blacklight/ui/statuses/TimeLineFragment.java | [
"public class HomeTimeLineApiCache\n{\n\tprivate static HashMap<Long, SoftReference<Bitmap>> mThumnnailCache = new HashMap<Long, SoftReference<Bitmap>>();\n\t\n\tprotected DataBaseHelper mHelper;\n\tprotected FileCacheManager mManager;\n\t\n\tpublic MessageListModel mMessages;\n\t\n\tprotected int mCurrentPage = 0;\n\n\tpublic HomeTimeLineApiCache(Context context) {\n\t\tmHelper = DataBaseHelper.instance(context);\n\t\tmManager = FileCacheManager.instance(context);\n\t}\n\t\n\tpublic void loadFromCache() {\n\t\tCursor cursor = query();\n\t\t\n\t\tif (cursor.getCount() == 1) {\n\t\t\tcursor.moveToFirst();\n\t\t\tmMessages = new Gson().fromJson(cursor.getString(1), getListClass());\n\t\t\tmCurrentPage = mMessages.getSize() / Constants.HOME_TIMELINE_PAGE_SIZE;\n\t\t\tmMessages.spanAll();\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tmMessages = getListClass().newInstance();\n\t\t\t} catch (Exception e) {\n\t\t\t\tmMessages = new MessageListModel();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void load(boolean newWeibo) {\n\t\tif (newWeibo) {\n\t\t\tmCurrentPage = 0;\n\t\t}\n\t\t\n\t\tMessageListModel list = load();\n\t\t\n\t\tif (newWeibo) {\n\t\t\tmMessages.getList().clear();\n\t\t}\n\t\t\n\t\tmMessages.addAll(false, list);\n\t}\n\t\n\tpublic Bitmap getThumbnailPic(MessageModel msg, int id) {\n\t\tString url = null;\n\t\tif (msg.hasMultiplePictures()) {\n\t\t\turl = msg.pic_urls.get(id).getThumbnail();\n\t\t} else if (id == 0) {\n\t\t\turl = msg.thumbnail_pic;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tif (url == null) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tString cacheName = url.substring(url.lastIndexOf(\"/\") + 1, url.length());\n\t\tbyte[] cache;\n\t\t\n\t\ttry {\n\t\t\tcache = mManager.getCache(Constants.FILE_CACHE_PICS_SMALL, cacheName);\n\t\t} catch (Exception e) {\n\t\t\tcache = null;\n\t\t}\n\t\t\n\t\tif (cache == null || cache.length <= 1000) {\n\t\t\ttry {\n\t\t\t\tcache = mManager.createCacheFromNetwork(Constants.FILE_CACHE_PICS_SMALL, cacheName, url);\n\t\t\t} catch (Exception e) {\n\t\t\t\tcache = null;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (cache == null) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tBitmap bmp = BitmapFactory.decodeByteArray(cache, 0, cache.length);\n\t\tmThumnnailCache.put(msg.id * 10 + id, new SoftReference<Bitmap>(bmp));\n\t\treturn bmp;\n\t}\n\t\n\tpublic Bitmap getCachedThumbnail(MessageModel msg, int id) {\n\t\tlong key = msg.id * 10 + id;\n\t\t\n\t\tif (mThumnnailCache.containsKey(key)) {\n\t\t\treturn mThumnnailCache.get(key).get();\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic Object getLargePic(MessageModel msg, int id) {\n\t\tString url = null;\n\t\tif (msg.hasMultiplePictures()) {\n\t\t\turl = msg.pic_urls.get(id).getLarge();\n\t\t} else if (id == 0) {\n\t\t\turl = msg.original_pic;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (url == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tString cacheName = url.substring(url.lastIndexOf(\"/\") + 1, url.length());\n\t\tbyte[] cache;\n\n\t\ttry {\n\t\t\tcache = mManager.getCache(Constants.FILE_CACHE_PICS_LARGE, cacheName);\n\t\t} catch (Exception e) {\n\t\t\tcache = null;\n\t\t}\n\n\t\tif (cache == null || cache.length <= 1000) {\n\t\t\ttry {\n\t\t\t\tcache = mManager.createCacheFromNetwork(Constants.FILE_CACHE_PICS_LARGE, cacheName, url);\n\t\t\t} catch (Exception e) {\n\t\t\t\tcache = null;\n\t\t\t}\n\t\t}\n\n\t\tif (cache == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (cacheName.endsWith(\".gif\")) {\n\t\t\tMovie movie = Movie.decodeByteArray(cache, 0, cache.length);\n\t\t\t\n\t\t\t// A real movie must have a dutation bigger than 0\n\t\t\t// Or it is just a static picture\n\t\t\tif (movie.duration() > 0) {\n\t\t\t\treturn movie;\n\t\t\t}\n\t\t} \n\t\t\n\t\ttry {\n\t\t\treturn BitmapFactory.decodeByteArray(cache, 0, cache.length);\n\t\t} catch (OutOfMemoryError e) {\n\t\t\t// If OOM, compress and decode.\n\t\t\tBitmapFactory.Options opt = new BitmapFactory.Options();\n\t\t\topt.inJustDecodeBounds = true;\n\t\t\tBitmapFactory.decodeByteArray(cache, 0, cache.length, opt);\n\t\t\topt.inSampleSize = Utility.computeSampleSize(opt, 512, 1024 * 1024);\n\t\t\topt.inJustDecodeBounds = false;\n\t\t\treturn BitmapFactory.decodeByteArray(cache, 0, cache.length, opt);\n\t\t}\n\t}\n\n\tpublic String saveLargePic(MessageModel msg, int id) {\n\t\tString url = null;\n\t\tif (msg.hasMultiplePictures()) {\n\t\t\turl = msg.pic_urls.get(id).getLarge();\n\t\t} else if (id == 0) {\n\t\t\turl = msg.original_pic;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (url == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tString cacheName = url.substring(url.lastIndexOf(\"/\") + 1, url.length());\n\t\ttry {\n\t\t\treturn mManager.copyCacheTo(Constants.FILE_CACHE_PICS_LARGE, cacheName, \"/sdcard/BlackLight\");\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic void cache() {\n\t\tSQLiteDatabase db = mHelper.getWritableDatabase();\n\t\tdb.beginTransaction();\n\t\tdb.execSQL(Constants.SQL_DROP_TABLE + HomeTimeLineTable.NAME);\n\t\tdb.execSQL(HomeTimeLineTable.CREATE);\n\t\t\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(HomeTimeLineTable.ID, 1);\n\t\tvalues.put(HomeTimeLineTable.JSON, new Gson().toJson(mMessages));\n\t\t\n\t\tdb.insert(HomeTimeLineTable.NAME, null, values);\n\t\t\n\t\tdb.setTransactionSuccessful();\n\t\tdb.endTransaction();\n\t}\n\t\n\tprotected Cursor query() {\n\t\treturn mHelper.getReadableDatabase().query(HomeTimeLineTable.NAME, null, null, null, null, null, null);\n\t}\n\t\n\tprotected MessageListModel load() {\n\t\treturn HomeTimeLineApi.fetchHomeTimeLine(Constants.HOME_TIMELINE_PAGE_SIZE, ++mCurrentPage);\n\t}\n\t\n\tprotected Class<? extends MessageListModel> getListClass() {\n\t\treturn MessageListModel.class;\n\t}\n}",
"public abstract class AsyncTask<Params, Progress, Result>\n{\n\tprivate static final String TAG = AsyncTask.class.getSimpleName();\n\t\n\tprivate static class AsyncResult<Data> {\n\t\tpublic AsyncTask task;\n\t\tpublic Data[] data;\n\t\t\n\t\tpublic AsyncResult(AsyncTask task, Data... data) {\n\t\t\tthis.task = task;\n\t\t\tthis.data = data;\n\t\t}\n\t}\n\t\n\tprivate static final int MSG_FINISH = 1000;\n\tprivate static final int MSG_PROGRESS = 1001;\n\t\n\tprivate static Handler sInternalHandler = new Handler() {\n\t\t@SuppressWarnings({\"unchecked\", \"RawUseOfParameterizedType\"})\n\t\t@Override\n\t\tpublic void handleMessage(Message msg) {\n\t\t\tAsyncResult result = (AsyncResult) msg.obj;\n\t\t\tswitch (msg.what) {\n\t\t\t\tcase MSG_FINISH:\n\t\t\t\t\tresult.task.onPostExecute(result.data[0]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MSG_PROGRESS:\n\t\t\t\t\tresult.task.onProgressUpdate(result.data);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t};\n\t\n\tprivate Params[] mParams;\n\t\n\tprivate Thread mThread = new Thread(new Runnable() {\n\t\t@Override\n\t\tpublic void run() {\n\t\t\tCrashHandler.register();\n\t\t\t\n\t\t\ttry {\n\t\t\t\tResult result = doInBackground(mParams);\n\t\t\t\tsInternalHandler.sendMessage(sInternalHandler.obtainMessage(MSG_FINISH, new AsyncResult<Result>(AsyncTask.this, result)));\n\t\t\t} catch (Exception e) {\n\t\t\t\t// Don't crash the whole app\n\t\t\t\tif (DEBUG) {\n\t\t\t\t\tLog.d(TAG, e.getClass().getSimpleName() + \" caught when running background task. Printing stack trace.\");\n\t\t\t\t\tLog.d(TAG, Log.getStackTraceString(e));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tThread.currentThread().interrupt();\n\t\t}\n\t});\n\t\n\tprotected void onPostExecute(Result result) {}\n\t\n\tprotected abstract Result doInBackground(Params... params);\n\t\n\tprotected void onPreExecute() {}\n\t\n\tprotected void onProgressUpdate(Progress... progress) {}\n\t\n\tprotected void publishProgress(Progress... progress) {\n\t\tsInternalHandler.sendMessage(sInternalHandler.obtainMessage(MSG_PROGRESS, new AsyncResult<Progress>(this, progress)));\n\t}\n\t\n\tpublic void execute(Params... params) {\n\t\tonPreExecute();\n\t\tmParams = params;\n\t\tmThread.start();\n\t}\n}",
"public class Settings\n{\n\tpublic static final String XML_NAME = \"settings\";\n\t\n\t// Actions\n\tpublic static final String FAST_SCROLL = \"fast_scroll\";\n\tpublic static final String RIGHT_HANDED = \"right_handed\";\n\n\t// Notification\n\tpublic static final String NOTIFICATION_SOUND = \"notification_sound\",\n\t\t\tNOTIFICATION_VIBRATE = \"notification_vibrate\",\n\t\t\tNOTIFICATION_INTERVAL = \"notification_interval\";\n\t\n\tprivate static Settings sInstance;\n\t\n\tprivate SharedPreferences mPrefs;\n\t\n\tpublic static Settings getInstance(Context context) {\n\t\tif (sInstance == null) {\n\t\t\tsInstance = new Settings(context);\n\t\t}\n\t\t\n\t\treturn sInstance;\n\t}\n\t\n\tprivate Settings(Context context) {\n\t\tmPrefs = context.getSharedPreferences(XML_NAME, Context.MODE_PRIVATE);\n\t}\n\t\n\tpublic Settings putBoolean(String key, boolean value) {\n\t\tmPrefs.edit().putBoolean(key, value).commit();\n\t\treturn this;\n\t}\n\t\n\tpublic boolean getBoolean(String key, boolean def) {\n\t\treturn mPrefs.getBoolean(key, def);\n\t}\n\t\n\tpublic Settings putInt(String key, int value) {\n\t\tmPrefs.edit().putInt(key, value).commit();\n\t\treturn this;\n\t}\n\t\n\tpublic int getInt(String key, int defValue) {\n\t\treturn mPrefs.getInt(key, defValue);\n\t}\n\t\n}",
"public class Utility\n{\n\tprivate static final String TAG = Utility.class.getSimpleName();\n\t\n\tprivate static final int REQUEST_CODE = 100001;\n\t\n\tpublic static int expireTimeInDays(long time) {\n\t\treturn (int) TimeUnit.MILLISECONDS.toDays(time - System.currentTimeMillis());\n\t}\n\t\n\tpublic static boolean isTokenExpired(long time) {\n\t\treturn time <= System.currentTimeMillis();\n\t}\n\t\n\tpublic static boolean isCacheAvailable(long createTime, int availableDays) {\n\t\treturn System.currentTimeMillis() <= createTime + TimeUnit.DAYS.toMillis(availableDays);\n\t}\n\t\n\tpublic static int lengthOfString(String str) throws UnsupportedEncodingException {\n\t\t// Considers 1 Chinese character as 2 English characters\n\t\treturn (str.getBytes(\"GB2312\").length + 1) / 2;\n\t}\n\t\n\tpublic static int getSupportedMaxPictureSize() {\n\t\tint[] array = new int[1];\n\t\tGLES10.glGetIntegerv(GLES10.GL_MAX_TEXTURE_SIZE, array, 0);\n\t\t\n\t\tif (array[0] == 0) {\n\t\t\tGLES11.glGetIntegerv(GLES11.GL_MAX_TEXTURE_SIZE, array, 0);\n\t\t\t\n\t\t\tif (array[0] == 0) {\n\t\t\t\tGLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, array, 0);\n\t\t\t\t\n\t\t\t\tif (array[0] == 0) {\n\t\t\t\t\tGLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, array, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn array[0] != 0 ? array[0] : 2048;\n\t}\n\t\n\tpublic static boolean changeFastScrollColor(AbsListView v, int color) {\n\t\ttry {\n\t\t\tField f = AbsListView.class.getDeclaredField(\"mFastScroller\");\n\t\t\tf.setAccessible(true);\n\t\t\tObject o = f.get(v);\n\t\t\tf = f.getType().getDeclaredField(\"mThumbImage\");\n\t\t\tf.setAccessible(true);\n\t\t\to = f.get(o);\n\t\t\t((ImageView) o).setColorFilter(color);\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.e(TAG, Log.getStackTraceString(e));\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic static void startServiceAlarm(Context context, Class<?> service, long interval) {\n\t\tAlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n\t\tIntent i = new Intent(context, service);\n\t\tPendingIntent p = PendingIntent.getService(context, REQUEST_CODE, i, PendingIntent.FLAG_CANCEL_CURRENT);\n\t\tam.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, interval, p);\n\t}\n\t\n\tpublic static void stopServiceAlarm(Context context, Class<?> service) {\n\t\tAlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n\t\tIntent i = new Intent(context, service);\n\t\tPendingIntent p = PendingIntent.getService(context, REQUEST_CODE, i, PendingIntent.FLAG_CANCEL_CURRENT);\n\t\tam.cancel(p);\n\t}\n\t\n\tpublic static void startServices(Context context) {\n\t\tSettings mSettings = Settings.getInstance(context);\n\t\tstartServiceAlarm(context,\n\t\t\t\tCommentTimeLineFetcherService.class,\n\t\t\t\tgetIntervalTime(mSettings.getInt(Settings.NOTIFICATION_INTERVAL, 1))\n\t\t\t\t);\n\t\tstartServiceAlarm(\n\t\t\t\tcontext,\n\t\t\t\tMentionsTimeLineFetcherService.class, \n\t\t\t\tgetIntervalTime(mSettings.getInt(Settings.NOTIFICATION_INTERVAL, 1))\n\t\t\t\t);\n\t}\n\t\n\tpublic static void stopServices(Context context) {\n\t\tstopServiceAlarm(context, CommentTimeLineFetcherService.class);\n\t\tstopServiceAlarm(context, MentionsTimeLineFetcherService.class);\n\t}\n\n\tpublic static void restartServices(Context context) {\n\t\tstopServices(context);\n\n\t\tConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n\n\t\tif (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {\n\t\t\tstartServices(context);\n\t\t}\n\t}\n\t\n\tpublic static int getIntervalTime(int id) {\n\t\tswitch (id){\n\t\tcase 0:\n\t\t\treturn 1 * 60 * 1000;\n\t\tcase 1:\n\t\t\treturn 3 * 60 * 1000;\n\t\tcase 2:\n\t\t\treturn 5 * 60 * 1000;\n\t\tcase 3:\n\t\t\treturn 10 * 60 * 1000;\n\t\tcase 4:\n\t\t\treturn 30 * 60 * 1000;\n\t\t}\n\t\treturn -1;\n\t}\n\t\n\tpublic static int getActionBarHeight(Context context) {\n\t\tTypedValue v = new TypedValue();\n\t\t\n\t\tif (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, v, true)) {\n\t\t\treturn TypedValue.complexToDimensionPixelSize(v.data, context.getResources().getDisplayMetrics());\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tpublic static void setActionBarTranslation(Activity activity, float y) {\n\t\tViewGroup vg = (ViewGroup) activity.findViewById(android.R.id.content).getParent();\n\t\tint count = vg.getChildCount();\n\t\t\n\t\tfor (int i = 0; i < count; i++) {\n\t\t\tView v = vg.getChildAt(i);\n\t\t\t\n\t\t\tif (v.getId() != android.R.id.content) {\n\t\t\t\tv.setTranslationY(y);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@TargetApi(19)\n\tpublic static void enableTint(Activity activity) {\n\t\tif (Build.VERSION.SDK_INT < 19) return;\n\t\t\n\t\tWindow w = activity.getWindow();\n\t\tWindowManager.LayoutParams p = w.getAttributes();\n\t\tp.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;\n\t\tw.setAttributes(p);\n\t\t\n\t\tSystemBarTintManager m = new SystemBarTintManager(activity);\n\t\tm.setStatusBarTintEnabled(true);\n\t\tm.setStatusBarTintResource(R.color.action_gray);\n\t}\n\t\n\tpublic static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {\n\t\tint initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);\n\t\tint roundedSize;\n\t\tif (initialSize <= 8) {\n\t\t\troundedSize = 1;\n\t\t\twhile (roundedSize < initialSize) {\n\t\t\t\troundedSize <<= 1;\n\t\t\t}\n\t\t} else {\n\t\t\troundedSize = (initialSize + 7) / 8 * 8;\n\t\t}\n\t\treturn roundedSize;\n\t}\n\t\n\tprivate static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {\n\t\tdouble w = options.outWidth;\n\t\tdouble h = options.outHeight;\n\t\tint lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));\n\t\tint upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength),\n\t\tMath.floor(h / minSideLength));\n\t\tif (upperBound < lowerBound) {\n\t\t\treturn lowerBound;\n\t\t}\n\t\t\n\t\tif ((maxNumOfPixels == -1) && (minSideLength == -1)) {\n\t\t\treturn 1;\n\t\t} else if (minSideLength == -1) {\n\t\t\treturn lowerBound;\n\t\t} else {\n\t\t\treturn upperBound;\n\t\t}\n\t}\n\n // SmartBar Support\n public static boolean hasSmartBar() {\n try {\n Method method = Class.forName(\"android.os.Build\").getMethod(\"hasSmartBar\");\n return ((Boolean) method.invoke(null)).booleanValue();\n } catch (Exception e) {\n }\n\n if (Build.DEVICE.equals(\"mx2\") || Build.DEVICE.equals(\"mx3\")) {\n return true;\n } else if (Build.DEVICE.equals(\"mx\") || Build.DEVICE.equals(\"m9\")) {\n return false;\n }\n\n return false;\n }\n\n}",
"public class WeiboAdapter extends BaseAdapter implements AbsListView.RecyclerListener, AbsListView.OnScrollListener, \n\t\t\t\t\t\t\t\t\t\tView.OnClickListener, View.OnLongClickListener\n{\n\tprivate static final String TAG = WeiboAdapter.class.getSimpleName();\n\t\n\tprivate MessageListModel mList;\n\tprivate LayoutInflater mInflater;\n\tprivate StatusTimeUtils mTimeUtils;\n\tprivate UserApiCache mUserApi;\n\tprivate HomeTimeLineApiCache mHomeApi;\n\tprivate LoginApiCache mLogin;\n\t\n\tprivate String mUid;\n\t\n\tprivate int mGray;\n\t\n\tprivate Context mContext;\n\t\n\tprivate ArrayDeque<View> mViewDeque = new ArrayDeque<View>(10);\n\t\n\tprivate boolean mBindOrig;\n\tprivate boolean mShowCommentStatus;\n\tprivate boolean mScrolling = false;\n\t\n\tpublic WeiboAdapter(Context context, AbsListView listView, MessageListModel list, boolean bindOrig, boolean showCommentStatus) {\n\t\tmList = list;\n\t\tmInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\tmTimeUtils = StatusTimeUtils.instance(context);\n\t\tmUserApi = new UserApiCache(context);\n\t\tmHomeApi = new HomeTimeLineApiCache(context);\n\t\tmLogin = new LoginApiCache(context);\n\t\tmGray = context.getResources().getColor(R.color.light_gray);\n\t\tmUid = mLogin.getUid();\n\t\tmContext = context;\n\t\tmBindOrig = bindOrig;\n\t\tmShowCommentStatus = showCommentStatus;\n\t\t\n\t\tlistView.setRecyclerListener(this);\n\t\tlistView.setOnScrollListener(this);\n\t\t\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tView v = mInflater.inflate(R.layout.weibo, null);\n\t\t\tnew ViewHolder(v, null);\n\t\t\tmViewDeque.offer(v);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int getCount() {\n\t\treturn mList.getSize();\n\t}\n\n\t@Override\n\tpublic Object getItem(int position) {\n\t\treturn mList.get(position);\n\t}\n\n\t@Override\n\tpublic long getItemId(int position) {\n\t\treturn mList.get(position).id;\n\t}\n\n\t@Override\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n\t\tif (position >= getCount()) {\n\t\t\treturn convertView;\n\t\t} else {\n\t\t\tMessageModel msg = mList.get(position);\n\t\t\t\n\t\t\treturn bindView(msg, convertView);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onMovedToScrapHeap(View v) {\n\t\tif (v.getTag() instanceof ViewHolder) {\n\t\t\tViewHolder h = (ViewHolder) v.getTag();\n\t\t\t\n\t\t\tif (!h.sub) {\n\t\t\t\tmViewDeque.offer(v);\n\t\t\t}\n\t\t\t\n\t\t\th.getAvatar().setImageBitmap(null);\n\t\t\th.getAvatar().setTag(true);\n\t\t\th.getAvatar().setOnClickListener(null);\n\t\t\th.getCommentAndRetweet().setVisibility(View.VISIBLE);\n\t\t\t\n\t\t\tLinearLayout container = h.getContainer();\n\t\t\t\n\t\t\tfor (int i = 0; i < 9; i++) {\n\t\t\t\tImageView iv = (ImageView) container.getChildAt(i);\n\t\t\t\tiv.setImageBitmap(null);\n\t\t\t\tiv.setVisibility(View.VISIBLE);\n\t\t\t\tiv.setOnClickListener(null);\n\t\t\t\tiv.setTag(true);\n\t\t\t}\n\t\t\t\n\t\t\th.getScroll().setVisibility(View.GONE);\n\t\t\th.getOriginParent().setVisibility(View.GONE);\n\t\t\t\n\t\t\th.msg = null;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onScrollStateChanged(AbsListView v, int state) {\n\t\tmScrolling = state != AbsListView.OnScrollListener.SCROLL_STATE_IDLE;\n\t}\n\t\n\t@Override\n\tpublic void onScroll(AbsListView p1, int p2, int p3, int p4) {\n\t\t// Do nothing\n\t}\n\t\n\t@Override\n\tpublic void onClick(View v) {\n\t\tMessageModel msg = v.getTag() instanceof ViewHolder ? ((ViewHolder) v.getTag()).msg\n\t\t\t\t\t\t\t: (MessageModel) v.getTag();\n\t\tif (msg instanceof CommentModel) {\n\t\t\tIntent i = new Intent();\n\t\t\ti.setAction(Intent.ACTION_MAIN);\n\t\t\ti.setClass(mContext, ReplyToActivity.class);\n\t\t\ti.putExtra(\"comment\", (CommentModel) msg);\n\t\t\tmContext.startActivity(i);\n\t\t} else {\n\t\t\tIntent i = new Intent();\n\t\t\ti.setAction(Intent.ACTION_MAIN);\n\t\t\ti.setClass(mContext, SingleActivity.class);\n\t\t\ti.putExtra(\"msg\", msg);\n\t\t\tmContext.startActivity(i);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean onLongClick(View v) {\n\t\tMessageModel msg = v.getTag() instanceof ViewHolder ? ((ViewHolder) v.getTag()).msg\n\t\t\t\t\t\t\t: (MessageModel) v.getTag();\n\t\tif (msg instanceof CommentModel) {\n\t\t\tfinal CommentModel comment = (CommentModel) msg;\n\t\t\tif (comment.user.id.equals(mUid) || (comment.status != null && comment.status.user.id != null && comment.status.user.id.equals(mUid))) {\n\t\t\t\tnew AlertDialog.Builder(mContext)\n\t\t\t\t\t.setMessage(R.string.confirm_delete)\n\t\t\t\t\t.setCancelable(true)\n\t\t\t\t\t.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\tnew DeleteTask().execute(comment);\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\tdialog.dismiss();\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.show();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate View bindView(final MessageModel msg, View convertView) {\n\t\tView v = null;\n\t\tViewHolder h = null;\n\t\tboolean useExisted = true;\n\t\t\n\t\t// If not inflated before, then we have much work to do\n\t\tv = convertView != null ? convertView : mViewDeque.poll();\n\t\t\n\t\tif (v == null) {\n\t\t\tuseExisted = false;\n\t\t\tv = mInflater.inflate(R.layout.weibo, null);\n\t\t}\n\t\t\n\t\tif (!useExisted) {\n\t\t\th = new ViewHolder(v, msg);\n\t\t} else {\n\t\t\th = (ViewHolder) v.getTag();\n\t\t\t\n\t\t\tif (h.msg != null) {\n\t\t\t\tonMovedToScrapHeap(v);\n\t\t\t}\n\t\t\t\n\t\t\th.msg = msg;\n\t\t}\n\t\t\n\t\tTextView name = h.getName();\n\t\tTextView from = h.getFrom();\n\t\tTextView content = h.getContent();\n\t\tTextView date = h.getDate();\n\t\tTextView retweet = h.getRetweets();\n\t\tTextView comments = h.getComments();\n\t\t\n\t\tname.setText(msg.user != null ? msg.user.getName() : \"\");\n\t\tfrom.setText(msg.source != null ? Html.fromHtml(msg.source).toString() : \"\");\n\t\tcontent.setText(SpannableStringUtils.getSpan(msg));\n\t\tcontent.setMovementMethod(HackyMovementMethod.getInstance());\n\t\t\n\t\tdate.setText(mTimeUtils.buildTimeString(msg.created_at));\n\n\t\tif (!mShowCommentStatus || msg instanceof CommentModel) {\n\t\t\th.getCommentAndRetweet().setVisibility(View.GONE);\n\t\t} else {\n\t\t\tretweet.setText(String.valueOf(msg.reposts_count));\n\t\t\tcomments.setText(String.valueOf(msg.comments_count));\n\t\t}\n\t\t\n\t\tbindMultiPicLayout(h, msg, true);\n\t\t\n\t\t// If this retweets/repies to others, show the original\n\t\tif (mBindOrig) {\n\t\t\tif (!(msg instanceof CommentModel) && msg.retweeted_status != null) {\n\t\t\t\tbindOrig(h, msg.retweeted_status, true);\n\t\t\t} else if (msg instanceof CommentModel) {\n\t\t\t\tCommentModel comment = (CommentModel) msg;\n\t\t\t\tif (comment.reply_comment != null) {\n\t\t\t\t\tbindOrig(h, comment.reply_comment, false);\n\t\t\t\t} else if (comment.status != null) {\n\t\t\t\t\tbindOrig(h, comment.status, false);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\n\t\t}\n\t\t\n\t\tif (msg.user != null) {\n\t\t\tBitmap bmp = mUserApi.getCachedSmallAvatar(msg.user);\n\t\t\t\n\t\t\tif (bmp != null) {\n\t\t\t\th.getAvatar().setImageBitmap(bmp);\n\t\t\t\th.getAvatar().setTag(false);\n\t\t\t}\n\t\t\t\n\t\t\th.getAvatar().setOnClickListener(new View.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_MAIN);\n\t\t\t\t\ti.setClass(mContext, UserTimeLineActivity.class);\n\t\t\t\t\ti.putExtra(\"user\", msg.user);\n\t\t\t\t\tmContext.startActivity(i);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t\n\t\tv.setOnClickListener(this);\n\t\tv.setOnLongClickListener(this);\n\t\t\n\t\tnew ImageDownloader().execute(new Object[]{v});\n\t\t\n\t\treturn v;\n\t}\n\t\n\tprivate void bindOrig(ViewHolder h, MessageModel msg, boolean showPic) {\n\t\th.getOriginParent().setVisibility(View.VISIBLE);\n\t\th.getOrigContent().setText(SpannableStringUtils.getOrigSpan(msg));\n\t\th.getOrigContent().setMovementMethod(HackyMovementMethod.getInstance());\n\t\t\n\t\tbindMultiPicLayout(h, msg, showPic);\n\t\t\n\t\th.getOriginParent().setTag(msg);\n\t\th.getOriginParent().setOnClickListener(this);\n\t}\n\t\n\tprivate void bindMultiPicLayout(ViewHolder h, final MessageModel msg, boolean showPic) {\n\t\tHorizontalScrollView scroll = h.getScroll();\n\n\t\tif (showPic && (msg.thumbnail_pic != null || msg.pic_urls.size() > 0)) {\n\t\t\tscroll.setVisibility(View.VISIBLE);\n\n\t\t\tLinearLayout container = h.getContainer();\n\n\t\t\tint numChilds = msg.hasMultiplePictures() ? msg.pic_urls.size() : 1;\n\n\t\t\tfor (int i = 0; i < 9; i++) {\n\t\t\t\tImageView iv = (ImageView) container.getChildAt(i);\n\t\t\t\t\n\t\t\t\tif (i >= numChilds) {\n\t\t\t\t\tiv.setVisibility(View.GONE);\n\t\t\t\t} else {\n\t\t\t\t\tBitmap bmp = mHomeApi.getCachedThumbnail(msg, i);\n\t\t\t\t\t\n\t\t\t\t\tif (bmp != null) {\n\t\t\t\t\t\tiv.setImageBitmap(bmp);\n\t\t\t\t\t\tiv.setTag(false);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfinal int finalId = i;\n\t\t\t\t\t\n\t\t\t\t\tiv.setOnClickListener(new View.OnClickListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\t\t\ti.setAction(Intent.ACTION_MAIN);\n\t\t\t\t\t\t\ti.setClass(mContext, ImageActivity.class);\n\t\t\t\t\t\t\ti.putExtra(\"model\", msg);\n\t\t\t\t\t\t\ti.putExtra(\"defaultId\", finalId);\n\n\t\t\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\t\t\tLog.d(TAG, \"defaultId = \" + finalId);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tmContext.startActivity(i);\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}\n\t\n\tpublic void notifyDataSetChangedAndClear() {\n\t\tsuper.notifyDataSetChanged();\n\t}\n\t\n\tprivate boolean waitUntilNotScrolling(ViewHolder h, MessageModel msg) {\n\t\twhile (mScrolling) {\n\t\t\tif (h.msg != msg) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\ttry {\n\t\t\t\tThread.sleep(200);\n\t\t\t} catch (Exception e) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\t// Downloads images including avatars\n\tprivate class ImageDownloader extends AsyncTask<Object, Object, Void> {\n\n\t\t@Override\n\t\tprotected Void doInBackground(Object[] params) {\n\t\t\tView v = (View) params[0];\n\t\t\tViewHolder h = (ViewHolder) v.getTag();\n\t\t\tMessageModel msg = h.msg;\n\t\t\t\n\t\t\tObject tag = h.getAvatar().getTag();\n\t\t\t\n\t\t\tif (tag == null) {\n\t\t\t\ttag = true;\n\t\t\t}\n\t\t\t\n\t\t\t// Avatars\n\t\t\tif (v != null && Boolean.parseBoolean(tag.toString())) {\n\t\t\t\tif (!waitUntilNotScrolling(h, msg)) return null;\n\t\t\t\t\n\t\t\t\tBitmap avatar = mUserApi.getSmallAvatar(msg.user);\n\t\t\t\t\n\t\t\t\tpublishProgress(new Object[]{v, 0, avatar, msg});\n\t\t\t}\n\t\t\t\n\t\t\t// Images\n\t\t\tMessageModel realMsg = msg;\n\n\t\t\tif (msg.retweeted_status != null) {\n\t\t\t\trealMsg = msg.retweeted_status;\n\t\t\t}\n\t\t\t\n\t\t\tif (v != null && !(msg instanceof CommentModel) && (realMsg.pic_urls.size() > 0 || !TextUtils.isEmpty(msg.thumbnail_pic))) {\n\t\t\t\tif (!waitUntilNotScrolling(h, msg)) return null;\n\t\t\t\t\n\t\t\t\tLinearLayout container = h.getContainer();\n\t\t\t\t\n\t\t\t\tint numChilds = realMsg.hasMultiplePictures() ? realMsg.pic_urls.size() : 1;\n\t\t\t\t\n\t\t\t\tfor (int i = 0; i < numChilds; i++) {\n\t\t\t\t\tif (!waitUntilNotScrolling(h, msg)) return null;\n\t\t\t\t\t\n\t\t\t\t\tImageView imgView = (ImageView) container.getChildAt(i);\n\t\t\t\t\t\n\t\t\t\t\ttag = imgView.getTag();\n\t\t\t\t\t\n\t\t\t\t\tif (tag == null) {\n\t\t\t\t\t\ttag = true;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (!Boolean.parseBoolean(tag.toString())) continue;\n\t\t\t\t\t\n\t\t\t\t\tBitmap img = mHomeApi.getThumbnailPic(realMsg, i);\n\t\t\t\t\t\n\t\t\t\t\tif (img != null) {\n\t\t\t\t\t\tpublishProgress(new Object[]{v, 1, img, imgView, i, msg});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tprotected void onProgressUpdate(Object[] values) {\n\t\t\tsuper.onProgressUpdate(values);\n\t\t\t\n\t\t\tView v = (View) values[0];\n\t\t\t\n\t\t\tif (!(v.getTag() instanceof ViewHolder) || (((ViewHolder) v.getTag()).msg != null &&\n\t\t\t\t((ViewHolder) v.getTag()).msg.id != ((MessageModel) values[values.length -1]).id)) {\n\t\t\t\t\n\t\t\t\treturn;\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tswitch (Integer.parseInt(String.valueOf(values[1]))) {\n\t\t\t\tcase 0:\n\t\t\t\t\tBitmap avatar = (Bitmap) values[2];\n\t\t\t\t\tif (v != null) {\n\t\t\t\t\t\tImageView iv = ((ViewHolder) v.getTag()).getAvatar();\n\t\t\t\t\t\tif (iv != null) {\n\t\t\t\t\t\t\tiv.setImageBitmap(avatar);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tBitmap img = (Bitmap) values[2];\n\t\t\t\t\tImageView iv = (ImageView) values[3];\n\t\t\t\t\tiv.setImageBitmap(img);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\t\n\t}\n\t\n\tprivate class DeleteTask extends AsyncTask<CommentModel, Void, Void> {\n\t\tprivate ProgressDialog prog;\n\n\t\t@Override\n\t\tprotected void onPreExecute() {\n\t\t\tprog = new ProgressDialog(mContext);\n\t\t\tprog.setMessage(mContext.getResources().getString(R.string.plz_wait));\n\t\t\tprog.setCancelable(false);\n\t\t\tprog.show();\n\t\t}\n\n\t\t@Override\n\t\tprotected Void doInBackground(CommentModel[] params) {\n\t\t\tNewCommentApi.deleteComment(params[0].id);\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tprotected void onPostExecute(Void result) {\n\t\t\tprog.dismiss();\n\t\t}\n\t}\n\t\n\tprivate static class ViewHolder {\n\t\tpublic MessageModel msg;\n\t\tpublic boolean sub = false;\n\t\t\n\t\tprivate TextView date, retweets, comments, name, from, content;\n\t\tprivate HorizontalScrollView scroll;\n\t\tprivate LinearLayout container;\n\t\tprivate View originParent;\n\t\tprivate View comment_and_retweet;\n\t\tprivate ImageView weibo_avatar;\n\t\tprivate View v;\n\t\tprivate TextView orig_content;\n\t\t\n\t\tpublic ViewHolder(View v, MessageModel msg) {\n\t\t\tthis.v = v;\n\t\t\tthis.msg = msg;\n\t\t\t\n\t\t\tv.setTag(this);\n\t\t\t\n\t\t\tgetDate();\n\t\t\tgetComments();\n\t\t\tgetRetweets();\n\t\t\tgetName();\n\t\t\tgetFrom();\n\t\t\tgetContent();\n\t\t\tgetScroll();\n\t\t\tgetContainer();\n\t\t\tgetOriginParent();\n\t\t\tgetCommentAndRetweet();\n\t\t\tgetAvatar();\n\t\t\tgetOrigContent();\n\t\t}\n\t\t\n\t\tpublic TextView getDate() {\n\t\t\tif (date == null) {\n\t\t\t\tdate = (TextView) v.findViewById(R.id.weibo_date);\n\t\t\t}\n\t\t\t\n\t\t\treturn date;\n\t\t}\n\t\t\n\t\tpublic TextView getComments() {\n\t\t\tif (comments == null) {\n\t\t\t\tcomments = (TextView) v.findViewById(R.id.weibo_comments);\n\t\t\t}\n\n\t\t\treturn comments;\n\t\t}\n\t\t\n\t\tpublic TextView getRetweets() {\n\t\t\tif (retweets == null) {\n\t\t\t\tretweets = (TextView) v.findViewById(R.id.weibo_retweet);\n\t\t\t}\n\t\t\t\n\t\t\treturn retweets;\n\t\t}\n\t\t\n\t\tpublic TextView getName() {\n\t\t\tif (name == null) {\n\t\t\t\tname = (TextView) v.findViewById(R.id.weibo_name);\n\t\t\t}\n\t\t\t\n\t\t\treturn name;\n\t\t}\n\t\t\n\t\tpublic TextView getFrom() {\n\t\t\tif (from == null) {\n\t\t\t\tfrom = (TextView) v.findViewById(R.id.weibo_from);\n\t\t\t}\n\t\t\t\n\t\t\treturn from;\n\t\t}\n\t\t\n\t\tpublic TextView getContent() {\n\t\t\tif (content == null) {\n\t\t\t\tcontent = (TextView) v.findViewById(R.id.weibo_content);\n\t\t\t}\n\t\t\t\n\t\t\treturn content;\n\t\t}\n\t\t\n\t\tpublic HorizontalScrollView getScroll() {\n\t\t\tif (scroll == null) {\n\t\t\t\tscroll = (HorizontalScrollView) v.findViewById(R.id.weibo_pics_scroll);\n\t\t\t}\n\t\t\t\n\t\t\treturn scroll;\n\t\t}\n\t\t\n\t\tpublic LinearLayout getContainer() {\n\t\t\tif (container == null) {\n\t\t\t\tcontainer = (LinearLayout) getScroll().findViewById(R.id.weibo_pics);\n\t\t\t}\n\t\t\t\n\t\t\treturn container;\n\t\t}\n\t\t\n\t\tpublic View getOriginParent() {\n\t\t\tif (originParent == null) {\n\t\t\t\toriginParent = v.findViewById(R.id.weibo_origin);\n\t\t\t}\n\t\t\t\n\t\t\treturn originParent;\n\t\t}\n\t\t\n\t\tpublic View getCommentAndRetweet() {\n\t\t\tif (comment_and_retweet == null) {\n\t\t\t\tcomment_and_retweet = v.findViewById(R.id.weibo_comment_and_retweet);\n\t\t\t}\n\t\t\t\n\t\t\treturn comment_and_retweet;\n\t\t}\n\t\t\n\t\tpublic ImageView getAvatar() {\n\t\t\tif (weibo_avatar == null) {\n\t\t\t\tweibo_avatar = (ImageView) v.findViewById(R.id.weibo_avatar);\n\t\t\t}\n\t\t\t\n\t\t\treturn weibo_avatar;\n\t\t}\n\t\t\n\t\tpublic TextView getOrigContent() {\n\t\t\tif (orig_content == null) {\n\t\t\t\torig_content = (TextView) v.findViewById(R.id.weibo_orig_content);\n\t\t\t}\n\t\t\t\n\t\t\treturn orig_content;\n\t\t}\n\t}\n\n}",
"public class SwipeUpAndDownRefreshLayout extends SwipeRefreshLayout\n{\n\tprivate Canvas mCanvas;\n\tprivate Bitmap mBitmap;\n\tprivate int mWidth, mHeight, mProgressBarHeight;\n\t\n\tprivate boolean mIsDown = false;\n\tprivate boolean mDownPriority = false;\n\t\n\tprivate Field mTarget, mProgressBar, mReturningToStart, mDownEvent;\n\tprivate Method mSetBounds, mDraw, mUpdateContentOffsetTop;\n\t\n\tpublic SwipeUpAndDownRefreshLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\t\n\tpublic SwipeUpAndDownRefreshLayout(Context context, AttributeSet attrs) {\n\t\tsuper(context, attrs);\n\t\t\n\t\ttry {\n\t\t\tinitFields();\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\t\n\tprivate void initFields() throws NoSuchFieldException, NoSuchMethodException {\n\t\tmTarget = SwipeRefreshLayout.class.getDeclaredField(\"mTarget\");\n\t\tmTarget.setAccessible(true);\n\t\t\n\t\tmProgressBar = SwipeRefreshLayout.class.getDeclaredField(\"mProgressBar\");\n\t\tmProgressBar.setAccessible(true);\n\t\t\n\t\tmReturningToStart = SwipeRefreshLayout.class.getDeclaredField(\"mReturningToStart\");\n\t\tmReturningToStart.setAccessible(true);\n\t\t\n\t\tmDownEvent = SwipeRefreshLayout.class.getDeclaredField(\"mDownEvent\");\n\t\tmDownEvent.setAccessible(true);\n\t\t\n\t\tmUpdateContentOffsetTop = SwipeRefreshLayout.class.getDeclaredMethod(\"updateContentOffsetTop\", int.class);\n\t\tmUpdateContentOffsetTop.setAccessible(true);\n\t}\n\t\n\tpublic boolean isDown() {\n\t\treturn mIsDown;\n\t}\n\t\n\tpublic void setIsDown(boolean isDown) {\n\t\tmIsDown = isDown;\n\t}\n\t\n\tpublic void setDownHasPriority() {\n\t\tmDownPriority = true;\n\t}\n\t\n\tpublic boolean canChildScrollDown() {\n\t\ttry {\n\t\t\tView v = (View) mTarget.get(this);\n\t\t\treturn v.canScrollVertically(1);\n\t\t} catch (Exception e) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n\t\tsuper.onLayout(changed, left, top, right, bottom);\n\t\t\n\t\tmWidth = getMeasuredWidth();\n\t\tmHeight = getMeasuredHeight();\n\t\t\n\t\ttry {\n\t\t\tField f = SwipeRefreshLayout.class.getDeclaredField(\"mProgressBarHeight\");\n\t\t\tf.setAccessible(true);\n\t\t\tmProgressBarHeight = Integer.parseInt(f.get(this).toString());\n\t\t} catch (Exception e) {\n\t\t\tmProgressBarHeight = 0;\n\t\t}\n\t\t\n\t\tmBitmap = Bitmap.createBitmap(mWidth, mProgressBarHeight, Bitmap.Config.ARGB_8888);\n\t\tmCanvas = new Canvas(mBitmap);\n\t}\n\n\t@Override\n\tpublic void draw(Canvas canvas) {\n\t\tObject progressBar = null;\n\t\t\n\t\ttry {\n\t\t\tprogressBar = mProgressBar.get(this);\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t}\n\t\t\n\t\tMethod m = mSetBounds;\n\t\t\n\t\tif (m == null && progressBar != null) {\n\t\t\ttry {\n\t\t\t\tm = progressBar.getClass().getDeclaredMethod(\"setBounds\", int.class, int.class, int.class, int.class);\n\t\t\t\tm.setAccessible(true);\n\t\t\t} catch (Exception e) {\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (m != null) {\n\t\t\tmSetBounds = m;\n\t\t\t\n\t\t\ttry {\n\t\t\t\tm.invoke(progressBar, 0, 0, 0, 0);\n\t\t\t} catch (Exception e) {\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tsuper.draw(canvas);\n\t\t\n\t\tif (m != null) {\n\t\t\tPaint p = new Paint();\n\t\t\tp.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));\n\t\t\tmCanvas.drawPaint(p);\n\t\t\ttry {\n\t\t\t\tm.invoke(progressBar, 0, 0, mWidth, mProgressBarHeight);\n\t\t\t\t\n\t\t\t\tMethod method = mDraw;\n\t\t\t\t\n\t\t\t\tif (method == null) {\n\t\t\t\t\tmethod = progressBar.getClass().getDeclaredMethod(\"draw\", Canvas.class);\n\t\t\t\t\tmethod.setAccessible(true);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmDraw = method;\n\t\t\t\tmethod.invoke(progressBar, mCanvas);\n\t\t\t} catch (Exception e) {\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tcanvas.drawBitmap(mBitmap, 0, isDown() ? mHeight - mProgressBarHeight : 0, null);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean onInterceptTouchEvent(MotionEvent ev) {\n\t\tboolean handled = super.onInterceptTouchEvent(ev);\n\t\tboolean returningToStart;\n\t\ttry {\n\t\t\treturningToStart = Boolean.parseBoolean(mReturningToStart.get(this).toString());\n\t\t} catch (Exception e) {\n\t\t\treturn handled;\n\t\t}\n\t\t\n\t\tif (!handled && !returningToStart && !canChildScrollDown()) {\n\t\t\thandled = onTouchEvent(ev);\n\t\t}\n\t\t\n\t\treturn handled;\n\t}\n\n\t@Override\n\tpublic boolean onTouchEvent(MotionEvent event) {\n\t\tboolean returningToStart = false;\n\t\tMotionEvent downEvent = null;\n\t\ttry {\n\t\t\treturningToStart = Boolean.parseBoolean(mReturningToStart.get(this).toString());\n\t\t\tdownEvent = (MotionEvent) mDownEvent.get(this);\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t}\n\t\t\n\t\tboolean ret;\n\t\t\n\t\tif (event.getAction() == MotionEvent.ACTION_MOVE\n\t\t\t&& downEvent != null && !returningToStart && !canChildScrollDown() && (mDownPriority || canChildScrollUp())) {\n\t\t\t\tdownEvent.setLocation(downEvent.getX(), -downEvent.getY());\n\t\t\t\tevent.setLocation(event.getX(), -event.getY());\n\t\t\t\t\n\t\t\t\tret = super.onTouchEvent(event);\n\t\t\t\t\n\t\t\t\tdownEvent.setLocation(downEvent.getX(), -downEvent.getY());\n\t\t\t\tevent.setLocation(event.getX(), -event.getY());\n\t\t\t\t\n\t\t\t\t// Abandon the offset animation when swiping up\n\t\t\t\ttry {\n\t\t\t\t\tmUpdateContentOffsetTop.invoke(this, -100);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\tret = super.onTouchEvent(event);\n\t\t}\n\t\t\n\t\tif (!canChildScrollDown()) {\n\t\t\tmIsDown = true;\n\t\t}\n\t\t\n\t\tif ((!mDownPriority || canChildScrollDown()) && !canChildScrollUp()) {\n\t\t\tmIsDown = false;\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n}",
"public static boolean hasSmartBar() {\n try {\n Method method = Class.forName(\"android.os.Build\").getMethod(\"hasSmartBar\");\n return ((Boolean) method.invoke(null)).booleanValue();\n } catch (Exception e) {\n }\n\n if (Build.DEVICE.equals(\"mx2\") || Build.DEVICE.equals(\"mx3\")) {\n return true;\n } else if (Build.DEVICE.equals(\"mx\") || Build.DEVICE.equals(\"m9\")) {\n return false;\n }\n\n return false;\n}"
] | import android.app.Fragment;
import android.app.Service;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.ListView;
import android.widget.Toast;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.widget.SwipeRefreshLayout;
import java.util.ConcurrentModificationException;
import us.shandian.blacklight.R;
import us.shandian.blacklight.cache.statuses.HomeTimeLineApiCache;
import us.shandian.blacklight.support.AsyncTask;
import us.shandian.blacklight.support.Settings;
import us.shandian.blacklight.support.Utility;
import us.shandian.blacklight.support.adapter.WeiboAdapter;
import us.shandian.blacklight.ui.common.SwipeUpAndDownRefreshLayout;
import static us.shandian.blacklight.support.Utility.hasSmartBar; | /*
* Copyright (C) 2014 Peter Cai
*
* This file is part of BlackLight
*
* BlackLight 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.
*
* BlackLight 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 BlackLight. If not, see <http://www.gnu.org/licenses/>.
*/
package us.shandian.blacklight.ui.statuses;
public class TimeLineFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener,
View.OnTouchListener, View.OnLongClickListener
{
private ListView mList;
private View mNew;
private WeiboAdapter mAdapter;
private HomeTimeLineApiCache mCache;
// Pull To Refresh
private SwipeUpAndDownRefreshLayout mSwipeRefresh;
private boolean mRefreshing = false;
private boolean mNewHidden = false;
protected boolean mBindOrig = true;
protected boolean mShowCommentStatus = true;
private int mLastCount = 0;
private float mLastY = -1.0f;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
initTitle();
View v = inflater.inflate(R.layout.home_timeline, null);
mList = (ListView) v.findViewById(R.id.home_timeline);
mCache = bindApiCache();
mCache.loadFromCache();
mAdapter = new WeiboAdapter(getActivity(), mList, mCache.mMessages, mBindOrig, mShowCommentStatus);
mList.setAdapter(mAdapter);
mList.setDrawingCacheEnabled(true);
mList.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
mList.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE | ViewGroup.PERSISTENT_SCROLLING_CACHE);
// Swipe To Refresh
bindSwipeToRefresh((ViewGroup) v);
if (mCache.mMessages.getSize() == 0) {
new Refresher().execute(new Boolean[]{true});
}
// Floating "New" button
bindNewButton(v);
return v;
}
@Override
public void onStop() {
super.onStop();
try {
mCache.cache();
} catch (ConcurrentModificationException e) {
}
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (!hidden) {
initTitle();
resume();
}
}
@Override
public void onResume() {
super.onResume();
resume();
}
public void resume() { | Settings settings = Settings.getInstance(getActivity()); | 2 |
goshippo/shippo-java-client | src/main/java/com/shippo/model/CarrierAccount.java | [
"public class APIConnectionException extends ShippoException {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic APIConnectionException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic APIConnectionException(String message, Throwable e) {\n\t\tsuper(message, e);\n\t}\n\n}",
"public class APIException extends ShippoException {\n\n private static final long serialVersionUID = 1L;\n\n public APIException(String message, Throwable e) {\n super(message, e);\n }\n\n}",
"public class AuthenticationException extends ShippoException {\n\n public AuthenticationException(String message) {\n super(message);\n }\n\n private static final long serialVersionUID = 1L;\n\n}",
"public class InvalidRequestException extends ShippoException {\n\n private static final long serialVersionUID = 1L;\n\n private final String param;\n\n public InvalidRequestException(String message, String param, Throwable e) {\n super(message, e);\n this.param = param;\n }\n\n public String getParam() {\n return param;\n }\n\n}",
"public abstract class APIResource extends ShippoObject {\n\n\tprivate static String className(Class<?> clazz) {\n\t\tString className = clazz.getSimpleName().toLowerCase()\n\t\t\t\t.replace(\"$\", \" \");\n\n\t\t// Special case class names\n\t\tif (className.equals(\"address\")) {\n\t\t\treturn \"addresse\";\n\t\t} else if (className.equals(\"customsitem\")) {\n\t\t\treturn \"customs/item\";\n\t\t} else if (className.equals(\"customsdeclaration\")) {\n\t\t\treturn \"customs/declaration\";\n\t\t} else if (className.equals(\"carrieraccount\")) {\n\t\t\treturn \"carrier_account\";\n\t\t} else if (className.equals(\"batch\")) {\n\t\t\treturn \"batche\";\n\t\t} else {\n\t\t\treturn className;\n\t\t}\n\t}\n\n\tprotected static String singleClassURL(Class<?> clazz) {\n\t\treturn String.format(\"%s/%s\", Shippo.getApiBase(), className(clazz));\n\t}\n\n\tprotected static String classURL(Class<?> clazz) {\n\t\treturn String.format(\"%ss\", singleClassURL(clazz));\n\t}\n\n\tprotected static String classURLWithTrailingSlash(Class<?> clazz) {\n\t\treturn String.format(\"%ss/\", singleClassURL(clazz));\n\t}\n\n\tprotected static String instanceURL(Class<?> clazz, String id)\n\t\t\tthrows InvalidRequestException {\n\t\ttry {\n\t\t\treturn String.format(\"%s/%s\", classURL(clazz), urlEncode(id));\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new InvalidRequestException(\"Unable to encode parameters to \"\n\t\t\t\t\t+ CHARSET\n\t\t\t\t\t+ \". Please contact [email protected] for assistance.\",\n\t\t\t\t\tnull, e);\n\t\t}\n\t}\n\n\tpublic static final String CHARSET = \"UTF-8\";\n\n\tprivate static final String DNS_CACHE_TTL_PROPERTY_NAME = \"networkaddress.cache.ttl\";\n\n\t/*\n\t * Set this property to override your environment's default\n\t * URLStreamHandler; Settings the property should not be needed in most\n\t * environments.\n\t */\n\tprivate static final String CUSTOM_URL_STREAM_HANDLER_PROPERTY_NAME = \"com.shippo.net.customURLStreamHandler\";\n\n\tprotected enum RequestMethod {\n\t\tGET, POST, PUT\n\t}\n\n\tprotected static String urlEncode(String str)\n\t\t\tthrows UnsupportedEncodingException {\n\t\t// Preserve original behavior that passing null for an object id will\n\t\t// lead\n\t\t// to us actually making a request to /v1/foo/null\n\t\tif (str == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn URLEncoder.encode(str, CHARSET);\n\t\t}\n\t}\n\n\tprivate static String urlEncodePair(String k, String v)\n\t\t\tthrows UnsupportedEncodingException {\n\t\treturn String.format(\"%s=%s\", urlEncode(k), urlEncode(v));\n\t}\n\n\tstatic Map<String, String> getHeaders(String apiKey, Class<?> clazz) {\n\t\tMap<String, String> headers = new HashMap<String, String>();\n\t\theaders.put(\"Accept-Charset\", CHARSET);\n\t\theaders.put(\"User-Agent\",\n\t\t\t\tString.format(\"Shippo/v1 JavaBindings/%s\", Shippo.VERSION));\n\n\t\tif (apiKey == null) {\n\t\t\tapiKey = Shippo.apiKey;\n\t\t}\n\n\t\theaders.put(\"Authorization\", String.format(\"ShippoToken %s\", apiKey));\n\t\theaders.put(\"Accept\", \"application/json\");\n\n\t\t// debug headers\n\t\tString[] propertyNames = { \"os.name\", \"os.version\", \"os.arch\",\n\t\t\t\t\"java.version\", \"java.vendor\", \"java.vm.version\",\n\t\t\t\t\"java.vm.vendor\" };\n\t\tMap<String, String> propertyMap = new HashMap<String, String>();\n\t\tfor (String propertyName : propertyNames) {\n\t\t\tpropertyMap.put(propertyName, System.getProperty(propertyName));\n\t\t}\n\t\t// propertyMap.put(\"bindings.version\", Shippo.VERSION);\n\t\t// propertyMap.put(\"lang\", \"Java\");\n\t\t// propertyMap.put(\"publisher\", \"Shippo\");\n\t\theaders.put(\"User-Agent\", GsonFactory.getGson(clazz).toJson(propertyMap));\n\t\theaders.put(\"Content-Type\", \"application/json\");\n\t\tif (Shippo.apiVersion != null) {\n\t\t headers.put(\"Shippo-API-Version\", Shippo.apiVersion);\n\t\t}\n\t\treturn headers;\n\t}\n\n\tprivate static java.net.HttpURLConnection createShippoConnection(\n\t\t\tString url, String apiKey, Class<?> clazz) throws IOException {\n\t\tURL shippoURL;\n\t\tString customURLStreamHandlerClassName = System.getProperty(\n\t\t\t\tCUSTOM_URL_STREAM_HANDLER_PROPERTY_NAME, null);\n\t\tif (customURLStreamHandlerClassName != null) {\n\t\t\t// instantiate the custom handler provided\n\t\t\ttry {\n\t\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\t\tClass<URLStreamHandler> urlClass = (Class<URLStreamHandler>) Class\n\t\t\t\t\t\t.forName(customURLStreamHandlerClassName);\n\t\t\t\tConstructor<URLStreamHandler> constructor = urlClass\n\t\t\t\t\t\t.getConstructor();\n\t\t\t\tURLStreamHandler customHandler = constructor.newInstance();\n\t\t\t\tshippoURL = new URL(null, url, customHandler);\n\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\tthrow new IOException(e);\n\t\t\t} catch (SecurityException e) {\n\t\t\t\tthrow new IOException(e);\n\t\t\t} catch (NoSuchMethodException e) {\n\t\t\t\tthrow new IOException(e);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tthrow new IOException(e);\n\t\t\t} catch (InstantiationException e) {\n\t\t\t\tthrow new IOException(e);\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tthrow new IOException(e);\n\t\t\t} catch (InvocationTargetException e) {\n\t\t\t\tthrow new IOException(e);\n\t\t\t}\n\t\t} else {\n\t\t\tshippoURL = new URL(url);\n\t\t}\n\t\tjava.net.HttpURLConnection conn = (java.net.HttpURLConnection) shippoURL\n\t\t\t\t.openConnection();\n\t\tconn.setConnectTimeout(Shippo.httpConnectTimeout);\n\t\tconn.setReadTimeout(Shippo.httpReadTimeout);\n\t\tconn.setUseCaches(false);\n\t\tfor (Map.Entry<String, String> header : getHeaders(apiKey, clazz).entrySet()) {\n\t\t\tconn.setRequestProperty(header.getKey(), header.getValue());\n\t\t}\n\n\t\treturn conn;\n\t}\n\n\tprivate static void throwInvalidCertificateException()\n\t\t\tthrows APIConnectionException {\n\t\tthrow new APIConnectionException(\n\t\t\t\t\"Invalid server certificate. You tried to connect to a server that has a revoked SSL certificate, which means we cannot securely send data to that server. Please email [email protected] if you need help connecting to the correct API server.\");\n\t}\n\n\tprivate static void checkSSLCert(java.net.HttpURLConnection hconn)\n\t\t\tthrows IOException, APIConnectionException {\n\t\t if (!Shippo.getVerifySSL() &&\n\t\t !hconn.getURL().getHost().equals(\"api.shippo.com\")) {\n\t\t return;\n\t\t }\n\n\t\t javax.net.ssl.HttpsURLConnection conn =\n\t\t (javax.net.ssl.HttpsURLConnection) hconn;\n\t\t conn.connect();\n\n\t\t Certificate[] certs = conn.getServerCertificates();\n\n\t\t try {\n\t\t MessageDigest md = MessageDigest.getInstance(\"SHA-1\");\n\n\t\t byte[] der = certs[0].getEncoded();\n\t\t md.update(der);\n\t\t byte[] digest = md.digest();\n\n\t\t byte[] revokedCertDigest = {};\n\n\t\t if (Arrays.equals(digest, revokedCertDigest)) {\n\t\t throwInvalidCertificateException();\n\t\t }\n\n\t\t } catch (NoSuchAlgorithmException e) {\n\t\t throw new RuntimeException(e);\n\t\t } catch (CertificateEncodingException e) {\n\t\t throwInvalidCertificateException();\n\t\t }\n\t}\n\n\tprivate static String formatURL(String url, String query) {\n\t\tif (query == null || query.isEmpty()) {\n\t\t\treturn url;\n\t\t} else {\n\t\t\t// In some cases, URL can already contain a question mark (eg,\n\t\t\t// upcoming invoice lines)\n\t\t\tString separator = url.contains(\"?\") ? \"&\" : \"?\";\n\t\t\treturn String.format(\"%s%s%s\", url, separator, query);\n\t\t}\n\t}\n\n\tprivate static java.net.HttpURLConnection createGetConnection(String url,\n\t\t\tString query, String apiKey, Class<?> clazz) throws IOException,\n\t\t\tAPIConnectionException {\n\t\tif (Shippo.isDEBUG()) {\n\t\t\tSystem.out.println(\"GET URL: \" + url);\n\t\t}\n\t\tString getURL = formatURL(url, query);\n\t\tjava.net.HttpURLConnection conn = createShippoConnection(getURL, apiKey, clazz);\n\t\tconn.setRequestMethod(\"GET\");\n\n\t\tcheckSSLCert(conn);\n\n\t\treturn conn;\n\t}\n\n\tprivate static java.net.HttpURLConnection createPostPutConnection(String url,\n\t\t\tString query, RequestMethod method, String apiKey, Class<?> clazz) throws IOException,\n\t\t\tAPIConnectionException {\n\t\tif (Shippo.isDEBUG()) {\n\t\t\tSystem.out.println(\"POST URL: \" + url);\n\t\t}\n\n\t\tjava.net.HttpURLConnection conn = createShippoConnection(url, apiKey, clazz);\n\t\tconn.setDoOutput(true);\n\t\tconn.setRequestMethod(method.toString());\n\t\tconn.setRequestProperty(\"Content-Type\", \"application/json\");\n\n\t\tcheckSSLCert(conn);\n\n\t\tOutputStream output = null;\n\t\ttry {\n\t\t\toutput = conn.getOutputStream();\n\t\t\toutput.write(query.getBytes(CHARSET));\n\t\t} finally {\n\t\t\tif (output != null) {\n\t\t\t\toutput.close();\n\t\t\t}\n\t\t}\n\t\treturn conn;\n\n\t}\n\n\tprivate static java.net.HttpURLConnection createPutConnection(String url,\n\t\t\tString query, String apiKey, Class<?> clazz) throws IOException,\n\t\t\tAPIConnectionException {\n\t\tif (Shippo.isDEBUG()) {\n\t\t\tSystem.out.println(\"PUT URL: \" + url);\n\t\t}\n\n\t\tjava.net.HttpURLConnection conn = createShippoConnection(url, apiKey, clazz);\n\t\tconn.setDoOutput(true);\n\t\tconn.setRequestMethod(\"PUT\");\n\t\tconn.setRequestProperty(\"Content-Type\", \"application/json\");\n\n\t\tcheckSSLCert(conn);\n\n\t\tOutputStream output = null;\n\t\ttry {\n\t\t\toutput = conn.getOutputStream();\n\t\t\toutput.write(query.getBytes(CHARSET));\n\t\t} finally {\n\t\t\tif (output != null) {\n\t\t\t\toutput.close();\n\t\t\t}\n\t\t}\n\t\treturn conn;\n\n\t}\n\n\tprivate static String mapToJson(Map<String, Object> params, Class<?> clazz) {\n\t\tGson gson = GsonFactory.getGson(clazz);\n\t\tif (params == null) {\n\t\t\treturn gson.toJson(new HashMap<String, Object>());\n\t\t}\n // hack to serialize list instead of object\n Object o = params.get(\"__list\");\n if (o != null) {\n return gson.toJson(o);\n }\n\t\treturn gson.toJson(params);\n\t}\n\n\tprivate static Map<String, String> flattenParams(Map<String, Object> params)\n\t\t\tthrows InvalidRequestException {\n\t\tif (params == null) {\n\t\t\treturn new HashMap<String, String>();\n\t\t}\n\t\tMap<String, String> flatParams = new HashMap<String, String>();\n\t\tfor (Map.Entry<String, Object> entry : params.entrySet()) {\n\t\t\tString key = entry.getKey();\n\t\t\tObject value = entry.getValue();\n\t\t\tif (value instanceof Map<?, ?>) {\n\t\t\t\tMap<String, Object> flatNestedMap = new HashMap<String, Object>();\n\t\t\t\tMap<?, ?> nestedMap = (Map<?, ?>) value;\n\t\t\t\tfor (Map.Entry<?, ?> nestedEntry : nestedMap.entrySet()) {\n\t\t\t\t\tflatNestedMap.put(\n\t\t\t\t\t\t\tString.format(\"%s[%s]\", key, nestedEntry.getKey()),\n\t\t\t\t\t\t\tnestedEntry.getValue());\n\t\t\t\t}\n\t\t\t\tflatParams.putAll(flattenParams(flatNestedMap));\n\t\t\t} else if (value == null) {\n\t\t\t\tflatParams.put(key, \"\");\n\t\t\t} else {\n\t\t\t\tflatParams.put(key, value.toString());\n\t\t\t}\n\t\t}\n\t\treturn flatParams;\n\t}\n\n\t// represents Errors returned as JSON\n\t@SuppressWarnings(\"unused\")\n\tprivate static class ErrorContainer {\n\t\tprivate APIResource.Error error;\n\t}\n\n\tprivate static class Error {\n\t\t@SuppressWarnings(\"unused\")\n\t\tString type;\n\t\tString message;\n\t\t@SuppressWarnings(\"unused\")\n\t\tString code;\n\t\tString param;\n\t}\n\n\t@SuppressWarnings(\"resource\")\n\tprivate static String getResponseBody(InputStream responseStream)\n\t\t\tthrows IOException {\n\t\t// \\A is the beginning of the stream boundary\n\t\tString rBody = new Scanner(responseStream, CHARSET).useDelimiter(\"\\\\A\")\n\t\t\t\t.next(); //\n\n\t\tresponseStream.close();\n\t\treturn rBody;\n\t}\n\n\tprivate static ShippoResponse makeURLConnectionRequest(\n\t\t\tAPIResource.RequestMethod method, String url, String query,\n\t\t\tString apiKey, Class<?> clazz) throws APIConnectionException {\n\t\tjava.net.HttpURLConnection conn = null;\n\n\t\t// Print Information about the Connection\n\t\tif (Shippo.isDEBUG()) {\n\t\t\tSystem.out.println(\"URL: \" + url);\n\t\t\tSystem.out.println(\"Query: \" + query);\n\t\t\tSystem.out.println(\"API Key: \" + apiKey);\n\t\t}\n\n\t\ttry {\n\t\t\tif(method.equals(RequestMethod.GET)){\n\t\t\t\tconn = createGetConnection(url, query, apiKey, clazz);\n\t\t\t}\n\t\t\telse if (method.equals(RequestMethod.POST) || method.equals(RequestMethod.PUT)) {\n\t\t\t\tconn = createPostPutConnection(url, query, method, apiKey, clazz);\n\t\t\t}else{\n\t\t\t\tthrow new APIConnectionException(\n\t\t\t\t\t\tString.format(\n\t\t\t\t\t\t\t\t\"Unrecognized HTTP method %s. \"\n\t\t\t\t\t\t\t\t\t\t+ \"This indicates a bug in the Shippo bindings. Please contact \"\n\t\t\t\t\t\t\t\t\t\t+ \"[email protected] for assistance.\",\n\t\t\t\t\t\t\t\tmethod));\n\t\t\t}\n\n\t\t\t// Trigger the Request\n\t\t\tint rCode = conn.getResponseCode();\n\n\t\t\tString rBody;\n\t\t\tMap<String, List<String>> headers;\n\t\t\t\n\t\t\tif (rCode >= 200 && rCode < 300) {\n\t\t\t\trBody = getResponseBody(conn.getInputStream());\n\t\t\t}\n\t\t\telse if(rCode == 429){\n\t\t\t\trBody = \"Too many requests\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttry{\n\t\t\t\trBody = getResponseBody(conn.getErrorStream());\n\t\t\t\t}\n\t\t\t\tcatch(NullPointerException e){\n\t\t\t\t\trBody = \"\";\n\t\t\t\t}\n\t\t\t}\n\t\t\theaders = conn.getHeaderFields();\n\n\t\t\t// /////////////////////////////////////////////////////////////////\n\t\t\t// PRINT RESULTS\n\t\t\t// /////////////////////////////////////////////////////////////////\n\t\t\tif (Shippo.isDEBUG()) {\n\t\t\t\tSystem.out.println(\"Headers: \");\n\t\t\t\tfor (Map.Entry<String, List<String>> entry : headers.entrySet()) {\n\t\t\t\t\tSystem.out.println(entry.getKey() + \" : \"\n\t\t\t\t\t\t\t+ entry.getValue());\n\t\t\t\t}\n\t\t\t\tSystem.out.println(\"Response Code: \" + rCode);\n\t\t\t\tSystem.out.println(\"Reponse Body: \" + rBody);\n\t\t\t}\n\n\t\t\treturn new ShippoResponse(rCode, rBody, headers);\n\t\t} catch (IOException e) {\n\t\t\tthrow new APIConnectionException(\n\t\t\t\t\tString.format(\n\t\t\t\t\t\t\t\"IOException during API request to Shippo (%s): %s \"\n\t\t\t\t\t\t\t\t\t+ \"Please check your internet connection and try again. If this problem persists,\"\n\t\t\t\t\t\t\t\t\t+ \"you should check Shippo's service status at http://status.goshippo.com/,\"\n\t\t\t\t\t\t\t\t\t+ \" or let us know at [email protected].\",\n\t\t\t\t\t\t\tShippo.getApiBase(), e.getMessage()), e);\n\t\t} finally {\n\t\t\tif (conn != null) {\n\t\t\t\tconn.disconnect();\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected static <T> T request(APIResource.RequestMethod method,\n\t\t\tString url, Map<String, Object> params, Class<T> clazz,\n\t\t\tString apiKey) throws AuthenticationException,\n\t\t\tInvalidRequestException, APIConnectionException, APIException {\n\t\tString originalDNSCacheTTL = null;\n\t\tBoolean allowedToSetTTL = true;\n\t\ttry {\n\t\t\toriginalDNSCacheTTL = java.security.Security\n\t\t\t\t\t.getProperty(DNS_CACHE_TTL_PROPERTY_NAME);\n\t\t\t// disable DNS cache\n\t\t\tjava.security.Security\n\t\t\t\t\t.setProperty(DNS_CACHE_TTL_PROPERTY_NAME, \"0\");\n\t\t} catch (SecurityException se) {\n\t\t\tallowedToSetTTL = false;\n\t\t}\n\n\t\ttry {\n\t\t\treturn _request(method, url, params, clazz, apiKey);\n\t\t} finally {\n\t\t\tif (allowedToSetTTL) {\n\t\t\t\tif (originalDNSCacheTTL == null) {\n\t\t\t\t\t// value unspecified by implementation\n\t\t\t\t\t// DNS_CACHE_TTL_PROPERTY_NAME of -1 = cache forever\n\t\t\t\t\tjava.security.Security.setProperty(\n\t\t\t\t\t\t\tDNS_CACHE_TTL_PROPERTY_NAME, \"-1\");\n\t\t\t\t} else {\n\t\t\t\t\tjava.security.Security.setProperty(\n\t\t\t\t\t\t\tDNS_CACHE_TTL_PROPERTY_NAME, originalDNSCacheTTL);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected static <T> T _request(APIResource.RequestMethod method,\n\t\t\tString url, Map<String, Object> params, Class<T> clazz,\n\t\t\tString apiKey) throws AuthenticationException,\n\t\t\tInvalidRequestException, APIConnectionException, APIException {\n\t\tif ((Shippo.apiKey == null || Shippo.apiKey.length() == 0)\n\t\t\t\t&& (apiKey == null || apiKey.length() == 0)) {\n\t\t\tthrow new AuthenticationException(\n\t\t\t\t\t\"No API key provided. (HINT: set your API key using 'Shippo.apiKey = <API-KEY>'. \"\n\t\t\t\t\t\t\t+ \"You can generate API keys from the Shippo web interface. \"\n\t\t\t\t\t\t\t+ \"See https://goshippo.com/docs for details or email [email protected] if you have questions.\");\n\t\t}\n\n\t\tif (apiKey == null) {\n\t\t\tapiKey = Shippo.apiKey;\n\t\t}\n\n\t\tString query;\n\t\ttry {\n\t\t\tquery = createQuery(params, method, clazz);\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t throw new InvalidRequestException(\"Unable to encode parameters to \" + CHARSET\n\t + \". Please contact [email protected] for assistance.\", null, e);\n\t\t}\n\t\tShippoResponse response = makeURLConnectionRequest(method, url, query, apiKey, clazz);\n\n\t\tint rCode = response.responseCode;\n\t\tString rBody = response.responseBody;\n\n\t\tif (rCode < 200 || rCode >= 300) {\n\t\t\thandleAPIError(rBody, rCode);\n\t\t}\n\t\treturn GsonFactory.getGson(clazz).fromJson(rBody, clazz);\n\t}\n\n\tprivate static void handleAPIError(String rBody, int rCode)\n\t\t\tthrows InvalidRequestException, AuthenticationException,\n\t\t\tAPIException {\n\n\t\t// Current API does not support JSON Based error response bodies\n\t\t// APIResource.Error error = GSON.fromJson(rBody,\n\t\t// APIResource.ErrorContainer.class).error;\n\t\tAPIResource.Error error = new Error();\n\t\terror.message = rBody;\n\t\terror.code = rCode + \"\";\n\n\t\tswitch (rCode) {\n\t\tcase 400:\n\t\t\tthrow new InvalidRequestException(error.message, error.param, null);\n\t\tcase 404:\n\t\t\tthrow new InvalidRequestException(error.message, error.param, null);\n\t\tcase 401:\n\t\t\tthrow new AuthenticationException(error.message);\n\t\tdefault:\n\t\t\tthrow new APIException(error.message, null);\n\t\t}\n\t}\n\n private static String createGETQuery(Map<String, Object> params, Class<?> clazz)\n \t\tthrows UnsupportedEncodingException, InvalidRequestException {\n\t\tMap<String, String> flatParams = flattenParams(params);\n\t\tStringBuilder queryStringBuffer = new StringBuilder();\n\t\tfor (Map.Entry<String, String> entry : flatParams.entrySet()) {\n\t\t if (queryStringBuffer.length() > 0) {\n\t\t queryStringBuffer.append(\"&\");\n\t\t }\n\t\t queryStringBuffer.append(urlEncodePair(entry.getKey(), entry.getValue()));\n\t\t}\n\t\treturn queryStringBuffer.toString();\n\t}\n\n private static String createQuery(Map<String, Object> params, APIResource.RequestMethod method,\n \t\tClass<?> clazz) throws UnsupportedEncodingException, InvalidRequestException {\n\t\tswitch (method) {\n\t\tcase GET:\n\t\t\treturn createGETQuery(params, clazz);\n\t\tcase POST:\n\t\t\treturn mapToJson(params, clazz);\n\t\tdefault:\n\t\t\treturn mapToJson(params, clazz);\n }\n\n}\n}"
] | import java.util.HashMap;
import java.util.Map;
import com.shippo.exception.APIConnectionException;
import com.shippo.exception.APIException;
import com.shippo.exception.AuthenticationException;
import com.shippo.exception.InvalidRequestException;
import com.shippo.net.APIResource; | package com.shippo.model;
public class CarrierAccount extends APIResource {
String objectId;
String accountId;
String carrier;
Boolean test;
Boolean active;
Object parameters;
public static CarrierAccount create(Map<String, Object> params) | throws AuthenticationException, InvalidRequestException, | 2 |
Lyneira/MachinaCraft | MachinaDrill/src/me/lyneira/MachinaDrill/Detector.java | [
"public enum BlockRotation {\r\n ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;\r\n\r\n private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };\r\n private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };\r\n private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };\r\n private final static BlockRotation[] byOrdinal = BlockRotation.values();\r\n \r\n\r\n /**\r\n * Returns the opposite rotation.\r\n */\r\n public final BlockRotation getOpposite() {\r\n return byOrdinal[(this.ordinal() + 2) % 4];\r\n }\r\n\r\n /**\r\n * Returns the rotation left of this one.\r\n */\r\n public final BlockRotation getLeft() {\r\n return byOrdinal[(this.ordinal() + 1) % 4];\r\n }\r\n\r\n /**\r\n * Returns the rotation right of this one.\r\n */\r\n public final BlockRotation getRight() {\r\n return byOrdinal[(this.ordinal() + 3) % 4];\r\n }\r\n\r\n /**\r\n * Adds the given {@link BlockRotation} to this one and returns the result.\r\n * \r\n * @param other\r\n * The rotation to add.\r\n * @return The new rotation\r\n */\r\n public final BlockRotation add(final BlockRotation other) {\r\n return byOrdinal[(this.ordinal() + other.ordinal()) % 4];\r\n }\r\n\r\n /**\r\n * Subtracts the given {@link BlockRotation} from this one and returns the\r\n * result.\r\n * \r\n * @param other\r\n * The rotation to add.\r\n * @return The new rotation\r\n */\r\n public final BlockRotation subtract(final BlockRotation other) {\r\n return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];\r\n }\r\n\r\n /**\r\n * Converts a BlockRotation into a BlockFace in the XZ plane.\r\n * \r\n * @return The BlockFace corresponding to this rotation.\r\n */\r\n public final BlockFace getYawFace() {\r\n return yawFace[this.ordinal()];\r\n }\r\n \r\n /**\r\n * Converts a BlockRotation into a BlockVector in the XZ plane.\r\n * \r\n * @return The BlockVector corresponding to this rotation.\r\n */\r\n public final BlockVector getYawVector() {\r\n return yawVector[this.ordinal()];\r\n }\r\n \r\n /**\r\n * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.\r\n * \r\n * @return\r\n */\r\n public final byte getYawData() {\r\n return yawData[this.ordinal()];\r\n }\r\n\r\n /**\r\n * Converts the yaw from a float-based {@link Location} to a BlockRotation\r\n * \r\n * @param yaw\r\n * @return\r\n */\r\n public static final BlockRotation yawFromLocation(Location location) {\r\n // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).\r\n int yaw = ((int)location.getYaw() % 360 + 360) % 360;\r\n if (yaw < 45) {\r\n // WEST\r\n return ROTATE_270;\r\n } else if (yaw < 135) {\r\n // NORTH\r\n return ROTATE_180;\r\n } else if (yaw < 225) {\r\n // EAST\r\n return ROTATE_90;\r\n } else if (yaw < 315) {\r\n // SOUTH\r\n return ROTATE_0;\r\n } else {\r\n // WEST\r\n return ROTATE_270;\r\n }\r\n }\r\n\r\n public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {\r\n switch(face) {\r\n case SOUTH:\r\n return ROTATE_0;\r\n case EAST:\r\n return ROTATE_90;\r\n case NORTH:\r\n return ROTATE_180;\r\n case WEST:\r\n return ROTATE_270;\r\n default:\r\n throw new Exception(\"Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST\");\r\n }\r\n }\r\n}\r",
"public class BlockVector {\r\n public final int x;\r\n public final int y;\r\n public final int z;\r\n\r\n /**\r\n * Constructs a BlockVector from the given x, y and z values.\r\n * \r\n * @param x\r\n * The length in the x direction\r\n * @param y\r\n * The length in the y direction\r\n * @param z\r\n * The length in the z direction\r\n */\r\n public BlockVector(int x, int y, int z) {\r\n this.x = x;\r\n this.y = y;\r\n this.z = z;\r\n }\r\n\r\n /**\r\n * Constructs a new BlockVector identical to the given vector.\r\n * \r\n * @param vector\r\n * The vector to copy\r\n */\r\n public BlockVector(BlockVector vector) {\r\n this.x = vector.x;\r\n this.y = vector.y;\r\n this.z = vector.z;\r\n }\r\n\r\n /**\r\n * Constructs a BlockVector from the given BlockFace\r\n * \r\n * @param face\r\n * The BlockFace to copy\r\n */\r\n public BlockVector(BlockFace face) {\r\n x = face.getModX();\r\n y = face.getModY();\r\n z = face.getModZ();\r\n }\r\n\r\n /**\r\n * Constructs a BlockVector from the given Block\r\n * \r\n * @param face\r\n * The BlockFace to copy\r\n */\r\n public BlockVector(Block block) {\r\n x = block.getX();\r\n y = block.getY();\r\n z = block.getZ();\r\n }\r\n\r\n /**\r\n * Returns the {@link Block} that this BlockVector represents in the given\r\n * World.\r\n * \r\n * @param world\r\n * The world to get the block in\r\n * @return The block equivalent to this BlockVector.\r\n */\r\n public final Block getBlock(World world) {\r\n return world.getBlockAt(x, y, z);\r\n }\r\n\r\n /**\r\n * Returns the {@link Block} that this BlockVector represents in the given\r\n * World.\r\n * \r\n * @param world\r\n * The world to get the block in\r\n * @param originX\r\n * The X origin this block is relative to\r\n * @param originY\r\n * The Y origin this block is relative to\r\n * @param originZ\r\n * The Z origin this block is relative to\r\n * @return The block corresponding to this BlockVector and the given origin.\r\n */\r\n public final Block getBlock(World world, int originX, int originY, int originZ) {\r\n return world.getBlockAt(x + originX, y + originY, z + originZ);\r\n }\r\n\r\n /**\r\n * Adds the given BlockFace to this BlockVector\r\n * \r\n * @param face\r\n * The BlockFace to add\r\n * @return A new BlockVector with the BlockFace added\r\n */\r\n public BlockVector add(BlockFace face) {\r\n return new BlockVector(x + face.getModX(), y + face.getModY(), z + face.getModZ());\r\n }\r\n\r\n /**\r\n * Adds the given BlockFace n times to this BlockVector\r\n * \r\n * @param face\r\n * The BlockFace to add\r\n * @param n\r\n * The number of times to apply this blockface.\r\n * @return A new BlockVector with the BlockFace added\r\n */\r\n public BlockVector add(BlockFace face, int n) {\r\n return new BlockVector(x + face.getModX() * n, y + face.getModY() * n, z + face.getModZ() * n);\r\n }\r\n\r\n /**\r\n * Adds the given {@link BlockVector} to this {@link BlockVector}\r\n * \r\n * @param vector\r\n * The vector to add\r\n * @return A new {@link BlockVector} with the given vector added\r\n */\r\n public BlockVector add(BlockVector vector) {\r\n return new BlockVector(x + vector.x, y + vector.y, z + vector.z);\r\n }\r\n\r\n /**\r\n * Adds the given {@link BlockVector} n times to this {@link BlockVector}\r\n * \r\n * @param vector\r\n * The vector to add\r\n * @param n\r\n * The number of times to apply this vector.\r\n * @return A new {@link BlockVector} with the given vector added\r\n */\r\n public BlockVector add(BlockVector vector, int n) {\r\n return new BlockVector(x + vector.x * n, y + vector.y * n, z + vector.z * n);\r\n }\r\n\r\n /**\r\n * Adds the given coordinates x, y, z to this {@link BlockVector}\r\n * \r\n * @param x\r\n * The x coordinate\r\n * @param y\r\n * The y coordinate\r\n * @param z\r\n * The z coordinate\r\n * @return A new {@link BlockVector} with the given coordinates added\r\n */\r\n public BlockVector add(int x, int y, int z) {\r\n return new BlockVector(x + this.x, y + this.y, z + this.z);\r\n }\r\n\r\n /**\r\n * Substract the given {@link BlockVector} from this one. If this vector and\r\n * 'other' are locations, substract() returns a vector pointing from 'other'\r\n * to this BlockLocation.\r\n * \r\n * @param other\r\n * The {@link BlockVector} to subtract\r\n * @return A new {@link BlockVector} with the given vector subtracted\r\n */\r\n public BlockVector subtract(BlockVector other) {\r\n return new BlockVector(this.x - other.x, this.y - other.y, this.z - other.z);\r\n }\r\n\r\n /**\r\n * Faster equality test for BlockVectors than equals()\r\n * \r\n * @param other\r\n * @return True if the vectors are equal.\r\n */\r\n public boolean equalsOther(BlockVector other) {\r\n if (other == null)\r\n return false;\r\n return this.x == other.x && this.y == other.y && this.z == other.z;\r\n }\r\n\r\n /**\r\n * Fastest equality test for BlockVectors, use only if the parameter is\r\n * known to be non-null.\r\n * \r\n * @param other\r\n * @return True if the vectors are equal.\r\n */\r\n public boolean equalsOtherNotNull(BlockVector other) {\r\n return this.x == other.x && this.y == other.y && this.z == other.z;\r\n }\r\n\r\n /**\r\n * Returns a BlockVector rotated by the given BlockRotation around the Y\r\n * axis.\r\n * \r\n * @param rotate\r\n * The amount to rotate by\r\n * @return A new rotated BlockVector\r\n */\r\n public BlockVector rotateYaw(BlockRotation rotate) {\r\n switch (rotate) {\r\n case ROTATE_0:\r\n return this;\r\n case ROTATE_90:\r\n return new BlockVector(z, y, -x);\r\n case ROTATE_180:\r\n return new BlockVector(-x, y, -z);\r\n case ROTATE_270:\r\n default:\r\n return new BlockVector(-z, y, x);\r\n }\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n /*\r\n * Squeeze the coordinates into a long, keeping only 28 bits of x and z.\r\n * Masking y is unnecessary because it's completely shifted to the\r\n * right)\r\n * \r\n * 28 bits still gives a range of ~158 million in both positive and\r\n * negative directions, and the CraftBukkit world is limited to 30\r\n * million in either direction.\r\n */\r\n long hashCode = x & 0xFFFFFFFL | ((z & 0xFFFFFFFL) << 28) | (y << 56);\r\n /*\r\n * Apply a hash method from MurmurHash3\r\n * http://code.google.com/p/smhasher/wiki/MurmurHash3\r\n */\r\n hashCode ^= hashCode >>> 33;\r\n hashCode *= 0xff51afd7ed558ccdL;\r\n hashCode ^= hashCode >>> 33;\r\n hashCode *= 0xc4ceb9fe1a85ec53L;\r\n hashCode ^= hashCode >>> 33;\r\n return (int) hashCode;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == null)\r\n return false;\r\n\r\n if (!(obj instanceof BlockVector))\r\n return false;\r\n\r\n BlockVector other = (BlockVector) obj;\r\n\r\n return this.x == other.x && this.y == other.y && this.z == other.z;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return Integer.toString(x) + \", \" + Integer.toString(y) + \", \" + Integer.toString(z);\r\n }\r\n\r\n /*\r\n * Static stuff\r\n */\r\n \r\n public static BlockVector fromBlockFace(BlockFace face) {\r\n return faceVectors[face.ordinal()];\r\n }\r\n \r\n private final static BlockVector[] faceVectors;\r\n \r\n static {\r\n BlockFace[] faces = BlockFace.values();\r\n faceVectors = new BlockVector[faces.length];\r\n for (int i = 0; i < faces.length; i++) {\r\n faceVectors[i] = new BlockVector(faces[i]);\r\n }\r\n } \r\n}\r",
"public class MachinaBlock extends BlockVector {\r\n\r\n public final int typeId;\r\n public final short data;\r\n\r\n public MachinaBlock(int x, int y, int z, int typeId, short data) {\r\n super(x, y, z);\r\n this.typeId = typeId;\r\n this.data = data;\r\n }\r\n\r\n public MachinaBlock(BlockVector vector, int typeId, short data) {\r\n super(vector);\r\n this.typeId = typeId;\r\n this.data = data;\r\n }\r\n\r\n public MachinaBlock(int x, int y, int z, int typeId) {\r\n super(x, y, z);\r\n this.typeId = typeId;\r\n this.data = -1;\r\n }\r\n\r\n public MachinaBlock(BlockVector vector, int typeId) {\r\n super(vector);\r\n this.typeId = typeId;\r\n this.data = -1;\r\n }\r\n \r\n public MachinaBlock(MachinaBlock other, int originX, int originY, int originZ) {\r\n super(other.x + originX, other.y + originY, other.z + originZ);\r\n typeId = other.typeId;\r\n data = other.data;\r\n }\r\n\r\n /**\r\n * Returns a MachinaBlock rotated by the given BlockRotation around the Y\r\n * axis.\r\n * \r\n * @param rotate\r\n * The amount to rotate by\r\n * @return A new rotated MachinaBlock\r\n */\r\n @Override\r\n public MachinaBlock rotateYaw(final BlockRotation rotate) {\r\n switch (rotate) {\r\n case ROTATE_0:\r\n return this;\r\n case ROTATE_90:\r\n return new MachinaBlock(z, y, -x, typeId, data);\r\n case ROTATE_180:\r\n return new MachinaBlock(-x, y, -z, typeId, data);\r\n case ROTATE_270:\r\n default:\r\n return new MachinaBlock(-z, y, x, typeId, data);\r\n }\r\n }\r\n\r\n /**\r\n * Matches this {@link MachinaBlock} with the given world and returns true\r\n * if successful. In other words, it returns true if the world contains this\r\n * block's type and data at this block's location. A data value of -1 will\r\n * only match the type.\r\n * \r\n * @param world\r\n * @return\r\n */\r\n public boolean match(World world) {\r\n return matchInternal(world, x, y, z);\r\n }\r\n\r\n public boolean match(World world, int originX, int originY, int originZ) {\r\n return matchInternal(world, x + originX, y + originY, z + originZ);\r\n }\r\n\r\n public boolean match(World world, BlockVector origin) {\r\n return matchInternal(world, x + origin.x, y + origin.y, z + origin.z);\r\n }\r\n\r\n /**\r\n * Compares only the type of this MachinaBlock to the given block and\r\n * returns true if they match.\r\n * \r\n * @param block\r\n * The block to compare to\r\n * @return True if the type matches.\r\n */\r\n public boolean matchTypeOnly(Block block) {\r\n if (data == -1) {\r\n return block.getTypeId() == typeId;\r\n }\r\n return block.getTypeId() == typeId && block.getData() == data;\r\n }\r\n\r\n private boolean matchInternal(World world, int x, int y, int z) {\r\n if (data == -1) {\r\n return world.getBlockTypeIdAt(x, y, z) == typeId;\r\n } else {\r\n final Block block = world.getBlockAt(x, y, z);\r\n return (block.getTypeId() == typeId && block.getData() == data);\r\n }\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"[type: \" + typeId + \" data: \" + data + \" - \" + super.toString() + \"]\";\r\n }\r\n}\r",
"public class MachinaBlueprint {\r\n\r\n /**\r\n * The model that should be scanned for when detection is triggered. The\r\n * base model is a part of the machina that remains present and static in\r\n * all forms and variations of the machina. For best detection performance,\r\n * it should be a set of blocks that fully defines the direction of the\r\n * machina. (for example blocks of differing types that don't occur\r\n * symmetrically)\r\n */\r\n private final BlueprintModel baseModel;\r\n\r\n /**\r\n * Callback class that will be run when the base model has been detected. It\r\n * may detect extensions on the base model and add them to the machina being\r\n * constructed. The detector will receive the direction used by MachinaCore\r\n * to detect the base model, but in some cases (like a symmetric machina)\r\n * this may not be the correct direction.\r\n */\r\n private MachinaDetector detector;\r\n private final MachinaBlock triggerBlock;\r\n\r\n public MachinaBlueprint(MachinaBlock triggerBlock, BlueprintModel baseModel) {\r\n this.baseModel = new BlueprintModel(baseModel);\r\n if (triggerBlock == null)\r\n throw new NullPointerException(\"Cannot construct a MachinaBlueprint without a trigger block!\");\r\n this.triggerBlock = triggerBlock;\r\n }\r\n\r\n /*\r\n * Extensions - Extensions are the same as a base model but the location and\r\n * presence of these is variable. They are not directly detected by\r\n * MachinaCore, instead the Detector can trigger detection of an Extension\r\n * at a specific location. If successful, the extension will be added to the\r\n * model of the machina being constructed. The offset is automatically\r\n * calculated by MachinaCore. A single extension can be detected multiple\r\n * times at different locations.\r\n * \r\n * They can be predefined same as the base model. Coordinates of the\r\n * extension's blocks are specific to this extension.\r\n */\r\n\r\n /*\r\n * Detector - Callback class that will be run when the base model has been\r\n * detected. It may detect extensions on the base model and add them to the\r\n * machina being constructed. The detector will receive the direction used\r\n * by MachinaCore to detect the base model, but in some cases (like a\r\n * symmetric machina) this may not be the correct direction.\r\n */\r\n\r\n /**\r\n * Detects whether a machina conforming to this blueprint is present at the\r\n * given block and adds it to the given universe.\r\n * \r\n * @param universe\r\n * The universe (and its corresponding world) to detect in\r\n * @param block\r\n * The block to detect at\r\n * @param player\r\n * The player that initiated this detection or null if not a\r\n * player\r\n * @return\r\n */\r\n public DetectResult detect(Universe universe, Block block, Player player) {\r\n if (!triggerBlock.matchTypeOnly(block))\r\n return DetectResult.FAILURE;\r\n\r\n ConstructionModel constructionModel = null;\r\n for (BlockRotation r : BlockRotation.values()) {\r\n final MachinaBlock rotatedTrigger = triggerBlock.rotateYaw(r);\r\n final BlockVector origin = new BlockVector(block.getX() - rotatedTrigger.x, block.getY() - rotatedTrigger.y, block.getZ() - rotatedTrigger.z);\r\n final World world = block.getWorld();\r\n constructionModel = baseModel.construct(block.getWorld(), r, origin);\r\n if (constructionModel != null) {\r\n /*\r\n * Machina base model was constructed, now hand it to the\r\n * detector for extension\r\n */\r\n final MachinaController controller = detector.detect(constructionModel, player, world, r, origin);\r\n final Machina machina;\r\n if (controller == null) {\r\n return DetectResult.FAILURE;\r\n } else if (universe.add(machina = new Machina(universe, constructionModel.machinaModel(), controller))) {\r\n machina.scheduleEvent(new CreationEvent(player), 1);\r\n return DetectResult.SUCCESS;\r\n } else {\r\n MachinaCore.info(\"Successfully detected a machina but had a collision!\");\r\n return DetectResult.COLLISION;\r\n }\r\n }\r\n }\r\n return DetectResult.FAILURE;\r\n }\r\n\r\n public final static MachinaCore.MachinaBlueprintFriend machinaCoreFriend = new MachinaCore.MachinaBlueprintFriend() {\r\n @Override\r\n protected void setDetector(MachinaBlueprint blueprint, MachinaDetector detector) {\r\n blueprint.detector = detector;\r\n }\r\n };\r\n}\r",
"public interface MachinaController {\r\n /**\r\n * Called to inform the controller that its machina has been created and is\r\n * successfully added to the universe.\r\n * <p>\r\n * <b>Note:</b> Since it may also be called when a\r\n * machina gets loaded with the world, not just when a player creates a new\r\n * machina, this method is not a replacement for CreationEvent!\r\n * \r\n * @param machina\r\n * The machina to link to\r\n */\r\n public void initialize(Machina machina);\r\n}\r",
"public interface MachinaDetector {\r\n\r\n /**\r\n * Called when the detector is registered with MachinaCore. The returned\r\n * blueprint will be used to detect a machina's base model before being\r\n * handed to the detector.\r\n * \r\n * @return The base blueprint for this detector.\r\n */\r\n public MachinaBlueprint getBlueprint();\r\n\r\n /**\r\n * Performs any dynamic detection for the detected base model, adding those\r\n * blocks to it. Performs needed permission checks for the player.\r\n * Configures a MachinaController and returns it if detection was\r\n * successful, null otherwise. If successful, the model that was passed in\r\n * will be used to initialize the corresponding machina and it will be\r\n * linked to the returned MachinaController.\r\n * \r\n * @param model\r\n * The base model that was detected\r\n * @param player\r\n * The player that initiated the detection. Can be null if\r\n * detection was triggered by redstone or other plugin means.\r\n * @param world\r\n * The world the machina is being detected in\r\n * @param yaw\r\n * The direction detected for the base model. May not be the only\r\n * valid direction if the trigger block is also the origin and\r\n * the machina's base model has symmetry.\r\n * @param origin\r\n * The origin point for the detected base model\r\n * @return A MachinaController if successful, null otherwise.\r\n */\r\n public MachinaController detect(ConstructionModel model, Player player, World world, BlockRotation yaw, BlockVector origin);\r\n}\r",
"public class BlueprintModel {\r\n final UniqueIdObjectMap<ModelNode> nodes;\r\n private ModelNode root;\r\n\r\n public BlueprintModel() {\r\n this(10);\r\n }\r\n\r\n public BlueprintModel(int initialCapacity) {\r\n nodes = new UniqueIdObjectMap<ModelNode>(initialCapacity);\r\n root = new ModelNode(new BlockVector(0, 0, 0));\r\n nodes.put(root, 0);\r\n }\r\n\r\n public BlueprintModel(BlueprintModel other) {\r\n nodes = new UniqueIdObjectMap<ModelNode>(other.nodes.capacity());\r\n root = new ModelNode(other.root);\r\n nodes.put(root, 0);\r\n NodeIterator it = other.nodeIterator(0);\r\n it.next();\r\n while (it.hasNext()) {\r\n final int id = it.next();\r\n nodes.put(new ModelNode(other.nodes.get(id)), id);\r\n }\r\n }\r\n\r\n protected BlueprintModel(int initialCapacity, ModelNode root) {\r\n nodes = new UniqueIdObjectMap<ModelNode>(initialCapacity);\r\n this.root = root;\r\n nodes.put(root, 0);\r\n }\r\n\r\n public int addNode(BlockVector origin) {\r\n return (addNode(0, origin));\r\n }\r\n\r\n public int addNode(int parentId, BlockVector origin) {\r\n final ModelNode parent = nodes.get(parentId);\r\n if (parent == null) {\r\n throw new IllegalArgumentException(\"Cannot add a node to a nonexistent parent!\");\r\n }\r\n final ModelNode newNode = new ModelNode(parentId, origin);\r\n final int id = nodes.add(newNode);\r\n parent.addChild(id);\r\n return id;\r\n }\r\n\r\n public void removeNode(int nodeId) {\r\n ModelNode node = nodes.get(nodeId);\r\n if (node == null) {\r\n return;\r\n }\r\n\r\n final int parentId = node.parent;\r\n if (parentId >= 0) {\r\n // Node is not the root, so remove it from parent\r\n nodes.get(node.parent).removeChild(nodeId);\r\n\r\n // Walk the tree and remove all subnodes\r\n for (NodeIterator it = nodeIterator(nodeId); it.hasNext();) {\r\n nodes.remove(it.next());\r\n }\r\n } else {\r\n throw new UnsupportedOperationException(\"Cannot remove the root node in a ConstructionModelTree!\");\r\n }\r\n\r\n }\r\n\r\n public boolean hasNode(int nodeId) {\r\n return nodes.get(nodeId) != null;\r\n }\r\n\r\n public TIntIterator children(int nodeId) {\r\n final ModelNode node = nodes.get(nodeId);\r\n if (node == null) {\r\n return null;\r\n }\r\n return node.children();\r\n }\r\n\r\n public MachinaBlock getBlock(int id) {\r\n root.dumpBlocks();\r\n return root.blocks.get(id);\r\n }\r\n\r\n public MachinaBlock getBlock(int nodeId, int id) {\r\n ModelNode node = nodes.get(nodeId);\r\n if (node == null)\r\n return null;\r\n return node.blocks.get(id);\r\n }\r\n\r\n public int addBlock(MachinaBlock block) {\r\n return root.blocks.add(block);\r\n }\r\n\r\n public int addBlock(int nodeId, MachinaBlock block) {\r\n ModelNode node = nodes.get(nodeId);\r\n if (node == null)\r\n return -1;\r\n return node.blocks.add(block);\r\n }\r\n\r\n public void deleteBlock(int id) {\r\n root.blocks.remove(id);\r\n }\r\n\r\n public void deleteBlock(int nodeId, int id) {\r\n ModelNode node = nodes.get(nodeId);\r\n if (node == null)\r\n return;\r\n node.blocks.remove(id);\r\n }\r\n\r\n public void clearRootBlocks() {\r\n root.clearBlocks();\r\n }\r\n\r\n public void clearBlocks(int nodeId) {\r\n ModelNode node = nodes.get(nodeId);\r\n if (node == null)\r\n return;\r\n node.clearBlocks();\r\n }\r\n\r\n public void putBlock(MachinaBlock newBlock, int id) {\r\n root.blocks.put(newBlock, id);\r\n }\r\n\r\n public void putBlock(int nodeId, MachinaBlock newBlock, int id) {\r\n ModelNode node = nodes.get(nodeId);\r\n if (node == null)\r\n return;\r\n node.blocks.put(newBlock, id);\r\n }\r\n\r\n /* *************\r\n * Other methods\r\n */\r\n /**\r\n * Detects whether this model is present for the given world, rotation and\r\n * origin and returns a properly rotated copy of this model if successful.\r\n * Returns null on failure.\r\n * \r\n * @param world\r\n * @param rotation\r\n * @param origin\r\n * @return\r\n */\r\n public ConstructionModel construct(World world, BlockRotation rotation, BlockVector origin) {\r\n ModelNode newRoot = new ModelNode(root.parent, root.origin, root.blocks.capacity());\r\n newRoot.copyChildren(root);\r\n\r\n ConstructionModel constructionModel = new ConstructionModel(world, origin, nodes.capacity(), newRoot);\r\n\r\n if (constructionModel.putBlueprintBlocks(0, root.blockIterator(), rotation) == false)\r\n return null;\r\n\r\n NodeIterator it = nodeIterator(0);\r\n // We've already added the root, so the while is only necessary for\r\n // subnodes.\r\n it.next();\r\n\r\n while (it.hasNext()) {\r\n final int nodeId = it.next();\r\n ModelNode node = nodes.get(nodeId);\r\n ModelNode newNode = new ModelNode(node.parent, node.origin, node.blocks.capacity());\r\n newNode.copyChildren(node);\r\n constructionModel.nodes.put(newNode, nodeId);\r\n if (constructionModel.putBlueprintBlocks(nodeId, node.blockIterator(), rotation) == false)\r\n return null;\r\n }\r\n\r\n return constructionModel;\r\n }\r\n\r\n /*\r\n * Nonpublic methods\r\n */\r\n NodeIterator nodeIterator(int nodeId) {\r\n return new NodeIterator(nodeId, nodes);\r\n }\r\n \r\n /*\r\n * Debug\r\n */\r\n public void dumpTree() {\r\n MachinaCore.info(\"Beginning tree dump\");\r\n NodeIterator it = nodeIterator(0);\r\n while (it.hasNext()) {\r\n int nodeId = it.next();\r\n MachinaCore.info(\"Dumping node id \" + nodeId);\r\n ModelNode node = nodes.get(nodeId);\r\n node.dumpBlocks();\r\n }\r\n }\r\n\r\n}\r",
"public class ConstructionModel extends BlueprintModel {\r\n\r\n private final World world;\r\n private final BlockVector origin;\r\n private int x;\r\n private int y;\r\n private int z;\r\n\r\n ConstructionModel(World world, BlockVector origin, int initialCapacity, ModelNode root) {\r\n super(initialCapacity, root);\r\n this.world = world;\r\n this.origin = origin;\r\n }\r\n\r\n public Block getWorldBlock(BlockVector location) {\r\n return location.getBlock(world, origin.x, origin.y, origin.z);\r\n }\r\n\r\n public Block getWorldBlock(int nodeId, BlockVector location) {\r\n if (!hasNode(nodeId))\r\n return null;\r\n determineOrigin(nodeId);\r\n return location.getBlock(world, x, y, z);\r\n }\r\n\r\n public int extend(BlockVector location) {\r\n x = origin.x;\r\n y = origin.y;\r\n z = origin.z;\r\n return extendInternal(0, location);\r\n }\r\n\r\n public int extend(BlockVector location, int[] types) {\r\n x = origin.x;\r\n y = origin.y;\r\n z = origin.z;\r\n return extendInternal(0, location, types);\r\n }\r\n\r\n public int extend(BlockVector location, int typeId) {\r\n x = origin.x;\r\n y = origin.y;\r\n z = origin.z;\r\n return extendInternal(0, location, typeId);\r\n }\r\n\r\n public int extend(BlockVector location, int typeId, short data) {\r\n x = origin.x;\r\n y = origin.y;\r\n z = origin.z;\r\n return extendInternal(0, location, typeId, data);\r\n }\r\n\r\n public int extend(int nodeId, BlockVector location) {\r\n if (!hasNode(nodeId))\r\n return -1;\r\n determineOrigin(nodeId);\r\n return extendInternal(nodeId, location);\r\n }\r\n\r\n public int extend(int nodeId, BlockVector location, int[] types) {\r\n if (!hasNode(nodeId))\r\n return -1;\r\n determineOrigin(nodeId);\r\n\r\n return extendInternal(nodeId, location, types);\r\n }\r\n\r\n public int extend(int nodeId, BlockVector location, int typeId) {\r\n if (!hasNode(nodeId))\r\n return -1;\r\n determineOrigin(nodeId);\r\n\r\n return extendInternal(nodeId, location, typeId);\r\n }\r\n\r\n public int extend(int nodeId, BlockVector location, int typeId, short data) {\r\n if (!hasNode(nodeId))\r\n return -1;\r\n determineOrigin(nodeId);\r\n\r\n return extendInternal(nodeId, location, typeId, data);\r\n }\r\n\r\n /**\r\n * Converts this model into a MachinaModel and returns it.\r\n * \r\n * @return The MachinaModel that was created.\r\n */\r\n public MachinaModel machinaModel() {\r\n return new MachinaModel(world, origin, this);\r\n }\r\n\r\n /*\r\n * Nonpublic methods\r\n */\r\n\r\n /**\r\n * Iterates over all blocks returned by the given UniqueIdObjectIterator,\r\n * rotating them by the given rotation and detecting whether they are\r\n * present in the world. If all are detected successfully, the rotated\r\n * blocks will be added to the node with their detected data values.\r\n * Otherwise the state of the tree is undefined and it should no longer be\r\n * used.\r\n * \r\n * @param nodeId\r\n * The node to add blocks to\r\n * @param it\r\n * An iterator over all blocks to be added\r\n * @param rotation\r\n * How to rotate the blocks before detecting\r\n * @return True if successful, false if not all blocks were detected.\r\n */\r\n boolean putBlueprintBlocks(int nodeId, UniqueIdObjectIterator<MachinaBlock> it, BlockRotation rotation) {\r\n determineOrigin(nodeId);\r\n ModelNode node = nodes.get(nodeId);\r\n while (it.hasNext()) {\r\n final MachinaBlock block = it.next();\r\n final BlockVector rotated = block.rotateYaw(rotation);\r\n final Block worldBlock = rotated.getBlock(world, x, y, z);\r\n final int typeId = worldBlock.getTypeId();\r\n if (typeId != block.typeId)\r\n return false;\r\n final short data = worldBlock.getData();\r\n if (block.data != -1 && data != block.data) {\r\n return false;\r\n }\r\n node.blocks.put(new MachinaBlock(rotated, typeId, data), it.lastId());\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Walk up the tree to determine the full origin and store it in x, y and z.\r\n * \r\n * @param nodeId\r\n * The node from which to start.\r\n */\r\n private void determineOrigin(int nodeId) {\r\n x = origin.x;\r\n y = origin.y;\r\n z = origin.z;\r\n /*\r\n * we know the root of a ConstructionModelTree is always 0,0,0 so it's\r\n * safe to skip the root, otherwise this would be -1\r\n */\r\n for (int i = nodeId; i != 0;) {\r\n ModelNode node = nodes.get(i);\r\n BlockVector nodeOrigin = node.origin;\r\n x += nodeOrigin.x;\r\n y += nodeOrigin.y;\r\n z += nodeOrigin.z;\r\n i = node.parent;\r\n }\r\n }\r\n\r\n private int extendInternal(int nodeId, BlockVector location) {\r\n final Block block = location.getBlock(world, x, y, z);\r\n return addBlock(nodeId, new MachinaBlock(location.x, location.y, location.z, block.getTypeId(), block.getData()));\r\n }\r\n\r\n private int extendInternal(int nodeId, BlockVector location, int[] types) {\r\n final Block block = location.getBlock(world, x, y, z);\r\n final int blockType = block.getTypeId();\r\n for (int i : types) {\r\n if (i == blockType) {\r\n return addBlock(nodeId, new MachinaBlock(location.x, location.y, location.z, i, block.getData()));\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n private int extendInternal(int nodeId, BlockVector location, int typeId) {\r\n final Block block = location.getBlock(world, x, y, z);\r\n if (block.getTypeId() == typeId) {\r\n return addBlock(nodeId, new MachinaBlock(location.x, location.y, location.z, typeId, block.getData()));\r\n }\r\n return -1;\r\n }\r\n\r\n private int extendInternal(int nodeId, BlockVector location, int typeId, short data) {\r\n final Block block = location.getBlock(world, x, y, z);\r\n if (block.getTypeId() == typeId) {\r\n if (data == -1) {\r\n data = block.getData();\r\n } else if (block.getData() != data) {\r\n return -1;\r\n }\r\n return addBlock(nodeId, new MachinaBlock(location.x, location.y, location.z, typeId, data));\r\n }\r\n return -1;\r\n }\r\n\r\n}\r"
] | import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import me.lyneira.MachinaCore.block.BlockRotation;
import me.lyneira.MachinaCore.block.BlockVector;
import me.lyneira.MachinaCore.block.MachinaBlock;
import me.lyneira.MachinaCore.machina.MachinaBlueprint;
import me.lyneira.MachinaCore.machina.MachinaController;
import me.lyneira.MachinaCore.machina.MachinaDetector;
import me.lyneira.MachinaCore.machina.model.BlueprintModel;
import me.lyneira.MachinaCore.machina.model.ConstructionModel;
| package me.lyneira.MachinaDrill;
class Detector implements MachinaDetector {
static int activationDepthLimit = 0;
static int materialCore = Material.GOLD_BLOCK.getId();
static int materialBase = Material.WOOD.getId();
static int materialHeadNormal = Material.IRON_BLOCK.getId();
static int materialHeadFast = Material.DIAMOND_BLOCK.getId();
static final int materialFurnace = Material.FURNACE.getId();
static final int materialFurnaceBurning = Material.BURNING_FURNACE.getId();
private static final int[] furnaceTypes = new int[] { materialFurnace, materialFurnaceBurning };
| private final MachinaBlueprint blueprint;
| 3 |
bafomdad/realfilingcabinet | com/bafomdad/realfilingcabinet/items/capabilities/CapabilityFolder.java | [
"@Config(modid=RealFilingCabinet.MOD_ID)\npublic static class ConfigRFC {\n\t\t\n\t// RECIPES\n\t@Comment({\"Enable Crafting Upgrade recipe\"})\n\t@Tap\n\tpublic static boolean craftingUpgrade = true;\n\t@Comment({\"Enable Ender Upgrade recipe\"})\n\t@Tap\n\tpublic static boolean enderUpgrade = true;\n\t@Comment({\"Enable Oredict Upgrade recipe\"})\n\t@Tap\n\tpublic static boolean oreDictUpgrade = true;\n\t@Comment({\"Enable Mob Upgrade recipe\"})\n\t@Tap\n\tpublic static boolean mobUpgrade = true;\n\t@Comment({\"Enable Fluid Upgrade recipe\"})\n\t@Tap\n\tpublic static boolean fluidUpgrade = true;\n\t@Comment({\"Enable Life Upgrade recipe\"})\n\t@Tap\n\tpublic static boolean lifeUpgrade = true;\n\t@Comment({\"Enable Smelting Upgrade recipe\"})\n\t@Tap\n\tpublic static boolean smeltingUpgrade = true;\n\t\t\n\t// MISC\n\t@Comment({\"Disable this if you want TheOneProbe to handle the overlay instead.\"})\n\t@Tap\n\tpublic static boolean magnifyingGlassGui = true;\n\t@Comment({\"If enabled, will let Mob Folders with a villager in it spawn villagers with their professions randomized.\"})\n\t@Tap\n\tpublic static boolean randomVillager = false;\n\t@Comment({\"If enabled, will let filing cabinets use a different texture depending on the season.\"})\n\t@Tap\n\tpublic static boolean seasonalCabinets = true;\n\t@Comment({\"If enabled, will let Fluid Folders place water in the nether.\"})\n\t@Tap\n\tpublic static boolean waterNether = false;\n\t@Comment({\"If disabled, will not let folders pick up dropped items.\"})\n\t@Tap\n\tpublic static boolean pickupStuff = true;\n\t@Comment({\"Will output stuff to console for debugging purposes.\"})\n\t@Tap\n\tpublic static boolean debugLogger = false;\n\t@Comment({\"Use this to blacklist certain mobs from being captured in the Mob Folder. Put the class names of the entities here.\"})\n\tpublic static String[] mobFolderBlacklist = new String[]{};\n\t@Comment({\"If enabled, A fluid cabinet filled with more than 3000mb of water will never run out of water.\"})\n\t@Tap\n\tpublic static boolean infiniteWaterSource = true;\n\t@Comment({\"Configure the general folder storage limit for dyed folders.\"})\n\t@Tap\n\tpublic static int folderSizeLimit = 1000;\n\t\t\n\t// INTEGRATION\n\t@Comment({\"If enabled, will add mana cabinets and folders for Botania\"})\n\t@Tap\n\tpublic static boolean botaniaIntegration = true;\n\t@Comment({\"If enabled, will add a folder and a cabinet when it detects that Thaumcraft is installed.\"})\n\t@Tap\n\tpublic static boolean tcIntegration = true;\n}",
"@Mod(modid=RealFilingCabinet.MOD_ID, name=RealFilingCabinet.MOD_NAME, version=RealFilingCabinet.VERSION, dependencies = \"after:forge@[\" + RealFilingCabinet.FORGE_VER + \",);\")\npublic class RealFilingCabinet {\n\n\tpublic static final String MOD_ID = \"realfilingcabinet\";\n\tpublic static final String MOD_NAME = \"Real Filing Cabinet\";\n\tpublic static final String VERSION = \"@VERSION@\";\n\tpublic static final String FORGE_VER = \"14.21.0.2363\";\n\t\n\t// intentional typo in order to disable integration with storage drawers for now\n\tpublic static final String STORAGEDRAWERS = \"storageDrawers\";\n\t\n\t@SidedProxy(clientSide=\"com.bafomdad.realfilingcabinet.proxies.ClientProxy\", serverSide=\"com.bafomdad.realfilingcabinet.proxies.CommonProxy\")\n\tpublic static CommonProxy proxy;\n\t\n\[email protected](MOD_ID)\n\tpublic static RealFilingCabinet instance;\n\t\n\tpublic static Logger logger;\n\t\n\tpublic static boolean botaniaLoaded = Loader.isModLoaded(\"botania\");\n\tpublic static boolean topLoaded = Loader.isModLoaded(\"theoneprobe\");\n\tpublic static boolean wailaLoaded = Loader.isModLoaded(\"waila\");\n\tpublic static boolean tcLoaded = Loader.isModLoaded(\"thaumcraft\");\n\tpublic static boolean crtLoaded = Loader.isModLoaded(\"crafttweaker\");\n\t\n\[email protected]\n\tpublic void preInit(FMLPreInitializationEvent event) {\n\t\t\n\t\tNetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandlerRFC());\n\t\tNewConfigRFC.preInit(event);\n\t\tlogger = event.getModLog();\n\t\t\n\t\tproxy.preInit(event);\n\t\tproxy.initAllModels();\n\t}\n\t\n\[email protected]\n\tpublic void init(FMLInitializationEvent event) {\n\n\t\tproxy.init(event);\n\t}\n\t\n\[email protected]\n\tpublic void postInit(FMLPostInitializationEvent event) {\n\t\t\n\t\tproxy.postInit(event);\n\t\tMinecraftForge.EVENT_BUS.register(new EventHandlerServer());\n\t\tCapabilityProviderFolder.register();\n\t}\n\t\n\[email protected]\n\tpublic void serverLoad(FMLServerStartingEvent event) {\n\t\t\n\t\tevent.registerServerCommand(new CommandRFC());\n\t}\n}",
"public class StringLibs {\n\n\t// UPGRADES\n\tpublic static String RFC_UPGRADE = \"RFC_upgrade\";\n\tpublic static String TAG_CREATIVE = \"TAG_creativeUpgrade\";\n\tpublic static String TAG_ENDER = \"TAG_enderUpgrade\";\n\tpublic static String TAG_CRAFT = \"TAG_craftingUpgrade\";\n\tpublic static String TAG_OREDICT = \"TAG_oredictUpgrade\";\n\tpublic static String TAG_MOB = \"TAG_mobUpgrade\";\n\tpublic static String TAG_FLUID = \"TAG_fluidUpgrade\";\n\tpublic static String TAG_LIFE = \"TAG_lifeUpgrade\";\n\tpublic static String TAG_SMELT = \"TAG_smeltingUpgrade\";\n\t\n\t// ENDER FOLDER\n\tpublic static String RFC_SLOTINDEX = \"RFC_slotindex\";\n\tpublic static String RFC_TILEPOS = \"RFC_tilepos\";\n\tpublic static String RFC_DIM = \"RFC_dim\";\n\tpublic static String RFC_HASH = \"RFC_enderhash\";\n\t\n\t// UUID\n\tpublic static String RFC_OWNER = \"Own\";\n\tpublic static String RFC_COPY = \"OwnCopy\";\n\tpublic static String RFC_FALLBACK = \"RFC_playername\";\n\t\n\t// MISC\n\tpublic static String RFC_TAPED = \"RFC_whiteoutTaped\";\n\tpublic static String RFC_PLACEMODE = \"RFC_placeMode\";\n\tpublic static String RFC_IGNORENBT = \"RFC_ignoreNBT\";\n\tpublic static String RFC_CRAFTABLE = \"RFC_isCraftable\";\n\t\n\t// ENTITY\n\tpublic static String RFC_MOBUPGRADE = \"RFC_mobUpgrade\";\n}",
"public class TextHelper {\n\n\tprivate static final NavigableMap<Long, String> suffixes = new TreeMap();\n\t\n\tstatic {\n\t\tsuffixes.put(1000L, \"k\");\n\t\tsuffixes.put(1000000L, \"M\");\n\t\tsuffixes.put(1000000000L, \"b\");\n\t\tsuffixes.put(1000000000000L, \"T\");\n\t\tsuffixes.put(1000000000000000L, \"q\");\n\t}\n\t\n\tpublic static String format(long value) {\n\t\t\n\t\tif (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1);\n\t\tif (value < 0) return \"-\" + format(-value);\n\t\tif (value < 1000) return Long.toString(value);\n\t\t\n\t\tEntry<Long, String> e = suffixes.floorEntry(value);\n\t\tLong divideBy = e.getKey();\n\t\tString suffix = e.getValue();\n\t\t\n\t\tlong truncated = value / (divideBy / 10);\n\t\tboolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10);\n\t\t\n\t\treturn hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix;\n\t}\n\t\n\t// client only\n\tpublic static String localize(String str) {\n\t\t\n\t\treturn I18n.format(str);\n\t}\n\t\n\t// server only\n\tpublic static String localizeCommands(String str) {\n\t\t\n\t\treturn net.minecraft.util.text.translation.I18n.translateToLocalFormatted(\"commands.\" + RealFilingCabinet.MOD_ID + \".\" + str);\n\t}\n\t\n\tpublic static String folderStr(ItemStack folder) {\n\t\t\n\t\tif (!(folder.getItem() instanceof IFolder))\n\t\t\treturn null;\n\t\t\n\t\tObject obj = ItemFolder.getObject(folder);\n\t\tif (obj != null) {\n\t\t\treturn folder.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getDisplayName();\n\t\t}\n\t\treturn null;\n\t}\n}",
"public class RFCItems {\n\n\tpublic static ItemEmptyFolder emptyFolder;\n\tpublic static ItemFolder folder;\n\tpublic static ItemMagnifyingGlass magnifyingGlass;\n\tpublic static ItemWhiteoutTape whiteoutTape;\n\tpublic static ItemUpgrades upgrades;\n\tpublic static ItemFilter filter;\n\tpublic static ItemKeys keys;\n\tpublic static ItemDebugger debugger;\n\tpublic static ItemMysteryFolder mysteryFolder;\n\tpublic static ItemSuitcase suitcase;\n\tpublic static ItemEmptyDyedFolder emptyDyedFolder;\n\tpublic static ItemDyedFolder dyedFolder;\n\tpublic static ItemAutoFolder autoFolder;\n\t\n\t// Thaumcraft integration\n\tpublic static ItemAspectFolder aspectFolder;\n\t\n\tpublic static void init() {\n\t\t\n\t\tif (RealFilingCabinet.botaniaLoaded && ConfigRFC.botaniaIntegration)\n\t\t\tBotaniaRFC.initItem();\n\t\t\n\t\temptyFolder = new ItemEmptyFolder();\n\t\tfolder = new ItemFolder();\n\t\tmagnifyingGlass = new ItemMagnifyingGlass();\n\t\twhiteoutTape = new ItemWhiteoutTape();\n\t\tupgrades = new ItemUpgrades();\n\t\tfilter = new ItemFilter();\n\t\tkeys = new ItemKeys();\n\t\tdebugger = new ItemDebugger();\n\t\tmysteryFolder = new ItemMysteryFolder();\n\t\tsuitcase = new ItemSuitcase();\n\t\temptyDyedFolder = new ItemEmptyDyedFolder();\n\t\tdyedFolder = new ItemDyedFolder();\n//\t\tautoFolder = new ItemAutoFolder();\n\t\t\n\t\tif (RealFilingCabinet.tcLoaded && ConfigRFC.tcIntegration)\n\t\t\taspectFolder = new ItemAspectFolder();\n\t}\n}",
"public class ItemFolder extends Item implements IFolder {\n\t\n\tpublic static int extractSize = 0; // TODO: Figure out how to move this to CapabilityFolder\n\t\n\tpublic enum FolderType {\n\t\tNORMAL,\n\t\tENDER,\n\t\tDURA,\n\t\tMOB,\n\t\tFLUID,\n\t\tNBT;\n\t}\n\n\tpublic ItemFolder() {\n\t\t\n\t\tsetRegistryName(\"folder\");\n\t\tsetTranslationKey(RealFilingCabinet.MOD_ID + \".folder\");\n\t\tsetHasSubtypes(true);\n\t\tsetMaxStackSize(1);\n\t}\n\t\n\t@Override\n\tpublic NBTTagCompound getNBTShareTag(ItemStack stack) {\n\t\t\n\t\tif(!stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn super.getNBTShareTag(stack);\n\t\t\n\t\tNBTTagCompound tag = stack.hasTagCompound() ? stack.getTagCompound().copy() : new NBTTagCompound();\n\t\ttag.setTag(\"folderCap\", stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).serializeNBT());\n\t\tLogRFC.debug(\"Sharing tag: \" + tag.toString());\n\t\treturn tag;\n\t}\n\t\n\t@Override\n\tpublic String getTranslationKey(ItemStack stack) {\n\t\t\n\t\treturn getTranslationKey() + \"_\" + FolderType.values()[stack.getItemDamage()].toString().toLowerCase();\n\t}\n\t\n\t@Override\n\tpublic void addInformation(ItemStack stack, World player, List<String> list, ITooltipFlag whatisthis) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null)) // Direction doesn't really matter here.\n\t\t\tstack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).addTooltips(player, list, whatisthis);\n\t}\n\t\n\tpublic ItemStack getContainerItem(ItemStack stack) {\n\t\t\n\t\tif(!stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn ItemStack.EMPTY;\n\t\t\n\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\tlong count = cap.getCount();\n\t\tlong extract = 0;\n\t\tif (count > 0 && cap.isItemStack())\n\t\t\textract = Math.min(cap.getItemStack().getMaxStackSize(), count);\n\t\t\n\t\tif (NBTUtils.getBoolean(stack, StringLibs.RFC_TAPED, false))\n\t\t\treturn ItemStack.EMPTY;\n\t\t\n\t\tItemStack copy = stack.copy();\n\t\tif (stack.getItemDamage() == FolderType.DURA.ordinal() && count == 0) // TODO: This works with 0 items? Might want to test this later\n\t\t\tsetRemSize(copy, 0);\n\n\t\tremove(copy, extract);\n\t\textractSize = (int)extract;\n\t\t\n\t\treturn copy;\n\t}\n\t\n\tpublic boolean hasContainerItem(ItemStack stack) {\n\t\t\n\t\treturn !getContainerItem(stack).isEmpty();\n\t}\n\t\n\tpublic static String getFolderDisplayName(ItemStack stack) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getDisplayName();\n\t\t\n\t\treturn \"\";\n\t}\n\t\n\tpublic static int getFileMeta(ItemStack stack) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null)) {\n\t\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\t\tif(cap.isFluidStack()) {\n\t\t\t\treturn cap.getItemStack().getItemDamage();\n\t\t\t} else if(cap.isBlock()) {\n\t\t\t\treturn cap.getBlock().getBlock().getMetaFromState(cap.getBlock());\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\t\n\tpublic static void setFileMeta(ItemStack stack, int meta) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null)) {\n\t\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\t\tif(cap.isFluidStack()) {\n\t\t\t\tcap.getItemStack().setItemDamage(meta);\n\t\t\t} else if(cap.isBlock()) {\n\t\t\t\tcap.setContents(cap.getBlock().getBlock().getMetaFromState(cap.getBlock()));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void setFileSize(ItemStack stack, long count) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\tstack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).setCount(count);\n\t}\n\t\n\tpublic static long getFileSize(ItemStack stack) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getCount();\n\t\t\n\t\treturn 0;\n\t}\n\t\n\tpublic static void remove(ItemStack stack, long count) {\n\t\t\n\t\tlong current = getFileSize(stack);\n\t\tsetFileSize(stack, Math.max(current - count, 0));\n\t}\n\t\n\t// trial new way of adding to contents of folder, while also returning the remainder in cases of reaching the storage limit\n\tpublic static ItemStack insert(ItemStack folder, ItemStack items, boolean simulate) {\n\t\t\n\t\tif (folder.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn folder.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).insertItems(items, simulate);\n\t\t\n\t\treturn items;\n\t}\n\t\n\t/*\n\t * Maybe find a better way of adding things?\n\t */\n\t@Deprecated\n\tpublic static void add(ItemStack stack, long count) {\n\t\t\n\t\tlong current = getFileSize(stack);\n\t\tsetFileSize(stack, current + count);\n\t}\n\t\n\tpublic static void setRemSize(ItemStack stack, int count) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\tstack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).setRemaining(count);\n\t}\n\t\n\tpublic static int getRemSize(ItemStack stack) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getRemaining();\n\t\t\n\t\treturn 0;\n\t}\n\t\n\tpublic static void addRem(ItemStack stack, int count) {\n\t\t\n\t\tint current = getRemSize(stack);\n\t\tsetRemSize(stack, current + count);\n\t}\n\t\n\tpublic static void remRem(ItemStack stack, int count) {\n\t\t\n\t\tint current = getRemSize(stack);\n\t\tsetRemSize(stack, Math.max(current - count, 0));\n\t}\n\t\n\tpublic static NBTTagCompound getItemTag(ItemStack stack) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null)) {\n\t\t\t\n\t\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\t\tif(cap.isItemStack())\n\t\t\t\treturn cap.getItemStack().getTagCompound();\n\t\t}\n\t\t\n\t\treturn new NBTTagCompound();\n\t}\n\t\n\tpublic static void setItemTag(ItemStack stack, NBTTagCompound tag) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null)) {\n\t\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\t\t\n\t\t\tif(cap.isItemStack())\n\t\t\t\tcap.getItemStack().setTagCompound(tag);\n\t\t}\n\t}\n\n\tpublic static Object getObject(ItemStack folder) {\n\n\t\tif(folder.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn folder.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getContents();\n\t\t\n\t\treturn null;\n\t}\n\n\tpublic static boolean setObject(ItemStack folder, Object object) {\n\t\t\n\t\tif(folder.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null) && folder.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getContents() == null)\n\t\t\treturn folder.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).setContents(object);\n\t\t\n\t\treturn false;\n\t}\n\t\n//\t@Override\n//\tpublic boolean itemInteractionForEntity(ItemStack stack, EntityPlayer player, EntityLivingBase target, EnumHand hand) {\n//\t\t\n//\t\tif (target.isChild() && !(target instanceof EntityZombie))\n//\t\t\treturn false;\n//\t\t\n//\t\tif (target instanceof EntityCabinet)\n//\t\t\treturn false;\n//\t\t\n//\t\tif (target instanceof IEntityOwnable && ((IEntityOwnable)target).getOwner() != null)\n//\t\t\treturn false;\n//\t\t\n//\t\tString entityblacklist = target.getClass().getSimpleName();\n//\t\tfor (String toBlacklist : ConfigRFC.mobFolderBlacklist) {\n//\t\t\tif (toBlacklist.contains(entityblacklist))\n//\t\t\t\treturn false;\n//\t\t}\n//\t\tItemStack folder = player.getHeldItemMainhand();\n//\t\tif (!folder.isEmpty() && folder.getItem() == this && folder.getItemDamage() == FolderType.MOB.ordinal()) {\n//\t\t\tif (!ConfigRFC.mobUpgrade) return false;\n//\t\t\t\n//\t\t\tif (getObject(folder) != null) {\n//\t\t\t\tResourceLocation res = EntityList.getKey(target);\n//\t\t\t\tif (getObject(folder).equals(res.toString()))\n//\t\t\t\t{\n//\t\t\t\t\tadd(folder, 1);\n//\t\t\t\t\tMobUtils.dropMobEquips(player.world, target);\n//\t\t\t\t\ttarget.setDead();\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\treturn true;\n//\t\t}\n//\t\treturn false;\n//\t}\n\t\n\t@Override\n\tpublic EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {\n\t\t\n\t\tItemStack stack = player.getHeldItem(hand);\n\t\tif (getObject(stack) != null) {\n\t\t\tif (stack.getItemDamage() < 2) {\n\t\t\t\tif (((ItemStack)getObject(stack)).getItem() instanceof ItemBlock) {\t\n\t\t\t\t\tlong count = ItemFolder.getFileSize(stack);\n\t\t\t\t\tif (stack.getItemDamage() == FolderType.ENDER.ordinal() && !EnderUtils.preValidateEnderFolder(stack))\n\t\t\t\t\t\treturn EnumActionResult.FAIL;\n\t\t\t\t\t\n\t\t\t\t\tif (count > 0) {\n\t\t\t\t\t\tItemStack stackToPlace = new ItemStack(((ItemStack)getObject(stack)).getItem(), 1, ((ItemStack)getObject(stack)).getItemDamage());\n\t\t\t\t\t\tItemStack savedfolder = player.getHeldItem(hand);\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.setHeldItem(hand, stackToPlace);\n\t\t\t\t\t\tEnumActionResult ear = stackToPlace.onItemUse(player, world, pos, hand, side, hitX, hitY, hitZ);\n\t\t\t\t\t\tplayer.setHeldItem(hand, savedfolder);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (ear == EnumActionResult.SUCCESS) {\n\t\t\t\t\t\t\tif (!player.capabilities.isCreativeMode) {\n\t\t\t\t\t\t\t\tif (stack.getItemDamage() == FolderType.ENDER.ordinal() && !world.isRemote) {\n\t\t\t\t\t\t\t\t\tEnderUtils.syncToTile(EnderUtils.getTileLoc(stack), NBTUtils.getInt(stack, StringLibs.RFC_DIM, 0), NBTUtils.getInt(stack, StringLibs.RFC_SLOTINDEX, 0), 1, true);\n\t\t\t\t\t\t\t\t\tif (player instanceof FakePlayer)\n\t\t\t\t\t\t\t\t\t\tEnderUtils.syncToFolder(EnderUtils.getTileLoc(stack), stack, NBTUtils.getInt(stack, StringLibs.RFC_SLOTINDEX, 0));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tremove(stack, 1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn EnumActionResult.SUCCESS;\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\tif (stack.getItemDamage() == 3) {\n\t\t\t\tif (MobUtils.spawnEntityFromFolder(world, player, stack, pos, side))\n\t\t\t\t\treturn EnumActionResult.SUCCESS;\n\t\t\t}\n\t\t\tif (stack.getItemDamage() == 4) {\n\t\t\t\tif (!(getObject(stack) instanceof FluidStack))\n\t\t\t\t\treturn EnumActionResult.PASS;\n\t\t\t\t\n\t\t\t\tif (FluidUtils.doPlace(world, player, stack, pos, side))\n\t\t\t\t\treturn EnumActionResult.SUCCESS;\n\t\t\t}\n\t\t}\n\t\treturn EnumActionResult.PASS;\n\t}\n\t\n\t@Override\n public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {\n \n\t\tItemStack stack = player.getHeldItem(hand);\n\t\tif (!stack.isEmpty() && stack.getItem() != this)\n\t\t\treturn ActionResult.newResult(EnumActionResult.PASS, stack);\n\n\t\tif (stack.getItemDamage() == FolderType.DURA.ordinal()) {\n\t\t\tNBTTagCompound tag = stack.getTagCompound();\n\t\t\ttag.setBoolean(StringLibs.RFC_IGNORENBT, !tag.getBoolean(StringLibs.RFC_IGNORENBT));\n\t\t\treturn ActionResult.newResult(EnumActionResult.SUCCESS, stack);\n\t\t}\n\t\tif (!stack.isEmpty() && stack.getItemDamage() != FolderType.FLUID.ordinal())\n\t\t\treturn ActionResult.newResult(EnumActionResult.PASS, stack);\n\t\t\n\t\tRayTraceResult rtr = rayTrace(world, player, true);\n\t\tif (rtr == null)\n\t\t\treturn ActionResult.newResult(EnumActionResult.PASS, stack);\n\t\t\n\t\tif (!MobUtils.canPlayerChangeStuffHere(world, player, stack, rtr.getBlockPos(), rtr.sideHit))\n\t\t\treturn ActionResult.newResult(EnumActionResult.PASS, stack);\n\t\t\n\t\telse {\n\t\t\tif (rtr.typeOfHit == RayTraceResult.Type.BLOCK) {\n\t\t\t\tBlockPos pos = rtr.getBlockPos();\n\t\t\t\tif (FluidUtils.doDrain(world, player, stack, pos, rtr.sideHit))\n\t\t\t\t\treturn ActionResult.newResult(EnumActionResult.SUCCESS, stack);\n\t\t\t}\n\t\t}\n\t\treturn ActionResult.newResult(EnumActionResult.PASS, stack);\n }\n\t\n\t@Override\n public boolean onEntitySwing(EntityLivingBase entityLiving, ItemStack stack) {\n \n\t\tif (entityLiving instanceof EntityPlayer && entityLiving.isSneaking()) {\n\t\t\tif (!stack.isEmpty() && stack.getItem() == this) {\n\t\t\t\tif (stack.getItemDamage() == 4) {\t\n\t\t\t\t\tNBTTagCompound tag = stack.getTagCompound();\n\t\t\t\t\ttag.setBoolean(StringLibs.RFC_PLACEMODE, !tag.getBoolean(StringLibs.RFC_PLACEMODE));\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n }\n\t\n\t@Override\n\tpublic void onUpdate(ItemStack stack, World world, Entity entity, int itemSlot, boolean isSelected) {\n\t\t\n\t\tif (!stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null) || !stack.hasTagCompound() || !stack.getTagCompound().hasKey(\"folderCap\", 10))\n\t\t\treturn;\n\t\t\n\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\tLogRFC.debug(\"Deserializing: \" + stack.getTagCompound().getCompoundTag(\"folderCap\").toString());\n\t\tcap.deserializeNBT(stack.getTagCompound().getCompoundTag(\"folderCap\"));\n\t\tstack.getTagCompound().removeTag(\"folderCap\");\n\t\t\n\t\tif (stack.getTagCompound().getSize() <= 0)\n\t\t\tstack.setTagCompound(null);\n\t}\n\t\n\t@Override\n\tpublic boolean shouldCauseReequipAnimation(ItemStack oldstack, ItemStack newstack, boolean slotchanged) {\n\t\t\n\t\treturn oldstack.getItem() != newstack.getItem() || (oldstack.getItem() == newstack.getItem() && oldstack.getItemDamage() != newstack.getItemDamage());\n\t}\n\t\n\t@Override\n\tpublic ItemStack isFolderEmpty(ItemStack stack) {\n\n\t\tswitch (stack.getItemDamage()) \n\t\t{\n\t\t\tcase 0: return new ItemStack(RFCItems.emptyFolder, 1, 0);\n\t\t\tcase 2: return new ItemStack(RFCItems.emptyFolder, 1, 1);\n\t\t\tcase 3: return new ItemStack(RFCItems.emptyFolder, 1, 2);\n\t\t\tcase 4: return new ItemStack(RFCItems.emptyFolder, 1, 3);\n\t\t\tcase 5: return new ItemStack(RFCItems.emptyFolder, 1, 4);\n\t\t}\n\t\treturn ItemStack.EMPTY;\n\t}\n}",
"public enum FolderType {\n\tNORMAL,\n\tENDER,\n\tDURA,\n\tMOB,\n\tFLUID,\n\tNBT;\n}",
"public class NBTUtils {\n\n\t/** Checks if an ItemStack has a Tag Compound **/\n\tpublic static boolean detectNBT(ItemStack stack) {\n\t\treturn stack.hasTagCompound();\n\t}\n\n\t/** Tries to initialize an NBT Tag Compound in an ItemStack,\n\t * this will not do anything if the stack already has a tag\n\t * compound **/\n\tpublic static void initNBT(ItemStack stack) {\n\t\tif(!detectNBT(stack))\n\t\t\tinjectNBT(stack, new NBTTagCompound());\n\t}\n\n\t/** Injects an NBT Tag Compound to an ItemStack, no checks\n\t * are made previously **/\n\tpublic static void injectNBT(ItemStack stack, NBTTagCompound nbt) {\n\t\tstack.setTagCompound(nbt);\n\t}\n\n\t/** Gets the NBTTagCompound in an ItemStack. Tries to init it\n\t * previously in case there isn't one present **/\n\tpublic static NBTTagCompound getNBT(ItemStack stack) {\n\t\tinitNBT(stack);\n\t\treturn stack.getTagCompound();\n\t}\n\n\t// SETTERS ///////////////////////////////////////////////////////////////////\n\n\tpublic static void setBoolean(ItemStack stack, String tag, boolean b) {\n\t\tgetNBT(stack).setBoolean(tag, b);\n\t}\n\n\tpublic static void setByte(ItemStack stack, String tag, byte b) {\n\t\tgetNBT(stack).setByte(tag, b);\n\t}\n\t\n\tpublic static void setByteArray(ItemStack stack, String tag, byte[] b) {\n\t\t\n\t\tgetNBT(stack).setByteArray(tag, b);\n\t}\n\n\tpublic static void setShort(ItemStack stack, String tag, short s) {\n\t\tgetNBT(stack).setShort(tag, s);\n\t}\n\n\tpublic static void setInt(ItemStack stack, String tag, int i) {\n\t\tgetNBT(stack).setInteger(tag, i);\n\t}\n\n\tpublic static void setLong(ItemStack stack, String tag, long l) {\n\t\tgetNBT(stack).setLong(tag, l);\n\t}\n\n\tpublic static void setFloat(ItemStack stack, String tag, float f) {\n\t\tgetNBT(stack).setFloat(tag, f);\n\t}\n\n\tpublic static void setDouble(ItemStack stack, String tag, double d) {\n\t\tgetNBT(stack).setDouble(tag, d);\n\t}\n\n\tpublic static void setCompound(ItemStack stack, String tag, NBTTagCompound cmp) {\n\t\tif(!tag.equalsIgnoreCase(\"ench\")) // not override the enchantments\n\t\t\tgetNBT(stack).setTag(tag, cmp);\n\t}\n\n\tpublic static void setString(ItemStack stack, String tag, String s) {\n\t\tgetNBT(stack).setString(tag, s);\n\t}\n\n\tpublic static void setList(ItemStack stack, String tag, NBTTagList list) {\n\t\tgetNBT(stack).setTag(tag, list);\n\t}\n\t\n\tpublic static void setIntArray(ItemStack stack, String key, int[] val) {\n\t\t\n\t\tgetCompound(stack, key, true).setIntArray(key, val);\n\t}\n\n\t// GETTERS ///////////////////////////////////////////////////////////////////\n\t\n\tpublic static int[] getIntArray(ItemStack stack, String key) {\n\t\t\n\t\treturn detectNBT(stack) ? getCompound(stack, key, true).getIntArray(key) : new int[0];\n\t}\n\n\tpublic static boolean verifyExistance(ItemStack stack, String tag) {\n\t\treturn stack != null && getNBT(stack).hasKey(tag);\n\t}\n\n\tpublic static boolean getBoolean(ItemStack stack, String tag, boolean defaultExpected) {\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getBoolean(tag) : defaultExpected;\n\t}\n\n\tpublic static byte getByte(ItemStack stack, String tag, byte defaultExpected) {\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getByte(tag) : defaultExpected;\n\t}\n\t\n\tpublic static byte[] getByteArray(ItemStack stack, String tag) {\n\t\t\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getByteArray(tag) : null;\n\t}\n\n\tpublic static short getShort(ItemStack stack, String tag, short defaultExpected) {\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getShort(tag) : defaultExpected;\n\t}\n\n\tpublic static int getInt(ItemStack stack, String tag, int defaultExpected) {\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getInteger(tag) : defaultExpected;\n\t}\n\n\tpublic static long getLong(ItemStack stack, String tag, long defaultExpected) {\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getLong(tag) : defaultExpected;\n\t}\n\n\tpublic static float getFloat(ItemStack stack, String tag, float defaultExpected) {\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getFloat(tag) : defaultExpected;\n\t}\n\n\tpublic static double getDouble(ItemStack stack, String tag, double defaultExpected) {\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getDouble(tag) : defaultExpected;\n\t}\n\n\t/** If nullifyOnFail is true it'll return null if it doesn't find any\n\t * compounds, otherwise it'll return a new one. **/\n\tpublic static NBTTagCompound getCompound(ItemStack stack, String tag, boolean nullifyOnFail) {\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getCompoundTag(tag) : nullifyOnFail ? null : new NBTTagCompound();\n\t}\n\n\tpublic static String getString(ItemStack stack, String tag, String defaultExpected) {\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getString(tag) : defaultExpected;\n\t}\n\n\tpublic static NBTTagList getList(ItemStack stack, String tag, int objtype, boolean nullifyOnFail) {\n\t\treturn verifyExistance(stack, tag) ? getNBT(stack).getTagList(tag, objtype) : nullifyOnFail ? null : new NBTTagList();\n\t}\n}"
] | import com.bafomdad.realfilingcabinet.NewConfigRFC.ConfigRFC;
import com.bafomdad.realfilingcabinet.RealFilingCabinet;
import com.bafomdad.realfilingcabinet.helpers.StringLibs;
import com.bafomdad.realfilingcabinet.helpers.TextHelper;
import com.bafomdad.realfilingcabinet.init.RFCItems;
import com.bafomdad.realfilingcabinet.items.ItemFolder;
import com.bafomdad.realfilingcabinet.items.ItemFolder.FolderType;
import com.bafomdad.realfilingcabinet.utils.NBTUtils;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.*;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import org.lwjgl.input.Keyboard;
import java.util.List; | package com.bafomdad.realfilingcabinet.items.capabilities;
// Funwayguy: Your new capability based class for dealing with folder stuff. Unique to each item rootStack so feel free to add/remove stuff.
public class CapabilityFolder implements INBTSerializable<NBTTagCompound>
{
// The ItemStack instance you're working within (REFERENCE PURPOSES ONLY!)
private final ItemStack rootStack;
private String displayName = "";
private Object contents;
private long count = 0;
private int remSize = 0;
public CapabilityFolder(ItemStack rootStack)
{
this.rootStack = rootStack;
}
public void addTooltips(World world, List<String> list, ITooltipFlag tooltipFlag)
{
if (rootStack.getItem() == RFCItems.dyedFolder) {
ItemStack item = getItemStack();
list.add((Keyboard.isKeyDown(42)) || (Keyboard.isKeyDown(54)) ? count + " " + item.getDisplayName() : TextHelper.format(count) + " " + item.getDisplayName());
return;
} | if(rootStack.getItemDamage() == ItemFolder.FolderType.FLUID.ordinal() && isFluidStack()) | 6 |
HumBuch/HumBuch | src/main/java/de/dhbw/humbuch/viewmodel/LoginViewModel.java | [
"public class LoginEvent {\n\tprivate final String message;\n\n\tpublic LoginEvent(String message) {\n\t\tthis.message = message;\n\t}\n\t\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n}",
"public interface DAO<EntityType extends Entity> {\n\n\t/**\n\t * Should an event be fired?\n\t */\n\tpublic enum FireUpdateEvent { YES, NO }\n\n\t/**\n\t * Persist the indicated entity to database, don't fire an update event\n\t * \n\t * @param entity\n\t * @return the primary key\n\t */\n\tEntityType insert(EntityType entity);\n\n\t/**\n\t * Persist the indicated entity to database, fire an update event when \n\t * {@link FireUpdateEvent.YES} is passed\n\t * \n\t * @param entity\n\t * @param fireUpdateEvent\n\t * @return the primary key\n\t */\n\tEntityType insert(EntityType entity, FireUpdateEvent fireUpdateEvent);\n\t\n\t/**\n\t * Persist the indicated entity {@link Collection} to database, don't fire an update event\n\t * \n\t * @param entity\n\t * @return the primary key\n\t */\n\tCollection<EntityType> insert(Collection<EntityType> entities);\n\t\n\t/**\n\t * Persist the indicated entity {@link Collection} to database, fire an update event when \n\t * {@link FireUpdateEvent.YES} is passed\n\t * \n\t * @param entity\n\t * @param fireUpdateEvent\n\t * @return the primary key\n\t */\n\tCollection<EntityType> insert(Collection<EntityType> entities, FireUpdateEvent fireUpdateEvent);\n\n\t/**\n\t * Update indicated entity to database, don't fire an update event\n\t * \n\t * @param entity\n\t */\n\tvoid update(EntityType entity);\n\n\t/**\n\t * Update indicated entity to database, fire an update event when \n\t * {@link FireUpdateEvent.YES} is passed\n\t * \n\t * @param entity\n\t * @param fireUpdateEvent\n\t */\n\tvoid update(EntityType entity, FireUpdateEvent fireUpdateEvent);\n\n\t/**\n\t * Update indicated entity {@link Collection} to database, don't fire an update event\n\t * \n\t * @param entity\n\t */\n\tvoid update(Collection<EntityType> entities);\n\t\n\t/**\n\t * Update indicated entity {@link Collection} to database, fire an update event when \n\t * {@link FireUpdateEvent.YES} is passed\n\t * \n\t * @param entity\n\t * @param fireUpdateEvent\n\t */\n\tvoid update(Collection<EntityType> entities, FireUpdateEvent fireUpdateEvent);\n\t\n\t/**\n\t * Delete indicated entity from database, don't fire an update event\n\t * \n\t * @param entity\n\t */\n\tvoid delete(EntityType entity);\n\n\t/**\n\t * Delete indicated entity from database, fire an update event when \n\t * {@link FireUpdateEvent.YES} is passed\n\t * \n\t * @param entity\n\t * @param fireUpdateEvent\n\t */\n\tvoid delete(EntityType entity, FireUpdateEvent fireUpdateEvent);\n\n\t/**\n\t * Delete indicated entity {@link Collection} from database, don't fire an update event\n\t * \n\t * @param entity\n\t */\n\tvoid delete(Collection<EntityType> entities);\n\t\n\t/**\n\t * Delete indicated entity {@link Collection} from database, fire an update event when \n\t * {@link FireUpdateEvent.YES} is passed\n\t * \n\t * @param entity\n\t * @param fireUpdateEvent\n\t */\n\tvoid delete(Collection<EntityType> entities, FireUpdateEvent fireUpdateEvent);\n\t\n\t/**\n\t * Return the entity class\n\t * \n\t * @return entity\n\t */\n\tClass<EntityType> getEntityClass();\n\n\t/**\n\t * Get the entity manager\n\t * \n\t * @return entity\n\t */\n\tEntityManager getEntityManager();\n\n\t/**\n\t * Retrieve an object using indicated ID\n\t * \n\t * @param id\n\t * @return entity\n\t */\n\tEntityType find(final Object id);\n\n\t/**\n\t * Retrieve all entities of the type indicated by the {@link DAO}\n\t * \n\t * @return {@link Collection} of entities\n\t */\n\tList<EntityType> findAll();\n\n\t/**\n\t * Retrieve all entities of the type indicated by the {@link DAO} with the\n\t * given {@link Criteria}\n\t * \n\t * @param criteriaArray\n\t * - {@link Criterion}s, separated by commas\n\t * @return {@link Collection} of entities\n\t */\n\tList<EntityType> findAllWithCriteria(Criterion... criteriaArray);\n\n\t/**\n\t * Retrieve all entities of the type indicated by the {@link DAO} with the\n\t * given {@link Criteria} in the given {@link Order}\n\t * \n\t * @param order\n\t * \t\t\t - {@link Order}\n\t * @param criteriaArray\n\t * - {@link Criterion}s, separated by commas\n\t * @return {@link Collection} of entities\n\t */\n\tList<EntityType> findAllWithCriteria(Order order, Criterion... criteriaArray);\n\t\n\t/**\n\t * Retrieve <b>a single entity</b> of the type indicated by the {@link DAO}\n\t * with the given {@link Criteria}. Only use this method when you are sure\n\t * there is only one entity retrieved from the database - this just frees\n\t * you from the hassle of getting the first and only element out of a\n\t * {@link Collection}\n\t * \n\t * @param criteriaArray\n\t * - {@link Criterion}s, separated by commas\n\t * @return <b>a single entity</b> if the amount of entities\n\t * found in the database is greater than 0, otherwise <i>null</i>\n\t */\n\tEntityType findSingleWithCriteria(Criterion... criteriaArray);\n\t\n\t/**\n\t * Retrieve <b>a single entity</b> of the type indicated by the {@link DAO}\n\t * with the given {@link Criteria} in the given {@link Order}. \n\t * Only use this method when you are sure\n\t * there is only one entity retrieved from the database - this just frees\n\t * you from the hassle of getting the first and only element out of a\n\t * {@link Collection}\n\t * \n\t * @param order\n\t * \t\t\t - {@link Order}\n\t * @param criteriaArray\n\t * - {@link Criterion}s, separated by commas\n\t * @return <b>a single entity</b> if the amount of entities\n\t * found in the database is greater than 0, otherwise <i>null</i>\n\t */\n\tEntityType findSingleWithCriteria(Order order, Criterion... criteriaArray);\n\t\n\t\n\t/**\n\t * Fire an update event\n\t */\n\tvoid fireUpdateEvent();\n}",
"@Entity\n@Table(name=\"user\")\npublic class User implements de.dhbw.humbuch.model.entity.Entity, Serializable {\n\tprivate static final long serialVersionUID = 12872765838454735L;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\tprivate int id;\n\tprivate String username;\n\tprivate String password;\n\tprivate String email;\n\t\n\t@ManyToMany\n\t@JoinTable(\n\t\t\tname=\"user_has_role\",\n\t\t\tjoinColumns={@JoinColumn(name=\"user_id\", referencedColumnName=\"id\")},\n\t\t inverseJoinColumns={@JoinColumn(name=\"role_id\", referencedColumnName=\"id\")}\n\t\t\t)\n\tprivate List<Role> roles = new ArrayList<Role>();\n\t\n\t/**\n\t * Required by Hibernate.<p>\n\t * Use the {@link Builder} instead.\n\t * \n\t * @see Builder\n\t */\n\t@Deprecated\n\tpublic User() {}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic 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 List<Role> getRoles() {\n\t\treturn roles;\n\t}\n\n\tpublic void setRoles(List<Role> roles) {\n\t\tthis.roles = roles;\n\t}\n\n\tpublic static class Builder {\n\t\tprivate final String username;\n\t\tprivate final String password;\n\t\t\n\t\tprivate String email;\n\t\t\n\t\tpublic Builder(String username, String password) {\n\t\t\tthis.username = username;\n\t\t\tthis.password = password;\n\t\t}\n\t\t\n\t\tpublic Builder email(String email) {\n\t\t\tthis.email = email;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\tpublic User build() {\n\t\t\treturn new User(this);\n\t\t}\n\t}\n\t\n\tprivate User(Builder builder) {\n\t\tthis.username = builder.username;\n\t\tthis.password = builder.password;\n\t\t\n\t\tthis.email = builder.email;\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;\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 (!(obj instanceof User))\n\t\t\treturn false;\n\t\tUser other = (User) obj;\n\t\tif (getId() != other.getId())\n\t\t\treturn false;\n\t\treturn true;\n\t}\n}",
"public class PasswordHash\n{\n public static final String PBKDF2_ALGORITHM = \"PBKDF2WithHmacSHA1\";\n\n // The following constants may be changed without breaking existing hashes.\n public static final int SALT_BYTE_SIZE = 20;\n public static final int HASH_BYTE_SIZE = 20;\n public static final int PBKDF2_ITERATIONS = 500;\n\n public static final int ITERATION_INDEX = 0;\n public static final int SALT_INDEX = 1;\n public static final int PBKDF2_INDEX = 2;\n\n /**\n * Returns a salted PBKDF2 hash of the password.\n *\n * @param password the password to hash\n * @return a salted PBKDF2 hash of the password\n */\n public static String createHash(String password)\n throws NoSuchAlgorithmException, InvalidKeySpecException\n {\n return createHash(password.toCharArray());\n }\n\n /**\n * Returns a salted PBKDF2 hash of the password.\n *\n * @param password the password to hash\n * @return a salted PBKDF2 hash of the password\n */\n public static String createHash(char[] password)\n throws NoSuchAlgorithmException, InvalidKeySpecException\n {\n // Generate a random salt\n SecureRandom random = new SecureRandom();\n byte[] salt = new byte[SALT_BYTE_SIZE];\n random.nextBytes(salt);\n\n // Hash the password\n byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);\n // format iterations:salt:hash\n return PBKDF2_ITERATIONS + \":\" + toHex(salt) + \":\" + toHex(hash);\n }\n\n /**\n * Validates a password using a hash.\n *\n * @param password the password to check\n * @param correctHash the hash of the valid password\n * @return true if the password is correct, false if not\n */\n public static boolean validatePassword(String password, String correctHash)\n throws NoSuchAlgorithmException, InvalidKeySpecException\n {\n return validatePassword(password.toCharArray(), correctHash);\n }\n\n /**\n * Validates a password using a hash.\n *\n * @param password the password to check\n * @param correctHash the hash of the valid password\n * @return true if the password is correct, false if not\n */\n public static boolean validatePassword(char[] password, String correctHash)\n throws NoSuchAlgorithmException, InvalidKeySpecException\n {\n // Decode the hash into its parameters\n String[] params = correctHash.split(\":\");\n int iterations = Integer.parseInt(params[ITERATION_INDEX]);\n byte[] salt = fromHex(params[SALT_INDEX]);\n byte[] hash = fromHex(params[PBKDF2_INDEX]);\n // Compute the hash of the provided password, using the same salt, \n // iteration count, and hash length\n byte[] testHash = pbkdf2(password, salt, iterations, hash.length);\n // Compare the hashes in constant time. The password is correct if\n // both hashes match.\n return slowEquals(hash, testHash);\n }\n\n /**\n * Compares two byte arrays in length-constant time. This comparison method\n * is used so that password hashes cannot be extracted from an on-line \n * system using a timing attack and then attacked off-line.\n * \n * @param a the first byte array\n * @param b the second byte array \n * @return true if both byte arrays are the same, false if not\n */\n private static boolean slowEquals(byte[] a, byte[] b)\n {\n int diff = a.length ^ b.length;\n for(int i = 0; i < a.length && i < b.length; i++)\n diff |= a[i] ^ b[i];\n return diff == 0;\n }\n\n /**\n * Computes the PBKDF2 hash of a password.\n *\n * @param password the password to hash.\n * @param salt the salt\n * @param iterations the iteration count (slowness factor)\n * @param bytes the length of the hash to compute in bytes\n * @return the PBDKF2 hash of the password\n */\n private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)\n throws NoSuchAlgorithmException, InvalidKeySpecException\n {\n PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);\n SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);\n return skf.generateSecret(spec).getEncoded();\n }\n\n /**\n * Converts a string of hexadecimal characters into a byte array.\n *\n * @param hex the hex string\n * @return the hex string decoded into a byte array\n */\n private static byte[] fromHex(String hex)\n {\n byte[] binary = new byte[hex.length() / 2];\n for(int i = 0; i < binary.length; i++)\n {\n binary[i] = (byte)Integer.parseInt(hex.substring(2*i, 2*i+2), 16);\n }\n return binary;\n }\n\n /**\n * Converts a byte array into a hexadecimal string.\n *\n * @param array the byte array to convert\n * @return a length*2 character string encoding the byte array\n */\n private static String toHex(byte[] array)\n {\n BigInteger bi = new BigInteger(1, array);\n String hex = bi.toString(16);\n int paddingLength = (array.length * 2) - hex.length();\n if(paddingLength > 0)\n return String.format(\"%0\" + paddingLength + \"d\", 0) + hex;\n else\n return hex;\n }\n \n}",
"@Theme(\"humbuch\")\n@SuppressWarnings(\"serial\")\n@Widgetset(\"com.vaadin.DefaultWidgetSet\")\n@Title(\"HumBuch Schulbuchverwaltung\")\npublic class MainUI extends ScopedUI {\n\n\tprivate final static Logger LOG = LoggerFactory.getLogger(MainUI.class);\n\n\tpublic static final String LOGIN_VIEW = \"login_view\";\n\tpublic static final String BOOK_MANAGEMENT_VIEW = \"book_management_view\";\n\tpublic static final String DUNNING_VIEW = \"dunning_view\";\n\tpublic static final String LENDING_VIEW = \"lending_view\";\n\tpublic static final String RETURN_VIEW = \"return_view\";\n\tpublic static final String STUDENT_INFORMATION_VIEW = \"student_information_view\";\n\tpublic static final String SETTINGS_VIEW = \"settings_view\";\n\tpublic static final String ERROR_VIEW = \"error_view\";\n\n\t@Inject\n\tprivate LoginView loginView;\n\n\t@Inject\n\tprivate DunningView dunningView;\n\n\t@Inject\n\tprivate LendingView lendingView;\n\n\t@Inject\n\tprivate ReturnView returnView;\n\n\t@Inject\n\tprivate TeachingMaterialView bookManagementView;\n\n\t@Inject\n\tprivate StudentInformationView studentInformationView;\n\n\t@Inject\n\tprivate SettingsView settingsView;\n\n\t@Inject\n\tprivate ErrorView errorView;\n\n\tprivate Header header = new Header();\n\tprivate VerticalLayout viewContainer = new VerticalLayout();;\n\tprivate GridLayout root;\n\tprivate ComponentContainerViewDisplay ccViewDisplay;\n\tprivate Sidebar sidebar;\n\tprivate Panel panelContent = new Panel();\n\tprivate View currentView;\n\n\tprivate LoginViewModel loginViewModel;\n\tpublic Navigator navigator;\n\n\t@BindState(IsLoggedIn.class)\n\tprivate BasicState<Boolean> isLoggedIn = new BasicState<Boolean>(Boolean.class);\n\n\t@Inject\n\tpublic MainUI(ViewModelComposer viewModelComposer, LoginViewModel loginViewModel, EventBus eventBus, MVVMConfig mvvmConfig) {\n\t\tthis.loginViewModel = loginViewModel;\n\t\teventBus.register(this);\n\t\tbindViewModel(viewModelComposer, loginViewModel);\n\t}\n\n\t@Override\n\tprotected void init(VaadinRequest request) {\n\n\t\tgetUI().getSession().setLocale(new Locale(\"de\", \"DE\"));\n\n\t\tccViewDisplay = new ComponentContainerViewDisplay(viewContainer);\n\t\tnavigator = new Navigator(UI.getCurrent(), ccViewDisplay);\n\n\t\tnavigator.setErrorView(errorView);\n\n\t\tnavigator.addView(\"\", lendingView);\n\t\tnavigator.addView(LOGIN_VIEW, loginView);\n\t\tnavigator.addView(BOOK_MANAGEMENT_VIEW, bookManagementView);\n\t\tnavigator.addView(DUNNING_VIEW, dunningView);\n\t\tnavigator.addView(LENDING_VIEW, lendingView);\n\t\tnavigator.addView(RETURN_VIEW, returnView);\n\t\tnavigator.addView(STUDENT_INFORMATION_VIEW, studentInformationView);\n\t\tnavigator.addView(SETTINGS_VIEW, settingsView);\n\n\t\t// Make the displayed view as big as possible\n\t\tviewContainer.setSizeFull();\n\n\t\tif (!isLoggedIn.get()) {\n\t\t\tbuildMainView(true);\n\t\t} else {\n\t\t\tbuildMainView(false);\n\t\t}\n\n\t\tattachListener();\n\n\t}\n\n\t/**\n\t * Build the MainView with header, navigation bar and footer\n\t * \n\t * @param cancel\n\t * Whether the MainView should be build or not\n\t */\n\tprivate void buildMainView(boolean cancel) {\n\t\tif (cancel) {\n\t\t\tsetContent(viewContainer);\n\t\t\treturn;\n\t\t}\n\n\t\troot = new GridLayout(2, 2);\n\n\t\theader.setWidth(\"100%\");\n\t\tsidebar = new Sidebar();\n\t\tsidebar.setWidth(\"150px\");\n\t\tsidebar.getLogoutButton().addClickListener(new ClickListener() {\n\t\t\t@Override\n\t\t\tpublic void buttonClick(ClickEvent event) {\n\t\t\t\tloginViewModel.doLogout(new Object());\n\t\t\t}\n\t\t});\n\n\t\tpanelContent.setContent(viewContainer);\n\t\tpanelContent.setSizeFull();\n\n\t\troot.setSizeFull();\n\t\troot.setRowExpandRatio(1, 1);\n\t\troot.setColumnExpandRatio(0, 0);\n\t\troot.setColumnExpandRatio(1, 1);\n\t\troot.addStyleName(\"main-view\");\n\n\t\troot.addComponent(panelContent, 1, 1);\n\t\troot.addComponent(header, 1, 0);\n\t\troot.addComponent(sidebar, 0, 0, 0, 1);\n\n\t\tsetContent(root);\n\t}\n\n\t/**\n\t * Attaches all listeners to the components.\n\t */\n\tprivate void attachListener() {\n\n\t\t/**\n\t\t * Checks if the user is logged in before the view changes\n\t\t */\n\t\tnavigator.addViewChangeListener(new ViewChangeListener() {\n\n\t\t\t@Override\n\t\t\tpublic boolean beforeViewChange(ViewChangeEvent event) {\n\t\t\t\tcurrentView = event.getNewView();\n\t\t\t\tboolean isLoginView = currentView instanceof LoginView;\n\n\t\t\t\tif (!isLoggedIn.get() && !isLoginView) {\n\t\t\t\t\t// Redirect to login view always if a user has not yet\n\t\t\t\t\t// logged in\n\t\t\t\t\tgetNavigator().navigateTo(MainUI.LOGIN_VIEW);\n\t\t\t\t\treturn false;\n\n\t\t\t\t} else if (isLoggedIn.get() && isLoginView) {\n\t\t\t\t\t// If someone tries to access to login view while logged in,\n\t\t\t\t\t// then cancel\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void afterViewChange(ViewChangeEvent event) {\n\t\t\t\tif (isLoggedIn.get()) {\n\t\t\t\t\tView newView = event.getNewView();\n\t\t\t\t\tif (newView instanceof ViewInformation) {\n\t\t\t\t\t\tViewInformation view = (ViewInformation) newView;\n\t\t\t\t\t\tpanelContent.setCaption(((ViewInformation) view)\n\t\t\t\t\t\t\t\t.getTitle());\n\t\t\t\t\t\tsidebar.changeMenuBarSelection(event.getViewName());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLOG.warn(\"New View does not implement ViewInformation interface.\"\n\t\t\t\t\t\t\t\t+ \" Could not set caption of panel correctly.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t});\n\n\t\t/**\n\t\t * Listens for a login or logout of a user an constructs the UI\n\t\t * accordingly\n\t\t */\n\t\tisLoggedIn.addStateChangeListener(new StateChangeListener() {\n\n\t\t\t@Override\n\t\t\tpublic void stateChange(Object arg0) {\n\t\t\t\tif (isLoggedIn.get()) {\n\t\t\t\t\tbuildMainView(false);\n\t\t\t\t} else {\n\t\t\t\t\tbuildMainView(true);\n\t\t\t\t\tgetNavigator().navigateTo(MainUI.LOGIN_VIEW);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t});\n\n\t\t/**\n\t\t * Adds the help HTML to the help button.\n\t\t */\n\t\theader.getHelpButton().addClickListener(new ClickListener() {\n\t\t\t@Override\n\t\t\tpublic void buttonClick(ClickEvent event) {\n\t\t\t\tString name = \"help/\" + currentView.getClass().getSimpleName() + \".html\";\n\t\t\t\tResourceLoader res = new ResourceLoader(name);\n\t\t\t\tStreamResource sr = new StreamResource(res, \"Hilfe\");\n\t\t\t\tnew PrintingComponent(sr, \"Hilfe\", MIMEType.HTML);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Handles {@link MessageEvent}s showing the message in a Vaadin\n\t * {@link Notification}\n\t * \n\t * @param messageEvent\n\t * {@link MessageEvent} containing the message to show\n\t */\n\t@Subscribe\n\tpublic void handleMessageEvent(MessageEvent messageEvent) {\n\t\tType notificationType;\n\t\tswitch (messageEvent.type) {\n\t\tcase ERROR:\n\t\t\tnotificationType = Type.ERROR_MESSAGE;\n\t\t\tbreak;\n\t\tcase WARNING:\n\t\t\tnotificationType = Type.WARNING_MESSAGE;\n\t\t\tbreak;\n\t\tcase TRAYINFO:\n\t\t\tnotificationType = Type.TRAY_NOTIFICATION;\n\t\t\tbreak;\n\t\tcase INFO:\n\t\tdefault:\n\t\t\tnotificationType = Type.HUMANIZED_MESSAGE;\n\t\t}\n\n\t\tNotification.show(messageEvent.caption, messageEvent.message, notificationType);\n\t}\n\n\t/**\n\t * Handles {@link ConfirmEvent}s showing a window with a cancel and a\n\t * confirm button.\n\t * \n\t * @param confirmEvent\n\t * {@link ConfirmEvent}s containing the confirmable information\n\t */\n\t@Subscribe\n\tpublic void handleConfirmEvent(final ConfirmEvent confirmEvent) {\n\t\tConfirmDialog.show(confirmEvent.caption, confirmEvent.message,\n\t\t\t\tconfirmEvent.confirmCaption, confirmEvent.cancelCaption,\n\t\t\t\tnew ConfirmDialog.Listener() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClose(ConfirmDialog dialog) {\n\t\t\t\t\t\tif (dialog.isConfirmed()) {\n\t\t\t\t\t\t\tconfirmEvent.confirm();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconfirmEvent.cancel();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t}\n\n\tprivate void bindViewModel(ViewModelComposer viewModelComposer,\n\t\t\tObject... viewModels) {\n\t\ttry {\n\t\t\tviewModelComposer.bind(this, viewModels);\n\t\t} catch (IllegalAccessException | NoSuchElementException\n\t\t\t\t| UnsupportedOperationException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}"
] | import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.List;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
import com.google.inject.Inject;
import de.davherrmann.mvvm.ActionHandler;
import de.davherrmann.mvvm.BasicState;
import de.davherrmann.mvvm.State;
import de.davherrmann.mvvm.annotations.HandlesAction;
import de.davherrmann.mvvm.annotations.ProvidesState;
import de.dhbw.humbuch.event.LoginEvent;
import de.dhbw.humbuch.model.DAO;
import de.dhbw.humbuch.model.entity.User;
import de.dhbw.humbuch.util.PasswordHash;
import de.dhbw.humbuch.view.MainUI; | package de.dhbw.humbuch.viewmodel;
/**
* @author David Vitt
* @author Johannes Idelhauser
*
*/
public class LoginViewModel {
private final static Logger LOG = LoggerFactory.getLogger(MainUI.class);
public interface IsLoggedIn extends State<Boolean> {}
public interface DoLogout extends ActionHandler {}
public interface DoLogin extends ActionHandler {}
private DAO<User> daoUser;
private EventBus eventBus;
private Properties properties;
@ProvidesState(IsLoggedIn.class)
public final BasicState<Boolean> isLoggedIn = new BasicState<Boolean>(Boolean.class);
/**
* Constructor
*
* @param daoUser
* @param properties
* @param eventBus
*/
@Inject
public LoginViewModel(DAO<User> daoUser, Properties properties, EventBus eventBus) {
this.properties = properties;
this.eventBus = eventBus;
this.daoUser = daoUser;
updateLoginStatus();
}
private void updateLoginStatus() {
isLoggedIn.set(properties.currentUser.get() != null);
}
/**
* Validates {@code username} and {@code password}. Fires an event if something is wrong.<br>
* Sets the logged in {@link User} in the corresponding {@link Properties} state
*
* @param username
* @param password
*/
@HandlesAction(DoLogin.class)
public void doLogin(String username, String password) {
properties.currentUser.set(null);
updateLoginStatus();
try {
if (username.equals("") || password.equals("")) { | eventBus.post(new LoginEvent("Bitte geben Sie einen Nutzernamen und Passwort an.")); | 0 |
dotcool/coolreader | src/com/dotcool/reader/task/CopyDBTask.java | [
"public class LNReaderApplication extends FOCApplication {\n\tprivate static final String TAG = LNReaderApplication.class.toString();\n\tprivate static NovelsDao novelsDao = null;\n\tprivate static DownloadListActivity downloadListActivity = null;\n\tprivate static UpdateService service = null;\n\tprivate static LNReaderApplication instance;\n\tprivate static Hashtable<String, AsyncTask<?, ?, ?>> runningTasks;\n\tprivate static ArrayList<DownloadModel> downloadList;\n\n\tprivate static Object lock = new Object();\n\n\t\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\n\t\tinitSingletons();\n\t\tinstance = this;\n\n\t\tdoBindService();\n\t\tLog.d(TAG, \"Application created.\");\n\t}\n\n\tpublic static LNReaderApplication getInstance() {\n\t\treturn instance;\n\t}\n\n\tprotected void initSingletons() {\n\t\tif (novelsDao == null)\n\t\t\tnovelsDao = NovelsDao.getInstance(this);\n\t\tif (downloadListActivity == null)\n\t\t\tdownloadListActivity = DownloadListActivity.getInstance();\n\t\tif (runningTasks == null)\n\t\t\trunningTasks = new Hashtable<String, AsyncTask<?, ?, ?>>();\n\t\tif (downloadList == null)\n\t\t\tdownloadList = new ArrayList<DownloadModel>();\n\t}\n\n\t/*\n\t * AsyncTask listing method\n\t */\n\tpublic static Hashtable<String, AsyncTask<?, ?, ?>> getTaskList() {\n\t\treturn runningTasks;\n\t}\n\n\tpublic AsyncTask<?, ?, ?> getTask(String key) {\n\t\treturn runningTasks.get(key);\n\t}\n\n\tpublic boolean addTask(String key, AsyncTask<?, ?, ?> task) {\n\t\tsynchronized (lock) {\n\t\t\tif (runningTasks.containsKey(key)) {\n\t\t\t\tAsyncTask<?, ?, ?> tempTask = runningTasks.get(key);\n\t\t\t\tif (tempTask != null && tempTask.getStatus() != Status.FINISHED)\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\trunningTasks.put(key, task);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic boolean removeTask(String key) {\n\t\tsynchronized (lock) {\n\t\t\tif (!runningTasks.containsKey(key))\n\t\t\t\treturn false;\n\t\t\trunningTasks.remove(key);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic boolean isOnline() {\n\t\tConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n\t\tNetworkInfo netInfo = cm.getActiveNetworkInfo();\n\t\tif (netInfo != null && netInfo.isConnectedOrConnecting()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/*\n\t * DownloadActivity method\n\t */\n\tpublic int addDownload(String id, String name) {\n\t\tsynchronized (lock) {\n\t\t\tdownloadList.add(new DownloadModel(id, name, 0));\n\t\t\tif (DownloadListActivity.getInstance() != null)\n\t\t\t\tDownloadListActivity.getInstance().updateContent();\n\t\t\treturn downloadList.size();\n\t\t}\n\t}\n\n\tpublic void removeDownload(String id) {\n\t\tsynchronized (lock) {\n\t\t\tfor (int i = 0; i < downloadList.size(); i++) {\n\t\t\t\tif (downloadList.get(i).getDownloadId() == id) {\n\t\t\t\t\tdownloadList.remove(i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (DownloadListActivity.getInstance() != null)\n\t\t\tDownloadListActivity.getInstance().updateContent();\n\t}\n\n\tpublic String getDownloadDescription(String id) {\n\t\tString name = \"\";\n\t\tfor (int i = 0; i < downloadList.size(); i++) {\n\t\t\tif (downloadList.get(i).getDownloadId() == id) {\n\t\t\t\tname = downloadList.get(i).getDownloadName();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn name;\n\t}\n\n\tpublic boolean checkIfDownloadExists(String name) {\n\t\tsynchronized (lock) {\n\t\t\tboolean exists = false;\n\t\t\tfor (int i = 0; i < downloadList.size(); i++) {\n\t\t\t\tif (downloadList.get(i).getDownloadName().equals(name)) {\n\t\t\t\t\texists = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn exists;\n\t\t}\n\t}\n\n\tpublic ArrayList<DownloadModel> getDownloadList() {\n\t\treturn downloadList;\n\t}\n\n\t\n\n\tpublic void updateDownload(String id, Integer progress, String message) {\n\n\t\t/*\n\t\t * Although this may seem an attempt at a fake incremental download bar\n\t\t * its actually a progressbar smoother.\n\t\t */\n\n\t\tint index = 0;\n\t\tInteger oldProgress;\n\t\tfinal Integer Increment;\n\t\tint smoothTime = 1000;\n\t\tint tickTime = 25;\n\t\tint tempIncrease = 0;\n\t\tfor (int i = 0; i < downloadList.size(); i++) {\n\t\t\tif (downloadList.get(i).getDownloadId() == id) {\n\t\t\t\tindex = i;\n\t\t\t}\n\t\t}\n\t\tfinal int idx = index;\n\n\t\t// Download status message\n\t\tif (downloadList.get(idx) != null) {\n\t\t\tdownloadList.get(idx).setDownloadMessage(message);\n\t\t}\n\t\tif (DownloadListActivity.getInstance() != null) {\n\t\t\tDownloadListActivity.getInstance().updateContent();\n\t\t}\n\n\t\toldProgress = downloadList.get(index).getDownloadProgress();\n\t\ttempIncrease = (progress - oldProgress);\n\t\tif (tempIncrease < smoothTime / tickTime) {\n\t\t\tsmoothTime = tickTime * tempIncrease;\n\t\t\ttempIncrease = 1;\n\t\t} else\n\t\t\ttempIncrease /= (smoothTime / tickTime);\n\n\t\tIncrement = tempIncrease;\n\t\tnew CountDownTimer(smoothTime, tickTime) {\n\t\t\t@Override\n\t\t\tpublic void onTick(long millisUntilFinished) {\n\t\t\t\tif (downloadList.size() > idx) {\n\t\t\t\t\tDownloadModel temp = downloadList.get(idx);\n\t\t\t\t\tif (temp != null) {\n\t\t\t\t\t\ttemp.setDownloadProgress(temp.getDownloadProgress() + Increment);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (DownloadListActivity.getInstance() != null) {\n\t\t\t\t\tDownloadListActivity.getInstance().updateContent();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onFinish() {\n\t\t\t}\n\t\t}.start();\n\t}\n\n\t/*\n\t * UpdateService method\n\t */\n\tprivate final ServiceConnection mConnection = new ServiceConnection() {\n\n\t\tpublic void onServiceConnected(ComponentName className, IBinder binder) {\n\t\t\tservice = ((UpdateService.MyBinder) binder).getService();\n\t\t\tLog.d(UpdateService.TAG, \"onServiceConnected\");\n\t\t\tToast.makeText(getApplicationContext(), \"Connected\", Toast.LENGTH_SHORT).show();\n\t\t}\n\n\t\tpublic void onServiceDisconnected(ComponentName className) {\n\t\t\tservice = null;\n\t\t\tLog.d(UpdateService.TAG, \"onServiceDisconnected\");\n\t\t}\n\t};\n\n\tprivate void doBindService() {\n\t\tbindService(new Intent(this, UpdateService.class), mConnection, Context.BIND_AUTO_CREATE);\n\t\tLog.d(UpdateService.TAG, \"doBindService\");\n\t}\n\n\tpublic void setUpdateServiceListener(ICallbackNotifier notifier) {\n\t\tif (service != null) {\n\t\t\tservice.notifier = notifier;\n\t\t}\n\t}\n\n\tpublic void runUpdateService(boolean force, ICallbackNotifier notifier) {\n\t\tif (service == null) {\n\t\t\tdoBindService();\n\t\t\tservice.force = force;\n\t\t\tservice.notifier = notifier;\n\t\t} else\n\t\t\tservice.force = force;\n\t\tservice.notifier = notifier;\n\t\tservice.onStartCommand(null, BIND_AUTO_CREATE, (int) (new Date().getTime() / 1000));\n\t}\n\n\t@Override\n\tpublic void onLowMemory() {\n\n\t\t/*\n\t\t * java.lang.IllegalArgumentException\n\t\t * in android.app.LoadedApk.forgetServiceDispatcher\n\t\t * \n\t\t * probable crash: service is not checked if it exists after onLowMemory.\n\t\t * Technically fixed. needs checking.\n\t\t */\n\t\tif (mConnection != null) {\n\t\t\tLog.w(TAG, \"Low Memory, Trying to unbind service...\");\n\t\t\ttry {\n\t\t\t\tunbindService(mConnection);\n\t\t\t\tLog.i(TAG, \"Unbind service done.\");\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLog.e(TAG, \"Failed to unbind.\", ex);\n\t\t\t}\n\t\t}\n\t\tsuper.onLowMemory();\n\t}\n\n\t/*\n\t * CSS caching method.\n\t * Also used for caching javascript.\n\t */\n\tprivate Hashtable<Integer, String> cssCache = null;\n\n\tpublic String ReadCss(int styleId) {\n\t\tif (cssCache == null)\n\t\t\tcssCache = new Hashtable<Integer, String>();\n\t\tif (!cssCache.containsKey(styleId)) {\n\t\t\tcssCache.put(styleId, UIHelper.readRawStringResources(getApplicationContext(), styleId));\n\t\t}\n\t\treturn cssCache.get(styleId);\n\t}\n\n\tpublic void resetFirstRun() {\n\t\tSharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();\n\t\tedit.remove(Constants.PREF_FIRST_RUN);\n\t\tedit.commit();\n\t}\n\n\tpublic void restartApplication() {\n\t\tIntent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());\n\t\ti.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n\t\tstartActivity(i);\n\t}\n}",
"public class CallbackEventData implements ICallbackEventData {\n\tprotected String message;\n\tprotected String source;\n\n\tpublic CallbackEventData() {};\n\n\tpublic CallbackEventData(String message) {\n\t\tthis.message = message;\n\t}\n\n\tpublic CallbackEventData(String message, String source) {\n\t\tthis.message = message;\n\t\tthis.source = source;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n\n\tpublic void setMessage(String message) {\n\t\tthis.message = message;\n\t}\n\n\tpublic String getSource() {\n\t\treturn source;\n\t}\n}",
"public interface ICallbackEventData {\n\n\tpublic abstract String getMessage();\n\tpublic abstract void setMessage(String message);\n}",
"public interface ICallbackNotifier {\n\n\t//public void onCallback(String message);\n\tpublic void onCallback(ICallbackEventData message);\n}",
"public class NovelsDao {\n\tprivate static final String TAG = NovelsDao.class.toString();\n\tprivate static DBHelper dbh;\n\tprivate static Context context;\n\n\tprivate static NovelsDao instance;\n\tprivate static Object lock = new Object();\n\n\tpublic static NovelsDao getInstance(Context applicationContext) {\n\t\tsynchronized (lock) {\n\t\t\tif (instance == null) {\n\t\t\t\tinstance = new NovelsDao(applicationContext);\n\t\t\t\tcontext = applicationContext;\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\tpublic static NovelsDao getInstance() {\n\t\tsynchronized (lock) {\n\t\t\tif (instance == null) {\n\t\t\t\ttry {\n\t\t\t\t\tinstance = new NovelsDao(LNReaderApplication.getInstance().getApplicationContext());\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tLog.e(TAG, \"Failed to get context for NovelsDao\", ex);\n\t\t\t\t\t// throw new BakaReaderException(\"NovelsDao is not Initialized!\", BakaReaderException.NULL_NOVELDAO,\n\t\t\t\t\t// ex);\n\t\t\t\t\tthrow new NullPointerException(\"NovelsDao is not Initialized!\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\tprivate NovelsDao(Context context) {\n\t\tif (dbh == null) {\n\t\t\tdbh = new DBHelper(context);\n\t\t}\n\t}\n\n\tpublic DBHelper getDBHelper() {\n\t\tif (dbh == null) {\n\t\t\tdbh = new DBHelper(context);\n\t\t}\n\t\treturn dbh;\n\t}\n\n\tpublic void deleteDB() {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\ttry {\n\t\t\t\tdbh.deletePagesDB(db);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic String copyDB(boolean makeBackup) throws IOException {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tString filePath;\n\t\t\ttry {\n\t\t\t\tfilePath = dbh.copyDB(db, context, makeBackup);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t\treturn filePath;\n\t\t}\n\t}\n\n\tpublic ArrayList<PageModel> getNovels(ICallbackNotifier notifier, boolean alphOrder,String api) throws Exception {\n\t\tArrayList<PageModel> list = null;\n\t\tPageModel page = null;\n\t\tSQLiteDatabase db = null;\n\n\t\t// check if main page exist\n\t\tsynchronized (dbh) {\n\t\t\ttry {\n\t\t\t\tdb = dbh.getReadableDatabase();\n\t\t\t\t\n\t\t\t\tif(api.equals(\"/api/leixin/cat/1\")){\n\t\t\t\t page = PageModelHelper.getHistoryPage(db);\n\t\t\t\t}else if(api.equals(\"/api/leixin/cat/3\")){\n page = PageModelHelper.getKehuanPage(db);\n }else if(api.equals(\"/api/leixin/cat/7\")){\n page = PageModelHelper.getXuanhuanPage(db);\n }else if(api.equals(\"/api/leixin/cat/10\")){\n page = PageModelHelper.getQitaPage(db);\n }else if(api.equals(\"/api/book/update/11\")){\n page = PageModelHelper.getUpdatePage(db);\n }else if(api.equals(\"/api/book/update/12\")){\n page = PageModelHelper.getMoodPage(db);\n }else {\n page = PageModelHelper.getMainPage(db); \n }\n\t\t\t\t\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\tif (page == null) {\n\t\t\tLog.d(TAG, \"No Main_Page data!\");\n\t\t\tlist = getNovelsFromInternet(notifier,api);\n\t\t} else {\n\t\t\t// get from db\n\t\t\tsynchronized (dbh) {\n\t\t\t\ttry {\n\t\t\t\t\tdb = dbh.getReadableDatabase();\n\t\t\t\t\tlist = dbh.getAllNovels(db, alphOrder);// dbh.selectAllByColumn(db,\n\t\t\t\t\t// DBHelper.COLUMN_TYPE,\n\t\t\t\t\t// PageModel.TYPE_NOVEL);\n\t\t\t\t} finally {\n\t\t\t\t\tdb.close();\n\t\t\t\t}\n\t\t\t}\n\t\t\tLog.d(TAG, \"Found: \" + list.size());\n\t\t}\n\n\t\treturn list;\n\t}\n\n\tpublic ArrayList<PageModel> getNovelsFromInternet(ICallbackNotifier notifier,String api) throws Exception {\n\t\tif (!LNReaderApplication.getInstance().isOnline())\n\t\t\tthrow new BakaReaderException(\"没有网络,请稍后...\", BakaReaderException.NO_NETWORK_CONNECTIFITY);\n\t\tif (notifier != null) {\n\t\t\tnotifier.onCallback(new CallbackEventData(\"正在加载列表请稍后...\"));\n\t\t}\n\t\t// get last updated main page revision from internet\n\n\t\tPageModel mainPage = new PageModel();\n\t\tif(api.equals(\"/api/leixin/cat/1\")){\n\t\t mainPage.setPage(\"Category:history\");\n\t\t mainPage.setTitle(LNReaderApplication.getInstance().getResources().getString(R.string.str_xuanhuan));\n }else if(api.equals(\"/api/leixin/cat/3\")){\n mainPage.setPage(\"Category:kehuan\");\n mainPage.setTitle(LNReaderApplication.getInstance().getResources().getString(R.string.str_xuanhuan));\n }else if(api.equals(\"/api/leixin/cat/7\")){\n mainPage.setPage(\"Category:xuanhuan\");\n mainPage.setTitle(LNReaderApplication.getInstance().getResources().getString(R.string.str_xuanhuan));\n }else if(api.equals(\"/api/leixin/cat/10\")){\n mainPage.setPage(\"Category:qita\");\n mainPage.setTitle(LNReaderApplication.getInstance().getResources().getString(R.string.str_xuanhuan));\n }else if(api.equals(\"/api/book/update/11\")){\n mainPage.setPage(\"Category:update\");\n mainPage.setTitle(LNReaderApplication.getInstance().getResources().getString(R.string.light_novels));\n }else if(api.equals(\"/api/book/mood/12\")){\n mainPage.setPage(\"Category:mood\");\n mainPage.setTitle(LNReaderApplication.getInstance().getResources().getString(R.string.originals));\n }\n\t\tmainPage.setLanguage(Constants.LANG_ENGLISH);\n\t\tmainPage = getPageModel(mainPage, notifier);\n\t\tmainPage.setType(PageModel.TYPE_OTHER);\n\t\tmainPage.setParent(\"\");\n\n\t\tArrayList<PageModel> list = null;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\ttry {\n\t\t\t\t// db.beginTransaction();\n\t\t\t\tmainPage = PageModelHelper.insertOrUpdatePageModel(db, mainPage, false);\n\t\t\t\tLog.d(TAG, \"Updated Main_Page\");\n\n\t\t\t\t// now get the novel list\n\t\t\t\tlist = new ArrayList<PageModel>();\n\n\t\t\t\tString url = UIHelper.getBaseUrl(LNReaderApplication.getInstance().getApplicationContext()) + api;\n\t\t\t\tLog.d(TAG, \"--\"+url);\n\t\t\t\tint retry = 0;\n\t\t\t\twhile (retry < getRetry()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tResponse response = Jsoup.connect(url).timeout(getTimeout(retry)).execute();\n\t\t\t\t\t\t//Document doc = response.parse();\n\t\t\t\t\t\tString result =response.body();\n\t\t\t\t\t\t//String result = AppUtil.getContent(url);\n\t\t\t\t\t\t\n\t\t\t\t\t\tLog.d(TAG, \"Found from internet: \"+ result + \" Novels\");\n\t\t\t\t\t\tlist = BakaTsukiParser.ParseNovelList(result);\n\t\t\t\t\t\tLog.d(TAG, \"Found from internet: \" + list.size() + \" Novels\");\n\n\t\t\t\t\t\t// saved to db and get saved value\n\t\t\t\t\t\tlist = PageModelHelper.insertAllNovel(db, list);\n\n\t\t\t\t\t\t// db.setTransactionSuccessful();\n\n\t\t\t\t\t\tif (notifier != null) {\n\t\t\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Found: \" + list.size() + \" novels.\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} catch (EOFException eof) {\n\t\t\t\t\t\t++retry;\n\t\t\t\t\t\tif (notifier != null) {\n\t\t\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Retrying: Main_Page (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage()));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (retry > getRetry())\n\t\t\t\t\t\t\tthrow eof;\n\t\t\t\t\t} catch (IOException eof) {\n\t\t\t\t\t\t++retry;\n\t\t\t\t\t\tString message = \"Retrying: Main_Page (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage();\n\t\t\t\t\t\tif (notifier != null) {\n\t\t\t\t\t\t\tnotifier.onCallback(new CallbackEventData(message));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tLog.d(TAG, message, eof);\n\t\t\t\t\t\tif (retry > getRetry())\n\t\t\t\t\t\t\tthrow eof;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\t// db.endTransaction();\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\treturn list;\n\t}\n\n\tpublic ArrayList<PageModel> getWatchedNovel() {\n\t\tArrayList<PageModel> watchedNovel = null;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\ttry {\n\t\t\t\t// watchedNovel = dbh.selectAllByColumn(db,\n\t\t\t\t// DBHelper.COLUMN_IS_WATCHED + \" = ? and (\"\n\t\t\t\t// + DBHelper.COLUMN_PARENT + \" = ? or \"\n\t\t\t\t// + DBHelper.COLUMN_PARENT + \" = ? )\"\n\t\t\t\t// , new String[] { \"1\", \"Main_Page\", \"Category:Teasers\" }\n\t\t\t\t// , DBHelper.COLUMN_TITLE );\n\t\t\t\twatchedNovel = dbh.getAllWatchedNovel(db, true);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\treturn watchedNovel;\n\t}\n\n\tpublic ArrayList<PageModel> getTeaser(ICallbackNotifier notifier, boolean alphOrder) throws Exception {\n\t\tSQLiteDatabase db = null;\n\t\tPageModel page = null;\n\t\tArrayList<PageModel> list = null;\n\t\t// check if main page exist\n\t\tsynchronized (dbh) {\n\t\t\ttry {\n\t\t\t\tdb = dbh.getReadableDatabase();\n\t\t\t\tpage = PageModelHelper.getTeaserPage(db);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\n\t\tif (page == null) {\n\t\t\treturn getTeaserFromInternet(notifier);\n\t\t} else {\n\t\t\t// get from db\n\t\t\tsynchronized (dbh) {\n\t\t\t\ttry {\n\t\t\t\t\tdb = dbh.getReadableDatabase();\n\t\t\t\t\tlist = dbh.getAllTeaser(db, alphOrder);\n\t\t\t\t} finally {\n\t\t\t\t\tdb.close();\n\t\t\t\t}\n\t\t\t}\n\t\t\tLog.d(TAG, \"Found: \" + list.size());\n\t\t}\n\n\t\treturn list;\n\t}\n\n\tpublic ArrayList<PageModel> getTeaserFromInternet(ICallbackNotifier notifier) throws Exception {\n\t\tif (!LNReaderApplication.getInstance().isOnline())\n\t\t\tthrow new BakaReaderException(\"No Network Connectifity\", BakaReaderException.NO_NETWORK_CONNECTIFITY);\n\t\tif (notifier != null) {\n\t\t\tnotifier.onCallback(new CallbackEventData(\"Downloading Teaser Novels list...\"));\n\t\t}\n\n\t\t// parse Category:Teasers information\n\t\tPageModel teaserPage = new PageModel();\n\t\tteaserPage.setPage(\"Category:Teasers\");\n\t\tteaserPage.setLanguage(Constants.LANG_ENGLISH);\n\t\tteaserPage.setTitle(\"Teasers\");\n\t\tteaserPage = getPageModel(teaserPage, notifier);\n\t\tteaserPage.setType(PageModel.TYPE_OTHER);\n\n\t\t// update page model\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tteaserPage = PageModelHelper.insertOrUpdatePageModel(db, teaserPage, true);\n\t\t\tLog.d(TAG, \"Updated Category:Teasers\");\n\t\t}\n\n\t\t// get teaser list\n\t\tArrayList<PageModel> list = null;\n\t\tString url = UIHelper.getBaseUrl(LNReaderApplication.getInstance().getApplicationContext()) + \"/project/index.php?title=Category:Teasers\";\n\t\tint retry = 0;\n\t\twhile (retry < getRetry()) {\n\t\t\ttry {\n\t\t\t\tResponse response = Jsoup.connect(url).timeout(getTimeout(retry)).execute();\n\t\t\t\tString doc = response.body();\n\n\t\t\t\tlist = BakaTsukiParser.ParseTeaserList(doc);\n\t\t\t\tLog.d(TAG, \"Found from internet: \" + list.size() + \" Teaser\");\n\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Found: \" + list.size() + \" teaser.\"));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} catch (EOFException eof) {\n\t\t\t\t++retry;\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Retrying: Category:Teasers (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage()));\n\t\t\t\t}\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t} catch (IOException eof) {\n\t\t\t\t++retry;\n\t\t\t\tString message = \"Retrying: Category:Teasers (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage();\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(message));\n\t\t\t\t}\n\t\t\t\tLog.d(TAG, message, eof);\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t}\n\t\t}\n\n\t\t// save teaser list\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tfor (PageModel pageModel : list) {\n\t\t\t\tpageModel = PageModelHelper.insertOrUpdatePageModel(db, pageModel, true);\n\t\t\t\tLog.d(TAG, \"Updated teaser: \" + pageModel.getPage());\n\t\t\t}\n\t\t}\n\n\t\treturn list;\n\t}\n\n\t// Originals, copied from teaser\n\tpublic ArrayList<PageModel> getOriginal(ICallbackNotifier notifier, boolean alphOrder) throws Exception {\n\t\tSQLiteDatabase db = null;\n\t\tPageModel page = null;\n\t\tArrayList<PageModel> list = null;\n\t\t// check if main page exist\n\t\tsynchronized (dbh) {\n\t\t\ttry {\n\t\t\t\tdb = dbh.getReadableDatabase();\n\t\t\t\tpage = PageModelHelper.getOriginalPage(db);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\n\t\tif (page == null) {\n\t\t\treturn getOriginalFromInternet(notifier);\n\t\t} else {\n\t\t\t// get from db\n\t\t\tsynchronized (dbh) {\n\t\t\t\ttry {\n\t\t\t\t\tdb = dbh.getReadableDatabase();\n\t\t\t\t\tlist = dbh.getAllOriginal(db, alphOrder);\n\t\t\t\t} finally {\n\t\t\t\t\tdb.close();\n\t\t\t\t}\n\t\t\t}\n\t\t\tLog.d(TAG, \"Found: \" + list.size());\n\t\t}\n\n\t\treturn list;\n\t}\n\n\tpublic ArrayList<PageModel> getOriginalFromInternet(ICallbackNotifier notifier) throws Exception {\n\t\tif (!LNReaderApplication.getInstance().isOnline())\n\t\t\tthrow new Exception(\"No Network Connectifity\");\n\t\tif (notifier != null) {\n\t\t\tnotifier.onCallback(new CallbackEventData(\"Downloading Original Novels list...\"));\n\t\t}\n\n\t\t// parse Category:Teasers information\n\t\tPageModel teaserPage = new PageModel();\n\t\tteaserPage.setPage(\"Category:Original\");\n\t\tteaserPage.setLanguage(Constants.LANG_ENGLISH);\n\t\tteaserPage.setTitle(\"Original Novels\");\n\t\tteaserPage = getPageModel(teaserPage, notifier);\n\t\tteaserPage.setType(PageModel.TYPE_OTHER);\n\n\t\t// update page model\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tteaserPage = PageModelHelper.insertOrUpdatePageModel(db, teaserPage, true);\n\t\t\tLog.d(TAG, \"Updated Category:Original\");\n\t\t}\n\n\t\t// get teaser list\n\t\tArrayList<PageModel> list = null;\n\t\tString url = UIHelper.getBaseUrl(LNReaderApplication.getInstance().getApplicationContext()) + \"/project/index.php?title=Category:Original\";\n\t\tint retry = 0;\n\t\twhile (retry < getRetry()) {\n\t\t\ttry {\n\t\t\t\tResponse response = Jsoup.connect(url).timeout(getTimeout(retry)).execute();\n\t\t\t\tString doc = response.body();\n\n\t\t\t\tlist = BakaTsukiParser.ParseOriginalList(doc);\n\t\t\t\tLog.d(TAG, \"Found from internet: \" + list.size() + \" Teaser\");\n\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Found: \" + list.size() + \" original.\"));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} catch (EOFException eof) {\n\t\t\t\t++retry;\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Retrying: Category:Original (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage()));\n\t\t\t\t}\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t} catch (IOException eof) {\n\t\t\t\t++retry;\n\t\t\t\tString message = \"Retrying: Category:Original (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage();\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(message));\n\t\t\t\t}\n\t\t\t\tLog.d(TAG, message, eof);\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t}\n\t\t}\n\n\t\t// save original list\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tfor (PageModel pageModel : list) {\n\t\t\t\tpageModel = PageModelHelper.insertOrUpdatePageModel(db, pageModel, true);\n\t\t\t\tLog.d(TAG, \"Updated original: \" + pageModel.getPage());\n\t\t\t}\n\t\t}\n\n\t\treturn list;\n\t}\n\n\t// Alternative Language, copied from Original\n\tpublic ArrayList<PageModel> getAlternative(ICallbackNotifier notifier, boolean alphOrder, String language) throws Exception {\n\t\tSQLiteDatabase db = null;\n\t\tPageModel page = null;\n\t\tArrayList<PageModel> list = null;\n\t\t// check if main page exist\n\t\tsynchronized (dbh) {\n\t\t\ttry {\n\t\t\t\tdb = dbh.getReadableDatabase();\n\t\t\t\tpage = PageModelHelper.getAlternativePage(db, language);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\n\t\tif (page == null) {\n\t\t\treturn getAlternativeFromInternet(notifier, language);\n\t\t} else {\n\t\t\t// get from db\n\t\t\tsynchronized (dbh) {\n\t\t\t\ttry {\n\t\t\t\t\tdb = dbh.getReadableDatabase();\n\t\t\t\t\tlist = dbh.getAllAlternative(db, alphOrder, language);\n\t\t\t\t} finally {\n\t\t\t\t\tdb.close();\n\t\t\t\t}\n\t\t\t}\n\t\t\tLog.d(TAG, \"Found: \" + list.size());\n\t\t}\n\n\t\treturn list;\n\t}\n\n\tpublic ArrayList<PageModel> getAlternativeFromInternet(ICallbackNotifier notifier, String language) throws Exception {\n\t\tif (!LNReaderApplication.getInstance().isOnline())\n\t\t\tthrow new BakaReaderException(\"No Network Connectifity\", BakaReaderException.NO_NETWORK_CONNECTIFITY);\n\t\tif (notifier != null) {\n\t\t\tnotifier.onCallback(new CallbackEventData(\"Downloading \" + language + \" Novels list...\"));\n\t\t}\n\n\t\t// parse information\n\t\tPageModel teaserPage = new PageModel();\n\n\t\tif (language != null) {\n\t\t\tteaserPage.setPage(AlternativeLanguageInfo.getAlternativeLanguageInfo().get(language).getCategoryInfo());\n\t\t\tteaserPage.setTitle(language + \" Novels\");\n\t\t\tteaserPage.setLanguage(language);\n\t\t}\n\n\t\tteaserPage = getPageModel(teaserPage, notifier);\n\t\tteaserPage.setType(PageModel.TYPE_NOVEL);\n\n\t\t// update page model\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tteaserPage = PageModelHelper.insertOrUpdatePageModel(db, teaserPage, true);\n\t\t\tLog.d(TAG, \"Updated \" + language);\n\t\t}\n\n\t\t// get alternative list\n\t\tArrayList<PageModel> list = null;\n\t\tString url = null;\n\t\tif (language != null)\n\t\t\turl = UIHelper.getBaseUrl(LNReaderApplication.getInstance().getApplicationContext()) + \"/project/index.php?title=\" + AlternativeLanguageInfo.getAlternativeLanguageInfo().get(language).getCategoryInfo();\n\t\tint retry = 0;\n\t\twhile (retry < getRetry()) {\n\t\t\ttry {\n\t\t\t\tResponse response = Jsoup.connect(url).timeout(getTimeout(retry)).execute();\n\t\t\t\tDocument doc = response.parse();\n\t\t\t\tlist = BakaTsukiParserAlternative.ParseAlternativeList(doc, language);\n\t\t\t\tLog.d(TAG, \"Found from internet: \" + list.size() + \" \" + language + \" Novel\");\n\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Found: \" + list.size() + \" \" + language + \" .\"));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} catch (EOFException eof) {\n\t\t\t\t++retry;\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Retrying: \" + language + \" (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage()));\n\t\t\t\t}\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t} catch (IOException eof) {\n\t\t\t\t++retry;\n\t\t\t\tString message = \"Retrying: \" + language + \" (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage();\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(message));\n\t\t\t\t}\n\t\t\t\tLog.d(TAG, message, eof);\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t}\n\t\t}\n\n\t\t// save teaser list\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tfor (PageModel pageModel : list) {\n\t\t\t\tpageModel = PageModelHelper.insertOrUpdatePageModel(db, pageModel, true);\n\t\t\t\tLog.d(TAG, \"Updated \" + language + \" novel: \" + pageModel.getPage());\n\t\t\t}\n\t\t}\n\n\t\treturn list;\n\t}\n\n\t/**\n\t * Get page model from db. If autoDownload = true, get the pageModel from\n\t * internet if not exists.\n\t * \n\t * @param page\n\t * @param notifier\n\t * @param autoDownload\n\t * @return\n\t * @throws Exception\n\t */\n\tpublic PageModel getPageModel(PageModel page, ICallbackNotifier notifier, boolean autoDownload) throws Exception {\n\t\tPageModel pageModel = null;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\ttry {\n\t\t\t\tpageModel = PageModelHelper.getPageModel(db, page.getPage());\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\tif (pageModel == null && autoDownload) {\n\t\t\tpageModel = getPageModelFromInternet(page, notifier);\n\t\t}\n\t\treturn pageModel;\n\t}\n\n\t/**\n\t * Get page model from db. Get the pageModel from internet if not exists.\n\t * \n\t * @param page\n\t * @param notifier\n\t * @return\n\t * @throws Exception\n\t */\n\tpublic PageModel getPageModel(PageModel page, ICallbackNotifier notifier) throws Exception {\n\t\treturn getPageModel(page, notifier, true);\n\t}\n\n\t/**\n\t * Return pageModel, null if not exist.\n\t * \n\t * @param page\n\t * @param notifier\n\t * @return\n\t * @throws Exception\n\t */\n\tpublic PageModel getExistingPageModel(PageModel page, ICallbackNotifier notifier) throws Exception {\n\t\tPageModel pageModel = null;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\ttry {\n\t\t\t\tpageModel = PageModelHelper.getPageModel(db, page.getPage());\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\n\t\treturn pageModel;\n\t}\n\n\tpublic PageModel getPageModelFromInternet(PageModel page, ICallbackNotifier notifier) throws Exception {\n\t\tif (!LNReaderApplication.getInstance().isOnline())\n\t\t\tthrow new BakaReaderException(\"没有网络连接\", BakaReaderException.NO_NETWORK_CONNECTIFITY);\n\t\tLog.d(TAG, \"PageModel = \" + page.getPage());\n\n\t\tint retry = 0;\n\t\twhile (retry < getRetry()) {\n\t\t\ttry {\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"正在加载 \" + \" 请稍后\"));\n\t\t\t\t}\n\t\t\t\tString encodedTitle = Util.UrlEncode(page.getPage());\n\t\t\t\tString fullUrl = \"http://www.baka-tsuki.org/project/api.php?action=query&prop=info&format=xml&redirects=yes&titles=\" + encodedTitle;\n\t\t\t\tResponse response = Jsoup.connect(fullUrl).timeout(getTimeout(retry)).execute();\n\t\t\t\tPageModel pageModel = null;\n\t\t\t\tString lang = page.getLanguage();\n\t\t\t\tif (lang != null)\n\t\t\t\t\tpageModel = CommonParser.parsePageAPI(page, response.parse(), fullUrl);\n\t\t\t\tpageModel.setFinishedRead(page.isFinishedRead());\n\t\t\t\tpageModel.setWatched(page.isWatched());\n\n\t\t\t\tsynchronized (dbh) {\n\t\t\t\t\t// save to db and get saved value\n\t\t\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpageModel = PageModelHelper.insertOrUpdatePageModel(db, pageModel, false);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tdb.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn pageModel;\n\t\t\t} catch (EOFException eof) {\n\t\t\t\t++retry;\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"重新尝试: \" + page.getPage() + \" (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage()));\n\t\t\t\t}\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t} catch (IOException eof) {\n\t\t\t\t++retry;\n\t\t\t\tString message = \"重新尝试: \" + page.getPage() + \" (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage();\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(message));\n\t\t\t\t}\n\t\t\t\tLog.d(TAG, message, eof);\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic PageModel updatePageModel(PageModel page) {\n\t\tPageModel pageModel = null;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\ttry {\n\t\t\t\tpageModel = PageModelHelper.insertOrUpdatePageModel(db, page, false);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\treturn pageModel;\n\t}\n\n\t/*\n\t * NovelCollectionModel\n\t */\n\n\tpublic NovelCollectionModel getNovelDetails(PageModel page, ICallbackNotifier notifier) throws Exception {\n\t\tNovelCollectionModel novel = null;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\ttry {\n\t\t\t\tnovel = NovelCollectionModelHelper.getNovelDetails(db, page.getPage());\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\tif (novel == null) {\n\t\t\tnovel = getNovelDetailsFromInternet(page, notifier);\n\t\t}\n\t\treturn novel;\n\t}\n\n\tpublic NovelCollectionModel getNovelDetailsFromInternet(PageModel page, ICallbackNotifier notifier) throws Exception {\n\t\tif (!LNReaderApplication.getInstance().isOnline())\n\t\t\tthrow new BakaReaderException(\"没有网络连接\", BakaReaderException.NO_NETWORK_CONNECTIFITY);\n\t\tLog.d(TAG, \"Getting Novel Details from internet: \" + page.getPage());\n\t\tNovelCollectionModel novel = null;\n\n\t\tint retry = 0;\n\t\twhile (retry < getRetry()) {\n\t\t\ttry {\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"正在加载小说详细信息: \" + page.getPage()));\n\t\t\t\t}\n\t\t\t\t//String encodedTitle = Util.UrlEncode();\n\t\t\t\tString fullUrl = UIHelper.getBaseUrl(LNReaderApplication.getInstance().getApplicationContext()) + \"/api/article/\" + page.getId()+\"/1\";\n\t\t\t\tResponse response = Jsoup.connect(fullUrl).timeout(getTimeout(retry)).execute();\n\t\t\t\tString doc = response.body();\n\t\t\t\t/*\n\t\t\t\t * Add your section of alternative language here, create own\n\t\t\t\t * parser for each language for modularity reason\n\t\t\t\t */\n\t\t\t\tif (!page.getLanguage().equals(Constants.LANG_ENGLISH))\n\t\t\t\t\tnovel = BakaTsukiParserAlternative.ParseNovelDetails(doc, page);\n\t\t\t\telse\n\t\t\t\t\tnovel = BakaTsukiParser.ParseNovelDetails(doc, page);\n\t\t\t} catch (EOFException eof) {\n\t\t\t\t++retry;\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"重新尝试: \" + page.getPage() + \" (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage()));\n\t\t\t\t}\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t} catch (IOException eof) {\n\t\t\t\t++retry;\n\t\t\t\tString message = \"重新尝试: \" + page.getPage() + \" (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage();\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(message));\n\t\t\t\t}\n\t\t\t\tLog.d(TAG, message, eof);\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t}\n\n\t\t\t// Novel details' Page Model\n\t\t\tif (novel != null) {\n\t\t\t\tpage = updateNovelDetailsPageModel(page, notifier, novel);\n\n\t\t\t\tsynchronized (dbh) {\n\t\t\t\t\t// insert to DB and get saved value\n\t\t\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdb.beginTransaction();\n\t\t\t\t\t\tnovel = NovelCollectionModelHelper.insertNovelDetails(db, novel);\n\t\t\t\t\t\tdb.setTransactionSuccessful();\n\t\t\t\t\t\t//db.endTransaction();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tdb.endTransaction();\n\t\t\t\t\t\tdb.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// update info for each chapters\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"获取章节信息: \" + page.getPage()));\n\t\t\t\t}\n\t\t\t\tLog.d(TAG, \"Cover size: \" + novel.getFlattedChapterList().size());\n\t\t\t\tArrayList<PageModel> chapters = getUpdateInfo(novel.getFlattedChapterList(), notifier);\n\t\t\t\t\n\t\t\t\tfor (PageModel pageModel : chapters) {\n\t\t\t\t\tpageModel = updatePageModel(pageModel);\n\t\t\t\t}\n\n\t\t\t\t// download cover image\n\t\t\t\tLog.d(TAG, \"Cover imgurl: \" + page.getImgurl());\n\t\t\t\tnovel.setCoverUrl(new URL(Constants.BASE_IMAGE_URL+ page.getImgurl()));\n\t\t\t\tif (novel.getCoverUrl() != null) {\n\t\t\t\t\tif (notifier != null) {\n\t\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"获取封面图片.\"));\n\t\t\t\t\t}\n\t\t\t\t\tDownloadFileTask task = new DownloadFileTask(notifier);\n\t\t\t\t\tImageModel image = task.downloadImage(novel.getCoverUrl());\n\t\t\t\t\t// TODO: need to save to db?\n\t\t\t\t\tLog.d(TAG, \"Cover Image: \" + image.toString());\n\t\t\t\t\tnovel.setCover(image.getDedepath());\n\t\t\t\t\t\n\t\t\t\t\tsynchronized (dbh) {\n\t // insert to DB and get saved value\n\t SQLiteDatabase db = dbh.getWritableDatabase();\n\t try {\n\t db.beginTransaction();\n\t NovelCollectionModelHelper.insertNovelDetailsImg(db, novel);\n\t db.setTransactionSuccessful();\n\t //db.endTransaction();\n\t } finally {\n\t db.endTransaction();\n\t db.close();\n\t }\n\t }\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\tLog.d(TAG, \"Complete getting Novel Details from internet: \" + page.getPage());\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn novel;\n\t}\n\n\tpublic PageModel updateNovelDetailsPageModel(PageModel page, ICallbackNotifier notifier, NovelCollectionModel novel) throws Exception {\n\t\t// comment out because have teaser now...\n\t\t// page.setParent(\"Main_Page\"); // insurance\n\n\t\t// get the last update time from internet\n\t\tif (notifier != null) {\n\t\t\tnotifier.onCallback(new CallbackEventData(\"获取小说信息: \" + page.getPage()));\n\t\t}\n\t\t/*PageModel novelPageTemp = getPageModelFromInternet(page, notifier);\n\t\tif (novelPageTemp != null) {\n\t\t\tpage.setLastUpdate(novelPageTemp.getLastUpdate());\n\t\t\tpage.setLastCheck(new Date());\n\t\t\tnovel.setLastUpdate(novelPageTemp.getLastUpdate());\n\t\t\tnovel.setLastCheck(new Date());\n\t\t} else {\n\t\t\tpage.setLastUpdate(new Date(0));\n\t\t\tpage.setLastCheck(new Date());\n\t\t\tnovel.setLastUpdate(new Date(0));\n\t\t\tnovel.setLastCheck(new Date());\n\t\t}*/\n\t\t// save the changes\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\ttry {\n\t\t\t\tpage = PageModelHelper.insertOrUpdatePageModel(db, page, true);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\treturn page;\n\t}\n\n\tpublic PageModel getUpdateInfo(PageModel pageModel, ICallbackNotifier notifier) throws Exception {\n\t\tArrayList<PageModel> pageModels = new ArrayList<PageModel>();\n\t\tpageModels.add(pageModel);\n\t\tpageModels = getUpdateInfo(pageModels, notifier);\n\t\treturn pageModels.get(0);\n\t}\n\n\t/***\n\t * Bulk update page info through wiki API - LastUpdateInfo. - Redirected. -\n\t * Missing flag.\n\t * \n\t * @param pageModels\n\t * @param notifier\n\t * @return\n\t * @throws Exception\n\t */\n\tpublic ArrayList<PageModel> getUpdateInfo(ArrayList<PageModel> pageModels, ICallbackNotifier notifier) throws Exception {\n\t\tArrayList<PageModel> resultPageModel = new ArrayList<PageModel>();\n\t\tArrayList<PageModel> noInfoPageModel = new ArrayList<PageModel>();\n\t\tArrayList<PageModel> externalPageModel = new ArrayList<PageModel>();\n\n\t\tString baseUrl = UIHelper.getBaseUrl(LNReaderApplication.getInstance().getApplicationContext()) + \"/project/api.php?action=query&prop=info&format=xml&redirects=yes&titles=\";\n\t\tint i = 0;\n\t\tint retry = 0;\n\t\twhile (i < pageModels.size()) {\n\t\t\tint apiPageCount = 1;\n\t\t\tArrayList<PageModel> checkedPageModel = new ArrayList<PageModel>();\n\t\t\tString titles = \"\";\n\n\t\t\twhile (i < pageModels.size() && apiPageCount < 50) {\n\t\t\t\tif (pageModels.get(i).isExternal()) {\n\t\t\t\t\tpageModels.get(i).setMissing(false);\n\t\t\t\t\texternalPageModel.add(pageModels.get(i));\n\t\t\t\t\t++i;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (pageModels.get(i).isMissing() || pageModels.get(i).getPage().endsWith(\"&action=edit&redlink=1\")) {\n\t\t\t\t\tpageModels.get(i).setMissing(true);\n\t\t\t\t\tnoInfoPageModel.add(pageModels.get(i));\n\t\t\t\t\t++i;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (titles.length() + pageModels.get(i).getPage().length() < 2000) {\n\t\t\t\t\ttitles += \"|\" + Util.UrlEncode(pageModels.get(i).getPage());\n\t\t\t\t\tcheckedPageModel.add(pageModels.get(i));\n\t\t\t\t\t++i;\n\t\t\t\t\t++apiPageCount;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// request the page\n\t\t\twhile (retry < getRetry()) {\n\t\t\t\ttry {\n\t\t\t\t\t// Log.d(TAG, \"Trying to get: \" + baseUrl + titles);\n\t\t\t\t\tString url = baseUrl + titles;\n\t\t\t\t\tResponse response = Jsoup.connect(url).timeout(getTimeout(retry)).execute();\n\t\t\t\t\tDocument doc = response.parse();\n\t\t\t\t\tArrayList<PageModel> updatedPageModels = CommonParser.parsePageAPI(checkedPageModel, doc, url);\n\t\t\t\t\tresultPageModel.addAll(updatedPageModels);\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (EOFException eof) {\n\t\t\t\t\t++retry;\n\t\t\t\t\tif (notifier != null) {\n\t\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Retrying: Get Pages Info (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage()));\n\t\t\t\t\t}\n\t\t\t\t\tif (retry > getRetry())\n\t\t\t\t\t\tthrow eof;\n\t\t\t\t} catch (IOException eof) {\n\t\t\t\t\t++retry;\n\t\t\t\t\tString message = \"Retrying: Get Pages Info (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage();\n\t\t\t\t\tif (notifier != null) {\n\t\t\t\t\t\tnotifier.onCallback(new CallbackEventData(message));\n\t\t\t\t\t}\n\t\t\t\t\tLog.d(TAG, message, eof);\n\t\t\t\t\tif (retry > getRetry())\n\t\t\t\t\t\tthrow eof;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (PageModel page : externalPageModel) {\n\t\t\tgetExternalUpdateInfo(page);\n\t\t}\n\n\t\tresultPageModel.addAll(noInfoPageModel);\n\t\tresultPageModel.addAll(externalPageModel);\n\n\t\treturn resultPageModel;\n\t}\n\n\tpublic void getExternalUpdateInfo(PageModel page) {\n\t\tint retry;\n\t\tMap<String, String> headers = null;\n\t\t// Date: Wed, 13 Nov 2013 13:08:35 GMT\n\t\tDateFormat df = new SimpleDateFormat(\"EEE, dd MMM yyyy kk:mm:ss z\", Locale.US);\n\t\tretry = 0;\n\t\twhile (retry < getRetry()) {\n\t\t\ttry {\n\t\t\t\theaders = Jsoup.connect(page.getPage()).timeout(getTimeout(retry)).maxBodySize(1).execute().headers();\n\t\t\t\tbreak;\n\t\t\t} catch (Exception e) {\n\t\t\t\tLog.e(TAG, \"Error when getting updated date for: \" + page.getPage(), e);\n\t\t\t\t++retry;\n\t\t\t}\n\t\t}\n\t\tif (headers != null) {\n\t\t\tString dateStr = null;\n\t\t\tif (headers.containsKey(\"Last-Modified\")) {\n\t\t\t\tdateStr = headers.get(\"Last-Modified\");\n\t\t\t}\n\t\t\telse if (headers.containsKey(\"Date\")) {\n\t\t\t\tdateStr = headers.get(\"Date\");\n\t\t\t}\n\t\t\tif (!Util.isStringNullOrEmpty(dateStr)) {\n\t\t\t\ttry {\n\t\t\t\t\tLog.d(TAG, \"External Novel last update: \" + dateStr);\n\t\t\t\t\tpage.setLastUpdate(df.parse(dateStr));\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLog.e(TAG, \"Failed to parse date for: \" + page.getPage(), e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpage.setLastCheck(new Date());\n\t}\n\n\tpublic void deleteBooks(BookModel bookDel) {\n\t\tsynchronized (dbh) {\n\t\t\t// get from db\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\ttry {\n\t\t\t\tBookModel tempBook = BookModelHelper.getBookModel(db, bookDel.getId());\n\t\t\t\tif (tempBook != null) {\n\t\t\t\t\tArrayList<PageModel> chapters = tempBook.getChapterCollection();\n\t\t\t\t\tfor (PageModel chapter : chapters) {\n\t\t\t\t\t\tNovelContentModelHelper.deleteNovelContent(db, chapter);\n\t\t\t\t\t}\n\t\t\t\t\tBookModelHelper.deleteBookModel(db, tempBook);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void deletePage(PageModel page) {\n\t\tsynchronized (dbh) {\n\t\t\t// get from db\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\ttry {\n\t\t\t\tPageModel tempPage = PageModelHelper.getPageModel(db, page.getId());\n\t\t\t\tif (tempPage != null) {\n\t\t\t\t\tPageModelHelper.deletePageModel(db, tempPage);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic ArrayList<PageModel> getChapterCollection(String page, String title, BookModel book) {\n\t\tsynchronized (dbh) {\n\t\t\t// get from db\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\ttry {\n\t\t\t\treturn NovelCollectionModelHelper.getChapterCollection(db, page + Constants.NOVEL_BOOK_DIVIDER + title, book);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic ArrayList<PageModel> getAllContentPageModel() {\n\t\tArrayList<PageModel> result = null;\n\t\tsynchronized (dbh) {\n\t\t\t// get from db\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\ttry {\n\t\t\t\tresult = PageModelHelper.getAllContentPageModel(db);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/*\n\t * NovelContentModel\n\t */\n\n\tpublic NovelContentModel getNovelContent(BookModel page, boolean download, ICallbackNotifier notifier) throws Exception {\n\t\tNovelContentModel content = null;\n\n\t\tsynchronized (dbh) {\n\t\t\t// get from db\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\ttry {\n\t\t\t\tcontent = NovelContentModelHelper.getNovelContent(db, page.getPage());\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\t// get from Internet;\n\t\tif (download && content == null) {\n\t\t\tLog.d(\"getNovelContent\", \"Get from Internet: \" + page.getPage());\n\t\t\tcontent = getNovelContentFromInternet(page, notifier);\n\t\t}\n\t\tLog.d(\"getNovelContent\", \"Text: \" + content.getContent());\n\t\treturn content;\n\t}\n\n\tpublic NovelContentModel getNovelContentFromInternet(BookModel page, ICallbackNotifier notifier) throws Exception {\n\t\tif (!LNReaderApplication.getInstance().isOnline())\n\t\t\tthrow new BakaReaderException(\"没有网络连接\", BakaReaderException.NO_NETWORK_CONNECTIFITY);\n\n\t\tString oldTitle = page.getTitle();\n\n\t\tNovelContentModel content = new NovelContentModel();\n\t\tint retry = 0;\n\t\tString doc = null;\n\t\twhile (retry < getRetry()) {\n\t\t\ttry {\n\t\t\t\tString encodedUrl = Constants.BASE_URL + \"/api/article/\"+page.getBookId()+\"/ch/\"+page.getChapter();\n\t\t\t\tResponse response = Jsoup.connect(encodedUrl).timeout(getTimeout(retry)).execute();\n\t\t\t\tdoc = response.body();\n\t\t\t\t\n\t\t\t\tcontent = BakaTsukiParser.ParseNovelContent(doc, page);\n\t\t\t\tcontent.setUpdatingFromInternet(true);\n\t\t\t\tbreak;\n\t\t\t} catch (EOFException eof) {\n\t\t\t\t++retry;\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Retrying: \" + page.getPage() + \" (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage()));\n\t\t\t\t}\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t} catch (IOException eof) {\n\t\t\t\t++retry;\n\t\t\t\tString message = \"Retrying: \" + page.getPage() + \" (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage();\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(message));\n\t\t\t\t}\n\t\t\t\tLog.d(TAG, message, eof);\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t}\n\t\t}\n\t\t/*if (doc != null) {\n\t\t\t// download all attached images\n\t\t\tDownloadFileTask task = new DownloadFileTask(notifier);\n\t\t\tfor (ImageModel image : content.getImages()) {\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Start downloading: \" + image.getUrl()));\n\t\t\t\t}\n\t\t\t\timage = task.downloadImage(image.getUrl());\n\t\t\t\t// TODO: need to save image to db? mostly thumbnail only\n\t\t\t}\n\n\t\t\t// download linked big images\n\t\t\tboolean isDownloadBigImage = PreferenceManager.getDefaultSharedPreferences(LNReaderApplication.getInstance()).getBoolean(Constants.PREF_DOWLOAD_BIG_IMAGE, false);\n\t\t\tif (isDownloadBigImage) {\n\t\t\t\tDocument imageDoc = Jsoup.parse(content.getContent());\n\t\t\t\tArrayList<String> images = CommonParser.parseImagesFromContentPage(imageDoc);\n\t\t\t\tfor (String imageUrl : images) {\n\t\t\t\t\t// ImageModel bigImage = getImageModelFromInternet(image, notifier);\n\t\t\t\t\tImageModel bigImage = new ImageModel();\n\t\t\t\t\tbigImage.setBigImage(true);\n\t\t\t\t\tbigImage.setName(imageUrl);\n\t\t\t\t\tbigImage.setReferer(imageUrl);\n\t\t\t\t\tbigImage = getImageModel(bigImage, notifier);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// get last updated info\n\n\t\t\tPageModel contentPageModelTemp = getPageModelFromInternet(content.getPageModel(), notifier);\n\t\t\tif (contentPageModelTemp != null) {\n\t\t\t\t// overwrite the old title\n\t\t\t\tcontent.getPageModel().setTitle(oldTitle);\n\t\t\t\t// syncronize the date\n\t\t\t\tcontent.getPageModel().setLastUpdate(contentPageModelTemp.getLastUpdate());\n\t\t\t\tcontent.getPageModel().setLastCheck(new Date());\n\t\t\t\tcontent.setLastUpdate(contentPageModelTemp.getLastUpdate());\n\t\t\t\tcontent.setLastCheck(new Date());\n\t\t\t}\n\n\t\t\t// page model will be also saved in insertNovelContent()\n\t\t\tsynchronized (dbh) {\n\t\t\t\t// save to DB, and get the saved value\n\t\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\t\ttry {\n\t\t\t\t\t// TODO: somehow using transaction cause problem...\n\t\t\t\t\tdb.beginTransaction();\n\t\t\t\t\tcontent = NovelContentModelHelper.insertNovelContent(db, content);\n\t\t\t\t\tdb.setTransactionSuccessful();\n\t\t\t\t} finally {\n\t\t\t\t\tdb.endTransaction();\n\t\t\t\t\tdb.close();\n\t\t\t\t}\n\t\t\t}\n\t\t}*/\n\t\treturn content;\n\t}\n\n\tpublic NovelContentModel updateNovelContent(NovelContentModel content) throws Exception {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\ttry {\n\t\t\t\tcontent = NovelContentModelHelper.insertNovelContent(db, content);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\treturn content;\n\t}\n\n\tpublic boolean deleteNovelContent(PageModel ref) {\n\t\tboolean result = false;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\ttry {\n\t\t\t\tresult = NovelContentModelHelper.deleteNovelContent(db, ref);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/*\n\t * ImageModel\n\t */\n\n\t/**\n\t * Get image from db, if not exist will try to download from internet\n\t * \n\t * @param image\n\t * @param notifier\n\t * @return\n\t * @throws Exception\n\t */\n\tpublic ImageModel getImageModel(ImageModel image, ICallbackNotifier notifier) throws Exception {\n\t\tif (image == null || image.getName() == null)\n\t\t\tthrow new BakaReaderException(\"Empty Image!\", BakaReaderException.EMPTY_IMAGE);\n\t\tImageModel imageTemp = null;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\ttry {\n\t\t\t\timageTemp = ImageModelHelper.getImage(db, image);\n\n\t\t\t\tif (imageTemp == null) {\n\t\t\t\t\tif (image.getReferer() == null)\n\t\t\t\t\t\timage.setReferer(image.getName());\n\t\t\t\t\tLog.d(TAG, \"Image not found, might need to check by referer: \" + image.getName() + \", referer: \" + image.getReferer());\n\t\t\t\t\timageTemp = ImageModelHelper.getImageByReferer(db, image);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\tboolean downloadBigImage = false;\n\t\tif (imageTemp == null) {\n\t\t\tLog.i(TAG, \"Image not found in DB, getting data from internet: \" + image.getName());\n\t\t\tdownloadBigImage = true;\n\t\t} else if (!new File(imageTemp.getPath()).exists()) {\n\t\t\ttry{\n\t\t\t\tLog.i(TAG, \"Image found in DB, but doesn't exist in path: \" + imageTemp.getPath()\n\t\t\t\t\t\t+\"\\nAttempting URLDecoding method with default charset:\"+java.nio.charset.Charset.defaultCharset().displayName());\n\t\t\t\tif(!new File(java.net.URLDecoder.decode(imageTemp.getPath(), java.nio.charset.Charset.defaultCharset().displayName())).exists()){\n\t\t\t\t\tLog.i(TAG, \"Image found in DB, but doesn't exist in URL decoded path: \" + java.net.URLDecoder.decode(imageTemp.getPath(), java.nio.charset.Charset.defaultCharset().displayName()));\n\t\t\t\t\tdownloadBigImage = true;\t\t\t\t\t\n\t\t\t\t} //else Log.i(TAG, \"Image found in DB with URL decoded path: \" + java.net.URLDecoder.decode(imageTemp.getPath(), java.nio.charset.Charset.defaultCharset().displayName()));\n\t\t\t\t\n\t\t\t}catch(Exception e){\n\t\t\t\tLog.i(TAG, \"Image found in DB, but path string seems to be broken: \" + imageTemp.getPath()\n\t\t\t\t\t\t+ \" Charset:\" + java.nio.charset.Charset.defaultCharset().displayName());\n\t\t\t\tdownloadBigImage = true;\n\t\t\t}\n\t\t}\n\t\tif (downloadBigImage) {\n\t\t\tLog.d(TAG, \"Downloading big image from internet: \" + image.getName());\n\t\t\timageTemp = getImageModelFromInternet(image, notifier);\n\t\t}\n\n\t\treturn imageTemp;\n\t}\n\n\t/**\n\t * Get image from internet from File:xxx\n\t * \n\t * @param page\n\t * @param notifier\n\t * @return\n\t * @throws Exception\n\t */\n\tpublic ImageModel getImageModelFromInternet(ImageModel image, ICallbackNotifier notifier) throws Exception {\n\t\tif (!LNReaderApplication.getInstance().isOnline())\n\t\t\tthrow new BakaReaderException(\"No Network Connectifity\", BakaReaderException.NO_NETWORK_CONNECTIFITY);\n\t\tString url = image.getName();\n\t\tif (!url.startsWith(\"http\"))\n\t\t\turl = UIHelper.getBaseUrl(LNReaderApplication.getInstance().getApplicationContext()) + url;\n\n\t\tif (notifier != null) {\n\t\t\tnotifier.onCallback(new CallbackEventData(\"Parsing File Page: \" + url));\n\t\t}\n\n\t\tint retry = 0;\n\t\twhile (retry < getRetry()) {\n\t\t\ttry {\n\t\t\t\tResponse response = Jsoup.connect(url).timeout(getTimeout(retry)).execute();\n\t\t\t\tDocument doc = response.parse();\n\n\t\t\t\t// only return the full image url\n\t\t\t\timage = CommonParser.parseImagePage(doc);\n\n\t\t\t\tDownloadFileTask downloader = new DownloadFileTask(notifier);\n\t\t\t\timage = downloader.downloadImage(image.getUrl());\n\t\t\t\timage.setReferer(url);\n\n\t\t\t\timage = insertImage(image);\n\t\t\t\tbreak;\n\t\t\t} catch (EOFException eof) {\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(\"Retrying: \" + url + \" (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage()));\n\t\t\t\t}\n\t\t\t\t++retry;\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t} catch (IOException eof) {\n\t\t\t\t++retry;\n\t\t\t\tString message = \"Retrying: \" + url + \" (\" + retry + \" of \" + getRetry() + \")\\n\" + eof.getMessage();\n\t\t\t\tif (notifier != null) {\n\t\t\t\t\tnotifier.onCallback(new CallbackEventData(message));\n\t\t\t\t}\n\t\t\t\tLog.d(TAG, message, eof);\n\t\t\t\tif (retry > getRetry())\n\t\t\t\t\tthrow eof;\n\t\t\t}\n\t\t}\n\t\treturn image;\n\t}\n\n\tpublic ImageModel insertImage(ImageModel image) {\n\t\tsynchronized (dbh) {\n\t\t\t// save to db and get the saved value\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\ttry {\n\t\t\t\timage = ImageModelHelper.insertImage(db, image);\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t}\n\t\treturn image;\n\t}\n\n\tpublic ArrayList<ImageModel> getAllImages() {\n\t\tArrayList<ImageModel> result;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\tresult = ImageModelHelper.getAllImages(db);\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic ArrayList<PageModel> doSearch(String searchStr, boolean isNovelOnly, ArrayList<String> languageList) {\n\t\tif (searchStr == null || searchStr.length() < 3)\n\t\t\treturn null;\n\n\t\tArrayList<PageModel> result;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\tresult = dbh.doSearch(db, searchStr, isNovelOnly, languageList);\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic boolean deleteNovel(PageModel novel) {\n\t\tboolean result = false;\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tresult = NovelCollectionModelHelper.deleteNovel(db, novel);\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic ArrayList<BookmarkModel> getBookmarks(PageModel novel) {\n\t\tArrayList<BookmarkModel> bookmarks = new ArrayList<BookmarkModel>();\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\tbookmarks = BookmarkModelHelper.getBookmarks(db, novel);\n\t\t}\n\t\treturn bookmarks;\n\t}\n\n\tpublic int addBookmark(BookmarkModel bookmark) {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\treturn BookmarkModelHelper.insertBookmark(db, bookmark);\n\t\t}\n\t}\n\n\tpublic int deleteBookmark(BookmarkModel bookmark) {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\treturn BookmarkModelHelper.deleteBookmark(db, bookmark);\n\t\t}\n\t}\n\n\tpublic ArrayList<BookmarkModel> getAllBookmarks(boolean isOrderByDate) {\n\t\tArrayList<BookmarkModel> bookmarks = new ArrayList<BookmarkModel>();\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\tbookmarks = BookmarkModelHelper.getAllBookmarks(db, isOrderByDate);\n\t\t}\n\t\treturn bookmarks;\n\t}\n\n\tpublic boolean isContentUpdated(PageModel page) {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\treturn dbh.isContentUpdated(db, page);\n\t\t}\n\t}\n\n\tpublic int isNovelUpdated(PageModel page) {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\treturn dbh.isNovelUpdated(db, page);\n\t\t}\n\t}\n\n\tpublic ArrayList<UpdateInfoModel> getAllUpdateHistory() {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getReadableDatabase();\n\t\t\treturn UpdateInfoModelHelper.getAllUpdateHistory(db);\n\t\t}\n\t}\n\n\tpublic void deleteAllUpdateHistory() {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tUpdateInfoModelHelper.deleteAllUpdateHistory(db);\n\t\t}\n\t}\n\n\tpublic void deleteUpdateHistory(UpdateInfoModel updateInfo) {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tUpdateInfoModelHelper.deleteUpdateHistory(db, updateInfo);\n\t\t}\n\t}\n\n\tpublic void insertUpdateHistory(UpdateInfoModel update) {\n\t\tsynchronized (dbh) {\n\t\t\tSQLiteDatabase db = dbh.getWritableDatabase();\n\t\t\tUpdateInfoModelHelper.insertUpdateHistory(db, update);\n\t\t}\n\t}\n\n\tpublic void deleteChapterCache(PageModel chapter) {\n\t\tdeleteNovelContent(chapter);\n\n\t\t// Set isDownloaded to false\n\t\tchapter.setDownloaded(false);\n\t\tupdatePageModel(chapter);\n\t}\n\n\tpublic void deleteBookCache(BookModel bookDel) {\n\t\tfor (PageModel p : bookDel.getChapterCollection()) {\n\t\t\tdeleteChapterCache(p);\n\t\t}\n\t}\n\n\tprivate int getRetry() {\n\t\treturn UIHelper.getIntFromPreferences(Constants.PREF_RETRY, 3);\n\t}\n\n\tprivate int getTimeout(int retry) {\n\t\tboolean increaseRetry = PreferenceManager.getDefaultSharedPreferences(LNReaderApplication.getInstance().getApplicationContext()).getBoolean(Constants.PREF_INCREASE_RETRY, false);\n\t\tint timeout = UIHelper.getIntFromPreferences(Constants.PREF_TIMEOUT, 60) * 1000;\n\t\tif (increaseRetry) {\n\t\t\ttimeout = timeout * (retry + 1);\n\t\t}\n\t\treturn timeout;\n\t}\n\t// public void temp() {\n\t// synchronized (dbh) {\n\t// SQLiteDatabase db = dbh.getWritableDatabase();\n\t// db.execSQL(\"DROP TABLE IF EXISTS \" + dbh.TABLE_NOVEL_BOOKMARK);\n\t// db.execSQL(dbh.DATABASE_CREATE_NOVEL_BOOKMARK);\n\t// }\n\t// }\n}"
] | import java.io.IOException;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.dotcool.reader.LNReaderApplication;
import com.dotcool.R;
import com.dotcool.reader.callback.CallbackEventData;
import com.dotcool.reader.callback.ICallbackEventData;
import com.dotcool.reader.callback.ICallbackNotifier;
import com.dotcool.reader.dao.NovelsDao; | package com.dotcool.reader.task;
public class CopyDBTask extends AsyncTask<Void, ICallbackEventData, Void> implements ICallbackNotifier {
private static final String TAG = CopyDBTask.class.toString();
private final ICallbackNotifier callback;
private final String source;
private final boolean makeBackup;
public CopyDBTask(boolean makeBackup, ICallbackNotifier callback, String source) {
this.makeBackup = makeBackup;
this.source = source;
this.callback = callback;
}
public void onCallback(ICallbackEventData message) {
publishProgress(message);
}
@Override
protected Void doInBackground(Void... params) {
Context ctx = LNReaderApplication.getInstance().getApplicationContext();
try {
copyDB(makeBackup);
} catch (IOException e) {
String message;
if (makeBackup) {
message = ctx.getResources().getString(R.string.copy_db_task_backup_error);
}
else {
message = ctx.getResources().getString(R.string.copy_db_task_restore_error);
} | publishProgress(new CallbackEventData(message)); | 1 |
Elopteryx/upload-parser | upload-parser-core/src/main/java/com/github/elopteryx/upload/internal/AbstractUploadParser.java | [
"@FunctionalInterface\npublic interface OnError {\n\n /**\n * The consumer function to implement.\n * @param context The upload context\n * @param throwable The error that occurred\n * @throws IOException If an error occurs with the IO\n * @throws ServletException If and error occurred with the servlet\n */\n void onError(UploadContext context, Throwable throwable) throws IOException, ServletException;\n \n}",
"@FunctionalInterface\npublic interface OnPartBegin {\n\n /**\n * The function to implement. When it's called depends on the size threshold. If enough bytes\n * have been read or if the part is fully uploaded then this method is called\n * with a buffer containing the read bytes. Note that the buffer is only passed\n * for validation, it should not be written out. The buffered and the upcoming\n * bytes will be written out to the output object returned by this method. If the callback\n * is not set then the uploaded bytes are discarded.\n * @param context The upload context\n * @param buffer The byte buffer containing the first bytes of the part\n * @return A non-null output object (a channel or stream) to write out the part\n * @throws IOException If an error occurred with the channel\n */\n PartOutput onPartBegin(UploadContext context, ByteBuffer buffer) throws IOException;\n\n}",
"@FunctionalInterface\npublic interface OnPartEnd {\n\n /**\n * The consumer function to implement.\n * @param context The upload context\n * @throws IOException If an error occurred with the current channel\n */\n void onPartEnd(UploadContext context) throws IOException;\n \n}",
"@FunctionalInterface\npublic interface OnRequestComplete {\n\n /**\n * The consumer function to implement.\n * @param context The upload context\n * @throws IOException If an error occurs with the IO\n * @throws ServletException If and error occurred with the servlet\n */\n void onRequestComplete(UploadContext context) throws IOException, ServletException;\n}",
"public class PartOutput {\n\n /**\n * The value object.\n */\n private final Object value;\n\n /**\n * Protected constructor, no need for public access.\n * The parser will use the given object here, which is why using\n * the static factory methods is encouraged. Passing an invalid\n * object will terminate the upload process.\n * @param value The value object.\n */\n protected PartOutput(final Object value) {\n this.value = value;\n }\n\n /**\n * Returns whether it is safe to retrieve the value object\n * with the class parameter.\n * @param clazz The class type to check\n * @param <T> Type parameter\n * @return Whether it is safe to cast or not\n */\n public <T> boolean safeToCast(final Class<T> clazz) {\n return value != null && clazz.isAssignableFrom(value.getClass());\n }\n\n /**\n * Retrieves the value object, casting it to the\n * given type.\n * @param clazz The class to cast\n * @param <T> Type parameter\n * @return The stored value object\n */\n public <T> T unwrap(final Class<T> clazz) {\n return clazz.cast(value);\n }\n\n /**\n * Creates a new instance from the given channel object. The parser will\n * use the channel to write out the bytes and will attempt to close it.\n * @param byteChannel A channel which can be used for writing\n * @return A new PartOutput instance\n */\n public static PartOutput from(final WritableByteChannel byteChannel) {\n return new PartOutput(byteChannel);\n }\n\n /**\n * Creates a new instance from the given stream object. The parser will\n * create a channel from the stream to write out the bytes and\n * will attempt to close it.\n * @param outputStream A stream which can be used for writing\n * @return A new PartOutput instance\n */\n public static PartOutput from(final OutputStream outputStream) {\n return new PartOutput(outputStream);\n }\n\n /**\n * Creates a new instance from the given path object. The parser will\n * create a channel from the path to write out the bytes and\n * will attempt to close it. If the file represented by the path\n * does not exist, it will be created. If the file exists and is not\n * empty then the uploaded bytes will be appended to the end of it.\n * @param path A file path which can be used for writing\n * @return A new PartOutput instance\n */\n public static PartOutput from(final Path path) {\n return new PartOutput(path);\n }\n}",
"public class PartSizeException extends UploadSizeException {\n\n /**\n * Public constructor.\n * @param message The message of the exception\n * @param actual The known size at the time of the exception\n * @param permitted The maximum permitted size\n */\n public PartSizeException(final String message, final long actual, final long permitted) {\n super(message, actual, permitted);\n }\n}",
"public class RequestSizeException extends UploadSizeException {\n\n /**\n * Public constructor.\n * @param message The message of the exception\n * @param actual The known size at the time of the exception in bytes\n * @param permitted The maximum permitted size in bytes\n */\n public RequestSizeException(final String message, final long actual, final long permitted) {\n super(message, actual, permitted);\n }\n}",
"public class NullChannel implements ReadableByteChannel, WritableByteChannel {\n\n /**\n * Flag to determine whether the channel is closed or not.\n */\n private boolean open = true;\n\n @Override\n public int read(final ByteBuffer dst) throws IOException {\n if (!open) {\n throw new ClosedChannelException();\n }\n return -1;\n }\n\n @Override\n public int write(final ByteBuffer src) throws IOException {\n if (!open) {\n throw new ClosedChannelException();\n }\n final var remaining = src.remaining();\n src.position(src.limit());\n return remaining;\n }\n\n @Override\n public boolean isOpen() {\n return open;\n }\n\n @Override\n public void close() {\n open = false;\n }\n}",
"public class OutputStreamBackedChannel implements WritableByteChannel {\n\n /**\n * Flag to determine whether the channel is closed or not.\n */\n private boolean open = true;\n\n /**\n * The stream the channel will write to.\n */\n private final OutputStream outputStream;\n\n /**\n * Public constructor.\n * @param outputStream The output stream\n */\n public OutputStreamBackedChannel(final OutputStream outputStream) {\n this.outputStream = Objects.requireNonNull(outputStream);\n }\n\n @Override\n public int write(final ByteBuffer src) throws IOException {\n if (!open) {\n throw new ClosedChannelException();\n }\n if (src.isDirect() || src.isReadOnly()) {\n throw new IllegalArgumentException(\"The buffer cannot be direct or read-only!\");\n }\n final var buf = src.array();\n final var offset = src.position();\n final var len = src.remaining();\n outputStream.write(buf, offset, len);\n src.position(offset + len);\n return len;\n }\n\n @Override\n public boolean isOpen() {\n return open;\n }\n\n @Override\n public void close() throws IOException {\n outputStream.close();\n open = false;\n }\n}"
] | import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;
import static java.util.Objects.requireNonNull;
import com.github.elopteryx.upload.OnError;
import com.github.elopteryx.upload.OnPartBegin;
import com.github.elopteryx.upload.OnPartEnd;
import com.github.elopteryx.upload.OnRequestComplete;
import com.github.elopteryx.upload.PartOutput;
import com.github.elopteryx.upload.errors.PartSizeException;
import com.github.elopteryx.upload.errors.RequestSizeException;
import com.github.elopteryx.upload.util.NullChannel;
import com.github.elopteryx.upload.util.OutputStreamBackedChannel;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.EnumSet;
import jakarta.servlet.http.HttpServletRequest; | /*
* Copyright (C) 2016 Adam Forgacs
*
* 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.elopteryx.upload.internal;
/**
* Base class for the parser implementations. This holds the common methods, like the more specific
* validation and the calling of the user-supplied functions.
*/
public abstract sealed class AbstractUploadParser implements MultipartParser.PartHandler permits AsyncUploadParser, BlockingUploadParser {
/**
* The default size allocated for the buffers.
*/
private static final int DEFAULT_USED_MEMORY = 4096;
/**
* The part begin callback, called at the beginning of each part parsing.
*/
private OnPartBegin partBeginCallback;
/**
* The part end callback, called at the end of each part parsing.
*/
private OnPartEnd partEndCallback;
/**
* The request callback, called after every part has been processed.
*/
OnRequestComplete requestCallback;
/**
* The error callback, called when an error occurred.
*/
OnError errorCallback;
/**
* The user object.
*/
private Object userObject;
/**
* The number of bytes to be allocated for the buffers.
*/
protected int maxBytesUsed = DEFAULT_USED_MEMORY;
/**
* The number of bytes that should be buffered before calling the part begin callback.
*/
protected int sizeThreshold;
/**
* The maximum size permitted for the parts. By default it is unlimited.
*/
private long maxPartSize = -1;
/**
* The maximum size permitted for the complete request. By default it is unlimited.
*/
protected long maxRequestSize = -1;
/**
* The valid mime type.
*/
protected static final String MULTIPART_FORM_DATA = "multipart/form-data";
/**
* The buffer that stores the first bytes of the current part.
*/
protected ByteBuffer checkBuffer;
/**
* The channel to where the current part is written.
*/
private WritableByteChannel writableChannel;
/**
* The known size of the request.
*/
protected long requestSize;
/**
* The context instance.
*/
protected UploadContextImpl context;
/**
* The reference to the multipart parser.
*/
protected MultipartParser.ParseState parseState;
/**
* The buffer that stores the bytes which were read from the
* servlet input stream or from a different source.
*/
protected ByteBuffer dataBuffer;
/**
* Sets up the necessary objects to start the parsing. Depending upon
* the environment the concrete implementations can be very different.
* @param request The servlet request
* @throws RequestSizeException If the supplied size is invalid
*/
void init(final HttpServletRequest request) {
// Fail fast mode
if (maxRequestSize > -1) {
final var requestSize = request.getContentLengthLong();
if (requestSize > maxRequestSize) {
throw new RequestSizeException("The size of the request (" + requestSize
+ ") is greater than the allowed size (" + maxRequestSize + ")!", requestSize, maxRequestSize);
}
}
checkBuffer = ByteBuffer.allocate(sizeThreshold);
context = new UploadContextImpl(request, userObject);
final var mimeType = request.getHeader(Headers.CONTENT_TYPE);
if (mimeType != null && mimeType.startsWith(MULTIPART_FORM_DATA)) {
final String boundary = Headers.extractBoundaryFromHeader(mimeType);
if (boundary == null) {
throw new IllegalArgumentException("Could not find boundary in multipart request with ContentType: "
+ mimeType
+ ", multipart data will not be available");
}
final var encodingHeader = request.getCharacterEncoding();
final var charset = encodingHeader == null ? ISO_8859_1 : Charset.forName(encodingHeader);
parseState = MultipartParser.beginParse(this, boundary.getBytes(charset), maxBytesUsed, charset);
}
}
/**
* Checks how many bytes have been read so far and stops the
* parsing if a max size has been set and reached.
* @param additional The amount to add, always non negative
*/
void checkPartSize(final int additional) {
final long partSize = context.incrementAndGetPartBytesRead(additional);
if (maxPartSize > -1 && partSize > maxPartSize) {
throw new PartSizeException("The size of the part ("
+ partSize
+ ") is greater than the allowed size ("
+ maxPartSize
+ ")!", partSize, maxPartSize);
}
}
/**
* Checks how many bytes have been read so far and stops the
* parsing if a max size has been set and reached.
* @param additional The amount to add, always non negative
*/
void checkRequestSize(final int additional) {
requestSize += additional;
if (maxRequestSize > -1 && requestSize > maxRequestSize) {
throw new RequestSizeException("The size of the request ("
+ requestSize
+ ") is greater than the allowed size ("
+ maxRequestSize
+ ")!", requestSize, maxRequestSize);
}
}
@Override
public void beginPart(final Headers headers) {
final var disposition = headers.getHeader(Headers.CONTENT_DISPOSITION);
if (disposition != null && disposition.startsWith("form-data")) {
final var fieldName = Headers.extractQuotedValueFromHeader(disposition, "name");
final var fileName = Headers.extractQuotedValueFromHeader(disposition, "filename");
context.reset(new PartStreamImpl(fileName, fieldName, headers));
}
}
@Override
public void data(final ByteBuffer buffer) throws IOException {
checkPartSize(buffer.remaining());
copyBuffer(buffer);
if (context.isBuffering() && context.getPartBytesRead() >= sizeThreshold) {
validate(false);
}
if (!context.isBuffering()) {
while (buffer.hasRemaining()) {
writableChannel.write(buffer);
}
}
}
private void copyBuffer(final ByteBuffer buffer) {
final var transferCount = Math.min(checkBuffer.remaining(), buffer.remaining());
if (transferCount > 0) {
checkBuffer.put(buffer.array(), buffer.arrayOffset() + buffer.position(), transferCount);
buffer.position(buffer.position() + transferCount);
}
}
private void validate(final boolean partFinished) throws IOException {
context.finishBuffering();
if (partFinished) {
context.getCurrentPart().markAsFinished();
}
PartOutput output = null;
checkBuffer.flip();
if (partBeginCallback != null) {
output = requireNonNull(partBeginCallback.onPartBegin(context, checkBuffer));
if (output.safeToCast(WritableByteChannel.class)) {
writableChannel = output.unwrap(WritableByteChannel.class);
} else if (output.safeToCast(OutputStream.class)) { | writableChannel = new OutputStreamBackedChannel(output.unwrap(OutputStream.class)); | 8 |
MHAVLOVICK/Sketchy | src/main/java/com/sketchy/image/ImageProcessingThread.java | [
"public class DrawingSize {\n\n\tprivate static final NumberFormat nf = NumberFormat.getInstance();\n\tstatic{\n\t\tnf.setGroupingUsed(false);\n\t\tnf.setMaximumFractionDigits(5);\n\t\tnf.setMaximumFractionDigits(0);\n\t\tnf.setMinimumIntegerDigits(1);\n\t\tnf.setMaximumIntegerDigits(5);\n\t}\n\t\n\tprivate double width;\n\tprivate double height;\n\tprivate String value=\"\";\n\t\n\tpublic DrawingSize(double width, double height){\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.value = nf.format(width) + \" x \" + nf.format(height);\n\t}\n\t\n\tpublic double getWidth() {\n\t\treturn width;\n\t}\n\n\tpublic double getHeight() {\n\t\treturn height;\n\t}\n\n\tpublic String getValue() {\n\t\treturn value;\n\t}\n\n\t// Format is width[mm] x height[mm] <comments>\n\tpublic static DrawingSize parse(String string) {\n\t\tdouble width=0;\n\t\tdouble height=0;\n\t\t\n\t\tString upperCasedString = StringUtils.upperCase(string);\n\t\tString widthString = StringUtils.substringBefore(upperCasedString, \"X\").trim();\n\t\tString heightString = StringUtils.substringAfter(upperCasedString, \"X\").trim();\n\t\t\n\t\twidthString = StringUtils.substringBeforeLast(widthString, \"MM\");\n\t\theightString = StringUtils.substringBefore(heightString, \" \");\n\t\theightString = StringUtils.substringBeforeLast(heightString, \"MM\");\n\t\t\n\t\ttry{\n\t\t\twidth = Double.parseDouble(widthString);\n\t\t\theight = Double.parseDouble(heightString);\n\t\t} catch (Exception e){\n\t\t\tthrow new RuntimeException(\"Invalid Drawing Size! '\" + string + \"'\");\n\t\t}\n\t\t\n\t\tif ((width<=0) || (height<=0)) {\n\t\t\tthrow new RuntimeException(\"Invalid Drawing Size! '\" + string + \"'\");\n\t\t}\n\t\treturn new DrawingSize(width, height);\n\t}\n\t\n}",
"public enum CenterOption{\n\tCENTER_NONE, CENTER_HORIZONTAL, CENTER_VERTICAL, CENTER_BOTH\n};",
"public enum FlipOption{\n\tFLIP_NONE, FLIP_VERTICAL, FLIP_HORIZONTAL, FLIP_BOTH\n};",
"public enum RenderOption{\n\tRENDER_NORMAL, RENDER_HALFTONE, RENDER_EDGE_DETECTION\n};",
"public enum RotateOption{\n\tROTATE_NONE, ROTATE_90, ROTATE_180, ROTATE_270\n};",
"public enum ScaleOption{\n\tSCALE_BILINEAR, SCALE_BICUBIC, SCALE_NEAREST_NEIGHBOR, SCALE_AREA_AVERAGING\n};",
"public class HttpServer {\n\n\tpublic static final File SOURCE_HTML_FILES_DIRECTORY = new File(\"src/main/resources/html\");\n\t\n\tpublic static final File SKETCHY_PROPERTY_FILE=new File(\"SketchyProperties.json\");\n\tpublic static final File IMAGE_UPLOAD_DIRECTORY = new File(\"upload\");\n\t\n\tpublic static ImageProcessingThread imageProcessingThread = null;\n\tpublic static DrawingProcessorThread drawingProccessorThread = null;\n\n\tpublic static File getUploadFile(String filename){\n \treturn new File(IMAGE_UPLOAD_DIRECTORY.getPath() + File.separator + filename);\n\t}\n\t\n\tpublic void start() throws Exception {\n \tif (!IMAGE_UPLOAD_DIRECTORY.exists()) {\n \t\tif (!IMAGE_UPLOAD_DIRECTORY.mkdir()) {\n \t\t\tthrow new Exception(\"Error Creating Upload Directory '\" + IMAGE_UPLOAD_DIRECTORY.getAbsolutePath() + \"!\");\n \t\t}\n \t}\n\n\t\tServer server = new Server(80);\n\n // File Upload Handler\n ServletHolder imageUploadHolder = new ServletHolder(new ImageUploadServlet());\n MultipartConfigElement multipartConfig = new MultipartConfigElement(FileUtils.getTempDirectory().getPath());\n imageUploadHolder.getRegistration().setMultipartConfig(multipartConfig);\n \n // File Upgrade Handler\n ServletHolder upgradeUploadHolder = new ServletHolder(new UpgradeUploadServlet());\n multipartConfig = new MultipartConfigElement(FileUtils.getTempDirectory().getPath());\n upgradeUploadHolder.getRegistration().setMultipartConfig(multipartConfig);\n \n ServletHandler servletHandler = new ServletHandler();\n ServletContextHandler servletContext = new ServletContextHandler();\n servletContext.setHandler(servletHandler);\n servletContext.addServlet(new ServletHolder(new JsonServlet()), \"/servlet/*\");\n servletContext.addServlet(imageUploadHolder, \"/imageUpload/*\");\n servletContext.addServlet(upgradeUploadHolder, \"/upgradeUpload/*\");\n \n // if we are developing, we shouldn't have the Sketchy.jar file in our classpath.\n // in this case, pull from the filesystem, not the .jar\n \n ContextHandler resourceContext = new ContextHandler();\n \n URL url = server.getClass().getClassLoader().getResource(\"html\");\n if (url!=null){\n\t ResourceHandler resourceHandler = new ResourceHandler();\n\t resourceHandler.setDirectoriesListed(false);\n\t resourceContext.setWelcomeFiles(new String[] { \"index.html\" });\n\t resourceContext.setContextPath(\"/\");\n\t String resourceBase = url.toExternalForm();\n\t resourceContext.setResourceBase(resourceBase);\n\t resourceContext.setHandler(resourceHandler);\n } else { \n ResourceHandler resourceHandler = new ResourceHandler();\n resourceHandler.setDirectoriesListed(false);\n resourceContext.setWelcomeFiles(new String[] { \"index.html\" });\n resourceContext.setContextPath(\"/\");\n resourceContext.setResourceBase(SOURCE_HTML_FILES_DIRECTORY.getCanonicalPath());\n resourceContext.setHandler(resourceHandler);\n }\n \n ResourceHandler uploadResourceHandler = new ResourceHandler();\n uploadResourceHandler.setDirectoriesListed(true);\n ContextHandler uploadResourceContext = new ContextHandler();\n uploadResourceContext.setContextPath(\"/upload\");\n uploadResourceContext.setResourceBase(\"./upload\");\n uploadResourceContext.setHandler(uploadResourceHandler);\n \n ContextHandlerCollection contexts = new ContextHandlerCollection();\n contexts.setHandlers(new Handler[] { resourceContext, servletContext, uploadResourceContext});\n server.setHandler(contexts);\n\n server.start();\n server.join();\n\t}\n\t\n\t\n public static void main(String[] args) throws Exception {\n \ttry{\n \t\tSketchyContext.load(SKETCHY_PROPERTY_FILE);\n \t} catch (Exception e){\n \t\tSystem.out.println(\"Error Loading Sketchy Property file! \" + e.getMessage());\n \t}\n \tHttpServer server = new HttpServer();\n \tserver.start();\n }\n}",
"public class SketchyImage {\n\tprivate double dotsPerMillimeterWidth = 0;\n\tprivate double dotsPerMillimeterHeight = 0;\n\t\n\tpublic SketchyImage(BufferedImage image, double dotsPerMillimeterWidth, double dotsPerMillimeterHeight) {\n\t\t// make sure image is a byte array\n\t\t// if not, then convert it\n\t\tif (image.getType() !=BufferedImage.TYPE_BYTE_INDEXED){\n\t\t\tthis.image = toByteImage(image);\n\t\t} else {\n\t\t\tthis.image = image;\n\t\t}\n\t\tthis.dotsPerMillimeterWidth = dotsPerMillimeterWidth;\n\t\tthis.dotsPerMillimeterHeight=dotsPerMillimeterHeight;\n\t}\n\t\n\tprivate BufferedImage image = null;\n\t\n\tpublic double getDotsPerMillimeterWidth() {\n\t\treturn dotsPerMillimeterWidth;\n\t}\n\n\tpublic void setDotsPerMillimeterWidth(double dotsPerMillimeterWidth) {\n\t\tthis.dotsPerMillimeterWidth = dotsPerMillimeterWidth;\n\t}\n\n\tpublic double getDotsPerMillimeterHeight() {\n\t\treturn dotsPerMillimeterHeight;\n\t}\n\n\tpublic void setDotsPerMillimeterHeight(double dotsPerMillimeterHeight) {\n\t\tthis.dotsPerMillimeterHeight = dotsPerMillimeterHeight;\n\t}\n\n\tpublic BufferedImage getImage() {\n\t\treturn image;\n\t}\n\tpublic void setImage(BufferedImage image) {\n\t\tthis.image = image;\n\t}\n\t\n\tpublic int getWidth(){\n\t\treturn image.getWidth();\n\t}\n\t\n\tpublic int getHeight(){\n\t\treturn image.getHeight();\n\t}\n\n\tpublic int getWidthInMillimeters(){\n\t\treturn (int) Math.ceil(image.getWidth() / getDotsPerMillimeterWidth());\n\t}\n\t\n\tpublic int getHeightInMillimeters(){\n\t\treturn (int) Math.ceil(image.getHeight() / getDotsPerMillimeterHeight());\n\t}\n\t\n\n\t\n\tpublic static void save(SketchyImage sketchyImage, File file) throws Exception {\n\t\tif (!file.getParentFile().canWrite()){\n\t\t\tthrow new Exception(\"Can not write to File: \" + file.getPath() + \"!\");\n\t\t}\n\t\t\n\t\tif (!StringUtils.endsWithIgnoreCase(file.getName(), \".png\")){\n\t\t\tthrow new Exception(\"Can not save SketchyImage! Must be a .png file!\");\n\t\t}\n\t\t\n\t\tIterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName(\"png\");\n\t\tImageWriter imageWriter = null;\n\t if (imageWriters.hasNext()) { // Just get first one\n\t \timageWriter = imageWriters.next();\n\t }\n\t if (imageWriter==null){\n\t \t// this should never happen!! if so.. we got problems\n\t \tthrow new Exception(\"Can not find ImageReader for .png Files!\");\n\t }\n\t\t\t\n\t\tImageOutputStream os = null;\n\t try {\n\t \tos = ImageIO.createImageOutputStream(file);\n\t \timageWriter.setOutput(os);\n\t \t\n\t ImageWriteParam imageWriterParam = imageWriter.getDefaultWriteParam();\n\t IIOMetadata metadata = imageWriter.getDefaultImageMetadata(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY), imageWriterParam);\n\n\t String metaDataFormatName = metadata.getNativeMetadataFormatName();\n\t IIOMetadataNode metaDataNode =(IIOMetadataNode) metadata.getAsTree(metaDataFormatName);\n\t \n\t NodeList childNodes = metaDataNode.getElementsByTagName(\"pHYs\");\n\t IIOMetadataNode physNode = null;\n\t if (childNodes.getLength() == 0) {\n\t \t physNode = new IIOMetadataNode(\"pHYs\");\n\t \t physNode.setAttribute(\"pixelsPerUnitXAxis\", Integer.toString((int)Math.ceil(sketchyImage.dotsPerMillimeterWidth*1000)));\n\t \t physNode.setAttribute(\"pixelsPerUnitYAxis\", Integer.toString((int)Math.ceil(sketchyImage.dotsPerMillimeterHeight*1000)));\n\t \t physNode.setAttribute(\"unitSpecifier\",\"meter\"); // always meter\n\t \t metaDataNode.appendChild(physNode);\n\t } else {\n\t \t for (int nodeIdx=0;nodeIdx<childNodes.getLength();nodeIdx++){\n\t \t\t physNode = (IIOMetadataNode) childNodes.item(nodeIdx);\n\t \t\t physNode.setAttribute(\"pixelsPerUnitXAxis\", Integer.toString((int)Math.ceil(sketchyImage.dotsPerMillimeterWidth*1000)));\n\t\t \t physNode.setAttribute(\"pixelsPerUnitYAxis\", Integer.toString((int)Math.ceil(sketchyImage.dotsPerMillimeterHeight*1000)));\n\t\t \t physNode.setAttribute(\"unitSpecifier\",\"meter\"); // always meter\n\t \t\t metaDataNode.appendChild(physNode);\n\t \t }\n\t }\n\t metadata.setFromTree(metaDataFormatName, metaDataNode);\n\t imageWriter.write(new IIOImage(sketchyImage.image, null, metadata));\n\t os.flush();\n\t } catch (Exception e){\n\t \tthrow new Exception(\"Error Saving SketchyImage File: \" + file.getPath() + \"! \" + e.getMessage());\n\t } finally {\n\t \tIOUtils.closeQuietly(os);\n\t } \n\t}\n\t\n\tpublic static SketchyImage load(File file) throws Exception {\n\t\tSketchyImage sketchyImage = null;\n\t\t\n\t\tif (!file.exists() || !file.canRead()){\n\t\t\tthrow new Exception(\"Can not find or read File: \" + file.getPath() + \"!\");\n\t\t}\n\t\t\n\t\tif (!StringUtils.endsWithIgnoreCase(file.getName(), \".png\")){\n\t\t\tthrow new Exception(\"Can not load SketchyImage! Must be a .png file!\");\n\t\t}\n\t\t\n\t\tIterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName(\"png\");\n\t ImageReader imageReader = null;\n\t if (imageReaders.hasNext()) { // Just get first one\n\t \timageReader = imageReaders.next();\n\t }\n\t if (imageReader==null){\n\t \t// this should never happen!! if so.. we got problems\n\t \tthrow new Exception(\"Can not find ImageReader for .png Files!\");\n\t }\n\t\t\t\n\t\tImageInputStream is = null;\n\t try {\n\t \tis = ImageIO.createImageInputStream(file);\n\t \timageReader.setInput(is, true);\n\t \tIIOMetadata metaData = imageReader.getImageMetadata(0); // always get first image\n\t IIOMetadataNode metaDataNode = (IIOMetadataNode) metaData.getAsTree(metaData.getNativeMetadataFormatName());\n\t if (metaDataNode==null){\n\t \tthrow new Exception(\"Error retreiving MetaData properties from .png File!\");\n\t }\n\t \n\t NodeList childNodes = metaDataNode.getElementsByTagName(\"pHYs\");\n\t // only look in the first node\n\t if (childNodes.getLength()==0){\n\t \tthrow new Exception(\"Invalid SketchyImage file. It must contain 'pixelsPerUnit' MetaData!\");\n\t }\n \tIIOMetadataNode physNode = (IIOMetadataNode) childNodes.item(0);\n \tString pixelsPerUnitXAxisAttribute = physNode.getAttribute(\"pixelsPerUnitXAxis\");\n \tString pixelsPerUnitYAxisAttribute = physNode.getAttribute(\"pixelsPerUnitYAxis\");\n \t// String unitSpecifierAttribute = physNode.getAttribute(\"unitSpecifier\"); Just assuming meter\n \tif (StringUtils.isBlank(pixelsPerUnitXAxisAttribute)){\n \t\tthrow new Exception(\"Invalid SketchyImage file. It must contain 'pixelsPerUnitXAxis' MetaData!\");\n\t }\n \tif (StringUtils.isBlank(pixelsPerUnitYAxisAttribute)){\n \t\tthrow new Exception(\"Invalid SketchyImage file. It must contain 'pixelsPerUnitYAxis' MetaData!\");\n\t }\n \t\n \tint pixelsPerUnitXAxis;\n \ttry{\n \t\tpixelsPerUnitXAxis = Integer.parseInt(pixelsPerUnitXAxisAttribute);\n \t\tif (pixelsPerUnitXAxis<=0) throw new Exception(\"Value must be > 0\");\n \t} catch (Exception e){\n \t\tthrow new Exception(\"Invalid 'pixelsPerUnitXAxis' MetaData Attribute! \" + e.getMessage());\n \t}\n \t\n \tint pixelsPerUnitYAxis;\n \ttry{\n \t\tpixelsPerUnitYAxis = Integer.parseInt(pixelsPerUnitYAxisAttribute);\n \t\tif (pixelsPerUnitYAxis<=0) throw new Exception(\"Value must be > 0\");\n \t} catch (Exception e){\n \t\tthrow new Exception(\"Invalid 'pixelsPerUnitYAxis' MetaData Attribute! \" + e.getMessage());\n \t}\n \t\n \t// We successfully processed the MetaData.. now read/set the image \n \tBufferedImage bufferedImage = imageReader.read(0); // always get first image\n\n \tdouble xPixelsPerMM = pixelsPerUnitXAxis/1000.0;\n \tdouble yPixelsPerMM = pixelsPerUnitYAxis/1000.0;\n \t\n \tsketchyImage = new SketchyImage(bufferedImage, xPixelsPerMM, yPixelsPerMM);\n\t } catch (Exception e){\n\t \tthrow new Exception(\"Error Loading SketchyImage File: \" + file.getPath() + \"! \" + e.getMessage());\n\t } finally {\n\t \tIOUtils.closeQuietly(is);\n\t } \n\t\t\n\t\treturn sketchyImage;\n\t}\n\t\n\tpublic boolean[][] toBooleanBitmapArray(int x, int y, int width, int height) throws Exception {\n\t byte[] buffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();\n\t boolean[][] ret = new boolean[width][height];\n\t int imageWidth=image.getWidth();\n\t \n\t for (int yIdx=0;yIdx<height;yIdx++){\n\t \tint yOffset=yIdx*imageWidth;\n\t \tfor (int xIdx=0;xIdx<width;xIdx++){\n\t\t \tret[xIdx][yIdx] = buffer[yOffset+xIdx]==0;\n\t\t }\n\t }\n\n\t return ret;\n }\n\t\n\tpublic static BufferedImage createByteImage(int width, int height){\n\t\tIndexColorModel model = new IndexColorModel(8,2,new byte[]{0,(byte)255}, new byte[]{0,(byte)255}, new byte[]{0,(byte)255});\n\t\treturn new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED, model);\t\t\n\t}\n\t\n\tpublic static BufferedImage toByteImage(BufferedImage image) {\n\t\tBufferedImage newImage = createByteImage(image.getWidth(), image.getHeight());\n\t\tGraphics2D graphics = newImage.createGraphics();\n\t\tgraphics.setBackground(Color.white);\n\t\tgraphics.fillRect(0, 0, image.getWidth(), image.getHeight());\n\t\tgraphics.drawImage(image, 0, 0, null);\n\t\treturn newImage;\n\t}\n\t\n\t\n\tpublic boolean[][] toBooleanBitmapArray(int blackValue) throws Exception {\n\t\treturn toBooleanBitmapArray(0,0, image.getWidth(), image.getHeight());\n }\n\t\n}"
] | import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.AreaAveragingScaleFilter;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageProducer;
import java.io.File;
import javax.imageio.ImageIO;
import marvin.image.MarvinImage;
import marvin.image.MarvinImageMask;
import marvin.plugin.MarvinImagePlugin;
import marvin.util.MarvinPluginLoader;
import org.apache.commons.io.FileUtils;
import com.sketchy.drawing.DrawingSize;
import com.sketchy.image.RenderedImageAttributes.CenterOption;
import com.sketchy.image.RenderedImageAttributes.FlipOption;
import com.sketchy.image.RenderedImageAttributes.RenderOption;
import com.sketchy.image.RenderedImageAttributes.RotateOption;
import com.sketchy.image.RenderedImageAttributes.ScaleOption;
import com.sketchy.server.HttpServer;
import com.sketchy.utils.image.SketchyImage; | /*
Sketchy
Copyright (C) 2015 Matthew Havlovick
http://www.quickdrawbot.com
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Contact Info:
Matt Havlovick
QuickDraw
470 I St
Washougal, WA 98671
[email protected]
http://www.quickdrawbot.com
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
*/
package com.sketchy.image;
public class ImageProcessingThread extends Thread{
public enum Status{
INIT, RENDERING, CANCELLED, ERROR, COMPLETED;
}
private RenderedImageAttributes renderedImageAttributes;
private boolean cancel=false;
private Status status = Status.INIT;
private String statusMessage="";
private int progress=0;
public ImageProcessingThread(RenderedImageAttributes renderedImageAttributes){
this.renderedImageAttributes = renderedImageAttributes;
this.cancel=false;
this.status=Status.INIT;
this.statusMessage="Initializing Rendering";
}
public void cancel(){
cancel=true;
}
public RenderedImageAttributes getRenderedImageAttributes() {
return renderedImageAttributes;
}
public int getProgress() {
return progress;
}
public void run(){
status=Status.RENDERING;
try{
progress=5;
DrawingSize drawingSize = DrawingSize.parse(renderedImageAttributes.getDrawingSize());
double dotsPerMM = 1/renderedImageAttributes.getPenWidth();
statusMessage = "Loading Image";
progress=10;
| File sourceImage = HttpServer.getUploadFile(ImageAttributes.getImageFilename(renderedImageAttributes.getSourceImageName())); | 6 |
OneNoteDev/Android-REST-API-Explorer | app/src/main/java/com/microsoft/o365_android_onenote_rest/snippet/PagesSnippet.java | [
"public class SnippetDetailFragment<T, Result>\n extends BaseFragment\n implements Callback<Result>,\n AuthenticationCallback<AuthenticationResult>, LiveAuthListener {\n\n public static final String ARG_ITEM_ID = \"item_id\";\n public static final String ARG_TEXT_INPUT = \"TextInput\";\n public static final String ARG_SPINNER_SELECTION = \"SpinnerSelection\";\n public static final int UNSET = -1;\n public static final String APP_STORE_URI = \"https://play.google.com/store/apps/details?id=com.microsoft.office.onenote\";\n\n @InjectView(txt_status_code)\n protected TextView mStatusCode;\n\n @InjectView(txt_status_color)\n protected View mStatusColor;\n\n @InjectView(txt_desc)\n protected TextView mSnippetDescription;\n\n @InjectView(txt_request_url)\n protected TextView mRequestUrl;\n\n @InjectView(txt_response_headers)\n protected TextView mResponseHeaders;\n\n @InjectView(txt_response_body)\n protected TextView mResponseBody;\n\n @InjectView(spinner)\n protected Spinner mSpinner;\n\n @InjectView(txt_input)\n protected EditText mEditText;\n\n @InjectView(progressbar)\n protected ProgressBar mProgressbar;\n\n @InjectView(btn_run)\n protected Button mRunButton;\n\n @Inject\n protected AuthenticationManager mAuthenticationManager;\n\n @Inject\n protected LiveAuthClient mLiveAuthClient;\n\n boolean setupDidRun = false;\n private AbstractSnippet<T, Result> mItem;\n\n public SnippetDetailFragment() {\n }\n\n @OnClick(txt_request_url)\n public void onRequestUrlClicked(TextView tv) {\n clipboard(tv);\n }\n\n @OnClick(txt_response_headers)\n public void onResponseHeadersClicked(TextView tv) {\n clipboard(tv);\n }\n\n @OnClick(txt_response_body)\n public void onResponseBodyClicked(TextView tv) {\n clipboard(tv);\n }\n\n @InjectView(btn_launch_browser)\n protected Button mLaunchBrowser;\n\n private void clipboard(TextView tv) {\n int which;\n switch (tv.getId()) {\n case txt_request_url:\n which = req_url;\n break;\n case txt_response_headers:\n which = response_headers;\n break;\n case txt_response_body:\n which = response_body;\n break;\n default:\n which = UNSET;\n }\n String what = which == UNSET ? \"\" : getString(which) + \" \";\n what += getString(clippy);\n Toast.makeText(getActivity(), what, Toast.LENGTH_SHORT).show();\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {\n // old way\n ClipboardManager clipboardManager = (ClipboardManager)\n getActivity().getSystemService(Context.CLIPBOARD_SERVICE);\n clipboardManager.setText(tv.getText());\n } else {\n clipboard11(tv);\n }\n }\n\n @TargetApi(11)\n private void clipboard11(TextView tv) {\n android.content.ClipboardManager clipboardManager =\n (android.content.ClipboardManager) getActivity()\n .getSystemService(Context.CLIPBOARD_SERVICE);\n ClipData clipData = ClipData.newPlainText(\"OneNote\", tv.getText());\n clipboardManager.setPrimaryClip(clipData);\n }\n\n @OnClick(btn_run)\n public void onRunClicked(Button btn) {\n mRequestUrl.setText(\"\");\n mResponseHeaders.setText(\"\");\n mResponseBody.setText(\"\");\n displayStatusCode(\"\", getResources().getColor(R.color.transparent));\n mProgressbar.setVisibility(VISIBLE);\n mItem.request(mItem.mService, this);\n }\n\n @OnClick(txt_hyperlink)\n public void onDocsLinkClicked(TextView textView) {\n launchUri(Uri.parse(mItem.getUrl()));\n }\n\n private void launchUri(Uri uri) {\n Intent launchOneNoteExtern = new Intent(Intent.ACTION_VIEW, uri);\n try {\n startActivity(launchOneNoteExtern);\n } catch (ActivityNotFoundException e) {\n launchOneNoteExtern = new Intent(Intent.ACTION_VIEW, Uri.parse(APP_STORE_URI));\n startActivity(launchOneNoteExtern);\n }\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (getArguments().containsKey(ARG_ITEM_ID)) {\n mItem = (AbstractSnippet<T, Result>)\n SnippetContent.ITEMS.get(getArguments().getInt(ARG_ITEM_ID));\n }\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View rootView = inflater.inflate(R.layout.fragment_snippet_detail, container, false);\n ButterKnife.inject(this, rootView);\n mSnippetDescription.setText(mItem.getDescription());\n if (Input.Spinner == mItem.mInputArgs) {\n mSpinner.setVisibility(VISIBLE);\n } else if (Input.Text == mItem.mInputArgs) {\n mEditText.setVisibility(VISIBLE);\n } else if (Input.Both == mItem.mInputArgs) {\n mSpinner.setVisibility(VISIBLE);\n mEditText.setVisibility(VISIBLE);\n }\n return rootView;\n }\n\n @Override\n public void onActivityCreated(@Nullable Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n if (null != getActivity() && getActivity() instanceof AppCompatActivity) {\n AppCompatActivity activity = (AppCompatActivity) getActivity();\n if (null != activity.getSupportActionBar()) {\n activity.getSupportActionBar().setTitle(mItem.getName());\n }\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n if (User.isOrg()) {\n mAuthenticationManager.connect(this);\n } else if (User.isMsa()) {\n mLiveAuthClient.loginSilent(BaseActivity.sSCOPES, this);\n }\n }\n\n private retrofit.Callback<String[]> getSetUpCallback() {\n return new retrofit.Callback<String[]>() {\n @Override\n public void success(String[] strings, Response response) {\n mProgressbar.setVisibility(View.GONE);\n if (isAdded() && (null == response || strings.length > 0)) {\n mRunButton.setEnabled(true);\n if (strings.length > 0) {\n populateSpinner(strings);\n }\n } else if (isAdded() && strings.length <= 0 && null != response) {\n AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n builder.setTitle(R.string.err_setup)\n .setMessage(R.string.err_setup_msg)\n .setPositiveButton(R.string.dismiss, null)\n .show();\n }\n }\n\n @Override\n public void failure(RetrofitError error) {\n if (isAdded()) {\n displayThrowable(error.getCause());\n mProgressbar.setVisibility(View.GONE);\n }\n }\n };\n }\n\n private void populateSpinner(String[] strings) {\n ArrayAdapter<String> spinnerArrayAdapter\n = new ArrayAdapter<>(\n getActivity(),\n simple_spinner_item,\n strings);\n spinnerArrayAdapter.setDropDownViewResource(simple_spinner_dropdown_item);\n mSpinner.setAdapter(spinnerArrayAdapter);\n }\n\n @Override\n public void success(Result result, Response response) {\n if (!isAdded()) {\n // the user has left...\n return;\n }\n mProgressbar.setVisibility(GONE);\n displayResponse(response);\n maybeShowQuickLink(result);\n }\n\n private void maybeShowQuickLink(Result result) {\n if (result instanceof BaseVO) {\n final BaseVO vo = (BaseVO) result;\n if (hasWebClientLink(vo)) {\n showBrowserLaunchBtn(vo);\n }\n }\n }\n\n private boolean hasWebClientLink(BaseVO vo) {\n return null != vo.links && null != vo.links.oneNoteWebUrl;\n }\n\n private boolean hasOneNoteClientLink(BaseVO vo) {\n return null != vo.links && null != vo.links.oneNoteClientUrl;\n }\n\n private void showBrowserLaunchBtn(final BaseVO vo) {\n mLaunchBrowser.setEnabled(true);\n mLaunchBrowser.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n launchUri(Uri.parse(vo.links.oneNoteWebUrl.href));\n }\n });\n }\n\n private void displayResponse(Response response) {\n int color = getColor(response);\n displayStatusCode(Integer.valueOf(response.getStatus())\n .toString(), getResources().getColor(color));\n displayRequestUrl(response);\n maybeDisplayResponseHeaders(response);\n maybeDisplayResponseBody(response);\n }\n\n private void maybeDisplayResponseBody(Response response) {\n if (null != response.getBody()) {\n String body = null;\n InputStream is = null;\n try {\n is = response.getBody().in();\n body = IOUtils.toString(is);\n String formattedJson = new JSONObject(body).toString(2);\n formattedJson = StringEscapeUtils.unescapeJson(formattedJson);\n mResponseBody.setText(formattedJson);\n } catch (JSONException e) {\n if (null != body) {\n // body wasn't JSON\n mResponseBody.setText(body);\n } else {\n // set the stack trace as the response body\n displayThrowable(e);\n }\n } catch (IOException e) {\n e.printStackTrace();\n displayThrowable(e);\n } finally {\n if (null != is) {\n IOUtils.closeQuietly(is);\n }\n }\n }\n }\n\n private void maybeDisplayResponseHeaders(Response response) {\n if (null != response.getHeaders()) {\n List<Header> headers = response.getHeaders();\n String headerText = \"\";\n for (Header header : headers) {\n headerText += header.getName() + \" : \" + header.getValue() + \"\\n\";\n }\n mResponseHeaders.setText(headerText);\n }\n }\n\n private void displayRequestUrl(Response response) {\n String requestUrl = response.getUrl();\n mRequestUrl.setText(requestUrl);\n }\n\n private void displayStatusCode(String text, int color) {\n mStatusCode.setText(text);\n mStatusColor.setBackgroundColor(color);\n }\n\n private void displayThrowable(Throwable t) {\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n t.printStackTrace(pw);\n String trace = sw.toString();\n mResponseBody.setText(trace);\n }\n\n private int getColor(Response response) {\n int color;\n switch (response.getStatus() / 100) {\n case 1:\n case 2:\n color = R.color.code_1xx;\n break;\n case 3:\n color = R.color.code_3xx;\n break;\n case 4:\n case 5:\n color = R.color.code_4xx;\n break;\n default:\n color = R.color.transparent;\n }\n return color;\n }\n\n @Override\n public void failure(RetrofitError error) {\n Timber.d(error, \"\");\n mProgressbar.setVisibility(GONE);\n if (null != error.getResponse()) {\n displayResponse(error.getResponse());\n }\n }\n\n @Override\n public Map<String, String> getParams() {\n Map<String, String> args = new HashMap<>();\n if (Input.Spinner == mItem.mInputArgs) {\n args.put(ARG_SPINNER_SELECTION, mSpinner.getSelectedItem().toString());\n } else if (Input.Text == mItem.mInputArgs) {\n args.put(ARG_TEXT_INPUT, mEditText.getText().toString());\n } else if (Input.Both == mItem.mInputArgs) {\n args.put(ARG_SPINNER_SELECTION, mSpinner.getSelectedItem().toString());\n args.put(ARG_TEXT_INPUT, mEditText.getText().toString());\n } else {\n throw new IllegalStateException(\"No input modifier to match type\");\n }\n return args;\n }\n\n @Override\n public void onSuccess(AuthenticationResult authenticationResult) {\n SharedPrefsUtil.persistAuthToken(authenticationResult);\n ready();\n }\n\n private void ready() {\n if (Input.None == mItem.mInputArgs) {\n mRunButton.setEnabled(true);\n } else if (!setupDidRun) {\n setupDidRun = true;\n mProgressbar.setVisibility(View.VISIBLE);\n mItem.setUp(AbstractSnippet.sServices, getSetUpCallback());\n }\n }\n\n @Override\n public void onError(Exception e) {\n if (!isAdded()) {\n return;\n }\n displayThrowable(e);\n AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n builder.setTitle(R.string.token_err_title)\n .setMessage(R.string.token_err_msg)\n .setPositiveButton(R.string.dismiss, null)\n .setNegativeButton(R.string.disconnect, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n mAuthenticationManager.disconnect();\n }\n }).show();\n }\n\n @Override\n public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {\n if (null != session) {\n SharedPrefsUtil.persistAuthToken(session);\n }\n ready();\n }\n\n @Override\n public void onAuthError(LiveAuthException exception, Object userState) {\n onError(exception);\n }\n}",
"public class SnippetApp extends Application {\n /**\n * The {@link dagger.ObjectGraph} used by Dagger to fulfill <code>@inject</code> annotations\n *\n * @see javax.inject.Inject\n * @see dagger.Provides\n * @see javax.inject.Singleton\n */\n public ObjectGraph mObjectGraph;\n\n private static SnippetApp sSnippetApp;\n\n @Inject\n protected String endpoint;\n\n @Inject\n protected Converter converter;\n\n @Inject\n protected RestAdapter.LogLevel logLevel;\n\n @Inject\n protected RequestInterceptor requestInterceptor;\n\n @Override\n public void onCreate() {\n super.onCreate();\n sSnippetApp = this;\n mObjectGraph = ObjectGraph.create(new AppModule());\n mObjectGraph.inject(this);\n if (BuildConfig.DEBUG) {\n Timber.plant(new Timber.DebugTree());\n }\n }\n\n public static SnippetApp getApp() {\n return sSnippetApp;\n }\n\n public RestAdapter getRestAdapter() {\n return new RestAdapter.Builder()\n .setEndpoint(endpoint)\n .setLogLevel(logLevel)\n .setConverter(converter)\n .setRequestInterceptor(requestInterceptor)\n .build();\n }\n}",
"public class OneNotePartsMap extends HashMap<String, TypedInput> {\n\n private static final String MANDATORY_PART_NAME = \"Presentation\";\n\n public OneNotePartsMap(TypedInput initValue) {\n put(MANDATORY_PART_NAME, initValue);\n }\n\n}",
"public interface PagesService {\n\n /**\n * Gets the collection of a users OneNote pages\n * Allows for query parameters to filter, order, sort... etc\n *\n * @param filter\n * @param order\n * @param select\n * @param top\n * @param skip\n * @param search\n * @param callback\n */\n @GET(\"/{version}/me/notes/pages\")\n void getPages(\n @Path(\"version\") String version,\n @Query(\"filter\") String filter,\n @Query(\"orderby\") String order,\n @Query(\"select\") String select,\n @Query(\"top\") Integer top,\n @Query(\"skip\") Integer skip,\n @Query(\"search\") String search,\n Callback<Envelope<Page>> callback\n );\n\n\n /**\n * Gets a page specified by page id\n *\n * @param version\n * @param id\n * @param callback\n */\n @GET(\"/{version}/me/notes/pages/{id}\")\n void getPageById(\n @Path(\"version\") String version,\n @Path(\"id\") String id,\n Callback<Envelope<Page>> callback\n );\n\n /**\n * @param version\n * @param id\n * @param callback\n */\n @GET(\"/{version}/me/notes/pages/{id}/content\")\n void getPageContentById(\n @Path(\"version\") String version,\n @Path(\"id\") String id,\n @Header(\"Accept\") String acceptType,\n Callback<Response> callback\n );\n\n /**\n * Gets the pages in a give OneNote section and\n * provides query parameters for sorting, ordering...\n * on the page collection\n *\n * @param version\n * @param sectionId\n * @param order\n * @param select\n * @param top\n * @param skip\n * @param search\n * @param callback\n */\n @GET(\"/{version}/me/notes/sections/{sectionId}/pages\")\n void getSectionPages(\n @Path(\"version\") String version,\n @Path(\"sectionId\") String sectionId,\n @Query(\"orderby\") String order,\n @Query(\"select\") String select,\n @Query(\"top\") Integer top,\n @Query(\"skip\") Integer skip,\n @Query(\"search\") String search,\n Callback<Envelope<Page>> callback\n );\n\n /**\n * Creates a new page in a specified OneNote section\n *\n * @param contentTypeHeader\n * @param version\n * @param id\n * @param content\n * @param callback\n */\n @POST(\"/{version}/me/notes/sections/{id}/pages\")\n void postPages(\n @Header(\"Content-type\") String contentTypeHeader,\n @Path(\"version\") String version,\n @Path(\"id\") String id,\n @Body TypedString content,\n Callback<Page> callback\n );\n\n /**\n * Creates a new page in a section specified by section title\n *\n * @param version\n * @param name\n * @param content\n * @param callback\n */\n @POST(\"/{version}/me/notes/pages\")\n void postPagesInSection(\n @Header(\"Content-type\") String contentTypeHeader,\n @Path(\"version\") String version,\n @Query(\"sectionName\") String name,\n @Body TypedString content,\n Callback<Envelope<Page>> callback\n );\n\n /**\n * Creates a new page with a multi-part content body\n * in a section specified by section id\n *\n * @param version\n * @param sectionId\n * @param partMap\n * @param callback\n */\n @Multipart\n @POST(\"/{version}/me/notes/sections/{sectionId}/pages\")\n void postMultiPartPages(\n @Path(\"version\") String version,\n @Path(\"sectionId\") String sectionId,\n @PartMap OneNotePartsMap partMap,\n Callback<Envelope<Page>> callback\n );\n\n /**\n * Deletes the specified page\n *\n * @param version\n * @param pageId\n * @param callback\n */\n @DELETE(\"/{version}/me/notes/pages/{pageId}\")\n void deletePage(\n @Path(\"version\") String version,\n @Path(\"pageId\") String pageId,\n Callback<Envelope<Page>> callback\n );\n\n /**\n * Appends new content to an existing page\n * specified by page id\n *\n * Note: This passes a blank Accept-Encoding header to\n * work around a known issue with the PATCH on this OneNote API\n *\n * @param encoding\n * @param version\n * @param pageId\n * @param body\n * @param callback\n */\n @PATCH(\"/{version}/me/notes/pages/{pageId}/content\")\n void patchPage(\n @Header(\"Accept-Encoding\") String encoding,\n @Path(\"version\") String version,\n @Path(\"pageId\") String pageId,\n @Body TypedString body,\n Callback<Envelope<Page>> callback\n );\n}",
"public class Page extends BaseVO {\n public String title;\n public String contentUrl;\n}",
"public class Section extends BaseVO {\n\n public String pagesUrl;\n public Notebook parentNotebook;\n public SectionGroup parentSectionGroup;\n\n @SerializedName(\"[email protected]\")\n public String parentSectionGroup_odata_context;\n\n @SerializedName(\"[email protected]\")\n public String parentNotebook_odata_context;\n\n}"
] | import com.google.gson.JsonArray;
import com.microsoft.o365_android_onenote_rest.R;
import com.microsoft.o365_android_onenote_rest.SnippetDetailFragment;
import com.microsoft.o365_android_onenote_rest.application.SnippetApp;
import com.microsoft.onenoteapi.service.OneNotePartsMap;
import com.microsoft.onenoteapi.service.PagesService;
import com.microsoft.onenoteapi.service.PatchCommand;
import com.microsoft.onenotevos.Envelope;
import com.microsoft.onenotevos.Page;
import com.microsoft.onenotevos.Section;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.joda.time.DateTime;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;
import timber.log.Timber;
import static com.microsoft.o365_android_onenote_rest.R.array.create_page_under_named_section;
import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_business_cards;
import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_image;
import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_note_tags;
import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_pdf;
import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_product_info;
import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_recipe;
import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_url_snapshot;
import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_web_page_snapshot;
import static com.microsoft.o365_android_onenote_rest.R.array.create_simple_page;
import static com.microsoft.o365_android_onenote_rest.R.array.delete_page;
import static com.microsoft.o365_android_onenote_rest.R.array.get_all_pages;
import static com.microsoft.o365_android_onenote_rest.R.array.get_page_as_html;
import static com.microsoft.o365_android_onenote_rest.R.array.get_pages_skip_and_top;
import static com.microsoft.o365_android_onenote_rest.R.array.meta_specific_page;
import static com.microsoft.o365_android_onenote_rest.R.array.page_append;
import static com.microsoft.o365_android_onenote_rest.R.array.pages_selected_meta;
import static com.microsoft.o365_android_onenote_rest.R.array.pages_specific_section;
import static com.microsoft.o365_android_onenote_rest.R.array.search_all_pages;
import static com.microsoft.o365_android_onenote_rest.R.array.specific_title; | /*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
*/
package com.microsoft.o365_android_onenote_rest.snippet;
public abstract class PagesSnippet<Result> extends AbstractSnippet<PagesService, Result> {
public PagesSnippet(Integer descriptionArray) {
super(SnippetCategory.pagesSnippetCategory, descriptionArray);
}
public PagesSnippet(Integer descriptionArray, Input input) {
super(SnippetCategory.pagesSnippetCategory, descriptionArray, input);
}
static PagesSnippet[] getPagesSnippets() {
return new PagesSnippet[]{
// Marker element
new PagesSnippet(null) {
@Override
public void request(
PagesService service
, Callback callback) {
// Not implemented
}
},
/*
* POST a new OneNote page in the section picked by the user
* HTTP POST https://www.onenote.com/api/beta/me/notes/sections/{id}/pages
* @see http://dev.onenote.com/docs#/reference/post-pages
*/
new PagesSnippet<Page>(create_simple_page, Input.Spinner) {
Map<String, Section> sectionMap = new HashMap<>();
String endpointVersion;
@Override
public void setUp(Services services, final retrofit.Callback<String[]> callback) {
fillSectionSpinner(services, callback, sectionMap);
}
@Override
public void request(
PagesService service, Callback<Page> callback) {
DateTime date = DateTime.now();
String simpleHtml = getSimplePageContentBody(SnippetApp
.getApp()
.getResources()
.openRawResource(R.raw.simple_page), date.toString(), null);
String contentType = "text/html; encoding=utf8";
TypedString typedString = new TypedString(simpleHtml) {
@Override
public String mimeType() {
return "text/html";
}
};
Section section = sectionMap.get(callback
.getParams()
.get(SnippetDetailFragment.ARG_SPINNER_SELECTION));
service.postPages(
contentType, //Content-Type value
getVersion(), //Version
section.id, //Section Id,
typedString, //HTML note body,
callback);
}
},
/*
* Creates a new page in a section referenced by title instead of Id
* HTTP POST https://www.onenote.com/api/beta/me/notes/pages{?sectionName}
* @see http://dev.onenote.com/docs#/reference/post-pages/v10menotespagessectionname
*/
new PagesSnippet<Envelope<Page>>(create_page_under_named_section, Input.Spinner) {
Map<String, Section> sectionMap = new HashMap<>();
@Override
public void setUp(Services services, final retrofit.Callback<String[]> callback) {
fillSectionSpinner(services, callback, sectionMap);
}
@Override
public void request(PagesService service, Callback<Envelope<Page>> callback) {
DateTime date = DateTime.now();
String simpleHtml = getSimplePageContentBody(SnippetApp
.getApp()
.getResources()
.openRawResource(R.raw.simple_page)
, date.toString()
, null);
TypedString typedString = new TypedString(simpleHtml) {
@Override
public String mimeType() {
return "text/html";
}
};
Section section = sectionMap.get(callback
.getParams()
.get(SnippetDetailFragment.ARG_SPINNER_SELECTION));
service.postPagesInSection(
"text/html; encoding=utf8",
getVersion(),
section.name,
typedString,
callback
);
}
},
/*
* Creates a page with an embedded image
* @see http://dev.onenote.com/docs#/reference/post-pages/v10menotespages
*/
new PagesSnippet<Envelope<Page>>(create_page_with_image, Input.Spinner) {
Map<String, Section> sectionMap = new HashMap<>();
@Override
public void setUp(Services services, final retrofit.Callback<String[]> callback) {
fillSectionSpinner(services, callback, sectionMap);
}
@Override
public void request(PagesService service, Callback<Envelope<Page>> callback) {
DateTime date = DateTime.now();
String imagePartName = "image1";
String simpleHtml = getSimplePageContentBody(SnippetApp
.getApp()
.getResources()
.openRawResource(R.raw.create_page_with_image)
, date.toString()
, imagePartName);
TypedString presentationString = new TypedString(simpleHtml) {
@Override
public String mimeType() {
return "text/html";
}
}; | OneNotePartsMap oneNotePartsMap = new OneNotePartsMap(presentationString); | 2 |
kmonaghan/Broadsheet.ie-Android | src/ie/broadsheet/app/dialog/MakeCommentDialog.java | [
"public class BaseFragmentActivity extends SherlockFragmentActivity {\n private ProgressDialog mProgressDialog;\n\n private SpiceManager spiceManager = new SpiceManager(BroadsheetServices.class);\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n mProgressDialog = new ProgressDialog(this);\n\n mProgressDialog.setIndeterminate(true);\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);\n\n EasyTracker.getInstance().setContext(this);\n\n }\n\n @Override\n protected void onStart() {\n spiceManager.start(this);\n super.onStart();\n\n EasyTracker.getInstance().activityStart(this);\n }\n\n @Override\n protected void onStop() {\n spiceManager.shouldStop();\n super.onStop();\n\n EasyTracker.getInstance().activityStop(this);\n }\n\n @Override\n protected void onPause() {\n mProgressDialog.dismiss();\n super.onPause();\n }\n\n public void onPreExecute(String message) {\n mProgressDialog.setMessage(message);\n mProgressDialog.show();\n }\n\n public void onPostExecute() {\n mProgressDialog.dismiss();\n }\n\n public SpiceManager getSpiceManager() {\n return spiceManager;\n }\n\n public void showError(String error) {\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n builder.setMessage(error).setPositiveButton(R.string.okay, null);\n\n builder.create().show();\n }\n}",
"public class BroadsheetApplication extends Application {\n private static BroadsheetApplication mApp = null;\n\n private List<Post> posts;\n\n public List<Post> getPosts() {\n return posts;\n }\n\n private Tracker mGaTracker;\n\n private GoogleAnalytics mGaInstance;\n\n public void setPosts(List<Post> posts) {\n if ((this.posts == null) || (posts == null)) {\n this.posts = posts;\n } else if (this.posts.size() > 0) {\n // this.posts.addAll(posts);\n for (Post post : posts) {\n this.posts.add(post);\n }\n } else {\n this.posts = posts;\n }\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n // Create global configuration and initialize ImageLoader with this configuration\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).build();\n ImageLoader.getInstance().init(config);\n\n this.posts = new ArrayList<Post>();\n\n Crashlytics.start(this);\n\n mGaInstance = GoogleAnalytics.getInstance(this);\n\n mGaTracker = mGaInstance.getTracker(\"UA-5653857-3\");\n\n mApp = this;\n }\n\n public Tracker getTracker() {\n return mGaTracker;\n }\n\n public static Context context() {\n return mApp.getApplicationContext();\n }\n\n}",
"public class Comment implements Serializable {\n private static final long serialVersionUID = 1L;\n\n @Key\n private int id;\n\n @Key\n private String name;\n\n @Key\n private String url;\n\n @Key\n private String date;\n\n @Key\n private String content;\n\n @Key\n private int parent;\n\n @Key\n private String avatar;\n\n @Key\n private String status;\n\n private String relativeTime;\n\n private TreeMap<String, Comment> childComment;\n\n private int childLevel = 0;\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 getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\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 getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public int getParent() {\n return parent;\n }\n\n public void setParent(int parent) {\n this.parent = parent;\n }\n\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public TreeMap<String, Comment> getChildComment() {\n return childComment;\n }\n\n public void setChildComment(TreeMap<String, Comment> childComment) {\n this.childComment = childComment;\n }\n\n public int getChildLevel() {\n return childLevel;\n }\n\n public void setChildLevel(int childLevel) {\n this.childLevel = childLevel;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((avatar == null) ? 0 : avatar.hashCode());\n result = prime * result + ((content == null) ? 0 : content.hashCode());\n result = prime * result + ((date == null) ? 0 : date.hashCode());\n result = prime * result + id;\n result = prime * result + ((name == null) ? 0 : name.hashCode());\n result = prime * result + parent;\n result = prime * result + ((status == null) ? 0 : status.hashCode());\n result = prime * result + ((url == null) ? 0 : url.hashCode());\n return result;\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 Comment other = (Comment) obj;\n if (avatar == null) {\n if (other.avatar != null)\n return false;\n } else if (!avatar.equals(other.avatar))\n return false;\n if (content == null) {\n if (other.content != null)\n return false;\n } else if (!content.equals(other.content))\n return false;\n if (date == null) {\n if (other.date != null)\n return false;\n } else if (!date.equals(other.date))\n return false;\n if (id != other.id)\n return false;\n if (name == null) {\n if (other.name != null)\n return false;\n } else if (!name.equals(other.name))\n return false;\n if (parent != other.parent)\n return false;\n if (status == null) {\n if (other.status != null)\n return false;\n } else if (!status.equals(other.status))\n return false;\n if (url == null) {\n if (other.url != null)\n return false;\n } else if (!url.equals(other.url))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Comment [id=\" + id + \", name=\" + name + \", url=\" + url + \", date=\" + date + \", content=\" + content\n + \", parent=\" + parent + \", avatar=\" + avatar + \", status=\" + status + \"]\";\n }\n\n @SuppressLint(\"SimpleDateFormat\")\n public String getRelativeTime() {\n if (relativeTime == null) {\n relativeTime = \"\";\n SimpleDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n Date result = null;\n try {\n result = df.parse(this.date);\n relativeTime = (String) DateUtils.getRelativeTimeSpanString(result.getTime(), new Date().getTime(),\n DateUtils.MINUTE_IN_MILLIS);\n\n } catch (ParseException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n return relativeTime;\n }\n}",
"public class MakeCommentRequest extends GoogleHttpClientSpiceRequest<Comment> {\n // private static final String TAG = \"MakeCommentRequest\";\n\n private String baseUrl;\n\n private int postId;\n\n private int commentId = 0;\n\n private String email;\n\n private String commentName;\n\n private String commentUrl;\n\n private String commentBody;\n\n public int getPostId() {\n return postId;\n }\n\n public void setPostId(int postId) {\n this.postId = postId;\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 getCommentName() {\n return commentName;\n }\n\n public void setCommentName(String commentName) {\n this.commentName = commentName;\n }\n\n public String getCommentUrl() {\n return commentUrl;\n }\n\n public void setCommentUrl(String commentUrl) {\n this.commentUrl = commentUrl;\n }\n\n public String getCommentBody() {\n return commentBody;\n }\n\n public void setCommentBody(String commentBody) {\n this.commentBody = commentBody;\n }\n\n public int getCommentId() {\n return commentId;\n }\n\n public void setCommentId(int commentId) {\n this.commentId = commentId;\n }\n\n public MakeCommentRequest() {\n super(Comment.class);\n\n this.baseUrl = BroadsheetApplication.context().getString(R.string.apiURL) + \"/?json=respond.submit_comment\";\n\n }\n\n @Override\n public Comment loadDataFromNetwork() throws Exception {\n GenericData data = new GenericData();\n data.put(\"post_id\", postId);\n data.put(\"email\", email);\n data.put(\"name\", commentName);\n if (commentUrl.length() > 0) {\n data.put(\"url\", commentUrl);\n }\n data.put(\"content\", commentBody);\n if (commentId > 0) {\n data.put(\"comment_parent\", commentId);\n }\n\n UrlEncodedContent content = new UrlEncodedContent(data);\n\n HttpRequest request = null;\n try {\n request = getHttpRequestFactory().buildPostRequest(new GenericUrl(baseUrl), content);\n } catch (IOException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n }\n request.setParser(new JacksonFactory().createJsonObjectParser());\n\n return request.execute().parseAs(getResultType());\n }\n\n}",
"public class BroadsheetServices extends GoogleHttpClientSpiceService {\n\n @Override\n public CacheManager createCacheManager(Application application) {\n CacheManager cacheManager = new CacheManager();\n\n JacksonObjectPersisterFactory jacksonObjectPersisterFactory;\n try {\n jacksonObjectPersisterFactory = new JacksonObjectPersisterFactory(application);\n cacheManager.addPersister(jacksonObjectPersisterFactory);\n } catch (CacheCreationException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n\n return cacheManager;\n }\n\n}"
] | import ie.broadsheet.app.BaseFragmentActivity;
import ie.broadsheet.app.BroadsheetApplication;
import ie.broadsheet.app.R;
import ie.broadsheet.app.model.json.Comment;
import ie.broadsheet.app.requests.MakeCommentRequest;
import ie.broadsheet.app.services.BroadsheetServices;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.octo.android.robospice.SpiceManager;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener; | package ie.broadsheet.app.dialog;
public class MakeCommentDialog extends SherlockDialogFragment implements OnClickListener {
public interface CommentMadeListener {
public void onCommentMade(Comment comment);
}
private CommentMadeListener mListener;
private static final String TAG = "MakeCommentDialog";
private SpiceManager spiceManager = new SpiceManager(BroadsheetServices.class);
private int postId;
private int commentId = 0;
private EditText email;
private EditText commenterName;
private EditText commenterUrl;
private EditText commentBody;
private Dialog dialog;
public int getPostId() {
return postId;
}
public void setPostId(int postId) {
this.postId = postId;
}
public int getCommentId() {
return commentId;
}
public void setCommentId(int commentId) {
this.commentId = commentId;
}
public void setCommentMadeListener(CommentMadeListener mListener) {
this.mListener = mListener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_make_comment, null);
commenterName = (EditText) view.findViewById(R.id.commenterName);
email = (EditText) view.findViewById(R.id.commenterEmail);
commenterUrl = (EditText) view.findViewById(R.id.commenterUrl);
commentBody = (EditText) view.findViewById(R.id.commentBody);
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
email.setText(sharedPref.getString("email", ""));
commenterName.setText(sharedPref.getString("commenterName", ""));
commenterUrl.setText(sharedPref.getString("commenterUrl", ""));
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(view)
// Add action buttons
.setPositiveButton(R.string.comment, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MakeCommentDialog.this.getDialog().cancel();
}
});
dialog = builder.create();
commenterName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
return dialog;
}
@Override
public void onStart() {
spiceManager.start(getActivity());
super.onStart();
AlertDialog d = (AlertDialog) getDialog();
if (d != null) {
Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(this);
}
((BroadsheetApplication) getActivity().getApplication()).getTracker().sendView("Post Comment");
}
@Override
public void onStop() {
spiceManager.shouldStop();
super.onStop();
}
@Override
public void onClick(View v) {
if (!validate()) {
return;
}
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("email", email.getText().toString());
editor.putString("commenterName", commenterName.getText().toString());
editor.putString("commenterUrl", commenterUrl.getText().toString());
editor.commit();
| MakeCommentRequest makeCommentRequest = new MakeCommentRequest(); | 3 |
mjdbc/mjdbc | src/test/java/com/github/mjdbc/test/DbValuesTest.java | [
"public class DbPreparedStatement<T> implements AutoCloseable {\n\n /**\n * Actual java.sql.PreparedStatement in use.\n */\n @NotNull\n public final PreparedStatement statement;\n\n /**\n * Mapper for the result. Used by methods like ${link {@link #query()} or {@link #queryList()}}\n */\n @NotNull\n public final DbMapper<T> resultMapper;\n\n /**\n * Mapping of parameter names to indexes.\n */\n @NotNull\n private final Map<String, List<Integer>> parametersMapping;\n\n @NotNull\n private final DbConnection dbConnection;\n\n public DbPreparedStatement(@NotNull DbConnection dbc, @NotNull String sql) throws SQLException {\n //noinspection unchecked\n this(dbc, sql, (DbMapper<T>) Mappers.VoidMapper, false);\n }\n\n public DbPreparedStatement(@NotNull DbConnection dbc, @NotNull String sql, @NotNull Class<T> resultClass) throws SQLException {\n //noinspection unchecked\n this(dbc, sql,\n Objects.requireNonNull(DbImpl.findOrResolveMapperByType(resultClass, null, (DbMapper<T>) dbc.db.getRegisteredMapperByType(resultClass)),\n () -> \"Mapper for class not found: \" + resultClass), false);\n }\n\n public DbPreparedStatement(@NotNull DbConnection dbc, @NotNull String sql, @NotNull DbMapper<T> resultMapper) throws SQLException {\n this(dbc, sql, resultMapper, false);\n }\n\n public DbPreparedStatement(@NotNull DbConnection dbc, @NotNull String sql, @NotNull DbMapper<T> resultMapper, boolean returnGeneratedKeys) throws SQLException {\n this.resultMapper = resultMapper;\n this.parametersMapping = new HashMap<>();\n this.dbConnection = dbc;\n String parsedSql = parse(sql, this.parametersMapping);\n statement = prepareStatement(dbc.getConnection(), parsedSql, returnGeneratedKeys);\n dbc.statementsToClose.add(this);\n }\n\n protected DbPreparedStatement(@NotNull DbConnection dbc, @NotNull String parsedSql, @NotNull DbMapper<T> resultMapper,\n @NotNull Map<String, List<Integer>> parametersMapping, boolean returnGeneratedKeys) throws SQLException {\n this.resultMapper = resultMapper;\n this.parametersMapping = parametersMapping;\n this.dbConnection = dbc;\n statement = prepareStatement(dbc.getConnection(), parsedSql, returnGeneratedKeys);\n dbc.statementsToClose.add(this);\n }\n\n @NotNull\n private static PreparedStatement prepareStatement(@NotNull Connection c, @NotNull String parsedSql, boolean returnGeneratedKeys) throws SQLException {\n return returnGeneratedKeys ? c.prepareStatement(parsedSql, Statement.RETURN_GENERATED_KEYS) : c.prepareStatement(parsedSql);\n }\n\n /**\n * Sets null for all fields matched by name.\n */\n @NotNull\n public DbPreparedStatement<T> setNull(@NotNull String name, @NotNull SQLType type) throws SQLException {\n for (int i : getIndexes(name)) {\n statement.setNull(i, type.getVendorTypeNumber());\n }\n return this;\n }\n\n /**\n * Sets boolean value for all fields matched by name.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, boolean value) throws SQLException {\n for (int i : getIndexes(name)) {\n statement.setBoolean(i, value);\n }\n return this;\n }\n\n /**\n * Sets int value for all fields matched by name.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, int value) throws SQLException {\n for (int i : getIndexes(name)) {\n statement.setInt(i, value);\n }\n return this;\n }\n\n /**\n * Sets int value for all fields matched by name. If value is null calls setNull for all fields.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, @Nullable DbInt value) throws SQLException {\n return value == null ? setNull(name, JDBCType.INTEGER) : set(name, value.getDbValue());\n }\n\n /**\n * Sets long value for all fields matched by name.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, long value) throws SQLException {\n for (int i : getIndexes(name)) {\n statement.setLong(i, value);\n }\n return this;\n }\n\n /**\n * Sets long value for all fields matched by name. If value is null calls setNull for all fields.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, @Nullable DbLong value) throws SQLException {\n return value == null ? setNull(name, JDBCType.BIGINT) : set(name, value.getDbValue());\n }\n\n /**\n * Sets float value for all fields matched by name.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, float value) throws SQLException {\n for (int i : getIndexes(name)) {\n statement.setFloat(i, value);\n }\n return this;\n }\n\n /**\n * Sets double value for all fields matched by name.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, double value) throws SQLException {\n for (int i : getIndexes(name)) {\n statement.setDouble(i, value);\n }\n return this;\n }\n\n /**\n * Sets BigDecimal value for all fields matched by name.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, @Nullable BigDecimal value) throws SQLException {\n for (int i : getIndexes(name)) {\n statement.setBigDecimal(i, value);\n }\n return this;\n }\n\n /**\n * Sets string value for all fields matched by name.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, @Nullable String value) throws SQLException {\n for (int i : getIndexes(name)) {\n statement.setString(i, value);\n }\n return this;\n }\n\n /**\n * Sets string value for all fields matched by name. If value is null - sets null.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, @Nullable DbString value) throws SQLException {\n return set(name, value == null ? null : value.getDbValue());\n }\n\n /**\n * Sets byte[] value for all fields matched by name.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, @Nullable byte[] value) throws SQLException {\n for (int i : getIndexes(name)) {\n statement.setBytes(i, value);\n }\n return this;\n }\n\n /**\n * Sets Timestamp value for all fields matched by name.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, @Nullable Timestamp value) throws SQLException {\n for (int i : getIndexes(name)) {\n statement.setTimestamp(i, value);\n }\n return this;\n }\n\n /**\n * Sets Timestamp value for all fields matched by name. If value is null - sets null.\n */\n @NotNull\n public DbPreparedStatement<T> set(@NotNull String name, @Nullable DbTimestamp value) throws SQLException {\n return set(name, value == null ? null : value.getDbValue());\n }\n\n /**\n * Sets all bean properties to named parameters.\n *\n * @param bean bean to map to named SQL parameters.\n * @return this.\n * @throws SQLException if anything bad happens during SQL operations or bean field accessors calls.\n */\n public DbPreparedStatement<T> bindBean(@NotNull Object bean) throws SQLException {\n return bindBean(dbConnection.db, bean, true);\n }\n\n /**\n * Sets all bean properties to named parameters.\n *\n * @param db database to use. This method call relies on binders registered in this database instance.\n * @param bean bean to map to named SQL parameters.\n * @param allowCustomFields if false and SQL contains keys not resolved with this bean - SQLException will be thrown.\n * @return this.\n * @throws SQLException if anything bad happens during SQL operations or bean field accessors calls.\n */\n @NotNull\n public DbPreparedStatement<T> bindBean(@NotNull Db db, @NotNull Object bean, boolean allowCustomFields) throws SQLException {\n List<BindInfo> binders = ((DbImpl) db).getBeanBinders(bean.getClass());\n for (String key : parametersMapping.keySet()) {\n BindInfo info = binders.stream().filter(i -> i.mappedName.equals(key)).findFirst().orElse(null);\n if (info == null) {\n if (allowCustomFields) {\n continue;\n }\n throw new SQLException(\"No mapping found for field: \" + key);\n }\n try {\n bindArg(this, info, getIndexes(key), bean);\n } catch (IllegalAccessException | InvocationTargetException e) {\n throw new SQLException(\"Error applying bean properties: \" + bean, e);\n }\n }\n return this;\n }\n\n protected static void bindArg(@NotNull DbPreparedStatement s, @NotNull DbImpl.BindInfo bi, @NotNull List<Integer> indexes, @NotNull Object bean) throws IllegalAccessException, InvocationTargetException, SQLException {\n for (Integer idx : indexes) {\n Object value = bi.field != null ? bi.field.get(bean) : bi.getter != null ? bi.getter.invoke(bean) : bean;\n //noinspection unchecked\n bi.binder.bind(s.statement, idx, value);\n }\n }\n\n\n /**\n * Executes sql statement and returns java.sql.ResultSet.\n */\n @NotNull\n public ResultSet executeQuery() throws SQLException {\n return statement.executeQuery();\n }\n\n /**\n * Executes sql statement and returns first result mapped using {@link #resultMapper}.\n */\n @Nullable\n public T query() throws SQLException {\n try (ResultSet r = executeQuery()) {\n if (r.next()) {\n return resultMapper.map(r);\n }\n return null;\n }\n }\n\n /**\n * Same as {@link #query()} but checks if result value is not null.\n * Throws {@link java.lang.NullPointerException} if value is null.\n */\n @NotNull\n public T queryNN() throws SQLException {\n T res = null;\n try (ResultSet r = statement.executeQuery()) {\n if (r.next()) {\n res = resultMapper.map(r);\n }\n Objects.requireNonNull(res);\n return res;\n }\n }\n\n /**\n * Executes sql statement and returns list of all values in result set mapped using {@link #resultMapper}.\n */\n @NotNull\n public List<T> queryList() throws SQLException {\n List<T> res = new ArrayList<>();\n try (ResultSet r = statement.executeQuery()) {\n while (r.next()) {\n res.add(resultMapper.map(r));\n }\n }\n return res;\n }\n\n /**\n * Executes insert method on wrapped statement.\n */\n public int insert() throws SQLException {\n return statement.executeUpdate();\n }\n\n @NotNull\n public T updateAndGetGeneratedKeys() throws SQLException {\n statement.executeUpdate();\n try (ResultSet r = statement.getGeneratedKeys()) {\n if (r.next()) {\n return resultMapper.map(r);\n }\n throw new SQLException(\"Result set is empty!\");\n }\n }\n\n /**\n * Runs {@link PreparedStatement#executeUpdate()} on wrapped statement and returns it's result.\n */\n public int update() throws SQLException {\n return statement.executeUpdate();\n }\n\n /**\n * Returns list of indexes for a given key.\n * If key is not found throws {@link IllegalArgumentException}\n */\n @NotNull\n public List<Integer> getIndexes(String name) {\n List<Integer> indexes = parametersMapping.get(name);\n if (indexes == null) {\n throw new IllegalArgumentException(\"Parameter not found: \" + name);\n }\n return indexes;\n }\n\n\n /**\n * Closes underlying sql statement.\n */\n @Override\n public void close() throws SQLException {\n statement.close();\n }\n\n // TODO: add mappings cache for parsed maps -> reuse DbConnection -> Db::cache!\n @NotNull\n protected static String parse(@NotNull String sql, @NotNull Map<String, List<Integer>> paramMap) {\n int length = sql.length();\n StringBuilder parsedQuery = new StringBuilder(length);\n boolean inSingleQuote = false;\n boolean inDoubleQuote = false;\n int index = 1;\n\n for (int i = 0; i < length; i++) {\n char c = sql.charAt(i);\n if (inSingleQuote) {\n if (c == '\\'') {\n inSingleQuote = false;\n }\n } else if (inDoubleQuote) {\n if (c == '\"') {\n inDoubleQuote = false;\n }\n } else {\n if (c == '\\'') {\n inSingleQuote = true;\n } else {\n if (c == '\"') {\n inDoubleQuote = true;\n } else {\n if (c == ':' && i + 1 < length && Character.isJavaIdentifierStart(sql.charAt(i + 1))) {\n int j = i + 2;\n while (j < length && Character.isJavaIdentifierPart(sql.charAt(j))) {\n j++;\n }\n String name = sql.substring(i + 1, j);\n c = '?'; // replace the parameter with a question mark\n i += name.length(); // skip past the end if the parameter\n\n List<Integer> indexList = paramMap.computeIfAbsent(name, k -> new ArrayList<>());\n indexList.add(index);\n\n index++;\n }\n }\n }\n }\n parsedQuery.append(c);\n }\n return parsedQuery.toString();\n }\n\n @NotNull\n public DbConnection getDbConnection() {\n return dbConnection;\n }\n\n @Override\n public String toString() {\n return \"DbPS[\" + statement + \"]\";\n }\n}",
"public final class Mappers {\n\n public static final DbMapper<BigDecimal> BigDecimalMapper = r -> r.getBigDecimal(1);\n\n public static final DbMapper<Boolean> BooleanMapper = r -> getNullable(r, r.getBoolean(1));\n\n public static final DbMapper<Byte> ByteMapper = r -> getNullable(r, r.getByte(1));\n\n public static final DbMapper<Character> CharacterMapper = r -> getNullable(r, (char) r.getInt(1));\n\n public static final DbMapper<Double> DoubleMapper = r -> getNullable(r, r.getDouble(1));\n\n public static final DbMapper<Float> FloatMapper = r -> getNullable(r, r.getFloat(1));\n\n public static final DbMapper<Integer> IntegerMapper = r -> getNullable(r, r.getInt(1));\n\n public static final DbMapper<Long> LongMapper = r -> getNullable(r, r.getLong(1));\n\n public static final DbMapper<Short> ShortMapper = r -> getNullable(r, r.getShort(1));\n\n public static final DbMapper<java.sql.Date> SqlDateMapper = r -> r.getDate(1);\n\n public static final DbMapper<java.sql.Time> SqlTimeMapper = r -> r.getTime(1);\n\n public static final DbMapper<String> StringMapper = r -> r.getString(1);\n\n public static final DbMapper<Timestamp> TimestampMapper = r -> r.getTimestamp(1);\n\n public static final DbMapper<java.util.Date> UtilDateMapper = r -> r.getDate(1);\n\n public static final DbMapper<Void> VoidMapper = r -> null;\n\n public static final Map<Class, DbMapper> BUILT_IN_MAPPERS = Collections.unmodifiableMap(new HashMap<Class, DbMapper>() {{\n\n // void methods.\n put(Void.TYPE, VoidMapper);\n put(Void.class, VoidMapper);\n\n // primitive types\n put(Boolean.TYPE, BooleanMapper);\n put(Boolean.class, BooleanMapper);\n put(Byte.TYPE, ByteMapper);\n put(Byte.class, ByteMapper);\n put(Character.TYPE, CharacterMapper);\n put(Character.class, CharacterMapper);\n put(Double.TYPE, DoubleMapper);\n put(Double.class, DoubleMapper);\n put(Short.TYPE, ShortMapper);\n put(Short.class, ShortMapper);\n put(Float.TYPE, FloatMapper);\n put(Float.class, FloatMapper);\n put(Integer.TYPE, IntegerMapper);\n put(Integer.class, IntegerMapper);\n put(Long.TYPE, LongMapper);\n put(Long.class, LongMapper);\n\n // jdbc related types\n put(BigDecimal.class, BigDecimalMapper);\n put(java.util.Date.class, UtilDateMapper);\n put(java.sql.Date.class, SqlDateMapper);\n put(java.sql.Time.class, SqlTimeMapper);\n put(Timestamp.class, TimestampMapper);\n\n // Common Java types\n put(String.class, StringMapper);\n\n // Collection wrappers are processed separately.\n }});\n\n public static <T> T getNullable(ResultSet r, T value) throws SQLException {\n return r.wasNull() ? null : value;\n }\n\n}",
"public interface DbInt {\n /**\n * @return database object representation.\n */\n int getDbValue();\n}",
"public interface DbLong {\n /**\n * @return database object representation.\n */\n long getDbValue();\n}",
"public interface DbString {\n /**\n * @return database object representation.\n */\n String getDbValue();\n}"
] | import com.github.mjdbc.DbPreparedStatement;
import com.github.mjdbc.Mappers;
import com.github.mjdbc.type.DbInt;
import com.github.mjdbc.type.DbLong;
import com.github.mjdbc.type.DbString;
import java.sql.Timestamp;
import org.junit.Test; | package com.github.mjdbc.test;
/**
* Tests for DbValue (Int,Long..) support.
*/
public class DbValuesTest extends DbTest {
@Test
public void checkDbInt() {
String login = db.execute(c -> new DbPreparedStatement<>(c, "SELECT login FROM users WHERE id = :id", Mappers.StringMapper)
.set("id", () -> 1)
.query());
assertEquals("u1", login);
}
@Test
public void checkDbIntNull() {
String login = db.execute(c -> new DbPreparedStatement<>(c, "SELECT login FROM users WHERE id = :id", Mappers.StringMapper) | .set("id", (DbInt) null) | 2 |
titorenko/quick-csv-streamer | src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java | [
"public static class ByteArrayChunk extends ReusableChunk {\n public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {});\n \n private final byte[] data;\n private final int length;\n private final boolean isLast;\n\n /**\n * @param data - underlying content\n * @param length - content length\n * @param isLast - is this chunk of is last\n * @param onFree - callback that will be called when data from this chunk has been fully consumed.\n */\n public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) {\n super(() -> onFree.accept(data));\n this.data = data;\n this.length = length;\n this.isLast = isLast;\n }\n\n public byte[] getData() {\n return data;\n }\n\n public int getLength() {\n return length;\n }\n\n public boolean isLast() {\n return isLast;\n }\n}",
"public static class CSVFileMetadata {\n \n public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('\"'));\n public static CSVFileMetadata TABS = new CSVFileMetadata('\\t', Optional.empty());\n \n public final char separator;\n public final Optional<Character> quote;\n\n public CSVFileMetadata(char separator, Optional<Character> quote) {\n this.separator = separator;\n this.quote = quote;\n }\n}",
"public class Pair<F, S> {\r\n \r\n public final F first;\r\n public final S second;\r\n\r\n /**\r\n * Constructor for a Pair.\r\n *\r\n * @param first the first object in the Pair\r\n * @param second the second object in the pair\r\n */\r\n public Pair(F first, S second) {\r\n this.first = first;\r\n this.second = second;\r\n }\r\n\r\n /**\r\n * Checks the two objects for equality by delegating to their respective\r\n * {@link Object#equals(Object)} methods.\r\n *\r\n * @param o the {@link Pair} to which this one is to be checked for equality\r\n * @return true if the underlying objects of the Pair are both considered\r\n * equal\r\n */\r\n @Override\r\n public boolean equals(Object o) {\r\n if (!(o instanceof Pair)) {\r\n return false;\r\n }\r\n Pair<?, ?> p = (Pair<?, ?>) o;\r\n return Objects.equals(p.first, first) && Objects.equals(p.second, second);\r\n }\r\n\r\n /**\r\n * Compute a hash code using the hash codes of the underlying objects\r\n *\r\n * @return a hashcode of the Pair\r\n */\r\n @Override\r\n public int hashCode() {\r\n return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());\r\n }\r\n \r\n @Override\r\n public String toString() {\r\n return first+\"=\"+second;\r\n }\r\n\r\n /**\r\n * Convenience method for creating an appropriately typed pair.\r\n * @param a the first object in the Pair\r\n * @param b the second object in the pair\r\n * @param <A> type of left element\r\n * @param <B> type of right element\r\n * @return a Pair that is templatized with the types of a and b\r\n */\r\n public static <A, B> Pair <A, B> of(A a, B b) {\r\n return new Pair<A, B>(a, b);\r\n }\r\n}",
"@FunctionalInterface\r\npublic static interface FunBiCharToBoolean {\r\n public boolean apply(char c, char q);\r\n}\r",
"@FunctionalInterface\r\npublic static interface FunBiCharToT<T> {\r\n public T apply(char c, char q);\r\n}\r",
"@FunctionalInterface\r\npublic static interface FunCharToBoolean {\r\n public boolean apply(char c);\r\n}\r",
"@FunctionalInterface\r\npublic static interface FunCharToT<T> {\r\n public T apply(char c);\r\n}\r"
] | import java.nio.charset.Charset;
import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk;
import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata;
import uk.elementarysoftware.quickcsv.functional.Pair;
import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean;
import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT;
import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean;
import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT; | @Override
public boolean nextLine() {
for(; hasMoreData() && buffer[currentIndex]!=CR && buffer[currentIndex]!=LF; currentIndex++);
return frontTrim();
}
public String currentLine() {
int startIdx = currentIndex;
for(; startIdx > start && buffer[startIdx]!=CR && buffer[startIdx]!=LF; startIdx--);
int endIdx = currentIndex;
for(; endIdx < end && buffer[endIdx]!=CR && buffer[endIdx]!=LF; endIdx++);
return new String(buffer, startIdx, endIdx - startIdx);
}
public Pair<ByteSlice, ByteSlice> splitOnLastLineEnd() {
int i = end-1;
for (;i >=currentIndex && buffer[i] != LF; i--);
SingleByteSlice prefix = new SingleByteSlice(src, buffer, currentIndex, i+1, charset);
SingleByteSlice suffix = new SingleByteSlice(src, buffer, i+1, end, charset);
return Pair.of(prefix, suffix);
}
public boolean skipUntil(final char c) {
boolean isFound = false;
while(currentIndex < end) {
if (buffer[currentIndex]==c) {
currentIndex++;
isFound = true;
break;
}
currentIndex++;
}
return isFound;
}
public boolean skipUntil(char c, char q) {
boolean inQuote = currentIndex < buffer.length && buffer[currentIndex] == q;
if (!inQuote) return skipUntil(c);
currentIndex++;
boolean isFound = false;
while(currentIndex < end) {
if (buffer[currentIndex]==c && buffer[currentIndex-1] == q) {
currentIndex++;
isFound = true;
break;
}
currentIndex++;
}
return isFound;
}
public ByteArrayField nextField(final char c) {
int startIndex = currentIndex;
int endIndex = currentIndex;
while(currentIndex < end) {
byte cur = buffer[currentIndex];
if (cur == c || cur == CR || cur == LF) {
endIndex = currentIndex;
if (cur == c)
currentIndex++;
break;
} else {
currentIndex++;
}
}
if (currentIndex == startIndex) return null;
if (currentIndex == end) endIndex = end;
fieldTemplateObject.modifyBounds(startIndex, endIndex);
return fieldTemplateObject;
}
@Override
public ByteArrayField nextField(char c, char q) {
boolean inQuote = currentIndex < buffer.length && buffer[currentIndex] == q;
if (!inQuote) return nextField(c);
currentIndex++;
int startIndex = currentIndex;
int endIndex = currentIndex;
while(currentIndex < end) {
byte cur = buffer[currentIndex];
if ((cur == c || cur == CR || cur == LF) && buffer[currentIndex-1] == q) {//there is an issue when we have escaped quote and then separator, but we ignore it for now
endIndex = currentIndex - 1;
if (cur == c) currentIndex++; //let frontTrim consume linebreaks later
break;
} else {
currentIndex++;
}
}
if (currentIndex == startIndex) return null;
if (currentIndex == end) {
if (buffer[end-1] == q) endIndex = end - 1; else endIndex = end;
}
fieldTemplateObject.modifyBounds(startIndex, endIndex, q);
return fieldTemplateObject;
}
@Override
public String toString() {
return new String(buffer, start, size());
}
@Override
public void incrementUse() {
src.incrementUseCount();
}
@Override
public void decremenentUse() {
src.decrementUseCount();
}
}
final class CompositeByteSlice implements ByteSlice {
private final SingleByteSlice prefix;
private final SingleByteSlice suffix;
private final ByteArrayField prefixFieldTemplateObject;
private final ByteArrayField suffixFieldTemplateObject;
private FunCharToT<ByteArrayField> nextFieldFun; | private FunBiCharToT<ByteArrayField> nextFieldFunQuoted; | 4 |
awvalenti/bauhinia | coronata/coronata-demos/src/main/java/com/github/awvalenti/bauhinia/coronata/demo5vibration/Vibration.java | [
"public class CoronataBuilder {\n\n\tprivate final CoronataConfig config = new CoronataConfig();\n\n\tprivate CoronataBuilder() {\n\t}\n\n\tpublic static CoronataBuilder beginConfig() {\n\t\treturn new CoronataBuilder();\n\t}\n\n\tpublic CoronataBuilder wiiRemotesExpected(int count) {\n\t\tconfig.setNumberOfWiiRemotes(count);\n\t\treturn this;\n\t}\n\n\tpublic CoronataBuilder timeoutInSeconds(int timeout) {\n\t\tconfig.setTimeoutInSeconds(timeout);\n\t\treturn this;\n\t}\n\n\tpublic CoronataBuilder onButton(CoronataButtonObserver o) {\n\t\tconfig.addObserver(o);\n\t\treturn this;\n\t}\n\n\tpublic CoronataBuilder onConnection(CoronataConnectionObserver o) {\n\t\tconfig.addObserver(o);\n\t\treturn this;\n\t}\n\n\tpublic CoronataBuilder onDisconnection(CoronataDisconnectionObserver o) {\n\t\tconfig.addObserver(o);\n\t\treturn this;\n\t}\n\n\tpublic CoronataBuilder\n\t\t\tonLifecycleEvents(CoronataLifecycleEventsObserver o) {\n\t\tconfig.addObserver(o);\n\t\treturn this;\n\t}\n\n\tpublic CoronataBuilder onLifecycleState(CoronataLifecycleStateObserver o) {\n\t\tconfig.addObserver(o);\n\t\treturn this;\n\t}\n\n\tpublic CoronataBuilder onPhase(CoronataPhaseObserver o) {\n\t\tconfig.addObserver(o);\n\t\treturn this;\n\t}\n\n\tpublic CoronataBuilder onError(CoronataErrorObserver o) {\n\t\tconfig.addObserver(o);\n\t\treturn this;\n\t}\n\n\tpublic CoronataConnectionProcess endConfig() {\n\t\tboolean isWindows =\n\t\t\t\tSystem.getProperty(\"os.name\").toLowerCase().contains(\"win\");\n\t\treturn isWindows ? new CoronataWindows(config) :\n\t\t\t\tnew CoronataLinux(config);\n\t}\n\n}",
"public class CoronataException extends Exception {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tCoronataException(Throwable cause, String detailMessage) {\n\t\tsuper(detailMessage, cause);\n\t}\n\n}",
"public interface CoronataWiiRemote {\n\n\tint LED_0 = 0x10, LED_1 = 0x20, LED_2 = 0x40, LED_3 = 0x80;\n\tint LEDS_NONE = 0x00, LEDS_ALL = LED_0 | LED_1 | LED_2 | LED_3;\n\n\tvoid setLightedLEDs(int ledsState);\n\n\tvoid startVibration();\n\n\tvoid stopVibration();\n\n\tvoid disconnect();\n\n}",
"public enum CoronataWiiRemoteButton {\n\n\tUP (2, 0x08),\n\tDOWN (2, 0x04),\n\tLEFT (2, 0x01),\n\tRIGHT(2, 0x02),\n\tA (3, 0x08),\n\tB (3, 0x04),\n\tMINUS(3, 0x10),\n\tHOME (3, 0x80),\n\tPLUS (2, 0x10),\n\tONE (3, 0x02),\n\tTWO (3, 0x01),\n\t;\n\n\tprivate final int byteIndex;\n\tprivate final int byteValue;\n\n\tprivate CoronataWiiRemoteButton(int byteIndex, int byteValue) {\n\t\tthis.byteIndex = byteIndex;\n\t\tthis.byteValue = byteValue;\n\t}\n\n\t// This method is not actually part of the API. It is here only\n\t// for implementation convenience. For this reason, it was given\n\t// package-level access. Thus, it is not exposed as API.\n\tboolean isPressedAccordingTo(byte[] dataReadFromWiiRemote) {\n\t\treturn (dataReadFromWiiRemote[byteIndex] & byteValue) != 0;\n\t}\n\n}",
"public interface CoronataButtonObserver {\n\n\tvoid buttonPressed(CoronataWiiRemoteButton button);\n\n\tvoid buttonReleased(CoronataWiiRemoteButton button);\n\n}",
"public interface CoronataConnectionObserver {\n\n\tvoid connected(CoronataWiiRemote wiiRemote);\n\n}",
"public interface CoronataErrorObserver {\n\n\tvoid errorOccurred(CoronataException e);\n\n}"
] | import com.github.awvalenti.bauhinia.coronata.CoronataBuilder;
import com.github.awvalenti.bauhinia.coronata.CoronataException;
import com.github.awvalenti.bauhinia.coronata.CoronataWiiRemote;
import com.github.awvalenti.bauhinia.coronata.CoronataWiiRemoteButton;
import com.github.awvalenti.bauhinia.coronata.observers.CoronataButtonObserver;
import com.github.awvalenti.bauhinia.coronata.observers.CoronataConnectionObserver;
import com.github.awvalenti.bauhinia.coronata.observers.CoronataErrorObserver;
| package com.github.awvalenti.bauhinia.coronata.demo5vibration;
public class Vibration implements
CoronataConnectionObserver,
CoronataButtonObserver,
CoronataErrorObserver {
| private CoronataWiiRemote wiiRemote;
| 2 |
fzakaria/WaterFlow | src/main/java/com/github/fzakaria/waterflow/poller/DecisionPoller.java | [
"public abstract class Workflow<InputType,OutputType> {\n\n protected final Logger log = LoggerFactory.getLogger(getClass());\n\n public abstract Name name();\n\n public abstract Version version();\n /**\n * Workflow name and version glued together to make a key.\n */\n @Value.Derived\n public Key key() {\n return Key.of(name(), version());\n }\n\n public abstract TypeToken<InputType> inputType();\n\n public abstract TypeToken<OutputType> outputType();\n\n public abstract DataConverter dataConverter();\n\n /** Optional description to register with workflow */\n @Value.Default\n public Description description() {\n return DEFAULT_DESCRIPTION;\n }\n\n /**\n * The total duration for this workflow execution.\n * Pass null unit or duration <= 0 for default timeout period of 365 days.\n * Default is 365 days.\n *\n * @see StartWorkflowExecutionRequest#executionStartToCloseTimeout\n */\n @Value.Default\n public Duration executionStartToCloseTimeout() {\n return SWF_TIMEOUT_YEAR;\n }\n\n /**\n * Specifies the maximum duration of <b>decision</b> tasks for this workflow execution.\n * Pass null unit or duration <= 0 for a timeout of NONE.\n * <p/>\n * Defaults to one minute, which should be plenty of time deciders that don't need to\n * connect to external services to make the next decision.\n *\n * @see StartWorkflowExecutionRequest#taskStartToCloseTimeout\n */\n @Value.Default\n public Duration taskStartToCloseTimeout() {\n return SWF_TIMEOUT_DECISION_DEFAULT;\n }\n\n /**\n * defaults to TERMINATE\n *\n * @see StartWorkflowExecutionRequest#childPolicy\n */\n @Value.Default\n public ChildPolicy childPolicy() {\n return ChildPolicy.TERMINATE; // sensible default\n }\n\n /** SWF task list this workflow is/will be xecuted under if none given in submissoin*/\n @Value.Default\n public TaskListName taskList() {\n return DEFAULT_TASK_LIST;\n }\n\n @Value.Check\n protected void check() {\n Preconditions.checkState(executionStartToCloseTimeout().compareTo(SWF_TIMEOUT_YEAR) <= 0,\n \"'executionStartToCloseTimeout' is longer than supported max timeout\");\n }\n\n /**\n * If available, return the input string given to this workflow when it was initiated on SWF.\n * @return the input or null if not available\n */\n public CompletionStage<InputType> workflowInput(List<Event> events) {\n return workflowStartedEvent(events).thenApply(e -> dataConverter().fromData(e.input(), inputType().getType()));\n }\n\n /**\n * If available return the start date of the workflow when it was initiated on SWF.\n * <p/>\n * @return the workflow start date or null if not available\n */\n public CompletionStage<Instant> workflowStartDate(List<Event> events) {\n return workflowStartedEvent(events).thenApply(Event::eventTimestamp);\n }\n\n\n private CompletionStage<Event> workflowStartedEvent(List<Event> events) {\n return events.stream().filter(e -> e.type() == WorkflowExecutionStarted)\n .findFirst().map(CompletableFuture::completedFuture).orElse( new CompletableFuture<>());\n }\n\n\n /**\n * Subclasses add zero or more decisions to the parameter during a decision task.\n * A final {@link DecisionType#CompleteWorkflowExecution} or {@link DecisionType#FailWorkflowExecution}\n * should be returned to indicate the workflow is complete. These decisions can be added by\n * {@link Action} instances automatically given their final state.\n * <p/>\n * An {@link DecisionType#FailWorkflowExecution} decision will be decided by the {@link DecisionPoller} if an unhandled exception is thrown\n * by this method.\n *\n * @see #createFailWorkflowExecutionDecision\n */\n public abstract CompletionStage<OutputType> decide(DecisionContext decisionContext);\n\n /**\n * Called if an external process issued a {@link EventType#WorkflowExecutionCancelRequested} for this workflow.\n * By default will simply add a {@link DecisionType#CancelWorkflowExecution} decision. Subclasses\n * can override this method to gracefully shut down a more complex workflow.\n */\n public void onCancelRequested(Event cancelEvent, List<Decision> decisions) {\n decisions.add(createCancelWorkflowExecutionDecision(cancelEvent.details()));\n }\n\n\n public static Decision createCompleteWorkflowExecutionDecision(String result) {\n return new Decision()\n .withDecisionType(DecisionType.CompleteWorkflowExecution)\n .withCompleteWorkflowExecutionDecisionAttributes(\n new CompleteWorkflowExecutionDecisionAttributes()\n .withResult(trimToMaxLength(result, MAX_DETAILS_LENGTH))\n );\n }\n\n public static Decision createCancelWorkflowExecutionDecision(String result) {\n return new Decision()\n .withDecisionType(DecisionType.CancelWorkflowExecution)\n .withCancelWorkflowExecutionDecisionAttributes(\n new CancelWorkflowExecutionDecisionAttributes()\n .withDetails(trimToMaxLength(result, MAX_DETAILS_LENGTH)));\n }\n\n /**\n * Create a fail workflow reason by combining a target name and message.\n *\n * @param target target name, optional, usually the <code>toString()</code> of the object that caused an error.\n * @param message error message\n *\n * @return message if target is null, otherwise target and message combined into a single string\n */\n public static String createFailReasonString(String target, String message) {\n String fail = target == null ? message : format(\"%s:%n%s\", target, message);\n return trimToMaxLength(fail, MAX_REASON_LENGTH);\n }\n\n public static Decision createFailWorkflowExecutionDecision(String target, String reason, String details) {\n return new Decision()\n .withDecisionType(DecisionType.FailWorkflowExecution)\n .withFailWorkflowExecutionDecisionAttributes(\n new FailWorkflowExecutionDecisionAttributes()\n .withReason(createFailReasonString(target, reason))\n .withDetails(trimToMaxLength(details, MAX_DETAILS_LENGTH))\n );\n }\n\n}",
"public interface DataConverter {\n\n /**\n * Given any input object return the String representation of it\n * @param input The object to serialize\n * @return The serialized string\n * @throws DataConverterException if anything goes awry\n */\n String toData(Object input) throws DataConverterException;\n\n /**\n * Given a input string and a target type, coerce the string to it\n * @param input The serialized version of the final output\n * @param type The type to be converted to\n * @return The deserialized result\n * @throws DataConverterException if anything goes awry\n */\n <T> T fromData(String input, Type type) throws DataConverterException;\n\n}",
"@Value.Immutable\npublic abstract class Event implements Comparable<Event> {\n\n public abstract HistoryEvent historyEvent();\n\n /**\n * All history events are required since we need to find the previous events\n * they might refer to.\n */\n @Value.Auxiliary\n public abstract List<HistoryEvent> historyEvents();\n\n public static List<Event> fromHistoryEvents(List<HistoryEvent> historyEvents) {\n return historyEvents.stream()\n .map(h -> ImmutableEvent.builder().historyEvent(h).historyEvents(historyEvents).build())\n .sorted().collect(toList());\n }\n\n public EventType type() { return EventType.valueOf(historyEvent().getEventType()); }\n\n public Long id() { return historyEvent().getEventId(); }\n\n public Instant eventTimestamp() { return historyEvent().getEventTimestamp().toInstant(); }\n\n public TaskType task() {\n if (WorkflowExecutionStarted == type()) { return WORKFLOW_EXECUTION; }\n if (WorkflowExecutionCancelRequested == type()) { return WORKFLOW_EXECUTION; }\n if (WorkflowExecutionCompleted == type()) { return WORKFLOW_EXECUTION; }\n if (CompleteWorkflowExecutionFailed == type()) { return WORKFLOW_EXECUTION; }\n if (WorkflowExecutionFailed == type()) { return WORKFLOW_EXECUTION; }\n if (FailWorkflowExecutionFailed == type()) { return WORKFLOW_EXECUTION; }\n if (WorkflowExecutionTimedOut == type()) { return WORKFLOW_EXECUTION; }\n if (WorkflowExecutionCanceled == type()) { return WORKFLOW_EXECUTION; }\n if (CancelWorkflowExecutionFailed == type()) { return WORKFLOW_EXECUTION; }\n if (WorkflowExecutionContinuedAsNew == type()) { return CONTINUE_AS_NEW; }\n if (ContinueAsNewWorkflowExecutionFailed == type()) { return CONTINUE_AS_NEW; }\n if (WorkflowExecutionTerminated == type()) { return WORKFLOW_EXECUTION; }\n if (DecisionTaskScheduled == type()) { return DECISION; }\n if (DecisionTaskStarted == type()) { return DECISION; }\n if (DecisionTaskCompleted == type()) { return DECISION; }\n if (DecisionTaskTimedOut == type()) { return DECISION; }\n if (ActivityTaskScheduled == type()) { return ACTIVITY; }\n if (ScheduleActivityTaskFailed == type()) { return ACTIVITY; }\n if (ActivityTaskStarted == type()) { return ACTIVITY; }\n if (ActivityTaskCompleted == type()) { return ACTIVITY; }\n if (ActivityTaskFailed == type()) { return ACTIVITY; }\n if (ActivityTaskTimedOut == type()) { return ACTIVITY; }\n if (ActivityTaskCanceled == type()) { return ACTIVITY; }\n if (ActivityTaskCancelRequested == type()) { return ACTIVITY; }\n if (RequestCancelActivityTaskFailed == type()) { return ACTIVITY; }\n if (WorkflowExecutionSignaled == type()) { return WORKFLOW_SIGNALED; }\n if (MarkerRecorded == type()) { return RECORD_MARKER; }\n if (RecordMarkerFailed == type()) { return RECORD_MARKER; }\n if (TimerStarted == type()) { return TIMER; }\n if (StartTimerFailed == type()) { return TIMER; }\n if (TimerFired == type()) { return TIMER; }\n if (TimerCanceled == type()) { return TIMER; }\n if (CancelTimerFailed == type()) { return TIMER; }\n if (StartChildWorkflowExecutionInitiated == type()) { return START_CHILD_WORKFLOW; }\n if (StartChildWorkflowExecutionFailed == type()) { return START_CHILD_WORKFLOW; }\n if (ChildWorkflowExecutionStarted == type()) { return START_CHILD_WORKFLOW; }\n if (ChildWorkflowExecutionCompleted == type()) { return START_CHILD_WORKFLOW; }\n if (ChildWorkflowExecutionFailed == type()) { return START_CHILD_WORKFLOW; }\n if (ChildWorkflowExecutionTimedOut == type()) { return START_CHILD_WORKFLOW; }\n if (ChildWorkflowExecutionCanceled == type()) { return START_CHILD_WORKFLOW; }\n if (ChildWorkflowExecutionTerminated == type()) { return START_CHILD_WORKFLOW; }\n if (SignalExternalWorkflowExecutionInitiated == type()) { return SIGNAL_EXTERNAL_WORKFLOW; }\n if (SignalExternalWorkflowExecutionFailed == type()) { return SIGNAL_EXTERNAL_WORKFLOW; }\n if (ExternalWorkflowExecutionSignaled == type()) { return SIGNAL_EXTERNAL_WORKFLOW; }\n if (RequestCancelExternalWorkflowExecutionInitiated == type()) { return CANCEL_EXTERNAL_WORKFLOW; }\n if (RequestCancelExternalWorkflowExecutionFailed == type()) { return CANCEL_EXTERNAL_WORKFLOW; }\n if (ExternalWorkflowExecutionCancelRequested == type()) { return CANCEL_EXTERNAL_WORKFLOW; }\n throw new IllegalArgumentException(\"Unknown EventType \" + type());\n }\n\n public EventState state() {\n if (WorkflowExecutionStarted == type()) { return INITIAL; }\n if (WorkflowExecutionCancelRequested == type()) { return ACTIVE; }\n if (WorkflowExecutionCompleted == type()) { return SUCCESS; }\n if (CompleteWorkflowExecutionFailed == type()) { return ERROR; }\n if (WorkflowExecutionFailed == type()) { return ERROR; }\n if (FailWorkflowExecutionFailed == type()) { return ERROR; }\n if (WorkflowExecutionTimedOut == type()) { return ERROR; }\n if (WorkflowExecutionCanceled == type()) { return ERROR; }\n if (CancelWorkflowExecutionFailed == type()) { return ERROR; }\n if (WorkflowExecutionContinuedAsNew == type()) { return INITIAL; }\n if (ContinueAsNewWorkflowExecutionFailed == type()) { return ERROR; }\n if (WorkflowExecutionTerminated == type()) { return ERROR; }\n if (DecisionTaskScheduled == type()) { return INITIAL; }\n if (DecisionTaskStarted == type()) { return ACTIVE; }\n if (DecisionTaskCompleted == type()) { return SUCCESS; }\n if (DecisionTaskTimedOut == type()) { return ERROR; }\n if (ActivityTaskScheduled == type()) { return INITIAL; }\n if (ScheduleActivityTaskFailed == type()) { return ERROR; }\n if (ActivityTaskStarted == type()) { return ACTIVE; }\n if (ActivityTaskCompleted == type()) { return SUCCESS; }\n if (ActivityTaskFailed == type()) { return ERROR; }\n if (ActivityTaskTimedOut == type()) { return ERROR; }\n if (ActivityTaskCanceled == type()) { return ERROR; }\n if (ActivityTaskCancelRequested == type()) { return ERROR; }\n if (RequestCancelActivityTaskFailed == type()) { return ERROR; }\n if (WorkflowExecutionSignaled == type()) { return SUCCESS; }\n if (MarkerRecorded == type()) { return INITIAL; }\n if (RecordMarkerFailed == type()) { return ERROR; }\n if (TimerStarted == type()) { return INITIAL; }\n if (StartTimerFailed == type()) { return ERROR; }\n if (TimerFired == type()) { return SUCCESS; }\n if (TimerCanceled == type()) { return SUCCESS; }\n if (CancelTimerFailed == type()) { return ACTIVE; }\n if (StartChildWorkflowExecutionInitiated == type()) { return INITIAL; }\n if (StartChildWorkflowExecutionFailed == type()) { return ERROR; }\n if (ChildWorkflowExecutionStarted == type()) { return ACTIVE; }\n if (ChildWorkflowExecutionCompleted == type()) { return SUCCESS; }\n if (ChildWorkflowExecutionFailed == type()) { return ERROR; }\n if (ChildWorkflowExecutionTimedOut == type()) { return ERROR; }\n if (ChildWorkflowExecutionCanceled == type()) { return ERROR; }\n if (ChildWorkflowExecutionTerminated == type()) { return ERROR; }\n if (SignalExternalWorkflowExecutionInitiated == type()) { return INITIAL; }\n if (SignalExternalWorkflowExecutionFailed == type()) { return ERROR; }\n if (ExternalWorkflowExecutionSignaled == type()) { return SUCCESS; }\n if (RequestCancelExternalWorkflowExecutionInitiated == type()) { return INITIAL; }\n if (RequestCancelExternalWorkflowExecutionFailed == type()) { return ERROR; }\n if (ExternalWorkflowExecutionCancelRequested == type()) { return SUCCESS; }\n throw new IllegalArgumentException(\"Unknown EventType \" + type());\n }\n\n public Long initialEventId() {\n if (WorkflowExecutionStarted == type()) { return historyEvent().getEventId(); }\n if (WorkflowExecutionCancelRequested == type()) { return historyEvent().getEventId(); }\n if (WorkflowExecutionCompleted == type()) { return historyEvent().getEventId(); }\n if (CompleteWorkflowExecutionFailed == type()) { return historyEvent().getEventId(); }\n if (WorkflowExecutionFailed == type()) { return historyEvent().getEventId(); }\n if (FailWorkflowExecutionFailed == type()) { return historyEvent().getEventId(); }\n if (WorkflowExecutionTimedOut == type()) { return historyEvent().getEventId(); }\n if (WorkflowExecutionCanceled == type()) { return historyEvent().getEventId(); }\n if (CancelWorkflowExecutionFailed == type()) { return historyEvent().getEventId(); }\n if (WorkflowExecutionContinuedAsNew == type()) { return historyEvent().getEventId(); }\n if (ContinueAsNewWorkflowExecutionFailed == type()) { return historyEvent().getEventId(); }\n if (WorkflowExecutionTerminated == type()) { return historyEvent().getEventId(); }\n if (DecisionTaskScheduled == type()) { return historyEvent().getEventId(); }\n if (DecisionTaskStarted == type()) { return historyEvent().getEventId(); }\n if (DecisionTaskCompleted == type()) { return historyEvent().getDecisionTaskCompletedEventAttributes().getScheduledEventId(); }\n if (DecisionTaskTimedOut == type()) { return historyEvent().getEventId(); }\n if (ActivityTaskScheduled == type()) { return historyEvent().getEventId(); }\n if (ScheduleActivityTaskFailed == type()) { return historyEvent().getEventId(); }\n if (ActivityTaskStarted == type()) { return historyEvent().getActivityTaskStartedEventAttributes().getScheduledEventId(); }\n if (ActivityTaskCompleted == type()) { return historyEvent().getActivityTaskCompletedEventAttributes().getScheduledEventId(); }\n if (ActivityTaskFailed == type()) { return historyEvent().getActivityTaskFailedEventAttributes().getScheduledEventId(); }\n if (ActivityTaskTimedOut == type()) { return historyEvent().getActivityTaskTimedOutEventAttributes().getScheduledEventId(); }\n if (ActivityTaskCanceled == type()) { return historyEvent().getActivityTaskCanceledEventAttributes().getScheduledEventId(); }\n if (ActivityTaskCancelRequested == type()) { return historyEvent().getEventId(); }\n if (RequestCancelActivityTaskFailed == type()) { return historyEvent().getEventId(); }\n if (WorkflowExecutionSignaled == type()) { return historyEvent().getEventId(); }\n if (MarkerRecorded == type()) { return historyEvent().getEventId(); }\n if (RecordMarkerFailed == type()) { return historyEvent().getEventId(); }\n if (TimerStarted == type()) { return historyEvent().getEventId(); }\n if (StartTimerFailed == type()) { return null; }\n if (TimerFired == type()) { return historyEvent().getTimerFiredEventAttributes().getStartedEventId(); }\n if (TimerCanceled == type()) { return historyEvent().getTimerCanceledEventAttributes().getStartedEventId(); }\n if (CancelTimerFailed == type()) { return historyEvent().getEventId(); }\n if (StartChildWorkflowExecutionInitiated == type()) { return historyEvent().getEventId(); }\n if (StartChildWorkflowExecutionFailed == type()) { return historyEvent().getStartChildWorkflowExecutionFailedEventAttributes().getInitiatedEventId(); }\n if (ChildWorkflowExecutionStarted == type()) { return historyEvent().getChildWorkflowExecutionStartedEventAttributes().getInitiatedEventId(); }\n if (ChildWorkflowExecutionCompleted == type()) { return historyEvent().getChildWorkflowExecutionCompletedEventAttributes().getInitiatedEventId(); }\n if (ChildWorkflowExecutionFailed == type()) { return historyEvent().getChildWorkflowExecutionFailedEventAttributes().getInitiatedEventId(); }\n if (ChildWorkflowExecutionTimedOut == type()) { return historyEvent().getChildWorkflowExecutionTimedOutEventAttributes().getInitiatedEventId(); }\n if (ChildWorkflowExecutionCanceled == type()) { return historyEvent().getChildWorkflowExecutionCanceledEventAttributes().getInitiatedEventId(); }\n if (ChildWorkflowExecutionTerminated == type()) { return historyEvent().getChildWorkflowExecutionTerminatedEventAttributes().getInitiatedEventId(); }\n if (SignalExternalWorkflowExecutionInitiated == type()) { return historyEvent().getEventId(); }\n if (SignalExternalWorkflowExecutionFailed == type()) { return historyEvent().getSignalExternalWorkflowExecutionFailedEventAttributes().getInitiatedEventId(); }\n if (ExternalWorkflowExecutionSignaled == type()) { return historyEvent().getExternalWorkflowExecutionSignaledEventAttributes().getInitiatedEventId(); }\n if (RequestCancelExternalWorkflowExecutionInitiated == type()) { return historyEvent().getEventId(); }\n if (RequestCancelExternalWorkflowExecutionFailed == type()) { return historyEvent().getEventId(); }\n if (ExternalWorkflowExecutionCancelRequested == type()) { return historyEvent().getEventId(); }\n throw new IllegalArgumentException(\"Unknown EventType \" + type());\n }\n\n public ActionId actionId() {\n if (WorkflowExecutionStarted == type()) { return null; }\n if (WorkflowExecutionCancelRequested == type()) { return null; }\n if (WorkflowExecutionCompleted == type()) { return null; }\n if (CompleteWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionFailed == type()) { return null; }\n if (FailWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionTimedOut == type()) { return null; }\n if (WorkflowExecutionCanceled == type()) { return null; }\n if (CancelWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionContinuedAsNew == type()) { return null; }\n if (ContinueAsNewWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionTerminated == type()) { return null; }\n if (DecisionTaskScheduled == type()) { return null; }\n if (DecisionTaskStarted == type()) { return null; }\n if (DecisionTaskCompleted == type()) { return null; }\n if (DecisionTaskTimedOut == type()) { return null; }\n if (ActivityTaskScheduled == type()) { return ActionId.of(historyEvent().getActivityTaskScheduledEventAttributes().getActivityId()); }\n if (ScheduleActivityTaskFailed == type()) { return ActionId.of(historyEvent().getScheduleActivityTaskFailedEventAttributes().getActivityId()); }\n if (ActivityTaskStarted == type()) {\n long scheduledEventId = historyEvent().getActivityTaskStartedEventAttributes().getScheduledEventId();\n Optional<HistoryEvent> scheduledEvent = historyEvents().stream().filter(he -> he.getEventId() == scheduledEventId).findFirst();\n assert scheduledEvent.isPresent() : \"If we have task started then there must be scheduled event\";\n return ImmutableEvent.builder().from(this).historyEvent(scheduledEvent.get()).build().actionId();\n }\n if (ActivityTaskCompleted == type()) {\n long scheduledEventId = historyEvent().getActivityTaskCompletedEventAttributes().getScheduledEventId();\n Optional<HistoryEvent> scheduledEvent = historyEvents().stream().filter(he -> he.getEventId() == scheduledEventId).findFirst();\n assert scheduledEvent.isPresent() : \"If we have task completed then there must be scheduled event\";\n return ImmutableEvent.builder().from(this).historyEvent(scheduledEvent.get()).build().actionId();\n }\n if (ActivityTaskFailed == type()) {\n long scheduledEventId = historyEvent().getActivityTaskFailedEventAttributes().getScheduledEventId();\n Optional<HistoryEvent> scheduledEvent = historyEvents().stream().filter(he -> he.getEventId() == scheduledEventId).findFirst();\n assert scheduledEvent.isPresent() : \"If we have task failed then there must be scheduled event\";\n return ImmutableEvent.builder().from(this).historyEvent(scheduledEvent.get()).build().actionId();\n }\n if (ActivityTaskTimedOut == type()) {\n long scheduledEventId = historyEvent().getActivityTaskTimedOutEventAttributes().getScheduledEventId();\n Optional<HistoryEvent> scheduledEvent = historyEvents().stream().filter(he -> he.getEventId() == scheduledEventId).findFirst();\n assert scheduledEvent.isPresent() : \"If we have task timeout then there must be scheduled event\";\n return ImmutableEvent.builder().from(this).historyEvent(scheduledEvent.get()).build().actionId();\n }\n if (ActivityTaskCanceled == type()) {\n long scheduledEventId = historyEvent().getActivityTaskCanceledEventAttributes().getScheduledEventId();\n Optional<HistoryEvent> scheduledEvent = historyEvents().stream().filter(he -> he.getEventId() == scheduledEventId).findFirst();\n assert scheduledEvent.isPresent() : \"If we have task cancelled then there must be scheduled event\";\n return ImmutableEvent.builder().from(this).historyEvent(scheduledEvent.get()).build().actionId();\n }\n if (ActivityTaskCancelRequested == type()) { return null; }\n if (RequestCancelActivityTaskFailed == type()) { return null; }\n if (WorkflowExecutionSignaled == type()) { return ActionId.of(historyEvent().getWorkflowExecutionSignaledEventAttributes().getSignalName()); }\n if (MarkerRecorded == type()) { return ActionId.of(historyEvent().getMarkerRecordedEventAttributes().getMarkerName()); }\n if (RecordMarkerFailed == type()) { return null; }\n if (TimerStarted == type()) { return ActionId.of(historyEvent().getTimerStartedEventAttributes().getTimerId()); }\n if (StartTimerFailed == type()) { return ActionId.of(historyEvent().getStartTimerFailedEventAttributes().getTimerId()); }\n if (TimerFired == type()) { return ActionId.of(historyEvent().getTimerFiredEventAttributes().getTimerId()); }\n if (TimerCanceled == type()) { return ActionId.of(historyEvent().getTimerCanceledEventAttributes().getTimerId()); }\n if (CancelTimerFailed == type()) { return ActionId.of(historyEvent().getCancelTimerFailedEventAttributes().getTimerId()); }\n if (StartChildWorkflowExecutionInitiated == type()) { return ActionId.of(historyEvent().getStartChildWorkflowExecutionInitiatedEventAttributes().getControl()); }\n if (StartChildWorkflowExecutionFailed == type()) { return null; }\n if (ChildWorkflowExecutionStarted == type()) { return null; }\n if (ChildWorkflowExecutionCompleted == type()) { return null; }\n if (ChildWorkflowExecutionFailed == type()) { return null; }\n if (ChildWorkflowExecutionTimedOut == type()) { return null; }\n if (ChildWorkflowExecutionCanceled == type()) { return null; }\n if (ChildWorkflowExecutionTerminated == type()) { return null; }\n if (SignalExternalWorkflowExecutionInitiated == type()) { return ActionId.of(historyEvent().getSignalExternalWorkflowExecutionInitiatedEventAttributes().getSignalName()); }\n if (SignalExternalWorkflowExecutionFailed == type()) { return null; }\n if (ExternalWorkflowExecutionSignaled == type()) { return null; }\n if (RequestCancelExternalWorkflowExecutionInitiated == type()) { return ActionId.of(historyEvent().getRequestCancelExternalWorkflowExecutionInitiatedEventAttributes().getControl()); }\n if (RequestCancelExternalWorkflowExecutionFailed == type()) { return ActionId.of(historyEvent().getRequestCancelExternalWorkflowExecutionFailedEventAttributes().getControl()); }\n if (ExternalWorkflowExecutionCancelRequested == type()) { return null; }\n throw new IllegalArgumentException(\"Unknown EventType \" + type());\n }\n\n public String input() {\n if (WorkflowExecutionStarted == type()) { return historyEvent().getWorkflowExecutionStartedEventAttributes().getInput(); }\n if (WorkflowExecutionCancelRequested == type()) { return null; }\n if (WorkflowExecutionCompleted == type()) { return null; }\n if (CompleteWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionFailed == type()) { return null; }\n if (FailWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionTimedOut == type()) { return null; }\n if (WorkflowExecutionCanceled == type()) { return null; }\n if (CancelWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionContinuedAsNew == type()) { return historyEvent().getWorkflowExecutionContinuedAsNewEventAttributes().getInput(); }\n if (ContinueAsNewWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionTerminated == type()) { return null; }\n if (DecisionTaskScheduled == type()) { return null; }\n if (DecisionTaskStarted == type()) { return null; }\n if (DecisionTaskCompleted == type()) { return null; }\n if (DecisionTaskTimedOut == type()) { return null; }\n if (ActivityTaskScheduled == type()) { return historyEvent().getActivityTaskScheduledEventAttributes().getInput(); }\n if (ScheduleActivityTaskFailed == type()) { return null; }\n if (ActivityTaskStarted == type()) { return null; }\n if (ActivityTaskCompleted == type()) { return null; }\n if (ActivityTaskFailed == type()) { return null; }\n if (ActivityTaskTimedOut == type()) { return null; }\n if (ActivityTaskCanceled == type()) { return null; }\n if (ActivityTaskCancelRequested == type()) { return null; }\n if (RequestCancelActivityTaskFailed == type()) { return null; }\n if (WorkflowExecutionSignaled == type()) { return historyEvent().getWorkflowExecutionSignaledEventAttributes().getInput(); }\n if (MarkerRecorded == type()) { return historyEvent().getMarkerRecordedEventAttributes().getDetails(); }\n if (RecordMarkerFailed == type()) { return null; }\n if (TimerStarted == type()) { return \"Timer Started\"; }\n if (StartTimerFailed == type()) { return null; }\n if (TimerFired == type()) { return null; }\n if (TimerCanceled == type()) { return null; }\n if (CancelTimerFailed == type()) { return null; }\n if (StartChildWorkflowExecutionInitiated == type()) { return historyEvent().getStartChildWorkflowExecutionInitiatedEventAttributes().getInput(); }\n if (StartChildWorkflowExecutionFailed == type()) { return null; }\n if (ChildWorkflowExecutionStarted == type()) { return null; }\n if (ChildWorkflowExecutionCompleted == type()) { return null; }\n if (ChildWorkflowExecutionFailed == type()) { return null; }\n if (ChildWorkflowExecutionTimedOut == type()) { return null; }\n if (ChildWorkflowExecutionCanceled == type()) { return null; }\n if (ChildWorkflowExecutionTerminated == type()) { return null; }\n if (SignalExternalWorkflowExecutionInitiated == type()) { return historyEvent().getSignalExternalWorkflowExecutionInitiatedEventAttributes().getInput(); }\n if (SignalExternalWorkflowExecutionFailed == type()) { return null; }\n if (ExternalWorkflowExecutionSignaled == type()) { return null; }\n if (RequestCancelExternalWorkflowExecutionInitiated == type()) { return null; }\n if (RequestCancelExternalWorkflowExecutionFailed == type()) { return null; }\n if (ExternalWorkflowExecutionCancelRequested == type()) { return null; }\n throw new IllegalArgumentException(\"Unknown EventType \" + type());\n }\n\n public String control() {\n if (WorkflowExecutionStarted == type()) { return null; }\n if (WorkflowExecutionCancelRequested == type()) { return null; }\n if (WorkflowExecutionCompleted == type()) { return null; }\n if (CompleteWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionFailed == type()) { return null; }\n if (FailWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionTimedOut == type()) { return null; }\n if (WorkflowExecutionCanceled == type()) { return null; }\n if (CancelWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionContinuedAsNew == type()) { return null; }\n if (ContinueAsNewWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionTerminated == type()) { return null; }\n if (DecisionTaskScheduled == type()) { return null; }\n if (DecisionTaskStarted == type()) { return null; }\n if (DecisionTaskCompleted == type()) { return null; }\n if (DecisionTaskTimedOut == type()) { return null; }\n if (ActivityTaskScheduled == type()) { return historyEvent().getActivityTaskScheduledEventAttributes().getControl(); }\n if (ScheduleActivityTaskFailed == type()) { return null; }\n if (ActivityTaskStarted == type()) { return null; }\n if (ActivityTaskCompleted == type()) { return null; }\n if (ActivityTaskFailed == type()) { return null; }\n if (ActivityTaskTimedOut == type()) { return null; }\n if (ActivityTaskCanceled == type()) { return null; }\n if (ActivityTaskCancelRequested == type()) { return null; }\n if (RequestCancelActivityTaskFailed == type()) { return null; }\n if (WorkflowExecutionSignaled == type()) { return null; }\n if (MarkerRecorded == type()) { return null; }\n if (RecordMarkerFailed == type()) { return null; }\n if (TimerStarted == type()) { return historyEvent().getTimerStartedEventAttributes().getControl(); }\n if (StartTimerFailed == type()) { return null; }\n if (TimerFired == type()) { return null; }\n if (TimerCanceled == type()) { return null; }\n if (CancelTimerFailed == type()) { return null; }\n if (StartChildWorkflowExecutionInitiated == type()) { return historyEvent().getStartChildWorkflowExecutionInitiatedEventAttributes().getControl(); }\n if (StartChildWorkflowExecutionFailed == type()) { return historyEvent().getStartChildWorkflowExecutionFailedEventAttributes().getControl(); }\n if (ChildWorkflowExecutionStarted == type()) { return null; }\n if (ChildWorkflowExecutionCompleted == type()) { return null; }\n if (ChildWorkflowExecutionFailed == type()) { return null; }\n if (ChildWorkflowExecutionTimedOut == type()) { return null; }\n if (ChildWorkflowExecutionCanceled == type()) { return null; }\n if (ChildWorkflowExecutionTerminated == type()) { return null; }\n if (SignalExternalWorkflowExecutionInitiated == type()) { return historyEvent().getSignalExternalWorkflowExecutionInitiatedEventAttributes().getControl(); }\n if (SignalExternalWorkflowExecutionFailed == type()) { return historyEvent().getSignalExternalWorkflowExecutionFailedEventAttributes().getControl(); }\n if (ExternalWorkflowExecutionSignaled == type()) { return null; }\n if (RequestCancelExternalWorkflowExecutionInitiated == type()) { return historyEvent().getRequestCancelExternalWorkflowExecutionInitiatedEventAttributes().getControl(); }\n if (RequestCancelExternalWorkflowExecutionFailed == type()) { return historyEvent().getRequestCancelExternalWorkflowExecutionFailedEventAttributes().getControl(); }\n if (ExternalWorkflowExecutionCancelRequested == type()) { return null; }\n throw new IllegalArgumentException(\"Unknown EventType \" + type());\n }\n\n public String output() {\n if (WorkflowExecutionStarted == type()) { return null; }\n if (WorkflowExecutionCancelRequested == type()) { return null; }\n if (WorkflowExecutionCompleted == type()) { return historyEvent().getWorkflowExecutionCompletedEventAttributes().getResult(); }\n if (CompleteWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionFailed == type()) { return null; }\n if (FailWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionTimedOut == type()) { return null; }\n if (WorkflowExecutionCanceled == type()) { return null; }\n if (CancelWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionContinuedAsNew == type()) { return null; }\n if (ContinueAsNewWorkflowExecutionFailed == type()) { return null; }\n if (WorkflowExecutionTerminated == type()) { return null; }\n if (DecisionTaskScheduled == type()) { return null; }\n if (DecisionTaskStarted == type()) { return null; }\n if (DecisionTaskCompleted == type()) { return historyEvent().getDecisionTaskCompletedEventAttributes().getExecutionContext(); }\n if (DecisionTaskTimedOut == type()) { return null; }\n if (ActivityTaskScheduled == type()) { return null; }\n if (ScheduleActivityTaskFailed == type()) { return null; }\n if (ActivityTaskStarted == type()) { return null; }\n if (ActivityTaskCompleted == type()) { return historyEvent().getActivityTaskCompletedEventAttributes().getResult(); }\n if (ActivityTaskFailed == type()) { return null; }\n if (ActivityTaskTimedOut == type()) { return null; }\n if (ActivityTaskCanceled == type()) { return null; }\n if (ActivityTaskCancelRequested == type()) { return null; }\n if (RequestCancelActivityTaskFailed == type()) { return null; }\n if (WorkflowExecutionSignaled == type()) { return historyEvent().getWorkflowExecutionSignaledEventAttributes().getInput(); }\n if (MarkerRecorded == type()) { return historyEvent().getMarkerRecordedEventAttributes().getDetails(); }\n if (RecordMarkerFailed == type()) { return null; }\n if (TimerStarted == type()) { return null; }\n if (StartTimerFailed == type()) { return null; }\n if (TimerFired == type()) { return \"Timer Fired\"; }\n if (TimerCanceled == type()) { return \"Timer Canceled\"; }\n if (CancelTimerFailed == type()) { return null; }\n if (StartChildWorkflowExecutionInitiated == type()) { return null; }\n if (StartChildWorkflowExecutionFailed == type()) { return null; }\n if (ChildWorkflowExecutionStarted == type()) { return null; }\n if (ChildWorkflowExecutionCompleted == type()) { return historyEvent().getChildWorkflowExecutionCompletedEventAttributes().getResult(); }\n if (ChildWorkflowExecutionFailed == type()) { return null; }\n if (ChildWorkflowExecutionTimedOut == type()) { return null; }\n if (ChildWorkflowExecutionCanceled == type()) { return null; }\n if (ChildWorkflowExecutionTerminated == type()) { return null; }\n if (SignalExternalWorkflowExecutionInitiated == type()) { return null; }\n if (SignalExternalWorkflowExecutionFailed == type()) { return null; }\n if (ExternalWorkflowExecutionSignaled == type()) { return historyEvent().getExternalWorkflowExecutionSignaledEventAttributes().getWorkflowExecution().getRunId(); }\n if (RequestCancelExternalWorkflowExecutionInitiated == type()) { return null; }\n if (RequestCancelExternalWorkflowExecutionFailed == type()) { return null; }\n if (ExternalWorkflowExecutionCancelRequested == type()) { return null; }\n throw new IllegalArgumentException(\"Unknown EventType \" + type());\n }\n\n public String reason() {\n if (WorkflowExecutionStarted == type()) { return null; }\n if (WorkflowExecutionCancelRequested == type()) { return \"Workflow Execution Cancel Requested\"; }\n if (WorkflowExecutionCompleted == type()) { return null; }\n if (CompleteWorkflowExecutionFailed == type()) { return \"Complete Workflow Execution Failed\"; }\n if (WorkflowExecutionFailed == type()) { return \"Workflow Execution Failed\"; }\n if (FailWorkflowExecutionFailed == type()) { return \"Fail Workflow Execution Failed\"; }\n if (WorkflowExecutionTimedOut == type()) { return \"Workflow Execution Timed Out\"; }\n if (WorkflowExecutionCanceled == type()) { return \"Workflow Execution Canceled\"; }\n if (CancelWorkflowExecutionFailed == type()) { return \"Cancel Workflow Execution Failed\"; }\n if (WorkflowExecutionContinuedAsNew == type()) { return null; }\n if (ContinueAsNewWorkflowExecutionFailed == type()) { return \"Continue As New Workflow Execution Failed\"; }\n if (WorkflowExecutionTerminated == type()) { return \"Workflow Execution Terminated\"; }\n if (DecisionTaskScheduled == type()) { return null; }\n if (DecisionTaskStarted == type()) { return null; }\n if (DecisionTaskCompleted == type()) { return null; }\n if (DecisionTaskTimedOut == type()) { return null; }\n if (ActivityTaskScheduled == type()) { return null; }\n if (ScheduleActivityTaskFailed == type()) { return \"Schedule Activity Task Failed\"; }\n if (ActivityTaskStarted == type()) { return null; }\n if (ActivityTaskCompleted == type()) { return null; }\n if (ActivityTaskFailed == type()) { return historyEvent().getActivityTaskFailedEventAttributes().getReason(); }\n if (ActivityTaskTimedOut == type()) { return historyEvent().getActivityTaskTimedOutEventAttributes().getTimeoutType(); }\n if (ActivityTaskCanceled == type()) { return \"Activity Task Canceled\"; }\n if (ActivityTaskCancelRequested == type()) { return \"Activity Task Cancel Requested\"; }\n if (RequestCancelActivityTaskFailed == type()) { return \"Request Cancel Activity Task Failed\"; }\n if (WorkflowExecutionSignaled == type()) { return null; }\n if (MarkerRecorded == type()) { return null; }\n if (RecordMarkerFailed == type()) { return \"Record Marker Failed\"; }\n if (TimerStarted == type()) { return null; }\n if (StartTimerFailed == type()) { return \"Start Timer Failed\"; }\n if (TimerFired == type()) { return null; }\n if (TimerCanceled == type()) { return null; }\n if (CancelTimerFailed == type()) { return null; }\n if (StartChildWorkflowExecutionInitiated == type()) { return null; }\n if (StartChildWorkflowExecutionFailed == type()) { return \"Start Child Workflow Execution Failed\"; }\n if (ChildWorkflowExecutionStarted == type()) { return null; }\n if (ChildWorkflowExecutionCompleted == type()) { return null; }\n if (ChildWorkflowExecutionFailed == type()) { return historyEvent().getChildWorkflowExecutionFailedEventAttributes().getReason(); }\n if (ChildWorkflowExecutionTimedOut == type()) { return \"Child Workflow Execution Timed Out\"; }\n if (ChildWorkflowExecutionCanceled == type()) { return \"Child Workflow Execution Canceled\"; }\n if (ChildWorkflowExecutionTerminated == type()) { return \"Child Workflow Execution Terminated\"; }\n if (SignalExternalWorkflowExecutionInitiated == type()) { return null; }\n if (SignalExternalWorkflowExecutionFailed == type()) { return \"Signal External Workflow Execution Failed\"; }\n if (ExternalWorkflowExecutionSignaled == type()) { return null; }\n if (RequestCancelExternalWorkflowExecutionInitiated == type()) { return null; }\n if (RequestCancelExternalWorkflowExecutionFailed == type()) { return \"Request Cancel External Workflow Execution Failed\"; }\n if (ExternalWorkflowExecutionCancelRequested == type()) { return null; }\n throw new IllegalArgumentException(\"Unknown EventType \" + type());\n }\n\n public String details() {\n if (WorkflowExecutionStarted == type()) { return null; }\n if (WorkflowExecutionCancelRequested == type()) { return historyEvent().getWorkflowExecutionCancelRequestedEventAttributes().getCause(); }\n if (WorkflowExecutionCompleted == type()) { return null; }\n if (CompleteWorkflowExecutionFailed == type()) { return historyEvent().getCompleteWorkflowExecutionFailedEventAttributes().getCause(); }\n if (WorkflowExecutionFailed == type()) { return historyEvent().getWorkflowExecutionFailedEventAttributes().getDetails(); }\n if (FailWorkflowExecutionFailed == type()) { return historyEvent().getFailWorkflowExecutionFailedEventAttributes().getCause(); }\n if (WorkflowExecutionTimedOut == type()) { return null; }\n if (WorkflowExecutionCanceled == type()) { return historyEvent().getWorkflowExecutionCanceledEventAttributes().getDetails(); }\n if (CancelWorkflowExecutionFailed == type()) { return historyEvent().getCancelWorkflowExecutionFailedEventAttributes().getCause(); }\n if (WorkflowExecutionContinuedAsNew == type()) { return null; }\n if (ContinueAsNewWorkflowExecutionFailed == type()) { return historyEvent().getContinueAsNewWorkflowExecutionFailedEventAttributes().getCause(); }\n if (WorkflowExecutionTerminated == type()) { return historyEvent().getWorkflowExecutionTerminatedEventAttributes().getDetails(); }\n if (DecisionTaskScheduled == type()) { return null; }\n if (DecisionTaskStarted == type()) { return null; }\n if (DecisionTaskCompleted == type()) { return null; }\n if (DecisionTaskTimedOut == type()) { return null; }\n if (ActivityTaskScheduled == type()) { return null; }\n if (ScheduleActivityTaskFailed == type()) { return historyEvent().getScheduleActivityTaskFailedEventAttributes().getCause(); }\n if (ActivityTaskStarted == type()) { return null; }\n if (ActivityTaskCompleted == type()) { return null; }\n if (ActivityTaskFailed == type()) { return historyEvent().getActivityTaskFailedEventAttributes().getDetails(); }\n if (ActivityTaskTimedOut == type()) { return historyEvent().getActivityTaskTimedOutEventAttributes().getDetails(); }\n if (ActivityTaskCanceled == type()) { return historyEvent().getActivityTaskCanceledEventAttributes().getDetails(); }\n if (ActivityTaskCancelRequested == type()) { return null; }\n if (RequestCancelActivityTaskFailed == type()) { return historyEvent().getRequestCancelActivityTaskFailedEventAttributes().getCause(); }\n if (WorkflowExecutionSignaled == type()) { return null; }\n if (MarkerRecorded == type()) { return historyEvent().getMarkerRecordedEventAttributes().getDetails(); }\n if (RecordMarkerFailed == type()) { return historyEvent().getRecordMarkerFailedEventAttributes().getCause(); }\n if (TimerStarted == type()) { return null; }\n if (StartTimerFailed == type()) { return historyEvent().getStartTimerFailedEventAttributes().getCause(); }\n if (TimerFired == type()) { return null; }\n if (TimerCanceled == type()) { return null; }\n if (CancelTimerFailed == type()) { return null; }\n if (StartChildWorkflowExecutionInitiated == type()) { return null; }\n if (StartChildWorkflowExecutionFailed == type()) { return historyEvent().getStartChildWorkflowExecutionFailedEventAttributes().getCause(); }\n if (ChildWorkflowExecutionStarted == type()) { return null; }\n if (ChildWorkflowExecutionCompleted == type()) { return null; }\n if (ChildWorkflowExecutionFailed == type()) { return historyEvent().getChildWorkflowExecutionFailedEventAttributes().getDetails(); }\n if (ChildWorkflowExecutionTimedOut == type()) { return historyEvent().getChildWorkflowExecutionTimedOutEventAttributes().getTimeoutType(); }\n if (ChildWorkflowExecutionCanceled == type()) { return historyEvent().getChildWorkflowExecutionCanceledEventAttributes().getDetails(); }\n if (ChildWorkflowExecutionTerminated == type()) { return historyEvent().getChildWorkflowExecutionTerminatedEventAttributes().getWorkflowExecution().getRunId(); }\n if (SignalExternalWorkflowExecutionInitiated == type()) { return null; }\n if (SignalExternalWorkflowExecutionFailed == type()) { return historyEvent().getSignalExternalWorkflowExecutionFailedEventAttributes().getCause(); }\n if (ExternalWorkflowExecutionSignaled == type()) { return null; }\n if (RequestCancelExternalWorkflowExecutionInitiated == type()) { return null; }\n if (RequestCancelExternalWorkflowExecutionFailed == type()) { return historyEvent().getRequestCancelExternalWorkflowExecutionFailedEventAttributes().getCause(); }\n if (ExternalWorkflowExecutionCancelRequested == type()) { return null; }\n throw new IllegalArgumentException(\"Unknown EventType \" + type());\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(1000);\n sb.append(format(\"%s: %s, %s, \", type(), id(), initialEventId()));\n appendIf(actionId(), sb);\n appendIf(input(), sb);\n appendIf(output(), sb);\n appendIf(control(), sb);\n appendIf(reason(), sb);\n sb.append(\" \");\n sb.append(eventTimestamp());\n return sb.toString();\n }\n\n private static void appendIf(Object value, StringBuilder sb) {\n if (value != null) {\n sb.append(\" \");\n sb.append(value);\n sb.append(\",\");\n }\n }\n\n /**\n * Sort by eventId descending (most recent event first).\n */\n @Override\n public int compareTo(Event event) {\n return event.id().compareTo(id());\n }\n\n}",
"public class DecisionTaskIterator extends AbstractIterator<HistoryEvent> {\n\n private String nextPageToken;\n private Iterator<HistoryEvent> currentPage = Collections.emptyIterator();\n private boolean isLastPage = false;\n private final AmazonSimpleWorkflow swf;\n private final PollForDecisionTaskRequest request;\n\n public DecisionTaskIterator(AmazonSimpleWorkflow swf, PollForDecisionTaskRequest request,\n DecisionTask startingResponse) {\n this.swf = swf;\n this.request = request;\n this.nextPageToken = startingResponse.getNextPageToken();\n this.currentPage = Optional.ofNullable(startingResponse.getEvents())\n .map(List::iterator).orElse( Collections.emptyIterator());\n this.isLastPage = this.nextPageToken == null;\n }\n\n @Override\n protected HistoryEvent computeNext() {\n if (!currentPage.hasNext() && !isLastPage) {\n DecisionTask decisionTask = nextDecisionTask(nextPageToken);\n nextPageToken = decisionTask.getNextPageToken();\n isLastPage = this.nextPageToken == null;\n currentPage = Optional.ofNullable(decisionTask.getEvents())\n .map(List::iterator).orElse(Collections.emptyIterator());\n }\n\n if (currentPage.hasNext()) {\n return currentPage.next();\n }else {\n endOfData();\n return null;\n }\n }\n\n protected DecisionTask nextDecisionTask(String nextPageToken) {\n return swf.pollForDecisionTask(request.withNextPageToken(nextPageToken));\n }\n}",
"public static Decision createCompleteWorkflowExecutionDecision(String result) {\n return new Decision()\n .withDecisionType(DecisionType.CompleteWorkflowExecution)\n .withCompleteWorkflowExecutionDecisionAttributes(\n new CompleteWorkflowExecutionDecisionAttributes()\n .withResult(trimToMaxLength(result, MAX_DETAILS_LENGTH))\n );\n}",
"public static Decision createFailWorkflowExecutionDecision(String target, String reason, String details) {\n return new Decision()\n .withDecisionType(DecisionType.FailWorkflowExecution)\n .withFailWorkflowExecutionDecisionAttributes(\n new FailWorkflowExecutionDecisionAttributes()\n .withReason(createFailReasonString(target, reason))\n .withDetails(trimToMaxLength(details, MAX_DETAILS_LENGTH))\n );\n}"
] | import com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils;
import com.amazonaws.services.simpleworkflow.model.Decision;
import com.amazonaws.services.simpleworkflow.model.DecisionTask;
import com.amazonaws.services.simpleworkflow.model.FailWorkflowExecutionDecisionAttributes;
import com.amazonaws.services.simpleworkflow.model.HistoryEvent;
import com.amazonaws.services.simpleworkflow.model.PollForDecisionTaskRequest;
import com.amazonaws.services.simpleworkflow.model.RegisterWorkflowTypeRequest;
import com.amazonaws.services.simpleworkflow.model.RespondDecisionTaskCompletedRequest;
import com.amazonaws.services.simpleworkflow.model.TaskList;
import com.amazonaws.services.simpleworkflow.model.TypeAlreadyExistsException;
import com.github.fzakaria.waterflow.Workflow;
import com.github.fzakaria.waterflow.converter.DataConverter;
import com.github.fzakaria.waterflow.event.Event;
import com.github.fzakaria.waterflow.immutable.DecisionContext;
import com.github.fzakaria.waterflow.immutable.Key;
import com.github.fzakaria.waterflow.immutable.Name;
import com.github.fzakaria.waterflow.immutable.Version;
import com.github.fzakaria.waterflow.swf.DecisionTaskIterator;
import com.github.fzakaria.waterflow.swf.RegisterWorkflowTypeRequestBuilder;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import org.immutables.value.Value;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
import static com.amazonaws.services.simpleworkflow.model.EventType.WorkflowExecutionCancelRequested;
import static com.github.fzakaria.waterflow.TaskType.WORKFLOW_EXECUTION;
import static com.github.fzakaria.waterflow.Workflow.createCompleteWorkflowExecutionDecision;
import static com.github.fzakaria.waterflow.Workflow.createFailWorkflowExecutionDecision;
import static com.github.fzakaria.waterflow.event.EventState.ERROR;
import static java.lang.String.format; | package com.github.fzakaria.waterflow.poller;
/**
* Poll for {@link DecisionTask} event on a single domain and task list and ask a registered {@link Workflow} for next decisions.
* <p/>
* Implements {@link Runnable} so that multiple instances of this class can be scheduled to handle higher levels of activity tasks.
*
* @see BasePoller
*/
@Value.Immutable
public abstract class DecisionPoller extends BasePoller<DecisionTask> {
public abstract List<Workflow<?,?>> workflows();
public abstract DataConverter dataConverter();
/**
* Register workflows added to this poller on Amazon SWF with this instance's domain and task list.
* {@link TypeAlreadyExistsException} are ignored making this method idempotent.
*
*/
@Override
public void register() {
for (Workflow workflow : workflows()) {
try {
RegisterWorkflowTypeRequest request =
RegisterWorkflowTypeRequestBuilder.builder().domain(domain())
.workflow(workflow).build();
swf().registerWorkflowType(request);
log.info(format("Register workflow succeeded %s", workflow));
} catch (TypeAlreadyExistsException e) {
log.info(format("Register workflow already exists %s", workflow));
} catch (Throwable t) {
String format = format("Register workflow failed %s", workflow);
log.error(format);
throw new IllegalStateException(format, t);
}
}
}
@Override
protected DecisionTask poll() {
// Events are request in newest-first reverse order;
PollForDecisionTaskRequest request = createPollForDecisionTaskRequest();
//If no decision task is available in the specified task list before the timeout of 60 seconds expires,
//an empty result is returned. An empty result, in this context, means that a DecisionTask is returned,
//but that the value of taskToken is an empty string.
//{@see http://docs.aws.amazon.com/amazonswf/latest/apireference/API_PollForDecisionTask.html}
DecisionTask decisionTask = swf().pollForDecisionTask(request);
if (decisionTask == null || decisionTask.getTaskToken() == null) {
return null;
}
return decisionTask;
}
@Override
protected void consume(DecisionTask decisionTask) {
// Events are request in newest-first reverse order;
PollForDecisionTaskRequest request = createPollForDecisionTaskRequest();
DecisionTaskIterator decisionTaskIterator = new DecisionTaskIterator(swf(), request, decisionTask);
final List<HistoryEvent> historyEvents = Lists.newArrayList(decisionTaskIterator);
final List<Event> events = Event.fromHistoryEvents(historyEvents);
if (events.isEmpty()) {
log.debug("No decisions found for a workflow");
return;
}
final Workflow<?,?> workflow = lookupWorkflow(decisionTask);
// Finished loading history for this workflow, now ask it to make the next set of decisions.
final String workflowId = decisionTask.getWorkflowExecution().getWorkflowId();
final String runId = decisionTask.getWorkflowExecution().getRunId();
//Order here is important since decisionContext creates a new array
final DecisionContext decisionContext = DecisionContext.create().addAllEvents(events);
final List<Decision> decisions = decisionContext.decisions();
List<Event> workflowErrors = events.stream().filter(e -> e.task() == WORKFLOW_EXECUTION)
.filter(e -> e.state() == ERROR).collect(Collectors.toList());
if (workflowErrors.isEmpty()) {
try {
//No need to replay if cancel event exists. Just cancel immediately
Optional<Event> cancelEvent = events.stream().filter(e -> e.type() == WorkflowExecutionCancelRequested).findFirst();
cancelEvent.ifPresent(event -> workflow.onCancelRequested(event, decisions));
CompletionStage<?> future = workflow.decide(decisionContext);
future.thenApply( r -> {
log.debug("Workflow {} completed. Added final decision to complete workflow.", workflow.key());
return dataConverter().toData(r);
}).exceptionally(t -> {
Throwable rootCause = Throwables.getRootCause(t);
log.debug("Workflow {} failed. Added final decision to complete workflow.", workflow.key(), rootCause);
return dataConverter().toData(rootCause);
}).thenAccept(r -> decisions.add(createCompleteWorkflowExecutionDecision(r)));
if (log.isDebugEnabled()) {
log.debug(WorkflowExecutionUtils.prettyPrintDecisions(decisions));
}
} catch (Throwable t) {
String runInfo = format("%s %s", workflowId, runId);
String details = dataConverter().toData(t);
log.error(runInfo, t); | decisions.add(createFailWorkflowExecutionDecision(runInfo, t.getMessage(), details)); | 5 |
multi-os-engine/moe-plugin-gradle | src/main/java/org/moe/gradle/tasks/AbstractBaseTask.java | [
"public abstract class RuleClosure extends Closure<Task> {\n\n protected RuleClosure(Object owner) {\n super(Require.nonNull(owner));\n }\n\n public abstract Task doCall(String taskName);\n}",
"public abstract class ValueClosure<V> extends Closure<V> {\n\n protected ValueClosure(@NotNull Object owner) {\n super(Require.nonNull(owner));\n }\n\n public abstract V doCall();\n}",
"public class Server {\n\n private static final Logger LOG = Logging.getLogger(Server.class);\n\n private static final String MOE_REMOTEBUILD_DISABLE = \"moe.remotebuild.disable\";\n private static final String SDK_ROOT_MARK = \"REMOTE_MOE_SDK_ROOT___1234567890\";\n\n @NotNull\n final Session session;\n\n @NotNull\n private final MoePlugin plugin;\n\n @NotNull\n private final ServerSettings settings;\n\n @Nullable\n private String userHome;\n\n @NotNull\n public String getUserHome() {\n return Require.nonNull(userHome);\n }\n\n @Nullable\n private String userName;\n\n @NotNull\n public String getUserName() {\n return Require.nonNull(userName);\n }\n\n @Nullable\n private URI buildDir;\n\n @NotNull\n public URI getBuildDir() {\n return Require.nonNull(buildDir);\n }\n\n @Nullable\n private URI sdkDir;\n\n @NotNull\n public URI getSdkDir() {\n return Require.nonNull(sdkDir);\n }\n\n @Nullable\n private Task moeRemoteServerSetupTask;\n\n @NotNull\n public Task getMoeRemoteServerSetupTask() {\n return Require.nonNull(moeRemoteServerSetupTask);\n }\n\n private final ExecutorService executor = Executors.newFixedThreadPool(1);\n\n private Server(@NotNull JSch jsch, @NotNull Session session, @NotNull MoePlugin plugin, @NotNull ServerSettings settings) {\n Require.nonNull(jsch);\n this.session = Require.nonNull(session);\n this.plugin = Require.nonNull(plugin);\n this.settings = Require.nonNull(settings);\n\n this.userName = session.getUserName();\n\n final Project project = plugin.getProject();\n project.getGradle().buildFinished(new ConfigurationClosure<BuildResult>(project) {\n @Override\n public void doCall(BuildResult object) {\n if (!session.isConnected()) {\n return;\n }\n try {\n lockRemoteKeychain();\n } catch (Throwable e) {\n LOG.error(\"Failed to lock remote keychain\", e);\n }\n try {\n if (buildDir != null) {\n final ServerCommandRunner runner = new ServerCommandRunner(Server.this, \"cleanup\", \"\" +\n \"rm -rf '\" + getBuildDir() + \"'\");\n runner.setQuiet(true);\n runner.run();\n }\n } catch (Throwable e) {\n LOG.error(\"Failed to cleanup on remote server\", e);\n }\n disconnect();\n }\n });\n }\n\n @Nullable\n public static Server setup(@NotNull MoePlugin plugin) {\n Require.nonNull(plugin);\n\n ServerSettings settings = new ServerSettings(plugin);\n\n final Project project = plugin.getProject();\n project.getTasks().create(\"moeConfigRemote\", task -> {\n task.setGroup(MOE);\n task.setDescription(\"Starts an interactive remote server connection configurator and tester\");\n task.getActions().add(t -> {\n settings.interactiveConfig();\n });\n });\n project.getTasks().create(\"moeTestRemote\", task -> {\n task.setGroup(MOE);\n task.setDescription(\"Tests the connection to the remote server\");\n task.getActions().add(t -> {\n if (!settings.testConnection()) {\n throw new GradleException(\"Remote connection test failed\");\n }\n });\n });\n\n if (project.hasProperty(MOE_REMOTEBUILD_DISABLE)) {\n return null;\n }\n\n if (!settings.isConfigured()) {\n return null;\n }\n\n // Create session\n try {\n final JSch jsch = settings.getJSch();\n final Session session = settings.getJSchSession(jsch);\n return new Server(jsch, session, plugin, settings);\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n public void connect() {\n Require.nonNull(plugin);\n moeRemoteServerSetupTask = plugin.getProject().getTasks().create(\"moeRemoteServerSetup\", task -> {\n task.setGroup(MOE);\n task.setDescription(\"Sets up the SDK on the remote server\");\n task.getActions().add(t -> {\n\n if (session.isConnected()) {\n return;\n }\n try {\n session.connect();\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n setupUserHome();\n setupBuildDir();\n prepareServerMOE();\n });\n });\n }\n\n private void prepareServerMOE() {\n final MoeSDK sdk = plugin.getSDK();\n\n final File gradlewZip = sdk.getGradlewZip();\n final FileList list = new FileList(gradlewZip.getParentFile(), getBuildDir());\n final String remoteGradlewZip = list.add(gradlewZip);\n upload(\"prepare - gradlew\", list);\n\n final String output = exec(\"install MOE SDK\", \"\" +\n \"cd \" + getBuildDir().getPath() + \" && \" +\n\n \"unzip \" + remoteGradlewZip + \" && \" +\n\n \"cd gradlew && \" +\n\n \"echo 'distributionBase=GRADLE_USER_HOME' >> gradle/wrapper/gradle-wrapper.properties && \" +\n \"echo 'distributionPath=wrapper/dists' >> gradle/wrapper/gradle-wrapper.properties && \" +\n \"echo 'zipStoreBase=GRADLE_USER_HOME' >> gradle/wrapper/gradle-wrapper.properties && \" +\n \"echo 'zipStorePath=wrapper/dists' >> gradle/wrapper/gradle-wrapper.properties && \" +\n \"echo 'distributionUrl=https\\\\://services.gradle.org/distributions/gradle-\" + plugin.getRequiredGradleVersion() + \"-bin.zip' >> gradle/wrapper/gradle-wrapper.properties && \" +\n\n \"echo 'buildscript {' >> build.gradle && \" +\n \"echo ' repositories {' >> build.gradle && \" +\n \"echo ' \" + settings.getGradleRepositories() + \"' >> build.gradle && \" +\n \"echo ' }' >> build.gradle && \" +\n \"echo ' dependencies {' >> build.gradle && \" +\n \"echo ' classpath group: \\\"org.multi-os-engine\\\", name: \\\"moe-gradle\\\", version: \\\"\" + sdk.pluginVersion + \"\\\"' >> build.gradle && \" +\n \"echo ' }' >> build.gradle && \" +\n \"echo '}' >> build.gradle && \" +\n \"echo '' >> build.gradle && \" +\n \"echo 'apply plugin: \\\"moe-sdk\\\"' >> build.gradle && \" +\n \"echo 'task printSDKRoot << { print \\\"\" + SDK_ROOT_MARK + \":${moe.sdk.root}\\\" }' >> build.gradle && \" +\n\n \"./gradlew printSDKRoot -s && \" +\n \"cd .. && rm -rf gradlew && rm -f gradlew.zip\"\n );\n final int start = output.indexOf(SDK_ROOT_MARK);\n Require.NE(start, -1, \"SDK_ROOT_MARK not found\");\n final int start2 = start + SDK_ROOT_MARK.length() + 1;\n try {\n sdkDir = new URI(\"file://\" + output.substring(start2, output.indexOf('\\n', start2)));\n } catch (URISyntaxException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n exec(\"check MOE SDK path\", \"[ -d '\" + sdkDir.getPath() + \"' ]\");\n }\n\n private void setupUserHome() {\n final ChannelExec channel;\n try {\n channel = (ChannelExec) session.openChannel(\"exec\");\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n channel.setCommand(\"echo $HOME\");\n\n final ByteArrayOutputStream baos = new ByteArrayOutputStream();\n channel.setOutputStream(baos);\n\n try {\n channel.connect();\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n while (!channel.isClosed()) {\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n channel.disconnect();\n if (channel.getExitStatus() != 0) {\n throw new GradleException(\"Failed to initialize connection with server\");\n }\n userHome = baos.toString().trim();\n LOG.quiet(\"MOE Remote Build - REMOTE_HOME=\" + getUserHome());\n }\n\n private void setupBuildDir() {\n final ChannelExec channel;\n try {\n channel = (ChannelExec) session.openChannel(\"exec\");\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n channel.setCommand(\"mktemp -d\");\n\n final ByteArrayOutputStream baos = new ByteArrayOutputStream();\n channel.setOutputStream(baos);\n\n try {\n channel.connect();\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n while (!channel.isClosed()) {\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n channel.disconnect();\n if (channel.getExitStatus() != 0) {\n throw new GradleException(\"Failed to initialize connection with server\");\n }\n try {\n buildDir = new URI(\"file://\" + baos.toString().trim());\n } catch (URISyntaxException e) {\n throw new GradleException(e.getMessage(), e);\n }\n LOG.quiet(\"MOE Remote Build - REMOTE_BUILD_DIR=\" + buildDir.getPath());\n }\n\n private void disconnect() {\n if (!session.isConnected()) {\n return;\n }\n session.disconnect();\n userHome = null;\n }\n\n private void assertConnected() {\n if (!session.isConnected()) {\n throw new GradleException(\"MOE Remote Build session in not connected\");\n }\n }\n\n public void upload(@NotNull String name, @NotNull FileList list) {\n assertConnected();\n new ServerFileUploader(this, name, list).run();\n }\n\n public void downloadFile(@NotNull String name, @NotNull String remoteFile, @NotNull File localOutputDir) {\n assertConnected();\n new ServerFileDownloader(this, name, remoteFile, localOutputDir, false).run();\n }\n\n public void downloadDirectory(@NotNull String name, @NotNull String remoteFile, @NotNull File localOutputDir) {\n assertConnected();\n new ServerFileDownloader(this, name, remoteFile, localOutputDir, true).run();\n }\n\n public String exec(@NotNull String name, @NotNull String command) {\n assertConnected();\n final ServerCommandRunner runner = new ServerCommandRunner(this, name, command);\n runner.run();\n return runner.getOutput();\n }\n\n public String getRemotePath(Path relative) {\n assertConnected();\n\n try {\n return getRemotePath(getBuildDir(), relative);\n } catch (IOException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n public String getSDKRemotePath(@NotNull File file) throws IOException {\n Require.nonNull(file);\n\n final Path filePath = file.toPath().toAbsolutePath();\n final Path sdk = plugin.getSDK().getRoot().toPath().toAbsolutePath();\n\n if (!filePath.getRoot().equals(sdk.getRoot())) {\n throw new IOException(\"non-sdk file\");\n }\n\n final Path relative = sdk.relativize(filePath);\n return getRemotePath(getSdkDir(), relative);\n }\n\n public static String getRemotePath(@NotNull URI root, @NotNull Path relative) throws IOException {\n Require.nonNull(root);\n Require.nonNull(relative);\n\n if (relative.toString().contains(\"..\")) {\n throw new IOException(\"Relative path points to extenral directory: \" + relative);\n }\n\n ArrayList<String> comps = new ArrayList<>();\n for (Path path : relative) {\n comps.add(path.getFileName().toString());\n }\n\n try {\n return new URI(root.getPath() + \"/\" + comps.stream().collect(Collectors.joining(\"/\"))).getPath();\n } catch (URISyntaxException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n public boolean checkFileMD5(String remotePath, @NotNull File localFile) {\n // Get local file md5\n final Future<String> localMD5Future = executor.submit(() -> {\n try {\n return DigestUtils.md5Hex(new FileInputStream(localFile));\n } catch (IOException ignore) {\n return null;\n }\n });\n\n // Get remote file md5\n assertConnected();\n final ServerCommandRunner runner = new ServerCommandRunner(this, \"check file md5\", \"\" +\n \"[ -f '\" + remotePath + \"' ] && md5 -q '\" + remotePath + \"'\");\n runner.setQuiet(true);\n try {\n runner.run();\n } catch (GradleException ignore) {\n return false;\n }\n final String remoteMD5 = runner.getOutput().trim();\n\n // Check equality\n final String localMD5;\n try {\n localMD5 = localMD5Future.get();\n } catch (InterruptedException | ExecutionException e) {\n throw new GradleException(e.getMessage(), e);\n }\n if (localMD5 == null) {\n return false;\n }\n return remoteMD5.compareToIgnoreCase(localMD5) == 0;\n }\n\n public void unlockRemoteKeychain() {\n assertConnected();\n\n final String kc_name = settings.getKeychainName();\n final String kc_pass = settings.getKeychainPass();\n final int kc_lock_to = settings.getKeychainLockTimeout();\n\n final ServerCommandRunner runner = new ServerCommandRunner(this, \"unlock keychain\", \"\" +\n \"security unlock-keychain -p '\" + kc_pass + \"' \" + kc_name + \" && \" +\n \"security set-keychain-settings -t \" + kc_lock_to + \" -l \" + kc_name);\n runner.setQuiet(true);\n runner.run();\n }\n\n private void lockRemoteKeychain() {\n assertConnected();\n\n final String kc_name = settings.getKeychainName();\n\n final ServerCommandRunner runner = new ServerCommandRunner(this, \"lock keychain\", \"\" +\n \"security lock-keychain \" + kc_name);\n runner.setQuiet(true);\n runner.run();\n }\n}",
"public class FileUtils {\n public static void deleteFileOrFolder(final @NotNull Path path) throws IOException {\n Require.nonNull(path);\n\n if (!path.toFile().exists()) {\n return;\n }\n Files.walkFileTree(path, new SimpleFileVisitor<Path>() {\n @Override\n public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)\n throws IOException {\n Files.delete(file);\n return CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(final Path dir, final IOException e)\n throws IOException {\n if (e != null) throw e;\n Files.delete(dir);\n return CONTINUE;\n }\n });\n }\n\n public static void deleteFileOrFolder(final @NotNull File file) throws IOException {\n Require.nonNull(file);\n\n deleteFileOrFolder(Paths.get(file.toURI()));\n }\n\n @NotNull\n public static String read(@NotNull File file) {\n Require.nonNull(file);\n\n String string;\n try {\n string = new String(Files.readAllBytes(Paths.get(file.toURI())));\n } catch (IOException e) {\n throw new GradleException(\"Failed to read \" + file, e);\n }\n return string;\n }\n\n public static void write(@NotNull File file, @NotNull String string) {\n Require.nonNull(file);\n Require.nonNull(string);\n\n try {\n Files.write(Paths.get(file.toURI()), string.getBytes(),\n StandardOpenOption.CREATE,\n StandardOpenOption.WRITE,\n StandardOpenOption.TRUNCATE_EXISTING);\n } catch (IOException e) {\n throw new GradleException(\"Failed to write \" + file, e);\n }\n }\n\n @NotNull\n public static File getRelativeTo(@NotNull File base, @NotNull File other) {\n Require.nonNull(base);\n Require.nonNull(other);\n\n return Paths.get(base.getAbsolutePath()).relativize(Paths.get(other.getAbsolutePath())).toFile();\n }\n\n @NotNull\n public static String getNameAsArtifact(@NotNull File file, @NotNull String version) {\n Require.nonNull(file);\n Require.nonNull(version);\n\n final String name = file.getName();\n final int idx = name.indexOf('.');\n if (idx == -1) {\n throw new GradleException(\"Unexpected state\");\n\n } else {\n final String baseName = name.substring(0, idx);\n final String ext = name.substring(idx + 1);\n return \"multi-os-engine:\" + baseName + \":\" + version + \"@\" + ext;\n }\n }\n\n public static void classAndJarInputIterator(\n @NotNull FileCollection fileCollection,\n @NotNull Consumer<InputStream> consumer\n ) {\n FileUtilsKt.classAndJarInputIterator(fileCollection, (path, inputStream) -> {\n consumer.accept(inputStream);\n return Unit.INSTANCE;\n });\n }\n}",
"public class Require {\n private Require() {\n\n }\n\n public static <T> T nonNull(T obj) {\n if (obj == null)\n throw new GradleException();\n return obj;\n }\n\n public static <T> T nullObject(T obj) {\n if (obj != null)\n throw new GradleException();\n return obj;\n }\n\n public static <T> T nonNull(T obj, String message) {\n if (message == null) {\n return nonNull(obj);\n }\n if (obj == null)\n throw new GradleException(message);\n return obj;\n }\n\n public static <T> T nullObject(T obj, String message) {\n if (message == null) {\n return nullObject(obj);\n }\n if (obj != null)\n throw new GradleException(message);\n return obj;\n }\n\n public static <T> T[] sizeEQ(T[] arrays, int other) {\n return EQ(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeNE(T[] arrays, int other) {\n return NE(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeLT(T[] arrays, int other) {\n return LT(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeLE(T[] arrays, int other) {\n return LE(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeGT(T[] arrays, int other) {\n return GT(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeGE(T[] arrays, int other) {\n return GE(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeEQ(T[] arrays, int other, String message) {\n return EQ(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T> T[] sizeNE(T[] arrays, int other, String message) {\n return NE(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T> T[] sizeLT(T[] arrays, int other, String message) {\n return LT(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T> T[] sizeLE(T[] arrays, int other, String message) {\n return LE(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T> T[] sizeGT(T[] arrays, int other, String message) {\n return GT(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T> T[] sizeGE(T[] arrays, int other, String message) {\n return GE(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T extends Collection> T sizeEQ(T coll, int other) {\n return EQ(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeNE(T coll, int other) {\n return NE(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeLT(T coll, int other) {\n return LT(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeLE(T coll, int other) {\n return LE(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeGT(T coll, int other) {\n return GT(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeGE(T coll, int other) {\n return GE(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeEQ(T coll, int other, String message) {\n return EQ(coll, nonNull(coll).size(), other, message);\n }\n\n public static <T extends Collection> T sizeNE(T coll, int other, String message) {\n return NE(coll, nonNull(coll).size(), other, message);\n }\n\n public static <T extends Collection> T sizeLT(T coll, int other, String message) {\n return LT(coll, nonNull(coll).size(), other, message);\n }\n\n public static <T extends Collection> T sizeLE(T coll, int other, String message) {\n return LE(coll, nonNull(coll).size(), other, message);\n }\n\n public static <T extends Collection> T sizeGT(T coll, int other, String message) {\n return GT(coll, nonNull(coll).size(), other, message);\n }\n\n public static <T extends Collection> T sizeGE(T coll, int other, String message) {\n return GE(coll, nonNull(coll).size(), other, message);\n }\n\n public static void EQ(int actual, int value, String message) {\n check(actual == value, null, message);\n }\n\n public static void NE(int actual, int value, String message) {\n check(actual != value, null, message);\n }\n\n public static void LT(int actual, int value, String message) {\n check(actual < value, null, message);\n }\n\n public static void LE(int actual, int value, String message) {\n check(actual <= value, null, message);\n }\n\n public static void GT(int actual, int value, String message) {\n check(actual > value, null, message);\n }\n\n public static void GE(int actual, int value, String message) {\n check(actual >= value, null, message);\n }\n\n public static <T> T EQ(T object, int actual, int value, String message) {\n return check(actual == value, object, message);\n }\n\n public static <T> T NE(T object, int actual, int value, String message) {\n return check(actual != value, object, message);\n }\n\n public static <T> T LT(T object, int actual, int value, String message) {\n return check(actual < value, object, message);\n }\n\n public static <T> T LE(T object, int actual, int value, String message) {\n return check(actual <= value, object, message);\n }\n\n public static <T> T GT(T object, int actual, int value, String message) {\n return check(actual > value, object, message);\n }\n\n public static <T> T GE(T object, int actual, int value, String message) {\n return check(actual >= value, object, message);\n }\n\n public static void TRUE(boolean actual, String message) {\n check(actual, null, message);\n }\n\n public static void FALSE(boolean actual, String message) {\n check(!actual, null, message);\n }\n\n public static <T> T check(boolean succeed, T object, String message) {\n if (succeed) {\n return object;\n }\n throw new GradleException(message);\n }\n}"
] | import org.gradle.api.*;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import org.gradle.process.ExecResult;
import org.gradle.process.ExecSpec;
import org.gradle.process.JavaExecSpec;
import org.moe.common.utils.FileUtilsKt;
import org.moe.gradle.*;
import org.moe.gradle.anns.IgnoreUnused;
import org.moe.gradle.anns.NotNull;
import org.moe.gradle.anns.Nullable;
import org.moe.gradle.groovy.closures.RuleClosure;
import org.moe.gradle.groovy.closures.ValueClosure;
import org.moe.gradle.remote.Server;
import org.moe.gradle.utils.FileUtils;
import org.moe.gradle.utils.Require;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.function.Function;
import java.util.function.Supplier; | /*
Copyright (C) 2016 Migeran
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.moe.gradle.tasks;
public abstract class AbstractBaseTask extends DefaultTask {
protected static final String CONVENTION_LOG_FILE = "logFile";
private static final String CONVENTION_REMOTE_BUILD_HELPER = "remoteBuildHelper";
private static final String MOE_RAW_BINDING_OUTPUT_OPTION = "raw-binding-output";
private Object logFile;
private final Logger logger = Logging.getLogger(getClass());
@OutputFile
@NotNull
public File getLogFile() {
return getProject().file(getOrConvention(logFile, CONVENTION_LOG_FILE));
}
@IgnoreUnused
public void setLogFile(Object logFile) {
this.logFile = logFile;
}
private Boolean remoteExecutionStatusSet;
@Internal
public boolean getRemoteExecutionStatusSet() {
return Require.nonNull(remoteExecutionStatusSet);
}
@Input
@NotNull
@IgnoreUnused
public Long getRemoteBuildHelper() {
Require.nonNull(remoteExecutionStatusSet, "Remote execution status was not set on task '" + getName() + "'");
return getOrConvention(null, CONVENTION_REMOTE_BUILD_HELPER);
}
protected void setSupportsRemoteBuild(boolean value) {
Require.nullObject(remoteExecutionStatusSet, "Remote execution status was already set on task '" + getName() + "'");
remoteExecutionStatusSet = value;
addConvention(CONVENTION_REMOTE_BUILD_HELPER, () -> {
if (remoteExecutionStatusSet) {
if (getMoePlugin().getRemoteServer() != null) {
return new Date().getTime();
} else {
return 0L;
}
} else {
return 0L;
}
});
}
@TaskAction
@IgnoreUnused
private void runInternal() {
// Reset logs
FileUtils.write(getLogFile(), "");
run();
setDidWork(true);
}
abstract protected void run();
@Internal
protected @NotNull MoeExtension getMoeExtension() {
return (MoeExtension) getExtension();
}
@Internal
public @NotNull AbstractMoeExtension getExtension() {
return AbstractMoeExtension.getInstance(getProject());
}
@NotNull
@Internal
protected MoePlugin getMoePlugin() {
return Require.nonNull((MoePlugin) getMoeExtension().plugin);
}
@Internal
protected @NotNull MoeSDK getMoeSDK() {
return getMoeExtension().plugin.getSDK();
}
public void addConvention(String name, Supplier<@Nullable Object> supplier) {
Require.nonNull(name);
Require.nonNull(supplier);
| getConvention().add(name, new ValueClosure<Object>(this) { | 1 |
kstateome/lti-attendance | src/main/java/edu/ksu/canvas/attendance/controller/RosterController.java | [
"@Entity\n@Table(name = \"attendance_section\")\npublic class AttendanceSection implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"section_id\")\n private Long sectionId; //attendance project's local section Id\n\n // Canvas has the authoritative data.\n @Column(name = \"canvas_course_id\", nullable = false)\n private Long canvasCourseId;\n\n @Column(name = \"canvas_section_id\", nullable = false)\n private Long canvasSectionId;\n\n // Canvas has the authoritative data.\n @Column(name = \"section_name\")\n private String name;\n\n @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = true, mappedBy = \"attendanceSection\")\n private AttendanceAssignment attendanceAssignment;\n\n public AttendanceSection() {\n\n }\n\n\n public Long getSectionId() {\n return sectionId;\n }\n\n public void setSectionId(Long sectionId) {\n this.sectionId = sectionId;\n }\n\n public Long getCanvasCourseId() {\n return canvasCourseId;\n }\n\n public void setCanvasCourseId(Long canvasCourseId) {\n this.canvasCourseId = canvasCourseId;\n }\n\n public Long getCanvasSectionId() {\n return canvasSectionId;\n }\n\n public void setCanvasSectionId(Long canvasSectionId) {\n this.canvasSectionId = canvasSectionId;\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 AttendanceAssignment getAttendanceAssignment() {\n return attendanceAssignment;\n }\n\n\n public void setAttendanceAssignment(AttendanceAssignment attendanceAssignment) {\n this.attendanceAssignment = attendanceAssignment;\n }\n\n\n @Override\n public String toString() {\n return \"AttendanceSection [sectionId=\" + sectionId + \", canvasCourseId=\" + canvasCourseId + \", canvasSectionId=\"\n + canvasSectionId + \", name=\" + name +\"]\";\n }\n\n}",
"public class RosterForm extends CourseConfigurationForm {\n\n private List<SectionModel> sectionModels;\n private long sectionId;\n private Date currentDate;\n\n\n public List<SectionModel> getSectionModels() {\n return sectionModels;\n }\n\n public void setSectionModels(List<SectionModel> sectionModels) {\n this.sectionModels = sectionModels;\n }\n\n public long getSectionId() {\n return sectionId;\n }\n\n public void setSectionId(long sectionId) {\n this.sectionId = sectionId;\n }\n\n public Date getCurrentDate() {\n return currentDate;\n }\n\n public void setCurrentDate(Date currentDate) {\n this.currentDate = currentDate;\n }\n\n}",
"@Component\npublic class RosterFormValidator implements Validator {\n\n private static final Logger LOG = LogManager.getLogger(RosterFormValidator.class);\n\n public static final String MINIMUM_MINUTES_MISSED_ERROR_CODE = \"Min.rosterForm.sectionModels.attendances.minutesMissed\";\n public static final String SELECTIVELY_REQUIRED_MINUTES_MISSED_ERROR_CODE = \"SelectivelyRequired.rosterForm.sectionModels.attendances.minutesMissed\";\n\n \n @Override\n public boolean supports(Class<?> clazz) {\n return RosterForm.class.isAssignableFrom(clazz);\n }\n\n @Override\n public void validate(Object target, Errors errors) {\n RosterForm rosterForm = (RosterForm) target;\n\n int sectionIndex = 0;\n for (SectionModel sectionModel : rosterForm.getSectionModels()) {\n\n int attendanceIndex = 0;\n for (AttendanceModel attendance : sectionModel.getAttendances()) {\n String minutesMissedField = \"sectionModels[\" + sectionIndex + \"].attendances[\" + attendanceIndex + \"].minutesMissed\";\n if (attendance.getMinutesMissed() != null && attendance.getMinutesMissed() <= 0) {\n errors.rejectValue(minutesMissedField, MINIMUM_MINUTES_MISSED_ERROR_CODE);\n }\n\n if (attendance.getStatus() == Status.TARDY && attendance.getMinutesMissed() == null && !rosterForm.getSimpleAttendance()) {\n errors.rejectValue(minutesMissedField, SELECTIVELY_REQUIRED_MINUTES_MISSED_ERROR_CODE);\n }\n attendanceIndex++;\n }\n\n sectionIndex++;\n }\n }\n\n}",
"@Component\npublic class SectionModelFactory {\n\n\n public List<SectionModel> createSectionModels(List<AttendanceSection> sections) {\n List<SectionModel> ret = new ArrayList<>();\n\n for (AttendanceSection section : sections) {\n ret.add(createSectionModel(section));\n }\n\n return ret;\n }\n\n\n private SectionModel createSectionModel(AttendanceSection attendanceSection) {\n SectionModel ret = new SectionModel();\n ret.setCanvasSectionId(attendanceSection.getCanvasSectionId());\n ret.setCanvasCourseId(attendanceSection.getCanvasCourseId());\n ret.setSectionName(attendanceSection.getName());\n ret.setSectionId(attendanceSection.getSectionId());\n\n return ret;\n }\n\n}",
"@Component\npublic class AttendanceCourseService {\n\n @Autowired\n private AttendanceCourseRepository attendanceCourseRepository;\n\n\n /**\n * @throws RuntimeException when courseForm is null\n */\n public void save(CourseConfigurationForm courseForm, long canvasCourseId) {\n Validate.notNull(courseForm, \"courseForm must not be null\");\n \n AttendanceCourse attendanceCourse = attendanceCourseRepository.findByCanvasCourseId(canvasCourseId);\n if (attendanceCourse == null) {\n attendanceCourse = new AttendanceCourse(canvasCourseId, courseForm.getTotalClassMinutes(), courseForm.getDefaultMinutesPerSession());\n } else {\n attendanceCourse.setShowNotesToStudents(courseForm.getShowNotesToStudents());\n attendanceCourse.setDefaultMinutesPerSession(courseForm.getDefaultMinutesPerSession());\n attendanceCourse.setTotalMinutes(courseForm.getTotalClassMinutes());\n if (courseForm.getSimpleAttendance() != null && courseForm.getSimpleAttendance()) {\n attendanceCourse.setAttendanceType(AttendanceType.SIMPLE);\n }\n else {\n attendanceCourse.setAttendanceType(AttendanceType.MINUTES);\n }\n }\n\n attendanceCourseRepository.save(attendanceCourse);\n }\n\n\n /**\n * @throws RuntimeException if course does not exist or if the courseForm is null\n */\n public void loadIntoForm(CourseConfigurationForm courseForm, long courseId) {\n Validate.notNull(courseForm, \"courseForm must not be null\");\n \n AttendanceCourse attendanceCourse = attendanceCourseRepository.findByCanvasCourseId(courseId);\n \n if(attendanceCourse == null) {\n RuntimeException e = new IllegalArgumentException(\"Cannot load data into courseForm for non-existent course\");\n throw new ContextedRuntimeException(e).addContextValue(\"courseId\", courseId);\n }\n\n courseForm.setTotalClassMinutes(attendanceCourse.getTotalMinutes());\n courseForm.setDefaultMinutesPerSession(attendanceCourse.getDefaultMinutesPerSession());\n courseForm.setSimpleAttendance(attendanceCourse.getAttendanceType().equals(AttendanceType.SIMPLE));\n courseForm.setShowNotesToStudents(attendanceCourse.getShowNotesToStudents());\n }\n\n public AttendanceCourse findByCanvasCourseId(Long courseId) {\n return attendanceCourseRepository.findByCanvasCourseId(courseId);\n }\n\n}",
"@Component\npublic class AttendanceSectionService {\n\n @Autowired\n private AttendanceSectionRepository sectionRepository;\n\n @Autowired\n private AttendanceAssignmentRepository assignmentRepository;\n\n\n\n public AttendanceSection getSection(long canvasSectionId) {\n return sectionRepository.findByCanvasSectionId(canvasSectionId);\n }\n\n public AttendanceSection getFirstSectionOfCourse(long canvasCourseId) {\n List<AttendanceSection> sections = sectionRepository.findByCanvasCourseId(canvasCourseId);\n return sections.isEmpty() ? null : sections.get(0);\n }\n\n public List<AttendanceSection> getSectionByCanvasCourseId(long canvasCourseId) {\n return sectionRepository.findByCanvasCourseId(canvasCourseId);\n }\n\n public List<AttendanceSection> getSectionsByCourse(long canvasCourseId) {\n return sectionRepository.findByCanvasCourseId(canvasCourseId);\n }\n\n /**\n * @throws RuntimeException when courseForm or sections list are null or empty\n */\n public void save(CourseConfigurationForm courseForm, long canvasCourseId) {\n Validate.notNull(courseForm, \"courseForm must not be null\");\n\n List<AttendanceSection> sections = sectionRepository.findByCanvasCourseId(canvasCourseId);\n if(CollectionUtils.isEmpty(sections)) {\n RuntimeException e = new RuntimeException(\"Cannot load data into courseForm for non-existent sections for this course\");\n throw new ContextedRuntimeException(e).addContextValue(\"courseId\", canvasCourseId);\n }\n\n List<AttendanceAssignment> attendanceAssignments = new ArrayList<>();\n for(AttendanceSection section : sections) {\n AttendanceAssignment assignment = assignmentRepository.findByAttendanceSection(section);\n if(assignment == null) {\n assignment = new AttendanceAssignment();\n assignment.setAttendanceSection(section);\n }\n\n attendanceAssignments.add(assignment);\n }\n\n for(AttendanceAssignment assignment : attendanceAssignments) {\n assignment.setAssignmentName(courseForm.getAssignmentName());\n assignment.setGradingOn(courseForm.getGradingOn());\n assignment.setAssignmentPoints(courseForm.getAssignmentPoints());\n assignment.setPresentPoints(courseForm.getPresentPoints());\n assignment.setTardyPoints(courseForm.getTardyPoints());\n assignment.setExcusedPoints(courseForm.getExcusedPoints());\n assignment.setAbsentPoints(courseForm.getAbsentPoints());\n assignmentRepository.save(assignment);\n }\n }\n\n public void resetAttendanceAssignmentsForCourse(long canvasCourseId) {\n\n List<AttendanceSection> sections = sectionRepository.findByCanvasCourseId(canvasCourseId);\n if(CollectionUtils.isEmpty(sections)) {\n RuntimeException e = new RuntimeException(\"Cannot load data into courseForm for non-existent sections for this course\");\n throw new ContextedRuntimeException(e).addContextValue(\"courseId\", canvasCourseId);\n }\n\n List<AttendanceAssignment> attendanceAssignments = new ArrayList<>();\n for(AttendanceSection section : sections) {\n AttendanceAssignment assignment = assignmentRepository.findByAttendanceSection(section);\n if(assignment != null) {\n attendanceAssignments.add(assignment);\n }\n }\n\n for (AttendanceAssignment assignment: attendanceAssignments) {\n assignment.setGradingOn(false);\n assignment.setCanvasAssignmentId(null);\n assignment.setAssignmentName(null);\n assignment.setAssignmentPoints(null);\n assignment.setPresentPoints(null);\n assignment.setTardyPoints(null);\n assignment.setExcusedPoints(null);\n assignment.setAbsentPoints(null);\n assignmentRepository.save(assignment);\n }\n }\n\n\n /**\n * @throws RuntimeException if course does not exist or if the courseForm is null\n */\n public void loadIntoForm(CourseConfigurationForm courseForm, long courseId) {\n Validate.notNull(courseForm, \"courseForm must not be null\");\n\n List<AttendanceSection> sections = sectionRepository.findByCanvasCourseId(courseId);\n if(CollectionUtils.isEmpty(sections)){\n RuntimeException e = new RuntimeException(\"Cannot load data into courseForm for non-existent sections for this course\");\n throw new ContextedRuntimeException(e).addContextValue(\"courseId\", courseId);\n }\n\n AttendanceAssignment attendanceAssignment = assignmentRepository.findByAttendanceSection(sections.get(0));\n if(attendanceAssignment == null) {\n attendanceAssignment = new AttendanceAssignment();\n }\n\n courseForm.setAssignmentName(StringUtils.defaultIfEmpty(attendanceAssignment.getAssignmentName(), \"Attendance\"));\n courseForm.setAssignmentPoints(StringUtils.defaultIfEmpty(attendanceAssignment.getAssignmentPoints(), \"100\"));\n //default to full points for present or excused\n courseForm.setPresentPoints(StringUtils.defaultIfEmpty(attendanceAssignment.getPresentPoints(), courseForm.getAssignmentPoints()));\n courseForm.setExcusedPoints(StringUtils.defaultIfEmpty(attendanceAssignment.getExcusedPoints(), courseForm.getAssignmentPoints()));\n courseForm.setTardyPoints(StringUtils.defaultIfEmpty(attendanceAssignment.getTardyPoints(), \"0\"));\n courseForm.setAbsentPoints(StringUtils.defaultIfEmpty(attendanceAssignment.getAbsentPoints(), \"0\"));\n courseForm.setGradingOn(attendanceAssignment.getGradingOn());\n }\n\n public AttendanceSection getSectionInListById(Long canvasCourseId, Long sectionId) {\n List<AttendanceSection> sectionList = sectionRepository.findByCanvasCourseId(canvasCourseId);\n return sectionList.stream().filter(x -> x.getCanvasSectionId().equals(sectionId)).findFirst().orElse(null);\n\n }\n\n}",
"@Component\npublic class AttendanceService {\n\n private static final Logger LOG = LogManager.getLogger(AttendanceService.class);\n\n @Autowired\n private AttendanceRepository attendanceRepository;\n\n @Autowired\n private AttendanceStudentRepository studentRepository;\n\n\n /**\n * This method is tuned to save as fast as possible. Data is loaded and saved in batches.\n */\n @Transactional\n public void save(RosterForm rosterForm) {\n long begin = System.currentTimeMillis();\n\n List<Attendance> saveToDb = new ArrayList<>();\n\n List<Attendance> attendancesInDBForCourse = null;\n for (SectionModel sectionModel : rosterForm.getSectionModels()) {\n List<AttendanceStudent> attendanceStudents = null;\n if (sectionModel.getCanvasSectionId() == rosterForm.getSectionId()) {\n for (AttendanceModel attendanceModel : sectionModel.getAttendances()) {\n if (attendanceModel.getAttendanceId() == null) {\n if (attendanceStudents == null) {\n long beginLoad = System.currentTimeMillis();\n attendanceStudents = studentRepository.findByCanvasSectionIdOrderByNameAsc(sectionModel.getCanvasSectionId());\n long endLoad = System.currentTimeMillis();\n LOG.debug(\"loaded \" + attendanceStudents.size() + \" students by section in \" + (endLoad - beginLoad) + \" millis..\");\n }\n\n Attendance attendance = new Attendance();\n AttendanceStudent attendanceStudent = attendanceStudents.stream().filter(s -> s.getStudentId().equals(attendanceModel.getAttendanceStudentId())).findFirst().get();\n attendance.setAttendanceStudent(attendanceStudent);\n attendance.setDateOfClass(attendanceModel.getDateOfClass());\n attendance.setMinutesMissed(attendanceModel.getMinutesMissed());\n attendance.setStatus(attendanceModel.getStatus());\n attendance.setNotes(attendanceModel.getNotes());\n adjustMinutesMissedBasedOnAttendanceStatus(attendance);\n\n saveToDb.add(attendance);\n } else {\n if (attendancesInDBForCourse == null) {\n long beginLoad = System.currentTimeMillis();\n attendancesInDBForCourse = attendanceRepository.getAttendanceByCourseAndDayOfClass(sectionModel.getCanvasCourseId(), rosterForm.getCurrentDate());\n long endLoad = System.currentTimeMillis();\n LOG.debug(\"loaded \" + attendancesInDBForCourse.size() + \" attendance entries for course in \" + (endLoad - beginLoad) + \" millis..\");\n }\n\n Attendance attendance = attendancesInDBForCourse.stream().filter(a -> a.getAttendanceId().equals(attendanceModel.getAttendanceId())).findFirst().get();\n attendance.setMinutesMissed(attendanceModel.getMinutesMissed());\n attendance.setStatus(attendanceModel.getStatus());\n attendance.setNotes(attendanceModel.getNotes());\n adjustMinutesMissedBasedOnAttendanceStatus(attendance);\n\n saveToDb.add(attendance);\n }\n }\n }\n }\n\n long beginSave = System.currentTimeMillis();\n attendanceRepository.saveInBatches(saveToDb);\n long endSave = System.currentTimeMillis();\n\n long end = System.currentTimeMillis();\n LOG.debug(\"saving in batches took \" + (endSave - beginSave) + \" millis\");\n LOG.info(\"Saving attendances took \" + (end - begin) + \" millis\");\n }\n\n private void adjustMinutesMissedBasedOnAttendanceStatus(Attendance attendance) {\n if (attendance.getStatus() == Status.PRESENT) {\n attendance.setMinutesMissed(null);\n }\n }\n\n\n public void loadIntoForm(RosterForm rosterForm, Date date) {\n long begin = System.currentTimeMillis();\n\n Long canvasCourseId = rosterForm.getSectionModels().get(0).getCanvasCourseId();\n List<Attendance> attendancesInDb = attendanceRepository.getAttendanceByCourseAndDayOfClass(canvasCourseId, date);\n LOG.debug(\"attendances found for a given course and a given day of class: \" + attendancesInDb.size());\n\n for (SectionModel sectionModel : rosterForm.getSectionModels()) {\n List<AttendanceModel> sectionAttendances = new ArrayList<>();\n List<AttendanceStudent> attendanceStudents = studentRepository.findByCanvasSectionIdOrderByNameAsc(sectionModel.getCanvasSectionId());\n\n attendanceStudents.sort(Comparator.comparing(AttendanceStudent::getDeleted));\n\n for (AttendanceStudent student : attendanceStudents) {\n Attendance foundAttendance = findAttendanceFrom(attendancesInDb, student);\n if (foundAttendance == null) {\n Status status = student.getDeleted() ? Status.ABSENT : Status.NA;\n sectionAttendances.add(new AttendanceModel(student, status, date));\n } else {\n sectionAttendances.add(new AttendanceModel(foundAttendance));\n }\n }\n\n sectionModel.setAttendances(sectionAttendances);\n }\n\n long end = System.currentTimeMillis();\n LOG.info(\"loadAttendanceForDateIntoRoster took: \" + (end - begin) + \" millis\");\n }\n\n private Attendance findAttendanceFrom(List<Attendance> attendances, AttendanceStudent student) {\n List<Attendance> matchingAttendances =\n attendances.stream()\n .filter(attendance -> attendance.getAttendanceStudent().getStudentId().equals(student.getStudentId()))\n .collect(Collectors.toList());\n\n // by definition of the data there should only be one...\n return matchingAttendances.isEmpty() ? null : matchingAttendances.get(0);\n\n }\n\n @Transactional\n public boolean delete(RosterForm rosterForm) {\n List<Attendance> attendancesInDBForCourse = null;\n boolean sectionHasAttendancesForDate = false;\n for (SectionModel sectionModel : rosterForm.getSectionModels()) {\n if (sectionModel.getCanvasSectionId() != null && sectionModel.getCanvasSectionId().equals(rosterForm.getSectionId())) {\n attendancesInDBForCourse = attendanceRepository.getAttendanceByCourseAndDayOfClass(sectionModel.getCanvasCourseId(), rosterForm.getCurrentDate());\n if (!attendancesInDBForCourse.isEmpty()) {\n sectionHasAttendancesForDate = true;\n attendanceRepository.deleteAttendanceByCourseAndDayOfClass(sectionModel.getCanvasCourseId(), rosterForm.getCurrentDate(), rosterForm.getSectionId());\n }\n }\n }\n return sectionHasAttendancesForDate;\n }\n\n public Map<Long,String> getAttendanceCommentsBySectionId(long sectionId) {\n return attendanceRepository.getAttendanceCommentsBySectionId(sectionId);\n }\n\n}",
"public class DropDownOrganizer {\n\n\n private DropDownOrganizer() {\n // This is a utility class, so it doesn't need a public constructor\n }\n\n\n /**\n * Puts the selected section first in the list and sorts the rest alphabetically.\n */\n public static List<AttendanceSection> sortWithSelectedSectionFirst(List<AttendanceSection> sections, String selectedSectionId) {\n Optional<AttendanceSection> selectedSection = sections.stream().filter(s -> String.valueOf(s.getCanvasSectionId()).equals(selectedSectionId)).findFirst();\n List<AttendanceSection> remainingSections = sections.stream()\n .filter(s -> !String.valueOf(s.getCanvasSectionId()).equals(selectedSectionId))\n .sorted((s1, s2) -> s1.getName().compareTo(s2.getName()))\n .collect(Collectors.toList());\n \n List<AttendanceSection> organizedDropDown = new ArrayList<>();\n selectedSection.ifPresent(organizedDropDown::add);\n organizedDropDown.addAll(remainingSections);\n \n return organizedDropDown;\n }\n\n}"
] | import edu.ksu.canvas.attendance.entity.AttendanceSection;
import edu.ksu.canvas.attendance.form.RosterForm;
import edu.ksu.canvas.attendance.form.RosterFormValidator;
import edu.ksu.canvas.attendance.model.SectionModelFactory;
import edu.ksu.canvas.attendance.services.AttendanceCourseService;
import edu.ksu.canvas.attendance.services.AttendanceSectionService;
import edu.ksu.canvas.attendance.services.AttendanceService;
import edu.ksu.canvas.attendance.util.DropDownOrganizer;
import edu.ksu.lti.launch.exception.NoLtiSessionException;
import org.apache.commons.validator.routines.LongValidator;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List; | package edu.ksu.canvas.attendance.controller;
@Controller
@Scope("session")
@SessionAttributes("rosterForm")
@RequestMapping("/roster")
public class RosterController extends AttendanceBaseController {
private static final Logger LOG = LogManager.getLogger(RosterController.class);
@Autowired
private SectionModelFactory sectionModelFactory;
@Autowired
private AttendanceService attendanceService;
@Autowired
private AttendanceCourseService courseService;
@Autowired
private AttendanceSectionService sectionService;
@Autowired
private RosterFormValidator validator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
@RequestMapping()
public ModelAndView roster(@RequestParam(required = false) Date date) throws NoLtiSessionException {
return roster(date, null);
}
@RequestMapping("/{sectionId}")
public ModelAndView roster(@RequestParam(required = false) Date date, @PathVariable String sectionId) throws NoLtiSessionException {
ensureCanvasApiTokenPresent();
Long validatedSectionId = LongValidator.getInstance().validate(sectionId); | AttendanceSection selectedSection = getSelectedSection(validatedSectionId); | 0 |
onesocialweb/osw-lib-gwt | src/org/onesocialweb/gwt/service/imp/GwtActivities.java | [
"public class GwtActivityDomReader extends ActivityDomReader {\n\n\t@Override\n\tprotected AclDomReader getAclDomReader() {\n\t\treturn new GwtAclDomReader();\n\t}\n\n\t@Override\n\tprotected ActivityFactory getActivityFactory() {\n\t\treturn new DefaultActivityFactory();\n\t}\n\n\t@Override\n\tprotected AtomDomReader getAtomDomReader() {\n\t\treturn new GwtAtomDomReader();\n\t}\n\n\t@Override\n\tprotected Date parseDate(String atomDate) {\n\t\treturn AtomHelper.parseDate(atomDate);\n\t}\n\n}",
"public interface RequestCallback<T> {\n\n\tpublic void onSuccess(T result);\n\n\tpublic void onFailure();\n}",
"public interface Stream<T> extends Observable<StreamEvent<T>> {\n\n\tpublic List<T> getItems();\n\n\tpublic void refresh(RequestCallback<List<T>> callback);\n\n\tpublic boolean isReady();\n\n}",
"public abstract class StreamEvent<T> implements Event {\n\n\tpublic enum Type {\n\t\tadded, removed, cleared, refreshed\n\t};\n\n\tprivate final List<T> items;\n\n\tprivate final Type type;\n\n\tpublic StreamEvent(Type type, List<T> items) {\n\t\tthis.type = type;\n\t\tthis.items = items;\n\t}\n\t\n\n\tpublic List<T> getItems() {\n\t\treturn this.items;\n\t}\n\n\tpublic Type getType() {\n\t\treturn type;\n\t}\n}",
"public enum Type {\n\tadded, removed, cleared, refreshed\n};",
"public class ObservableHelper<T extends Event> implements Observable<T> {\n\n\tprivate final List<Observer<T>> observers = new ArrayList<Observer<T>>();\n\n\t@Override\n\tpublic void registerEventHandler(Observer<T> handler) {\n\t\tobservers.add(handler);\n\t}\n\n\t@Override\n\tpublic void unregisterEventHandler(Observer<T> handler) {\n\t\tobservers.remove(handler);\n\t}\n\n\tpublic void fireEvent(T event) {\n\t\tfor (Observer<T> observer : observers) {\n\t\t\tobserver.handleEvent(event);\n\t\t}\n\t}\n\n}",
"public interface Observer<T extends Event> {\n\n\tpublic void handleEvent(T event);\n\n}",
"public class ElementAdapter extends NodeAdapter implements Element {\n\n\tpublic ElementAdapter(com.google.gwt.xml.client.Element element) {\n\t\tsuper(element);\n\t}\n\n\t@Override\n\tpublic String getAttribute(String name) {\n\t\treturn getGwtElement().getAttribute(name);\n\t}\n\n\t@Override\n\tpublic String getAttributeNS(String namespaceURI, String localName)\n\t\t\tthrows DOMException {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Attr getAttributeNode(String name) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Attr getAttributeNodeNS(String namespaceURI, String localName)\n\t\t\tthrows DOMException {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic NodeList getElementsByTagName(String name) {\n\t\treturn new NodeListAdapter(getGwtElement().getElementsByTagName(name));\n\t}\n\n\t@Override\n\tpublic NodeList getElementsByTagNameNS(String namespaceURI, String localName)\n\t\t\tthrows DOMException {\n\t\treturn getElementsByTagName(localName);\n\t}\n\n\t@Override\n\tpublic TypeInfo getSchemaTypeInfo() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String getTagName() {\n\t\treturn getGwtElement().getTagName();\n\t}\n\n\t@Override\n\tpublic boolean hasAttribute(String name) {\n\t\treturn getGwtElement().hasAttribute(name);\n\t}\n\n\t@Override\n\tpublic boolean hasAttributeNS(String namespaceURI, String localName)\n\t\t\tthrows DOMException {\n\t\treturn hasAttribute(localName);\n\t}\n\n\t@Override\n\tpublic void removeAttribute(String name) throws DOMException {\n\t\tgetGwtElement().removeAttribute(name);\n\t}\n\n\t@Override\n\tpublic void removeAttributeNS(String namespaceURI, String localName)\n\t\t\tthrows DOMException {\n\t\tremoveAttribute(localName);\n\t}\n\n\t@Override\n\tpublic Attr removeAttributeNode(Attr oldAttr) throws DOMException {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void setAttribute(String name, String value) throws DOMException {\n\t\tgetGwtElement().setAttribute(name, value);\n\t}\n\n\t@Override\n\tpublic void setAttributeNS(String namespaceURI, String qualifiedName,\n\t\t\tString value) throws DOMException {\n\t\tgetGwtElement().setAttribute(qualifiedName, value);\n\t}\n\n\t@Override\n\tpublic Attr setAttributeNode(Attr newAttr) throws DOMException {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Attr setAttributeNodeNS(Attr newAttr) throws DOMException {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void setIdAttribute(String name, boolean isId) throws DOMException {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void setIdAttributeNS(String namespaceURI, String localName,\n\t\t\tboolean isId) throws DOMException {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void setIdAttributeNode(Attr idAttr, boolean isId)\n\t\t\tthrows DOMException {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\tpublic com.google.gwt.xml.client.Element getGwtElement() {\n\t\treturn (com.google.gwt.xml.client.Element) getGwtNode();\n\t}\n\n}",
"public interface Element extends Node {\n\t/**\n\t * The name of the element. If <code>Node.localName</code> is different from\n\t * <code>null</code>, this attribute is a qualified name. For example, in:\n\t * \n\t * <pre>\n\t * <elementExample id=\"demo\"> ... \n\t * </elementExample> ,\n\t * </pre>\n\t * \n\t * <code>tagName</code> has the value <code>\"elementExample\"</code>. Note\n\t * that this is case-preserving in XML, as are all of the operations of the\n\t * DOM. The HTML DOM returns the <code>tagName</code> of an HTML element in\n\t * the canonical uppercase form, regardless of the case in the source HTML\n\t * document.\n\t */\n\tpublic String getTagName();\n\n\t/**\n\t * Retrieves an attribute value by name.\n\t * \n\t * @param name\n\t * The name of the attribute to retrieve.\n\t * @return The <code>Attr</code> value as a string, or the empty string if\n\t * that attribute does not have a specified or default value.\n\t */\n\tpublic String getAttribute(String name);\n\n\t/**\n\t * Adds a new attribute. If an attribute with that name is already present\n\t * in the element, its value is changed to be that of the value parameter.\n\t * This value is a simple string; it is not parsed as it is being set. So\n\t * any markup (such as syntax to be recognized as an entity reference) is\n\t * treated as literal text, and needs to be appropriately escaped by the\n\t * implementation when it is written out. In order to assign an attribute\n\t * value that contains entity references, the user must create an\n\t * <code>Attr</code> node plus any <code>Text</code> and\n\t * <code>EntityReference</code> nodes, build the appropriate subtree, and\n\t * use <code>setAttributeNode</code> to assign it as the value of an\n\t * attribute. <br>\n\t * To set an attribute with a qualified name and namespace URI, use the\n\t * <code>setAttributeNS</code> method.\n\t * \n\t * @param name\n\t * The name of the attribute to create or alter.\n\t * @param value\n\t * Value to set in string form.\n\t * @exception DOMException\n\t * INVALID_CHARACTER_ERR: Raised if the specified name is not\n\t * an XML name according to the XML version in use specified\n\t * in the <code>Document.xmlVersion</code> attribute. <br>\n\t * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is\n\t * readonly.\n\t */\n\tpublic void setAttribute(String name, String value) throws DOMException;\n\n\t/**\n\t * Removes an attribute by name. If a default value for the removed\n\t * attribute is defined in the DTD, a new attribute immediately appears with\n\t * the default value as well as the corresponding namespace URI, local name,\n\t * and prefix when applicable. The implementation may handle default values\n\t * from other schemas similarly but applications should use\n\t * <code>Document.normalizeDocument()</code> to guarantee this information\n\t * is up-to-date. <br>\n\t * If no attribute with this name is found, this method has no effect. <br>\n\t * To remove an attribute by local name and namespace URI, use the\n\t * <code>removeAttributeNS</code> method.\n\t * \n\t * @param name\n\t * The name of the attribute to remove.\n\t * @exception DOMException\n\t * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is\n\t * readonly.\n\t */\n\tpublic void removeAttribute(String name) throws DOMException;\n\n\t/**\n\t * Retrieves an attribute node by name. <br>\n\t * To retrieve an attribute node by qualified name and namespace URI, use\n\t * the <code>getAttributeNodeNS</code> method.\n\t * \n\t * @param name\n\t * The name (<code>nodeName</code>) of the attribute to retrieve.\n\t * @return The <code>Attr</code> node with the specified name (\n\t * <code>nodeName</code>) or <code>null</code> if there is no such\n\t * attribute.\n\t */\n\tpublic Attr getAttributeNode(String name);\n\n\t/**\n\t * Adds a new attribute node. If an attribute with that name (\n\t * <code>nodeName</code>) is already present in the element, it is replaced\n\t * by the new one. Replacing an attribute node by itself has no effect. <br>\n\t * To add a new attribute node with a qualified name and namespace URI, use\n\t * the <code>setAttributeNodeNS</code> method.\n\t * \n\t * @param newAttr\n\t * The <code>Attr</code> node to add to the attribute list.\n\t * @return If the <code>newAttr</code> attribute replaces an existing\n\t * attribute, the replaced <code>Attr</code> node is returned,\n\t * otherwise <code>null</code> is returned.\n\t * @exception DOMException\n\t * WRONG_DOCUMENT_ERR: Raised if <code>newAttr</code> was\n\t * created from a different document than the one that\n\t * created the element. <br>\n\t * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is\n\t * readonly. <br>\n\t * INUSE_ATTRIBUTE_ERR: Raised if <code>newAttr</code> is\n\t * already an attribute of another <code>Element</code>\n\t * object. The DOM user must explicitly clone\n\t * <code>Attr</code> nodes to re-use them in other elements.\n\t */\n\tpublic Attr setAttributeNode(Attr newAttr) throws DOMException;\n\n\t/**\n\t * Removes the specified attribute node. If a default value for the removed\n\t * <code>Attr</code> node is defined in the DTD, a new node immediately\n\t * appears with the default value as well as the corresponding namespace\n\t * URI, local name, and prefix when applicable. The implementation may\n\t * handle default values from other schemas similarly but applications\n\t * should use <code>Document.normalizeDocument()</code> to guarantee this\n\t * information is up-to-date.\n\t * \n\t * @param oldAttr\n\t * The <code>Attr</code> node to remove from the attribute list.\n\t * @return The <code>Attr</code> node that was removed.\n\t * @exception DOMException\n\t * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is\n\t * readonly. <br>\n\t * NOT_FOUND_ERR: Raised if <code>oldAttr</code> is not an\n\t * attribute of the element.\n\t */\n\tpublic Attr removeAttributeNode(Attr oldAttr) throws DOMException;\n\n\t/**\n\t * Returns a <code>NodeList</code> of all descendant <code>Elements</code>\n\t * with a given tag name, in document order.\n\t * \n\t * @param name\n\t * The name of the tag to match on. The special value \"*\" matches\n\t * all tags.\n\t * @return A list of matching <code>Element</code> nodes.\n\t */\n\tpublic NodeList getElementsByTagName(String name);\n\n\t/**\n\t * Retrieves an attribute value by local name and namespace URI. <br>\n\t * Per [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML\n\t * Namespaces</a>] , applications must use the value <code>null</code> as\n\t * the <code>namespaceURI</code> parameter for methods if they wish to have\n\t * no namespace.\n\t * \n\t * @param namespaceURI\n\t * The namespace URI of the attribute to retrieve.\n\t * @param localName\n\t * The local name of the attribute to retrieve.\n\t * @return The <code>Attr</code> value as a string, or the empty string if\n\t * that attribute does not have a specified or default value.\n\t * @exception DOMException\n\t * NOT_SUPPORTED_ERR: May be raised if the implementation\n\t * does not support the feature <code>\"XML\"</code> and the\n\t * language exposed through the Document does not support XML\n\t * Namespaces (such as [<a href=\n\t * 'http://www.w3.org/TR/1999/REC-html401-19991224/'>HTML\n\t * 4.01</a>]).\n\t * @since DOM Level 2\n\t */\n\tpublic String getAttributeNS(String namespaceURI, String localName)\n\t\t\tthrows DOMException;\n\n\t/**\n\t * Adds a new attribute. If an attribute with the same local name and\n\t * namespace URI is already present on the element, its prefix is changed to\n\t * be the prefix part of the <code>qualifiedName</code>, and its value is\n\t * changed to be the <code>value</code> parameter. This value is a simple\n\t * string; it is not parsed as it is being set. So any markup (such as\n\t * syntax to be recognized as an entity reference) is treated as literal\n\t * text, and needs to be appropriately escaped by the implementation when it\n\t * is written out. In order to assign an attribute value that contains\n\t * entity references, the user must create an <code>Attr</code> node plus\n\t * any <code>Text</code> and <code>EntityReference</code> nodes, build the\n\t * appropriate subtree, and use <code>setAttributeNodeNS</code> or\n\t * <code>setAttributeNode</code> to assign it as the value of an attribute. <br>\n\t * Per [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML\n\t * Namespaces</a>] , applications must use the value <code>null</code> as\n\t * the <code>namespaceURI</code> parameter for methods if they wish to have\n\t * no namespace.\n\t * \n\t * @param namespaceURI\n\t * The namespace URI of the attribute to create or alter.\n\t * @param qualifiedName\n\t * The qualified name of the attribute to create or alter.\n\t * @param value\n\t * The value to set in string form.\n\t * @exception DOMException\n\t * INVALID_CHARACTER_ERR: Raised if the specified qualified\n\t * name is not an XML name according to the XML version in\n\t * use specified in the <code>Document.xmlVersion</code>\n\t * attribute. <br>\n\t * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is\n\t * readonly. <br>\n\t * NAMESPACE_ERR: Raised if the <code>qualifiedName</code> is\n\t * malformed per the Namespaces in XML specification, if the\n\t * <code>qualifiedName</code> has a prefix and the\n\t * <code>namespaceURI</code> is <code>null</code>, if the\n\t * <code>qualifiedName</code> has a prefix that is \"xml\" and\n\t * the <code>namespaceURI</code> is different from \"<a\n\t * href='http://www.w3.org/XML/1998/namespace'>\n\t * http://www.w3.org/XML/1998/namespace</a>\", if the\n\t * <code>qualifiedName</code> or its prefix is \"xmlns\" and\n\t * the <code>namespaceURI</code> is different from\n\t * \"<a href='http://www.w3.org/2000/xmlns/'>http://www.w3.org/2000/xmlns/</a>\"\n\t * , or if the <code>namespaceURI</code> is\n\t * \"<a href='http://www.w3.org/2000/xmlns/'>http://www.w3.org/2000/xmlns/</a>\"\n\t * and neither the <code>qualifiedName</code> nor its prefix\n\t * is \"xmlns\". <br>\n\t * NOT_SUPPORTED_ERR: May be raised if the implementation\n\t * does not support the feature <code>\"XML\"</code> and the\n\t * language exposed through the Document does not support XML\n\t * Namespaces (such as [<a href=\n\t * 'http://www.w3.org/TR/1999/REC-html401-19991224/'>HTML\n\t * 4.01</a>]).\n\t * @since DOM Level 2\n\t */\n\tpublic void setAttributeNS(String namespaceURI, String qualifiedName,\n\t\t\tString value) throws DOMException;\n\n\t/**\n\t * Removes an attribute by local name and namespace URI. If a default value\n\t * for the removed attribute is defined in the DTD, a new attribute\n\t * immediately appears with the default value as well as the corresponding\n\t * namespace URI, local name, and prefix when applicable. The implementation\n\t * may handle default values from other schemas similarly but applications\n\t * should use <code>Document.normalizeDocument()</code> to guarantee this\n\t * information is up-to-date. <br>\n\t * If no attribute with this local name and namespace URI is found, this\n\t * method has no effect. <br>\n\t * Per [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML\n\t * Namespaces</a>] , applications must use the value <code>null</code> as\n\t * the <code>namespaceURI</code> parameter for methods if they wish to have\n\t * no namespace.\n\t * \n\t * @param namespaceURI\n\t * The namespace URI of the attribute to remove.\n\t * @param localName\n\t * The local name of the attribute to remove.\n\t * @exception DOMException\n\t * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is\n\t * readonly. <br>\n\t * NOT_SUPPORTED_ERR: May be raised if the implementation\n\t * does not support the feature <code>\"XML\"</code> and the\n\t * language exposed through the Document does not support XML\n\t * Namespaces (such as [<a href=\n\t * 'http://www.w3.org/TR/1999/REC-html401-19991224/'>HTML\n\t * 4.01</a>]).\n\t * @since DOM Level 2\n\t */\n\tpublic void removeAttributeNS(String namespaceURI, String localName)\n\t\t\tthrows DOMException;\n\n\t/**\n\t * Retrieves an <code>Attr</code> node by local name and namespace URI. <br>\n\t * Per [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML\n\t * Namespaces</a>] , applications must use the value <code>null</code> as\n\t * the <code>namespaceURI</code> parameter for methods if they wish to have\n\t * no namespace.\n\t * \n\t * @param namespaceURI\n\t * The namespace URI of the attribute to retrieve.\n\t * @param localName\n\t * The local name of the attribute to retrieve.\n\t * @return The <code>Attr</code> node with the specified attribute local\n\t * name and namespace URI or <code>null</code> if there is no such\n\t * attribute.\n\t * @exception DOMException\n\t * NOT_SUPPORTED_ERR: May be raised if the implementation\n\t * does not support the feature <code>\"XML\"</code> and the\n\t * language exposed through the Document does not support XML\n\t * Namespaces (such as [<a href=\n\t * 'http://www.w3.org/TR/1999/REC-html401-19991224/'>HTML\n\t * 4.01</a>]).\n\t * @since DOM Level 2\n\t */\n\tpublic Attr getAttributeNodeNS(String namespaceURI, String localName)\n\t\t\tthrows DOMException;\n\n\t/**\n\t * Adds a new attribute. If an attribute with that local name and that\n\t * namespace URI is already present in the element, it is replaced by the\n\t * new one. Replacing an attribute node by itself has no effect. <br>\n\t * Per [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML\n\t * Namespaces</a>] , applications must use the value <code>null</code> as\n\t * the <code>namespaceURI</code> parameter for methods if they wish to have\n\t * no namespace.\n\t * \n\t * @param newAttr\n\t * The <code>Attr</code> node to add to the attribute list.\n\t * @return If the <code>newAttr</code> attribute replaces an existing\n\t * attribute with the same local name and namespace URI, the\n\t * replaced <code>Attr</code> node is returned, otherwise\n\t * <code>null</code> is returned.\n\t * @exception DOMException\n\t * WRONG_DOCUMENT_ERR: Raised if <code>newAttr</code> was\n\t * created from a different document than the one that\n\t * created the element. <br>\n\t * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is\n\t * readonly. <br>\n\t * INUSE_ATTRIBUTE_ERR: Raised if <code>newAttr</code> is\n\t * already an attribute of another <code>Element</code>\n\t * object. The DOM user must explicitly clone\n\t * <code>Attr</code> nodes to re-use them in other elements. <br>\n\t * NOT_SUPPORTED_ERR: May be raised if the implementation\n\t * does not support the feature <code>\"XML\"</code> and the\n\t * language exposed through the Document does not support XML\n\t * Namespaces (such as [<a href=\n\t * 'http://www.w3.org/TR/1999/REC-html401-19991224/'>HTML\n\t * 4.01</a>]).\n\t * @since DOM Level 2\n\t */\n\tpublic Attr setAttributeNodeNS(Attr newAttr) throws DOMException;\n\n\t/**\n\t * Returns a <code>NodeList</code> of all the descendant\n\t * <code>Elements</code> with a given local name and namespace URI in\n\t * document order.\n\t * \n\t * @param namespaceURI\n\t * The namespace URI of the elements to match on. The special\n\t * value \"*\" matches all namespaces.\n\t * @param localName\n\t * The local name of the elements to match on. The special value\n\t * \"*\" matches all local names.\n\t * @return A new <code>NodeList</code> object containing all the matched\n\t * <code>Elements</code>.\n\t * @exception DOMException\n\t * NOT_SUPPORTED_ERR: May be raised if the implementation\n\t * does not support the feature <code>\"XML\"</code> and the\n\t * language exposed through the Document does not support XML\n\t * Namespaces (such as [<a href=\n\t * 'http://www.w3.org/TR/1999/REC-html401-19991224/'>HTML\n\t * 4.01</a>]).\n\t * @since DOM Level 2\n\t */\n\tpublic NodeList getElementsByTagNameNS(String namespaceURI, String localName)\n\t\t\tthrows DOMException;\n\n\t/**\n\t * Returns <code>true</code> when an attribute with a given name is\n\t * specified on this element or has a default value, <code>false</code>\n\t * otherwise.\n\t * \n\t * @param name\n\t * The name of the attribute to look for.\n\t * @return <code>true</code> if an attribute with the given name is\n\t * specified on this element or has a default value,\n\t * <code>false</code> otherwise.\n\t * @since DOM Level 2\n\t */\n\tpublic boolean hasAttribute(String name);\n\n\t/**\n\t * Returns <code>true</code> when an attribute with a given local name and\n\t * namespace URI is specified on this element or has a default value,\n\t * <code>false</code> otherwise. <br>\n\t * Per [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML\n\t * Namespaces</a>] , applications must use the value <code>null</code> as\n\t * the <code>namespaceURI</code> parameter for methods if they wish to have\n\t * no namespace.\n\t * \n\t * @param namespaceURI\n\t * The namespace URI of the attribute to look for.\n\t * @param localName\n\t * The local name of the attribute to look for.\n\t * @return <code>true</code> if an attribute with the given local name and\n\t * namespace URI is specified or has a default value on this\n\t * element, <code>false</code> otherwise.\n\t * @exception DOMException\n\t * NOT_SUPPORTED_ERR: May be raised if the implementation\n\t * does not support the feature <code>\"XML\"</code> and the\n\t * language exposed through the Document does not support XML\n\t * Namespaces (such as [<a href=\n\t * 'http://www.w3.org/TR/1999/REC-html401-19991224/'>HTML\n\t * 4.01</a>]).\n\t * @since DOM Level 2\n\t */\n\tpublic boolean hasAttributeNS(String namespaceURI, String localName)\n\t\t\tthrows DOMException;\n\n\t/**\n\t * The type information associated with this element.\n\t * \n\t * @since DOM Level 3\n\t */\n\tpublic TypeInfo getSchemaTypeInfo();\n\n\t/**\n\t * If the parameter <code>isId</code> is <code>true</code>, this method\n\t * declares the specified attribute to be a user-determined ID attribute .\n\t * This affects the value of <code>Attr.isId</code> and the behavior of\n\t * <code>Document.getElementById</code>, but does not change any schema that\n\t * may be in use, in particular this does not affect the\n\t * <code>Attr.schemaTypeInfo</code> of the specified <code>Attr</code> node.\n\t * Use the value <code>false</code> for the parameter <code>isId</code> to\n\t * undeclare an attribute for being a user-determined ID attribute. <br>\n\t * To specify an attribute by local name and namespace URI, use the\n\t * <code>setIdAttributeNS</code> method.\n\t * \n\t * @param name\n\t * The name of the attribute.\n\t * @param isId\n\t * Whether the attribute is a of type ID.\n\t * @exception DOMException\n\t * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is\n\t * readonly. <br>\n\t * NOT_FOUND_ERR: Raised if the specified node is not an\n\t * attribute of this element.\n\t * @since DOM Level 3\n\t */\n\tpublic void setIdAttribute(String name, boolean isId) throws DOMException;\n\n\t/**\n\t * If the parameter <code>isId</code> is <code>true</code>, this method\n\t * declares the specified attribute to be a user-determined ID attribute .\n\t * This affects the value of <code>Attr.isId</code> and the behavior of\n\t * <code>Document.getElementById</code>, but does not change any schema that\n\t * may be in use, in particular this does not affect the\n\t * <code>Attr.schemaTypeInfo</code> of the specified <code>Attr</code> node.\n\t * Use the value <code>false</code> for the parameter <code>isId</code> to\n\t * undeclare an attribute for being a user-determined ID attribute.\n\t * \n\t * @param namespaceURI\n\t * The namespace URI of the attribute.\n\t * @param localName\n\t * The local name of the attribute.\n\t * @param isId\n\t * Whether the attribute is a of type ID.\n\t * @exception DOMException\n\t * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is\n\t * readonly. <br>\n\t * NOT_FOUND_ERR: Raised if the specified node is not an\n\t * attribute of this element.\n\t * @since DOM Level 3\n\t */\n\tpublic void setIdAttributeNS(String namespaceURI, String localName,\n\t\t\tboolean isId) throws DOMException;\n\n\t/**\n\t * If the parameter <code>isId</code> is <code>true</code>, this method\n\t * declares the specified attribute to be a user-determined ID attribute .\n\t * This affects the value of <code>Attr.isId</code> and the behavior of\n\t * <code>Document.getElementById</code>, but does not change any schema that\n\t * may be in use, in particular this does not affect the\n\t * <code>Attr.schemaTypeInfo</code> of the specified <code>Attr</code> node.\n\t * Use the value <code>false</code> for the parameter <code>isId</code> to\n\t * undeclare an attribute for being a user-determined ID attribute.\n\t * \n\t * @param idAttr\n\t * The attribute node.\n\t * @param isId\n\t * Whether the attribute is a of type ID.\n\t * @exception DOMException\n\t * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is\n\t * readonly. <br>\n\t * NOT_FOUND_ERR: Raised if the specified node is not an\n\t * attribute of this element.\n\t * @since DOM Level 3\n\t */\n\tpublic void setIdAttributeNode(Attr idAttr, boolean isId)\n\t\t\tthrows DOMException;\n\n}"
] | import java.util.ArrayList;
import java.util.List;
import org.onesocialweb.gwt.model.GwtActivityDomReader;
import org.onesocialweb.gwt.service.RequestCallback;
import org.onesocialweb.gwt.service.Stream;
import org.onesocialweb.gwt.service.StreamEvent;
import org.onesocialweb.gwt.service.StreamEvent.Type;
import org.onesocialweb.gwt.util.ObservableHelper;
import org.onesocialweb.gwt.util.Observer;
import org.onesocialweb.gwt.xml.ElementAdapter;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.xml.dom.ActivityDomReader;
import org.w3c.dom.Element;
import com.calclab.emite.core.client.packet.IPacket;
import com.calclab.emite.core.client.packet.gwt.GWTPacket;
import com.calclab.emite.core.client.xmpp.session.Session;
import com.calclab.emite.core.client.xmpp.stanzas.IQ;
import com.calclab.emite.core.client.xmpp.stanzas.XmppURI;
import com.calclab.suco.client.Suco;
import com.calclab.suco.client.events.Listener; | /*
* Copyright 2010 Vodafone Group Services 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 org.onesocialweb.gwt.service.imp;
public class GwtActivities implements Stream<ActivityEntry> {
private final ObservableHelper<StreamEvent<ActivityEntry>> helper = new ObservableHelper<StreamEvent<ActivityEntry>>();
private final Session session = Suco.get(Session.class);
private final String jid;
private final List<ActivityEntry> entries = new ArrayList<ActivityEntry>();
private boolean isReady = false;
public GwtActivities(String jid) {
this.jid = jid;
}
@Override
public List<ActivityEntry> getItems() {
return entries;
}
@Override
public void refresh(final RequestCallback<List<ActivityEntry>> callback) {
IQ iq = new IQ(IQ.Type.get);
IPacket pubsubElement = iq.addChild("pubsub",
"http://jabber.org/protocol/pubsub");
IPacket itemsElement = pubsubElement.addChild("items",
"http://jabber.org/protocol/pubsub");
itemsElement.setAttribute("node", "urn:xmpp:microblog:0");
iq.setTo(XmppURI.jid(jid));
session.sendIQ("osw", iq, new Listener<IPacket>() {
public void onEvent(IPacket packet) {
// Check if not an error
if (IQ.isSuccess(packet)) {
// IQ Succes means we can clear the existing entries
entries.clear();
// Parse the packet and check if a proper query result
IPacket pubsubResult = packet.getFirstChild("pubsub");
IPacket itemsResult = pubsubResult.getFirstChild("items");
if (itemsResult != null
&& itemsResult.getChildrenCount() > 0) {
// Parse the packet and store the notifications
for (IPacket item : itemsResult.getChildren()) {
if (item instanceof GWTPacket) {
GWTPacket i_packet = (GWTPacket) item
.getFirstChild("entry");
if (i_packet == null)
continue;
Element element = new ElementAdapter(i_packet
.getElement());
ActivityDomReader reader = new GwtActivityDomReader();
ActivityEntry activity = reader
.readEntry(element);
entries.add(activity);
}
}
}
// Set the ready flag to true
isReady = true;
// Fire the event to the observer
helper
.fireEvent(new ActivityEvent(Type.refreshed,
entries));
// Execute the callback
if (callback != null) {
callback.onSuccess(entries);
return;
}
// Done
return;
}
// If we are here, there was an error
if (callback != null) {
callback.onFailure();
}
}
});
}
@Override
public void registerEventHandler( | Observer<StreamEvent<ActivityEntry>> handler) { | 6 |
JavaBaas/JavaBaas_SDK_Android | source/src/main/java/com/javabaas/cache/JBCacheManager.java | [
"public abstract class IObjectManager {\n\n static String appKey = \"\";\n static String appId = \"\";\n static String host = \"\";\n static final int LOGIN_WITH_USERNAME_TYPE = 0;\n static final int LOGIN_WITH_SNS_TYPE = 1;\n static final int LOGIN_WITH_PHONE_TYPE = 2;\n\n private String tableName;\n private Context context;\n private static long timeDiff;\n\n IObjectManager(Context context, String tableName) {\n this.tableName = tableName;\n this.context = context;\n }\n\n\n /**\n * 保存或更新对象\n *\n * @param object 对象\n * @param id 对象id (更新对象时使用)\n * @param listener\n */\n void saveObject(final JBObject object, boolean isSync, String id, final SaveCallback listener) {\n String url;\n if (tableName.equals(\"_User\")) {\n url = \"/api/user\";\n } else\n url = \"/api/object/\" + tableName;\n int method = Method.POST;\n if (!Utils.isBlankString(id)) {\n url = url + \"/\" + id;\n method = Method.PUT;\n }\n HashMap clone = (HashMap) object.clone();\n for (Map.Entry<String, Object> stringObjectEntry : object.entrySet()) {\n Object value = stringObjectEntry.getValue();\n if (value instanceof JBFile || (value instanceof Map && ((Map) value).get(\"__type\") != null && ((Map) value).get(\"__type\").equals(\"File\"))) {\n JBFile file = new JBFile();\n file.putAll((Map) value);\n clone.put(stringObjectEntry.getKey(), Utils.mapFromFileObject(file));\n } else if (value instanceof JBObject) {\n clone.put(stringObjectEntry.getKey(), Utils.mapFromPointerObject((JBObject) value));\n } else if (value instanceof JBAcl) {\n clone.putAll(((JBAcl) value).getACLMap());\n }\n }\n JSONObject jsonObject = new JSONObject(true);\n jsonObject.putAll(clone);\n String requestBody = jsonObject.toString();\n\n customJsonRequest(context, isSync, new ResponseListener<CustomResponse>() {\n @Override\n public void onResponse(CustomResponse entity) {\n JSONObject response = JSON.parseObject(entity.getData());\n JSONObject data = response.getJSONObject(\"data\");\n object.putAll(data);\n if (listener != null) {\n listener.done(object);\n }\n }\n\n @Override\n public void onError(JBException e) {\n if (listener != null)\n listener.error(e);\n }\n }, url, method, requestBody);\n }\n\n\n /**\n * 删除对象\n *\n * @param id\n * @param deleteCallback\n */\n void deleteObject(String id, boolean isSync, final DeleteCallback deleteCallback) {\n String url = \"/api/object/\" + tableName + \"/\" + id;\n customJsonRequest(context, isSync, new ResponseListener<CustomResponse>() {\n @Override\n public void onResponse(CustomResponse entity) {\n if (deleteCallback != null) {\n deleteCallback.done();\n }\n }\n\n @Override\n public void onError(JBException e) {\n if (deleteCallback != null)\n deleteCallback.error(e);\n }\n }, url, Method.DELETE, null);\n }\n\n /**\n * 通过query删除\n *\n * @param parameters\n * @param isSync\n * @param deleteCallback\n */\n void deleteByQuery(final Map<String, String> parameters, boolean isSync, final DeleteCallback deleteCallback) {\n\n customJsonRequest(context, isSync, new ResponseListener<CustomResponse>() {\n @Override\n public void onResponse(CustomResponse entity) {\n if (deleteCallback != null) {\n deleteCallback.done();\n }\n }\n\n @Override\n public void onError(JBException e) {\n if (deleteCallback != null)\n deleteCallback.error(e);\n }\n }, \"/api/object/\" + tableName + \"/deleteByQuery\" + parseParameter(parameters), Method.DELETE, null);\n }\n\n /**\n * 对象查询\n *\n * @param parameters\n * @param findCallback\n * @param cacheType\n */\n void objectQuery(final Map<String, String> parameters, boolean isSync, final FindCallback<JBObject> findCallback, JBQuery.CachePolicy cacheType) {\n final StringBuilder url = new StringBuilder(\"/api/object/\" + tableName);\n\n url.append(parseParameter(parameters));\n\n if (cacheType == JBQuery.CachePolicy.CACHE_THEN_NETWORK || cacheType == JBQuery.CachePolicy.CACHE_ONLY) {\n JBCacheManager.sharedInstance().get(url.toString(), -1, tableName, JBObject.class, findCallback);\n if (cacheType == JBQuery.CachePolicy.CACHE_ONLY)\n return;\n }\n\n customJsonRequest(context, isSync, new ResponseListener<CustomResponse>() {\n @Override\n public void onResponse(CustomResponse entity) {\n List<JBObject> jbObjects = JSON.parseArray(entity.getData(), JBObject.class);\n for (JBObject jbObject : jbObjects) {\n parseJBObject(jbObject);\n jbObject.setClassName(tableName);\n }\n JBCacheManager.sharedInstance().save(url.toString(), entity.getData(), tableName);\n if (findCallback != null)\n findCallback.done(jbObjects);\n }\n\n @Override\n public void onError(JBException e) {\n if (findCallback != null)\n findCallback.error(e);\n }\n }, url.toString(), Method.GET, null);\n }\n\n\n /**\n * count查询\n *\n * @param parameters\n * @param callback\n */\n void countQuery(final Map<String, String> parameters, boolean isSync, final CountCallback callback) {\n customJsonRequest(context, isSync, new ResponseListener<CustomResponse>() {\n @Override\n public void onResponse(CustomResponse entity) {\n JSONObject data = JSON.parseObject(entity.getData());\n JSONObject dataJSONObject = data.getJSONObject(\"data\");\n int count = dataJSONObject.getIntValue(\"count\");\n if (callback != null)\n callback.done(count);\n }\n\n @Override\n public void onError(JBException e) {\n if (callback != null)\n callback.error(e);\n }\n }, \"/api/object/\" + tableName + \"/count\" + parseParameter(parameters), Method.GET, null);\n }\n\n /**\n * 自增\n *\n * @param incrementKeyAmount\n * @param objectId\n * @param isSync\n * @param callback\n */\n void incrementObjectKey(Map<String, Integer> incrementKeyAmount, String objectId, boolean isSync, final RequestCallback callback) {\n JSONObject jsonObject = new JSONObject(true);\n jsonObject.putAll(incrementKeyAmount);\n customJsonRequest(context, isSync, new ResponseListener<CustomResponse>() {\n @Override\n public void onResponse(CustomResponse entity) {\n if (callback != null)\n callback.done();\n }\n\n @Override\n public void onError(JBException e) {\n if (callback != null)\n callback.error(e);\n }\n }, \"/api/object/\" + tableName + \"/\" + objectId + \"/inc\", Method.PUT, jsonObject.toJSONString());\n }\n\n /**\n * 用户登录\n *\n * @param params\n * @param type\n * @param value\n * @param isSync\n * @param callback\n */\n void userLogin(Map<String, String> params, int type, int value, boolean isSync, final LoginCallback callback) {\n String url = \"/api/user/\";\n int method = Method.GET;\n String requestBody = null;\n switch (type) {\n case LOGIN_WITH_USERNAME_TYPE:\n url += \"login\";\n break;\n case LOGIN_WITH_SNS_TYPE:\n url = url + \"loginWithSns/\" + value;\n method = Method.POST;\n JSONObject jsonObject = new JSONObject();\n jsonObject.putAll(params);\n requestBody = jsonObject.toString();\n break;\n }\n\n customJsonRequest(context, isSync, new ResponseListener<CustomResponse>() {\n @Override\n public void onResponse(CustomResponse entity) {\n JSONObject data = JSON.parseObject(entity.getData());\n if (callback != null) {\n JBUser jbUser = new JBUser();\n jbUser.putAll(data);\n JBUser.changeCurrentUser(jbUser, true);\n callback.done(jbUser);\n }\n }\n\n @Override\n public void onError(JBException e) {\n if (callback != null)\n callback.error(e);\n }\n }, method == Method.GET ? url + parseParameter(params) : url, method, requestBody);\n }\n\n /**\n * 绑定第三方平台\n *\n * @param auth\n * @param userId\n * @param isSync\n * @param callback\n */\n void bindWithSns(JBUser.JBThirdPartyUserAuth auth, String userId, boolean isSync, final RequestCallback callback) {\n int snsType = auth.getSnsType();\n String url = \"/api/user/\" + userId + \"/binding/\" + snsType;\n HashMap<String, String> params = new HashMap<>();\n params.put(\"accessToken\", auth.accessToken);\n if(snsType == 3 || snsType == 1) {\n params.put(\"openId\", auth.getUserId());\n params.put(\"unionId\",auth.getUnionid());\n } else if(snsType == 2){\n params.put(\"uid\", auth.getUserId());\n }\n\n JSONObject jsonObject = new JSONObject();\n jsonObject.putAll(params);\n customJsonRequest(context, isSync, new ResponseListener<CustomResponse>() {\n @Override\n public void onResponse(CustomResponse entity) {\n if (callback != null)\n callback.done();\n }\n\n @Override\n public void onError(JBException e) {\n if (callback != null)\n callback.error(e);\n }\n }, url, Method.POST, jsonObject.toString());\n }\n\n /**\n * 更新密码\n *\n * @param params\n * @param callback\n */\n void updatePassword(Map<String, String> params, ResponseListener<CustomResponse> callback) {\n\n String url = \"/api/user/\" + JBUser.getCurrentUser().getId() + \"/updatePassword\";\n JSONObject jsonObject = new JSONObject();\n jsonObject.putAll(params);\n customJsonRequest(context, false, callback, url, Method.PUT, jsonObject.toString());\n }\n\n public abstract void customJsonRequest(final Context context, boolean isSync, final ResponseListener<CustomResponse> listener, final String url, final int method, final String requestBody);\n\n protected static Map<String, String> createRequestHeader() {\n if (timeDiff == 0L)\n timeDiff = (long) SharedPreferencesUtils.get(JBCloud.applicationContext, \"timeDiff\", 0L);\n String timestamp = String.valueOf(System.currentTimeMillis() + timeDiff);\n Map<String, String> headers = new HashMap<>();\n headers.put(\"JB-AppId\", appId);\n headers.put(\"JB-Timestamp\", timestamp);\n headers.put(\"JB-Plat\", \"android\");\n headers.put(\"JB-Sign\", Utils.MD5(appKey + \":\" + timestamp));\n headers.put(\"Content-Type\", \"application/json;charset=UTF-8\");\n if (JBUser.getCurrentUser() != null)\n headers.put(\"JB-SessionToken\", JBUser.getCurrentUser().getSessionToken());\n return headers;\n }\n\n public static void parseJBObject(JBObject jbObject) {\n for (String s : jbObject.keySet()) {\n Object o = jbObject.get(s);\n if (s.equals(\"acl\")) {\n JBAcl acl = new JBAcl(((Map) o));\n jbObject.put(s, acl);\n continue;\n }\n if (o instanceof Map) {\n Map map = (Map) o;\n JBObject object = new JBObject((String) map.get(\"className\"));\n object.putAll(map);\n parseJBObject(object);\n jbObject.put(s, object);\n }\n }\n }\n\n private String parseParameter(Map<String, String> parameters) {\n StringBuilder url = new StringBuilder();\n if (parameters != null) {\n url.append(\"?\");\n for (Map.Entry<String, String> stringStringEntry : parameters.entrySet()) {\n url.append(stringStringEntry.getKey()).append(\"=\").append(stringStringEntry.getValue()).append(\"&\");\n }\n }\n return url.toString();\n }\n\n public interface Method {\n int GET = 0;\n int POST = 1;\n int PUT = 2;\n int DELETE = 3;\n int HEAD = 4;\n int OPTIONS = 5;\n int TRACE = 6;\n int PATCH = 7;\n }\n}",
"public class JBCloud {\n public static Context applicationContext;\n\n static Class<? extends IObjectManager> objectManagerClass = null;\n\n public static final int CLOUD_FUNCTION_SUCCESS = 0;\n public static final int CLOUD_FUNCTION_ERROR = 1;\n\n /**\n *\n * @param context\n * @param appKey\n * @param appId\n * @param host base url\n */\n public static void init(Context context , String appKey , String appId , String host , GetInstallationIdCallback callback) {\n applicationContext = context;\n IObjectManager.appKey = appKey;\n IObjectManager.appId = appId;\n IObjectManager.host = host;\n syncTimestamp();\n getInstallationId(callback);\n setObjectManager(ObjectManagerImp.class);\n }\n\n public static void showLog(){\n Utils.showLog();\n }\n\n public static void setObjectManager(Class<? extends IObjectManager> objectManager){\n JBCloud.objectManagerClass = objectManager;\n }\n\n static IObjectManager getObjectManager(String tableName){\n if (objectManagerClass == null)\n setObjectManager(ObjectManagerImp.class);\n Class[] paramTypes = { Context.class, String.class};\n try {\n Constructor con = objectManagerClass.getConstructor(paramTypes);\n return ((IObjectManager) con.newInstance(applicationContext, tableName));\n } catch (Exception e) {\n throw new RuntimeException(\"IObjectManager illegal \" , e);\n }\n }\n\n public static void callFunctionInBackground(String name, Map<String, Object> params, final CloudCallback listener) {\n String url = \"/api/cloud/\" + name;\n StringBuilder stringBuffer = new StringBuilder(url);\n stringBuffer.append(\"?\");\n for (String s : params.keySet()) {\n Object o = params.get(s);\n stringBuffer.append(s).append(\"=\").append(String.valueOf(o)).append(\"&\");\n }\n JBCloud.getObjectManager(null).customJsonRequest(applicationContext, false ,new ResponseListener<CustomResponse>() {\n @Override\n public void onResponse(CustomResponse entity) {\n JSONObject response = JSON.parseObject(entity.getData());\n int code = response.getIntValue(\"code\");\n ResponseEntity responseEntity = new ResponseEntity();\n responseEntity.setCode(code);\n responseEntity.setData(response.getJSONObject(\"data\"));\n responseEntity.setMessage(response.getString(\"message\"));\n if (listener == null)\n return;\n if (code == CLOUD_FUNCTION_SUCCESS){\n listener.done(responseEntity);\n }else if (code == CLOUD_FUNCTION_ERROR){\n JBException jbException = new JBException(response.getString(\"message\"));\n jbException.errorCode = JBException.CLOUD_ERROR;\n listener.error(jbException , responseEntity);\n }else {\n listener.done(responseEntity);\n }\n }\n\n @Override\n public void onError(JBException e) {\n if (listener != null)\n listener.error(e , null);\n }\n }, stringBuffer.toString(), IObjectManager.Method.GET, null);\n }\n\n //获取InstallationID\n public static void getInstallationId(final GetInstallationIdCallback callback) {\n String installationId = (String) SharedPreferencesUtils.get(applicationContext, \"installationId\" , \"\");\n if (!TextUtils.isEmpty(installationId)){\n if (callback != null)\n callback.done(installationId);\n return;\n }\n String url = \"/api/installation\";\n HashMap<String, Object> params = new HashMap<>();\n params.put(\"deviceToken\" , getDeviceId());\n params.put(\"deviceType\" , \"android\");\n JBCloud.getObjectManager(null).customJsonRequest(applicationContext, false, new ResponseListener<CustomResponse>() {\n @Override\n public void onResponse(CustomResponse entity) {\n JSONObject response = JSON.parseObject(entity.getData());\n JSONObject data = response.getJSONObject(\"data\");\n String id = data.getString(\"_id\");\n Utils.printLog(\"InstallationId 获取成功 \"+id );\n if (callback != null)\n callback.done(id);\n if (id != null)\n SharedPreferencesUtils.put(applicationContext, \"installationId\", id);\n }\n\n @Override\n public void onError(JBException e) {\n Utils.printLog(\"InstallationId 获取失败 \"+ e.getMessage());\n if (callback != null)\n callback.error(e);\n }\n },url, IObjectManager.Method.POST, JSON.toJSONString(params));\n }\n\n //同步时间戳\n public static void syncTimestamp() {\n String url = \"/time\";\n Request.Builder builder = new Request.Builder();\n builder.get().url(IObjectManager.host + url);\n Call call = ObjectManagerImp.client.newCall(builder.build());\n call.enqueue(new Callback() {\n @Override\n public void onFailure(Call call, IOException e) {\n Utils.printLog(\"时间戳获取失败 \" + e.getMessage());\n }\n\n @Override\n public void onResponse(Call call, Response response) throws IOException {\n Utils.printLog(\"时间戳获取成功 \" );\n SharedPreferencesUtils.put(applicationContext, \"timeDiff\", Long.valueOf(response.body().string()) - System.currentTimeMillis());\n\n }\n });\n }\n\n //获取设备唯一ID\n public static String getDeviceId(){\n final TelephonyManager tm = (TelephonyManager) applicationContext.getSystemService(Context.TELEPHONY_SERVICE);\n final String tmDevice, tmSerial, androidId;\n tmDevice = \"\" + tm.getDeviceId();\n tmSerial = \"\" + tm.getSimSerialNumber();\n androidId = \"\" + android.provider.Settings.Secure.getString(applicationContext.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);\n UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());\n return deviceUuid.toString();\n }\n\n}",
"public interface FindCallback<T> {\n void done(List<T> result);\n void error(JBException e);\n}",
"public class JBObject extends LinkedHashMap<String, Object> {\n protected String className;\n\n public JBObject() {\n }\n\n public JBObject(String className) {\n this.className = className;\n }\n\n public void setId(String id) {\n this.put(\"_id\", id);\n }\n\n public String getId() {\n return (String) get(\"_id\");\n }\n\n public String getClassName() {\n return className;\n }\n\n public void setClassName(String className) {\n this.className = className;\n }\n\n public JBObject getJBObject(String key) {\n return (JBObject) get(key);\n }\n\n public Date getCreatedAt() {\n return new Date((long) get(\"createdAt\"));\n }\n\n public JBFile getJBFile(String key){\n Object o = get(key);\n if (o instanceof JSONObject){\n JBFile jbFile = new JBFile();\n jbFile.putAll(((JSONObject) o));\n return jbFile;\n }else if (o instanceof JBObject){\n JBFile jbFile = new JBFile();\n jbFile.putAll(((JBObject) o));\n return jbFile;\n }\n return null;\n }\n\n public int getInt(String key){\n Number v = (Number)this.get(key);\n return v != null?v.intValue():0;\n }\n\n public double getDouble(String key) {\n Number number = (Number)this.get(key);\n return number != null?number.doubleValue():0.0D;\n }\n\n public JSONArray getJSONArray(String key) {\n Object list = this.get(key);\n if(list == null) {\n return null;\n } else if(list instanceof JSONArray) {\n return (JSONArray)list;\n } else {\n JSONArray array;\n if(list instanceof Collection) {\n array = new JSONArray((Collection)list);\n return array;\n } else if(!(list instanceof Object[])) {\n return null;\n } else {\n array = new JSONArray();\n Object[] arr$ = (Object[])list;\n int len$ = arr$.length;\n\n for(int i$ = 0; i$ < len$; ++i$) {\n Object obj = arr$[i$];\n array.put(obj);\n }\n\n return array;\n }\n }\n }\n\n public org.json.JSONObject getJSONObject(String key) {\n Object object = this.get(key);\n if(object instanceof org.json.JSONObject) {\n return (org.json.JSONObject)object;\n } else {\n String jsonString = JSON.toJSONString(object);\n org.json.JSONObject jsonObject = null;\n\n try {\n jsonObject = new org.json.JSONObject(jsonString);\n return jsonObject;\n } catch (Exception var6) {\n throw new IllegalStateException(\"Invalid json string\", var6);\n }\n }\n }\n\n public List getList(String key) {\n return (List)this.get(key);\n }\n\n public long getLong(String key) {\n Number number = (Number)this.get(key);\n return number != null?number.longValue():0L;\n }\n\n public JBUser getJBUser(String key) {\n return (JBUser)this.get(key);\n }\n\n public Date getDate(String key){\n Object o = get(key);\n if (o instanceof Long){\n return new Date((Long) o);\n }else\n return o == null ? null : ((Date) o);\n }\n\n @Override\n public boolean equals(Object object) {\n return object instanceof JBObject && ((JBObject) object).getId().equals(getId());\n }\n\n public static JBObject createWithoutData(String className, String id) {\n JBObject jbObject = new JBObject(className);\n jbObject.setId(id);\n return jbObject;\n }\n\n\n public void saveInBackground(SaveCallback callback) {\n JBCloud.getObjectManager(className).saveObject(this, false, getId(), callback);\n }\n\n public JBObject save() throws JBException {\n final Object[] objects = new Object[2];\n JBCloud.getObjectManager(className).saveObject(this, true, getId(), new SaveCallback() {\n @Override\n public void done(JBObject object) {\n objects[0] = object;\n }\n\n @Override\n public void error(JBException e) {\n objects[1] = e;\n }\n });\n if (objects[1] != null)\n throw (JBException) objects[1];\n return (JBObject) objects[0];\n }\n\n public void deleteInBackground(DeleteCallback callback) {\n deleteByIdInBackground(className , getId() , callback);\n }\n\n public void delete()throws JBException{\n deleteById(className , getId());\n }\n\n public static void deleteByIdInBackground(String className, String id, DeleteCallback callback) {\n if (Utils.isBlankString(id))\n return;\n JBCloud.getObjectManager(className).deleteObject(id, false, callback);\n }\n\n public static void deleteById(String className, String id) throws JBException{\n if (Utils.isBlankString(id))\n return;\n final Object[] objects = new Object[1];\n JBCloud.getObjectManager(className).deleteObject(id, false, new DeleteCallback() {\n @Override\n public void done() {\n\n }\n\n @Override\n public void error(JBException e) {\n objects[0] = e;\n }\n });\n if (objects[1] != null)\n throw (JBException) objects[0];\n }\n\n public void incrementKeyInBackground(String key , RequestCallback callback){\n incrementKeyInBackground(key , 1 , callback);\n }\n\n public void incrementKeyInBackground(String key , int amount , RequestCallback callback){\n HashMap<String, Integer> map = new HashMap<>();\n map.put(key , amount);\n incrementKeysInBackground(className , getId() , map , callback);\n }\n\n public void incrementKey(String key) throws JBException {\n incrementKey(key , 1);\n }\n\n public void incrementKey(String key , int amount) throws JBException {\n HashMap<String, Integer> map = new HashMap<>();\n map.put(key , amount);\n incrementKeys(className , getId() , map);\n }\n\n public static void incrementKeysInBackground(String className , String id , Map<String , Integer> incrementKeyAmount , RequestCallback callback){\n if (Utils.isBlankString(id))\n return;\n JBCloud.getObjectManager(className).incrementObjectKey(incrementKeyAmount , id , false , callback);\n }\n\n public static void incrementKeys(String className , String id , Map<String , Integer> incrementKeyAmount) throws JBException{\n if (Utils.isBlankString(id))\n return;\n final Object[] objects = new Object[1];\n JBCloud.getObjectManager(className).incrementObjectKey(incrementKeyAmount, id, true, new RequestCallback() {\n @Override\n public void done() {\n\n }\n\n @Override\n public void error(JBException e) {\n objects[0] = e;\n }\n });\n if (objects[0] != null){\n throw (JBException) objects[0];\n }\n }\n}",
"public class JBException extends Exception {\n /**\n * 认证失败\n */\n public static int AUTH_FAILURE_ERROR = 1;\n\n /**\n * 网络错误\n */\n public static int NETWORK_ERROR = 2;\n\n /**\n * 解析错误\n */\n public static int PARSE_ERROR = 3;\n\n /**\n * 服务器错误\n */\n public static int SERVER_ERROR = 4;\n\n /**\n * 云方法错误\n */\n public static int CLOUD_ERROR = 5;\n\n /**\n * 上传错误\n */\n public static int UPLOAD_ERROR = 6;\n\n //responseErrorCode\n public static int SESSION_TOKEN_ERROR_CODE = 1310;\n\n public int errorCode;\n public int responseErrorCode;\n public String responseErrorMsg;\n\n public JBException() {\n }\n\n public JBException(String detailMessage) {\n super(detailMessage);\n }\n\n public JBException(int errorCode , String detailMessage) {\n super(detailMessage);\n this.errorCode = errorCode;\n }\n\n public int getErrorCode() {\n return errorCode;\n }\n\n public int getResponseErrorCode() {\n return responseErrorCode;\n }\n\n public String getResponseErrorMsg() {\n return responseErrorMsg;\n }\n}",
"public class Utils {\n public static boolean isBlankString(String str) {\n return str == null || str.trim().equals(\"\");\n }\n\n private static Map<Class<?>, Field[]> fieldsMap = Collections.synchronizedMap(new WeakHashMap());\n static Pattern pattern = Pattern.compile(\"^[a-zA-Z_][a-zA-Z_0-9]*$\");\n static Pattern emailPattern = Pattern.compile(\"^\\\\w+?@\\\\w+?[.]\\\\w+\");\n static Pattern phoneNumPattern = Pattern.compile(\"1\\\\d{10}\");\n static Pattern verifyCodePattern = Pattern.compile(\"\\\\d{6}\");\n private static final ThreadLocal<SimpleDateFormat> THREAD_LOCAL_DATE_FORMAT = new ThreadLocal();\n static Random random = new Random();\n public static boolean isEmptyList(List e) {\n return e == null || e.isEmpty();\n }\n\n public static Field[] getAllFields(Class<?> clazz) {\n if(clazz != null && clazz != Object.class) {\n Field[] theResult = fieldsMap.get(clazz);\n if(theResult != null) {\n return theResult;\n } else {\n ArrayList fields = new ArrayList();\n\n int length;\n for(length = 0; clazz != null && clazz != Object.class; clazz = clazz.getSuperclass()) {\n Field[] i = clazz.getDeclaredFields();\n length += i != null?i.length:0;\n fields.add(i);\n }\n\n theResult = new Field[length];\n int var11 = 0;\n Iterator i$ = fields.iterator();\n\n while(true) {\n Field[] someFields;\n do {\n if(!i$.hasNext()) {\n fieldsMap.put(clazz, theResult);\n return theResult;\n }\n\n someFields = (Field[])i$.next();\n } while(someFields == null);\n\n Field[] arr$ = someFields;\n int len$ = someFields.length;\n\n for(int i$1 = 0; i$1 < len$; ++i$1) {\n Field field = arr$[i$1];\n field.setAccessible(true);\n }\n\n System.arraycopy(someFields, 0, theResult, var11, someFields.length);\n var11 += someFields.length;\n }\n }\n } else {\n return new Field[0];\n }\n }\n\n public static boolean checkEmailAddress(String email) {\n return emailPattern.matcher(email).find();\n }\n\n public static boolean checkMobilePhoneNumber(String phoneNumber) {\n return phoneNumPattern.matcher(phoneNumber).find();\n }\n\n public static boolean checkMobileVerifyCode(String verifyCode) {\n return verifyCodePattern.matcher(verifyCode).find();\n }\n\n public static void checkClassName(String className) {\n if(isBlankString(className)) {\n throw new IllegalArgumentException(\"Blank class name\");\n } else if(!pattern.matcher(className).matches()) {\n throw new IllegalArgumentException(\"Invalid class name\");\n }\n }\n\n public static boolean isBlankContent(String content) {\n return isBlankString(content) || content.trim().equals(\"{}\");\n }\n\n public static boolean contains(Map<String, Object> map, String key) {\n return map.containsKey(key);\n }\n\n public static Map<String, Object> createDeleteOpMap(String key) {\n HashMap map = new HashMap();\n map.put(\"__op\", \"Delete\");\n HashMap result = new HashMap();\n result.put(key, map);\n return result;\n }\n\n public static Map<String, Object> createStringObjectMap(String key, Object value) {\n HashMap map = new HashMap();\n map.put(key, value);\n return map;\n }\n\n public static Map<String, Object> mapFromPointerObject(JBObject object) {\n HashMap result = new LinkedHashMap();\n result.put(\"__type\", \"Pointer\");\n result.put(\"className\", object.getClassName());\n if(!isBlankString(object.getId())) {\n result.put(\"_id\", object.getId());\n }\n return result;\n }\n\n public static Map<String, Object> mapFromFileObject(JBFile object) {\n HashMap result = new LinkedHashMap();\n result.put(\"__type\", \"File\");\n if(!isBlankString(object.getId())) {\n result.put(\"_id\", object.getId());\n }\n return result;\n }\n\n public static Map<String, Object> mapFromUserObjectId(String userObjectId) {\n if(isBlankString(userObjectId)) {\n return null;\n } else {\n HashMap result = new HashMap();\n result.put(\"__type\", \"Pointer\");\n result.put(\"className\", \"_User\");\n result.put(\"_id\", userObjectId);\n return result;\n }\n }\n\n public static boolean isDigitString(String s) {\n if(s == null) {\n return false;\n } else {\n for(int i = 0; i < s.length(); ++i) {\n char c = s.charAt(i);\n if(!Character.isDigit(c)) {\n return false;\n }\n }\n\n return true;\n }\n }\n\n public static Date dateFromString(String content) {\n if(isBlankString(content)) {\n return null;\n } else if(isDigitString(content)) {\n return new Date(Long.parseLong(content));\n } else {\n Date date = null;\n SimpleDateFormat format = THREAD_LOCAL_DATE_FORMAT.get();\n if(format == null) {\n format = new SimpleDateFormat(\"yyyy-MM-dd\\'T\\'HH:mm:ss.SSS\\'Z\\'\");\n format.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n THREAD_LOCAL_DATE_FORMAT.set(format);\n }\n\n try {\n date = format.parse(content);\n } catch (Exception var4) {\n }\n\n return date;\n }\n }\n\n public static String stringFromDate(Date date) {\n SimpleDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd\\'T\\'HH:mm:ss.SSS\\'Z\\'\");\n df.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n String isoDate = df.format(date);\n return isoDate;\n }\n\n public static long mapFromDate(Date date) {\n HashMap result = new HashMap();\n result.put(\"__type\", \"Date\");\n result.put(\"iso\", stringFromDate(date));\n return date.getTime();\n }\n\n public static Date dateFromMap(Map<String, Object> map) {\n String value = (String)map.get(\"iso\");\n return dateFromString(value);\n }\n\n public static Map<String, Object> mapFromByteArray(byte[] data) {\n HashMap result = new HashMap();\n result.put(\"__type\", \"Bytes\");\n result.put(\"base64\", Base64.encodeToString(data, 2));\n return result;\n }\n\n public static byte[] dataFromMap(Map<String, Object> map) {\n String value = (String)map.get(\"base64\");\n return Base64.decode(value, 2);\n }\n\n\n public static boolean hasProperty(Class<?> clazz, String property) {\n Field[] fields = getAllFields(clazz);\n Field[] arr$ = fields;\n int len$ = fields.length;\n\n for(int i$ = 0; i$ < len$; ++i$) {\n Field f = arr$[i$];\n if(f.getName().equals(property)) {\n return true;\n }\n }\n\n return false;\n }\n\n public static boolean checkAndSetValue(Class<?> clazz, Object parent, String property, Object value) {\n if(clazz == null) {\n return false;\n } else {\n try {\n Field[] exception = getAllFields(clazz);\n Field[] arr$ = exception;\n int len$ = exception.length;\n\n for(int i$ = 0; i$ < len$; ++i$) {\n Field f = arr$[i$];\n if(f.getName().equals(property) && (f.getType().isInstance(value) || value == null)) {\n f.set(parent, value);\n return true;\n }\n }\n\n return false;\n } catch (Exception var9) {\n return false;\n }\n }\n }\n\n public static String getJSONValue(String msg, String key) {\n Map jsonMap = JSON.parseObject(msg, HashMap.class);\n if(jsonMap != null && !jsonMap.isEmpty()) {\n Object action = jsonMap.get(key);\n return action != null?action.toString():null;\n } else {\n return null;\n }\n }\n\n public static String jsonStringFromMapWithNull(Object map) {\n return JSON.toJSONString(map, new SerializerFeature[]{SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullNumberAsZero});\n }\n\n public static String jsonStringFromObjectWithNull(Object map) {\n return JSON.toJSONString(map, new SerializerFeature[]{SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullNumberAsZero});\n }\n\n public static String restfulServerData(Map<String, Object> data) {\n if(data == null) {\n return \"{}\";\n } else {\n Map map = getParsedMap(data);\n return jsonStringFromMapWithNull(map);\n }\n }\n\n public static Map<String, Object> getParsedMap(Map<String, Object> map) {\n LinkedHashMap newMap = new LinkedHashMap<>(map.size());\n Iterator i$ = map.entrySet().iterator();\n\n while(i$.hasNext()) {\n Map.Entry entry = (Map.Entry)i$.next();\n String key = (String)entry.getKey();\n Object o = entry.getValue();\n newMap.put(key, getParsedObject(o));\n }\n\n return newMap;\n }\n\n public static Object getParsedObject(Object object) {\n return object == null?null:(object instanceof JBObject? mapFromPointerObject((JBObject) object):(object instanceof Map ?getParsedMap((Map) object):(object instanceof Collection ?getParsedList((Collection) object):(object instanceof Date ?mapFromDate((Date) object):(object instanceof byte[]?mapFromByteArray((byte[])((byte[])object)):((object instanceof JSONObject ?JSON.parse(object.toString()):(object instanceof JSONArray ?JSON.parse(object.toString()):object))))))));\n }\n\n static List getParsedList(Collection list) {\n ArrayList newList = new ArrayList(list.size());\n Iterator i$ = list.iterator();\n\n while(i$.hasNext()) {\n Object o = i$.next();\n newList.add(getParsedObject(o));\n }\n\n return newList;\n }\n\n public static String joinCollection(Collection<String> collection, String separator) {\n StringBuilder builder = new StringBuilder();\n boolean wasFirst = true;\n Iterator i$ = collection.iterator();\n\n while(i$.hasNext()) {\n String value = (String)i$.next();\n if(wasFirst) {\n wasFirst = false;\n builder.append(value);\n } else {\n builder.append(separator).append(value);\n }\n }\n\n return builder.toString();\n }\n\n public static boolean isWifi(Context context) {\n ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();\n return activeNetInfo != null && activeNetInfo.getType() == 1;\n }\n\n public static String stringFromBytes(byte[] bytes) {\n try {\n return new String(bytes, \"UTF-8\");\n } catch (Exception var2) {\n return null;\n }\n }\n\n public static String base64Encode(String data) {\n return Base64.encodeToString(data.getBytes(), 10);\n }\n\n public static String getRandomString(int length) {\n String letters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n StringBuilder randomString = new StringBuilder(length);\n\n for(int i = 0; i < length; ++i) {\n randomString.append(letters.charAt(random.nextInt(letters.length())));\n }\n\n return randomString.toString();\n }\n\n public static Map<String, Object> createMap(String cmp, Object value) {\n HashMap dict = new HashMap();\n dict.put(cmp, value);\n return dict;\n }\n\n public static String MD5(String s) {\n char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};\n try {\n byte[] btInput = s.getBytes();\n // 获得MD5摘要算法的 MessageDigest 对象\n MessageDigest mdInst = MessageDigest.getInstance(\"MD5\");\n // 使用指定的字节更新摘要\n mdInst.update(btInput);\n // 获得密文\n byte[] md = mdInst.digest();\n // 把密文转换成十六进制的字符串形式\n int j = md.length;\n char str[] = new char[j * 2];\n int k = 0;\n for (byte byte0 : md) {\n str[k++] = hexDigits[byte0 >>> 4 & 0xf];\n str[k++] = hexDigits[byte0 & 0xf];\n }\n return new String(str).toLowerCase();\n } catch (Exception e) {\n return \"\";\n }\n }\n\n public static boolean isEmpty(CharSequence str) {\n if (str == null || str.length() == 0)\n return true;\n else\n return false;\n }\n\n private static boolean isShowLog = false;\n private static String JAVA_BAAS_LOG = \"JavaBaasLog\";\n public static void showLog(){\n isShowLog = true;\n }\n\n public static void printLog(String msg){\n if (isShowLog){\n Log.d(JAVA_BAAS_LOG , msg);\n }\n }\n\n}"
] | import com.alibaba.fastjson.JSON;
import java.io.File;
import java.util.List;
import com.javabaas.IObjectManager;
import com.javabaas.JBCloud;
import com.javabaas.callback.FindCallback;
import com.javabaas.JBObject;
import com.javabaas.exception.JBException;
import com.javabaas.util.Utils; | package com.javabaas.cache;
public class JBCacheManager {
private static JBCacheManager instance = null;
private static File keyValueCacheDir() {
File dir = new File(JBPersistenceUtils.getCacheDir(), "JBKeyValueCache");
dir.mkdirs();
return dir;
}
private static File getCacheFile(String fileName) {
return new File(keyValueCacheDir(), fileName);
}
private JBCacheManager() {
}
public static synchronized JBCacheManager sharedInstance() {
if(instance == null) {
instance = new JBCacheManager();
}
return instance;
}
public String fileCacheKey(String key, String ts) {
return !Utils.isBlankString(ts)?Utils.MD5(key + ts):Utils.MD5(key);
}
public boolean hasCache(String key) {
return this.hasCache(key, (String)null);
}
public boolean hasCache(String key, String ts) {
File file = this.getCacheFile(key, ts);
return file.exists();
}
public boolean hasValidCache(String key, String ts, long maxAgeInMilliseconds) {
File file = this.getCacheFile(key, ts);
return file.exists() && System.currentTimeMillis() - file.lastModified() < maxAgeInMilliseconds;
}
private File getCacheFile(String key, String ts) {
return getCacheFile(this.fileCacheKey(key, ts));
}
| public <T> void get(String key, long maxAgeInMilliseconds, String className, Class<T> clazz, FindCallback<T> getCallback) { | 2 |
6ag/BaoKanAndroid | app/src/main/java/tv/baokan/baokanandroid/ui/fragment/NewsFragment.java | [
"public class TabFragmentPagerAdapter extends FragmentPagerAdapter {\n\n private List<ColumnBean> mSelectedList = new ArrayList<>();\n private List<BaseFragment> mListFragments = new ArrayList<>();\n\n public TabFragmentPagerAdapter(FragmentManager fm, List<? extends BaseFragment> listFragments, List<ColumnBean> selectedList) {\n super(fm);\n this.mListFragments.addAll(listFragments);\n this.mSelectedList.addAll(selectedList);\n }\n\n /**\n * 重新加载数据\n *\n * @param newListFragments 新的fragment集合\n * @param newSelectedList 新的选中分类集合\n */\n public void reloadData(List<? extends BaseFragment> newListFragments, List<ColumnBean> newSelectedList) {\n\n // 清除原有数据源\n this.mListFragments.clear();\n this.mSelectedList.clear();\n\n // 重新添加数据源\n this.mListFragments.addAll(newListFragments);\n this.mSelectedList.addAll(newSelectedList);\n\n // 刷新数据\n notifyDataSetChanged();\n }\n\n @Override\n public Object instantiateItem(ViewGroup container, int position) {\n return super.instantiateItem(container, position);\n }\n\n @Override\n public Fragment getItem(int position) {\n return mListFragments.get(position);\n }\n\n @Override\n public int getCount() {\n return mListFragments.size();\n }\n\n @Override\n public void destroyItem(ViewGroup container, int position, Object object) {\n // 重写父类销毁方法,就切换viewPager上的列表就不会重复去加载数据,但是会增加内存占用\n }\n\n @Override\n public CharSequence getPageTitle(int position) {\n return mSelectedList.get(position).getClassname();\n }\n\n}",
"public class BaoKanApp extends LitePalApplication {\n\n private static final String TAG = \"BaoKanApp\";\n\n public static BaoKanApp app;\n\n // 用于存放所有启动的Activity的集合\n private List<Activity> mActivityList;\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n app = this;\n\n // 存放所有activity的集合\n mActivityList = new ArrayList<>();\n\n // 渐进式图片\n ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this)\n .setProgressiveJpegConfig(new SimpleProgressiveJpegConfig())\n .build();\n Fresco.initialize(this, config);\n\n // 初始化app异常处理器 - 打包的时候开启\n CrashHandler handler = CrashHandler.getInstance();\n handler.init(getApplicationContext());\n\n// OkHttpClient okHttpClient = new OkHttpClient.Builder()\n// .connectTimeout(10000L, TimeUnit.MILLISECONDS)\n// .readTimeout(10000L, TimeUnit.MILLISECONDS)\n// //其他配置\n// .build();\n// OkHttpUtils.initClient(okHttpClient);\n\n // 初始化ShareSDK\n ShareSDK.initSDK(this);\n\n }\n\n @Override\n public void onTerminate() {\n super.onTerminate();\n\n }\n\n /**\n * 获取当前应用的版本号\n *\n * @return 版本号\n */\n public String getVersionName() {\n PackageManager pm = getPackageManager();\n // 第一个参数:应用程序的包名\n // 第二个参数:指定信息的标签,0表示获取基础信息,比如包名、版本号。要想获取权限等信息必须要通过标签指定。\n try {\n PackageInfo info = pm.getPackageInfo(getPackageName(), 0);\n return info.versionName;\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n }\n return \"\";\n }\n\n /**\n * 添加Activity\n */\n public void addActivity(Activity activity) {\n if (!mActivityList.contains(activity)) {\n mActivityList.add(activity);\n }\n }\n\n /**\n * 销毁单个Activity\n */\n public void removeActivity(Activity activity) {\n if (mActivityList.contains(activity)) {\n mActivityList.remove(activity);\n if (!activity.isFinishing()) {\n activity.finish();\n }\n }\n }\n\n /**\n * 销毁所有的Activity\n */\n public void removeAllActivity() {\n for (Activity activity : mActivityList) {\n if (!activity.isFinishing()) {\n activity.finish();\n }\n }\n }\n\n /**\n * 获取当前应用的版本号\n *\n * @return 版本号\n */\n// private String getVersionName() {\n// PackageManager pm = getPackageManager();\n// // 第一个参数:应用程序的包名\n// // 第二个参数:指定信息的标签,0表示获取基础信息,比如包名、版本号。要想获取权限等信息必须要通过标签指定。\n// try {\n// PackageInfo info = pm.getPackageInfo(getPackageName(), 0);\n// return info.versionName;\n// } catch (PackageManager.NameNotFoundException e) {\n// e.printStackTrace();\n// }\n// return \"\";\n// }\n}",
"public class ColumnBean implements Serializable {\n\n // 分类id\n private String classid;\n\n // 分类名称\n private String classname;\n\n public ColumnBean(String classid, String classname) {\n this.classid = classid;\n this.classname = classname;\n }\n\n public String getClassid() {\n return classid;\n }\n\n public void setClassid(String classid) {\n this.classid = classid;\n }\n\n public String getClassname() {\n return classname;\n }\n\n public void setClassname(String classname) {\n this.classname = classname;\n }\n}",
"public class ColumnActivity extends BaseActivity implements OnItemClickListener {\n\n private static final String TAG = \"ColumnActivity\";\n\n private OptionalGridView mOtherGv;\n private DragGridView mUserGv;\n private List<ColumnBean> selectedList = new ArrayList<>();\n private List<ColumnBean> optionalList = new ArrayList<>();\n private OptionalGridViewAdapter mOptionalGridViewAdapter;\n private DragGridViewAdapter mDragGridViewAdapter;\n private NavigationViewRed mNavigationViewRed;\n\n /**\n * 便捷启动当前activity\n *\n * @param activity 启动当前activity的activity\n */\n public static void start(Activity activity, List<ColumnBean> selectedList, List<ColumnBean> optionalList) {\n Intent intent = new Intent(activity, ColumnActivity.class);\n Bundle bundle = new Bundle();\n bundle.putSerializable(\"selectedList_key\", (Serializable) selectedList);\n bundle.putSerializable(\"optionalList_key\", (Serializable) optionalList);\n intent.putExtras(bundle);\n activity.startActivityForResult(intent, NewsFragment.REQUEST_CODE_COLUMN);\n activity.overridePendingTransition(R.anim.column_show, R.anim.column_bottom);\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_column);\n\n // 取出栏目数据\n Intent intent = getIntent();\n selectedList = (List<ColumnBean>) intent.getSerializableExtra(\"selectedList_key\");\n optionalList = (List<ColumnBean>) intent.getSerializableExtra(\"optionalList_key\");\n\n mNavigationViewRed = (NavigationViewRed) findViewById(R.id.nav_column);\n mNavigationViewRed.getRightView().setImageResource(R.drawable.top_navigation_close);\n mNavigationViewRed.setupNavigationView(false, true, \"栏目管理\", new NavigationViewRed.OnClickListener() {\n @Override\n public void onRightClick(View v) {\n setupResultData();\n finish();\n }\n });\n\n // 准备UI\n prepareUI();\n }\n\n /**\n * 准备UI\n */\n public void prepareUI() {\n mUserGv = (DragGridView) findViewById(R.id.userGridView);\n mOtherGv = (OptionalGridView) findViewById(R.id.otherGridView);\n\n // 配置GridView\n mDragGridViewAdapter = new DragGridViewAdapter(this, selectedList, true);\n mOptionalGridViewAdapter = new OptionalGridViewAdapter(this, optionalList, false);\n mUserGv.setAdapter(mDragGridViewAdapter);\n mOtherGv.setAdapter(mOptionalGridViewAdapter);\n mUserGv.setOnItemClickListener(this);\n mOtherGv.setOnItemClickListener(this);\n }\n\n // 返回true则是不继续传播事件,自己处理。返回false则系统继续传播处理\n @Override\n public boolean onKeyDown(int keyCode, KeyEvent event) {\n if (keyCode == KeyEvent.KEYCODE_BACK) {\n setupResultData();\n finish();\n return true;\n }\n return super.onKeyDown(keyCode, event);\n }\n\n /**\n * 设置回调数据\n */\n private void setupResultData() {\n // 在回调数据之前,缓存数据到本地\n HashMap<String, List<ColumnBean>> map = new HashMap<>();\n map.put(\"selected\", mDragGridViewAdapter.getSelectedList());\n map.put(\"optional\", mOptionalGridViewAdapter.getOptionalList());\n String jsonString = JSON.toJSONString(map);\n // 将栏目数据写入本地\n StreamUtils.writeStringToFile(\"column.json\", jsonString);\n LogUtils.d(TAG, jsonString);\n\n Intent intent = new Intent();\n Bundle bundle = new Bundle();\n bundle.putSerializable(\"selectedList_key\", (Serializable) mDragGridViewAdapter.getSelectedList());\n bundle.putSerializable(\"optionalList_key\", (Serializable) mOptionalGridViewAdapter.getOptionalList());\n intent.putExtras(bundle);\n // 这里会回调给MainActivity,然后在MainActivity里传递给NewsFragment\n setResult(RESULT_OK, intent);\n }\n\n /**\n * 获取点击的item的对应View,\n * 因为点击的Item已经有了自己归属的父容器MyGridView,所有我们要是有一个ImageView来代替Item移动\n *\n * @param view\n * @return\n */\n private ImageView getView(View view) {\n view.destroyDrawingCache();\n view.setDrawingCacheEnabled(true);\n Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());\n view.setDrawingCacheEnabled(false);\n ImageView iv = new ImageView(this);\n iv.setImageBitmap(cache);\n return iv;\n }\n\n /**\n * 获取移动的view,放入对应ViewGroup布局容器\n *\n * @param viewGroup\n * @param view\n * @param initLocation\n * @return\n */\n private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {\n int x = initLocation[0];\n int y = initLocation[1];\n viewGroup.addView(view);\n LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);\n mLayoutParams.leftMargin = x;\n mLayoutParams.topMargin = y;\n view.setLayoutParams(mLayoutParams);\n return view;\n }\n\n /**\n * 创建移动的item对应的ViewGroup布局容器\n * 用于存放我们移动的View\n */\n private ViewGroup getMoveViewGroup() {\n //window中最顶层的view\n ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();\n LinearLayout moveLinearLayout = new LinearLayout(this);\n moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));\n moveViewGroup.addView(moveLinearLayout);\n return moveLinearLayout;\n }\n\n /**\n * 点击item移动动画\n *\n * @param moveView\n * @param startLocation\n * @param endLocation\n * @param moveColumn\n * @param clickGridView\n */\n private void moveAnimation(View moveView, int[] startLocation, int[] endLocation, final ColumnBean moveColumn, final GridView clickGridView, final boolean isSelectedItem) {\n int[] initLocation = new int[2];\n // 获取传递过来的VIEW的坐标\n moveView.getLocationInWindow(initLocation);\n // 得到要移动的VIEW,并放入对应的容器中\n final ViewGroup moveViewGroup = getMoveViewGroup();\n final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);\n // 创建移动动画\n TranslateAnimation moveAnimation = new TranslateAnimation(\n startLocation[0], endLocation[0], startLocation[1],\n endLocation[1]);\n moveAnimation.setDuration(300L);\n // 动画配置\n AnimationSet moveAnimationSet = new AnimationSet(true);\n // 动画效果执行完毕后,View对象不保留在终止的位置\n moveAnimationSet.setFillAfter(false);\n moveAnimationSet.addAnimation(moveAnimation);\n mMoveView.startAnimation(moveAnimationSet);\n moveAnimationSet.setAnimationListener(new Animation.AnimationListener() {\n\n @Override\n public void onAnimationStart(Animation animation) {\n }\n\n @Override\n public void onAnimationRepeat(Animation animation) {\n }\n\n @Override\n public void onAnimationEnd(Animation animation) {\n moveViewGroup.removeView(mMoveView);\n // 判断点击的是SelectedDragGrid还是OptionalGridView\n if (isSelectedItem) {\n mOptionalGridViewAdapter.setVisible(true);\n mOptionalGridViewAdapter.notifyDataSetChanged();\n mDragGridViewAdapter.remove();\n } else {\n mDragGridViewAdapter.setVisible(true);\n mDragGridViewAdapter.notifyDataSetChanged();\n mOptionalGridViewAdapter.remove();\n }\n }\n });\n }\n\n @Override\n public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {\n switch (parent.getId()) {\n case R.id.userGridView:\n // position为 0,1 的不可以进行任何操作\n if (position != 0 && position != 1) {\n final ImageView moveImageView = getView(view);\n if (moveImageView != null) {\n TextView newTextView = (TextView) view.findViewById(R.id.text_item);\n final int[] startLocation = new int[2];\n newTextView.getLocationInWindow(startLocation);\n final ColumnBean columnBean = ((DragGridViewAdapter) parent.getAdapter()).getItem(position);//获取点击的频道内容\n mOptionalGridViewAdapter.setVisible(false);\n // 添加到最后一个\n mOptionalGridViewAdapter.addItem(columnBean);\n new Handler().postDelayed(new Runnable() {\n public void run() {\n try {\n int[] endLocation = new int[2];\n // 获取终点的坐标\n mOtherGv.getChildAt(mOtherGv.getLastVisiblePosition()).getLocationInWindow(endLocation);\n moveAnimation(moveImageView, startLocation, endLocation, columnBean, mUserGv, true);\n mDragGridViewAdapter.setRemove(position);\n } catch (Exception localException) {\n localException.printStackTrace();\n }\n }\n }, 50L);\n }\n }\n break;\n case R.id.otherGridView:\n final ImageView moveImageView = getView(view);\n if (moveImageView != null) {\n TextView newTextView = (TextView) view.findViewById(R.id.text_item);\n final int[] startLocation = new int[2];\n newTextView.getLocationInWindow(startLocation);\n final ColumnBean columnBean = ((OptionalGridViewAdapter) parent.getAdapter()).getItem(position);\n mDragGridViewAdapter.setVisible(false);\n // 添加到最后一个\n mDragGridViewAdapter.addItem(columnBean);\n new Handler().postDelayed(new Runnable() {\n public void run() {\n try {\n int[] endLocation = new int[2];\n // 获取终点的坐标\n mUserGv.getChildAt(mUserGv.getLastVisiblePosition()).getLocationInWindow(endLocation);\n moveAnimation(moveImageView, startLocation, endLocation, columnBean, mOtherGv, false);\n mOptionalGridViewAdapter.setRemove(position);\n } catch (Exception localException) {\n localException.printStackTrace();\n }\n }\n }, 50L);\n }\n break;\n default:\n break;\n }\n }\n\n}",
"public class LogUtils {\n\n private static final int VERBOSE = 1;\n private static final int DEBUG = 2;\n private static final int INFO = 3;\n private static final int WARN = 4;\n private static final int ERROR = 5;\n private static final int NOTHING = 6;\n public static int level = VERBOSE;\n\n /**\n * 最低级的日志\n *\n * @param tag tag标签\n * @param msg 日志信息\n */\n public static void v(String tag, String msg) {\n if (level <= VERBOSE) {\n Log.v(tag, msg);\n }\n }\n\n /**\n * debug级别日志,调试用\n *\n * @param tag tag标签\n * @param msg 日志信息\n */\n public static void d(String tag, String msg) {\n if (level <= DEBUG) {\n Log.v(tag, msg);\n }\n }\n\n /**\n * info级别日志,重要信息\n *\n * @param tag tag标签\n * @param msg 日志信息\n */\n public static void i(String tag, String msg) {\n if (level <= INFO) {\n Log.v(tag, msg);\n }\n }\n\n /**\n * warn级别日志,特别需要注意的提示\n *\n * @param tag tag标签\n * @param msg 日志信息\n */\n public static void w(String tag, String msg) {\n if (level <= WARN) {\n Log.v(tag, msg);\n }\n }\n\n /**\n * error级别日志,这个一般在catch块里用\n *\n * @param tag tag标签\n * @param msg 日志信息\n */\n public static void e(String tag, String msg) {\n if (level <= ERROR) {\n Log.v(tag, msg);\n }\n }\n\n}",
"public class StreamUtils {\n\n private static final String TAG = \"StreamUtils\";\n\n /**\n * inputStrean转String\n *\n * @param in InputStream\n * @param encode 编码\n * @return 转换后的字符串\n */\n public static String InputStreanToString(InputStream in, String encode) {\n\n String str = \"\";\n try {\n if (encode == null || encode.equals(\"\")) {\n // 默认以utf-8形式\n encode = \"utf-8\";\n }\n BufferedReader reader = new BufferedReader(new InputStreamReader(in, encode));\n StringBuffer sb = new StringBuffer();\n\n while ((str = reader.readLine()) != null) {\n sb.append(str).append(\"\\n\");\n }\n return sb.toString();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return str;\n }\n\n /**\n * 读取Assets下的文本文件\n *\n * @param context 上下文\n * @param fileName 文件名\n * @return 读取到的字符串\n */\n public static String readAssetsFile(Context context, String fileName) {\n\n StringBuilder stringBuffer = new StringBuilder();\n AssetManager assetManager = context.getAssets();\n try {\n InputStream is = assetManager.open(fileName);\n BufferedReader br = new BufferedReader(new InputStreamReader(is));\n String str = null;\n while ((str = br.readLine()) != null) {\n stringBuffer.append(str);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return stringBuffer.toString();\n }\n\n /**\n * 写入字符串到手机存储卡内\n *\n * @param fileName 文件名\n * @param string 要存储的字符串\n */\n public static void writeStringToFile(String fileName, String string) {\n FileOutputStream out = null;\n BufferedWriter writer = null;\n try {\n out = BaoKanApp.getContext().openFileOutput(fileName, Context.MODE_PRIVATE);\n writer = new BufferedWriter(new OutputStreamWriter(out));\n writer.write(string);\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n if (writer != null) {\n writer.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n /**\n * 从手机存储卡读取字符串数据\n *\n * @param fileName 文件名\n * @return 读取到的字符串\n */\n public static String readStringFromFile(String fileName) {\n FileInputStream in = null;\n BufferedReader reader = null;\n StringBuilder content = new StringBuilder();\n try {\n in = BaoKanApp.getContext().openFileInput(fileName);\n reader = new BufferedReader(new InputStreamReader(in));\n String line = \"\";\n while ((line = reader.readLine()) != null) {\n content.append(line);\n }\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n if (reader != null) {\n reader.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return content.toString();\n }\n\n /**\n * 判断文件是否存在\n *\n * @param filePath 文件绝对路径\n * @return 是否存在\n */\n public static boolean fileIsExists(String filePath) {\n try {\n File f = new File(filePath);\n if (!f.exists()) {\n return false;\n }\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n return true;\n }\n\n /**\n * 保存远程图片到相册 - 会保存到2个目录\n */\n public static void saveImageToAlbum(final Context context, final String imageUrl) {\n Picasso.with(context).load(imageUrl).into(new Target() {\n @Override\n public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {\n // 创建目录\n File appDir = new File(Environment.getExternalStorageDirectory(), \"BaoKanImage\");\n if (!appDir.exists()) {\n appDir.mkdir();\n }\n\n // 获取图片类型\n String[] imageTypes = new String[]{\".jpg\", \".png\", \".jpeg\", \"webp\"};\n String imageType = \"\";\n if (imageUrl.endsWith(imageTypes[0])) {\n imageType = \"jpg\";\n } else if (imageUrl.endsWith(imageTypes[1])) {\n imageType = \"png\";\n } else {\n imageType = \"jpeg\";\n }\n String fileName = System.currentTimeMillis() + \".\" + imageType;\n File file = new File(appDir, fileName);\n // 保存图片\n try {\n FileOutputStream fos = new FileOutputStream(file);\n if (TextUtils.equals(imageType, \"jpg\")) imageType = \"jpeg\";\n imageType = imageType.toUpperCase();\n bitmap.compress(Bitmap.CompressFormat.valueOf(imageType), 100, fos);\n fos.flush();\n fos.close();\n Toast.makeText(context, \"保存成功\", Toast.LENGTH_SHORT).show();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n // 其次把文件插入到系统图库\n try {\n MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n // 最后通知图库更新\n context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(\"file://\" + file.getPath())));\n }\n\n @Override\n public void onBitmapFailed(Drawable errorDrawable) {\n\n }\n\n @Override\n public void onPrepareLoad(Drawable placeHolderDrawable) {\n\n }\n });\n }\n\n /**\n * 保存图片到sd卡\n *\n * @param photoBitmap\n * @param photoName\n * @param path\n */\n public static String savePhoto(Bitmap photoBitmap, String path, String photoName) {\n String localPath = null;\n if (android.os.Environment.getExternalStorageState().equals(\n android.os.Environment.MEDIA_MOUNTED)) {\n File dir = new File(path);\n if (!dir.exists()) {\n dir.mkdirs();\n }\n\n File photoFile = new File(path, photoName + \".png\");\n FileOutputStream fileOutputStream = null;\n try {\n fileOutputStream = new FileOutputStream(photoFile);\n if (photoBitmap != null) {\n if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,\n fileOutputStream)) { // 转换完成\n localPath = photoFile.getPath();\n fileOutputStream.flush();\n }\n }\n } catch (IOException e) {\n photoFile.delete();\n localPath = null;\n e.printStackTrace();\n } finally {\n try {\n if (fileOutputStream != null) {\n fileOutputStream.close();\n fileOutputStream = null;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n return localPath;\n }\n\n}"
] | import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import tv.baokan.baokanandroid.R;
import tv.baokan.baokanandroid.adapter.TabFragmentPagerAdapter;
import tv.baokan.baokanandroid.app.BaoKanApp;
import tv.baokan.baokanandroid.model.ColumnBean;
import tv.baokan.baokanandroid.ui.activity.ColumnActivity;
import tv.baokan.baokanandroid.utils.LogUtils;
import tv.baokan.baokanandroid.utils.StreamUtils;
import static android.app.Activity.RESULT_OK; | package tv.baokan.baokanandroid.ui.fragment;
public class NewsFragment extends BaseFragment {
private static final String TAG = "NewsFragment";
public static final int REQUEST_CODE_COLUMN = 0;
private TabLayout mNewsTabLayout;
private ViewPager mNewsViewPager;
private ImageButton mNewsClassAdd;
private List<ColumnBean> selectedList = new ArrayList<>();
private List<ColumnBean> optionalList = new ArrayList<>();
List<NewsListFragment> newsListFragments = new ArrayList<>();
private TabFragmentPagerAdapter mFragmentPageAdapter;
@Override
protected View prepareUI() {
View view = View.inflate(mContext, R.layout.fragment_news, null);
mNewsTabLayout = (TabLayout) view.findViewById(R.id.tl_news_tabLayout);
mNewsViewPager = (ViewPager) view.findViewById(R.id.vp_news_viewPager);
mNewsClassAdd = (ImageButton) view.findViewById(R.id.ib_news_class_add);
// 点击加号进入栏目编辑activity
mNewsClassAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 弹出栏目管理activity
ColumnActivity.start(getActivity(), selectedList, optionalList);
}
});
return view;
}
@Override
protected void loadData() {
// 判断手机缓存里有没有栏目数据,有则加载,无咋加载默认json数据 | if (StreamUtils.fileIsExists(BaoKanApp.getContext().getFileStreamPath("column.json").getAbsolutePath())) { | 5 |
magnetsystems/message-samples-android | SmartShopper/app/src/main/java/com/magnet/smartshopper/activities/ProductListActivity.java | [
"public class ProductAdapter extends ArrayAdapter<Product> {\n // View lookup cache\n private static class ViewHolder {\n public ImageView ivItemImage;\n public TextView tvItemTitle;\n public TextView tvItemPrice;\n }\n\n public ProductAdapter(Context context, ArrayList<Product> aBooks) {\n super(context, 0, aBooks);\n }\n\n // Translates a particular `Product` given a position\n // into a relevant row within an AdapterView\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n // Get the data item for this position\n final Product product = getItem(position);\n // Check if an existing view is being reused, otherwise inflate the view\n ViewHolder viewHolder; // view lookup cache stored in tag\n if (convertView == null) {\n viewHolder = new ViewHolder();\n LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n convertView = inflater.inflate(R.layout.item_product, parent, false);\n viewHolder.ivItemImage = (ImageView)convertView.findViewById(R.id.ivItemImage);\n viewHolder.tvItemTitle = (TextView)convertView.findViewById(R.id.tvItemName);\n viewHolder.tvItemPrice = (TextView)convertView.findViewById(R.id.tvItemPrice);\n convertView.setTag(viewHolder);\n } else {\n viewHolder = (ViewHolder) convertView.getTag();\n }\n // Populate the data into the template view using the data object\n viewHolder.tvItemTitle.setText(product.getName());\n viewHolder.tvItemPrice.setText(product.getSalePrice());\n Picasso.with(getContext()).load(Uri.parse(product.getThumbnailImage())).error(R.drawable.notification_template_icon_bg).into(viewHolder.ivItemImage);\n // Return the completed view to render on screen\n return convertView;\n }\n}",
"public class MagnetMessageService {\n\n private static final String TAG = \"MagnetMessageService\";\n private static final String DEFAULT_USER = \"smartshopperandroid\";\n private static final String DEFAULT_PASSWORD = \"smartshopperandroid\";\n\n public static final String ITEM_ID = \"itemId\";\n public static final String ITEM_NAME = \"name\";\n public static final String ITEM_PRICE = \"salePrice\";\n public static final String ITEM_IMAGE = \"productUrl\";\n public static final String MY_WISH_LIST = \"myWishList\";\n\n public static void registerAndLoginUser(final Context context) {\n\n Log.e(TAG, \"Creating user -\" + DEFAULT_USER);\n MMXUser user = new MMXUser.Builder().username(DEFAULT_USER).displayName(DEFAULT_USER).build();\n\n\n user.register(DEFAULT_PASSWORD.getBytes(), new MMXUser.OnFinishedListener<Void>() {\n public void onSuccess(Void aVoid) {\n //Successful registration. login?\n Toast.makeText(context, \"User has been created\", Toast.LENGTH_LONG).show();\n loginUser(context);\n }\n\n public void onFailure(MMXUser.FailureCode failureCode, Throwable throwable) {\n if (MMXUser.FailureCode.REGISTRATION_USER_ALREADY_EXISTS.equals(failureCode)) {\n loginUser(context);\n return;\n }\n Toast.makeText(context, \"User Registration Error. Please try again.\" + failureCode.getDescription() + \" \" + failureCode.getValue(), Toast.LENGTH_LONG).show();\n\n }\n });\n }\n\n\n\n private static void loginUser(final Context context) {\n //Login with user\n MMX.login(DEFAULT_USER, DEFAULT_PASSWORD.getBytes(), new MMX.OnFinishedListener<Void>() {\n\n\n public void onSuccess(Void aVoid) {\n //success!\n //if an EventListener has already been registered, start receiving messages\n MMX.enableIncomingMessages(true);\n\n Toast.makeText(context,\n \"Logged in\", Toast.LENGTH_LONG).show();\n createWishListChannel();\n }\n\n public void onFailure(MMX.FailureCode failureCode, Throwable throwable) {\n Toast.makeText(context,\n \"Please try again.\", Toast.LENGTH_LONG).show();\n }\n });\n }\n\n private static void createWishListChannel() {\n \n MMXChannel.create(MY_WISH_LIST,\"Chanel to store my wish ist\",false,new MMXChannel.OnFinishedListener<MMXChannel>() {\n\n public void onSuccess(final MMXChannel result) {\n Log.i(TAG, \"Wish list channel got created\");\n }\n\n public void onFailure(final MMXChannel.FailureCode code, final Throwable ex) {\n Log.e(TAG, \"Exception caught: \" + code, ex);\n\n }\n });\n }\n\n public static void addToWishList(final Context context,final Product product) {\n\n MMXChannel.getPrivateChannel(MY_WISH_LIST, new MMXChannel.OnFinishedListener<MMXChannel>() {\n @Override\n public void onSuccess(MMXChannel mmxChannel) {\n Map<String, String> messageMap = new HashMap<String, String>(4);\n\n messageMap.put(ITEM_ID, product.getId());\n messageMap.put(ITEM_NAME, product.getName());\n if(product.getSalePrice() != null && product.getSalePrice().length() > 1) {\n messageMap.put(ITEM_PRICE, product.getSalePrice().substring(1));\n }\n\n messageMap.put(ITEM_IMAGE, product.getThumbnailImage());\n\n mmxChannel.publish(messageMap, new MMXChannel.OnFinishedListener<String>() {\n @Override\n public void onSuccess(String s) {\n Toast.makeText(context,\n \"Product '\" + product.getName() + \"' has been added to wish list\", Toast.LENGTH_LONG).show();\n }\n\n @Override\n public void onFailure(MMXChannel.FailureCode failureCode, Throwable throwable) {\n Toast.makeText(context,\n \"Error during publish: \" + throwable.getMessage(), Toast.LENGTH_LONG).show();\n\n }\n });\n }\n\n @Override\n public void onFailure(MMXChannel.FailureCode failureCode, Throwable throwable) {\n Toast.makeText(context,\n \"Not able to find the channel : \" + throwable.getMessage(), Toast.LENGTH_LONG).show();\n }\n });\n\n\n }\n\n public static void shareTheProduct(final Context context, final User targetUser, final Product product) {\n\n HashSet<MMXUser> recipients = new HashSet<MMXUser>();\n String username =targetUser.getUsername();\n MMXUser mmxUser = new MMXUser.Builder().username(username).displayName(username).build();\n recipients.add(mmxUser);\n\n Map<String, String> content = new HashMap<String, String>(4);\n content.put(ITEM_ID, product.getId());\n content.put(ITEM_NAME, product.getName());\n if(product.getSalePrice() != null && product.getSalePrice().length() > 1) {\n content.put(ITEM_PRICE, product.getSalePrice().substring(1));\n }\n content.put(ITEM_IMAGE, product.getThumbnailImage());\n // Build the message\n MMXMessage message = new MMXMessage.Builder()\n .recipients(recipients)\n .content(content)\n .build();\n\n String messageId = message.send(new MMXMessage.OnFinishedListener<String>() {\n\n @Override\n public void onSuccess(String s) {\n Toast.makeText(context,\n \"Product \" + product.getName() + \" has been shared\", Toast.LENGTH_LONG).show();\n }\n @Override\n public void onFailure(MMXMessage.FailureCode failureCode, Throwable throwable) {\n Toast.makeText(context,\n \"Error while sending the message\", Toast.LENGTH_LONG).show();\n }\n });\n\n }\n}",
"public class SearchItemService {\n\n private static final String API_KEY = \"API_KEY\";\n private static String RESPONSE_FORMAT = \"RESPONSE_FORMAT\";\n private static final String BASE_URL = \"BASE_URL\";\n\n private RestAdapter restAdapter;\n private Properties credentials;\n\n boolean initialized = false;\n\n\n private SearchItemService(){\n init();\n }\n\n public synchronized void init() {\n\n credentials = new Properties();\n try {\n credentials.load(Resources.getSystem().openRawResource(R.raw.walmartlabscredentials));\n } catch (IOException e) {\n e.printStackTrace();\n }\n restAdapter = new RestAdapter.Builder()\n .setEndpoint(BASE_URL)\n .build();\n initialized = true;\n }\n\n public List<Product> getItems(String category) {\n restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);\n\n SearchItemServiceClient apiService =\n restAdapter.create(SearchItemServiceClient.class);\n\n SearchResponseObject response = apiService.search(category, RESPONSE_FORMAT, API_KEY);\n\n List<Product> products = new ArrayList<Product>(2);\n\n for(Items items : response.getItems()){\n Product product = new Product();\n product.setId(items.getItemId());\n product.setName(items.getName());\n product.setSalePrice(\"$\"+ items.getSalePrice());\n product.setThumbnailImage(items.getThumbnailImage());\n\n products.add(product);\n\n }\n return products;\n\n\n }\n\n\n}",
"public interface SearchItemServiceClient {\n\n /**\n * \n * GET /getitemservice/v1/search\n * @param query style:Query optional:false\n * @param format style:Query optional:false\n * @param apiKey style:Query optional:false\n */\n @GET(\"/search\")\n SearchResponseObject search(\n @Query(\"query\") String query,\n @Query(\"format\") String format,\n @Query(\"apiKey\") String apiKey);\n\n}",
"public class Items {\n\n private String name;\n private String salePrice;\n private String thumbnailImage;\n private String itemId;\n\n public String getSalePrice() {\n return salePrice;\n }\n public void setSalePrice(String value) {\n this.salePrice = value;\n }\n\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n\n public String getThumbnailImage() {\n return thumbnailImage;\n }\n public void setThumbnailImage(String value) {\n this.thumbnailImage = value;\n }\n\n public String getItemId() {\n return itemId;\n }\n\n public void setItemId(String itemId) {\n this.itemId = itemId;\n }\n}",
"public class Product implements Serializable {\n\n private String id;\n private String name;\n private String salePrice;\n private String thumbnailImage;\n\n public String getSalePrice() {\n return salePrice;\n }\n public void setSalePrice(String value) {\n this.salePrice = value;\n }\n\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n\n public String getThumbnailImage() {\n return thumbnailImage;\n }\n public void setThumbnailImage(String value) {\n this.thumbnailImage = value;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n}",
"public class SearchResponseObject {\n\n private String query;\n private String sort;\n private String responseGroup;\n private Integer totalResults;\n private Integer start;\n private Integer numItems;\n private java.util.List<Items> items;\n private java.util.List<String> facets;\n\n public String getQuery() {\n return query;\n }\n public void setQuery(String value) {\n this.query = value;\n }\n\n public String getSort() {\n return sort;\n }\n public void setSort(String value) {\n this.sort = value;\n }\n\n public String getResponseGroup() {\n return responseGroup;\n }\n public void setResponseGroup(String value) {\n this.responseGroup = value;\n }\n\n public Integer getTotalResults() {\n return totalResults;\n }\n public void setTotalResults(Integer value) {\n this.totalResults = value;\n }\n\n public Integer getStart() {\n return start;\n }\n public void setStart(Integer value) {\n this.start = value;\n }\n\n public Integer getNumItems() {\n return numItems;\n }\n public void setNumItems(Integer value) {\n this.numItems = value;\n }\n\n public java.util.List<Items> getItems() {\n return items;\n }\n public void setItems(java.util.List<Items> value) {\n this.items = value;\n }\n\n public java.util.List<String> getFacets() {\n return facets;\n }\n public void setFacets(java.util.List<String> value) {\n this.facets = value;\n }\n\n}",
"public class WeatherService {\n\n public static final String BASE_URL = \"http://api.wunderground.com/\";\n\n private static RestAdapter restAdapter = new RestAdapter.Builder()\n .setEndpoint(BASE_URL)\n .build();\n\n public static Weather getCurrentTemperature() {\n\n restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);\n WeatherServiceClient apiService =\n restAdapter.create(WeatherServiceClient.class);\n WeatherResponse response = apiService.getCurrentWeather();\n Weather weather = new Weather();\n weather.setTemp(response.getCurrent_observation().getTemp_f().toString());\n weather.setIconUrl(response.getCurrent_observation().getIcon_url());\n\n return weather;\n\n\n }\n\n\n}",
"public class Weather {\n\n\n private String temp;\n private String iconUrl;\n\n public String getTemp() {\n return temp;\n }\n\n public void setTemp(String temp) {\n this.temp = temp;\n }\n\n public String getIconUrl() {\n return iconUrl;\n }\n\n public void setIconUrl(String iconUrl) {\n this.iconUrl = iconUrl;\n }\n}"
] | import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.magnet.mmx.client.common.Log;
import com.magnet.smartshopper.R;
import com.magnet.smartshopper.adapters.ProductAdapter;
import com.magnet.smartshopper.services.MagnetMessageService;
import com.magnet.smartshopper.walmart.SearchItemService;
import com.magnet.smartshopper.walmart.SearchItemServiceClient;
import com.magnet.smartshopper.walmart.model.Items;
import com.magnet.smartshopper.walmart.model.Product;
import com.magnet.smartshopper.walmart.model.SearchResponseObject;
import com.magnet.smartshopper.wunderground.WeatherService;
import com.magnet.smartshopper.wunderground.model.Weather;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import retrofit.RestAdapter; | package com.magnet.smartshopper.activities;
public class ProductListActivity extends AppCompatActivity {
private static final String API_KEY = "API_KEY";
private static String RESPONSE_FORMAT = "RESPONSE_FORMAT";
private static final String BASE_URL = "BASE_URL";
private final String TAG = "ProductListActivity";
public static final String PRODUCT_DETAIL_KEY = "product";
private ListView lvProducts;
private ProductAdapter productAdapter;
private ProgressBar progress;
private RestAdapter restAdapter;
private Properties credentials;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initWalmartApiCredentials();
setContentView(R.layout.activity_product_list);
Log.setLoggable(null, Log.VERBOSE);
Toast.makeText(ProductListActivity.this,
"Trying to get the weather", Toast.LENGTH_LONG).show();
MagnetMessageService.registerAndLoginUser(this);
lvProducts = (ListView) findViewById(R.id.lvProducts);
ArrayList<Product> products = new ArrayList<Product>();
// initialize the adapter
productAdapter = new ProductAdapter(this, products);
// attach the adapter to the ListView
lvProducts.setAdapter(productAdapter);
progress = (ProgressBar) findViewById(R.id.progress);
setupProductSelectedListener();
//Get Current Weather for fixed location SF
new AsyncTask<Void,String,Weather>() {
@Override
protected Weather doInBackground(Void ...avoid) {
try { | Weather weather = WeatherService.getCurrentTemperature(); | 7 |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/frames/CreateBindingsNode.java | [
"@NodeInfo(language = \"HB\")\npublic abstract class HBNode extends Node {\n // Execute with a generic unspecialized return value.\n public abstract Object executeGeneric(VirtualFrame frame);\n\n // Execute without a return value.\n public void executeVoid(VirtualFrame frame) {\n executeGeneric(frame);\n }\n}",
"public interface Binding {\n // Returns the bound value from the frame.\n Object get();\n}",
"public final class Bindings {\n private Map<String, Binding> bindings;\n\n public Bindings() {\n this.bindings = new HashMap<>();\n }\n\n public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {\n this();\n // Bootstrap builtins into frame.\n for (String name : builtinScope) {\n Type type = builtinScope.get(name);\n if (type instanceof FunctionType) {\n Object function = new Function((FunctionType)type, null);\n this.bindings.put(name, new BuiltinBinding(name, function));\n } else {\n System.out.println(\"Skipping bootstrap of builtin \" + name + \": \" + type.toString());\n }\n }\n }\n\n public boolean contains(String name) {\n return this.bindings.containsKey(name);\n }\n\n public Binding get(String name) {\n return this.bindings.get(name);\n }\n\n public Object getValue(String name) {\n Binding binding = this.get(name);\n return binding.get();\n }\n\n public void add(String name, Binding binding) {\n this.bindings.put(name, binding);\n }\n\n public static final BindingsIdentifier IDENTIFIER = new BindingsIdentifier();\n\n private static final class BindingsIdentifier {\n private BindingsIdentifier() {\n }\n }\n}",
"public final class MaterializedBinding implements Binding {\n private MaterializedFrame frame;\n private String name;\n\n public MaterializedBinding(String name, MaterializedFrame frame) {\n this.frame = frame;\n this.name = name;\n }\n\n @Override\n public Object get() {\n FrameSlot frameSlot = this.frame.getFrameDescriptor().findFrameSlot(this.name);\n return frame.getValue(frameSlot);\n }\n}",
"public final class FunctionType extends ConcreteType {\n private final Type[] parameterTypes;\n private final Type returnType;\n private final String name;\n private final CallTarget callTarget;\n // Scope where the function was declared.\n private Scope declarationScope;\n // Scope inside the function (ie. of its block).\n private Scope ownScope;\n\n public FunctionType(\n Type[] parameterTypes,\n Type returnType,\n String name,\n CallTarget callTarget\n ) {\n this.parameterTypes = parameterTypes;\n this.returnType = returnType;\n this.name = name;\n this.callTarget = callTarget;\n }\n\n public Type[] getParameterTypes() {\n return this.parameterTypes;\n }\n\n public Type getReturnType() {\n return this.returnType;\n }\n\n public String getName() {\n return this.name;\n }\n\n public CallTarget getCallTarget() {\n return this.callTarget;\n }\n\n public Scope getOwnScope() {\n if (this.ownScope != null && !this.ownScope.isClosed()) {\n throw new RuntimeException(\"Scope not yet closed\");\n }\n return this.ownScope;\n }\n\n public void setOwnScope(Scope scope) {\n if (this.ownScope != null) {\n throw new RuntimeException(\"Cannot re-set scope\");\n }\n this.ownScope = scope;\n }\n\n public Scope getDeclarationScope() {\n if (this.declarationScope != null && !this.declarationScope.isClosed()) {\n throw new RuntimeException(\"Scope not yet closed\");\n }\n return this.declarationScope;\n }\n\n public void setDeclarationScope(Scope declarationScope) {\n if (this.declarationScope != null) {\n throw new RuntimeException(\"Cannot re-set scope\");\n }\n this.declarationScope = declarationScope;\n }\n\n @Override\n public Property getProperty(String name) throws PropertyNotFoundException {\n throw new PropertyNotFoundException(\"Not yet implemented\");\n }\n}",
"public final class Resolution {\n private String name;\n private Type type;\n // First item is nearest parent, last item is furthest/highest parent.\n private List<Scope> path;\n\n public Resolution(String name) {\n this.name = name;\n this.type = null;\n this.path = new ArrayList<>();\n }\n\n public String getName() {\n return this.name;\n }\n\n public void pushScope(Scope scope) {\n this.path.add(scope);\n }\n\n public Type getType() {\n return this.type;\n }\n\n public void setType(Type type) {\n this.type = type;\n }\n\n public boolean isLocal() {\n this.assertPathIsNotEmpty();\n return this.path.size() == 1;\n }\n\n public boolean isNonLocal() {\n this.assertPathIsNotEmpty();\n return this.path.size() > 1;\n }\n\n public Scope getHighestScope() {\n this.assertPathIsNotEmpty();\n return this.path.get(this.path.size() - 1);\n }\n\n private void assertPathIsNotEmpty() {\n if (this.path.isEmpty()) {\n throw new RuntimeException(\"Empty path in resolution\");\n }\n }\n\n @Override\n public String toString() {\n StringBuilder result = new StringBuilder();\n result.append(\"Resolution@\").append(Integer.toHexString(hashCode()));\n result.append(\"{\");\n boolean comma = false;\n for (Scope scope : this.path) {\n if (comma) {\n result.append(\", \");\n } else {\n comma = true;\n }\n result.append(scope.toString());\n }\n result.append(\"}\");\n return result.toString();\n }\n}",
"public interface Scope {\n // Loose visitor pattern: scopes accept visitors; if they have the name the\n // resolution is looking for then they push themselves onto the path and\n // assign the type, otherwise they push themselves onto the path and\n // recurse to their parent scope.\n public void accept(Resolution resolution) throws NameNotFoundException;\n\n public Resolution resolve(String name) throws NameNotFoundException;\n\n // Get the type for the given name. Should create a `Resolution` and call\n // the `accept` recursion under the hood.\n public Type get(String name) throws NameNotFoundException;\n\n public void setLocal(String name, Type type);\n\n public Scope getParent();\n\n // Close the scope to prevent further modifications.\n public void close();\n\n // Returns whether or not the scope has been closed.\n public boolean isClosed();\n\n // Should only be called on closed scopes.\n public List<Resolution> getNonLocalResolutions();\n}"
] | import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.NodeField;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.MaterializedFrame;
import com.oracle.truffle.api.frame.VirtualFrame;
import java.util.ArrayList;
import java.util.List;
import org.hummingbirdlang.nodes.HBNode;
import org.hummingbirdlang.runtime.bindings.Binding;
import org.hummingbirdlang.runtime.bindings.Bindings;
import org.hummingbirdlang.runtime.bindings.MaterializedBinding;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.scope.Resolution;
import org.hummingbirdlang.types.scope.Scope; | package org.hummingbirdlang.nodes.frames;
// Assembles the `Bindings` for a function.
@NodeField(name = "type", type = FunctionType.class)
public abstract class CreateBindingsNode extends HBNode {
protected abstract FunctionType getType();
| public abstract Bindings executeCreateBindings(VirtualFrame frame); | 2 |
davidmoten/rxjava2-jdbc | rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/GetterTx.java | [
"public class Tuple2<T1, T2> {\n\n private final T1 value1;\n private final T2 value2;\n\n /**\n * Constructor.\n * \n * @param value1\n * first element\n * @param value2\n * second element\n */\n public Tuple2(T1 value1, T2 value2) {\n this.value1 = value1;\n this.value2 = value2;\n }\n\n /**\n * Returns a new instance.\n * \n * @param r\n * first element\n * @param s\n * second element \n * @param <R> type of first element\n * @param <S>\n * type of second element\n * \n * @return tuple\n */\n public static <R, S> Tuple2<R, S> create(R r, S s) {\n return new Tuple2<R, S>(r, s);\n }\n\n /**\n * Returns the first element of the tuple.\n * \n * @return first element\n */\n public T1 value1() {\n return value1;\n }\n\n /**\n * Returns the first element of the tuple.\n * \n * @return first element\n */\n public T1 _1() {\n return value1;\n }\n\n /**\n * Returns the 2nd element of the tuple.\n * \n * @return second element\n */\n public T2 value2() {\n return value2;\n }\n\n /**\n * Returns the 2nd element of the tuple.\n * \n * @return second element\n */\n public T2 _2() {\n return value2;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n return result;\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 Tuple2<?, ?> other = (Tuple2<?, ?>) obj;\n if (value1 == null) {\n if (other.value1 != null)\n return false;\n } else if (!value1.equals(other.value1))\n return false;\n if (value2 == null) {\n if (other.value2 != null)\n return false;\n } else if (!value2.equals(other.value2))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tuple2 [value1=\" + value1 + \", value2=\" + value2 + \"]\";\n }\n\n}",
"public class Tuple3<T1, T2, T3> {\n\n private final T1 value1;\n private final T2 value2;\n private final T3 value3;\n\n /**\n * Constructor.\n * \n * @param value1 first element \n * @param value2 second element\n * @param value3 third element\n */\n public Tuple3(T1 value1, T2 value2, T3 value3) {\n this.value1 = value1;\n this.value2 = value2;\n this.value3 = value3;\n }\n \n public static <T1,T2,T3> Tuple3<T1,T2,T3> create(T1 value1, T2 value2, T3 value3) {\n return new Tuple3<T1,T2,T3>(value1, value2, value3);\n }\n\n public T1 value1() {\n return value1;\n }\n\n public T2 value2() {\n return value2;\n }\n\n public T3 value3() {\n return value3;\n }\n\n public T1 _1() {\n return value1;\n }\n\n public T2 _2() {\n return value2;\n }\n\n public T3 _3() {\n return value3;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n result = prime * result + ((value3 == null) ? 0 : value3.hashCode());\n return result;\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 Tuple3<?, ?, ?> other = (Tuple3<?, ?, ?>) obj;\n if (value1 == null) {\n if (other.value1 != null)\n return false;\n } else if (!value1.equals(other.value1))\n return false;\n if (value2 == null) {\n if (other.value2 != null)\n return false;\n } else if (!value2.equals(other.value2))\n return false;\n if (value3 == null) {\n if (other.value3 != null)\n return false;\n } else if (!value3.equals(other.value3))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tuple3 [value1=\" + value1 + \", value2=\" + value2 + \", value3=\" + value3 + \"]\";\n }\n\n}",
"public class Tuple4<T1, T2, T3, T4> {\n\n private final T1 value1;\n private final T2 value2;\n private final T3 value3;\n private final T4 value4;\n\n /**\n * Constructor.\n * \n * @param value1 first element\n * @param value2 second element\n * @param value3 third element\n * @param value4 fourth element\n */\n public Tuple4(T1 value1, T2 value2, T3 value3, T4 value4) {\n this.value1 = value1;\n this.value2 = value2;\n this.value3 = value3;\n this.value4 = value4;\n }\n\n public static <T1, T2, T3, T4> Tuple4<T1, T2, T3, T4> create(T1 value1, T2 value2, T3 value3, T4 value4) {\n return new Tuple4<T1, T2, T3, T4>(value1, value2, value3, value4);\n }\n\n public T1 value1() {\n return value1;\n }\n\n public T2 value2() {\n return value2;\n }\n\n public T3 value3() {\n return value3;\n }\n\n public T4 value4() {\n return value4;\n }\n\n public T1 _1() {\n return value1;\n }\n\n public T2 _2() {\n return value2;\n }\n\n public T3 _3() {\n return value3;\n }\n\n public T4 _4() {\n return value4;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n result = prime * result + ((value3 == null) ? 0 : value3.hashCode());\n result = prime * result + ((value4 == null) ? 0 : value4.hashCode());\n return result;\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 Tuple4<?, ?, ?, ?> other = (Tuple4<?, ?, ?, ?>) obj;\n if (value1 == null) {\n if (other.value1 != null)\n return false;\n } else if (!value1.equals(other.value1))\n return false;\n if (value2 == null) {\n if (other.value2 != null)\n return false;\n } else if (!value2.equals(other.value2))\n return false;\n if (value3 == null) {\n if (other.value3 != null)\n return false;\n } else if (!value3.equals(other.value3))\n return false;\n if (value4 == null) {\n if (other.value4 != null)\n return false;\n } else if (!value4.equals(other.value4))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tuple4 [value1=\" + value1 + \", value2=\" + value2 + \", value3=\" + value3 + \", value4=\" + value4 + \"]\";\n }\n\n}",
"public class Tuple5<T1, T2, T3, T4, T5> {\n\n private final T1 value1;\n private final T2 value2;\n private final T3 value3;\n private final T4 value4;\n private final T5 value5;\n\n /**\n * Constructor.\n * \n * @param value1 first element\n * @param value2 second element\n * @param value3 third element\n * @param value4 fourth element\n * @param value5 fifth element\n */\n public Tuple5(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) {\n this.value1 = value1;\n this.value2 = value2;\n this.value3 = value3;\n this.value4 = value4;\n this.value5 = value5;\n }\n\n public static <T1, T2, T3, T4, T5> Tuple5<T1, T2, T3, T4, T5> create(T1 value1, T2 value2, T3 value3, T4 value4,\n T5 value5) {\n return new Tuple5<T1, T2, T3, T4, T5>(value1, value2, value3, value4, value5);\n }\n\n public T1 value1() {\n return value1;\n }\n\n public T2 value2() {\n return value2;\n }\n\n public T3 value3() {\n return value3;\n }\n\n public T4 value4() {\n return value4;\n }\n\n public T5 value5() {\n return value5;\n }\n\n public T1 _1() {\n return value1;\n }\n\n public T2 _2() {\n return value2;\n }\n\n public T3 _3() {\n return value3;\n }\n\n public T4 _4() {\n return value4;\n }\n\n public T5 _5() {\n return value5;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n result = prime * result + ((value3 == null) ? 0 : value3.hashCode());\n result = prime * result + ((value4 == null) ? 0 : value4.hashCode());\n result = prime * result + ((value5 == null) ? 0 : value5.hashCode());\n return result;\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 Tuple5<?, ?, ?, ?, ?> other = (Tuple5<?, ?, ?, ?, ?>) obj;\n if (value1 == null) {\n if (other.value1 != null)\n return false;\n } else if (!value1.equals(other.value1))\n return false;\n if (value2 == null) {\n if (other.value2 != null)\n return false;\n } else if (!value2.equals(other.value2))\n return false;\n if (value3 == null) {\n if (other.value3 != null)\n return false;\n } else if (!value3.equals(other.value3))\n return false;\n if (value4 == null) {\n if (other.value4 != null)\n return false;\n } else if (!value4.equals(other.value4))\n return false;\n if (value5 == null) {\n if (other.value5 != null)\n return false;\n } else if (!value5.equals(other.value5))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tuple5 [value1=\" + value1 + \", value2=\" + value2 + \", value3=\" + value3 + \", value4=\" + value4\n + \", value5=\" + value5 + \"]\";\n }\n\n}",
"public class Tuple6<T1, T2, T3, T4, T5, T6> {\n\n private final T1 value1;\n private final T2 value2;\n private final T3 value3;\n private final T4 value4;\n private final T5 value5;\n private final T6 value6;\n\n /**\n * Constructor.\n * \n * @param value1\n * first element\n * @param value2\n * second element\n * @param value3\n * third element\n * @param value4\n * fourth element\n * @param value5\n * fifth element\n * @param value6\n * sixth element\n */\n public Tuple6(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) {\n this.value1 = value1;\n this.value2 = value2;\n this.value3 = value3;\n this.value4 = value4;\n this.value5 = value5;\n this.value6 = value6;\n }\n\n public static <T1, T2, T3, T4, T5, T6> Tuple6<T1, T2, T3, T4, T5, T6> create(T1 value1,\n T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) {\n return new Tuple6<T1, T2, T3, T4, T5, T6>(value1, value2, value3, value4, value5, value6);\n }\n\n public T1 value1() {\n return value1;\n }\n\n public T2 value2() {\n return value2;\n }\n\n public T3 value3() {\n return value3;\n }\n\n public T4 value4() {\n return value4;\n }\n\n public T5 value5() {\n return value5;\n }\n\n public T6 value6() {\n return value6;\n }\n\n public T1 _1() {\n return value1;\n }\n\n public T2 _2() {\n return value2;\n }\n\n public T3 _3() {\n return value3;\n }\n\n public T4 _4() {\n return value4;\n }\n\n public T5 _5() {\n return value5;\n }\n\n public T6 _6() {\n return value6;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n result = prime * result + ((value3 == null) ? 0 : value3.hashCode());\n result = prime * result + ((value4 == null) ? 0 : value4.hashCode());\n result = prime * result + ((value5 == null) ? 0 : value5.hashCode());\n result = prime * result + ((value6 == null) ? 0 : value6.hashCode());\n return result;\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 Tuple6<?, ?, ?, ?, ?, ?> other = (Tuple6<?, ?, ?, ?, ?, ?>) obj;\n if (value1 == null) {\n if (other.value1 != null)\n return false;\n } else if (!value1.equals(other.value1))\n return false;\n if (value2 == null) {\n if (other.value2 != null)\n return false;\n } else if (!value2.equals(other.value2))\n return false;\n if (value3 == null) {\n if (other.value3 != null)\n return false;\n } else if (!value3.equals(other.value3))\n return false;\n if (value4 == null) {\n if (other.value4 != null)\n return false;\n } else if (!value4.equals(other.value4))\n return false;\n if (value5 == null) {\n if (other.value5 != null)\n return false;\n } else if (!value5.equals(other.value5))\n return false;\n if (value6 == null) {\n if (other.value6 != null)\n return false;\n } else if (!value6.equals(other.value6))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tuple6 [value1=\" + value1 + \", value2=\" + value2 + \", value3=\" + value3\n + \", value4=\" + value4 + \", value5=\" + value5 + \", value6=\" + value6 + \"]\";\n }\n}",
"public class Tuple7<T1, T2, T3, T4, T5, T6, T7> {\n\n private final T1 value1;\n private final T2 value2;\n private final T3 value3;\n private final T4 value4;\n private final T5 value5;\n private final T6 value6;\n private final T7 value7;\n\n /**\n * Constructor.\n * \n * @param value1\n * first element\n * @param value2\n * second element\n * @param value3\n * third element\n * @param value4\n * fourth element\n * @param value5\n * fifth element\n * @param value6\n * sixth element\n * @param value7\n * seventh element\n */\n public Tuple7(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) {\n this.value1 = value1;\n this.value2 = value2;\n this.value3 = value3;\n this.value4 = value4;\n this.value5 = value5;\n this.value6 = value6;\n this.value7 = value7;\n }\n\n public static <T1, T2, T3, T4, T5, T6, T7> Tuple7<T1, T2, T3, T4, T5, T6, T7> create(T1 value1,\n T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) {\n return new Tuple7<T1, T2, T3, T4, T5, T6, T7>(value1, value2, value3, value4, value5,\n value6, value7);\n }\n\n public T1 value1() {\n return value1;\n }\n\n public T2 value2() {\n return value2;\n }\n\n public T3 value3() {\n return value3;\n }\n\n public T4 value4() {\n return value4;\n }\n\n public T5 value5() {\n return value5;\n }\n\n public T6 value6() {\n return value6;\n }\n\n public T7 value7() {\n return value7;\n }\n\n public T1 _1() {\n return value1;\n }\n\n public T2 _2() {\n return value2;\n }\n\n public T3 _3() {\n return value3;\n }\n\n public T4 _4() {\n return value4;\n }\n\n public T5 _5() {\n return value5;\n }\n\n public T6 _6() {\n return value6;\n }\n\n public T7 _7() {\n return value7;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n result = prime * result + ((value3 == null) ? 0 : value3.hashCode());\n result = prime * result + ((value4 == null) ? 0 : value4.hashCode());\n result = prime * result + ((value5 == null) ? 0 : value5.hashCode());\n result = prime * result + ((value6 == null) ? 0 : value6.hashCode());\n result = prime * result + ((value7 == null) ? 0 : value7.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n @SuppressWarnings(\"rawtypes\")\n final Tuple7 other = (Tuple7) obj;\n return Objects.equals(value1, other.value1) //\n && Objects.equals(value2, other.value2) //\n && Objects.equals(value3, other.value3) //\n && Objects.equals(value4, other.value4) //\n && Objects.equals(value5, other.value5) //\n && Objects.equals(value6, other.value6) //\n && Objects.equals(value7, other.value7);\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(\"Tuple7 [value1=\");\n builder.append(value1);\n builder.append(\", value2=\");\n builder.append(value2);\n builder.append(\", value3=\");\n builder.append(value3);\n builder.append(\", value4=\");\n builder.append(value4);\n builder.append(\", value5=\");\n builder.append(value5);\n builder.append(\", value6=\");\n builder.append(value6);\n builder.append(\", value7=\");\n builder.append(value7);\n builder.append(\"]\");\n return builder.toString();\n }\n\n}",
"public class TupleN<T> {\n\n private final List<T> list;\n\n /**\n * Constructor.\n * \n * @param list\n * values of the elements in the tuple\n */\n public TupleN(List<T> list) {\n this.list = list;\n }\n\n @SafeVarargs\n public static <T> TupleN<T> create(T... array) {\n return new TupleN<T>(Arrays.asList(array));\n }\n\n public List<T> values() {\n // defensive copy\n return new ArrayList<T>(list);\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((list == null) ? 0 : list.hashCode());\n return result;\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 TupleN<?> other = (TupleN<?>) obj;\n if (list == null) {\n if (other.list != null)\n return false;\n } else if (!list.equals(other.list))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"TupleN [values=\" + list + \"]\";\n }\n\n}",
"public final class Tuples {\n\n /**\n * Private constructor to prevent instantiation.\n */\n private Tuples() {\n // prevent instantiation.\n }\n\n public static <T> ResultSetMapper<T> single(final Class<T> cls) {\n Preconditions.checkNotNull(cls, \"cls cannot be null\");\n return new ResultSetMapper<T>() {\n\n @Override\n public T apply(ResultSet rs) {\n return mapObject(rs, cls, 1);\n }\n\n };\n }\n\n public static <T1, T2> ResultSetMapper<Tuple2<T1, T2>> tuple(final Class<T1> cls1,\n final Class<T2> cls2) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n return new ResultSetMapper<Tuple2<T1, T2>>() {\n\n @Override\n public Tuple2<T1, T2> apply(ResultSet rs) {\n return new Tuple2<T1, T2>(mapObject(rs, cls1, 1), mapObject(rs, cls2, 2));\n }\n };\n }\n\n public static <T1, T2, T3> ResultSetMapper<Tuple3<T1, T2, T3>> tuple(final Class<T1> cls1,\n final Class<T2> cls2, final Class<T3> cls3) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n Preconditions.checkNotNull(cls3, \"cls3 cannot be null\");\n return new ResultSetMapper<Tuple3<T1, T2, T3>>() {\n @Override\n public Tuple3<T1, T2, T3> apply(ResultSet rs) {\n return new Tuple3<T1, T2, T3>(mapObject(rs, cls1, 1),\n mapObject(rs, cls2, 2), mapObject(rs, cls3, 3));\n }\n };\n }\n \n public static <T1, T2, T3, T4> ResultSetMapper<Tuple4<T1, T2, T3, T4>> tuple(\n final Class<T1> cls1, final Class<T2> cls2, final Class<T3> cls3,\n final Class<T4> cls4) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n Preconditions.checkNotNull(cls3, \"cls3 cannot be null\");\n Preconditions.checkNotNull(cls4, \"cls4 cannot be null\");\n return new ResultSetMapper<Tuple4<T1, T2, T3, T4>>() {\n @Override\n public Tuple4<T1, T2, T3, T4> apply(ResultSet rs) {\n return new Tuple4<T1, T2, T3, T4>(mapObject(rs, cls1, 1),\n mapObject(rs, cls2, 2), mapObject(rs, cls3, 3),\n mapObject(rs, cls4, 4));\n }\n };\n }\n\n public static <T1, T2, T3, T4, T5> ResultSetMapper<Tuple5<T1, T2, T3, T4, T5>> tuple(\n final Class<T1> cls1, final Class<T2> cls2, final Class<T3> cls3, final Class<T4> cls4,\n final Class<T5> cls5) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n Preconditions.checkNotNull(cls3, \"cls3 cannot be null\");\n Preconditions.checkNotNull(cls4, \"cls4 cannot be null\");\n Preconditions.checkNotNull(cls5, \"cls5 cannot be null\");\n\n return new ResultSetMapper<Tuple5<T1, T2, T3, T4, T5>>() {\n @Override\n public Tuple5<T1, T2, T3, T4, T5> apply(ResultSet rs) {\n return new Tuple5<T1, T2, T3, T4, T5>(mapObject(rs, cls1, 1),\n mapObject(rs, cls2, 2), mapObject(rs, cls3, 3),\n mapObject(rs, cls4, 4), mapObject(rs, cls5, 5));\n }\n };\n }\n\n public static <T1, T2, T3, T4, T5, T6> ResultSetMapper<Tuple6<T1, T2, T3, T4, T5, T6>> tuple(\n final Class<T1> cls1, final Class<T2> cls2, final Class<T3> cls3, final Class<T4> cls4,\n final Class<T5> cls5, final Class<T6> cls6) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n Preconditions.checkNotNull(cls3, \"cls3 cannot be null\");\n Preconditions.checkNotNull(cls4, \"cls4 cannot be null\");\n Preconditions.checkNotNull(cls5, \"cls5 cannot be null\");\n Preconditions.checkNotNull(cls6, \"cls6 cannot be null\");\n return new ResultSetMapper<Tuple6<T1, T2, T3, T4, T5, T6>>() {\n @Override\n public Tuple6<T1, T2, T3, T4, T5, T6> apply(ResultSet rs) {\n return new Tuple6<T1, T2, T3, T4, T5, T6>(mapObject(rs, cls1, 1),\n mapObject(rs, cls2, 2), mapObject(rs, cls3, 3),\n mapObject(rs, cls4, 4), mapObject(rs, cls5, 5),\n mapObject(rs, cls6, 6));\n }\n };\n }\n\n public static <T1, T2, T3, T4, T5, T6, T7> ResultSetMapper<Tuple7<T1, T2, T3, T4, T5, T6, T7>> tuple(\n final Class<T1> cls1, final Class<T2> cls2, final Class<T3> cls3, final Class<T4> cls4,\n final Class<T5> cls5, final Class<T6> cls6, final Class<T7> cls7) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n Preconditions.checkNotNull(cls3, \"cls3 cannot be null\");\n Preconditions.checkNotNull(cls4, \"cls4 cannot be null\");\n Preconditions.checkNotNull(cls5, \"cls5 cannot be null\");\n Preconditions.checkNotNull(cls6, \"cls6 cannot be null\");\n Preconditions.checkNotNull(cls7, \"cls7 cannot be null\");\n return new ResultSetMapper<Tuple7<T1, T2, T3, T4, T5, T6, T7>>() {\n @Override\n public Tuple7<T1, T2, T3, T4, T5, T6, T7> apply(ResultSet rs) {\n return new Tuple7<T1, T2, T3, T4, T5, T6, T7>(mapObject(rs, cls1, 1),\n mapObject(rs, cls2, 2), mapObject(rs, cls3, 3),\n mapObject(rs, cls4, 4), mapObject(rs, cls5, 5),\n mapObject(rs, cls6, 6), mapObject(rs, cls7, 7));\n }\n };\n }\n\n public static <T> ResultSetMapper<TupleN<T>> tupleN(final Class<T> cls) {\n Preconditions.checkNotNull(cls, \"cls cannot be null\");\n return new ResultSetMapper<TupleN<T>>() {\n @Override\n public TupleN<T> apply(ResultSet rs) {\n return toTupleN(cls, rs);\n }\n };\n }\n\n private static <T> TupleN<T> toTupleN(final Class<T> cls, ResultSet rs) {\n try {\n int n = rs.getMetaData().getColumnCount();\n List<T> list = new ArrayList<T>();\n for (int i = 1; i <= n; i++) {\n list.add(mapObject(rs, cls, i));\n }\n return new TupleN<T>(list);\n } catch (SQLException e) {\n throw new SQLRuntimeException(e);\n }\n }\n}"
] | import java.sql.ResultSet;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.davidmoten.rx.jdbc.tuple.Tuple2;
import org.davidmoten.rx.jdbc.tuple.Tuple3;
import org.davidmoten.rx.jdbc.tuple.Tuple4;
import org.davidmoten.rx.jdbc.tuple.Tuple5;
import org.davidmoten.rx.jdbc.tuple.Tuple6;
import org.davidmoten.rx.jdbc.tuple.Tuple7;
import org.davidmoten.rx.jdbc.tuple.TupleN;
import org.davidmoten.rx.jdbc.tuple.Tuples;
import com.github.davidmoten.guavamini.Preconditions;
import io.reactivex.Flowable;
import io.reactivex.Single; | package org.davidmoten.rx.jdbc;
public interface GetterTx {
/**
* Transforms the results using the given function.
*
* @param mapper
* transforms ResultSet row to an object of type T
* @param <T>
* the type being mapped to
* @return the results of the query as an Observable
*/
<T> Flowable<Tx<T>> get(@Nonnull ResultSetMapper<? extends T> mapper);
default <T> Flowable<Tx<T>> getAs(@Nonnull Class<T> cls) {
Preconditions.checkNotNull(cls, "cls cannot be null");
return get(rs -> Util.mapObject(rs, cls, 1));
}
default <T> Flowable<Tx<Optional<T>>> getAsOptional(@Nonnull Class<T> cls) {
Preconditions.checkNotNull(cls, "cls cannot be null");
return get(rs -> Optional.ofNullable(Util.mapObject(rs, cls, 1)));
}
/**
* <p>
* Transforms each row of the {@link ResultSet} into an instance of
* <code>T</code> using <i>automapping</i> of the ResultSet columns into
* corresponding constructor parameters that are assignable. Beyond normal
* assignable criteria (for example Integer 123 is assignable to a Double) other
* conversions exist to facilitate the automapping:
* </p>
* <p>
* They are:
* <ul>
* <li>java.sql.Blob --> byte[]</li>
* <li>java.sql.Blob --> java.io.InputStream</li>
* <li>java.sql.Clob --> String</li>
* <li>java.sql.Clob --> java.io.Reader</li>
* <li>java.sql.Date --> java.util.Date</li>
* <li>java.sql.Date --> Long</li>
* <li>java.sql.Timestamp --> java.util.Date</li>
* <li>java.sql.Timestamp --> Long</li>
* <li>java.sql.Time --> java.util.Date</li>
* <li>java.sql.Time --> Long</li>
* <li>java.math.BigInteger -->
* Short,Integer,Long,Float,Double,BigDecimal</li>
* <li>java.math.BigDecimal -->
* Short,Integer,Long,Float,Double,BigInteger</li>
* </ul>
*
* @param cls
* class to automap each row of the ResultSet to
* @param <T>
* generic type of returned stream emissions
* @return Flowable of T
*
*/
default <T> Flowable<Tx<T>> autoMap(@Nonnull Class<T> cls) {
Preconditions.checkNotNull(cls, "cls cannot be null");
return get(Util.autoMap(cls));
}
/**
* Automaps all the columns of the {@link ResultSet} into the target class
* <code>cls</code>. See {@link #autoMap(Class) autoMap()}.
*
* @param cls
* class of the TupleN elements
* @param <T>
* generic type of returned stream emissions
* @return stream of transaction items
*/
default <T> Flowable<Tx<TupleN<T>>> getTupleN(@Nonnull Class<T> cls) {
Preconditions.checkNotNull(cls, "cls cannot be null");
return get(Tuples.tupleN(cls));
}
/**
* Automaps all the columns of the {@link ResultSet} into {@link Object} . See
* {@link #autoMap(Class) autoMap()}.
*
* @return stream of transaction items
*/
default Flowable<Tx<TupleN<Object>>> getTupleN() {
return get(Tuples.tupleN(Object.class));
}
/**
* Automaps the columns of the {@link ResultSet} into the specified classes. See
* {@link #autoMap(Class) autoMap()}.
*
* @param cls1
* first class
* @param cls2
* second class
* @param <T1>
* type of first class
* @param <T2>
* type of second class
* @return stream of transaction items
*/
default <T1, T2> Flowable<Tx<Tuple2<T1, T2>>> getAs(@Nonnull Class<T1> cls1,
@Nonnull Class<T2> cls2) {
return get(Tuples.tuple(cls1, cls2));
}
/**
* Automaps the columns of the {@link ResultSet} into the specified classes. See
* {@link #autoMap(Class) autoMap()}.
*
* @param cls1
* first class
* @param cls2
* second class
* @param cls3
* third class
* @param <T1>
* type of first class
* @param <T2>
* type of second class
* @param <T3>
* type of third class
* @return stream of tuples
*/
default <T1, T2, T3> Flowable<Tx<Tuple3<T1, T2, T3>>> getAs(@Nonnull Class<T1> cls1,
@Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3) {
return get(Tuples.tuple(cls1, cls2, cls3));
}
/**
* Automaps the columns of the {@link ResultSet} into the specified classes. See
* {@link #autoMap(Class) autoMap()}.
*
* @param cls1
* first class
* @param cls2
* second class
* @param cls3
* third class
* @param cls4
* fourth class
* @param <T1>
* type of first class
* @param <T2>
* type of second class
* @param <T3>
* type of third class
* @param <T4>
* type of fourth class
* @return stream of tuples
*/
default <T1, T2, T3, T4> Flowable<Tx<Tuple4<T1, T2, T3, T4>>> getAs(@Nonnull Class<T1> cls1,
@Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3, @Nonnull Class<T4> cls4) {
return get(Tuples.tuple(cls1, cls2, cls3, cls4));
}
/**
* Automaps the columns of the {@link ResultSet} into the specified classes. See
* {@link #autoMap(Class) autoMap()}.
*
* @param cls1
* first class
* @param cls2
* second class
* @param cls3
* third class
* @param cls4
* fourth class
* @param cls5
* fifth class
* @param <T1>
* type of first class
* @param <T2>
* type of second class
* @param <T3>
* type of third class
* @param <T4>
* type of fourth class
* @param <T5>
* type of fifth class
* @return stream of transaction items
*/ | default <T1, T2, T3, T4, T5> Flowable<Tx<Tuple5<T1, T2, T3, T4, T5>>> getAs( | 3 |
cm-heclouds/JAVA-HTTP-SDK | javaSDK/src/main/java/cmcc/iot/onenet/javasdk/api/cmds/QueryCmdsStatus.java | [
"public abstract class AbstractAPI<T> {\n public String key;\n public String url;\n public Method method;\n public ObjectMapper mapper = initObjectMapper();\n\n private ObjectMapper initObjectMapper() {\n ObjectMapper objectMapper = new ObjectMapper();\n //关闭字段不识别报错\n objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n //调整默认时区为北京时间\n TimeZone timeZone = TimeZone.getTimeZone(\"GMT+8\");\n DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.CHINA);\n dateFormat.setTimeZone(timeZone);\n objectMapper.setDateFormat(dateFormat);\n objectMapper.setTimeZone(timeZone);\n return objectMapper;\n }\n}",
"public class OnenetApiException extends RuntimeException {\n\t private String message = null;\n\t public String getMessage() {\n\t\treturn message;\n\t}\n\t\tpublic OnenetApiException( String message) {\n\t this.message = message;\n\t }\n}",
"public class HttpGetMethod extends BasicHttpMethod {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\tHttpGet httpGet;\n\n\tpublic HttpGetMethod(Method method) {\n\t\tsuper(method);\n\n\t}\n\n\tpublic HttpResponse execute() throws Exception {\n\t\tHttpResponse httpResponse = null;\n\t\thttpClient = HttpClients.createDefault();\n\n\t\thttpResponse = httpClient.execute(httpRequestBase);\n\t\tint statusCode = httpResponse.getStatusLine().getStatusCode();\n\t\tif (statusCode != HttpStatus.SC_OK && statusCode != 221) {\n\t\t\tString response = EntityUtils.toString(httpResponse.getEntity());\n\t\t\tlogger.error(\"request failed status:{}, response::{}\",statusCode, response);\n\t\t\tthrow new OnenetApiException(\"request failed: \" + response);\n\t\t}\n\n\t\treturn httpResponse;\n\t}\n}",
"public enum Method{\n POST,GET,DELETE,PUT\n}",
"public class BasicResponse<T> {\n\tpublic int errno;\n\tpublic String error;\n @JsonProperty(\"data\")\n public Object dataInternal;\n public T data;\n @JsonIgnore\n public String json;\n\n\tpublic String getJson() {\n\t\treturn json;\n\t}\n\n\tpublic void setJson(String json) {\n\t\tthis.json = json;\n\t}\n\n\tpublic int getErrno() {\n return errno;\n }\n\n public void setErrno(int errno) {\n this.errno = errno;\n }\n\n public String getError() {\n return error;\n }\n\n public void setError(String error) {\n this.error = error;\n }\n\n @JsonGetter(\"data\")\n public Object getDataInternal() {\n return dataInternal;\n }\n @JsonSetter(\"data\")\n public void setDataInternal(Object dataInternal) {\n this.dataInternal = dataInternal;\n }\n\n public T getData() {\n return data;\n }\n\n public void setData(T data) {\n this.data = data;\n }\n}",
"public class CmdsResponse {\n\t@JsonProperty(\"status\")\n\tprivate Integer status;\n\t@JsonProperty(\"desc\")\n\tprivate String desc;\n\tpublic Integer getStatus() {\n\t\treturn status;\n\t}\n\tpublic void setStatus(Integer status) {\n\t\tthis.status = status;\n\t}\n\tpublic String getDesc() {\n\t\treturn desc;\n\t}\n\tpublic void setDesc(String desc) {\n\t\tthis.desc = desc;\n\t}\n\t\n}",
"public class Config {\n\tprivate final static Properties properties;\n private static org.slf4j.Logger logger = LoggerFactory.getLogger(Config.class);\n\tstatic {\n//\t\tLogger.getRootLogger().setLevel(Level.OFF);\n\t\tInputStream in = Config.class.getClassLoader().getResourceAsStream(\"config.properties\");\n\t\tproperties = new Properties();\n\t\ttry {\n\t\t\tproperties.load(in);\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"init config error\", e);\n\t\t}\n\t}\n\n\t/**\n\t * 读取以逗号分割的字符串,作为字符串数组返回\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static List<String> getStringList(String conf) {\n\t\treturn Arrays.asList(StringUtils.split(properties.getProperty(conf), \",\"));\n\t}\n\n\t/**\n\t * 读取字符串\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static String getString(String conf) {\n\t\treturn properties.getProperty(conf);\n\t}\n\n\t/**\n\t * 读取整数\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static int getInt(String conf) {\n\t\tint ret = 0;\n\t\ttry {\n\t\t\tret = Integer.parseInt(getString(conf));\n\t\t} catch (NumberFormatException e) {\n\t\t\tlogger.error(\"format error\", e);\n\t\t}\n\t\treturn ret;\n\t}\n\n\t/**\n\t * 读取布尔值\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static boolean getBoolean(String conf) {\n\t\treturn Boolean.parseBoolean(getString(conf));\n\t}\n}"
] | import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import cmcc.iot.onenet.javasdk.api.AbstractAPI;
import cmcc.iot.onenet.javasdk.exception.OnenetApiException;
import cmcc.iot.onenet.javasdk.http.HttpGetMethod;
import cmcc.iot.onenet.javasdk.request.RequestInfo.Method;
import cmcc.iot.onenet.javasdk.response.BasicResponse;
import cmcc.iot.onenet.javasdk.response.cmds.CmdsResponse;
import cmcc.iot.onenet.javasdk.utils.Config; | package cmcc.iot.onenet.javasdk.api.cmds;
public class QueryCmdsStatus extends AbstractAPI {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private HttpGetMethod HttpMethod;
private String cmdUuid;
/**
* @param cmdUuid:命令id,String
* @param key:masterkey或者设备apikey
*/
public QueryCmdsStatus(String cmdUuid,String key) {
this.cmdUuid = cmdUuid;
this.key=key;
this.method= Method.GET;
this.HttpMethod=new HttpGetMethod(method);
Map<String, Object> headmap = new HashMap<String, Object>();
headmap.put("api-key", key);
HttpMethod.setHeader(headmap);
this.url = Config.getString("test.url") + "/cmds/" + cmdUuid;
HttpMethod.setcompleteUrl(url,null);
}
public BasicResponse<CmdsResponse> executeApi() {
BasicResponse response=null;
try {
HttpResponse httpResponse=HttpMethod.execute();
response = mapper.readValue(httpResponse.getEntity().getContent(), BasicResponse.class);
response.setJson(mapper.writeValueAsString(response));
Object newData = mapper.readValue(mapper.writeValueAsString(response.getDataInternal()), CmdsResponse.class);
response.setData(newData);
return response;
} catch (Exception e) {
logger.error("json error {}", e.getMessage()); | throw new OnenetApiException(e.getMessage()); | 1 |
quhfus/DoSeR-Disambiguation | doser-dis-disambiguationserver/src/main/java/doser/server/actions/disambiguation/DisambiguationService.java | [
"public final class DisambiguationMainService {\n\n\tpublic final static int MAXCLAUSECOUNT = 4096;\n\n\tprivate static final int TIMERPERIOD = 10000;\n\n\tprivate static DisambiguationMainService instance = null;\n\n//\tprivate Model hdtdbpediaCats;\n//\tprivate Model hdtdbpediaCats_ger;\n//\tprivate Model hdtdbpediaCatsL;\n//\tprivate Model hdtdbpediaCatsL_ger;\n//\tprivate Model hdtdbpediaDesc;\n//\tprivate Model hdtdbpediaLabels;\n//\tprivate Model hdtdbpediaLabels_ger;\n//\tprivate Model hdtdbpediaSkosCategories;\n//\tprivate Model hdtdbpediaInstanceTypes;\n//\tprivate Model hdtYagoCatsLab;\n//\tprivate Model hdtyagoTaxonomy;\n//\tprivate Model hdtyagoTransTypes;\n//\tprivate Model hdtdbpediaRedirects;\n\n\tprivate Map<KnowledgeBaseIdentifiers, AbstractKnowledgeBase> knowledgebases;\n\n\tprivate List<Timer> timerList;\n\n\t/**\n\t * The DisambiguationMainService Constructor specifies a set of knowledge\n\t * bases which are used for disambiguation. Dynamic knowledge bases will be\n\t * initialized in a background thread loader. The static knowledge bases are\n\t * initialized within the PriorLoader class. The Apache Lucene searchers and\n\t * readers are created in the constructor of the EntityCentricDisambiguation\n\t * class. /**\n\t */\n\tprivate DisambiguationMainService() {\n\t\tsuper();\n\t\tthis.knowledgebases = new EnumMap<KnowledgeBaseIdentifiers, AbstractKnowledgeBase>(\n\t\t\t\tKnowledgeBaseIdentifiers.class);\n\t\tthis.knowledgebases.put(KnowledgeBaseIdentifiers.Standard,\n\t\t\t\tnew EntityCentricKBDBpedia(Properties.getInstance()\n\t\t\t\t\t\t.getEntityCentricKBWikipedia(), false,\n\t\t\t\t\t\tnew DefaultSimilarity()));\n\t\tthis.knowledgebases.put(KnowledgeBaseIdentifiers.Biomed,\n\t\t\t\tnew EntityCentricKBBiomed(Properties.getInstance()\n\t\t\t\t\t\t.getEntityCentricKBBiomed(), false,\n\t\t\t\t\t\tnew DefaultSimilarity()));\n\t\t// this.knowledgebases.put(KnowledgeBaseIdentifiers.CSTable,\n\t\t// new EnCenKBCStable(Properties.getInstance().getCSTableIndex(),\n\t\t// false, new DefaultSimilarity()));\n\t\t// this.knowledgebases.put(KnowledgeBaseIdentifiers.DbPediaBiomedCopy,\n\t\t// new EntityCentricKnowledgeBaseDefault(Properties.getInstance()\n\t\t// .getDbPediaBiomedCopyKB(), true,\n\t\t// new DefaultSimilarity()));\n\t\t// this.knowledgebases.put(\n\t\t// KnowledgeBaseIdentifiers.DocumentCentricDefault,\n\t\t// new DocumentCentricKnowledgeBaseDefault(Properties\n\t\t// .getInstance().getDocumentCentricKB(), false,\n\t\t// new DefaultSimilarity()));\n\n\t\t// Create Timer thread, which periodically calls the IndexReader updates\n\t\t// for dynamic knowledge bases\n\t\tthis.timerList = new ArrayList<Timer>();\n\t\tfor (AbstractKnowledgeBase kb : this.knowledgebases.values()) {\n\t\t\tTimer timer = new Timer();\n\t\t\tthis.timerList.add(timer);\n\t\t\ttimer.scheduleAtFixedRate(kb, 0, TIMERPERIOD);\n\t\t}\n\n\t\tint threadSize = knowledgebases.size();\n\t\tif (threadSize > 0) {\n\t\t\tBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(\n\t\t\t\t\tthreadSize);\n\t\t\tThreadPoolExecutor ex = new ThreadPoolExecutor(threadSize,\n\t\t\t\t\tthreadSize, 100, TimeUnit.SECONDS, queue);\n\t\t\tfor (AbstractKnowledgeBase kb : knowledgebases.values()) {\n\t\t\t\tex.execute(new KnowledgeBaseInitializationThread(kb));\n\t\t\t}\n\t\t\tex.shutdown();\n\t\t\ttry {\n\t\t\t\twhile (!ex.awaitTermination(100, TimeUnit.SECONDS)) {\n\t\t\t\t\tLogger.getRootLogger().info(\n\t\t\t\t\t\t\t\"InitializationPhase not completed yet! Still waiting \"\n\t\t\t\t\t\t\t\t\t+ ex.getActiveCount());\n\t\t\t\t}\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tLogger.getRootLogger().warn(e.getStackTrace());\n\t\t\t}\n\t\t}\n\n\t\t// this.loadRelations();\n//\t\ttry {\n//\t\t\tfinal HDT hdt = HDTManager.mapIndexedHDT(Properties.getInstance()\n//\t\t\t\t\t.getDBPediaArticleCategories(), null);\n//\t\t\tfinal HDT hdt3 = HDTManager.mapIndexedHDT(Properties.getInstance()\n//\t\t\t\t\t.getDBPediaCategoryLabels(), null);\n//\t\t\tfinal HDT hdt5 = HDTManager.mapIndexedHDT(Properties.getInstance()\n//\t\t\t\t\t.getDBPediaLabels(), null);\n//\t\t\tfinal HDT hdt6 = HDTManager.mapIndexedHDT(Properties.getInstance()\n//\t\t\t\t\t.getDBPediaDescriptions(), null);\n//\t\t\tfinal HDT hdt7 = HDTManager.mapIndexedHDT(Properties.getInstance()\n//\t\t\t\t\t.getDBpediaSkosCategories(), null);\n//\t\t\tfinal HDT hdt8 = HDTManager.mapIndexedHDT(Properties.getInstance()\n//\t\t\t\t\t.getDBpediaInstanceTypes(), null);\n//\t\t\tfinal HDT hdt9 = HDTManager.mapIndexedHDT(Properties.getInstance()\n//\t\t\t\t\t.getDBpediaRedirects(), null);\n//\t\t\tfinal HDT hdt10 = HDTManager.mapIndexedHDT(Properties.getInstance().getDBPediaLabels_GER(), null);\n//\t\t\tfinal HDT hdt11 = HDTManager.mapIndexedHDT(Properties.getInstance().getDBPediaArticleCategories_GER(), null);\n//\t\t\tfinal HDT hdt12 = HDTManager.mapIndexedHDT(Properties.getInstance().getDBPediaCategoryLabels_GER(), null);\n//\t\t\tfinal HDTGraph graph = new HDTGraph(hdt);\n//\t\t\tfinal HDTGraph graph3 = new HDTGraph(hdt3);\n//\t\t\tfinal HDTGraph graph5 = new HDTGraph(hdt5);\n//\t\t\tfinal HDTGraph graph6 = new HDTGraph(hdt6);\n//\t\t\tfinal HDTGraph graph7 = new HDTGraph(hdt7);\n//\t\t\tfinal HDTGraph graph8 = new HDTGraph(hdt8);\n//\t\t\tfinal HDTGraph graph9 = new HDTGraph(hdt9);\n//\t\t\tfinal HDTGraph graph10 = new HDTGraph(hdt10);\n//\t\t\tfinal HDTGraph graph11 = new HDTGraph(hdt11);\n//\t\t\tfinal HDTGraph graph12 = new HDTGraph(hdt12);\n//\t\t\tthis.hdtdbpediaCats = ModelFactory.createModelForGraph(graph);\n//\t\t\tthis.hdtdbpediaCatsL = ModelFactory.createModelForGraph(graph3);\n//\t\t\tthis.hdtdbpediaLabels = ModelFactory.createModelForGraph(graph5);\n//\t\t\tthis.hdtdbpediaDesc = ModelFactory.createModelForGraph(graph6);\n//\t\t\tthis.hdtdbpediaSkosCategories = ModelFactory\n//\t\t\t\t\t.createModelForGraph(graph7);\n//\t\t\tthis.hdtdbpediaInstanceTypes = ModelFactory\n//\t\t\t\t\t.createModelForGraph(graph8);\n//\t\t\tthis.hdtdbpediaRedirects = ModelFactory\n//\t\t\t\t\t.createModelForGraph(graph9);\n//\t\t\tthis.hdtdbpediaLabels_ger = ModelFactory.createModelForGraph(graph10);\n//\t\t\tthis.hdtdbpediaCats_ger = ModelFactory.createModelForGraph(graph11);\n//\t\t\tthis.hdtdbpediaCatsL_ger = ModelFactory.createModelForGraph(graph12);\n//\t\t} catch (final IOException e) {\n//\t\t\te.printStackTrace();\n//\t\t}\n\t}\n\n\tpublic synchronized static DisambiguationMainService getInstance() {\n\t\tif (instance == null) {\n\t\t\tinstance = new DisambiguationMainService();\n\t\t}\n\t\treturn instance;\n\t}\n\n\tpublic static void initialize() {\n\t\tinstance = new DisambiguationMainService();\n\t}\n\n\tpublic void disambiguate(List<AbstractDisambiguationTask> taskList) {\n\t\tfor (int i = 0; i < taskList.size(); i++) {\n\t\t\tAbstractDisambiguationTask task = taskList.get(i);\n\t\t\tAbstractDisambiguationAlgorithm algorithm = DisambiguationHandler\n\t\t\t\t\t.getInstance().getAlgorithm(task);\n\t\t\tif (algorithm != null) {\n\t\t\t\ttask.setKb(this.knowledgebases.get(task.getKbIdentifier()));\n\t\t\t\talgorithm.disambiguate(task);\n\t\t\t}\n\t\t}\n\t}\n\n//\tpublic Model getDBPediaArticleCategories() {\n//\t\treturn this.hdtdbpediaCats;\n//\t}\n//\t\n//\tpublic Model getDBPediaArticleCategories_GER() {\n//\t\treturn this.hdtdbpediaCats_ger;\n//\t}\n//\n//\tpublic Model getDBPediaCategoryLabels() {\n//\t\treturn this.hdtdbpediaCatsL;\n//\t}\n//\t\n//\tpublic Model getDBPediaCategoryLabels_GER() {\n//\t\treturn this.hdtdbpediaCatsL_ger;\n//\t}\n//\n//\tpublic Model getDBPediaDescription() {\n//\t\treturn this.hdtdbpediaDesc;\n//\t}\n//\n//\tpublic Model getDBPediaInstanceTypes() {\n//\t\treturn this.hdtdbpediaInstanceTypes;\n//\t}\n//\n//\tpublic Model getDBPediaLabels() {\n//\t\treturn this.hdtdbpediaLabels;\n//\t}\n//\t\n//\tpublic Model getDBPediaLabels_GER() {\n//\t\treturn this.hdtdbpediaLabels_ger;\n//\t}\n//\n//\tpublic Model getDBpediaSkosCategories() {\n//\t\treturn this.hdtdbpediaSkosCategories;\n//\t}\n//\n//\tpublic Model getYagoCategoryLabels() {\n//\t\treturn this.hdtYagoCatsLab;\n//\t}\n//\n//\tpublic Model getYagoTaxonomy() {\n//\t\treturn this.hdtyagoTaxonomy;\n//\t}\n//\n//\tpublic Model getYagoTransitiveTypes() {\n//\t\treturn this.hdtyagoTransTypes;\n//\t}\n//\t\n//\tpublic Model getDBpediaRedirects() {\n//\t\treturn this.hdtdbpediaRedirects;\n//\t}\n\n\n\t/**\n\t * A seperate thread class to initialize our knowledgebases\n\t * \n\t * @author Stefan Zwicklbauer\n\t */\n\tclass KnowledgeBaseInitializationThread implements Runnable {\n\n\t\tprivate AbstractKnowledgeBase kb;\n\n\t\tpublic KnowledgeBaseInitializationThread(AbstractKnowledgeBase kb) {\n\t\t\tsuper();\n\t\t\tthis.kb = kb;\n\t\t}\n\n\t\t@Override\n\t\tpublic void run() {\n\t\t\tkb.initialize();\n\t\t}\n\t}\n\n\tpublic void shutDownDisambiguationService() {\n\t\tfor (Timer timer : timerList) {\n\t\t\ttimer.cancel();\n\t\t}\n\t}\n}",
"public abstract class AbstractDisambiguationTask {\n\n\tprotected int returnNr;\n\n\tprotected AbstractKnowledgeBase kb;\n\n\tprotected KnowledgeBaseIdentifiers kbIdentifier;\n\t\n\tprotected boolean retrieveDocClasses;\n\t\n\tprotected List<Response> responses;\n\n\tpublic int getReturnNr() {\n\t\treturn returnNr;\n\t}\n\n\tpublic void setReturnNr(int returnNr) {\n\t\tthis.returnNr = returnNr;\n\t}\n\n\tpublic AbstractKnowledgeBase getKb() {\n\t\treturn kb;\n\t}\n\n\tpublic void setKb(AbstractKnowledgeBase kb) {\n\t\tthis.kb = kb;\n\t}\n\n\tpublic KnowledgeBaseIdentifiers getKbIdentifier() {\n\t\treturn this.kbIdentifier;\n\t}\n\t\n\tpublic boolean isRetrieveDocClasses() {\n\t\treturn retrieveDocClasses;\n\t}\n\n\tpublic void setRetrieveDocClasses(boolean retrieveDocClasses) {\n\t\tthis.retrieveDocClasses = retrieveDocClasses;\n\t}\n\t\n\tpublic List<Response> getResponse() {\n\t\treturn responses;\n\t}\n\n\tpublic void setResponse(List<Response> responses) {\n\t\tthis.responses = responses;\n\t}\n\t\n\tpublic abstract void setKbIdentifier(String kbversion, String setting);\n}",
"public class DisambiguationTaskCollective extends AbstractDisambiguationTask {\n\n\tprivate List<EntityDisambiguationDPO> entitiesToDis;\n\t\n\t/* A maintopic e.g. the column identifier in a table */\n\tprivate String mainTopic;\n\n\tpublic DisambiguationTaskCollective(final List<EntityDisambiguationDPO> entityToDis, String mainTopic) {\n\t\tsuper();\n\t\tthis.entitiesToDis = entityToDis;\n\t\tthis.mainTopic = mainTopic;\n\t}\n\n\tpublic List<EntityDisambiguationDPO> getEntityToDisambiguate() {\n\t\treturn this.entitiesToDis;\n\t}\n\t\n\tpublic String getMainTopic() {\n\t\treturn this.mainTopic;\n\t}\n\n\tpublic void setSurfaceForm(final List<EntityDisambiguationDPO> surfaceForm) {\n\t\tthis.entitiesToDis = surfaceForm;\n\t}\n\n\t/**\n\t * Assignment function to determine the used knowledge base\n\t * \n\t * @param kbversion\n\t * @param setting\n\t */\n\t@Override\n\tpublic void setKbIdentifier(String kbversion, String setting) {\n\t\tif(setting == null) {\n\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.Standard;\n\t\t} else if(setting.equalsIgnoreCase(\"DocumentCentric\")) {\n\t\t\tif(kbversion.equalsIgnoreCase(\"default\")) {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.DocumentCentricDefault;\n\t\t\t} else {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.DocumentCentricDefault;\n\t\t\t}\n\t\t} else if(setting.equalsIgnoreCase(\"EntityCentric\")) {\n\t\t\tif(kbversion.equalsIgnoreCase(\"default\")) {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.Standard;\n\t\t\t} else if(kbversion.equalsIgnoreCase(\"cstable\")) {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.CSTable;\n\t\t\t} else if(kbversion.equalsIgnoreCase(\"biomed\")) {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.Biomed;\n\t\t\t} else {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.Standard;\n\t\t\t}\n\t\t} else {\n\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.Standard;\n\t\t}\n\t}\t\n}",
"public class DisambiguationTaskSingle extends AbstractDisambiguationTask {\n\n\tprivate EntityDisambiguationDPO entityToDis;\n\n\tpublic DisambiguationTaskSingle(final EntityDisambiguationDPO entityToDis) {\n\t\tsuper();\n\t\tthis.entityToDis = entityToDis;\n\t\tthis.retrieveDocClasses = false;\n\t}\n\n\tpublic EntityDisambiguationDPO getEntityToDisambiguate() {\n\t\treturn this.entityToDis;\n\t}\n\n\tpublic void setSurfaceForm(final EntityDisambiguationDPO surfaceForm) {\n\t\tthis.entityToDis = surfaceForm;\n\t}\n\n\t/**\n\t * Assignment function to determine the used knowledge base\n\t * \n\t * @param kbversion\n\t * @param setting\n\t */\n\t@Override\n\tpublic void setKbIdentifier(String kbversion, String setting) {\n\t\tif(setting == null) {\n\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.Standard;\n\t\t} else if(setting.equalsIgnoreCase(\"DocumentCentric\")) {\n\t\t\tif(kbversion.equalsIgnoreCase(\"default\")) {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.DocumentCentricDefault;\n\t\t\t} else {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.DocumentCentricDefault;\n\t\t\t}\n\t\t} else if(setting.equalsIgnoreCase(\"EntityCentric\")) {\n\t\t\tif(kbversion.equalsIgnoreCase(\"default\")) {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.Standard;\n\t\t\t} else if(kbversion.equalsIgnoreCase(\"cstable\")) {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.CSTable;\n\t\t\t} else if(kbversion.equalsIgnoreCase(\"biomedcopy\")) {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.Biomed;\n\t\t\t} else {\n\t\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.Standard;\n\t\t\t}\n\t\t} else {\n\t\t\tthis.kbIdentifier = KnowledgeBaseIdentifiers.Standard;\n\t\t}\n\t}\n}",
"public class DisambiguationRequest {\n\tprivate String documentUri;\n\tprivate List<EntityDisambiguationDPO> surfaceFormsToDisambiguate;\n\tprivate Integer docsToReturn;\n\tprivate String mainTopic;\n\n\tpublic String getDocumentUri() {\n\t\treturn this.documentUri;\n\t}\n\n\tpublic List<EntityDisambiguationDPO> getSurfaceFormsToDisambiguate() {\n\t\treturn this.surfaceFormsToDisambiguate;\n\t}\n\n\tpublic void setDocumentUri(final String documentUri) {\n\t\tthis.documentUri = documentUri;\n\t}\n\n\tpublic void setSurfaceFormsToDisambiguate(\n\t\t\tfinal List<EntityDisambiguationDPO> surfaceFormsToDisambiguate) {\n\t\tthis.surfaceFormsToDisambiguate = surfaceFormsToDisambiguate;\n\t}\n\n\tpublic Integer getDocsToReturn() {\n\t\treturn docsToReturn;\n\t}\n\n\tpublic void setDocsToReturn(Integer docsToReturn) {\n\t\tthis.docsToReturn = docsToReturn;\n\t}\n\n\tpublic String getMainTopic() {\n\t\treturn mainTopic;\n\t}\n\n\tpublic void setMainTopic(String mainTopic) {\n\t\tthis.mainTopic = mainTopic;\n\t}\n}",
"public class DisambiguationResponse {\n\t\n\tprivate List<Response> tasks; // NOPMD by quh on 18.02.14 09:34\n\n\tprivate String documentUri;\n\t\n\tpublic List<Response> getTasks() {\n\t\treturn tasks;\n\t}\n\n\tpublic void setTasks(List<Response> tasks) {\n\t\tthis.tasks = tasks;\n\t}\n\n\tpublic String getDocumentUri() {\n\t\treturn this.documentUri;\n\t}\n\n\tpublic void setDocumentUri(final String documentUri) {\n\t\tthis.documentUri = documentUri;\n\t}\n}",
"public class EntityDisambiguationDPO {\n\n\tprivate String documentId;\n\tprivate String context;\n\tprivate String selectedText;\n\tprivate String setting;\n\tprivate String kbversion;\n\tprivate int startPosition;\n\n\tpublic EntityDisambiguationDPO() {\n\t\tsuper();\n\t}\n\n\tpublic String getContext() {\n\t\treturn this.context;\n\t}\n\n\tpublic String getSelectedText() {\n\t\treturn this.selectedText;\n\t}\n\n\tpublic void setContext(final String context) {\n\t\tthis.context = context;\n\t}\n\n\tpublic void setSelectedText(final String selectedText) {\n\t\tthis.selectedText = selectedText;\n\t}\n\n\tpublic void setSetting(final String setting) {\n\t\tthis.setting = setting;\n\t}\n\n\tpublic String getSetting() {\n\t\treturn setting;\n\t}\n\t\n\tpublic void setDocumentId(final String documentId) {\n\t\tthis.documentId = documentId;\n\t}\n\n\tpublic String getDocumentId() {\n\t\treturn this.documentId;\n\t}\n\n\tpublic void setInternSetting(final String setting) {\n\t\tthis.setting = setting;\n\t}\n\t\n\tpublic String getKbversion() {\n\t\treturn kbversion;\n\t}\n\n\tpublic void setKbversion(String kbversion) {\n\t\tthis.kbversion = kbversion;\n\t}\n\n\tpublic int getStartPosition() {\n\t\treturn startPosition;\n\t}\n\n\tpublic void setStartPosition(int startPosition) {\n\t\tthis.startPosition = startPosition;\n\t}\n}",
"public class Response {\n\n\tprivate List<DisambiguatedEntity> disEntities;\n\tprivate String selectedText;\n\tprivate int documentId;\n\n\tpublic Response() {\n\t\tsuper();\n\t\tthis.disEntities = new LinkedList<DisambiguatedEntity>();\n\t}\n\n\tpublic List<DisambiguatedEntity> getDisEntities() {\n\t\treturn this.disEntities;\n\t}\n\n\tpublic String getSelectedText() {\n\t\treturn this.selectedText;\n\t}\n\n\tpublic void setDisEntities(final List<DisambiguatedEntity> disEntities) {\n\t\tthis.disEntities = disEntities;\n\t}\n\n\tpublic void setSelectedText(final String selectedText) {\n\t\tthis.selectedText = selectedText;\n\t}\n\n\tpublic int getDocumentId() {\n\t\treturn documentId;\n\t}\n\n\tpublic void setDocumentId(int documentId) {\n\t\tthis.documentId = documentId;\n\t}\n}",
"public final class Properties {\n\tprivate static Properties instance;\n\tprivate static final String RESOURCE_NAME = \"disambiguation.properties\";\n//\tprivate static final String RESOURCE_NAME = \"./disambiguation.properties\";\n\t\n\tpublic synchronized static Properties getInstance() {\n\t\tif (instance == null) {\n\t\t\tinstance = new Properties();\n\t\t}\n\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Provides easy access to property files (e.g. config.getInt())\n\t */\n\tPropertiesConfiguration config;\n\n\tprivate Properties() {\n\t\ttry {\n\t\t\tthis.config = new PropertiesConfiguration(RESOURCE_NAME);\n\t\t} catch (final ConfigurationException e) {\n\t\t\tLogger.getRootLogger().error(\"Failed to load properties file: \"\t+ RESOURCE_NAME, e);\n\t\t}\n\t}\n\n\t/**\n\t * ArtifactId of the application (from maven pom.xml)\n\t * \n\t * @return artifact id\n\t */\n\tpublic String getApplicationArtifactId() {\n\t\treturn this.config.getString(\"application.artifactId\");\n\t}\n\n\t/**\n\t * Name of the application (from maven pom.xml)\n\t * \n\t * @return application name\n\t */\n\tpublic String getApplicationName() {\n\t\treturn this.config.getString(\"application.name\");\n\t}\n\n\t/**\n\t * Version of the application (from maven pom.xml)\n\t * \n\t * @return application version\n\t */\n\tpublic String getApplicationVersion() {\n\t\treturn this.config.getString(\"application.version\");\n\t}\n\t\n\tpublic int getDisambiguationResultSize() {\n\t\tfinal String size = this.config.getString(\"disambiguation.returnSize\");\n\t\treturn Integer.valueOf(size);\n\t}\n\n\t/**\n\t * Get location of entity-centric knowledge base\n\t */\n\tpublic String getEntityCentricKBWikipedia() {\n\t\treturn this.config.getString(\"disambiguation.entityCentricKBWikipedia\");\n\t}\n\t\n\tpublic String getEntityCentricKBBiomed() {\n\t\treturn this.config.getString(\"disambiguation.entityCentricBiomedCalbC\");\n\t}\n\t\n\tpublic String getWord2VecService() {\n\t\treturn this.config.getString(\"disambiguation.Word2VecService\");\n\t}\n\n\tpublic String getWord2VecModel() {\n\t\treturn this.config.getString(\"word2vecmodel\");\n\t}\n\t\n\tpublic boolean getCandidateExpansion() {\n\t\tboolean bool = false;\n\t\tString s = this.config.getString(\"candidateExpansion\");\n\t\tif(s.equalsIgnoreCase(\"true\")) {\n\t\t\tbool = true;\n\t\t}\n\t\treturn bool;\n\t}\t\n}"
] | import java.util.LinkedList;
import java.util.List;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import doser.entitydisambiguation.backend.DisambiguationMainService;
import doser.entitydisambiguation.backend.AbstractDisambiguationTask;
import doser.entitydisambiguation.backend.DisambiguationTaskCollective;
import doser.entitydisambiguation.backend.DisambiguationTaskSingle;
import doser.entitydisambiguation.dpo.DisambiguationRequest;
import doser.entitydisambiguation.dpo.DisambiguationResponse;
import doser.entitydisambiguation.dpo.EntityDisambiguationDPO;
import doser.entitydisambiguation.dpo.Response;
import doser.entitydisambiguation.properties.Properties; | package doser.server.actions.disambiguation;
@Controller
@RequestMapping("/disambiguation")
public class DisambiguationService {
public DisambiguationService() {
super();
}
/**
* Testing
*
* @param request
* @return
*/
@RequestMapping(value = "/disambiguateWithoutCategories-single", method = RequestMethod.POST, headers = "Accept=application/json")
public @ResponseBody DisambiguationResponse annotateSingle(@RequestBody final DisambiguationRequest request) {
DisambiguationResponse annotationResponse = disambiguateSingle(request);
return annotationResponse;
}
@RequestMapping(value = "/disambiguationWithoutCategories-collective", method = RequestMethod.POST, headers = "Accept=application/json")
public @ResponseBody DisambiguationResponse annotateCollectiveWithoutCategories(
@RequestBody final DisambiguationRequest request) {
final DisambiguationResponse response = new DisambiguationResponse();
final DisambiguationMainService mainService = DisambiguationMainService.getInstance();
final List<EntityDisambiguationDPO> listToDis = request.getSurfaceFormsToDisambiguate();
if (mainService != null) {
final List<AbstractDisambiguationTask> tasks = new LinkedList<AbstractDisambiguationTask>();
DisambiguationTaskCollective collectiveTask = new DisambiguationTaskCollective(listToDis,
request.getMainTopic());
collectiveTask.setKbIdentifier("default", "EntityCentric");
collectiveTask.setReturnNr(1000);
tasks.add(collectiveTask);
mainService.disambiguate(tasks);
List<Response> responses = collectiveTask.getResponse();
response.setTasks(responses);
response.setDocumentUri(request.getDocumentUri());
}
return response;
}
@RequestMapping(value = "/disambiguationWithoutCategoriesBiomed-collective", method = RequestMethod.POST, headers = "Accept=application/json")
public @ResponseBody DisambiguationResponse annotateCollectiveWithoutCategoriesBiomed(
@RequestBody final DisambiguationRequest request) {
final DisambiguationResponse response = new DisambiguationResponse();
final DisambiguationMainService mainService = DisambiguationMainService.getInstance();
final List<EntityDisambiguationDPO> listToDis = request.getSurfaceFormsToDisambiguate();
if (mainService != null) {
final List<AbstractDisambiguationTask> tasks = new LinkedList<AbstractDisambiguationTask>();
DisambiguationTaskCollective collectiveTask = new DisambiguationTaskCollective(listToDis,
request.getMainTopic());
collectiveTask.setKbIdentifier("biomed", "EntityCentric");
collectiveTask.setReturnNr(1000);
tasks.add(collectiveTask);
mainService.disambiguate(tasks);
List<Response> responses = collectiveTask.getResponse();
response.setTasks(responses);
response.setDocumentUri(request.getDocumentUri());
}
return response;
}
private DisambiguationResponse disambiguateSingle(DisambiguationRequest request) {
final DisambiguationResponse response = new DisambiguationResponse();
final List<EntityDisambiguationDPO> listToDis = request.getSurfaceFormsToDisambiguate();
List<Response> responseList = new LinkedList<Response>();
response.setDocumentUri(request.getDocumentUri());
final List<AbstractDisambiguationTask> tasks = new LinkedList<AbstractDisambiguationTask>();
final DisambiguationMainService mainService = DisambiguationMainService.getInstance();
if (mainService != null) {
int docsToReturn = 0;
if (request.getDocsToReturn() == null) {
docsToReturn = Properties.getInstance().getDisambiguationResultSize();
} else {
docsToReturn = request.getDocsToReturn();
}
for (int i = 0; i < listToDis.size(); i++) {
EntityDisambiguationDPO dpo = listToDis.get(i); | DisambiguationTaskSingle task = new DisambiguationTaskSingle(dpo); | 3 |
indvd00m/java-ascii-render | ascii-render/src/test/java/com/indvd00m/ascii/render/tests/plot/TestPlot.java | [
"public class Region implements IRegion {\n\n\tprotected int x;\n\tprotected int y;\n\tprotected int width;\n\tprotected int height;\n\n\tpublic Region(int x, int y, int width, int height) {\n\t\tsuper();\n\t\tif (width < 0) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\tif (height < 0) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t}\n\n\t@Override\n\tpublic int getX() {\n\t\treturn x;\n\t}\n\n\t@Override\n\tpublic int getY() {\n\t\treturn y;\n\t}\n\n\t@Override\n\tpublic int getWidth() {\n\t\treturn width;\n\t}\n\n\t@Override\n\tpublic int getHeight() {\n\t\treturn height;\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 + height;\n\t\tresult = prime * result + width;\n\t\tresult = prime * result + x;\n\t\tresult = prime * result + y;\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\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tRegion other = (Region) obj;\n\t\tif (height != other.height) {\n\t\t\treturn false;\n\t\t}\n\t\tif (width != other.width) {\n\t\t\treturn false;\n\t\t}\n\t\tif (x != other.x) {\n\t\t\treturn false;\n\t\t}\n\t\tif (y != other.y) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"Region [x=\");\n\t\tbuilder.append(x);\n\t\tbuilder.append(\", y=\");\n\t\tbuilder.append(y);\n\t\tbuilder.append(\", width=\");\n\t\tbuilder.append(width);\n\t\tbuilder.append(\", height=\");\n\t\tbuilder.append(height);\n\t\tbuilder.append(\"]\");\n\t\treturn builder.toString();\n\t}\n\n}",
"public class Render implements IRender {\n\n\tprotected boolean pseudoCanvas;\n\n\t@Override\n\tpublic IContextBuilder newBuilder() {\n\t\treturn ContextBuilder.newBuilder();\n\t}\n\n\t@Override\n\tpublic ICanvas render(IContext context) {\n\t\tfinal ICanvas canvas;\n\t\tif (pseudoCanvas) {\n\t\t\tcanvas = new PseudoCanvas(context.getWidth(), context.getHeight());\n\t\t} else {\n\t\t\tcanvas = new Canvas(context.getWidth(), context.getHeight());\n\t\t}\n\t\tfor (ILayer layer : context.getLayers()) {\n\t\t\tIRegion region = layer.getRegion();\n\t\t\tICanvas layerCanvas = new Canvas(region.getWidth(), region.getHeight());\n\t\t\tfor (IElement element : layer.getElements()) {\n\t\t\t\telement.draw(layerCanvas, context);\n\t\t\t}\n\t\t\tdrawOver(canvas, layerCanvas, layer, region);\n\t\t}\n\t\treturn canvas;\n\t}\n\n\tprotected void drawOver(ICanvas c1, ICanvas c2, ILayer layer, IRegion region) {\n\t\tboolean opacity = layer.isOpacity();\n\t\tfor (int c1x = region.getX(); c1x < region.getX() + region.getWidth(); c1x++) {\n\t\t\tfor (int c1y = region.getY(); c1y < region.getY() + region.getHeight(); c1y++) {\n\t\t\t\tint c2x = c1x - region.getX();\n\t\t\t\tint c2y = c1y - region.getY();\n\t\t\t\tif (opacity || c2.isCharDrawed(c2x, c2y)) {\n\t\t\t\t\tchar c = c2.getChar(c2x, c2y);\n\t\t\t\t\tc1.draw(c1x, c1y, c);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isPseudoCanvas() {\n\t\treturn pseudoCanvas;\n\t}\n\n\t@Override\n\tpublic void setPseudoCanvas(boolean pseudoCanvas) {\n\t\tthis.pseudoCanvas = pseudoCanvas;\n\t}\n}",
"public interface ICanvas {\n\n\t/**\n\t * Final version of text with all drawed elements. Every {@code \\0} will be replaced with {@code \\s} symbol.\n\t *\n\t * @return\n\t */\n\tString getText();\n\n\t/**\n\t * Height of canvas.\n\t *\n\t * @return\n\t */\n\tint getHeight();\n\n\t/**\n\t * Width of canvas.\n\t *\n\t * @return\n\t */\n\tint getWidth();\n\n\t/**\n\t * Draw char in a particular position. Coordinates {@code x} and {@code y} may be any, canvas will draw only text\n\t * which gets in his region. {@code c} can contains line break.\n\t *\n\t * @param x\n\t * @param y\n\t * @param c\n\t */\n\tvoid draw(int x, int y, char c);\n\n\t/**\n\t * Draw char {@code count} times starting from {@code x} and {@code y}. Coordinates {@code x} and {@code y} may be\n\t * any, canvas will draw only text which gets in his region. {@code c} can contains line break.\n\t *\n\t * @param x\n\t * @param y\n\t * @param c\n\t * @param count\n\t */\n\tvoid draw(int x, int y, char c, int count);\n\n\t/**\n\t * Draw string in a particular position. Coordinates {@code x} and {@code y} may be any, canvas will draw only text\n\t * which gets in his region. {@code s} can contains line breaks.\n\t *\n\t * @param x\n\t * @param y\n\t * @param s\n\t */\n\tvoid draw(int x, int y, String s);\n\n\t/**\n\t * Draw string {@code count} times starting from {@code x} and {@code y}. Coordinates {@code x} and {@code y} may be\n\t * any, canvas will draw only text which gets in his region. {@code s} can contains line breaks.\n\t *\n\t * @param x\n\t * @param y\n\t * @param s\n\t */\n\tvoid draw(int x, int y, String s, int count);\n\n\t/**\n\t * Clear all region of canvas and fill it with {@code \\0} symbols.\n\t */\n\tvoid clear();\n\n\t/**\n\t * Gets char at a particular position. After creating canvas contains only {@code \\0} symbols and line breaks\n\t * {@code \\n}. If coordinates do not gets in a canvas region {@code \\0} will be returned.\n\t *\n\t * @param x\n\t * @param y\n\t * @return\n\t */\n\tchar getChar(int x, int y);\n\n\t/**\n\t * Set char at a particular position.\n\t *\n\t * @param x\n\t * @param y\n\t * @return previous value\n\t */\n\tchar setChar(int x, int y, char c);\n\n\t/**\n\t * Return {@code true} if any char except {@code \\0} was drawed in this position.\n\t *\n\t * @param x\n\t * @param y\n\t * @return\n\t */\n\tboolean isCharDrawed(int x, int y);\n\n\t/**\n\t * Returns a canvas whose value is this canvas, with any leading and trailing {@code \\s} and {@code \\0} symbols\n\t * removed.\n\t *\n\t * @return\n\t */\n\tICanvas trim();\n\n\t/**\n\t * Returns a canvas whose value is this canvas, with any leading and trailing whitespace {@code \\s} removed.\n\t *\n\t * @return\n\t */\n\tICanvas trimSpaces();\n\n\t/**\n\t * Returns a canvas whose value is this canvas, with any leading and trailing {@code \\0} symbol removed.\n\t *\n\t * @return\n\t */\n\tICanvas trimNulls();\n\n\t/**\n\t * Returns a canvas whose value is this canvas, with any leading and trailing {@code trimChar} symbol removed.\n\t *\n\t * @return\n\t */\n\tICanvas trim(char trimChar);\n\n\t/**\n\t * Returns a {@code ICanvas} that is a subcanvas of this canvas.\n\t *\n\t * @param region\n\t * @return\n\t */\n\tICanvas subCanvas(IRegion region);\n\n}",
"public interface IContextBuilder {\n\n\t/**\n\t * Build context.\n\t *\n\t * @return\n\t */\n\tIContext build();\n\n\t/**\n\t * Width of context.\n\t *\n\t * @return\n\t */\n\tIContextBuilder width(int width);\n\n\t/**\n\t * Height of context.\n\t *\n\t * @return\n\t */\n\tIContextBuilder height(int height);\n\n\t/**\n\t * Create new layer and add him to context in a context region {@code (0, 0, width, height)}.\n\t *\n\t * @return\n\t */\n\tIContextBuilder layer();\n\n\t/**\n\t * Create new layer and add him to context in a specific region.\n\t *\n\t * @param region\n\t * @return\n\t */\n\tIContextBuilder layer(IRegion region);\n\n\t/**\n\t * Create new layer and add him to context in a specific position.\n\t *\n\t * @param x\n\t * @param y\n\t * @param width\n\t * @param height\n\t * @return\n\t */\n\tIContextBuilder layer(int x, int y, int width, int height);\n\n\t/**\n\t * Create new layer and add layer to context in a context region {@code (0, 0, width, height)}.\n\t *\n\t * @return\n\t */\n\tIContextBuilder layer(IElement... elements);\n\n\t/**\n\t * Create new layer with {@code elements} and add layer to context in a specific region.\n\t *\n\t * @param region\n\t * @return\n\t */\n\tIContextBuilder layer(IRegion region, IElement... elements);\n\n\t/**\n\t * Create new layer with {@code elements} and add layer to context in a specific position.\n\t *\n\t * @param x\n\t * @param y\n\t * @param width\n\t * @param height\n\t * @param elements\n\t * @return\n\t */\n\tIContextBuilder layer(int x, int y, int width, int height, IElement... elements);\n\n\t/**\n\t * Create new layer with {@code elements} and add layer to context in a context region\n\t * {@code (0, 0, width, height)}.\n\t *\n\t * @return\n\t */\n\tIContextBuilder layer(List<IElement> elements);\n\n\t/**\n\t * Create new layer with {@code elements} and add layer to context in a specific region.\n\t *\n\t * @param region\n\t * @return\n\t */\n\tIContextBuilder layer(IRegion region, List<IElement> elements);\n\n\t/**\n\t * Create new layer with {@code elements} and add layer to context in a specific position.\n\t *\n\t * @param x\n\t * @param y\n\t * @param width\n\t * @param height\n\t * @param elements\n\t * @return\n\t */\n\tIContextBuilder layer(int x, int y, int width, int height, List<IElement> elements);\n\n\n\t/**\n\t * Opacity of last created layer. {@code False} by default.\n\t *\n\t * @param opacity\n\t * @return\n\t */\n\tIContextBuilder opacity(boolean opacity);\n\n\t/**\n\t * Add {@code element} to last created layer. New layer will be created, if layers count is 0.\n\t *\n\t * @param element\n\t * @return\n\t */\n\tIContextBuilder element(IElement element);\n\n\t/**\n\t * Add {@code elements} to last created layer. New layer will be created, if layers count is 0.\n\t *\n\t * @param elements\n\t * @return\n\t */\n\tIContextBuilder elements(IElement... elements);\n\n\t/**\n\t * Add {@code elements} to last created layer. New layer will be created, if layers count is 0.\n\t *\n\t * @param elements\n\t * @return\n\t */\n\tIContextBuilder elements(List<IElement> elements);\n\n}",
"public interface IRender {\n\n\t/**\n\t * New context builder.\n\t *\n\t * @return\n\t */\n\tIContextBuilder newBuilder();\n\n\t/**\n\t * Render context to canvas.\n\t *\n\t * @param context\n\t * @return\n\t */\n\tICanvas render(IContext context);\n\n\tboolean isPseudoCanvas();\n\n\tvoid setPseudoCanvas(boolean pseudoCanvas);\n}",
"public class Plot extends AbstractPlotObject<Plot> {\n\n\tpublic Plot(List<IPlotPoint> points, IRegion region) {\n\t\tsuper(points, region);\n\t}\n\n\t@Override\n\tpublic IPoint draw(ICanvas canvas, IContext context) {\n\t\tint width = region.getWidth();\n\t\tint height = region.getHeight();\n\t\tint startX = region.getX();\n\t\tint startY = region.getY();\n\t\t@SuppressWarnings(\"unused\")\n\t\tint lastX = startX + width - 1;\n\t\tint lastY = startY + height - 1;\n\n\t\tAxisLabels labels = context.lookupTyped(AxisLabels.class, getTypedId());\n\t\tif (labels != null) {\n\t\t\tstartX += labels.getLabelsYWidth();\n\t\t\twidth -= labels.getLabelsYWidth();\n\t\t\tlastY -= 1;\n\t\t\theight -= 1;\n\t\t}\n\n\t\tAxis axis = context.lookupTyped(Axis.class, getTypedId());\n\t\tif (axis != null) {\n\t\t\tstartX += 1;\n\t\t\twidth -= 1;\n\t\t\tlastY -= 1;\n\t\t\theight -= 1;\n\t\t}\n\n\t\tList<IPlotPoint> normalized = plotPoints.normalize(width - 1, height - 1);\n\t\tfor (IPlotPoint plotPoint : normalized) {\n\t\t\tint x = (int) (startX + plotPoint.getX());\n\t\t\tint y = (int) (lastY - plotPoint.getY());\n\t\t\tcanvas.draw(x, y, \"*\");\n\t\t}\n\n\t\treturn anchorPoint;\n\t}\n\n}",
"public interface IPlotPoint {\n\n\tdouble getX();\n\n\tdouble getY();\n\n}",
"public class PlotPoint implements IPlotPoint {\n\n\tprotected double x;\n\tprotected double y;\n\n\tpublic PlotPoint(double x, double y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\t@Override\n\tpublic double getX() {\n\t\treturn x;\n\t}\n\n\t@Override\n\tpublic double getY() {\n\t\treturn y;\n\t}\n\n}"
] | import com.indvd00m.ascii.render.Region;
import com.indvd00m.ascii.render.Render;
import com.indvd00m.ascii.render.api.ICanvas;
import com.indvd00m.ascii.render.api.IContextBuilder;
import com.indvd00m.ascii.render.api.IRender;
import com.indvd00m.ascii.render.elements.plot.Plot;
import com.indvd00m.ascii.render.elements.plot.api.IPlotPoint;
import com.indvd00m.ascii.render.elements.plot.misc.PlotPoint;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static org.junit.Assert.assertEquals; | package com.indvd00m.ascii.render.tests.plot;
/**
* @author indvd00m (gotoindvdum[at]gmail[dot]com)
* @since 1.0.0
*/
public class TestPlot {
@Before
public void setUpLocale() throws Exception {
Locale.setDefault(Locale.ENGLISH);
}
@Test
public void test01() {
List<IPlotPoint> points = new ArrayList<IPlotPoint>();
for (int degree = 0; degree <= 360; degree++) {
double val = Math.sin(Math.toRadians(degree));
IPlotPoint plotPoint = new PlotPoint(degree, val);
points.add(plotPoint);
}
IRender render = new Render(); | IContextBuilder builder = render.newBuilder(); | 3 |
flapdoodle-oss/de.flapdoodle.embed.process | src/main/java/de/flapdoodle/embed/process/store/UrlConnectionDownloader.java | [
"@Value.Immutable\npublic interface DownloadConfig {\n\t\n\tDistributionDownloadPath getDownloadPath();\n\t\n\tProgressListener getProgressListener();\n\n\tDirectory getArtifactStorePath();\n\t\n\tTempNaming getFileNaming();\n\n\tString getDownloadPrefix();\n\n\tString getUserAgent();\n\n\tOptional<String> getAuthorization();\n\n\tPackageResolver getPackageResolver();\n\n\t@Default\n\tdefault TimeoutConfig getTimeoutConfig() {\n\t\treturn TimeoutConfig.defaults();\n\t}\n\t\n\tOptional<ProxyFactory> proxyFactory();\n\n\tpublic static ImmutableDownloadConfig.Builder builder() {\n\t\treturn ImmutableDownloadConfig.builder();\n\t}\n}",
"public interface ProxyFactory {\n\n\tProxy createProxy();\n}",
"@Value.Immutable\npublic interface TimeoutConfig {\n\t\n\tint getConnectionTimeout();\n\t\n\tint getReadTimeout();\n\n\tstatic ImmutableTimeoutConfig defaults() {\n\t\treturn ImmutableTimeoutConfig.builder()\n\t\t\t\t.connectionTimeout(10000)\n\t\t\t\t.readTimeout(10000)\n\t\t\t\t.build();\n\t}\n\t\n\tstatic ImmutableTimeoutConfig.Builder builder() {\n\t\treturn ImmutableTimeoutConfig.builder();\n\t}\n}",
"@Value.Immutable\npublic abstract class Distribution {\n\n\t@Parameter\n\tpublic abstract Version version();\n\n\t@Parameter\n\tpublic abstract Platform platform();\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"\" + version() + \":\" + platform();\n\t}\n\n\tpublic static Distribution detectFor(Version version) {\n\t\treturn of(version, Platform.detect());\n\t}\n\n\tpublic static Distribution of(Version version, Platform platform) {\n\t\treturn ImmutableDistribution.of(version, platform);\n\t}\n}",
"public class PropertyOrPlatformTempDir extends PlatformTempDir {\n\n\tprivate static final PropertyOrPlatformTempDir _instance=new PropertyOrPlatformTempDir();\n\n\t@Override\n\tpublic File asFile() {\n\t\tString customTempDir = System.getProperty(\"de.flapdoodle.embed.io.tmpdir\");\n\t\tif (customTempDir!=null) {\n\t\t\treturn new File(customTempDir);\n\t\t}\n\t\treturn super.asFile();\n\t}\n\n\tpublic static Directory defaultInstance() {\n\t\treturn _instance;\n\t}\n}",
"public class Files {\n\n\tprivate static Logger logger = LoggerFactory.getLogger(Files.class);\n\tprivate static final int BYTE_BUFFER_LENGTH = 1024 * 16;\n\t/**\n\t * Instance to force loading {@link DeleteDirVisitor} class to avoid\n\t * {@link NoClassDefFoundError} in shutdown hook.\n\t */\n\tprivate static final SimpleFileVisitor<Path> DELETE_DIR_VISITOR = new DeleteDirVisitor();\n\n\tprivate Files() {\n\n\t}\n\n\t@Deprecated\n\tpublic static File createTempFile(String tempFileName) throws IOException {\n\t\treturn createTempFile(PropertyOrPlatformTempDir.defaultInstance(), tempFileName);\n\t}\n\n\tpublic static File createTempFile(Directory directory, String tempFileName) throws IOException {\n\t\tFile tempDir = directory.asFile();\n\t\treturn createTempFile(tempDir, tempFileName);\n\t}\n\n\tpublic static File createTempFile(File tempDir, String tempFileName) throws IOException {\n\t\tFile tempFile = fileOf(tempDir, tempFileName);\n\t\tcreateOrCheckDir(tempFile.getParentFile());\n\t\tif (!tempFile.createNewFile())\n\t\t\tthrow new FileAlreadyExistsException(\"could not create\",tempFile);\n\t\treturn tempFile;\n\t}\n\n\tpublic static File createOrCheckDir(String dir) throws IOException {\n\t\tFile tempFile = new File(dir);\n\t\treturn createOrCheckDir(tempFile);\n\t}\n\n\tpublic static File createOrCheckDir(File dir) throws IOException {\n\t\tif ((dir.exists()) && (dir.isDirectory()))\n\t\t\treturn dir;\n\t\treturn createDir(dir);\n\t}\n\n\tpublic static File createOrCheckUserDir(String prefix) throws IOException {\n\t\tFile tempDir = new File(System.getProperty(\"user.home\"));\n\t\tFile tempFile = new File(tempDir, prefix);\n\t\treturn createOrCheckDir(tempFile);\n\t}\n\n\t@Deprecated\n\tpublic static File createTempDir(String prefix) throws IOException {\n\t\treturn createTempDir(PropertyOrPlatformTempDir.defaultInstance(), prefix);\n\t}\n\n\tpublic static File createTempDir(Directory directory, String prefix) throws IOException {\n\t\tFile tempDir = directory.asFile();\n\t\treturn createTempDir(tempDir, prefix);\n\t}\n\n\tpublic static File createTempDir(File tempDir, String prefix) throws IOException {\n\t\tFile tempFile = new File(tempDir, prefix + \"-\" + UUID.randomUUID().toString());\n\t\treturn createDir(tempFile);\n\t}\n\n\tpublic static File createDir(File tempFile) throws IOException {\n\t\tif (!tempFile.mkdirs())\n\t\t\tthrow new IOException(\"could not create dirs: \" + tempFile);\n\t\treturn tempFile;\n\t}\n\n\tpublic static boolean forceDelete(final File fileOrDir) {\n\t\tboolean ret = false;\n\n\t\ttry {\n\t\t\tif ((fileOrDir != null) && (fileOrDir.exists())) {\n\t\t\t\tforceDelete(fileOrDir.toPath());\n\t\t\t\tlogger.debug(\"could delete {}\", fileOrDir);\n\t\t\t\tret = true;\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tlogger.warn(\"could not delete {}. Will try to delete it again when program exits.\", fileOrDir);\n\t\t\tFileCleaner.forceDeleteOnExit(fileOrDir);\n\t\t\tret = true;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Deletes a path from the filesystem\n\t *\n\t * If the path is a directory its contents\n\t * will be recursively deleted before it itself\n\t * is deleted.\n\t *\n\t * Note that removal of a directory is not an atomic-operation\n\t * and so if an error occurs during removal, some of the directories\n\t * descendants may have already been removed\n\t *\n\t * @throws IOException if an error occurs whilst removing a file or directory\n\t */\n\tpublic static void forceDelete(final Path path) throws IOException {\n\t\tif (!java.nio.file.Files.isDirectory(path)) {\n\t\t\tjava.nio.file.Files.delete(path);\n\t\t} else {\n\t\t\tjava.nio.file.Files.walkFileTree(path, DeleteDirVisitor.getInstance());\n\t\t}\n\t}\n\tprivate static class DeleteDirVisitor extends SimpleFileVisitor<Path> {\n\t\tpublic static SimpleFileVisitor<Path> getInstance() {\n\t\t\treturn DELETE_DIR_VISITOR;\n\t\t}\n\n\t\t@Override\n\t\tpublic FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {\n\t\t\tjava.nio.file.Files.deleteIfExists(file);\n\t\t\treturn FileVisitResult.CONTINUE;\n\t\t}\n\n\t\t@Override\n\t\tpublic FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {\n\t\t\tif (exc != null) {\n\t\t\t\tthrow exc;\n\t\t\t}\n\n\t\t\tjava.nio.file.Files.deleteIfExists(dir);\n\t\t\treturn FileVisitResult.CONTINUE;\n\t\t}\n\t}\n\n\tpublic static void write(final InputStream in, long size, final File output)\n\t\t\tthrows IOException {\n\t\ttry (final OutputStream out = java.nio.file.Files.newOutputStream(output.toPath())) {\n\t\t\tfinal byte[] buf = new byte[BYTE_BUFFER_LENGTH];\n\t\t\tint read;\n\t\t\tint left = buf.length;\n\t\t\tif (left > size) {\n\t\t\t\tleft = (int) size;\n\t\t\t}\n\t\t\twhile ((read = in.read(buf, 0, left)) > 0) {\n\n\t\t\t\tout.write(buf, 0, read);\n\n\t\t\t\tsize = size - read;\n\t\t\t\tif (left > size)\n\t\t\t\t\tleft = (int) size;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void write(final InputStream in, final File output) throws IOException {\n\t\tjava.nio.file.Files.copy(in, output.toPath());\n\t}\n\n\tpublic static void write(final String content, final File output) throws IOException {\n\t\tjava.nio.file.Files.write(output.toPath(), content.getBytes());\n\t}\n\n\tpublic static void moveFile(final File source, final File destination) throws IOException {\n java.nio.file.Files.move(source.toPath(), destination.toPath());\n\t}\n\n\tpublic static File fileOf(File base, File relative) {\n\t\treturn base.toPath().resolve(relative.toPath()).toFile();\n\t}\n\n\tpublic static File fileOf(File base, String relative) {\n\t\treturn base.toPath().resolve(relative).toFile();\n\t}\n\n\tpublic static boolean sameContent(Path source, Path destination) throws IOException {\n\t\tif (java.nio.file.Files.exists(source) && java.nio.file.Files.exists(destination)) {\n\t\t\tif (java.nio.file.Files.isReadable(source) && java.nio.file.Files.isReadable(destination)) {\n\t\t\t\ttry (BufferedInputStream fis1 = new BufferedInputStream(new FileInputStream(source.toFile()));\n\t\t\t\t\tBufferedInputStream fis2 = new BufferedInputStream(new FileInputStream(destination.toFile()))) {\n\n\t\t\t\t\tint chl;\n\t\t\t\t\tint chr;\n\t\t\t\t\tdo {\n\t\t\t\t\t\tchl = fis1.read();\n\t\t\t\t\t\tchr = fis2.read();\n\t\t\t\t\t\tif (chl != chr) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (chl != -1);\n\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}",
"public interface ProgressListener {\n\n\tvoid progress(String label, int percent);\n\n\tvoid done(String label);\n\n\tvoid start(String label);\n\n\tvoid info(String label, String message);\n}"
] | import java.net.URL;
import java.net.URLConnection;
import java.util.Optional;
import de.flapdoodle.embed.process.config.store.DownloadConfig;
import de.flapdoodle.embed.process.config.store.ProxyFactory;
import de.flapdoodle.embed.process.config.store.TimeoutConfig;
import de.flapdoodle.embed.process.distribution.Distribution;
import de.flapdoodle.embed.process.io.directories.PropertyOrPlatformTempDir;
import de.flapdoodle.embed.process.io.file.Files;
import de.flapdoodle.embed.process.io.progress.ProgressListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy; | /**
* Copyright (C) 2011
* Michael Mosmann <[email protected]>
* Martin Jöhren <[email protected]>
*
* with contributions from
* konstantin-ba@github,
Archimedes Trajano (trajano@github),
Kevin D. Keck (kdkeck@github),
Ben McCann (benmccann@github)
*
* 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 de.flapdoodle.embed.process.store;
/**
* Class for downloading runtime
*/
public class UrlConnectionDownloader implements Downloader {
private static final int DEFAULT_CONTENT_LENGTH = 20 * 1024 * 1024;
private static final int BUFFER_LENGTH = 1024 * 8 * 8;
private static final int READ_COUNT_MULTIPLIER = 100;
@Override
public String getDownloadUrl(DownloadConfig runtime, Distribution distribution) {
return runtime.getDownloadPath().getPath(distribution) + runtime.getPackageResolver().packageFor(distribution).archivePath();
}
@Override
public File download(DownloadConfig downloadConfig, Distribution distribution) throws IOException {
String progressLabel = "Download " + distribution;
ProgressListener progress = downloadConfig.getProgressListener();
progress.start(progressLabel);
File ret = Files.createTempFile(PropertyOrPlatformTempDir.defaultInstance(), downloadConfig.getFileNaming()
.nameFor(downloadConfig.getDownloadPrefix(), "." + downloadConfig.getPackageResolver().packageFor(distribution).archiveType()));
if (ret.canWrite()) {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(ret));
InputStreamAndLength downloadStreamAndLength = downloadInputStream(downloadConfig, distribution);
long length = downloadStreamAndLength.contentLength();
InputStream downloadStream = downloadStreamAndLength.downloadStream();
progress.info(progressLabel, "DownloadSize: " + length);
if (length == -1) length = DEFAULT_CONTENT_LENGTH;
long downloadStartedAt = System.currentTimeMillis();
try {
BufferedInputStream bis = new BufferedInputStream(downloadStream);
byte[] buf = new byte[BUFFER_LENGTH];
int read = 0;
long readCount = 0;
while ((read = bis.read(buf)) != -1) {
bos.write(buf, 0, read);
readCount = readCount + read;
if (readCount > length) length = readCount;
progress.progress(progressLabel, (int) (readCount * READ_COUNT_MULTIPLIER / length));
}
progress.info(progressLabel, "downloaded with " + downloadSpeed(downloadStartedAt,length));
} finally {
downloadStream.close();
bos.flush();
bos.close();
}
} else {
throw new IOException("Can not write " + ret);
}
progress.done(progressLabel);
return ret;
}
private InputStreamAndLength downloadInputStream(DownloadConfig downloadConfig, Distribution distribution)
throws IOException {
URL url = new URL(getDownloadUrl(downloadConfig, distribution));
Optional<Proxy> proxy = downloadConfig.proxyFactory().map(ProxyFactory::createProxy);
try {
URLConnection openConnection;
if (proxy.isPresent()) {
openConnection = url.openConnection(proxy.get());
} else {
openConnection = url.openConnection();
}
openConnection.setRequestProperty("User-Agent",downloadConfig.getUserAgent());
if (downloadConfig.getAuthorization().isPresent()) {
openConnection.setRequestProperty("Authorization", downloadConfig.getAuthorization().get());
}
| TimeoutConfig timeoutConfig = downloadConfig.getTimeoutConfig(); | 2 |
osglworks/java-tool | src/test/java/org/osgl/util/MimeTypeTest.java | [
"public abstract class TestBase extends osgl.ut.TestBase {\n\n protected static void run(Class<? extends TestBase> cls) {\n new JUnitCore().run(cls);\n }\n \n protected static void println(String tmpl, Object... args) {\n System.out.println(String.format(tmpl, args));\n }\n\n protected static String newRandStr() {\n return S.random(new Random().nextInt(30) + 15);\n }\n\n protected String loadFileAsString(String path) {\n return IO.read(getClass().getClassLoader().getResource(path)).toString();\n }\n}",
"public enum Trait {\n archive, audio, css, csv, doc, docx, excel, image, javascript, json, pdf,\n powerpoint, ppt, pptx, problem, text, video, word, xls, xlsx, xml, yaml;\n public boolean test(MimeType mimeType) {\n return mimeType.test(this);\n }\n}",
"public enum Trait {\n archive, audio, css, csv, doc, docx, excel, image, javascript, json, pdf,\n powerpoint, ppt, pptx, problem, text, video, word, xls, xlsx, xml, yaml;\n public boolean test(MimeType mimeType) {\n return mimeType.test(this);\n }\n}",
"public static MimeType findByContentType(String contentType) {\n return indexByContentType.get(contentType.trim().toLowerCase());\n}",
"@Deprecated\npublic static MimeType findByFileExtension(String fileExtension) {\n return indexByName.get(fileExtension.trim().toLowerCase());\n}"
] | import org.junit.Test;
import org.osgl.TestBase;
import org.osgl.util.MimeType.Trait;
import static org.osgl.util.MimeType.Trait.*;
import static org.osgl.util.MimeType.findByContentType;
import static org.osgl.util.MimeType.findByFileExtension; | package org.osgl.util;
/*-
* #%L
* Java Tool
* %%
* Copyright (C) 2014 - 2018 OSGL (Open Source General Library)
* %%
* 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.
* #L%
*/
public class MimeTypeTest extends TestBase {
@Test
public void test() { | MimeType mimeType = findByFileExtension("pdf"); | 4 |
alda-lang/alda-client-java | src/alda/repl/commands/ReplDownUp.java | [
"public class AldaScore {\n @SerializedName(\"chord-mode\")\n public Boolean chordMode;\n @SerializedName(\"current-instruments\")\n public Set<String> currentInstruments;\n\n public Map<String, Set<String>> nicknames;\n\n /**\n * Returns the current instruments if possible\n * @return null if not possible, string array with current instruments if possible.\n */\n public Set<String> currentInstruments() {\n if (this.currentInstruments != null &&\n this.currentInstruments.size() > 0) {\n return this.currentInstruments;\n }\n return null;\n }\n}",
"public class AldaServer extends AldaProcess {\n private static final int PING_TIMEOUT = 100; // ms\n private static final int PING_RETRIES = 5;\n private static final int STARTUP_RETRY_INTERVAL = 250; // ms\n private static final int SHUTDOWN_RETRY_INTERVAL = 250; // ms\n private static final int STATUS_RETRY_INTERVAL = 200; // ms\n private static final int STATUS_RETRIES = 10;\n private static final int JOB_STATUS_INTERVAL = 250; // ms\n\n // Relevant to playing input from the REPL.\n private static final int BUSY_WORKER_TIMEOUT = 10000; // ms\n private static final int BUSY_WORKER_RETRY_INTERVAL = 500; // ms\n\n public AldaServer(AldaServerOptions opts) {\n host = normalizeHost(opts.host);\n port = opts.port;\n timeout = opts.timeout;\n verbose = opts.verbose;\n quiet = opts.quiet;\n noColor = opts.noColor;\n\n if (!noColor) AnsiConsole.systemInstall();\n }\n\n // Calculate the number of retries before giving up, based on a fixed retry\n // interval and the desired overall timeout in seconds.\n private int calculateRetries(int timeout, int interval) {\n int retriesPerSecond = 1000 / interval;\n return timeout * retriesPerSecond;\n }\n\n private boolean ping(int timeout, int retries) throws NoResponseException {\n AldaRequest req = new AldaRequest(this.host, this.port);\n req.command = \"ping\";\n AldaResponse res = req.send(timeout, retries);\n return res.success;\n }\n\n public boolean checkForConnection(int timeout, int retries) {\n try {\n return ping(timeout, retries);\n } catch (NoResponseException e) {\n return false;\n }\n }\n\n public boolean checkForConnection() {\n return checkForConnection(PING_TIMEOUT, PING_RETRIES);\n }\n\n // Waits until the process is confirmed to be up, or we reach the timeout.\n //\n // Throws a NoResponseException if the timeout is reached.\n public void waitForConnection() throws NoResponseException {\n int retries = calculateRetries(timeout, STARTUP_RETRY_INTERVAL);\n\n if (!checkForConnection(STARTUP_RETRY_INTERVAL, retries)) {\n throw new NoResponseException(\n \"Timed out waiting for response from the server.\"\n );\n }\n }\n\n // Waits until the process is confirmed to be down, i.e. there is no response\n // to \"ping,\" OR, there is a response to \"ping,\" but the response indicates\n // \"success\": false.\n //\n // Throws a NoResponseException if the process is still pingable after the\n // timeout.\n public void waitForLackOfConnection() throws NoResponseException {\n int retries = calculateRetries(timeout, SHUTDOWN_RETRY_INTERVAL);\n\n while (retries >= 0) {\n try {\n if (!ping(SHUTDOWN_RETRY_INTERVAL, 0)) return;\n } catch (NoResponseException e) {\n return;\n }\n\n Util.sleep(SHUTDOWN_RETRY_INTERVAL);\n retries--;\n }\n\n throw new NoResponseException(\n \"Timed out waiting for the server to shut down.\"\n );\n }\n\n private static String normalizeHost(String host) {\n // trim leading/trailing whitespace and trailing \"/\"\n host = host.trim().replaceAll(\"/$\", \"\");\n // prepend tcp:// if not already present\n if (!(host.startsWith(\"tcp://\"))) {\n host = \"tcp://\" + host;\n }\n return host;\n }\n\n private void assertNotRemoteHost() throws InvalidOptionsException {\n String hostWithoutProtocol = host.replaceAll(\"tcp://\", \"\");\n\n if (!hostWithoutProtocol.equals(\"localhost\")) {\n throw new InvalidOptionsException(\n \"Alda servers cannot be started remotely.\");\n }\n }\n\n public void setQuiet(boolean quiet) {\n this.quiet = quiet;\n }\n\n public void msg(String message) {\n if (quiet)\n return;\n\n String hostWithoutProtocol = host.replaceAll(\"tcp://\", \"\");\n\n String prefix;\n if (hostWithoutProtocol.equals(\"localhost\")) {\n prefix = \"\";\n } else {\n prefix = hostWithoutProtocol + \":\";\n }\n\n prefix += Integer.toString(port);\n\n if (noColor) {\n prefix = String.format(\"[%s] \", prefix);\n } else {\n prefix = String.format(\"[%s] \", ansi().fg(BLUE)\n .a(prefix)\n .reset()\n .toString());\n }\n\n System.out.println(prefix + message);\n }\n\n public void error(String message) {\n String prefix;\n if (noColor) {\n prefix = \"ERROR \";\n } else {\n prefix = ansi().fg(RED).a(\"ERROR \").reset().toString();\n }\n\n // save and restore quiet value to print out errors\n boolean oldQuiet = quiet;\n quiet = false;\n msg(prefix + message);\n quiet = oldQuiet;\n }\n\n private final String CHECKMARK = \"\\u2713\";\n private final String X = \"\\u2717\";\n\n private void announceReady() {\n if (noColor) {\n msg(\"Ready \" + CHECKMARK);\n } else {\n msg(ansi().a(\"Ready \").fg(GREEN).a(CHECKMARK).reset().toString());\n }\n }\n\n private void announceServerUp() {\n if (noColor) {\n msg(\"Server up \" + CHECKMARK);\n } else {\n msg(ansi().a(\"Server up \").fg(GREEN).a(CHECKMARK).reset().toString());\n }\n }\n\n private void announceServerDown(boolean isGood) {\n Color color = isGood ? GREEN : RED;\n String glyph = isGood ? CHECKMARK : X;\n if (noColor) {\n msg(\"Server down \" + glyph);\n } else {\n msg(ansi().a(\"Server down \").fg(color).a(glyph).reset().toString());\n }\n }\n\n private void announceServerDown() {\n announceServerDown(false);\n }\n\n public void upBg(int numberOfWorkers)\n throws InvalidOptionsException, NoResponseException, AlreadyUpException,\n SystemException {\n assertNotRemoteHost();\n\n boolean serverAlreadyUp = checkForConnection();\n if (serverAlreadyUp) {\n throw new AlreadyUpException(\"Server already up.\");\n }\n\n boolean serverAlreadyTryingToStart;\n try {\n serverAlreadyTryingToStart = SystemUtils.IS_OS_UNIX &&\n AldaClient.checkForExistingServer(port);\n } catch (SystemException e) {\n System.out.println(\"WARNING: Unable to detect whether or not there is \" +\n \"already a server running on that port.\");\n serverAlreadyTryingToStart = false;\n }\n\n if (serverAlreadyTryingToStart) {\n throw new AlreadyUpException(\n \"There is already a server trying to start on this port. Please be \" +\n \"patient -- this can take a while.\"\n );\n }\n\n Object[] opts = {\"--host\", host,\n \"--port\", Integer.toString(port),\n \"--workers\", Integer.toString(numberOfWorkers),\n \"--alda-fingerprint\"};\n\n try {\n Util.forkProgram(Util.conj(opts, \"server\"));\n msg(\"Starting Alda server...\");\n waitForConnection();\n announceServerUp();\n } catch (URISyntaxException e) {\n throw new SystemException(\n String.format(\"Unable to fork '%s' into the background.\"), e\n );\n } catch (IOException e) {\n throw new SystemException(\"Unable to fork a background process.\", e);\n }\n\n msg(\"Starting worker processes...\");\n\n int workersAvailable = 0;\n while (workersAvailable == 0) {\n Util.sleep(STARTUP_RETRY_INTERVAL);\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"status\";\n AldaResponse res = req.send();\n if (res.body.contains(\"Server up\")) {\n Matcher a = Pattern.compile(\"(\\\\d+)/\\\\d+ workers available\")\n .matcher(res.body);\n if (a.find()) {\n workersAvailable = Integer.parseInt(a.group(1));\n }\n }\n }\n\n announceReady();\n }\n\n public void upFg(int numberOfWorkers) throws InvalidOptionsException {\n assertNotRemoteHost();\n\n Object[] args = {numberOfWorkers, port, verbose};\n\n Util.callClojureFn(\"alda.server/start-server!\", args);\n }\n\n public void down() throws NoResponseException {\n boolean serverAlreadyDown = !checkForConnection();\n if (serverAlreadyDown) {\n msg(\"Server already down.\");\n return;\n }\n\n msg(\"Stopping Alda server...\");\n\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"stop-server\";\n\n try {\n AldaResponse res = req.send();\n if (res.success) {\n announceServerDown(true);\n } else {\n throw new NoResponseException(\"Failed to stop server.\");\n }\n } catch (NoResponseException e) {\n announceServerDown(true);\n }\n }\n\n public void downUp(int numberOfWorkers)\n throws NoResponseException, AlreadyUpException, InvalidOptionsException,\n SystemException {\n down();\n\n waitForLackOfConnection();\n // The process can still hang around sometimes, causing upBg to fail if we\n // try to do it too soon. Giving it a little extra time here as a buffer.\n Util.sleep(1000);\n\n System.out.println();\n upBg(numberOfWorkers);\n }\n\n public void status() {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"status\";\n\n try {\n AldaResponse res = req.send(STATUS_RETRY_INTERVAL, STATUS_RETRIES);\n if (!res.success) throw new UnsuccessfulException(res.body);\n msg(res.body);\n } catch (NoResponseException e) {\n announceServerDown();\n } catch (UnsuccessfulException e) {\n msg(\"Unable to report status.\");\n }\n }\n\n public void version() throws NoResponseException {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"version\";\n AldaResponse res = req.send();\n String serverVersion = res.body;\n\n msg(serverVersion);\n }\n\n public AldaResponse play(String code, String from, String to)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n return play(code, null, from, to);\n }\n\n /**\n * Tries to play a bit of alda code\n *\n * @param code The pimary code to play\n * @param history The history context to supplement code\n * @param from Time to play from\n * @param to Time to stop playing\n * @return The response from the play, with useful information.\n */\n public AldaResponse play(String code, String history, String from, String to)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"play\";\n req.body = code;\n req.options = new AldaRequestOptions();\n\n if (from != null) {\n req.options.from = from;\n }\n\n if (to != null) {\n req.options.to = to;\n }\n\n if (history != null) {\n req.options.history = history;\n }\n\n return awaitAsyncResponse(req);\n }\n\n public AldaResponse playFromRepl(String input, String history, String from,\n String to)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n int retries = BUSY_WORKER_TIMEOUT / BUSY_WORKER_RETRY_INTERVAL;\n return playFromRepl(input, history, from, to, retries);\n }\n\n public AldaResponse playFromRepl(String input, String history, String from,\n String to, int retries)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n // Placeholder exception; we should never see this get thrown.\n String msg = \"Unexpected error trying to play input from the Alda REPL.\";\n NoAvailableWorkerException error = new NoAvailableWorkerException(msg);\n\n // Retry until we get a NoAvailableWorkerException `retries` times.\n while (retries >= 0) {\n try {\n return play(input, history.toString(), from, to);\n } catch (NoAvailableWorkerException e) {\n error = e;\n Util.sleep(BUSY_WORKER_RETRY_INTERVAL);\n retries--;\n }\n }\n\n // Throw the most recent NoAvailableWorkerException before we ran out of\n // retries.\n throw error;\n }\n\n\n public AldaResponse jobStatus(byte[] workerAddress, String jobId)\n throws NoResponseException {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"job-status\";\n req.workerToUse = workerAddress;\n req.options = new AldaRequestOptions();\n req.options.jobId = jobId;\n return req.send();\n }\n\n public void stop() throws UnsuccessfulException {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"stop-playback\";\n\n try {\n AldaResponse res = req.send();\n if (!res.success) throw new UnsuccessfulException(res.body);\n msg(res.body);\n } catch (NoResponseException e) {\n announceServerDown();\n }\n }\n\n /**\n * Raw parsing function\n * @return Returns the result of the parse.\n */\n public String parseRaw(String code, String outputType)\n throws NoResponseException, ParseError {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"parse\";\n req.body = code;\n req.options = new AldaRequestOptions();\n req.options.output = outputType;\n AldaResponse res = req.send();\n\n if (!res.success) {\n throw new ParseError(res.body);\n }\n\n return res.body;\n }\n\n public void parse(String code, String outputType)\n throws NoResponseException, ParseError {\n String res = parseRaw(code, outputType);\n if (res != null) {\n System.out.println(res);\n }\n }\n\n public void parse(File file, String outputType)\n throws NoResponseException, ParseError, SystemException {\n String fileBody = Util.readFile(file);\n parse(fileBody, outputType);\n }\n\n public void displayInstruments() throws NoResponseException {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"instruments\";\n AldaResponse res = req.send();\n\n for (String instrument : res.instruments) {\n System.out.println(instrument);\n }\n }\n\n public AldaResponse export(String code, String outputFormat, String filename)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"export\";\n req.body = code;\n req.options = new AldaRequestOptions();\n req.options.filename = filename;\n\n return awaitAsyncResponse(req);\n }\n\n // Makes an initial request, then makes job status requests until the request\n // is done and returns the final status response.\n private AldaResponse awaitAsyncResponse(AldaRequest req)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n String jobId = UUID.randomUUID().toString();\n req.options.jobId = jobId;\n\n // The original request can have side effects (e.g. playing a score), so it\n // needs to be sent exactly once and not retried, otherwise the side effects\n // could happen multiple times.\n //\n // play requests are asynchronous; the response from the worker should be\n // immediate, and then in the code below, we repeatedly ask the worker for\n // status and send updates to the user until the status is \"playing.\"\n AldaResponse res = req.send(3000, 0);\n\n if (!res.success) {\n String noWorkersYetMsg = \"No worker processes are ready yet\";\n String workersBusyMsg = \"All worker processes are currently busy\";\n\n if (res.body.contains(noWorkersYetMsg) ||\n res.body.contains(workersBusyMsg)) {\n throw new NoAvailableWorkerException(res.body);\n } else {\n throw new UnsuccessfulException(res.body);\n }\n }\n\n if (res.workerAddress == null) {\n throw new UnsuccessfulException(\n \"No worker address included in response; unable to check for status.\"\n );\n }\n\n String status = \"requested\";\n\n while (true) {\n AldaResponse update = jobStatus(res.workerAddress, jobId);\n\n // Ensures that any update we process is for this score, and not a\n // previous one.\n if (!update.jobId.equals(jobId)) continue;\n\n // Bail out if there was some problem server-side.\n if (!update.success) throw new UnsuccessfulException(update.body);\n\n // Update the job status if it's different.\n if (!update.body.equals(status)) {\n status = update.body;\n switch (status) {\n case \"parsing\": msg(\"Parsing/evaluating...\"); break;\n case \"playing\": msg(\"Playing...\"); break;\n case \"exporting\": msg(\"Exporting...\"); break;\n // In rare cases (i.e. when the score is really short), the worker can\n // be done already.\n case \"success\": msg(\"Done.\"); break;\n default: msg(status);\n }\n }\n\n // If the job is still pending, pause and then keep looping.\n if (update.pending) {\n Util.sleep(JOB_STATUS_INTERVAL);\n } else {\n // We succeeded!\n return update;\n }\n }\n }\n}",
"public class AlreadyUpException extends AldaException {\n\n public AlreadyUpException(String msg) {\n super(msg);\n }\n\n @Override\n public ExitCode getExitCode() { return ExitCode.USER_ERROR; }\n\n}",
"public class InvalidOptionsException extends AldaException {\n\n public InvalidOptionsException(String msg) {\n super(msg);\n }\n\n @Override\n public ExitCode getExitCode() { return ExitCode.USER_ERROR; }\n\n}",
"public class NoResponseException extends AldaException {\n\n public NoResponseException(String msg) {\n super(msg);\n }\n\n @Override\n public ExitCode getExitCode() { return ExitCode.NETWORK_ERROR; }\n\n}",
"public class SystemException extends AldaException {\n public SystemException(String msg) {\n super(msg);\n }\n\n public SystemException(String msg, Throwable e) {\n super(msg, e);\n }\n\n @Override\n public ExitCode getExitCode() { return ExitCode.SYSTEM_ERROR; }\n\n}",
"public class AldaRepl {\n public static final String ASCII_ART =\n \" █████╗ ██╗ ██████╗ █████╗\\n\" +\n \"██╔══██╗██║ ██╔══██╗██╔══██╗\\n\" +\n \"███████║██║ ██║ ██║███████║\\n\" +\n \"██╔══██║██║ ██║ ██║██╔══██║\\n\" +\n \"██║ ██║███████╗██████╔╝██║ ██║\\n\" +\n \"╚═╝ ╚═╝╚══════╝╚═════╝ ╚═╝ ╚═╝\\n\";\n\n public static final int ASCII_WIDTH = ASCII_ART.substring(0, ASCII_ART.indexOf('\\n')).length();\n public static final String HELP_TEXT = \"Type :help for a list of available commands.\";\n public static final String PROMPT = \"> \";\n\n public static final int DEFAULT_NUMBER_OF_WORKERS = 2;\n\n private AldaServer server;\n private ConsoleReader r;\n private boolean verbose;\n\n private ReplCommandManager manager;\n\n private StringBuffer history;\n private FileHistory fileHistory;\n\n private String promptPrefix = \"\";\n\n public AldaRepl(AldaServer server, boolean verbose) {\n this.server = server;\n server.setQuiet(true);\n this.verbose = verbose;\n history = new StringBuffer();\n manager = new ReplCommandManager();\n try {\n r = new ConsoleReader();\n\n // Capture Ctrl-C and throw a jline.console.UserInterruptException.\n r.setHandleUserInterrupt(true);\n\n // Disable default behavior where JLine treats `!` like a Bash expansion\n // character.\n r.setExpandEvents(false);\n\n // Enable history file.\n Path historyFile = Paths.get(System.getProperty(\"user.home\"),\n \".alda-repl-history\");\n if (!historyFile.toFile().exists()) Files.createFile(historyFile);\n fileHistory = new FileHistory(historyFile.toFile());\n r.setHistory(fileHistory);\n r.setHistoryEnabled(true);\n } catch (IOException e) {\n System.err.println(\"An error was detected when we tried to read a line.\");\n e.printStackTrace();\n ExitCode.SYSTEM_ERROR.exit();\n }\n if (!server.noColor) AnsiConsole.systemInstall();\n }\n\n /**\n * Centers and colors text\n * @param totalLen the total length to center to\n * @param toFormat the string to format\n * @param color the ANSI code to color. null will result in no color\n */\n private String centerText(int totalLen, String toFormat, Color color) {\n int offset = totalLen / 2 - toFormat.length() / 2;\n String out = \"\";\n if (offset > 0) {\n // Print out spaces to center the version string\n out = out + String.format(\"%1$\"+offset+\"s\", \" \");\n }\n out = out + toFormat;\n if (!server.noColor && color != null) {\n out = ansi().fg(color).a(out).reset().toString();\n }\n return out;\n }\n\n /**\n * Sanitizes instruments to remove their inst id.\n * guitar-IrqxY becomes guitar\n */\n public String sanitizeInstrument(String instrument) {\n return instrument.replaceFirst(\"-\\\\w+$\", \"\");\n }\n\n /**\n * Converts the current instrument to it's prefix form\n * For example, midi-square-wave becomes msw\n */\n public String instrumentToPrefix(String instrument) {\n // Split on non-words\n String[] parts = instrument.split(\"\\\\W\");\n StringBuffer completedName = new StringBuffer();\n // Build new name on first char of every part from the above split.\n for (String s : parts) {\n if (s.length() > 0)\n completedName.append(s.charAt(0));\n }\n return completedName.toString();\n }\n\n public void setPromptPrefix(AldaScore score) {\n if (score != null\n\t\t&& score.currentInstruments() != null\n\t\t&& score.currentInstruments().size() > 0) {\n\t Set<String> instruments = score.currentInstruments();\n\t boolean nicknameFound = false;\n\t String newPrompt = null;\n if (score.nicknames != null) {\n\t\t// Convert nick -> inst map to inst -> nick\n\t\tfor (Map.Entry<String, Set<String>> entry : score.nicknames.entrySet()) {\n\t\t // Check to see if we are playing any instruments from the nickname value set.\n\t\t Set<String> val = entry.getValue();\n\t\t // This destroys the nicknames value sets in the process.\n\t\t val.retainAll(instruments);\n\t\t if (val.size() > 0) {\n\t\t\t// Remove a possible period seperator, IE: nickname.piano\n\t\t\tnewPrompt = entry.getKey().replaceFirst(\"\\\\.\\\\w+$\", \"\");\n\t\t\tnewPrompt = instrumentToPrefix(newPrompt);\n\t\t\tbreak;\n\t\t }\n\t\t}\n\t }\n\n\t // No groups found, translate instruments normally:\n\t if (newPrompt == null) {\n\t\tnewPrompt =\n\t\t score.currentInstruments().stream()\n\t\t // Translate instruments to nicknames if available\n\t\t .map(this::sanitizeInstrument)\n\t\t // Translate midi-electric-piano-1 -> mep1\n\t\t .map(this::instrumentToPrefix)\n\t\t // Combine all instruments with /\n\t\t .reduce(\"\", (a, b) -> a + \"/\" + b)\n\t\t // remove leading / (which is always present)\n\t\t .substring(1);\n\t }\n\n\t if (newPrompt != null && newPrompt.length() > 0) {\n promptPrefix = newPrompt;\n return;\n }\n }\n // If we failed anywhere, reset prompt (probably no instruments playing).\n promptPrefix = \"\";\n }\n\n // Used by the Alda REPL.\n //\n // Errors are handled internally; if one occurs, the stacktrace is printed and\n // execution continues.\n private void offerToStartServer() {\n System.out.println(\"The server is down. Start server on port \" +\n server.port + \"?\");\n try {\n switch (Util.promptWithChoices(r, Arrays.asList(\"yes\", \"no\", \"quit\"))) {\n case \"yes\":\n try {\n System.out.println();\n server.setQuiet(false);\n server.upBg(DEFAULT_NUMBER_OF_WORKERS);\n server.setQuiet(true);\n } catch (InvalidOptionsException | NoResponseException |\n AlreadyUpException | SystemException e) {\n System.err.println(\"Unable to start server:\");\n e.printStackTrace();\n }\n break;\n case \"no\":\n // do nothing\n break;\n case \"quit\":\n ExitCode.SUCCESS.exit();\n default:\n // this shouldn't happen; if it does, just move on\n break;\n }\n } catch (SystemException e) {\n System.err.println(\"Error trying to read character:\");\n e.printStackTrace();\n }\n System.out.println();\n }\n\n private String asciiArt() {\n if (server.noColor) return ASCII_ART;\n return ansi().fg(BLUE).a(ASCII_ART).reset().toString();\n }\n\n private String helpText() {\n if (server.noColor) return HELP_TEXT;\n return ansi().fg(WHITE).bold().a(HELP_TEXT).reset().toString();\n }\n\n public void run() {\n System.out.println(asciiArt());\n System.out.println(centerText(ASCII_WIDTH, Util.version(), CYAN));\n System.out.println(centerText(ASCII_WIDTH, \"repl session\", CYAN));\n System.out.println(\"\\n\" + helpText() + \"\\n\");\n\n if (!server.checkForConnection()) {\n offerToStartServer();\n }\n\n while (true) {\n String input = \"\";\n try {\n input = r.readLine(promptPrefix + PROMPT);\n fileHistory.flush();\n } catch (IOException e) {\n System.err.println(\"An error was detected when we tried to read a line.\");\n e.printStackTrace();\n ExitCode.SYSTEM_ERROR.exit();\n } catch (UserInterruptException e) {\n\t\tinput = \":quit\";\n\t }\n\n // Check for quick quit keywords. input is null when we get EOF\n if (input == null || input.matches(\"^:?(quit|exit|bye).*\")) {\n // If we got an EOF, we need to print a line, so we quit on a newline\n if (input == null)\n System.out.println();\n\n // Let the master quit function handle this.\n input = \":quit\";\n }\n\n if (input.length() == 0) {\n // Don't do anything if we get no input\n continue;\n }\n\n // check for :keywords and act on them\n if (input.charAt(0) == ':') {\n // throw away ':'\n input = input.substring(1);\n\n // This limits size of splitString to 2 elements.\n // All arguments will be in splitString[1]\n String[] splitString = input.split(\"\\\\s\", 2);\n ReplCommand cmd = manager.get(splitString[0]);\n\n if (cmd != null) {\n // pass in empty string if we have no arguments\n String arguments = splitString.length > 1 ? splitString[1] : \"\";\n // Run the command\n try {\n cmd.act(arguments.trim(), history, server, r, this::setPromptPrefix);\n } catch (NoResponseException e) {\n System.out.println();\n offerToStartServer();\n } catch (UserInterruptException e) {\n try {\n // Quit the repl\n cmd.act(\":quit\", history, server, r, this::setPromptPrefix);\n } catch (NoResponseException nre) {\n // This shouldn't happen, but if it does...\n nre.printStackTrace();\n // Intentionally quitting should be considered successful.\n ExitCode.SUCCESS.exit();\n }\n }\n } else {\n System.err.println(\"No command '\" + splitString[0] + \"' was found\");\n }\n } else {\n try {\n // Play the stuff we just got, with history as context\n AldaResponse playResponse = server.playFromRepl(\n input, history.toString(), null, null\n );\n\n // If we have no exceptions, add to history\n history.append(input);\n history.append(\"\\n\");\n\n // If we're good, we should check to see if we reset the instrument\n if (playResponse != null) {\n this.setPromptPrefix(playResponse.score);\n }\n } catch (NoResponseException e) {\n System.out.println();\n offerToStartServer();\n } catch (NoAvailableWorkerException | UnsuccessfulException e) {\n server.error(e.getMessage());\n if (verbose) {\n System.out.println();\n e.printStackTrace();\n }\n }\n }\n }\n }\n}"
] | import alda.AldaResponse.AldaScore;
import alda.AldaServer;
import alda.error.AlreadyUpException;
import alda.error.InvalidOptionsException;
import alda.error.NoResponseException;
import alda.error.SystemException;
import alda.repl.AldaRepl;
import java.util.function.Consumer;
import jline.console.ConsoleReader; | package alda.repl.commands;
public class ReplDownUp implements ReplCommand {
@Override
public void act(String args, StringBuffer history, AldaServer server,
ConsoleReader reader, Consumer<AldaScore> newInstrument) | throws NoResponseException { | 4 |
PerficientDigital/AEM-DataLayer | weretail-reference/src/main/java/com/perficient/aem/weretail/datalayer/ProductGridItem.java | [
"public class Component extends CategorizableDataObject {\n\n\tpublic static final String DATA_KEY_COMPONENT_INFO = \"componentInfo\";\n\n\tpublic Component() {\n\t\tput(DATA_KEY_COMPONENT_INFO, new ComponentInfo());\n\t}\n\n\tpublic ComponentInfo getComponentInfo() {\n\t\treturn get(DATA_KEY_COMPONENT_INFO, ComponentInfo.class);\n\t}\n\n\tpublic void setComponentInfo(ComponentInfo componentInfo) {\n\t\tput(DATA_KEY_COMPONENT_INFO, componentInfo);\n\t}\n}",
"public interface ComponentDataElement {\n\n\t/**\n\t * Method called by the AEMDataLayerModel when adapting this class from a\n\t * resource in order to update the information in the Data Layer.\n\t * \n\t * @param dataLayer\n\t * the data layer to update\n\t */\n\tvoid updateDataLayer(DataLayer dataLayer);\n}",
"public class DataLayer extends ValueMapDecorator {\n\n\tpublic static final String DATA_KEY_ACCESS_CATEGORY = \"accessCategory\";\n\tpublic static final String DATA_KEY_CART = \"cart\";\n\tpublic static final String DATA_KEY_COMPONENT = \"component\";\n\tpublic static final String DATA_KEY_EVENT = \"event\";\n\tpublic static final String DATA_KEY_PAGE = \"page\";\n\tpublic static final String DATA_KEY_PAGE_INSTANCE_ID = \"pageInstanceID\";\n\tpublic static final String DATA_KEY_PRIVACY = \"privacy\";\n\tpublic static final String DATA_KEY_PRODUCT = \"product\";\n\tpublic static final String DATA_KEY_TRANSACTION = \"transaction\";\n\tpublic static final String DATA_KEY_USER = \"user\";\n\tpublic static final String DATA_KEY_VERSION = \"version \";\n\tprivate final AEMDataLayerConfig config;\n\tprivate final com.day.cq.wcm.api.Page page;\n\n\tpublic DataLayer(AEMDataLayerConfig config, com.day.cq.wcm.api.Page page) {\n\t\tsuper(new HashMap<String, Object>());\n\t\tthis.config = config;\n\t\tthis.page = page;\n\t\tput(DATA_KEY_EVENT, new ArrayList<EventInfo>());\n\t\tput(DATA_KEY_PAGE, new Page());\n\t\tput(DATA_KEY_VERSION, \"1.0\");\n\t}\n\n\tpublic void addComponent(Component component) {\n\t\tList<Component> components = getComponents();\n\t\tif (components == null) {\n\t\t\tcomponents = new ArrayList<Component>();\n\t\t\tsetComponents(components);\n\t\t}\n\t\tcomponents.add(component);\n\t}\n\n\tpublic void addEvent(EventInfo event) {\n\t\tList<EventInfo> events = getEvents();\n\t\tif (events == null) {\n\t\t\tevents = new ArrayList<EventInfo>();\n\t\t\tsetEvents(events);\n\t\t}\n\t\tevents.add(event);\n\t}\n\n\tpublic void addProduct(Product product) {\n\t\tif (!containsKey(DATA_KEY_PRODUCT)) {\n\t\t\tput(DATA_KEY_PRODUCT, new ArrayList<Product>());\n\t\t}\n\t\tgetProducts().add(product);\n\t}\n\n\tpublic List<AccessCategory> getAccessCategories() {\n\t\tif (!containsKey(DATA_KEY_PRIVACY)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn get(DATA_KEY_COMPONENT, new HashMap<String, List<AccessCategory>>()).get(DATA_KEY_ACCESS_CATEGORY);\n\t}\n\n\tpublic com.day.cq.wcm.api.Page getAEMPage() {\n\t\treturn page;\n\t}\n\n\tpublic Cart getCart() {\n\t\treturn get(DATA_KEY_CART, Cart.class);\n\t}\n\n\tpublic List<Component> getComponents() {\n\t\tif (!containsKey(DATA_KEY_COMPONENT)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn get(DATA_KEY_COMPONENT, new ArrayList<Component>());\n\t}\n\n\tpublic AEMDataLayerConfig getConfig() {\n\t\treturn this.config;\n\t}\n\n\tpublic List<EventInfo> getEvents() {\n\t\tif (!containsKey(DATA_KEY_EVENT)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn get(DATA_KEY_EVENT, new ArrayList<EventInfo>());\n\t}\n\n\tpublic Page getPage() {\n\t\treturn get(DATA_KEY_PAGE, Page.class);\n\t}\n\n\tpublic String getPageInstanceID() {\n\t\treturn this.get(DATA_KEY_PAGE_INSTANCE_ID, String.class);\n\t}\n\n\tpublic List<Product> getProducts() {\n\t\tif (!containsKey(DATA_KEY_PRODUCT)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn get(DATA_KEY_PRODUCT, new ArrayList<Product>());\n\t}\n\n\tpublic Transaction getTransaction() {\n\t\treturn get(DATA_KEY_TRANSACTION, Transaction.class);\n\t}\n\n\tpublic List<User> getUsers() {\n\t\tif (!containsKey(DATA_KEY_USER)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn get(DATA_KEY_USER, new ArrayList<User>());\n\t}\n\n\tpublic String getVersion() {\n\t\treturn get(DATA_KEY_VERSION, String.class);\n\t}\n\n\tpublic void setAccessCategories(List<AccessCategory> accessCategories) {\n\t\tHashMap<String, List<AccessCategory>> defaultPrivacy = new HashMap<String, List<AccessCategory>>();\n\t\tif (!containsKey(DATA_KEY_PRIVACY)) {\n\t\t\tput(DATA_KEY_COMPONENT, defaultPrivacy);\n\t\t}\n\t\tget(DATA_KEY_COMPONENT, defaultPrivacy).put(DATA_KEY_ACCESS_CATEGORY, accessCategories);\n\t}\n\n\tpublic void setCart(Cart cart) {\n\t\tput(DATA_KEY_CART, cart);\n\t}\n\n\tpublic void setComponents(List<Component> components) {\n\t\tput(DATA_KEY_COMPONENT, components);\n\t}\n\n\tpublic void setEvents(List<EventInfo> events) {\n\t\tput(DATA_KEY_EVENT, events);\n\t}\n\n\tpublic void setPage(Page page) {\n\t\tput(DATA_KEY_PAGE, page);\n\t}\n\n\tpublic void setPageInstanceID(String pageInstanceID) {\n\t\tput(DATA_KEY_PAGE_INSTANCE_ID, pageInstanceID);\n\t}\n\n\tpublic void setTransaction(Transaction transaction) {\n\t\tput(DATA_KEY_TRANSACTION, transaction);\n\t}\n\n\tpublic void setUsers(List<User> users) {\n\t\tput(DATA_KEY_USER, users);\n\t}\n\n}",
"public class ProductInfo extends BaseDataObject {\n\n\tpublic static final String DATA_KEY_COLOR = \"color\";\n\tpublic static final String DATA_KEY_DESCRIPTION = \"description\";\n\tpublic static final String DATA_KEY_MANUFACTURER = \"manufacturer\";\n\tpublic static final String DATA_KEY_PRODUCT_ID = \"productID\";\n\tpublic static final String DATA_KEY_PRODUCT_IMAGE = \"productImage\";\n\tpublic static final String DATA_KEY_PRODUCT_NAME = \"productName\";\n\tpublic static final String DATA_KEY_PRODUCT_THUMBNAIL = \"productThumbnail\";\n\tpublic static final String DATA_KEY_PRODUCT_URL = \"productURL\";\n\tpublic static final String DATA_KEY_SIZE = \"size\";\n\tpublic static final String DATA_KEY_SKU = \"sku\";\n\n\tpublic String getColor() {\n\t\treturn get(DATA_KEY_COLOR, String.class);\n\t}\n\n\tpublic String getDescription() {\n\t\treturn get(DATA_KEY_DESCRIPTION, String.class);\n\t}\n\n\tpublic String getManufacturer() {\n\t\treturn get(DATA_KEY_MANUFACTURER, String.class);\n\t}\n\n\tpublic String getProductID() {\n\t\treturn get(DATA_KEY_PRODUCT_ID, String.class);\n\t}\n\n\tpublic String getProductImage() {\n\t\treturn get(DATA_KEY_PRODUCT_IMAGE, String.class);\n\t}\n\n\tpublic String getProductName() {\n\t\treturn get(DATA_KEY_PRODUCT_NAME, String.class);\n\t}\n\n\tpublic String getProductThumbnail() {\n\t\treturn get(DATA_KEY_PRODUCT_THUMBNAIL, String.class);\n\t}\n\n\tpublic String getProductURL() {\n\t\treturn get(DATA_KEY_PRODUCT_URL, String.class);\n\t}\n\n\tpublic String getSize() {\n\t\treturn get(DATA_KEY_SIZE, String.class);\n\t}\n\n\tpublic String getSku() {\n\t\treturn get(DATA_KEY_SKU, String.class);\n\t}\n\n\tpublic void setColor(String color) {\n\t\tput(DATA_KEY_COLOR, color);\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tput(DATA_KEY_DESCRIPTION, description);\n\t}\n\n\tpublic void setManufacturer(String manufacturer) {\n\t\tput(DATA_KEY_MANUFACTURER, manufacturer);\n\t}\n\n\tpublic void setProductID(String productID) {\n\t\tput(DATA_KEY_PRODUCT_ID, productID);\n\t}\n\n\tpublic void setProductImage(String productImage) {\n\t\tput(DATA_KEY_PRODUCT_IMAGE, productImage);\n\t}\n\n\tpublic void setProductName(String productName) {\n\t\tput(DATA_KEY_PRODUCT_NAME, productName);\n\t}\n\n\tpublic void setProductThumbnail(String productThumbnail) {\n\t\tput(DATA_KEY_PRODUCT_THUMBNAIL, productThumbnail);\n\t}\n\n\tpublic void setProductURL(String productURL) {\n\t\tput(DATA_KEY_PRODUCT_URL, productURL);\n\t}\n\n\tpublic void setSize(String size) {\n\t\tput(DATA_KEY_SIZE, size);\n\t}\n\n\tpublic void setSku(String sku) {\n\t\tput(DATA_KEY_SKU, sku);\n\t}\n}",
"public class DataLayerUtil {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(DataLayerUtil.class);\n\n\tprivate DataLayerUtil() {\n\t\t// hidden\n\t}\n\n\tpublic static final DataLayer getDataLayer(ServletRequest request) {\n\t\treturn (DataLayer) request.getAttribute(DataLayerConstants.REQUEST_PROPERTY_AEM_DATALAYER);\n\t}\n\n\tpublic static final String getSiteSubpath(Page page, AEMDataLayerConfig config) {\n\t\treturn page.getPath().replace(page.getAbsoluteParent(config.getSiteRootLevel()).getPath(), \"\");\n\t}\n\n\tpublic static final String getSiteUrl(Page page, AEMDataLayerConfig config) {\n\t\tString subpath = getSiteSubpath(page, config);\n\t\treturn config.getUrlPrefix() + subpath + \".html\";\n\t}\n\n\tpublic static final String toJSON(DataLayer dataLayer) {\n\t\tObjectMapper objectMapper = new ObjectMapper();\n\t\tobjectMapper.setDateFormat(new SimpleDateFormat(DataLayerConstants.DATE_FORMAT));\n\n\t\tObjectWriter writer = null;\n\t\tif (dataLayer.getConfig().getPrettyPrint()) {\n\t\t\twriter = objectMapper.writerWithDefaultPrettyPrinter();\n\t\t} else {\n\t\t\twriter = objectMapper.writer();\n\t\t}\n\t\ttry {\n\t\t\treturn writer.writeValueAsString(dataLayer);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tlog.error(\"Exception writing DataLayer to JSON\", e);\n\t\t\treturn \"{\\\"error\\\":true}\";\n\t\t}\n\t}\n}"
] | import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import com.adobe.cq.commerce.api.Product;
import com.day.cq.wcm.api.Page;
import com.perficient.aem.datalayer.api.Component;
import com.perficient.aem.datalayer.api.ComponentDataElement;
import com.perficient.aem.datalayer.api.DataLayer;
import com.perficient.aem.datalayer.api.ProductInfo;
import com.perficient.aem.datalayer.core.DataLayerUtil; | package com.perficient.aem.weretail.datalayer;
@Model(adaptables = Resource.class, resourceType = {
"weretail/components/content/productgrid/item" }, adapters = ComponentDataElement.class)
public class ProductGridItem implements ComponentDataElement {
private Resource resource;
private Resource productDataResource;
private Product productData;
public ProductGridItem(Resource resource) {
this.resource = resource;
this.productDataResource = resource.getResourceResolver()
.getResource(resource.getValueMap().get("cq:productMaster", String.class));
productData = productDataResource.adaptTo(Product.class);
}
@Override
public void updateDataLayer(DataLayer dataLayer) {
com.perficient.aem.datalayer.api.Product product = new com.perficient.aem.datalayer.api.Product();
ProductInfo productInfo = product.getProductInfo();
productInfo.setDescription(productData.getDescription());
productInfo.setProductID(productData.getPath());
productInfo.setProductImage(dataLayer.getConfig().getUrlPrefix() + productData.getImageUrl());
productInfo.setProductName(productData.getTitle());
productInfo.setProductThumbnail(dataLayer.getConfig().getUrlPrefix() + productData.getThumbnailUrl());
Page page = dataLayer.getAEMPage();
productInfo.setProductURL(DataLayerUtil.getSiteUrl(page, dataLayer.getConfig()));
productInfo.setSku(productData.getSKU());
product.setProductInfo(productInfo);
product.addAttribute("displayType", "productgrid/item");
dataLayer.addProduct(product);
| Component component = new Component(); | 0 |
google/mug | mug/src/test/java/com/google/mu/util/stream/CasesTest.java | [
"static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() {\n return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll);\n}",
"public static <T> Collector<T, ?, T> onlyElement() {\n return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne);\n}",
"public static <T, R> Collector<T, ?, R> onlyElements(\n BiFunction<? super T, ? super T, ? extends R> twoElements) {\n requireNonNull(twoElements);\n return collectingAndThen(toTinyContainer(), c -> c.only(twoElements));\n}",
"@SafeVarargs\npublic static <T, R> Collector<T, ?, R> cases(\n Collector<? super T, ?, ? extends Optional<? extends R>>... cases) {\n List<Collector<? super T, ?, ? extends Optional<? extends R>>> caseList =\n Arrays.stream(cases).peek(Objects::requireNonNull).collect(toList());\n return collectingAndThen(\n toList(),\n input ->\n caseList.stream()\n .map(c -> input.stream().collect(c).orElse(null))\n .filter(v -> v != null)\n .findFirst()\n .orElseThrow(() -> unexpectedSize(input.size())));\n}",
"public static <R> Collector<Object, ?, Optional<R>> when(Supplier<? extends R> noElement) {\n requireNonNull(noElement);\n return collectingAndThen(\n counting(), c -> c == 0 ? Optional.of(noElement.get()) : Optional.empty());\n}",
"static final class TinyContainer<T> {\n private T first;\n private T second;\n private int size = 0;\n\n static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() {\n return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll);\n }\n\n void add(T value) {\n if (size == 0) {\n first = value;\n } else if (size == 1) {\n second = value;\n }\n size++;\n }\n\n // Hate to write this code! But a combiner is upon us whether we want parallel or not.\n TinyContainer<T> addAll(TinyContainer<? extends T> that) {\n int newSize = size + that.size;\n if (that.size > 0) {\n add(that.first);\n }\n if (that.size > 1) {\n add(that.second);\n }\n size = newSize;\n return this;\n }\n\n int size() {\n return size;\n }\n\n <R> Optional<R> when(\n Predicate<? super T> condition, Function<? super T, ? extends R> oneElement) {\n return size == 1 && condition.test(first)\n ? Optional.of(oneElement.apply(first))\n : Optional.empty();\n }\n\n <R> Optional<R> when(\n BiPredicate<? super T, ? super T> condition,\n BiFunction<? super T, ? super T, ? extends R> twoElements) {\n return size == 2 && condition.test(first, second)\n ? Optional.of(twoElements.apply(first, second))\n : Optional.empty();\n }\n\n <R> R only(BiFunction<? super T, ? super T, ? extends R> twoElements) {\n return when((x, y) -> true, twoElements).orElseThrow(() -> unexpectedSize(size));\n }\n\n T onlyOne() {\n return when(x -> true, identity()).orElseThrow(() -> unexpectedSize(size));\n }\n}"
] | import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer;
import static com.google.mu.util.stream.Cases.onlyElement;
import static com.google.mu.util.stream.Cases.onlyElements;
import static com.google.mu.util.stream.Cases.cases;
import static com.google.mu.util.stream.Cases.when;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static java.util.function.Function.identity;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.common.testing.NullPointerTester;
import com.google.mu.util.stream.Cases.TinyContainer;
import java.util.stream.Stream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; | package com.google.mu.util.stream;
@RunWith(JUnit4.class)
public final class CasesTest {
@Test public void when_zeroElement() {
assertThat(Stream.of(1).collect(when(() -> "zero"))).isEmpty();
assertThat(Stream.empty().collect(when(() -> "zero"))).hasValue("zero");
}
@Test public void when_oneElement() {
assertThat(Stream.of(1).collect(when(i -> i + 1))).hasValue(2);
assertThat(Stream.of(1, 2).collect(when(i -> i + 1))).isEmpty();
assertThat(Stream.of(1).collect(when(x -> x == 1, i -> i + 1))).hasValue(2);
assertThat(Stream.of(1).collect(when(x -> x == 2, i -> i + 1))).isEmpty();
}
@Test public void when_twoElements() {
assertThat(Stream.of(2, 3).collect(when((a, b) -> a * b))).hasValue(6);
assertThat(Stream.of(2, 3, 4).collect(when((a, b) -> a * b))).isEmpty();
assertThat(Stream.of(2, 3).collect(when((x, y) -> x < y, (a, b) -> a * b))).hasValue(6);
assertThat(Stream.of(2, 3).collect(when((x, y) -> x > y, (a, b) -> a * b))).isEmpty();
}
@Test public void only_oneElement() {
String result = Stream.of("foo").collect(onlyElement());
assertThat(result).isEqualTo("foo");
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class, () -> Stream.of(1, 2, 3).collect(onlyElement()));
assertThat(thrown).hasMessageThat().contains("size: 3");
}
@Test public void only_twoElements() {
int result = Stream.of(2, 3).collect(onlyElements((a, b) -> a * b));
assertThat(result).isEqualTo(6);
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class, () -> Stream.of(1).collect(onlyElements((a, b) -> a * b)));
assertThat(thrown).hasMessageThat().contains("size: 1");
}
@Test public void cases_firstCaseMatch() {
String result = Stream.of("foo", "bar").collect(cases(when((a, b) -> a + b), when(a -> a)));
assertThat(result).isEqualTo("foobar");
}
@Test public void cases_secondCaseMatch() {
String result = Stream.of("foo").collect(cases(when((a, b) -> a + b), when(a -> a)));
assertThat(result).isEqualTo("foo");
}
@Test public void cases_noMatchingCase() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
() -> Stream.of(1, 2, 3).collect(cases(when((a, b) -> a + b), when(a -> a))));
assertThat(thrown).hasMessageThat().contains("size: 3");
}
@Test public void toTinyContainer_empty() { | assertThat(Stream.empty().collect(toTinyContainer()).size()).isEqualTo(0); | 0 |
jackyhung/consumer-dispatcher | src/main/java/com/thenetcircle/comsumerdispatcher/thread/ConsumerJobExecutorPool.java | [
"public class CountChangedWatcher extends BaseJobPoolLevelWatcher implements ICountChangedWatcher {\n\tprivate static Log _logger = LogFactory.getLog(CountChangedWatcher.class);\n\t\n\tprotected int numToSet = 0;\n\tprotected String newSubNode = null;\n\t\n\t@Override\n\tpublic void register(ConsumerJobExecutorPool pool) {\n\t\tsuper.register(pool);\n\t\tif (DistributionManager.getInstance().isStandalone())\n\t\t\treturn;\n\t\t\n\t\t_logger.info(\"[Distribution Watcher] going to register count watcher...\");\n\t\t\n\t\tmutex = new Integer(-1);\n\t\ttry {\n\t\t\twatchOrGetNode(true);\n\t\t} catch (Exception e) {\n\t\t\t_logger.error(\"[Distribution CountChanged Watcher] error while trying to watch.\" + e, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void process(WatchedEvent event) {\n\t\tif(event.getType() == Watcher.Event.EventType.NodeDataChanged) {\n\t\t\t_logger.info(\"[Distribution CountChanged Watcher] got countchanged event....\");\n\t\t\tString numStr;\n\t\t\ttry {\n\t\t\t\tnumStr = watchOrGetNode(false);\n\t\t\t\tpool.setJobExecutorNum(Integer.valueOf(numStr));\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif (pool.getActiveJobExecutorCount() <= 0) {\n\t\t\t\t\t// if all threads stopped in the pool, give signal of purging by adding one child under purge node;\n\t\t\t\t\tString purgeSubNode = String.format(DistributionTreeConstants.CD_ROOT_DOMAIN_QUEUEONSERVER_NOTRUNNING_SUBNODES, getDomainName(), pool.getJobDefinition().getLogicName());\n\t\t\t\t\tnewSubNode = zk.create(purgeSubNode, \"\".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);\n\t\t\t\t\t_logger.info(\"[Distribution CountChanged Watcher] since no worker in pool for queue\" + getQueueJobNodeName() + \" added subnode to purge node: \" + newSubNode);\n\t\t\t\t} else {\n\t\t\t\t\tif(newSubNode != null && zk.exists(newSubNode, false) != null) {\n\t\t\t\t\t\t_logger.info(\"[Distribution CountChanged Watcher] goint to delete corresponding not running child node: \" + newSubNode);\n\t\t\t\t\t\tzk.delete(newSubNode, -1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\t_logger.error(\"[Distribution CountChanged Watcher] error while processing watched event\" + e, e);\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\twatchOrGetNode(true);\n\t\t} catch (Exception e) {\n\t\t\t_logger.error(e, e);\n\t\t}\n\t}\n\n\t@Override\n\tprotected String findTheNodePathToWatch() {\n\t\treturn String.format(DistributionTreeConstants.CD_ROOT_DOMAIN_QUEUEONSERVER_COUNT, getDomainName(), pool.getJobDefinition().getLogicName());\n\t}\n\n\t@Override\n\tprotected Watcher getWatcher() {\n\t\treturn this;\n\t}\n\n\t@Override\n\tprotected void doExecute() {\n\t\tif (DistributionManager.getInstance().isStandalone()) {\n\t\t\tpool.setJobExecutorNum(Integer.valueOf(numToSet));\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tzk.setData(findTheNodePathToWatch(), String.valueOf(numToSet).getBytes(), -1);\n\t\t\t} catch (Exception e) {\n\t\t\t\t_logger.error(\"[Distribution CountChanged Watcher] error to set data for node: \" + e, e);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void preExecute() {\n\t}\n\n\t@Override\n\tprotected void postExecute() {\n\t}\n\n\t/**\n\t * the number of jobs to be removed (- value) or added (+ value)\n\t * @param numToExecute\n\t */\n\tpublic void setNumToSet(int deltaToExecute) {\n\t\tthis.numToSet = deltaToExecute;\n\t}\n}",
"public interface IJobPoolLevelWatcher extends Watcher {\n\n\tpublic void register(ConsumerJobExecutorPool pool);\n}",
"public class NewUrlWatcher extends BaseJobPoolLevelWatcher implements INewUrlWatcher {\n\tprivate static Log _logger = LogFactory.getLog(NewUrlWatcher.class);\n\t\n\tprotected String newUrl;\n\t\n\t@Override\n\tpublic void register(ConsumerJobExecutorPool pool) {\n\t\tsuper.register(pool);\n\t\tif (DistributionManager.getInstance().isStandalone())\n\t\t\treturn;\n\t\t\n\t\t_logger.info(\"[Distribution Watcher] going to register new url watcher...\");\n\t\t\n\t\tmutex = new Integer(-1);\n\t\ttry {\n\t\t\twatchOrGetNode(true);\n\t\t} catch (Exception e) {\n\t\t\t_logger.error(\"[Distribution NewURL Watcher] error while trying to watch.\" + e, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void process(WatchedEvent event) {\n\t\tif(event.getType() == Watcher.Event.EventType.NodeDataChanged) {\n\t\t\t_logger.info(\"[Distribution NewURL Watcher] got NewURL event....\");\n\t\t\tString eventUrl;\n\t\t\ttry {\n\t\t\t\teventUrl = watchOrGetNode(false);\n\t\t\t\tpool.refreshUrl(eventUrl);\n\t\t\t} catch (Exception e) {\n\t\t\t\t_logger.error(\"[Distribution NewURL Watcher] error while processing watched event\" + e, e);\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\twatchOrGetNode(true);\n\t\t} catch (Exception e) {\n\t\t\t_logger.error(e, e);\n\t\t}\n\t}\n\n\t@Override\n\tprotected String findTheNodePathToWatch() {\n\t\treturn String.format(DistributionTreeConstants.CD_ROOT_DOMAIN_QUEUEONSERVER_REQURL, getDomainName(), pool.getJobDefinition().getLogicName());\n\t}\n\n\t@Override\n\tprotected Watcher getWatcher() {\n\t\treturn this;\n\t}\n\n\t@Override\n\tprotected void doExecute() {\n\t\tif (DistributionManager.getInstance().isStandalone()) {\n\t\t\tpool.refreshUrl(newUrl);\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tzk.setData(findTheNodePathToWatch(), newUrl.getBytes(), -1);\n\t\t\t} catch (Exception e) {\n\t\t\t\t_logger.error(\"[Distribution CountChanged Watcher] error to set data for node: \" + e, e);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void preExecute() {\n\t}\n\n\t@Override\n\tprotected void postExecute() {\n\t}\n\t\n\tpublic void setNewUrl(String url) {\n\t\tthis.newUrl = url;\n\t}\n}",
"public class QueuePurgeWatcher extends BaseJobPoolLevelWatcher implements IQueuePurgeWatcher {\n\tprivate static Log _logger = LogFactory.getLog(QueuePurgeWatcher.class);\n\t\n\t@Override\n\tpublic void register(ConsumerJobExecutorPool pool) {\n\t\tsuper.register(pool);\n\t\tif (DistributionManager.getInstance().isStandalone())\n\t\t\treturn;\n\t\t\n\t\t_logger.info(\"[Distribution Watcher] going to register queue purge watcher...\");\n\t\t\n\t\tmutex = new Integer(-1);\n\t\ttry {\n\t\t\t//watchOrGetNode(true);\n\t\t} catch (Exception e) {\n\t\t\t_logger.error(\"[Distribution Purge Watcher] error while trying to watch.\" + e, e);\n\t\t}\n\t}\n\t\n\t\n\t\n\t@Override\n\tprotected void preExecute() {\n\t\tif (DistributionManager.getInstance().isStandalone()) {\n\t\t\tpool.stopAllExecutors();\n\t\t} else {\n\t\t\t// use events to stop all threads\n\t\t\ttry {\n\t\t\t\t// set count node to 0 so that all applications will stop all workers\n\t\t\t\ttry {\n\t\t\t\t\t_logger.info(\"[Distribution Purge Watcher] set the count node to 0 so that to stop all running workers... \");\n\t\t\t\t\tString countNode = String.format(DistributionTreeConstants.CD_ROOT_DOMAIN_QUEUEONSERVER_COUNT, getDomainName(), pool.getJobDefinition().getLogicName());\n\t\t\t\t\tzk.setData(countNode, \"0\".getBytes(), -1);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t_logger.error(\"[Distribution Purge Watcher] error to set value of 0 to count node: \" + e, e);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\twhile (true) {\n\t synchronized (mutex) {\n\t \t// watch on not-running node\n\t List<String> list = zk.getChildren(findTheNodePathToWatch(), new Watcher() {\n\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\tpublic synchronized void process(WatchedEvent event) {\n\t\t\t\t\t\t\t\t_logger.info(\"[Distribution Purge Watcher] received one event...\");\n\t\t\t\t\t\t\t\tsynchronized (mutex) {\n\t\t\t\t\t\t mutex.notify();\n\t\t\t\t\t\t }\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t \t\n\t });\n\n\t if (list.size() < DistributionManager.getInstance().getLivingJoinedMemberNum()) {\n\t mutex.wait(); //TODO FIXME while start the application up, if the count is alread set to 0, need to add 'CD_ROOT_DOMAIN_QUEUEONSERVER_NOTRUNNING_SUBNODES' expicitly \n\t } else {\n\t break; // enough nodes, out of loop. meaning all running worker stopped, can continue to purge\n\t }\n\t }\n\t }\n\t\t\t} catch (Exception e) {\n\t\t\t\t_logger.error(\"[Distribution Purge Watcher] prePurge failed for job: \" + pool.getJobDefinition().getLogicName() + \" on domain: \" + pool.getJobDefinition().getUrl() + e, e);\n\t\t\t\tthrow new RuntimeException(\"[Distribution Purge Watcher] prePurge failed\", e);\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\t@Override\n\tprotected void doExecute() {\n\t\tQueueUtil.purgeQueue(pool.getJobDefinition());\n\t}\n\t\n\t@Override\n\tprotected void postExecute() {\n\t\tif (DistributionManager.getInstance().isStandalone()) {\n\t\t\tpool.startJobExecutors();\n\t\t} else {\n\t\t\tString num = String.valueOf(pool.getJobDefinition().getCount());\n\t\t\t_logger.info(\"[Distribution Purge Watcher] set the count node to \" + num + \" so that all workers start running ... \");\n\t\t\tString countNode = String.format(DistributionTreeConstants.CD_ROOT_DOMAIN_QUEUEONSERVER_COUNT, getDomainName(), pool.getJobDefinition().getLogicName());\n\t\t\ttry {\n\t\t\t\tzk.setData(countNode, num.getBytes(), -1);\n\t\t\t} catch (Exception e) {\n\t\t\t\t_logger.error(\"[Distribution Purge Watcher] error when trying to set new count value after purging queue: \" + e, e);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void process(WatchedEvent event) {\n\t}\n\t\n\t@Override\n\tprotected String findTheNodePathToWatch() {\n\t\treturn String.format(DistributionTreeConstants.CD_ROOT_DOMAIN_QUEUEONSERVER_NOTRUNNING, getDomainName(), pool.getJobDefinition().getLogicName());\n\t}\n\n\t@Override\n\tprotected Watcher getWatcher() {\n\t\treturn this;\n\t}\n}",
"public class JobExecutor extends DispatcherJob implements Runnable, Cloneable {\n\tprivate static Log _logger = LogFactory.getLog(JobExecutor.class);\n\t\n\tprivate ReentrantLock runLock;\n\tvolatile AtomicInteger completedJobs;\n\tprivate AtomicBoolean logErrorJobToFile; \n\tprivate long DELIVERY_WAIT_TIMEOUT = 3000;\n\n\tpublic void run() {\n\t\t_logger.info(\"started: \" + this.getName() + \" with params: \" + super.toString());\n\t\t\n\t\tConnectionFactory factory = new ConnectionFactory();\n\t\tfactory.setUsername(this.getFetcherQConf().getUserName());\n\t\tfactory.setPassword(this.getFetcherQConf().getPassword());\n\t\tfactory.setVirtualHost(this.getFetcherQConf().getVhost());\n\t\tfactory.setHost(this.getFetcherQConf().getHost());\n\t\tfactory.setPort(this.getFetcherQConf().getPort());\n\t\tfactory.setAutomaticRecoveryEnabled(true);\n\t\tfactory.setNetworkRecoveryInterval(5000);\n\t\t//factory.setRequestedHeartbeat();\n\t\t\n\t\tConnection conn = null;\n\t\tChannel channel = null;\n\t\tString queueName = getQueue();//\"image_admin\";\n\t\ttry {\n\t\t\tconn = factory.newConnection();\n\t\t\t// in one thread \n\t\t\tchannel = conn.createChannel();\n\t\t\tString exchangeName = getExchange();//\"image_admin_exchange\";\n\t\t\tString type = this.getType();\n\t\t\tboolean exclusive = false;\n\t\t\tboolean autoDelete = false;\n\t\t\tboolean durable = true;\n\t\t\tString routingKey = \"\";\n\t\t\t\n\t\t\tchannel.exchangeDeclare(exchangeName, type, durable);\n\t\t\tchannel.queueDeclare(queueName, durable, exclusive, autoDelete, null);\n\t\t\tchannel.queueBind(queueName, exchangeName, routingKey);\n\t\t\t\n\t\t\tboolean autoAck = false;\n\t\t\t\n\t\t\tQueueingConsumer consumer = new QueueingConsumer(channel);\n\t\t\tchannel.basicQos(getPrefetchCount());\n\t\t\tchannel.basicConsume(queueName, autoAck, consumer);\n\t\t\t//channel.basicQos(getPrefetchCount());\n\t\t\t\n\t\t\t\n\t\t\tboolean run = true;\n\t\t\twhile (run) {\n \tfinal ReentrantLock runLock = this.runLock;\n\t runLock.lock();\n\t try {\n\t\t\t\t QueueingConsumer.Delivery delivery;\n\t\t\t delivery = consumer.nextDelivery(DELIVERY_WAIT_TIMEOUT);\n\t\t\t if(null == delivery)\n\t\t\t \tcontinue;\n\t\t\t \n\t\t\t\t byte[] bobyByte = delivery.getBody();\n\t\t\t\t String bodyStr = new String(bobyByte, this.getEncoding());//\"US-ASCII\", \"utf-8\"\n\t\t\t\t \n\t\t\t\t\tif(dispatchJob(this.getName(), bodyStr)) {\n\t\t\t\t\t\tchannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);\n\t\t\t\t\t\t\n\t\t\t\t\t\tcompletedJobs.incrementAndGet();\n\t\t\t\t\t\tif(_logger.isDebugEnabled()) {\n\t\t\t\t\t\t\t_logger.debug(\"ack meg:\" + delivery.getEnvelope().getDeliveryTag());\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchannel.basicReject(delivery.getEnvelope().getDeliveryTag(), true);\n\t\t\t\t\t}\n\t\t\t\t \n\t\t\t\t if (Bootstrap.once) run = false;\n\t\t\t } catch (IOException ioe) { // the exception of io, continue the loop process , retry!\n\t\t\t \t_logger.error(\"[THREAD INTERRUPT] got error, but will continue:\" + queueName, ioe);\n\t\t\t \tcontinue;\n\t\t\t } catch (ShutdownSignalException se) { // got the queue connection error, quit the loop, let the Pool to start a new connection.\n\t\t\t \tthrow new JobFailedException(\"[THREAD INTERRUPT] got queue error:\" + queueName, se);\n\t\t\t } catch (ConsumerCancelledException ce) { // got the queue connection error, quit the loop, let the Pool to start a new connection.\n\t\t\t \tthrow new JobFailedException(\"[THREAD INTERRUPT] got queue consumer error:\" + queueName, ce);\n \t} catch (InterruptedException ie) { // got the signal to quit. and also the Pool should STOP this job.\n\t\t\t \tthrow new JobStopException(\"[THREAD INTERRUPT] got quit signal:\" + queueName, ie);\n\t } finally {\n\t runLock.unlock();\n\t }\n\t\t\t} // end loop\n\t\t} catch (IOException ioe) {\n\t\t\tthrow new JobStopException(\"[THREAD INTERRUPT] got certain error:\" + queueName, ioe);\n\t\t} catch (TimeoutException te) {\n\t\t\tthrow new JobStopException(\"[THREAD INTERRUPT] got certain error:\" + queueName, te);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tif (channel != null && channel.isOpen()) channel.close();\n\t\t\t} catch (Exception e) {\n\t\t\t\t_logger.error(e, e);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tif (conn!= null && conn.isOpen()) conn.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\t_logger.error(e, e);\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\n\tprivate boolean dispatchJob(String qname, String body) {\n\t\tString vhost = this.getFetcherQConf().getHost() + \"@\" + this.getFetcherQConf().getVhost() ;\n\t\ttry {\n\t\t\tMap<String, String> map = new HashMap<String, String>();\n\t\t\tmap.put(\"queueName\", qname);\n\t\t\tmap.put(\"bodyData\", body);\n\t\t\tString result = HttpUtil.sendHttpPost(this.getUrl(), this.getUrlhost(), map, this.getTimeout());\n\t\t\tif(null != result) result = result.trim();\n\t\t\tif (\"ok\".equalsIgnoreCase(result)) {\n\t\t\t\tif(_logger.isDebugEnabled()) {\n\t\t\t\t\t_logger.debug(\"the result of job for q \" + qname + \" on server \" + vhost + \":\" + result);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tif(_logger.isErrorEnabled())\n\t\t\t\t\t_logger.error(\"the result of job part is not right for q \" + qname + \" on server \" + vhost);\n\t\t\t\tif(_logger.isDebugEnabled())\n\t\t\t\t\t_logger.debug(\"the result of job part is not right for q \" + qname + \" on server \" + vhost + \": \" + \", body: \" + body + \", response: \" + result);\n\t\t\t\t\n\t\t\t\tif(logErrorJobToFile.get()) { // get logged to file, then acknowledge this job to queue\n\t\t\t\t\tFileUtil.logJobRawDataToFile(FileUtil.getErrorJobFileName(this), body);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(getRetry() == 0) { // disable retry\n\t\t\t\t\t_logger.info(\"get error, but wont retry for q \" + qname + \" on server \" + vhost + \": \" + \", body: \" + body + \", response: \" + result);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tif(_logger.isErrorEnabled())\n\t\t\t\t_logger.error(\"the status of job part is not right for q \" + qname + \" on server \" + vhost + \": \" + e.getMessage());\n\t\t\t\n\t\t\tif(logErrorJobToFile.get()) { // get logged to file, then acknowledge this job to queue\n\t\t\t\tFileUtil.logJobRawDataToFile(FileUtil.getErrorJobFileName(this), body);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic void setRunLock(ReentrantLock runLock) {\n\t\tthis.runLock = runLock;\n\t}\n\t\n\tpublic ReentrantLock getRunLock() {\n\t\treturn this.runLock;\n\t}\n\t\n\tpublic AtomicInteger getCompletedJobs() {\n\t\treturn completedJobs;\n\t}\n\n\tpublic void setCompletedJobs(AtomicInteger completedJobs) {\n\t\tthis.completedJobs = completedJobs;\n\t}\n\t\n\tpublic void setLogErrorJobToFile(AtomicBoolean logErrorJobToFile) {\n\t\tthis.logErrorJobToFile = logErrorJobToFile;\n\t}\n\n\t@Override\n\tpublic Object clone() throws CloneNotSupportedException {\n\t\treturn super.clone();\n\t}\n}",
"public class JobFailedException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 2263285375315953049L;\n\n\tpublic JobFailedException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n}",
"public class JobStopException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 7587359595408648856L;\n\t\n\tpublic JobStopException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n}"
] | import java.lang.Thread.State;
import java.lang.management.ManagementFactory;
import java.net.URL;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.thenetcircle.comsumerdispatcher.distribution.watcher.CountChangedWatcher;
import com.thenetcircle.comsumerdispatcher.distribution.watcher.IJobPoolLevelWatcher;
import com.thenetcircle.comsumerdispatcher.distribution.watcher.NewUrlWatcher;
import com.thenetcircle.comsumerdispatcher.distribution.watcher.QueuePurgeWatcher;
import com.thenetcircle.comsumerdispatcher.job.JobExecutor;
import com.thenetcircle.comsumerdispatcher.job.exception.JobFailedException;
import com.thenetcircle.comsumerdispatcher.job.exception.JobStopException; | package com.thenetcircle.comsumerdispatcher.thread;
public class ConsumerJobExecutorPool implements ConsumerJobExecutorPoolMBean {
private static Log _logger = LogFactory.getLog(ConsumerJobExecutorPool.class);
private final ObjectName mbeanName;
private final NamedThreadFactory threadFactory;
private final JobExecutor job;
private final HashSet<Worker> workers = new HashSet<Worker>();
protected final AtomicInteger completeTaskCount = new AtomicInteger(0);
private final AtomicInteger activeExecutorCount = new AtomicInteger(0);
private final AtomicBoolean logErrorJobToFile = new AtomicBoolean(false);
private IJobPoolLevelWatcher purgeWatcher, countChangedWatcher, urlChangedWatcher;
public ConsumerJobExecutorPool(JobExecutor job) {
String jmxType = job.getQueue() + "_" + job.getFetcherQConf().getHost() + "_" + job.getFetcherQConf().getVhost();
this.job = job;
threadFactory = new NamedThreadFactory(jmxType);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try
{
URL url = new URL(job.getUrl());
String domain = url.getHost();
Hashtable<String, String> kv = new Hashtable<String, String>();
kv.put("queue", job.getQueue());
kv.put("q_host", job.getFetcherQConf().getHost());
kv.put("q_vhost", job.getFetcherQConf().getVhost());
mbeanName = new ObjectName(domain, kv);
mbs.registerMBean(this, new ObjectName(domain, kv));
//watchers | purgeWatcher = new QueuePurgeWatcher(); | 3 |
onyxbits/TradeTrax | src/main/java/de/onyxbits/tradetrax/pages/edit/VariantEditor.java | [
"@Entity\n@Table(name = \"stock\")\npublic class Stock implements Serializable {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Row index\n\t */\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate long id;\n\n\t/**\n\t * Optional storage location identifier (free form text)\n\t */\n\t@Column(name = \"location\")\n\tprivate String location;\n\n\t/**\n\t * Optional comment (free form text).\n\t */\n\t@Column(name = \"comment\")\n\tprivate String comment;\n\n\t/**\n\t * How much a single unit cost when buying it\n\t */\n\t@Column(name = \"buyprice\")\n\tprivate long buyPrice;\n\n\t/**\n\t * How much a single unit return when selling it.\n\t */\n\t@Column(name = \"sellprice\")\n\tprivate long sellPrice;\n\n\t/**\n\t * How many individual items are in this stack? Stacks may only be sold as a\n\t * whole. In case a partial amount is to be sold, the Asset must be split into\n\t * smaller stacks first.\n\t * <p>\n\t * Any integer number is valid. A value of zero might mean the user is\n\t * tracking stock in refillable bins, a negative value might represent stock\n\t * that was bought on margins.\n\t */\n\t@Column(name = \"stacksize\")\n\tprivate int unitCount = 1;\n\n\t/**\n\t * Human readable name of the asset\n\t */\n\t@ManyToOne(cascade = { CascadeType.ALL })\n\tprivate Name name;\n\n\t/**\n\t * Subtype (e.g. if the asset is available in multiple colors).\n\t */\n\t@ManyToOne(cascade = CascadeType.ALL)\n\tprivate Variant variant;\n\n\t/**\n\t * Timestamp: when the asset was bought.\n\t */\n\t@Column\n\t@Type(type = \"timestamp\")\n\tprivate Date acquired;\n\n\t/**\n\t * Timestamp: when the asset was sold\n\t */\n\t@Column\n\t@Type(type = \"timestamp\")\n\tprivate Date liquidated;\n\n\tpublic Stock() {\n\t}\n\n\t/**\n\t * Create a stock using a template\n\t */\n\tpublic Stock(Stock template) {\n\t\tacquired = template.acquired;\n\t\tbuyPrice = template.buyPrice;\n\t\tcomment = template.comment;\n\t\tid = template.id;\n\t\tliquidated = template.liquidated;\n\t\tif (template.name != null) {\n\t\t\tname = new Name();\n\t\t\tname.setId(template.name.getId());\n\t\t\tname.setLabel(template.name.getLabel());\n\t\t}\n\t\tsellPrice = template.sellPrice;\n\t\tunitCount = template.unitCount;\n\t\tlocation = template.location;\n\t\tif (template.variant != null) {\n\t\t\tvariant = new Variant();\n\t\t\tvariant.setId(template.variant.getId());\n\t\t\tvariant.setLabel(template.variant.getLabel());\n\t\t}\n\t}\n\n\t/**\n\t * Split a new Stock off from this one.\n\t * \n\t * @param amount\n\t * number of units to transfer to the split off stock\n\t * @return a new instance with the specified number of units.\n\t */\n\tpublic Stock splitStock(int amount) {\n\t\tStock ret = new Stock();\n\t\tif (acquired != null) {\n\t\t\tret.acquired = (Date) acquired.clone();\n\t\t}\n\t\tret.buyPrice = buyPrice;\n\n\t\tif (liquidated != null) {\n\t\t\tret.liquidated = (Date) liquidated.clone();\n\t\t}\n\t\tret.name = name;\n\t\tret.sellPrice = sellPrice;\n\t\tret.variant = variant;\n\t\tret.unitCount = amount;\n\t\tunitCount -= amount;\n\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Create the criteria for finding other stock items that are allowed to merge\n\t * with this one. Two items may merge if they only differ in comment,\n\t * unitcount and acquisition/liquidation date (but they need to be in the same\n\t * state of acquisition/liquidation).\n\t * \n\t * @return Hibernate criterias\n\t */\n\tpublic List<Criterion> allowedToMergeWith() {\n\t\tVector<Criterion> ret = new Vector<Criterion>();\n\t\tret.add(Restrictions.ne(\"id\", id));\n\t\tret.add(Restrictions.eq(\"buyPrice\", buyPrice));\n\t\tret.add(Restrictions.eq(\"sellPrice\", sellPrice));\n\n\t\tif (name == null) {\n\t\t\t// This should never happen\n\t\t\tret.add(Restrictions.isNull(\"name\"));\n\t\t}\n\t\telse {\n\t\t\tret.add(Restrictions.eq(\"name.id\", name.getId()));\n\t\t}\n\t\tif (variant == null) {\n\t\t\tret.add(Restrictions.isNull(\"variant\"));\n\t\t}\n\t\telse {\n\t\t\tret.add(Restrictions.eq(\"variant.id\", variant.getId()));\n\t\t}\n\t\tif (acquired == null) {\n\t\t\tret.add(Restrictions.isNull(\"acquired\"));\n\t\t}\n\t\telse {\n\t\t\tret.add(Restrictions.isNotNull(\"acquired\"));\n\t\t}\n\t\tif (liquidated == null) {\n\t\t\tret.add(Restrictions.isNull(\"liquidated\"));\n\t\t}\n\t\telse {\n\t\t\tret.add(Restrictions.isNotNull(\"liquidated\"));\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Calculate the profit, disregarding of whether the asset has been acquired\n\t * and liquidated.\n\t * \n\t * @return the profit in database format.\n\t */\n\tpublic long calcProfit() {\n\t\treturn (sellPrice - buyPrice) * unitCount;\n\t}\n\n\t/**\n\t * Calculate the total aquisition cost, disregarding whether or not the asset\n\t * has been acquired.\n\t * \n\t * @return buyprice times unitcount\n\t */\n\tpublic long calcTotalCost() {\n\t\treturn buyPrice * unitCount;\n\t}\n\n\t/**\n\t * Calculate the total returns, disregarding whetehr or not the asset has been\n\t * liquidated.\n\t * \n\t * @return sellprice times unit\n\t */\n\tpublic long calcTotalReturns() {\n\t\treturn sellPrice * unitCount;\n\t}\n\n\t/**\n\t * Calculate the financial impact of the stock in its current state on the\n\t * owner's wallet.\n\t * \n\t * @return the balance in database format.\n\t */\n\tpublic long calcBalance() {\n\t\tlong bal = 0;\n\t\tif (liquidated != null) {\n\t\t\tbal = sellPrice * unitCount;\n\t\t}\n\t\tif (acquired != null) {\n\t\t\tbal -= buyPrice * unitCount;\n\t\t}\n\t\treturn bal;\n\t}\n\n\t/**\n\t * @return the comment\n\t */\n\tpublic String getComment() {\n\t\treturn comment;\n\t}\n\n\t/**\n\t * @param comment\n\t * the comment to set\n\t */\n\tpublic void setComment(String comment) {\n\t\tthis.comment = comment;\n\t}\n\n\t/**\n\t * @return the id\n\t */\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id\n\t * the id to set\n\t */\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the buyPrice\n\t */\n\tpublic long getBuyPrice() {\n\t\treturn buyPrice;\n\t}\n\n\t/**\n\t * @param buyPrice\n\t * the buyPrice to set\n\t */\n\tpublic void setBuyPrice(long buyPrice) {\n\t\tthis.buyPrice = buyPrice;\n\t}\n\n\t/**\n\t * @return the sellPrice\n\t */\n\tpublic long getSellPrice() {\n\t\treturn sellPrice;\n\t}\n\n\t/**\n\t * @param sellPrice\n\t * the sellPrice to set\n\t */\n\tpublic void setSellPrice(long sellPrice) {\n\t\tthis.sellPrice = sellPrice;\n\t}\n\n\t/**\n\t * @return the unitCount\n\t */\n\tpublic int getUnitCount() {\n\t\treturn unitCount;\n\t}\n\n\t/**\n\t * @param unitCount\n\t * the unitCount to set\n\t */\n\tpublic void setUnitCount(int unitCount) {\n\t\tthis.unitCount = unitCount;\n\t}\n\n\t/**\n\t * @return the name\n\t */\n\tpublic Name getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * @param name\n\t * the name to set\n\t */\n\tpublic void setName(Name name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * @return the variant\n\t */\n\tpublic Variant getVariant() {\n\t\treturn variant;\n\t}\n\n\t/**\n\t * @param variant\n\t * the variant to set\n\t */\n\tpublic void setVariant(Variant variant) {\n\t\tthis.variant = variant;\n\t}\n\n\t/**\n\t * @return the aquired\n\t */\n\tpublic Date getAcquired() {\n\t\treturn acquired;\n\t}\n\n\t/**\n\t * @param aquired\n\t * the aquired to set\n\t */\n\tpublic void setAcquired(Date aquired) {\n\t\tthis.acquired = aquired;\n\t}\n\n\t/**\n\t * @return the liquidated\n\t */\n\tpublic Date getLiquidated() {\n\t\treturn liquidated;\n\t}\n\n\t/**\n\t * @param liquidated\n\t * the liquidated to set\n\t */\n\tpublic void setLiquidated(Date liquidated) {\n\t\tthis.liquidated = liquidated;\n\t}\n\n\t/**\n\t * @return the location\n\t */\n\tpublic String getLocation() {\n\t\treturn location;\n\t}\n\n\t/**\n\t * @param location\n\t * the location to set\n\t */\n\tpublic void setLocation(String location) {\n\t\tthis.location = location;\n\t}\n}",
"@Entity\n@Table(name = \"variant\")\npublic class Variant implements Serializable{\n\t\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Row index\n\t */\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @NonVisual\n private Long id;\n \n /**\n * Human readable value.\n */\n @Column(name = \"label\", unique=true)\n @Validate(\"required\")\n private String label;\n \n\t/**\n\t * @return the id\n\t */\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id the id to set\n\t */\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the value\n\t */\n\tpublic String getLabel() {\n\t\treturn label;\n\t}\n\n\t/**\n\t * @param value the value to set\n\t */\n\tpublic void setLabel(String label) {\n\t\tthis.label = label;\n\t}\n\n}",
"@Import(library = \"context:js/mousetrap.min.js\")\npublic class Index {\n\n\t@SessionAttribute(Layout.FOCUSID)\n\tprivate long focusedStockId;\n\n\t@Property\n\tprivate DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);\n\n\t@Inject\n\tprivate Session session;\n\n\t@Inject\n\tprivate Messages messages;\n\n\t@Inject\n\tprivate BeanModelSource ledgerSource;\n\n\t@Property\n\t@Validate(\"required,minlength=3\")\n\tprivate String buyName;\n\n\t@Property\n\tprivate String buyVariant;\n\n\t@Property\n\tprivate String buyCost;\n\n\t@Property\n\tprivate String buyReturns;\n\n\t@Property\n\tprivate String buyLocation;\n\n\t@Property\n\tprivate int buyAmount = 1;\n\n\t@Property\n\tprivate StockPagedGridDataSource stocks;\n\n\t@Property\n\tprivate Stock row;\n\n\t@Component(id = \"buyform\")\n\tprivate Form buyForm;\n\n\t@Component(id = \"buyName\")\n\tprivate TextField buyNameField;\n\n\t@Component(id = \"buyVariant\")\n\tprivate TextField buyVariantField;\n\n\t@Component(id = \"buyAmount\")\n\tprivate TextField buyAmountField;\n\n\t@Component(id = \"buyCost\")\n\tprivate TextField buyCostField;\n\n\t@Component(id = \"buyReturns\")\n\tprivate TextField buyReturnsField;\n\n\t@Component(id = \"buyLocation\")\n\tprivate TextField buyLocationFiels;\n\n\t@Component(id = \"ledger\")\n\tprivate Grid ledger;\n\n\t@Component(id = \"filterForm\")\n\tprivate Form filterForm;\n\n\t@Component(id = \"reset\")\n\tprivate Submit reset;\n\n\t@Persist\n\t@Property\n\tprivate String filterName;\n\n\t@Persist\n\t@Property\n\tprivate String filterLocation;\n\n\t@Component(id = \"filterLocation\")\n\tprivate TextField filterLocationField;\n\n\t@Persist\n\t@Property\n\tprivate String filterComment;\n\n\t@Component(id = \"filterComment\")\n\tprivate TextField filterCommentField;\n\n\t@Component(id = \"filterName\")\n\tprivate TextField filterNameField;\n\n\t@Persist\n\t@Property\n\tprivate String filterVariant;\n\n\t@Component(id = \"filterVariant\")\n\tprivate TextField filterVariantField;\n\n\t@Persist\n\t@Property\n\tprivate StockState filterState;\n\n\t@Component(id = \"filterState\")\n\tprivate Select filterStateField;\n\n\t@Persist\n\t@Property\n\tprivate Date filterAcquisition;\n\n\t@Component(id = \"filterAcquisition\")\n\tprivate DateField filterAcquisitionField;\n\n\t@Persist\n\t@Validate(\"required\")\n\t@Property\n\tprivate TimeSpan filterAcquisitionSpan;\n\n\t@Component(id = \"filterAcquisitionSpan\")\n\tprivate Select filterAcquisitionSpanField;\n\n\t@Persist\n\t@Property\n\tprivate Date filterLiquidation;\n\n\t@Component(id = \"filterLiquidation\")\n\tprivate DateField filterLiquidationField;\n\n\t@Persist\n\t@Validate(\"required\")\n\t@Property\n\tprivate TimeSpan filterLiquidationSpan;\n\n\t@Component(id = \"filterLiquidationSpan\")\n\tprivate Select filterLiquidationSpanField;\n\n\t@Inject\n\tprivate SettingsStore settingsStore;\n\n\t@Inject\n\tprivate EventLogger eventLogger;\n\n\t@Inject\n\tprivate MoneyRepresentation moneyRepresentation;\n\n\t@Property\n\tprivate String matches;\n\n\t@Inject\n\tprivate Block acquisitionblock;\n\n\t@Inject\n\tprivate Block filterblock;\n\n\t@InjectComponent\n\tprivate Zone flipview;\n\n\t@Property\n\t@Persist\n\tprivate boolean showFilterForm;\n\n\t@Property\n\tprivate long matchingItemCount;\n\n\t@Property\n\t@Persist\n\tprivate boolean autofocusBuyForm;\n\n\t@Property\n\tprivate int matchingAssetCount;\n\n\t@Inject\n\tprivate JavaScriptSupport javaScriptSupport;\n\n\tpublic String styleFor(String tag) {\n\t\tString tmp = settingsStore.get(SettingsStore.TCACFIELDS, AcquisitionFields.DEFAULT);\n\t\tif (!tmp.contains(tag)) {\n\t\t\treturn \"display:none;\";\n\t\t}\n\t\treturn \"\";\n\t}\n\n\tpublic Block getActiveForm() {\n\t\tif (showFilterForm) {\n\t\t\treturn filterblock;\n\t\t}\n\t\telse {\n\t\t\treturn acquisitionblock;\n\t\t}\n\t}\n\n\tpublic void setupRender() {\n\t\tstocks = new StockPagedGridDataSource(session).withName(filterName).withVariant(filterVariant)\n\t\t\t\t.withState(filterState).withLocation(filterLocation).withComment(filterComment)\n\t\t\t\t.withAcquisition(filterAcquisition, filterAcquisitionSpan)\n\t\t\t\t.withLiquidation(filterLiquidation, filterLiquidationSpan);\n\t\tmatchingAssetCount = stocks.getAvailableRows();\n\t\tmatchingItemCount = stocks.getItemCount();\n\t}\n\n\tpublic void afterRender() {\n\t\tautofocusBuyForm = false;\n\n\t\t// Let the Escape key toggle the forms. It is slightly messy to do it this\n\t\t// way. Using getElementById() would be preferable, but the id is assigned\n\t\t// dynamically.\n\t\tjavaScriptSupport\n\t\t\t\t.addScript(\"Mousetrap.prototype.stopCallback = function(e, element) {return false;};\");\n\t\tjavaScriptSupport\n\t\t\t\t.addScript(\"Mousetrap.bind('esc', function() {document.getElementsByClassName('formtoggler')[0].click();});\");\n\t}\n\n\tpublic BeanModel<Object> getLedgerModel() {\n\t\tBeanModel<Object> model = ledgerSource.createDisplayModel(Object.class, messages);\n\t\tList<LedgerColumns> tmp = LedgerColumns.fromCsv(settingsStore.get(SettingsStore.TCLCOLUMNS,\n\t\t\t\tLedgerColumns.DEFAULT));\n\t\tfor (LedgerColumns col : tmp) {\n\t\t\tmodel.addEmpty(col.getName()).sortable(\n\t\t\t\t\tLedgerColumns.BUYPRICE.getName().equals(col.getName())\n\t\t\t\t\t\t\t|| LedgerColumns.SELLPRICE.getName().equals(col.getName())\n\t\t\t\t\t\t\t|| LedgerColumns.LIQUIDATED.getName().equals(col.getName())\n\t\t\t\t\t\t\t|| LedgerColumns.ACQUIRED.getName().equals(col.getName()));\n\t\t}\n\t\treturn model;\n\t}\n\n\tpublic List<String> onProvideCompletionsFromBuyVariant(String partial) {\n\t\treturn IdentUtil.suggestVariants(session, partial);\n\t}\n\n\tpublic List<String> onProvideCompletionsFromBuyName(String partial) {\n\t\treturn IdentUtil.suggestNames(session, partial);\n\t}\n\n\tpublic void onValidateFromBuyForm() {\n\t\ttry {\n\t\t\tmoneyRepresentation.userToDatabase(buyCost, 1);\n\t\t}\n\t\tcatch (ParseException e) {\n\t\t\tbuyForm.recordError(buyCostField, messages.get(\"invalid-numberformat\"));\n\t\t}\n\t\ttry {\n\t\t\tmoneyRepresentation.userToDatabase(buyReturns, 1);\n\t\t}\n\t\tcatch (ParseException e) {\n\t\t\tbuyForm.recordError(buyReturnsField, messages.get(\"invalid-numberformat\"));\n\t\t}\n\t}\n\n\tpublic Object onToggleForm() {\n\t\tshowFilterForm = !showFilterForm;\n\t\treturn flipview;\n\t}\n\n\t@CommitAfter\n\tpublic Object onSuccessFromBuyForm() {\n\t\tStock item = new Stock();\n\n\t\titem.setName(IdentUtil.findName(session, buyName));\n\t\titem.setVariant(IdentUtil.findVariant(session, buyVariant));\n\t\ttry {\n\t\t\titem.setBuyPrice(moneyRepresentation.userToDatabase(buyCost, 1));\n\t\t\titem.setSellPrice(moneyRepresentation.userToDatabase(buyReturns, 1));\n\t\t}\n\t\tcatch (ParseException e) {\n\t\t\t// We already validated this\n\t\t}\n\t\tCalendar now = Calendar.getInstance();\n\t\tnow.set(Calendar.MILLISECOND, 0);\n\t\tnow.set(Calendar.SECOND, 0);\n\t\tnow.set(Calendar.MINUTE, 0);\n\t\tnow.set(Calendar.HOUR_OF_DAY, 0);\n\n\t\titem.setLocation(buyLocation);\n\t\titem.setUnitCount(buyAmount);\n\t\titem.setAcquired(now.getTime());\n\t\tsession.persist(item);\n\t\tfocusedStockId = item.getId();\n\t\teventLogger.acquired(item);\n\t\twithNoFilters();\n\t\tledger.reset();\n\t\tautofocusBuyForm = true;\n\t\treturn Index.class;\n\t}\n\n\tpublic void onSelectedFromReset() {\n\t\t// Reset button event -> return all values to their defaults...\n\t\tfilterName = null;\n\t\tfilterState = null;\n\t\tfilterVariant = null;\n\t\tfilterAcquisition = null;\n\t\tfilterLiquidation = null;\n\t\tfilterLocation = null;\n\t\tfilterComment = null;\n\t\tledger.reset();\n\t\t// ... then just fall through to the success action.\n\t}\n\n\tpublic Object onSuccessFromFilterForm() {\n\t\treturn Index.class;\n\t}\n\n\tpublic Index withNoFilters() {\n\t\tfilterName = null;\n\t\tfilterState = null;\n\t\tfilterVariant = null;\n\t\tfilterAcquisition = null;\n\t\tfilterLiquidation = null;\n\t\tfilterLocation = null;\n\t\tfilterComment = null;\n\t\tshowFilterForm = false;\n\t\treturn this;\n\t}\n\n\tpublic Index withFilterName(String name) {\n\t\tthis.filterName = name;\n\t\tshowFilterForm = true;\n\t\treturn this;\n\t}\n\n\tpublic Index withFilterVariant(String name) {\n\t\tthis.filterVariant = name;\n\t\tshowFilterForm = true;\n\t\treturn this;\n\t}\n\n\tpublic String hasFilterName() {\n\t\treturn filterName;\n\t}\n\n\tpublic String hasFilterVariant() {\n\t\treturn filterVariant;\n\t}\n\n}",
"public class LabelManager {\n\n\t@Inject\n\tprivate Session session;\n\t\n\t@Inject\n\tprivate AlertManager alertManager;\n\t\n\t@Inject\n\tprivate Messages messages;\n\n\t@Inject\n\tprivate EventLogger eventLogger;\n\n\t@Property\n\tprivate Name name;\n\n\t@Property\n\tprivate Variant variant;\n\n\t@Property\n\tprivate LabelActions actions;\n\n\t@Property\n\tprivate boolean applyToNames;\n\n\t@Property\n\tprivate boolean applyToVariants;\n\n\t@Component(id = \"applyToNames\")\n\tprivate Checkbox applyToNamesField;\n\n\t@Component(id = \"applyToVariants\")\n\tprivate Checkbox applyToVariantsField;\n\n\t@Component(id = \"actionForm\")\n\tprivate Form actionForm;\n\n\t@Property\n\tprivate int affected;\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Name> getNames() {\n\t\treturn session.createCriteria(Name.class).addOrder(Order.asc(\"label\")).list();\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Variant> getVariants() {\n\t\treturn session.createCriteria(Variant.class).addOrder(Order.asc(\"label\")).list();\n\t}\n\n\tpublic void setupRender() {\n\t\taffected=0;\n\t}\n\n\t@CommitAfter\n\tpublic LabelManager onSuccessFromActionForm() {\n\t\tif (actions == LabelActions.TRIM) {\n\t\t\ttrimLabels();\n\t\t\talertManager.alert(Duration.SINGLE,Severity.INFO,messages.format(\"deleted\",affected));\n\t\t}\n\t\telse {\n\t\t\tsanitizeLabels();\n\t\t\talertManager.alert(Duration.SINGLE,Severity.INFO,messages.format(\"updated\",affected));\n\t\t}\n\t\treturn this;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void sanitizeLabels() {\n\t\tif (applyToNames) {\n\t\t\tList<Name> lst = session.createCriteria(Name.class).list();\n\t\t\tfor (Name n : lst) {\n\t\t\t\tswitch (actions) {\n\t\t\t\t\tcase UPPERCASE: {\n\t\t\t\t\t\tString s = n.getLabel().toUpperCase().trim();\n\t\t\t\t\t\tif (!s.equals(n.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(n.getLabel(), s);\n\t\t\t\t\t\t\tn.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase LOWERCASE: {\n\t\t\t\t\t\tString s = n.getLabel().toLowerCase().trim();\n\t\t\t\t\t\tif (!s.equals(n.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(n.getLabel(), s);\n\t\t\t\t\t\t\tn.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase CAPITALIZE: {\n\t\t\t\t\t\tString s = n.getLabel().toLowerCase().trim();\n\t\t\t\t\t\tif (s.length() >= 1) {\n\t\t\t\t\t\t\ts = Character.toUpperCase(s.charAt(0)) + s.substring(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!s.equals(n.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(n.getLabel(), s);\n\t\t\t\t\t\t\tn.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsession.update(n);\n\t\t\t}\n\t\t}\n\t\tif (applyToVariants) {\n\t\t\tList<Variant> lst = session.createCriteria(Variant.class).list();\n\t\t\tfor (Variant v : lst) {\n\t\t\t\tswitch (actions) {\n\t\t\t\t\tcase UPPERCASE: {\n\t\t\t\t\t\tString s = v.getLabel().toUpperCase().trim();\n\t\t\t\t\t\tif (!s.equals(v.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(v.getLabel(), s);\n\t\t\t\t\t\t\tv.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase LOWERCASE: {\n\t\t\t\t\t\tString s = v.getLabel().toLowerCase().trim();\n\t\t\t\t\t\tif (!s.equals(v.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(v.getLabel(), s);\n\t\t\t\t\t\t\tv.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase CAPITALIZE: {\n\t\t\t\t\t\tString s = v.getLabel().toLowerCase().trim();\n\t\t\t\t\t\tif (s.length() >= 1) {\n\t\t\t\t\t\t\ts = Character.toUpperCase(s.charAt(0)) + s.substring(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!s.equals(v.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(v.getLabel(), s);\n\t\t\t\t\t\t\tv.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsession.update(v);\n\t\t\t}\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void trimLabels() {\n\t\t// Yes, this is super inefficient, but these tables are not that big\n\t\tif (applyToNames) {\n\t\t\tList<Name> lst = session.createCriteria(Name.class).list();\n\t\t\tfor (Name n : lst) {\n\t\t\t\tlong count = (Long) session.createCriteria(Stock.class)\n\t\t\t\t\t\t.add(Restrictions.eq(\"name.id\", n.getId())).setProjection(Projections.rowCount())\n\t\t\t\t\t\t.uniqueResult();\n\t\t\t\tif (count < 1) {\n\t\t\t\t\tsession.delete(n);\n\t\t\t\t\teventLogger.deleted(n.getLabel());\n\t\t\t\t\taffected++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (applyToVariants) {\n\t\t\tList<Variant> lst = session.createCriteria(Variant.class).list();\n\t\t\tfor (Variant v : lst) {\n\t\t\t\tlong count = (Long) session.createCriteria(Stock.class)\n\t\t\t\t\t\t.add(Restrictions.eq(\"variant.id\", v.getId())).setProjection(Projections.rowCount())\n\t\t\t\t\t\t.uniqueResult();\n\t\t\t\tif (count < 1) {\n\t\t\t\t\tsession.delete(v);\n\t\t\t\t\teventLogger.deleted(v.getLabel());\n\t\t\t\t\taffected++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"public interface EventLogger {\n\n\t/**\n\t * Call this after selling off an asset.\n\t * \n\t * @param stock\n\t * the stock after saving it to the database.\n\t */\n\tpublic void liquidated(Stock stock);\n\n\t/**\n\t * Call this after acquiring an asset.\n\t * \n\t * @param stock\n\t * the stock after saving it to the database\n\t */\n\tpublic void acquired(Stock stock);\n\n\t/**\n\t * Call this after splitting a stock in two.\n\t * \n\t * @param parent\n\t * the stock from which units were split off (after saving it to the\n\t * database)\n\t * @param offspring\n\t * the newly created stock (after saving it to the database).\n\t */\n\tpublic void split(Stock parent, Stock offspring);\n\n\t/**\n\t * Call this after merging two assets\n\t * \n\t * @param accumulator\n\t * the stock into which was merged ( after being saved to the\n\t * database).\n\t * @param collected\n\t * the stock that was assimilated (after being saved to the\n\t * database).\n\t */\n\tpublic void merged(Stock accumulator, Stock collected);\n\n\t/**\n\t * Call this after a deleting a stock from the ledger\n\t * \n\t * @param stock\n\t * the stock after it has been deleted.\n\t */\n\tpublic void deleted(Stock stock);\n\n\t/**\n\t * Call this after the user edited a stock\n\t * \n\t * @param orig\n\t * the original state of the stock.\n\t */\n\tpublic void modified(Stock orig);\n\n\t/**\n\t * Rename a label\n\t * \n\t * @param orig\n\t * old name\n\t * @param now\n\t * new name\n\t */\n\tpublic void rename(String orig, String now);\n\n\t/**\n\t * Delete a label\n\t * \n\t * @param name\n\t * the label to delete\n\t */\n\tpublic void deleted(String name);\n\n\t/**\n\t * Create a filter expression for finding log entries that concern a specific\n\t * stock item.\n\t * \n\t * @param stock\n\t * the stock to search the log for\n\t * @return a string for grepping in the details messages.\n\t */\n\tpublic String grep(Stock stock);\n\n}"
] | import java.util.List;
import org.apache.tapestry5.alerts.AlertManager;
import org.apache.tapestry5.alerts.Duration;
import org.apache.tapestry5.alerts.Severity;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.Validate;
import org.apache.tapestry5.corelib.components.EventLink;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import de.onyxbits.tradetrax.entities.Stock;
import de.onyxbits.tradetrax.entities.Variant;
import de.onyxbits.tradetrax.pages.Index;
import de.onyxbits.tradetrax.pages.tools.LabelManager;
import de.onyxbits.tradetrax.services.EventLogger; | package de.onyxbits.tradetrax.pages.edit;
@Import(library = "context:js/mousetrap.min.js")
public class VariantEditor {
@Property
private long variantId;
@Property
@Validate("required")
private String name;
@Property
private String status;
@Component(id = "nameField")
private TextField nameField;
@Component(id = "editForm")
private Form form;
@Inject
private Session session;
@Inject | private EventLogger eventLogger; | 4 |
loganj/foursquared | main/src/com/joelapenna/foursquared/VenueActivity.java | [
"public class Tip implements FoursquareType, Parcelable {\n\n private String mCreated;\n private String mDistance;\n private String mId;\n private String mText;\n private User mUser;\n private Venue mVenue;\n\n public Tip() {\n }\n\n private Tip(Parcel in) {\n mCreated = ParcelUtils.readStringFromParcel(in);\n mDistance = ParcelUtils.readStringFromParcel(in);\n mId = ParcelUtils.readStringFromParcel(in);\n mText = ParcelUtils.readStringFromParcel(in);\n \n if (in.readInt() == 1) {\n mUser = in.readParcelable(User.class.getClassLoader());\n }\n \n if (in.readInt() == 1) {\n mUser = in.readParcelable(Venue.class.getClassLoader());\n }\n }\n \n public static final Parcelable.Creator<Tip> CREATOR = new Parcelable.Creator<Tip>() {\n public Tip createFromParcel(Parcel in) {\n return new Tip(in);\n }\n\n @Override\n public Tip[] newArray(int size) {\n return new Tip[size];\n }\n };\n \n public String getCreated() {\n return mCreated;\n }\n\n public void setCreated(String created) {\n mCreated = created;\n }\n\n public String getDistance() {\n return mDistance;\n }\n\n public void setDistance(String distance) {\n mDistance = distance;\n }\n\n public String getId() {\n return mId;\n }\n\n public void setId(String id) {\n mId = id;\n }\n\n public String getText() {\n return mText;\n }\n\n public void setText(String text) {\n mText = text;\n }\n\n public User getUser() {\n return mUser;\n }\n\n public void setUser(User user) {\n mUser = user;\n }\n\n public Venue getVenue() {\n return mVenue;\n }\n\n public void setVenue(Venue venue) {\n mVenue = venue;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n ParcelUtils.writeStringToParcel(out, mCreated);\n ParcelUtils.writeStringToParcel(out, mDistance);\n ParcelUtils.writeStringToParcel(out, mId);\n ParcelUtils.writeStringToParcel(out, mText);\n \n if (mUser != null) {\n out.writeInt(1); \n out.writeParcelable(mUser, flags);\n } else {\n out.writeInt(0);\n }\n \n if (mVenue != null) {\n out.writeInt(1);\n out.writeParcelable(mVenue, flags);\n } else {\n out.writeInt(0);\n }\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n}",
"public class Venue implements FoursquareType, Parcelable {\n\n private String mAddress;\n private Group<Checkin> mCheckins;\n private String mCity;\n private String mCityid;\n private String mCrossstreet;\n private String mDistance;\n private String mGeolat;\n private String mGeolong;\n private String mId;\n private String mName;\n private String mPhone;\n private Group<Special> mSpecials;\n private String mState;\n private Stats mStats;\n private Tags mTags;\n private Group<Tip> mTips;\n private Group<Tip> mTodos;\n private String mTwitter;\n private String mZip;\n private Category mCategory;\n\n public Venue() {\n }\n\n private Venue(Parcel in) {\n mAddress = ParcelUtils.readStringFromParcel(in);\n mCity = ParcelUtils.readStringFromParcel(in);\n mCityid = ParcelUtils.readStringFromParcel(in);\n mCrossstreet = ParcelUtils.readStringFromParcel(in);\n mDistance = ParcelUtils.readStringFromParcel(in);\n mGeolat = ParcelUtils.readStringFromParcel(in);\n mGeolong = ParcelUtils.readStringFromParcel(in);\n mId = ParcelUtils.readStringFromParcel(in);\n mName = ParcelUtils.readStringFromParcel(in);\n mPhone = ParcelUtils.readStringFromParcel(in);\n mState = ParcelUtils.readStringFromParcel(in);\n mTwitter = ParcelUtils.readStringFromParcel(in);\n mZip = ParcelUtils.readStringFromParcel(in);\n\n mCheckins = new Group<Checkin>();\n int numCheckins = in.readInt();\n for (int i = 0; i < numCheckins; i++) {\n Checkin checkin = in.readParcelable(Checkin.class.getClassLoader());\n mCheckins.add(checkin); \n }\n \n int numSpecials = in.readInt();\n if (numSpecials > 0) {\n mSpecials = new Group<Special>();\n for (int i = 0; i < numSpecials; i++) {\n Special special = in.readParcelable(Special.class.getClassLoader());\n mSpecials.add(special);\n }\n }\n \n if (in.readInt() == 1) {\n mStats = in.readParcelable(Stats.class.getClassLoader());\n }\n \n mTags = new Tags();\n int numTags = in.readInt();\n for (int i = 0; i < numTags; i++) {\n String tag = in.readString();\n mTags.add(tag);\n }\n \n mTips = new Group<Tip>();\n int numTips = in.readInt();\n for (int i = 0; i < numTips; i++) {\n Tip tip = in.readParcelable(Tip.class.getClassLoader());\n mTips.add(tip);\n }\n\n mTodos = new Group<Tip>();\n int numTodos = in.readInt();\n for (int i = 0; i < numTodos; i++) {\n Tip todo = in.readParcelable(Tip.class.getClassLoader());\n mTodos.add(todo);\n }\n\n if (in.readInt() == 1) {\n mCategory = in.readParcelable(Category.class.getClassLoader());\n }\n }\n \n public static final Parcelable.Creator<Venue> CREATOR = new Parcelable.Creator<Venue>() {\n public Venue createFromParcel(Parcel in) {\n return new Venue(in);\n }\n\n @Override\n public Venue[] newArray(int size) {\n return new Venue[size];\n }\n };\n \n public String getAddress() {\n return mAddress;\n }\n\n public void setAddress(String address) {\n mAddress = address;\n }\n\n public Group<Checkin> getCheckins() {\n return mCheckins;\n }\n\n public void setCheckins(Group<Checkin> checkins) {\n mCheckins = checkins;\n }\n\n public String getCity() {\n return mCity;\n }\n\n public void setCity(String city) {\n mCity = city;\n }\n\n public String getCityid() {\n return mCityid;\n }\n\n public void setCityid(String cityid) {\n mCityid = cityid;\n }\n\n public String getCrossstreet() {\n return mCrossstreet;\n }\n\n public void setCrossstreet(String crossstreet) {\n mCrossstreet = crossstreet;\n }\n\n public String getDistance() {\n return mDistance;\n }\n\n public void setDistance(String distance) {\n mDistance = distance;\n }\n\n public String getGeolat() {\n return mGeolat;\n }\n\n public void setGeolat(String geolat) {\n mGeolat = geolat;\n }\n\n public String getGeolong() {\n return mGeolong;\n }\n\n public void setGeolong(String geolong) {\n mGeolong = geolong;\n }\n\n public String getId() {\n return mId;\n }\n\n public void setId(String id) {\n mId = id;\n }\n\n public String getName() {\n return mName;\n }\n\n public void setName(String name) {\n mName = name;\n }\n\n public String getPhone() {\n return mPhone;\n }\n\n public void setPhone(String phone) {\n mPhone = phone;\n }\n \n public Group<Special> getSpecials() {\n return mSpecials;\n }\n\n public void setSpecials(Group<Special> specials) {\n mSpecials = specials;\n }\n \n public String getState() {\n return mState;\n }\n\n public void setState(String state) {\n mState = state;\n }\n\n public Stats getStats() {\n return mStats;\n }\n\n public void setStats(Stats stats) {\n mStats = stats;\n }\n\n public Tags getTags() {\n return mTags;\n }\n\n public void setTags(Tags tags) {\n mTags = tags;\n }\n\n public Group<Tip> getTips() {\n return mTips;\n }\n\n public void setTips(Group<Tip> tips) {\n mTips = tips;\n }\n\n public Group<Tip> getTodos() {\n return mTodos;\n }\n\n public void setTodos(Group<Tip> todos) {\n mTodos = todos;\n }\n\n public String getTwitter() {\n return mTwitter;\n }\n\n public void setTwitter(String twitter) {\n mTwitter = twitter;\n }\n\n public String getZip() {\n return mZip;\n }\n\n public void setZip(String zip) {\n mZip = zip;\n }\n\n public Category getCategory() {\n return mCategory;\n }\n \n public void setCategory(Category category) {\n mCategory = category;\n }\n \n \n @Override\n public void writeToParcel(Parcel out, int flags) {\n ParcelUtils.writeStringToParcel(out, mAddress);\n ParcelUtils.writeStringToParcel(out, mCity);\n ParcelUtils.writeStringToParcel(out, mCityid);\n ParcelUtils.writeStringToParcel(out, mCrossstreet);\n ParcelUtils.writeStringToParcel(out, mDistance);\n ParcelUtils.writeStringToParcel(out, mGeolat);\n ParcelUtils.writeStringToParcel(out, mGeolong);\n ParcelUtils.writeStringToParcel(out, mId);\n ParcelUtils.writeStringToParcel(out, mName);\n ParcelUtils.writeStringToParcel(out, mPhone);\n ParcelUtils.writeStringToParcel(out, mState);\n ParcelUtils.writeStringToParcel(out, mTwitter);\n ParcelUtils.writeStringToParcel(out, mZip);\n\n if (mCheckins != null) {\n out.writeInt(mCheckins.size());\n for (int i = 0; i < mCheckins.size(); i++) {\n out.writeParcelable(mCheckins.get(i), flags);\n }\n } else {\n out.writeInt(0);\n }\n \n if (mSpecials != null) {\n out.writeInt(mSpecials.size());\n for (int i = 0; i < mSpecials.size(); i++) {\n out.writeParcelable((Special)mSpecials.get(i), flags);\n }\n } else {\n out.writeInt(0);\n }\n \n if (mStats != null) {\n out.writeInt(1);\n out.writeParcelable(mStats, flags);\n } else {\n out.writeInt(0); \n }\n \n if (mTags != null) {\n out.writeInt(mTags.size());\n for (int i = 0; i < mTags.size(); i++) {\n out.writeString(mTags.get(i));\n }\n } else {\n out.writeInt(0);\n }\n \n if (mTips != null) {\n out.writeInt(mTips.size());\n for (int i = 0; i < mTips.size(); i++) {\n out.writeParcelable((Tip)mTips.get(i), flags);\n }\n } else {\n out.writeInt(0);\n }\n\n if (mTodos != null) {\n out.writeInt(mTodos.size());\n for (int i = 0; i < mTodos.size(); i++) {\n out.writeParcelable((Tip)mTodos.get(i), flags);\n }\n } else {\n out.writeInt(0);\n }\n \n if (mCategory != null) {\n out.writeInt(1);\n out.writeParcelable(mCategory, flags);\n } else {\n out.writeInt(0);\n }\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n}",
"public class Preferences {\n private static final String TAG = \"Preferences\";\n private static final boolean DEBUG = FoursquaredSettings.DEBUG;\n\n // Visible Preferences (sync with preferences.xml)\n public static final String PREFERENCE_SHARE_CHECKIN = \"share_checkin\";\n public static final String PREFERENCE_IMMEDIATE_CHECKIN = \"immediate_checkin\";\n public static final String PREFERENCE_STARTUP_TAB = \"startup_tab\";\n public static final String PREFERENCE_SYNC_CONTACTS = \"sync_contacts\";\n public static final String PREFERENCE_VENUES_SORT = \"venues_sort\";\n \n // Hacks for preference activity extra UI elements.\n public static final String PREFERENCE_ADVANCED_SETTINGS = \"advanced_settings\";\n public static final String PREFERENCE_TWITTER_CHECKIN = \"twitter_checkin\";\n public static final String PREFERENCE_FACEBOOK_CHECKIN = \"facebook_checkin\";\n public static final String PREFERENCE_TWITTER_HANDLE = \"twitter_handle\";\n public static final String PREFERENCE_FACEBOOK_HANDLE = \"facebook_handle\";\n public static final String PREFERENCE_FRIEND_REQUESTS = \"friend_requests\";\n public static final String PREFERENCE_FRIEND_ADD = \"friend_add\";\n public static final String PREFERENCE_CHANGELOG = \"changelog\";\n public static final String PREFERENCE_CITY_NAME = \"city_name\";\n public static final String PREFERENCE_LOGOUT = \"logout\";\n public static final String PREFERENCE_HELP = \"help\";\n public static final String PREFERENCE_SEND_FEEDBACK = \"send_feedback\";\n public static final String PREFERENCE_PINGS = \"pings_on\";\n public static final String PREFERENCE_PINGS_INTERVAL = \"pings_refresh_interval_in_minutes\";\n public static final String PREFERENCE_PINGS_VIBRATE = \"pings_vibrate\";\n public static final String PREFERENCE_PINGS_FLASH = \"pings_flash\";\n public static final String PREFERENCE_TOS_PRIVACY = \"tos_privacy\";\n public static final String PREFERENCE_PROFILE_SETTINGS = \"profile_settings\";\n\n // Credentials related preferences\n public static final String PREFERENCE_LOGIN = \"phone\";\n public static final String PREFERENCE_PASSWORD = \"password\";\n\n // Extra info for getUserCity\n private static final String PREFERENCE_CITY_ID = \"city_id\";\n private static final String PREFERENCE_CITY_GEOLAT = \"city_geolat\";\n private static final String PREFERENCE_CITY_GEOLONG = \"city_geolong\";\n private static final String PREFERENCE_CITY_SHORTNAME = \"city_shortname\";\n\n // Extra info for getUserId\n private static final String PREFERENCE_ID = \"id\";\n \n // Extra for storing user's supplied email address.\n private static final String PREFERENCE_USER_EMAIL = \"user_email\";\n \n // Extra for storing user's supplied first and last name.\n private static final String PREFERENCE_USER_NAME = \"user_name\";\n \n // Extra info about the user, their gender, to control icon used for 'me' in the UI.\n private static final String PREFERENCE_GENDER = \"gender\";\n \n // Extra info, can the user have followers or not.\n public static final String PREFERENCE_CAN_HAVE_FOLLOWERS = \"can_have_followers\";\n\n // Not-in-XML preferences for dumpcatcher\n public static final String PREFERENCE_DUMPCATCHER_CLIENT = \"dumpcatcher_client\";\n\n // Keeps track of the last changelog version shown to the user at startup.\n private static final String PREFERENCE_LAST_SEEN_CHANGELOG_VERSION \n = \"last_seen_changelog_version\";\n\n // User can choose to clear geolocation on each search.\n public static final String PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES\n = \"cache_geolocation_for_searches\";\n \n // If we're compiled to show the prelaunch activity, flag stating whether to skip\n // showing it on startup.\n public static final String PREFERENCE_SHOW_PRELAUNCH_ACTIVITY = \"show_prelaunch_activity\";\n \n // Last time pings service ran.\n public static final String PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME = \"pings_service_last_run_time\";\n \n // Broadcast an intent to show single full-screen images, or use our own poor image viewer.\n public static final String PREFERENCE_NATIVE_IMAGE_VIEWER\n = \"native_full_size_image_viewer\";\n \n \n /**\n * Gives us a chance to set some default preferences if this is the first install\n * of the application.\n */\n public static void setupDefaults(SharedPreferences preferences, Resources resources) {\n Editor editor = preferences.edit();\n if (!preferences.contains(PREFERENCE_STARTUP_TAB)) {\n String[] startupTabValues = resources.getStringArray(R.array.startup_tabs_values);\n editor.putString(PREFERENCE_STARTUP_TAB, startupTabValues[0]);\n }\n if (!preferences.contains(PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES)) {\n editor.putBoolean(PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES, false);\n }\n if (!preferences.contains(PREFERENCE_SHOW_PRELAUNCH_ACTIVITY)) {\n editor.putBoolean(PREFERENCE_SHOW_PRELAUNCH_ACTIVITY, true);\n }\n if (!preferences.contains(PREFERENCE_PINGS_INTERVAL)) {\n editor.putString(PREFERENCE_PINGS_INTERVAL, \"30\");\n }\n if (!preferences.contains(PREFERENCE_VENUES_SORT)) {\n String[] venuesSortValues = resources.getStringArray(R.array.venues_sort_values);\n editor.putString(PREFERENCE_VENUES_SORT, venuesSortValues[0]);\n }\n if (!preferences.contains(PREFERENCE_NATIVE_IMAGE_VIEWER)) {\n editor.putBoolean(PREFERENCE_NATIVE_IMAGE_VIEWER, true);\n }\n editor.commit();\n }\n \n public static String createUniqueId(SharedPreferences preferences) {\n String uniqueId = preferences.getString(PREFERENCE_DUMPCATCHER_CLIENT, null);\n if (uniqueId == null) {\n uniqueId = UUID.randomUUID().toString();\n Editor editor = preferences.edit();\n editor.putString(PREFERENCE_DUMPCATCHER_CLIENT, uniqueId);\n editor.commit();\n }\n return uniqueId;\n }\n\n public static boolean loginUser(Foursquare foursquare, String login, String password,\n Foursquare.Location location, Editor editor) throws FoursquareCredentialsException,\n FoursquareException, IOException {\n if (DEBUG) Log.d(Preferences.TAG, \"Trying to log in.\");\n\n foursquare.setCredentials(login, password);\n storeLoginAndPassword(editor, login, password);\n if (!editor.commit()) {\n if (DEBUG) Log.d(TAG, \"storeLoginAndPassword commit failed\");\n return false;\n }\n \n User user = foursquare.user(null, false, false, location);\n storeUser(editor, user);\n if (!editor.commit()) {\n if (DEBUG) Log.d(TAG, \"storeUser commit failed\");\n return false;\n }\n\n return true;\n }\n\n public static boolean logoutUser(Foursquare foursquare, Editor editor) {\n if (DEBUG) Log.d(Preferences.TAG, \"Trying to log out.\");\n // TODO: If we re-implement oAuth, we'll have to call clearAllCrendentials here.\n foursquare.setCredentials(null, null);\n return editor.clear().commit();\n }\n\n public static City getUserCity(SharedPreferences prefs) {\n City city = new City();\n city.setId(prefs.getString(Preferences.PREFERENCE_CITY_ID, null));\n city.setName(prefs.getString(Preferences.PREFERENCE_CITY_NAME, null));\n city.setShortname(prefs.getString(Preferences.PREFERENCE_CITY_SHORTNAME, null));\n city.setGeolat(prefs.getString(Preferences.PREFERENCE_CITY_GEOLAT, null));\n city.setGeolong(prefs.getString(Preferences.PREFERENCE_CITY_GEOLONG, null));\n return city;\n }\n\n public static String getUserId(SharedPreferences prefs) {\n return prefs.getString(PREFERENCE_ID, null);\n }\n \n public static String getUserName(SharedPreferences prefs) {\n return prefs.getString(PREFERENCE_USER_NAME, null);\n }\n \n public static String getUserEmail(SharedPreferences prefs) {\n return prefs.getString(PREFERENCE_USER_EMAIL, null);\n }\n\n public static String getUserGender(SharedPreferences prefs) {\n return prefs.getString(PREFERENCE_GENDER, null);\n }\n \n public static String getLastSeenChangelogVersion(SharedPreferences prefs) {\n return prefs.getString(PREFERENCE_LAST_SEEN_CHANGELOG_VERSION, null);\n }\n \n public static void storeCity(final Editor editor, City city) {\n if (city != null) {\n editor.putString(PREFERENCE_CITY_ID, city.getId());\n editor.putString(PREFERENCE_CITY_GEOLAT, city.getGeolat());\n editor.putString(PREFERENCE_CITY_GEOLONG, city.getGeolong());\n editor.putString(PREFERENCE_CITY_NAME, city.getName());\n editor.putString(PREFERENCE_CITY_SHORTNAME, city.getShortname());\n }\n }\n\n public static void storeLoginAndPassword(final Editor editor, String login, String password) {\n editor.putString(PREFERENCE_LOGIN, login);\n editor.putString(PREFERENCE_PASSWORD, password);\n }\n\n public static void storeUser(final Editor editor, User user) {\n if (user != null && user.getId() != null) {\n editor.putString(PREFERENCE_ID, user.getId());\n editor.putString(PREFERENCE_USER_NAME, StringFormatters.getUserFullName(user));\n editor.putString(PREFERENCE_USER_EMAIL, user.getEmail());\n editor.putBoolean(PREFERENCE_TWITTER_CHECKIN, user.getSettings().sendtotwitter());\n editor.putBoolean(PREFERENCE_FACEBOOK_CHECKIN, user.getSettings().sendtofacebook());\n editor.putString(PREFERENCE_TWITTER_HANDLE, user.getTwitter() != null ? user.getTwitter() : \"\");\n editor.putString(PREFERENCE_FACEBOOK_HANDLE, user.getFacebook() != null ? user.getFacebook() : \"\");\n editor.putString(PREFERENCE_GENDER, user.getGender());\n editor.putBoolean(PREFERENCE_CAN_HAVE_FOLLOWERS, UserUtils.getCanHaveFollowers(user));\n if (DEBUG) Log.d(TAG, \"Setting user info\");\n } else {\n if (Preferences.DEBUG) Log.d(Preferences.TAG, \"Unable to lookup user.\");\n }\n }\n \n public static void storeLastSeenChangelogVersion(final Editor editor, String version) {\n editor.putString(PREFERENCE_LAST_SEEN_CHANGELOG_VERSION, version);\n if (!editor.commit()) {\n Log.e(TAG, \"storeLastSeenChangelogVersion commit failed\");\n }\n }\n \n public static boolean getUseNativeImageViewerForFullScreenImages(SharedPreferences prefs) {\n return prefs.getBoolean(PREFERENCE_NATIVE_IMAGE_VIEWER, true);\n }\n}",
"public class NotificationsUtil {\n private static final String TAG = \"NotificationsUtil\";\n private static final boolean DEBUG = FoursquaredSettings.DEBUG;\n\n public static void ToastReasonForFailure(Context context, Exception e) {\n if (DEBUG) Log.d(TAG, \"Toasting for exception: \", e);\n\n if (e instanceof SocketTimeoutException) {\n Toast.makeText(context, \"Foursquare over capacity, server request timed out!\", Toast.LENGTH_SHORT).show();\n \n } else if (e instanceof SocketException) {\n Toast.makeText(context, \"Foursquare server not responding\", Toast.LENGTH_SHORT).show();\n\n } else if (e instanceof IOException) {\n Toast.makeText(context, \"Network unavailable\", Toast.LENGTH_SHORT).show();\n\n } else if (e instanceof LocationException) {\n Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();\n\n } else if (e instanceof FoursquareCredentialsException) {\n Toast.makeText(context, \"Authorization failed.\", Toast.LENGTH_SHORT).show();\n\n } else if (e instanceof FoursquareException) {\n // FoursquareError is one of these\n String message;\n int toastLength = Toast.LENGTH_SHORT;\n if (e.getMessage() == null) {\n message = \"Invalid Request\";\n } else {\n message = e.getMessage();\n toastLength = Toast.LENGTH_LONG;\n }\n Toast.makeText(context, message, toastLength).show();\n\n } else {\n Toast.makeText(context, \"A surprising new problem has occured. Try again!\",\n Toast.LENGTH_SHORT).show();\n DumpcatcherHelper.sendException(e);\n }\n }\n}",
"public abstract class TabsUtil {\n\n public static void setTabIndicator(TabSpec spec, String title, Drawable drawable, View view) {\n int sdk = new Integer(Build.VERSION.SDK).intValue();\n if (sdk < 4) {\n TabsUtil3.setTabIndicator(spec, title, drawable);\n } else {\n TabsUtil4.setTabIndicator(spec, view);\n }\n }\n \n private static TabHost.TabSpec addNativeLookingTab(Context context, final TabHost tabHost, String specName, \n String label, int iconId) {\n View view = LayoutInflater.from(context).inflate(R.layout.fake_native_tab, null);\n ImageView iv = (ImageView) view.findViewById(R.id.fakeNativeTabImageView);\n iv.setImageResource(iconId);\n TextView tv = (TextView) view.findViewById(R.id.fakeNativeTabTextView);\n tv.setText(label);\n \n int sdk = new Integer(Build.VERSION.SDK).intValue();\n if (sdk > 3) {\n TabsUtil4.addNativeLookingTab(context, tabHost, view);\n }\n \n TabHost.TabSpec spec = tabHost.newTabSpec(specName);\n TabsUtil.setTabIndicator(spec, label, context.getResources().getDrawable(iconId), view);\n return spec;\n }\n \n public static void addNativeLookingTab(Context context, final TabHost tabHost, String specName, \n String label, int iconId, int layout) {\n TabHost.TabSpec spec = addNativeLookingTab(context, tabHost, specName, label, iconId);\n \n spec.setContent(layout);\n tabHost.addTab(spec);\n }\n \n public static void addNativeLookingTab(Context context, final TabHost tabHost, String specName, \n String label, int iconId, Intent intent) {\n TabHost.TabSpec spec = addNativeLookingTab(context, tabHost, specName, label, iconId);\n \n spec.setContent(intent);\n tabHost.addTab(spec);\n }\n}",
"public class UserUtils {\n\n public static void ensureUserPhoto(final Context context, final User user, final boolean DEBUG,\n final String TAG) {\n Activity activity = ((Activity) context);\n final ImageView photo = (ImageView) activity.findViewById(R.id.photo);\n if (user.getPhoto() == null) {\n photo.setImageResource(R.drawable.blank_boy);\n return;\n }\n final Uri photoUri = Uri.parse(user.getPhoto());\n if (photoUri != null) {\n RemoteResourceManager userPhotosManager = ((Foursquared) activity.getApplication())\n .getRemoteResourceManager();\n try {\n Bitmap bitmap = BitmapFactory.decodeStream(userPhotosManager\n .getInputStream(photoUri));\n photo.setImageBitmap(bitmap);\n } catch (IOException e) {\n if (DEBUG) Log.d(TAG, \"photo not already retrieved, requesting: \" + photoUri);\n userPhotosManager.addObserver(new RemoteResourceManager.ResourceRequestObserver(\n photoUri) {\n @Override\n public void requestReceived(Observable observable, Uri uri) {\n observable.deleteObserver(this);\n updateUserPhoto(context, photo, uri, user, DEBUG, TAG);\n }\n });\n userPhotosManager.request(photoUri);\n }\n }\n }\n\n private static void updateUserPhoto(Context context, final ImageView photo, final Uri uri,\n final User user, final boolean DEBUG, final String TAG) {\n final Activity activity = ((Activity) context);\n activity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n try {\n if (DEBUG) Log.d(TAG, \"Loading user photo: \" + uri);\n RemoteResourceManager userPhotosManager = ((Foursquared) activity\n .getApplication()).getRemoteResourceManager();\n Bitmap bitmap = BitmapFactory.decodeStream(userPhotosManager\n .getInputStream(uri));\n photo.setImageBitmap(bitmap);\n if (DEBUG) Log.d(TAG, \"Loaded user photo: \" + uri);\n } catch (IOException e) {\n if (DEBUG) Log.d(TAG, \"Unable to load user photo: \" + uri);\n if (Foursquare.MALE.equals(user.getGender())) {\n photo.setImageResource(R.drawable.blank_boy);\n } else {\n photo.setImageResource(R.drawable.blank_girl);\n }\n } catch (Exception e) {\n Log.d(TAG, \"Ummm............\", e);\n }\n }\n });\n }\n \n public static boolean isFriend(User user) {\n if (user == null) {\n return false;\n } else if (TextUtils.isEmpty(user.getFriendstatus())) {\n return false;\n } else if (user.getFriendstatus().equals(\"friend\")) {\n return true;\n } else {\n return false;\n }\n }\n \n public static int getDrawableForMeTabByGender(String gender) {\n if (gender == null) {\n return R.drawable.me_tab_boy;\n } else if (gender.equals(\"female\")) {\n return R.drawable.me_tab_girl;\n } else {\n return R.drawable.me_tab_boy;\n }\n }\n \n public static int getDrawableForMeMenuItemByGender(String gender) {\n if (gender == null) {\n return R.drawable.ic_menu_myinfo_boy;\n } else if (gender.equals(\"female\")) {\n return R.drawable.ic_menu_myinfo_girl;\n } else {\n return R.drawable.ic_menu_myinfo_boy;\n }\n }\n \n public static boolean getCanHaveFollowers(User user) {\n if (user.getTypes() != null && user.getTypes().size() > 0) {\n if (user.getTypes().contains(\"canHaveFollowers\")) {\n return true;\n }\n }\n \n return false;\n }\n}",
"public class VenueView extends RelativeLayout {\n\n private boolean mCheckinButtonVisible = false;\n private boolean mCollapsible = false;\n\n private Button mCheckinButton;\n private TextView mVenueName;\n private TextView mVenueLocationLine1;\n private TextView mVenueLocationLine2;\n private ImageView mVenueSpecialIcon;\n \n\n public VenueView(Context context) {\n super(context);\n }\n\n public VenueView(Context context, AttributeSet attrs) {\n super(context, attrs);\n TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.VenueView, 0, 0);\n mCheckinButtonVisible = a.getBoolean(R.styleable.VenueView_checkinButton, false);\n mCollapsible = a.getBoolean(R.styleable.VenueView_collapsible, false);\n a.recycle();\n }\n\n @Override\n public void onFinishInflate() {\n super.onFinishInflate();\n ((Activity)getContext()).getLayoutInflater().inflate(R.layout.venue_view, this);\n mCheckinButton = (Button)findViewById(R.id.internal_checkinButton);\n mVenueName = (TextView)findViewById(R.id.internal_venueName);\n mVenueLocationLine1 = (TextView)findViewById(R.id.internal_venueLocationLine1);\n mVenueLocationLine2 = (TextView)findViewById(R.id.internal_venueLocationLine2);\n mVenueSpecialIcon = (ImageView)findViewById(R.id.internal_specialImageView);\n }\n\n public void setCheckinButtonEnabled(boolean enabled) {\n mCheckinButton.setEnabled(enabled);\n }\n\n public void setCheckinButtonVisibility(int visibility) {\n mCheckinButton.setVisibility(visibility);\n }\n\n public void setVenue(Venue venue) {\n mVenueName.setText(venue.getName());\n mVenueLocationLine1.setText(venue.getAddress());\n\n String line2 = StringFormatters.getVenueLocationCrossStreetOrCity(venue);\n if (TextUtils.isEmpty(line2)) {\n mVenueLocationLine2.setText(line2);\n mVenueLocationLine2.setVisibility(View.VISIBLE);\n } else if (mCollapsible) {\n mVenueLocationLine2.setVisibility(View.GONE);\n }\n\n if (mCheckinButtonVisible) {\n mCheckinButton.setVisibility(View.VISIBLE);\n }\n \n // Don't show the special unless it's linked to this venue!\n if (venue.getSpecials() != null && venue.getSpecials().size() > 0) {\n Venue specialVenue = venue.getSpecials().get(0).getVenue();\n if (specialVenue == null || specialVenue.getId().equals(venue.getId())) {\n mVenueSpecialIcon.setVisibility(View.VISIBLE);\n }\n }\n };\n\n public void setCheckinButtonOnClickListener(OnClickListener l) {\n mCheckinButton.setOnClickListener(l);\n }\n \n public void setSpecialOnClickListener(OnClickListener l) {\n mVenueSpecialIcon.setOnClickListener(l);\n }\n \n public void updateCheckinButtonText() {\n // If the user has enabled 'quick check-in', then update the text of the button\n // to reflect this.\n SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(\n getContext());\n if (settings.getBoolean(Preferences.PREFERENCE_IMMEDIATE_CHECKIN, false)) {\n mCheckinButton.setText(getContext().getString(R.string.venue_activity_checkin_button_quick));\n } else {\n mCheckinButton.setText(getContext().getString(R.string.venue_activity_checkin_button));\n }\n }\n}"
] | import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquare.util.VenueUtils;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.MenuUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.TabsUtil;
import com.joelapenna.foursquared.util.UserUtils;
import com.joelapenna.foursquared.widget.VenueView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.Toast;
import java.util.HashSet;
import java.util.Observable; | Intent intent;
tag = (String) this.getText(R.string.venue_checkins_tab);
intent = new Intent(this, VenueCheckinsActivity.class);
TabsUtil.addNativeLookingTab(this, tabHost, "t1", tag, R.drawable.friends_tab, intent);
tag = (String) this.getText(R.string.map_label);
intent = new Intent(this, VenueMapActivity.class);
TabsUtil.addNativeLookingTab(this, tabHost, "t2", tag, R.drawable.map_tab, intent);
tag = (String) this.getText(R.string.venue_info_tab);
intent = new Intent(this, VenueTipsActivity.class);
TabsUtil.addNativeLookingTab(this, tabHost, "t3", tag, R.drawable.tips_tab, intent);
}
private void onVenueSet() {
Venue venue = mStateHolder.venue;
if (DEBUG) Log.d(TAG, "onVenueSet:" + venue.getName());
setTitle(venue.getName() + " - Foursquare");
mVenueView.setVenue(venue);
mVenueView.setCheckinButtonEnabled(mStateHolder.venueId != null);
}
private void setVenue(Venue venue) {
mStateHolder.venue = venue;
mStateHolder.venueId = venue.getId();
venueObservable.notifyObservers(venue);
onVenueSet();
}
private void startCheckin() {
Intent intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class);
intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_CHECKIN, true);
intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.venue.getId());
intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_NAME, mStateHolder.venue.getName());
startActivityForResult(intent, RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE);
}
private void startCheckinQuick() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean tellFriends = settings.getBoolean(Preferences.PREFERENCE_SHARE_CHECKIN, true);
boolean tellTwitter = settings.getBoolean(Preferences.PREFERENCE_TWITTER_CHECKIN, false);
boolean tellFacebook = settings.getBoolean(Preferences.PREFERENCE_FACEBOOK_CHECKIN, false);
Intent intent = new Intent(VenueActivity.this, CheckinExecuteActivity.class);
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.venue.getId());
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_SHOUT, "");
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FRIENDS, tellFriends);
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_TWITTER, tellTwitter);
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK, tellFacebook);
startActivityForResult(intent, RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE);
}
private void showWebViewForSpecial() {
Intent intent = new Intent(this, SpecialWebViewActivity.class);
intent.putExtra(SpecialWebViewActivity.EXTRA_CREDENTIALS_USERNAME,
PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.PREFERENCE_LOGIN, ""));
intent.putExtra(SpecialWebViewActivity.EXTRA_CREDENTIALS_PASSWORD,
PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.PREFERENCE_PASSWORD, ""));
intent.putExtra(SpecialWebViewActivity.EXTRA_SPECIAL_ID,
mStateHolder.venue.getSpecials().get(0).getId());
startActivity(intent);
}
class VenueObservable extends Observable {
@Override
public void notifyObservers(Object data) {
setChanged();
super.notifyObservers(data);
}
public Venue getVenue() {
return mStateHolder.venue;
}
}
private class VenueTask extends AsyncTask<String, Void, Venue> {
private static final String PROGRESS_BAR_TASK_ID = TAG + "VenueTask";
private Exception mReason;
@Override
protected void onPreExecute() {
startProgressBar(PROGRESS_BAR_TASK_ID);
}
@Override
protected Venue doInBackground(String... params) {
try {
return ((Foursquared) getApplication()).getFoursquare().venue(
params[0],
LocationUtils.createFoursquareLocation(((Foursquared) getApplication())
.getLastKnownLocation()));
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Venue venue) {
try {
if (VenueUtils.isValid(venue)) {
setVenue(venue);
} else {
NotificationsUtil.ToastReasonForFailure(VenueActivity.this, mReason);
finish();
}
} finally {
stopProgressBar(PROGRESS_BAR_TASK_ID);
}
}
@Override
protected void onCancelled() {
stopProgressBar(PROGRESS_BAR_TASK_ID);
}
}
| private class TipAddTask extends AsyncTask<String, Void, Tip> { | 0 |
jenshadlich/s3srv | src/main/java/de/jeha/s3srv/resources/S3OperationsFacade.java | [
"public class RequestContext {\n\n private final boolean pathStyle;\n private final String bucket;\n private final String key;\n\n private RequestContext(boolean pathStyle, String bucket, String key) {\n this.pathStyle = pathStyle;\n this.bucket = bucket;\n this.key = key;\n }\n\n public static RequestContext build(HttpServletRequest request) {\n final String requestUri = request.getRequestURI();\n final String hostHeader = request.getHeader(Headers.HOST);\n final boolean pathStyle = detectPathStyle(request);\n\n String bucket = null;\n String key = null;\n\n String[] parts = StringUtils.split(requestUri, \"/\", 2);\n if (pathStyle) {\n if (parts.length >= 1) {\n bucket = parts[0];\n }\n if (parts.length >= 2) {\n key = parts[1];\n }\n } else {\n bucket = StringUtils.substringBefore(hostHeader, \".\");\n if (parts.length >= 1) {\n key = parts[0];\n }\n }\n return new RequestContext(pathStyle, bucket, key);\n }\n\n private static boolean detectPathStyle(HttpServletRequest request) {\n final String serverName = request.getServerName();\n final String hostHeader = request.getHeader(Headers.HOST);\n\n return !(hostHeader.startsWith(serverName) && serverName.endsWith(\".localhost\"));\n }\n\n public boolean isPathStyle() {\n return pathStyle;\n }\n\n public String getBucket() {\n return bucket;\n }\n\n public String getKey() {\n return key;\n }\n\n @Override\n public String toString() {\n return \"S3Context{\" +\n \"pathStyle=\" + pathStyle +\n \", bucket='\" + bucket + '\\'' +\n \", key='\" + key + '\\'' +\n '}';\n }\n\n}",
"public class CreateObject extends AbstractOperation {\n\n private static final Logger LOG = LoggerFactory.getLogger(CreateObject.class);\n\n public CreateObject(StorageBackend storageBackend) {\n super(storageBackend);\n }\n\n /**\n * Create an object.\n *\n * @param request HTTP request\n * @param bucket bucket\n * @param key object key\n * @return response\n */\n public Response createObject(HttpServletRequest request,\n String bucket,\n String key) {\n LOG.info(\"createObject '{}/{}'\", bucket, key);\n final String resource = \"/\" + bucket + \"/\" + key;\n\n AuthorizationContext authorizationContext = checkAuthorization(request, resource);\n if (!authorizationContext.isUserValid()) {\n return createErrorResponse(ErrorCodes.INVALID_ACCESS_KEY_ID, resource, null);\n }\n if (!authorizationContext.isSignatureValid()) {\n return createErrorResponse(ErrorCodes.SIGNATURE_DOES_NOT_MATCH, resource, null);\n }\n if (!getStorageBackend().doesBucketExist(bucket)) {\n return createErrorResponse(ErrorCodes.NO_SUCH_BUCKET, resource, null);\n }\n if (!getStorageBackend().getBucket(bucket).isOwnedBy(authorizationContext.getUser())) {\n return createErrorResponse(ErrorCodes.ACCESS_DENIED, resource, null);\n }\n\n final String expectedMD5 = request.getHeader(Headers.CONTENT_MD5); // optional\n try {\n S3Object object = getStorageBackend().createObject(\n bucket,\n key,\n request.getInputStream(),\n request.getContentLength(),\n expectedMD5,\n request.getContentType());\n\n return Response.ok()\n .header(Headers.ETAG, object.getETag())\n .build();\n } catch (IOException e) {\n LOG.error(\"Unable to read input stream\", e);\n return createErrorResponse(ErrorCodes.INTERNAL_ERROR, \"/\" + bucket + \"/\" + key, null);\n } catch (BadDigestException e) {\n return createErrorResponse(ErrorCodes.BAD_DIGEST, \"/\" + bucket + \"/\" + key, null);\n }\n }\n\n}",
"public class DeleteObject extends AbstractOperation {\n\n private static final Logger LOG = LoggerFactory.getLogger(DeleteObject.class);\n\n public DeleteObject(StorageBackend storageBackend) {\n super(storageBackend);\n }\n\n /**\n * Delete an object.\n *\n * @param request HTTP request\n * @param bucket bucket\n * @param key object key\n * @return response\n */\n public Response deleteObject(HttpServletRequest request,\n String bucket,\n String key) {\n LOG.info(\"deleteObject '{}/{}'\", bucket, key);\n final String resource = \"/\" + bucket + \"/\" + key;\n\n AuthorizationContext authorizationContext = checkAuthorization(request, resource);\n if (!authorizationContext.isUserValid()) {\n return createErrorResponse(ErrorCodes.INVALID_ACCESS_KEY_ID, resource, null);\n }\n if (!authorizationContext.isSignatureValid()) {\n return createErrorResponse(ErrorCodes.SIGNATURE_DOES_NOT_MATCH, resource, null);\n }\n if (!getStorageBackend().doesBucketExist(bucket)) {\n return createErrorResponse(ErrorCodes.NO_SUCH_BUCKET, resource, null);\n }\n if (!getStorageBackend().getBucket(bucket).isOwnedBy(authorizationContext.getUser())) {\n return createErrorResponse(ErrorCodes.ACCESS_DENIED, resource, null);\n }\n if (!getStorageBackend().doesObjectExist(bucket, key)) {\n return Response.status(Response.Status.NOT_FOUND)\n .build();\n }\n\n getStorageBackend().deleteObject(bucket, key);\n\n return Response.noContent()\n .build();\n }\n\n}",
"public class ExistsObject extends AbstractOperation {\n\n private static final Logger LOG = LoggerFactory.getLogger(ExistsObject.class);\n\n public ExistsObject(StorageBackend storageBackend) {\n super(storageBackend);\n }\n\n /**\n * Check if an object exists.\n *\n * @param request HTTP request\n * @param bucket bucket\n * @param key object key\n * @return response\n */\n public Response doesObjectExist(HttpServletRequest request,\n String bucket,\n String key) {\n LOG.info(\"doesObjectExist '{}/{}'\", bucket, key);\n final String resource = \"/\" + bucket + \"/\" + key;\n\n AuthorizationContext authorizationContext = checkAuthorization(request, resource);\n if (!authorizationContext.isUserValid()) {\n return createErrorResponse(ErrorCodes.INVALID_ACCESS_KEY_ID, resource, null);\n }\n if (!authorizationContext.isSignatureValid()) {\n return createErrorResponse(ErrorCodes.SIGNATURE_DOES_NOT_MATCH, resource, null);\n }\n if (!getStorageBackend().doesBucketExist(bucket)) {\n return createErrorResponse(ErrorCodes.NO_SUCH_BUCKET, resource, null);\n }\n if (!getStorageBackend().getBucket(bucket).isOwnedBy(authorizationContext.getUser())) {\n return createErrorResponse(ErrorCodes.ACCESS_DENIED, resource, null);\n }\n if (getStorageBackend().doesObjectExist(bucket, key)) {\n S3Object object = getStorageBackend().getObject(bucket, key);\n\n return Response.ok()\n .type(object.getContentType())\n .header(Headers.LAST_MODIFIED, RFC822Date.format(object.getLastModified()))\n .header(Headers.ETAG, object.getETag())\n .header(Headers.CONTENT_LENGTH, Integer.toString(object.getSize()))\n .build();\n } else {\n return Response.status(Response.Status.NOT_FOUND)\n .build();\n }\n }\n\n}",
"public class GetObject extends AbstractOperation {\n\n private static final Logger LOG = LoggerFactory.getLogger(ExistsObject.class);\n\n public GetObject(StorageBackend storageBackend) {\n super(storageBackend);\n }\n\n /**\n * Retrieve an object.\n *\n * @param request HTTP request\n * @param bucket bucket\n * @param key object key\n * @return response\n */\n public Response getObject(HttpServletRequest request,\n String bucket,\n String key) {\n LOG.info(\"getObject '{}/{}'\", bucket, key);\n final String resource = \"/\" + bucket + \"/\" + key;\n\n AuthorizationContext authorizationContext = checkAuthorization(request, resource);\n if (!authorizationContext.isUserValid()) {\n return createErrorResponse(ErrorCodes.INVALID_ACCESS_KEY_ID, resource, null);\n }\n if (!authorizationContext.isSignatureValid()) {\n return createErrorResponse(ErrorCodes.SIGNATURE_DOES_NOT_MATCH, resource, null);\n }\n if (!getStorageBackend().doesBucketExist(bucket)) {\n return createErrorResponse(ErrorCodes.NO_SUCH_BUCKET, resource, null);\n }\n if (!getStorageBackend().getBucket(bucket).isOwnedBy(authorizationContext.getUser())) {\n return createErrorResponse(ErrorCodes.ACCESS_DENIED, resource, null);\n }\n if (getStorageBackend().doesObjectExist(bucket, key)) {\n S3Object object = getStorageBackend().getObject(bucket, key);\n\n return Response.ok(object.getInputStream())\n .type(object.getContentType())\n .header(Headers.ETAG, object.getETag())\n .header(Headers.CONTENT_LENGTH, Integer.toString(object.getSize()))\n .build();\n } else {\n return Response.status(Response.Status.NOT_FOUND)\n .build();\n }\n }\n\n}",
"public class ListBuckets extends AbstractOperation {\n\n private static final Logger LOG = LoggerFactory.getLogger(ListBuckets.class);\n\n public ListBuckets(StorageBackend storageBackend) {\n super(storageBackend);\n }\n\n /**\n * List the buckets of some user\n *\n * @param request HTTP request\n * @return response\n */\n public Response listBuckets(HttpServletRequest request) {\n LOG.info(\"listBuckets\");\n final String resource = \"/\";\n\n AuthorizationContext authorizationContext = checkAuthorization(request, resource);\n if (!authorizationContext.isUserValid()) {\n return createErrorResponse(ErrorCodes.INVALID_ACCESS_KEY_ID, resource, null);\n }\n if (!authorizationContext.isSignatureValid()) {\n return createErrorResponse(ErrorCodes.SIGNATURE_DOES_NOT_MATCH, resource, null);\n }\n\n List<ListAllMyBucketsResult.BucketsEntry> buckets = getStorageBackend()\n .listBuckets()\n .stream()\n .filter(bucket -> bucket.isOwnedBy(authorizationContext.getUser()))\n .map(bucket -> new ListAllMyBucketsResult.BucketsEntry(bucket.getName(), bucket.getCreationDate()))\n .collect(Collectors.toList());\n\n ListAllMyBucketsResult response =\n new ListAllMyBucketsResult(\n new Owner(\n authorizationContext.getUser().getId(),\n authorizationContext.getUser().getDisplayName()),\n buckets);\n\n try {\n return Response.ok(JaxbMarshaller.marshall(response), MediaType.APPLICATION_XML_TYPE)\n .build();\n } catch (Exception e) {\n LOG.error(\"Unable to create xml response body\", e);\n return createErrorResponse(ErrorCodes.INTERNAL_ERROR, \"/\", null);\n }\n }\n\n}",
"public interface StorageBackend extends HealthAware {\n\n List<S3Bucket> listBuckets();\n\n void createBucket(S3User user, String bucket);\n\n boolean doesBucketExist(String bucket);\n\n S3Bucket getBucket(String bucket);\n\n void deleteBucket(String bucket);\n\n S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength,\n String expectedMD5, String contentType)\n throws IOException, BadDigestException;\n\n boolean doesObjectExist(String bucket, String key);\n\n List<S3Object> listObjects(String bucket, int max);\n\n S3Object getObject(String bucket, String key);\n\n void deleteObject(String bucket, String key);\n\n /**\n * @todo maybe separate storage backends for data and account data\n */\n S3User getUserByAccessId(String accessKey);\n\n}"
] | import com.codahale.metrics.annotation.Timed;
import de.jeha.s3srv.common.s3.RequestContext;
import de.jeha.s3srv.operations.buckets.*;
import de.jeha.s3srv.operations.objects.CreateObject;
import de.jeha.s3srv.operations.objects.DeleteObject;
import de.jeha.s3srv.operations.objects.ExistsObject;
import de.jeha.s3srv.operations.objects.GetObject;
import de.jeha.s3srv.operations.service.ListBuckets;
import de.jeha.s3srv.storage.StorageBackend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response; | package de.jeha.s3srv.resources;
/**
* @author [email protected]
*/
@Path("/")
public class S3OperationsFacade {
private static final Logger LOG = LoggerFactory.getLogger(S3OperationsFacade.class);
private final StorageBackend storageBackend;
public S3OperationsFacade(StorageBackend storageBackend) {
this.storageBackend = storageBackend;
}
@HEAD
@Path("{subResources:.*}")
@Timed
public Response head(@Context HttpServletRequest request) {
LOG.info("head");
final RequestContext context = RequestContext.build(request);
LOG.info("{}", context);
if (context.getBucket() != null && context.getKey() != null) {
return new ExistsObject(storageBackend).doesObjectExist(request, context.getBucket(), context.getKey());
}
if (context.getBucket() != null) {
return new ExistsBucket(storageBackend).doesBucketExist(request, context.getBucket());
}
throw new UnsupportedOperationException("Not yet implemented!"); // TODO
}
@GET
@Path("{subResources:.*}")
@Timed
public Response get(@Context HttpServletRequest request) {
LOG.info("get");
final RequestContext context = RequestContext.build(request);
LOG.info("{}", context);
if (context.getBucket() != null && context.getKey() != null) {
return new GetObject(storageBackend).getObject(request, context.getBucket(), context.getKey());
}
if (context.getBucket() != null && "acl".equals(request.getQueryString())) {
return new GetBucketACL(storageBackend).getBucketACL(request, context.getBucket());
}
if (context.getBucket() != null) {
return new ListObjects(storageBackend).listObjects(request, context.getBucket());
}
| return new ListBuckets(storageBackend).listBuckets(request); | 5 |
fuinorg/ddd-4-java | src/test/java/org/fuin/ddd4j/ddd/DomainEventExpectedEntityIdPathValidatorTest.java | [
"public class ACreatedEvent extends AbstractDomainEvent<AId> {\n\n private static final long serialVersionUID = 1L;\n\n private static final EventType EVENT_TYPE = new EventType(\"ACreatedEvent\");\n\n private AId id;\n\n public ACreatedEvent(final AId id) {\n super(new EntityIdPath(id));\n this.id = id;\n }\n\n public AId getId() {\n return id;\n }\n\n @Override\n public EventType getEventType() {\n return EVENT_TYPE;\n }\n\n}",
"public class AId implements ImplRootId {\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n public static final EntityType TYPE = new StringBasedEntityType(\"A\");\r\n\r\n private final long id;\r\n\r\n public AId(final long id) {\r\n this.id = id;\r\n }\r\n\r\n @Override\r\n public EntityType getType() {\r\n return TYPE;\r\n }\r\n\r\n @Override\r\n public String asString() {\r\n return \"\" + id;\r\n }\r\n\r\n @Override\r\n public String asTypedString() {\r\n return getType() + \" \" + asString();\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"AId [id=\" + id + \"]\";\r\n }\r\n\r\n}\r",
"public class BId implements EntityId {\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n public static final EntityType TYPE = new StringBasedEntityType(\"B\");\r\n\r\n private final long id;\r\n\r\n public BId(final long id) {\r\n this.id = id;\r\n }\r\n\r\n @Override\r\n public EntityType getType() {\r\n return TYPE;\r\n }\r\n\r\n @Override\r\n public String asString() {\r\n return \"\" + id;\r\n }\r\n\r\n @Override\r\n public String asTypedString() {\r\n return getType() + \" \" + asString();\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"BId [id=\" + id + \"]\";\r\n }\r\n\r\n}\r",
"public class CAddedEvent extends AbstractDomainEvent<BId> {\n\n private static final long serialVersionUID = 1L;\n\n private static final EventType EVENT_TYPE = new EventType(\"CAddedEvent\");\n\n private final CId cid;\n\n public CAddedEvent(final AId aid, final BId bid, final CId cid) {\n super(new EntityIdPath(aid, bid));\n this.cid = cid;\n }\n\n @Override\n public EventType getEventType() {\n return EVENT_TYPE;\n }\n\n public CId getCId() {\n return cid;\n }\n\n}",
"public class CEvent extends AbstractDomainEvent<CId> {\n\n private static final long serialVersionUID = 1L;\n\n private static final EventType EVENT_TYPE = new EventType(\"CEvent\");\n\n public CEvent(final AId aid, final BId bid, final CId cid) {\n super(new EntityIdPath(aid, bid, cid));\n }\n\n @Override\n public EventType getEventType() {\n return EVENT_TYPE;\n }\n\n}",
"public class CId implements EntityId {\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n public static final EntityType TYPE = new StringBasedEntityType(\"C\");\r\n\r\n private final long id;\r\n\r\n public CId(final long id) {\r\n this.id = id;\r\n }\r\n\r\n @Override\r\n public EntityType getType() {\r\n return TYPE;\r\n }\r\n\r\n @Override\r\n public String asString() {\r\n return \"\" + id;\r\n }\r\n\r\n @Override\r\n public String asTypedString() {\r\n return getType() + \" \" + asString();\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"CId [id=\" + id + \"]\";\r\n }\r\n\r\n}\r"
] | import static org.assertj.core.api.Assertions.assertThat;
import java.lang.annotation.Annotation;
import jakarta.validation.Payload;
import org.fuin.ddd4j.test.ACreatedEvent;
import org.fuin.ddd4j.test.AId;
import org.fuin.ddd4j.test.BId;
import org.fuin.ddd4j.test.CAddedEvent;
import org.fuin.ddd4j.test.CEvent;
import org.fuin.ddd4j.test.CId;
import org.junit.Test; | /**
* Copyright (C) 2015 Michael Schnell. All rights reserved.
* http://www.fuin.org/
*
* 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 3 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, see http://www.gnu.org/licenses/.
*/
package org.fuin.ddd4j.ddd;
//CHECKSTYLE:OFF Test code
public class DomainEventExpectedEntityIdPathValidatorTest {
@Test
public void testIsValidNull() {
// PREPARE
final DomainEventExpectedEntityIdPath anno = createAnnotation(AId.class);
final DomainEventExpectedEntityIdPathValidator testee = new DomainEventExpectedEntityIdPathValidator();
testee.initialize(anno);
// TEST & VERIFY
assertThat(testee.isValid(null, null)).isTrue();
}
@Test
public void testIsValidOneLevel() {
// PREPARE
final AId aid = new AId(1L);
final BId bid = new BId(2L);
final CId cid = new CId(3L);
final DomainEventExpectedEntityIdPath anno = createAnnotation(AId.class);
final DomainEventExpectedEntityIdPathValidator testee = new DomainEventExpectedEntityIdPathValidator();
testee.initialize(anno);
// TEST & VERIFY
assertThat(testee.isValid(new ACreatedEvent(aid), null)).isTrue();
assertThat(testee.isValid(new CAddedEvent(aid, bid, cid), null)).isFalse(); | assertThat(testee.isValid(new CEvent(aid, bid, cid), null)).isFalse(); | 4 |
bencvt/LibShapeDraw | projects/main/src/test/java/libshapedraw/SetupTestEnvironment.java | [
"public class LSDController {\n private static LSDController instance;\n private final Logger log;\n private final LinkedHashSet<LibShapeDraw> apiInstances;\n private int topApiInstanceId;\n private MinecraftAccess minecraftAccess;\n private LSDUpdateCheck updateCheck;\n private boolean initialized;\n private long lastDump;\n\n private LSDController() {\n if (LSDGlobalSettings.isLoggingEnabled()) {\n log = new FileLogger(LSDModDirectory.DIRECTORY, ApiInfo.getName(), LSDGlobalSettings.isLoggingAppend());\n } else {\n log = new NullLogger();\n }\n apiInstances = new LinkedHashSet<LibShapeDraw>();\n topApiInstanceId = 0;\n\n TridentConfig trident = TridentConfig.getInstance();\n trident.addPropertyInterpolator(new ReadonlyColorPropertyInterpolator());\n trident.addPropertyInterpolator(new ReadonlyVector3PropertyInterpolator());\n trident.addPropertyInterpolator(new ReadonlyLineStylePropertyInterpolator());\n\n log.info(ApiInfo.getName() + \" v\" + ApiInfo.getVersion() + \" by \" + ApiInfo.getAuthors());\n log.info(ApiInfo.getUrlMain().toString());\n log.info(ApiInfo.getUrlSource().toString());\n log.info(getClass().getName() + \" instantiated\");\n }\n\n public static LSDController getInstance() {\n if (instance == null) {\n instance = new LSDController();\n }\n return instance;\n }\n\n public static Logger getLog() {\n return getInstance().log;\n }\n\n public static MinecraftAccess getMinecraftAccess() {\n return getInstance().minecraftAccess;\n }\n\n /**\n * @return true if mod_LibShapeDraw has been instantiated and is linked up\n * to the controller\n */\n public static boolean isInitialized() {\n return getInstance().initialized;\n }\n\n /**\n * Called by mod_LibShapeDraw to establish a link between the LSDController\n * and mod_LibShapeDraw singletons.\n */\n public void initialize(MinecraftAccess minecraftAccess) {\n if (isInitialized()) {\n // LibShapeDraw is probably installed incorrectly, causing\n // ModLoader/Forge to bogusly instantiate mod_LibShapeDraw multiple\n // times.\n throw new IllegalStateException(\"multiple initializations of controller\");\n }\n this.minecraftAccess = minecraftAccess;\n initialized = true;\n log.info(getClass().getName() + \" initialized by \" + minecraftAccess.getClass().getName());\n }\n\n /**\n * Called by LibShapeDraw's constructor.\n */\n public String registerApiInstance(LibShapeDraw apiInstance, String ownerId) {\n if (apiInstances.contains(apiInstance)) {\n throw new IllegalStateException(\"already registered\");\n }\n String apiInstanceId = apiInstance.getClass().getSimpleName() + \"#\" + topApiInstanceId;\n topApiInstanceId++;\n apiInstances.add(apiInstance);\n log.info(\"registered API instance \" + apiInstanceId + \":\" + ownerId);\n return apiInstanceId;\n }\n\n /**\n * Called by LibShapeDraw.unregister.\n */\n public boolean unregisterApiInstance(LibShapeDraw apiInstance) {\n boolean result = apiInstances.remove(apiInstance);\n if (result) {\n log.info(\"unregistered API instance \" + apiInstance.getInstanceId());\n }\n return result;\n }\n\n /**\n * Called by mod_LibShapeDraw.\n * Dispatch the respawn event.\n */\n public void respawn(ReadonlyVector3 playerCoords, boolean isNewServer, boolean isNewDimension) {\n log.finer(\"respawn\");\n\n // Dispatch respawn event.\n for (LibShapeDraw apiInstance : apiInstances) {\n if (!apiInstance.getEventListeners().isEmpty()) {\n LSDRespawnEvent event = new LSDRespawnEvent(apiInstance, playerCoords, isNewServer, isNewDimension);\n for (LSDEventListener listener : apiInstance.getEventListeners()) {\n listener.onRespawn(event);\n }\n }\n }\n }\n\n /**\n * Called by mod_LibShapeDraw.\n * Periodically dump API state to log if configured to do so.\n * Dispatch gameTick events.\n * Handle update check.\n */\n public void gameTick(ReadonlyVector3 playerCoords) {\n log.finer(\"gameTick\");\n\n // Debug dump.\n if (LSDGlobalSettings.getLoggingDebugDumpInterval() > 0) {\n long now = System.currentTimeMillis();\n if (now > lastDump + LSDGlobalSettings.getLoggingDebugDumpInterval()) {\n debugDump();\n lastDump = now;\n }\n }\n\n // Dispatch game tick event.\n for (LibShapeDraw apiInstance : apiInstances) {\n if (!apiInstance.getEventListeners().isEmpty()) {\n LSDGameTickEvent event = new LSDGameTickEvent(apiInstance, playerCoords);\n for (LSDEventListener listener : apiInstance.getEventListeners()) {\n if (listener != null) {\n listener.onGameTick(event);\n }\n }\n }\n }\n\n if (updateCheck == null) {\n // Launch a new thread to send an update check through the network.\n // Will only happen once per Minecraft session.\n //\n // We waited until the first game tick event to start the check\n // because we didn't have a place to notify the user until now.\n updateCheck = new LSDUpdateCheck();\n } else {\n updateCheck.announceResultIfReady(minecraftAccess);\n }\n }\n\n /**\n * Called by mod_LibShapeDraw.\n * Dispatch preRender events.\n * Render all registered shapes.\n */\n public void render(ReadonlyVector3 playerCoords, boolean isGuiHidden) {\n log.finer(\"render\");\n\n // Initialize OpenGL for our rendering.\n int origDepthFunc = GL11.glGetInteger(GL11.GL_DEPTH_FUNC);\n GL11.glPushMatrix();\n GL11.glTranslated(-playerCoords.getX(), -playerCoords.getY(), -playerCoords.getZ());\n\n // Dispatch prerender event and render.\n for (LibShapeDraw apiInstance : apiInstances) {\n minecraftAccess.profilerStartSection(apiInstance.getInstanceId()).profilerStartSection(\"prerender\");\n if (!apiInstance.getEventListeners().isEmpty()) {\n LSDPreRenderEvent event = new LSDPreRenderEvent(apiInstance, playerCoords, minecraftAccess.getPartialTick(), isGuiHidden);\n for (LSDEventListener listener : apiInstance.getEventListeners()) {\n if (listener != null) {\n listener.onPreRender(event);\n }\n }\n }\n minecraftAccess.profilerEndStartSection(\"render\");\n if (apiInstance.isVisible() && (!isGuiHidden || apiInstance.isVisibleWhenHidingGui())) {\n for (Shape shape : apiInstance.getShapes()) {\n if (shape != null) {\n shape.render(minecraftAccess);\n }\n }\n }\n minecraftAccess.profilerEndSection().profilerEndSection();\n }\n\n // Revert OpenGL settings so we don't impact any elements Minecraft has\n // left to render.\n GL11.glPopMatrix();\n GL11.glDepthMask(true);\n GL11.glDepthFunc(origDepthFunc);\n GL11.glEnable(GL11.GL_TEXTURE_2D);\n GL11.glDisable(GL11.GL_BLEND);\n }\n\n /**\n * Log all the things.\n */\n public boolean debugDump() {\n if (!log.isLoggable(Level.INFO)) {\n return false;\n }\n final String INDENT = \" \";\n StringBuilder line = new StringBuilder().append(\"debug dump for \").append(this).append(\":\\n\");\n for (LibShapeDraw apiInstance : apiInstances) {\n line.append(INDENT).append(apiInstance.getInstanceId()).append(\":\\n\");\n\n line.append(INDENT).append(INDENT).append(\"id=\");\n line.append(apiInstance).append('\\n');\n\n line.append(INDENT).append(INDENT).append(\"visible=\");\n line.append(apiInstance.isVisible()).append('\\n');\n\n line.append(INDENT).append(INDENT).append(\"visibleWhenHidingGui=\");\n line.append(apiInstance.isVisibleWhenHidingGui()).append('\\n');\n\n line.append(INDENT).append(INDENT).append(\"shapes=\");\n if (apiInstance.getShapes().size() == 0) {\n line.append(\"0\\n\");\n } else {\n line.append(apiInstance.getShapes().size()).append(\":\\n\");\n for (Shape shape : apiInstance.getShapes()) {\n line.append(INDENT).append(INDENT).append(INDENT).append(shape).append('\\n');\n }\n }\n\n line.append(INDENT).append(INDENT).append(\"eventListeners=\");\n if (apiInstance.getEventListeners().size() == 0) {\n line.append(\"0\\n\");\n } else {\n line.append(apiInstance.getEventListeners().size()).append(\":\\n\");\n for (LSDEventListener listener : apiInstance.getEventListeners()) {\n line.append(INDENT).append(INDENT).append(INDENT).append(listener).append('\\n');\n }\n }\n }\n log.info(line.toString());\n return true;\n }\n}",
"public class LSDGlobalSettings {\n public static boolean isLoggingEnabled() {\n return getInstance().loggingEnabled;\n }\n public static boolean isLoggingAppend() {\n return getInstance().loggingAppend;\n }\n public static int getLoggingDebugDumpInterval() {\n return getInstance().loggingDebugDumpInterval;\n }\n public static boolean isUpdateCheckEnabled() {\n return getInstance().updateCheckEnabled;\n }\n\n private final boolean loggingEnabled;\n private final boolean loggingAppend;\n private final int loggingDebugDumpInterval;\n private final boolean updateCheckEnabled;\n\n private static LSDGlobalSettings instance;\n\n private LSDGlobalSettings() {\n try {\n Properties props = new Properties();\n try {\n InputStream in;\n File file = new File(LSDModDirectory.DIRECTORY, \"settings.properties\");\n if (file.exists()) {\n in = new FileInputStream(file);\n } else {\n in = getClass().getResourceAsStream(\"default-settings.properties\");\n }\n props.load(in);\n in.close();\n } catch (IOException e) {\n throw new LSDInternalException(\"unable to load resource\", e);\n }\n loggingEnabled = LSDUtil.parseBooleanStrict(props.getProperty(\"logging-enabled\"));\n loggingAppend = LSDUtil.parseBooleanStrict(props.getProperty(\"logging-append\"));\n loggingDebugDumpInterval = Integer.parseInt(props.getProperty(\"logging-debug-dump-interval\"));\n updateCheckEnabled = LSDUtil.parseBooleanStrict(props.getProperty(\"update-check-enabled\"));\n } catch (Exception e) {\n e.printStackTrace();\n throw new LSDInternalException(\"unable to load global settings\", e);\n }\n }\n\n private static LSDGlobalSettings getInstance() {\n if (instance == null) {\n instance = new LSDGlobalSettings();\n }\n return instance;\n }\n}",
"public class LSDInternalException extends RuntimeException {\n private static final long serialVersionUID = 1L;\n\n public LSDInternalException(String message) {\n super(message);\n }\n\n public LSDInternalException(String message, Throwable t) {\n super(message, t);\n }\n}",
"public class LSDInternalReflectionException extends LSDInternalException {\n private static final long serialVersionUID = 1L;\n\n public LSDInternalReflectionException(String message) {\n super(message);\n }\n\n public LSDInternalReflectionException(String message, Exception e) {\n super(message, e);\n }\n}",
"public class LSDModDirectory {\n public static final File DIRECTORY = new File(getMinecraftDir(), \"mods\" + File.separator + ApiInfo.getName());\n\n /**\n * Use reflection to invoke the static method. This supports both normal\n * play (reobfuscated minecraft.jar) and development (deobfuscated classes\n * in MCP).\n */\n private static File getMinecraftDir() {\n try {\n Method m;\n try {\n m = Minecraft.class.getMethod(\"b\");\n } catch (NoSuchMethodException e) {\n m = Minecraft.class.getMethod(\"getMinecraftDir\");\n }\n return (File) m.invoke(null);\n } catch (Exception e) {\n throw new LSDInternalReflectionException(\"unable to invoke Minecraft.getMinecraftDir\", e);\n }\n }\n}",
"public class LSDUtil {\n public static final Random random = new Random();\n\n public static class FileLogger extends Logger {\n /** Formats lines like: \"2012-05-21 20:57:06.540 [INFO] example message\" */\n public static class LineFormatter extends Formatter {\n @Override\n public String format(LogRecord record) {\n StringWriter w = new StringWriter();\n String ts = new Timestamp((new Date()).getTime()).toString();\n w.append(ts);\n for (int pad = ts.length(); pad < 23; pad++) {\n w.append('0');\n }\n w.append(\" [\").append(record.getLevel().getName());\n w.append(\"] \").append(formatMessage(record)).append('\\n');\n if (record.getThrown() != null) {\n record.getThrown().printStackTrace(new PrintWriter(w));\n }\n return w.toString();\n }\n }\n\n public FileLogger(File baseDirectory, String name, boolean append) {\n super(name, null);\n baseDirectory.mkdirs();\n String logFilePattern = baseDirectory.getPath() + File.separator + name + \".log\";\n try {\n FileHandler handler = new FileHandler(logFilePattern, append);\n handler.setFormatter(new LineFormatter());\n addHandler(handler);\n } catch (IOException e) {\n throw new LSDInternalException(\"unable to add file handler for \" + logFilePattern, e);\n }\n }\n }\n\n public static class NullLogger extends Logger {\n public NullLogger() {\n super(\"null\", null);\n setLevel(Level.OFF);\n }\n }\n\n /**\n * A List without any backend storage. Permanently empty; every operation\n * is a no-op.\n */\n public static class NullList implements List<Object> {\n @Override public boolean add(Object e) { return false; }\n @Override public void add(int i, Object e) {}\n @Override public boolean addAll(Collection<? extends Object> c) { return false; }\n @Override public boolean addAll(int i, Collection<? extends Object> c) { return false; }\n @Override public void clear() {}\n @Override public boolean contains(Object e) { return false; }\n @Override public boolean containsAll(Collection<?> c) { return false; }\n @Override public Object get(int i) { return null; }\n @Override public int indexOf(Object e) { return -1; }\n @Override public boolean isEmpty() { return true; }\n @Override public Iterator<Object> iterator() { return Collections.emptyList().iterator(); }\n @Override public int lastIndexOf(Object e) { return -1; }\n @Override public ListIterator<Object> listIterator() { return Collections.emptyList().listIterator(); }\n @Override public ListIterator<Object> listIterator(int i) { return Collections.emptyList().listIterator(i); }\n @Override public boolean remove(Object e) { return false; }\n @Override public Object remove(int i) { return null; }\n @Override public boolean removeAll(Collection<?> c) { return false; }\n @Override public boolean retainAll(Collection<?> c) { return false; }\n @Override public Object set(int i, Object e) { return null; }\n @Override public int size() { return 0; }\n @Override public List<Object> subList(int i, int j) { return Collections.emptyList(); }\n @Override public Object[] toArray() { return Collections.emptyList().toArray(); }\n @Override public <T> T[] toArray(T[] arr) { return Collections.emptyList().toArray(arr); }\n }\n\n /**\n * A Map without any backend storage. Permanently empty; every operation\n * is a no-op.\n */\n public static class NullMap implements Map<Object,Object> {\n @Override public void clear() {}\n @Override public boolean containsKey(Object k) { return false; }\n @Override public boolean containsValue(Object v) { return false; }\n @Override public Set<Entry<Object, Object>> entrySet() { return Collections.emptySet(); }\n @Override public Object get(Object k) { return null; }\n @Override public boolean isEmpty() { return true; }\n @Override public Set<Object> keySet() { return Collections.emptySet(); }\n @Override public Object put(Object k, Object v) { return null; }\n @Override public void putAll(Map<? extends Object, ? extends Object> m) {}\n @Override public Object remove(Object k) { return null; }\n @Override public int size() { return 0; }\n @Override public Collection<Object> values() { return Collections.emptyList(); }\n }\n\n /**\n * Stricter version of Boolean.parseBoolean.\n */\n public static boolean parseBooleanStrict(String value) {\n if (value.equalsIgnoreCase(\"true\")) {\n return true;\n }\n if (value.equalsIgnoreCase(\"false\")) {\n return false;\n }\n throw new IllegalArgumentException(\"expecting true or false, got \" + value);\n }\n\n /**\n * Check whether a class is loaded without attempting to actually load it.\n */\n public static boolean isClassLoaded(String className) {\n try {\n Method m = ClassLoader.class.getDeclaredMethod(\"findLoadedClass\", String.class);\n m.setAccessible(true);\n return m.invoke(ClassLoader.getSystemClassLoader(), className) != null;\n } catch (Exception e) {\n throw new LSDInternalReflectionException(\"ClassLoader.findLoadedClass reflection failed\", e);\n }\n }\n\n /**\n * Create a uniquely-named temporary directory. This does essentially the\n * same thing as java.nio.file.Files#createTempDirectory, which we can't\n * use because it's a Java 7+ feature. Many Minecraft users are still on\n * Java 6.\n */\n public static synchronized File createTempDirectory(String prefix) {\n File baseDir = new File(System.getProperty(\"java.io.tmpdir\"));\n baseDir.mkdirs();\n while (true) {\n File tempDir = new File(baseDir, prefix + Math.abs(random.nextLong()));\n if (!tempDir.exists()) {\n if (tempDir.mkdir()) {\n return tempDir;\n }\n }\n }\n }\n\n /**\n * Attempt to retrieve the contents at the specified URL as a UTF8-encoded,\n * newline-normalized string. No special handling for redirects or other\n * HTTP return codes; just a quick-and-dirty GET. Return null if anything\n * breaks.\n * <p>\n * Never invoke this method from Minecraft's main thread as this is an I/O\n * operation that can taken an arbitrary amount of time (timeouts set to 10\n * seconds).\n */\n public static String getUrlContents(URL url) {\n try {\n StringBuilder result = new StringBuilder();\n URLConnection conn = url.openConnection();\n conn.setConnectTimeout(10000);\n conn.setReadTimeout(10000);\n BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), \"UTF8\"));\n String line;\n while ((line = in.readLine()) != null) {\n if (result.length() > 0) {\n result.append('\\n');\n }\n result.append(line);\n }\n in.close();\n return result.toString();\n } catch (IOException e) {\n LSDController.getLog().log(Level.WARNING, \"unable to read \" + url, e);\n return null;\n }\n }\n\n /**\n * For getting at those pesky private and obfuscated fields.\n * <p>\n * Caveat: this is not guaranteed to work correctly if there are more than\n * one declared fields of the same exact type on obj.\n * <p>\n * From {@link Class#getDeclaredFields}: \"The elements in the array\n * returned are not sorted and are not in any particular order.\"\n * <p>\n * In practice things work as expected even if there are multiple fields of\n * the same type, but this is dependent on the JVM implementation.\n * \n * @return the nth (usually 0) field of the specified type declared by\n * obj's class.\n */\n @SuppressWarnings(\"rawtypes\")\n public static Field getFieldByType(Class objClass, Class fieldType, int n) {\n try {\n int index = 0;\n for (Field field : objClass.getDeclaredFields()) {\n field.setAccessible(true);\n if (field.getType().equals(fieldType)) {\n if (index == n) {\n return field;\n }\n index++;\n }\n }\n throw new LSDInternalReflectionException(\"field not found\");\n } catch (Exception e) {\n throw new LSDInternalReflectionException(\"unable to reflect field type \" +\n String.valueOf(fieldType) + \"#\" + n + \" for \" + String.valueOf(objClass), e);\n }\n }\n\n /**\n * Convenience wrapper for reflecting a field, eliminating the checked\n * exceptions.\n */\n public static Object getFieldValue(Field field, Object obj) {\n try {\n return field.get(obj);\n } catch (Exception e) {\n throw new LSDInternalReflectionException(\"unable to get field \\\"\" +\n String.valueOf(field) + \"\\\" for \" + String.valueOf(obj), e);\n }\n }\n\n /**\n * Set a field's value even if it's marked as final.\n */\n public static void setFinalField(Field field, Object obj, Object value) {\n // Via http://stackoverflow.com/questions/3301635\n try {\n field.setAccessible(true);\n Field fieldField = Field.class.getDeclaredField(\"modifiers\");\n fieldField.setAccessible(true);\n fieldField.setInt(field, field.getModifiers() & ~Modifier.FINAL);\n field.set(obj, value);\n } catch (Exception e) {\n throw new LSDInternalReflectionException(\"unable to set final field \\\"\" +\n String.valueOf(field) + \"\\\" for \" + String.valueOf(obj), e);\n }\n }\n}"
] | import java.io.File;
import java.lang.reflect.Field;
import libshapedraw.internal.LSDController;
import libshapedraw.internal.LSDGlobalSettings;
import libshapedraw.internal.LSDInternalException;
import libshapedraw.internal.LSDInternalReflectionException;
import libshapedraw.internal.LSDModDirectory;
import libshapedraw.internal.LSDUtil;
import org.junit.BeforeClass;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode; | package libshapedraw;
/**
* To ensure that JUnit testing does not touch the production Minecraft
* installation, every test case should extend SetupTestEnvironment.TestCase.
* <p>
* Involves some ClassLoader and Reflection hackery.
* <p>
* If you're running one of these test case classes individually in Eclipse or
* another IDE, you'll probably need to add the following to the VM arguments:
* -Djava.library.path=../../lib/natives
*/
public class SetupTestEnvironment {
private static File testMinecraftDirectory = null;
private static final String MODDIRECTORY_CLASS_NAME = "libshapedraw.internal.LSDModDirectory";
private static final String MODDIRECTORY_FIELD_NAME = "DIRECTORY";
public static class TestCase {
protected static final MockMinecraftAccess mockMinecraftAccess = new MockMinecraftAccess();
@BeforeClass
public static void setupTestEnvironment() throws LWJGLException {
if (setup()) {
LSDController.getInstance().initialize(mockMinecraftAccess);
try {
Display.setDisplayMode(new DisplayMode(0, 0));
Display.create();
} catch (UnsatisfiedLinkError e) {
throw new LSDInternalException("LWJGL link error, " +
"probably caused by missing VM argument:\n" +
"-Djava.library.path=../../lib/natives", e);
}
}
}
/**
* An alternative to @Test(expected=SomeException.class) for test cases
* with multiple lines that should be throwing exceptions.
*/
public static void assertThrows(Class<? extends Throwable> expected, Runnable method) {
try {
method.run();
} catch (Throwable thrown) {
if (expected.isInstance(thrown)) {
return;
}
throw new RuntimeException("expected " + String.valueOf(expected) + " not thrown", thrown);
}
throw new RuntimeException("expected " + String.valueOf(expected) + " not thrown");
}
public static void assertThrowsIAE(Runnable method) {
assertThrows(IllegalArgumentException.class, method);
}
public static File getTempDirectory() {
return testMinecraftDirectory;
}
}
private static boolean setup() {
println("setup test environment");
if (testMinecraftDirectory == null) {
testMinecraftDirectory = LSDUtil.createTempDirectory("LibShapeDrawJUnitTemp");
monkeyPatch();
return true;
}
// else we've already monkey patched, as we're running an entire test suite
return false;
}
private static void monkeyPatch() {
if (LSDUtil.isClassLoaded(MODDIRECTORY_CLASS_NAME)) {
throw new LSDInternalException("internal error, " + MODDIRECTORY_CLASS_NAME + " already loaded");
}
// Force ModDirectory class load and monkey patch ModDirectory.DIRECTORY.
File origDir = LSDModDirectory.DIRECTORY;
Field field;
try {
field = LSDModDirectory.class.getDeclaredField(MODDIRECTORY_FIELD_NAME);
} catch (Exception e) {
throw new LSDInternalReflectionException("unable to get field named " + MODDIRECTORY_FIELD_NAME, e);
}
LSDUtil.setFinalField(field, null, testMinecraftDirectory);
println("monkey patched directory field from:\n " + origDir + "\nto:\n " + testMinecraftDirectory);
if (!LSDModDirectory.class.getName().equals(MODDIRECTORY_CLASS_NAME)
|| !LSDUtil.isClassLoaded(MODDIRECTORY_CLASS_NAME)
|| !LSDModDirectory.DIRECTORY.equals(testMinecraftDirectory)) {
throw new LSDInternalException("internal error, sanity check failed");
}
disableUpdateCheck();
}
private static void disableUpdateCheck() { | if (!LSDGlobalSettings.isUpdateCheckEnabled()) { | 1 |
leandreck/spring-typescript-services | annotations/src/main/java/org/leandreck/endpoints/processor/TypeScriptEndpointProcessor.java | [
"public class MultipleConfigurationsFoundException extends Exception {\n\n private final transient Set<Element> elementsWithConfiguration;\n\n /**\n * @param elementsWithConfiguration all {@link Element}s annotated with {@link org.leandreck.endpoints.annotations.TypeScriptTemplatesConfiguration}\n */\n public MultipleConfigurationsFoundException(final Set<? extends Element> elementsWithConfiguration) {\n this.elementsWithConfiguration = new HashSet<>(elementsWithConfiguration);\n }\n\n /**\n * All {@link Element}s annotated with {@link org.leandreck.endpoints.annotations.TypeScriptTemplatesConfiguration}.\n * @return set of {@link Element}\n */\n public Set<Element> getElementsWithConfiguration() {\n return elementsWithConfiguration;\n }\n}",
"public class EndpointNode {\n\n private final String serviceName;\n private final String serviceURL;\n private final String template;\n private final List<MethodNode> methods;\n private final List<MethodNode> getMethods;\n private final List<MethodNode> headMethods;\n private final List<MethodNode> postMethods;\n private final List<MethodNode> putMethods;\n private final List<MethodNode> patchMethods;\n private final List<MethodNode> deleteMethods;\n private final List<MethodNode> optionsMethods;\n private final List<MethodNode> traceMethods;\n private final Set<TypeNode> types;\n private final PrintConfiguration printConfiguration;\n private final String doc;\n\n\n /**\n * Constructor.\n *\n * @param serviceName {@link #getServiceName()}\n * @param serviceURL {@link #getServiceURL()}\n * @param doc {@link #getDoc()}\n * @param template {@link #getTemplate()}\n * @param methods {@link #getMethods}\n * @param printConfiguration {@link #getPrintConfiguration()}\n */\n EndpointNode(final String serviceName, final String serviceURL, final String doc, final String template, final List<MethodNode> methods, final PrintConfiguration printConfiguration) {\n this.serviceName = serviceName;\n this.serviceURL = serviceURL;\n this.doc = doc;\n this.template = template;\n this.methods = methods;\n this.printConfiguration = printConfiguration;\n\n this.getMethods = this.getMethods().stream().filter(m -> m.getHttpMethods().contains(\"get\")).collect(toList());\n this.headMethods = this.getMethods().stream().filter(m -> m.getHttpMethods().contains(\"head\")).collect(toList());\n this.postMethods = this.getMethods().stream().filter(m -> m.getHttpMethods().contains(\"post\")).collect(toList());\n this.putMethods = this.getMethods().stream().filter(m -> m.getHttpMethods().contains(\"put\")).collect(toList());\n this.patchMethods = this.getMethods().stream().filter(m -> m.getHttpMethods().contains(\"patch\")).collect(toList());\n this.deleteMethods = this.getMethods().stream().filter(m -> m.getHttpMethods().contains(\"delete\")).collect(toList());\n this.optionsMethods = this.getMethods().stream().filter(m -> m.getHttpMethods().contains(\"options\")).collect(toList());\n this.traceMethods = this.getMethods().stream().filter(m -> m.getHttpMethods().contains(\"trace\")).collect(toList());\n\n this.types = collectTypes();\n }\n\n private Set<TypeNode> collectTypes() {\n final Map<String, TypeNode> typeMap = new HashMap<>();\n\n this.getMethods().stream()\n .map(MethodNode::getTypes)\n .flatMap(Collection::stream)\n .filter(TypeNode::isDeclaredComplexType)\n .forEach(type -> typeMap.put(type.getTypeName(), type));\n return new HashSet<>(typeMap.values());\n }\n\n /**\n * Name of this EndpointNode, usually this is the Name of the Java Class of the Endpoint.\n *\n * @return serviceName\n */\n public String getServiceName() {\n return serviceName;\n }\n\n /**\n * Base URL of this EndpointNode corresponds to value of @RequestMapping on the Java Class.\n *\n * @return serviceURL\n */\n public String getServiceURL() {\n return serviceURL;\n }\n\n public List<MethodNode> getMethods() {\n return methods;\n }\n\n public String getTemplate() {\n return template;\n }\n\n public Set<TypeNode> getTypes() {\n return types;\n }\n\n public List<MethodNode> getGetMethods() {\n return getMethods;\n }\n\n public List<MethodNode> getHeadMethods() {\n return headMethods;\n }\n\n public List<MethodNode> getPostMethods() {\n return postMethods;\n }\n\n public List<MethodNode> getTraceMethods() {\n return traceMethods;\n }\n\n public List<MethodNode> getOptionsMethods() {\n return optionsMethods;\n }\n\n public List<MethodNode> getDeleteMethods() {\n return deleteMethods;\n }\n\n public List<MethodNode> getPatchMethods() {\n return patchMethods;\n }\n\n public List<MethodNode> getPutMethods() {\n return putMethods;\n }\n\n /**\n * Template Engine Configuration of this {@link EndpointNode} for customizing the generated output.\n * @return printConfiguration\n */\n public PrintConfiguration getPrintConfiguration() {\n return printConfiguration;\n }\n\n /**\n * Documentation of this Endpointnode, this is the pure content of the JavaDoc of the Endpoint Java Class,\n * without any formatting characters or indentation.\n *\n * @return doc\n */\n public String getDoc() {\n return doc;\n }\n}",
"public class EndpointNodeFactory {\n\n private final MethodNodeFactory methodNodeFactory;\n private final TemplateConfiguration configuration;\n private final Elements elementUtils;\n\n public EndpointNodeFactory(final TemplateConfiguration configuration,\n final Types typeUtils,\n final Elements elementUtils) {\n this.configuration = configuration;\n this.methodNodeFactory = new MethodNodeFactory(configuration, typeUtils, elementUtils);\n this.elementUtils = elementUtils;\n }\n\n public EndpointNode createEndpointNode(final TypeElement typeElement) {\n\n final TypeScriptEndpoint annotation = typeElement.getAnnotation(TypeScriptEndpoint.class);\n\n final String name = defineName(typeElement, annotation);\n final String url = defineUrl(typeElement);\n final String template = defineTemplate(annotation);\n final List<MethodNode> methods = defineMethods(typeElement, (DeclaredType) typeElement.asType());\n\n final String doc = elementUtils.getDocComment(typeElement);\n\n return new EndpointNode(name, url, doc, template, methods, configuration.getGlobalPrintConfiguration());\n }\n\n private List<MethodNode> defineMethods(final TypeElement typeElement, final DeclaredType containingType) {\n final TypeMirror superclass = typeElement.getSuperclass();\n final List<MethodNode> superclassMethods;\n if (DECLARED.equals(superclass.getKind()) && !\"java.lang.Object\".equals(superclass.toString())) {\n superclassMethods = defineMethods((TypeElement) ((DeclaredType)superclass).asElement(), containingType);\n } else {\n superclassMethods = new ArrayList<>(20);\n }\n\n //Implemented Interfaces:\n typeElement.getInterfaces().stream()\n .flatMap(it -> defineMethods((TypeElement) ((DeclaredType)it).asElement(), containingType).stream())\n .forEach(superclassMethods::add);\n\n //Own enclosed Methods\n ElementFilter.methodsIn(typeElement.getEnclosedElements()).stream()\n .map(methodElement -> methodNodeFactory.createMethodNode(methodElement, containingType))\n .filter(method -> !method.isIgnored())\n .forEach(superclassMethods::add);\n return superclassMethods;\n }\n\n private static String defineName(final TypeElement typeElement, final TypeScriptEndpoint annotation) {\n final String name;\n if (annotation.value().isEmpty()) {\n name = typeElement.getSimpleName().toString();\n } else {\n name = annotation.value();\n }\n return name;\n }\n\n private static String defineUrl(final TypeElement typeElement) {\n final RequestMapping requestMapping = typeElement.getAnnotation(RequestMapping.class);\n if (requestMapping != null) {\n final String[] mappings = requestMapping.value();\n if (mappings.length > 0) {\n return mappings[0];\n }\n }\n return \"\";\n }\n\n private String defineTemplate(final TypeScriptEndpoint annotation) {\n final String template;\n if (annotation == null || annotation.template().isEmpty()) {\n template = configuration.getEndpointTemplate();\n } else {\n template = annotation.template();\n }\n\n return template;\n }\n}",
"public class MissingConfigurationTemplateException extends RuntimeException {\n\n private final transient Element element;\n\n MissingConfigurationTemplateException(final String message, final Element element) {\n super(message);\n this.element = element;\n }\n\n /**\n * @return The Element processed while hitting the missing {@link org.leandreck.endpoints.processor.config.TemplateConfiguration}\n */\n public Element getElement() {\n return element;\n }\n}",
"public abstract class TypeNode {\n\n protected static final String EMPTY_JAVA_DOC = \"\";\n private final boolean optional;\n\n protected TypeNode(final boolean optional) {\n this.optional = optional;\n }\n\n\n /**\n * {@link TypeNodeKind} of this TypeNode.\n *\n * @return {@link TypeNodeKind}\n */\n public abstract TypeNodeKind getKind();\n\n /**\n * Declared name of this Type as Methodparameter or Variable. For example\n * <code>private String someFieldName;</code> results in \"someFieldName\" as fieldName or\n * <code>public void execute(String anotherFieldName) {...}</code> in \"anotherFieldName\".\n * @return fieldname\n */\n public abstract String getFieldName();\n\n /**\n * Declared name or value in {@link org.springframework.web.bind.annotation.RequestParam} or\n * {@link org.springframework.web.bind.annotation.PathVariable} Annotation of this Type.<br>\n * <br>\n * For example:<br>\n * {@code public void delete(@PathVariable(name = \"pathVariable\") Long id, @RequestParam(name = \"queryParam\") String queryParameter){...}}<br>\n * results in \"pathVariable\" as parameterName for <code>id</code> and \"queryParam\" for <code>queryParameter</code>.\n * @return parametername\n */\n public abstract String getParameterName();\n\n /**\n * Returns the parameterName if set or the fieldName and appends an '?' if this TypeNode {@link #isOptional()} == true.\n * Templates can use this to declare Method-Parameters or use {@link #getAsVariableName()} and declare optional Parameters them self.\n *\n * @return variable name as function parameter\n */\n public String getAsFunctionParameter() {\n final String functionParameter = getParameterName() == null ? getFieldName() : getParameterName();\n return isOptional() ? functionParameter + '?' : functionParameter;\n }\n\n /**\n * Returns the parameterName if set or the fieldName and does not append an '?' if this TypeNode {@link #isOptional()} == true.\n * Templates should use this as Variable-Name if used not as Function-Parameter.\n *\n * @return variable name\n */\n public String getAsVariableName() {\n return getParameterName() == null ? getFieldName() : getParameterName();\n }\n\n /**\n * This is the raw name of this TypeNode without any decorations for collections or maps or bound Generics.<br>\n * Most of the time you should use {@link #getType()} in your templates.\n * For example:<br>\n * <br>\n * <ul>\n * <li>{@code Map<String, Number> -> 'Map'}</li>\n * <li>{@code List<GenericType<Innertype>> -> 'List'}</li>\n * </ul>\n *\n * @return name of this TypeNode.\n * @see #getType()\n */\n public abstract String getTypeName();\n\n public String getTypeNameVariable() {\n return getType();\n }\n\n /**\n * Returns the template-usable String representing this {@link TypeNode} with added decorations like '[]' as suffix for collections or\n * bound Generics.<br>\n * For example:<br>\n * <br>\n * <ul>\n * <li>{@code Map<String, Number> -> '{ [index: string]: number }'}</li>\n * <li>{@code List<GenericType<Innertype>> -> 'GenericType<InnerType>[]'}</li>\n * </ul>\n *\n * @return String representing this Instance of TypeNode\n * @see #getTypeName()\n */\n public abstract String getType();\n\n public String getVariableType() {\n return getTypeName();\n }\n\n /**\n * Classpath to the Freemarker Template which is used to generate this TypeNode.\n *\n * @return Path to template\n */\n public abstract String getTemplate();\n\n /**\n * Typeparameters are bound Generics as in {@code GenericType<BoundType>}.\n * For example {@code Type<TypeOne, TypeTwo>} results in a List with the two Entries with TypeNodes for 'TypeOne' and 'TypeTwo'.\n * @return all bound TypeParameters\n */\n public abstract List<TypeNode> getTypeParameters();\n\n public abstract List<TypeNode> getChildren();\n\n public abstract Set<TypeNode> getTypes();\n\n public abstract Set<TypeNode> getImports();\n\n public Set<EnumValue> getEnumValues() {\n return Collections.emptySet();\n }\n\n /**\n * Returns true if this TypeNode is a mapped Type.\n *\n * @return <code>true</code> if mapped\n * <code>false</code> otherwise\n */\n public boolean isMappedType() {\n return false;\n }\n\n public boolean isDeclaredComplexType() {\n return !(this.isMappedType()\n || (TypeNodeKind.MAP == this.getKind()));\n }\n\n /**\n * Returns wether this TypeNode is an optional Parameter or not.\n *\n * @return true if this TypeNode is wrapped in an {@link java.util.Optional} or is declared as not required in the respective Annotation<br>\n * false in all other cases.\n */\n public boolean isOptional() {\n return optional;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n final TypeNode typeNode = (TypeNode) o;\n return getTypeName().equals(typeNode.getTypeName());\n }\n\n @Override\n public int hashCode() {\n return getTypeName().hashCode();\n }\n\n /**\n * Documentation of this TypeNode, this is the pure content of the JavaDoc of the Java Type or Element,\n * without any formatting characters or indentation.\n *\n * @return doc\n */\n public String getDoc() {\n return EMPTY_JAVA_DOC;\n }\n}",
"public class Engine {\n\n private final Configuration freemarkerConfiguration;\n private final TemplateConfiguration templateConfiguration;\n\n public Engine(TemplateConfiguration configuration) {\n this.templateConfiguration = configuration;\n\n // Create your Configuration instance, and specify if up to what FreeMarker\n // version (here 2.3.25) do you want to apply the fixes that are not 100%\n // backward-compatible. See the Configuration JavaDoc for details.\n this.freemarkerConfiguration = new Configuration(Configuration.VERSION_2_3_23);\n\n // Set the preferred charset template files are stored in. UTF-8 is\n // a good choice in most applications:\n this.freemarkerConfiguration.setDefaultEncoding(\"UTF-8\");\n\n // Specify the source where the template files come from. Here I set a\n // plain directory for it, but non-file-system sources are possible too:\n this.freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), \"/\");\n\n\n // Sets how errors will appear.\n this.freemarkerConfiguration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);\n\n // Don't log exceptions inside FreeMarker that it will thrown at you anyway:\n this.freemarkerConfiguration.setLogTemplateExceptions(false);\n }\n\n public void processEndpoint(final EndpointNode clazz, final Writer out) throws IOException, TemplateException {\n final Template service = this.freemarkerConfiguration.getTemplate(clazz.getTemplate());\n service.process(clazz, out);\n out.append(\"\\n\");\n }\n\n public void processIndexTs(final TypesPackage params, final Writer out) throws IOException, TemplateException {\n final Template service = this.freemarkerConfiguration.getTemplate(templateConfiguration.getIndexTemplate());\n service.process(params, out);\n out.append(\"\\n\");\n }\n\n public void processModuleTs(final TypesPackage params, final Writer out) throws IOException, TemplateException {\n final Template service = this.freemarkerConfiguration.getTemplate(templateConfiguration.getApiModuleTemplate());\n service.process(params, out);\n out.append(\"\\n\");\n }\n\n public void processTypeScriptTypeNode(final TypeNode node, final Writer out) throws IOException, TemplateException {\n final Template temp = this.freemarkerConfiguration.getTemplate(node.getTemplate());\n temp.process(node, out);\n out.append(\"\\n\");\n }\n\n public void processServiceConfig(final Writer out) throws IOException, TemplateException {\n final Template service = this.freemarkerConfiguration.getTemplate(\"/org/leandreck/endpoints/templates/typescript/serviceconfig.ftl\");\n service.process(null, out);\n out.append(\"\\n\");\n }\n}",
"public class TypesPackage {\n\n private final Set<EndpointNode> endpoints;\n private final Set<TypeNode> types;\n\n public TypesPackage(final Set<EndpointNode> endpoints, final Set<TypeNode> types) {\n this.endpoints = endpoints;\n this.types = types;\n }\n\n public Set<EndpointNode> getEndpoints() {\n return endpoints;\n }\n\n public Set<TypeNode> getTypes() {\n return types;\n }\n}"
] | import freemarker.template.TemplateException;
import org.leandreck.endpoints.annotations.TypeScriptEndpoint;
import org.leandreck.endpoints.annotations.TypeScriptIgnore;
import org.leandreck.endpoints.annotations.TypeScriptTemplatesConfiguration;
import org.leandreck.endpoints.annotations.TypeScriptType;
import org.leandreck.endpoints.processor.config.MultipleConfigurationsFoundException;
import org.leandreck.endpoints.processor.config.TemplateConfiguration;
import org.leandreck.endpoints.processor.model.EndpointNode;
import org.leandreck.endpoints.processor.model.EndpointNodeFactory;
import org.leandreck.endpoints.processor.model.typefactories.MissingConfigurationTemplateException;
import org.leandreck.endpoints.processor.model.TypeNode;
import org.leandreck.endpoints.processor.printer.Engine;
import org.leandreck.endpoints.processor.printer.TypesPackage;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Types;
import javax.tools.StandardLocation;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import static java.util.stream.Collectors.toList;
import static javax.tools.Diagnostic.Kind.ERROR; | /**
* Copyright © 2016 Mathias Kowalzik ([email protected])
*
* 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.leandreck.endpoints.processor;
/**
* Annotation Processor for TypeScript-Annotations.
*/
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class TypeScriptEndpointProcessor extends AbstractProcessor {
private Filer filer;
private Messager messager;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
filer = processingEnv.getFiler();
messager = processingEnv.getMessager();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
final Set<String> annotations = new LinkedHashSet<>();
annotations.add(TypeScriptEndpoint.class.getCanonicalName());
annotations.add(TypeScriptIgnore.class.getCanonicalName());
annotations.add(TypeScriptType.class.getCanonicalName());
return annotations;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
final Set<? extends Element> annotated = roundEnv.getElementsAnnotatedWith(TypeScriptEndpoint.class);
final List<TypeElement> endpoints = annotated.stream()
.filter(element -> !ElementKind.METHOD.equals(element.getKind()))
.map(element -> (TypeElement) element)
.collect(toList());
if (!endpoints.isEmpty()) {
try {
final TemplateConfiguration templateConfiguration = TemplateConfiguration.buildFromEnvironment(roundEnv);
processEndpoints(templateConfiguration, endpoints);
} catch (MultipleConfigurationsFoundException mcfe) {
printMessage("Multiple configurations found for the template locations.");
printConfigurationErrors(mcfe);
} catch (MissingConfigurationTemplateException mcte) {
printMessage(mcte.getElement(), mcte.getMessage());
} catch (Exception unknown) {
final StringWriter writer = new StringWriter();
unknown.printStackTrace(new PrintWriter(writer));
printMessage("Unkown Error occured, please file a Bug https://github.com/leandreck/spring-typescript-services/issues \n%s", writer.toString());
}
}
return true;
}
private void processEndpoints(TemplateConfiguration templateConfiguration, final List<TypeElement> endpointElements) {
final Types typeUtils = processingEnv.getTypeUtils(); | final Engine engine = new Engine(templateConfiguration); | 5 |
hhua/product-hunt-android | app/src/main/java/com/hhua/android/producthunt/fragments/FollowingFragment.java | [
"public class ProductHuntApplication extends com.activeandroid.app.Application {\n private static Context context;\n\n @Override\n public void onCreate() {\n super.onCreate();\n ProductHuntApplication.context = this;\n Parse.initialize(this, ApiConfig.PARSE_API_APPLICATION_ID, ApiConfig.PARSE_API_CLIENT_KEY);\n }\n\n\n public static ProductHuntClient getRestClient() {\n return (ProductHuntClient) ProductHuntClient.getInstance(ProductHuntClient.class, ProductHuntApplication.context);\n }\n\n}",
"public class ProductHuntClient extends OAuthBaseClient {\n public static final Class<? extends Api> REST_API_CLASS = ProductHuntApi.class;\n public static final String REST_URL = ApiConfig.PRODUCT_API_ENDPOINT;\n public static final String REST_CONSUMER_KEY = ApiConfig.PRODUCT_API_CONSUMER_KEY;\n public static final String REST_CONSUMER_SECRET = ApiConfig.PRODUCT_API_CONSUMER_SECRET;\n\n public static final String REST_CALLBACK_URL = ApiConfig.PRODUCT_API_CALLBACK_URL;\n\n public ProductHuntClient(Context context) {\n super(context, REST_API_CLASS, REST_URL, REST_CONSUMER_KEY, REST_CONSUMER_SECRET, REST_CALLBACK_URL);\n }\n\n // Get Tech Hunts\n // GET /v1/posts?days_ago=1\n public void getTechHunts(int daysAgo, AsyncHttpResponseHandler handler){\n String apiUrl = getApiUrl(\"posts\");\n\n RequestParams params = new RequestParams();\n if (daysAgo > 0){\n params.put(\"days_ago\", daysAgo);\n }\n\n // Execute the request\n // No idea why I need to add header by myself\n getClient().addHeader(\"Authorization\", \"Bearer \" + getClient().getAccessToken().getToken());\n getClient().get(apiUrl, params, handler);\n }\n\n // Get Post\n // GET /v1/posts/:id\n public void getPost(int postId, AsyncHttpResponseHandler handler){\n String apiUrl = getApiUrl(\"posts/\" + postId);\n\n RequestParams params = new RequestParams();\n getClient().addHeader(\"Authorization\", \"Bearer \" + getClient().getAccessToken().getToken());\n getClient().get(apiUrl, params, handler);\n }\n\n // Get Featured Collections\n // GET /v1/collections\n public void getFeaturedCollections(int olderId, AsyncHttpResponseHandler handler){\n String apiUrl = getApiUrl(\"collections\");\n\n RequestParams params = new RequestParams();\n\n params.put(\"sort_by\", \"featured_at\");\n params.put(\"order\", \"desc\");\n params.put(\"per_page\", 20);\n params.put(\"search[featured]\", true);\n\n if (olderId > -1) {\n params.put(\"older\", olderId);\n }\n\n getClient().addHeader(\"Authorization\", \"Bearer \" + getClient().getAccessToken().getToken());\n getClient().get(apiUrl, params, handler);\n }\n\n // Get Selected Collections\n // GET /v1/collections/:id\n public void getCollection(int collectionId, AsyncHttpResponseHandler handler){\n String apiUrl = getApiUrl(\"collections/\" + collectionId);\n\n RequestParams params = new RequestParams();\n\n getClient().addHeader(\"Authorization\", \"Bearer \" + getClient().getAccessToken().getToken());\n getClient().get(apiUrl, params, handler);\n }\n\n // Get Current User Info\n // GET /v1/me\n public void getSettings(AsyncHttpResponseHandler handler){\n String apiUrl = getApiUrl(\"me\");\n\n RequestParams params = new RequestParams();\n\n getClient().addHeader(\"Authorization\", \"Bearer \" + getClient().getAccessToken().getToken());\n getClient().get(apiUrl, params, handler);\n }\n\n // Get All notifications\n // GET /v1/notifications\n public void getAllNotifications(AsyncHttpResponseHandler handler){\n String apiUrl = getApiUrl(\"notifications\");\n\n RequestParams params = new RequestParams();\n params.put(\"per_page\", 50);\n params.put(\"search[type]\", \"all\");\n\n getClient().addHeader(\"Authorization\", \"Bearer \" + getClient().getAccessToken().getToken());\n getClient().get(apiUrl, params, handler);\n }\n\n // Get a User\n // GET /v1/users/:id / /v1/user/:username\n public void getUser(int userId, AsyncHttpResponseHandler handler){\n String apiUrl = getApiUrl(\"users/\" + userId);\n\n RequestParams params = new RequestParams();\n\n getClient().addHeader(\"Authorization\", \"Bearer \" + getClient().getAccessToken().getToken());\n getClient().get(apiUrl, params, handler);\n }\n\n // Get Followers\n // GET /v1/users/:id/followers\n public void getFollowers(int userId, int olderId, AsyncHttpResponseHandler handler){\n String apiUrl = getApiUrl(\"users/\" + userId + \"/followers\");\n\n RequestParams params = new RequestParams();\n params.put(\"per_page\", 50);\n params.put(\"user_id\", userId);\n params.put(\"order\", \"desc\");\n\n if (olderId > -1){\n params.put(\"older\", olderId);\n }\n\n getClient().addHeader(\"Authorization\", \"Bearer \" + getClient().getAccessToken().getToken());\n getClient().get(apiUrl, params, handler);\n }\n\n // Get Followers\n // GET /v1/users/:id/following\n public void getFollowing(int userId, int olderId, AsyncHttpResponseHandler handler){\n String apiUrl = getApiUrl(\"users/\" + userId + \"/following\");\n\n RequestParams params = new RequestParams();\n params.put(\"per_page\", 50);\n params.put(\"user_id\", userId);\n params.put(\"order\", \"desc\");\n\n if (olderId > -1){\n params.put(\"older\", olderId);\n }\n\n getClient().addHeader(\"Authorization\", \"Bearer \" + getClient().getAccessToken().getToken());\n getClient().get(apiUrl, params, handler);\n }\n\n // Get Collections created by user\n // GET /v1/users/:id/collections\n public void getCollectionsByUser(int userId, int page, AsyncHttpResponseHandler handler){\n String apiUrl = getApiUrl(\"users/\" + userId + \"/collections\");\n RequestParams params = new RequestParams();\n\n params.put(\"sort_by\", \"created_at\");\n params.put(\"order\", \"desc\");\n params.put(\"per_page\", 50);\n\n if (page > 0) {\n params.put(\"page\", page);\n }\n\n getClient().addHeader(\"Authorization\", \"Bearer \" + getClient().getAccessToken().getToken());\n getClient().get(apiUrl, params, handler);\n }\n}",
"public class UserActivity extends AppCompatActivity {\n private final String LOG_D = \"UserActivity\";\n\n private ProductHuntClient client;\n private User user;\n private List<TechHunt> votedPosts;\n private List<TechHunt> submittedPosts;\n private List<TechHunt> makerPosts;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_user);\n final Toolbar toolbar = (Toolbar) findViewById(R.id.transparent_toolbar);\n setSupportActionBar(toolbar);\n\n ParseAnalytics.trackAppOpenedInBackground(getIntent());\n\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n Intent intent = getIntent();\n int userId = intent.getIntExtra(User.USER_ID_MESSAGE, -1);\n\n setTitle(\"\");\n\n if (userId == -1){\n Log.d(LOG_D, \"User ID (\" + userId + \") incorrect!\");\n return;\n }\n\n client = ProductHuntApplication.getRestClient();\n client.getUser(userId, new JsonHttpResponseHandler(){\n @Override\n public void onSuccess(int statusCode, Header[] headers, JSONObject response) {\n Log.d(LOG_D, response.toString());\n\n try {\n user = User.fromJSON(response.getJSONObject(\"user\"));\n\n TextView tvUserName = (TextView) findViewById(R.id.tvUserName);\n TextView tvUserDescription = (TextView) findViewById(R.id.tvUserDescription);\n TextView tvTwitterUserName = (TextView) findViewById(R.id.tvTwitterUserName);\n ImageView ivUserProfile = (ImageView) findViewById(R.id.ivUserProfile);\n ivUserProfile.setImageResource(0);\n\n tvUserName.setText(user.getName());\n tvUserDescription.setText(user.getHeadline());\n tvTwitterUserName.setText(\"@\" + user.getTwitterName());\n\n Picasso.with(getApplicationContext()).load(user.getLargeProfileImageUrl()).fit().into(ivUserProfile);\n\n final RelativeLayout userPageHeader = (RelativeLayout) findViewById(R.id.userPageHeader);\n toolbar.bringToFront();\n Picasso.with(getApplicationContext()).load(user.getBackgroundImageUrl()).resize(500, 300).centerCrop().into(new Target() {\n @Override\n public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {\n userPageHeader.setBackground(new BitmapDrawable(getApplicationContext().getResources(), bitmap));\n toolbar.bringToFront();\n }\n\n @Override\n public void onBitmapFailed(Drawable errorDrawable) {\n Log.d(\"USER_BITMAP\", \"FAILED\");\n }\n\n @Override\n public void onPrepareLoad(Drawable placeHolderDrawable) {\n Log.d(\"USER_BITMAP\", \"Prepare Load\");\n }\n });\n\n // Load page slider data\n votedPosts = new ArrayList<TechHunt>();\n JSONArray votes = response.getJSONObject(\"user\").getJSONArray(\"votes\");\n for(int i = 0; i < votes.length(); i++){\n votedPosts.add(TechHunt.fromJSON(votes.getJSONObject(i).getJSONObject(\"post\")));\n }\n\n submittedPosts = new ArrayList<TechHunt>();\n submittedPosts.addAll(TechHunt.fromJSONArray(response.getJSONObject(\"user\").getJSONArray(\"posts\")));\n\n makerPosts = new ArrayList<TechHunt>();\n makerPosts.addAll(TechHunt.fromJSONArray(response.getJSONObject(\"user\").getJSONArray(\"maker_of\")));\n\n // Get the view pager\n ViewPager vpPager = (ViewPager) findViewById(R.id.userPageViewPager);\n // Set the view pager adapter to the pager\n vpPager.setAdapter(new UserPagerAdapter(getSupportFragmentManager()));\n // Find the pager sliding tabs\n PagerSlidingTabStrip tabStrip = (PagerSlidingTabStrip) findViewById(R.id.userPageTabs);\n // Attach pager tabs to the viewpager\n tabStrip.setViewPager(vpPager);\n\n }catch (JSONException e){\n e.printStackTrace();\n }\n\n }\n\n @Override\n public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {\n Log.d(LOG_D, errorResponse.toString());\n }\n });\n\n\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n // Respond to the action bar's Up/Home button\n case android.R.id.home:\n //NavUtils.navigateUpFromSameTask(this);\n finish(); // Destroys the Activity and goes back the activity which starts it.\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n // Return the order of the fragment in the view pager\n public class UserPagerAdapter extends FragmentPagerAdapter {\n //private String tabTitles[] = {\"Upvoted\", \"Submitted\", \"Collections\", \"Made\", \"Following\", \"Followers\"};\n private String tabTitles[] = {\"Upvoted\", \"Submitted\", \"Made\", \"Collections\", \"Followers\", \"Following\"};\n\n\n public UserPagerAdapter(FragmentManager fm){\n super(fm);\n }\n\n @Override\n public Fragment getItem(int position) {\n switch (position){\n case 0:\n PostsFragment votedPostsFragment = new PostsFragment();\n votedPostsFragment.setPosts(votedPosts);\n return votedPostsFragment;\n case 1:\n PostsFragment submittedPostsFragment = new PostsFragment();\n submittedPostsFragment.setPosts(submittedPosts);\n return submittedPostsFragment;\n case 2:\n PostsFragment makerPostsFragment = new PostsFragment();\n makerPostsFragment.setPosts(makerPosts);\n return makerPostsFragment;\n case 3:\n UserCollectionsFragment userCollectionsFragment = new UserCollectionsFragment();\n userCollectionsFragment.setUserId(user.getId());\n return userCollectionsFragment;\n case 4:\n FollowersFragment followersFragment = new FollowersFragment();\n followersFragment.setUserId(user.getId());\n return followersFragment;\n case 5:\n FollowingFragment followingFragment = new FollowingFragment();\n followingFragment.setUserId(user.getId());\n return followingFragment;\n default:\n return null;\n }\n }\n\n @Override\n public CharSequence getPageTitle(int position) {\n return tabTitles[position];\n }\n\n @Override\n public int getCount() {\n return tabTitles.length;\n }\n }\n}",
"public abstract class EndlessScrollListener implements AbsListView.OnScrollListener{\n // The minimum amount of items to have below your current scroll position\n // before loading more.\n private int visibleThreshold = 5;\n // The current offset index of data you have loaded\n private int currentPage = 0;\n // The total number of items in the dataset after the last load\n private int previousTotalItemCount = 0;\n // True if we are still waiting for the last set of data to load.\n private boolean loading = true;\n // Sets the starting page index\n private int startingPageIndex = 0;\n\n public EndlessScrollListener() {\n }\n\n public EndlessScrollListener(int visibleThreshold) {\n this.visibleThreshold = visibleThreshold;\n }\n\n public EndlessScrollListener(int visibleThreshold, int startPage) {\n this.visibleThreshold = visibleThreshold;\n this.startingPageIndex = startPage;\n this.currentPage = startPage;\n }\n\n // This happens many times a second during a scroll, so be wary of the code you place here.\n // We are given a few useful parameters to help us work out if we need to load some more data,\n // but first we check if we are waiting for the previous load to finish.\n @Override\n public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)\n {\n // If the total item count is zero and the previous isn't, assume the\n // list is invalidated and should be reset back to initial state\n if (totalItemCount < previousTotalItemCount) {\n this.currentPage = this.startingPageIndex;\n this.previousTotalItemCount = totalItemCount;\n if (totalItemCount == 0) { this.loading = true; }\n }\n // If it's still loading, we check to see if the dataset count has\n // changed, if so we conclude it has finished loading and update the current page\n // number and total item count.\n if (loading && (totalItemCount > previousTotalItemCount)) {\n loading = false;\n previousTotalItemCount = totalItemCount;\n currentPage++;\n }\n\n // If it isn't currently loading, we check to see if we have breached\n // the visibleThreshold and need to reload more data.\n // If we do need to reload some more data, we execute onLoadMore to fetch the data.\n if (!loading && (totalItemCount - visibleItemCount)<=(firstVisibleItem + visibleThreshold)) {\n loading = onLoadMore(currentPage + 1, totalItemCount);\n }\n }\n\n // Defines the process for actually loading more data based on page\n // Returns true if more data is being loaded; returns false if there is no more data to load.\n public abstract boolean onLoadMore(int page, int totalItemsCount);\n\n @Override\n public void onScrollStateChanged(AbsListView view, int scrollState) {\n // Don't take any action on changed\n }\n}",
"public class FollowersArrayAdapter extends ArrayAdapter<Follower> {\n public FollowersArrayAdapter(Context context, List<Follower> followers) {\n super(context, android.R.layout.simple_list_item_1, followers);\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n final Follower follower = getItem(position);\n final User user = follower.getUser();\n\n if (convertView == null){\n convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false);\n }\n\n ImageView ivProfile = (ImageView) convertView.findViewById(R.id.ivProfile);\n TextView tvUserName = (TextView) convertView.findViewById(R.id.tvUserName);\n TextView tvUserHeadline = (TextView) convertView.findViewById(R.id.tvUserHeadline);\n\n ivProfile.setImageResource(0);\n\n tvUserName.setText(user.getName());\n tvUserHeadline.setText(user.getHeadline());\n\n Picasso.with(getContext()).load(user.getMediumProfileImageUrl()).fit().into(ivProfile);\n\n ivProfile.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n int userId = user.getId();\n\n Intent intent = new Intent(getContext(), UserActivity.class);\n intent.putExtra(User.USER_ID_MESSAGE, userId);\n\n getContext().startActivity(intent);\n }\n });\n\n return convertView;\n }\n}",
"public class Follower {\n private int id;\n private User user;\n\n public static Follower fromJSON(JSONObject jsonObject){\n Follower follower = new Follower();\n\n try{\n follower.id = jsonObject.getInt(\"id\");\n follower.user = User.fromJSON(jsonObject.getJSONObject(\"user\"));\n }catch (JSONException e){\n e.printStackTrace();\n }\n\n return follower;\n }\n\n public static List<Follower> fromJSONArray(JSONArray jsonArray){\n List<Follower> followers = new ArrayList<Follower>();\n\n for(int i = 0; i < jsonArray.length(); i++){\n try {\n Follower follower = Follower.fromJSON(jsonArray.getJSONObject(i));\n followers.add(follower);\n }catch (JSONException e){\n e.printStackTrace();\n continue;\n }\n }\n\n return followers;\n }\n\n public int getId() {\n return id;\n }\n\n public User getUser() {\n return user;\n }\n}",
"public class User {\n public static final String USER_ID_MESSAGE = \"com.hhua.android.producthunt.user.USER_ID\";\n\n private int id;\n private String name;\n private String headline;\n private String username;\n private String twitterName;\n private String websiteUrl;\n private String smallProfileImageUrl;\n private String mediumProfileImageUrl;\n private String largeProfileImageUrl;\n private String backgroundImageUrl;\n private int votesCount;\n private int postsCount;\n private int makerCount;\n private int collectionsCount;\n private int followersCount;\n private int followingCount;\n\n public static User fromJSON(JSONObject jsonObject){\n User user = new User();\n\n try {\n user.id = jsonObject.getInt(\"id\");\n user.name = jsonObject.getString(\"name\");\n user.headline = jsonObject.getString(\"headline\");\n user.username = jsonObject.getString(\"username\");\n user.twitterName = jsonObject.getString(\"twitter_username\");\n user.websiteUrl = jsonObject.getString(\"website_url\");\n user.smallProfileImageUrl = jsonObject.getJSONObject(\"image_url\").getString(\"40px\");\n user.mediumProfileImageUrl = jsonObject.getJSONObject(\"image_url\").getString(\"60px\");\n user.largeProfileImageUrl = jsonObject.getJSONObject(\"image_url\").getString(\"96px\");\n user.backgroundImageUrl = jsonObject.getJSONObject(\"image_url\").getString(\"original\");\n user.votesCount = jsonObject.optInt(\"votes_count\");\n user.postsCount = jsonObject.optInt(\"posts_count\");\n user.makerCount = jsonObject.optInt(\"maker_of_count\");\n user.collectionsCount = jsonObject.optInt(\"collections_count\");\n user.followersCount = jsonObject.optInt(\"followers_count\");\n user.followingCount = jsonObject.optInt(\"followings_count\");\n }catch (JSONException e){\n e.printStackTrace();\n }\n return user;\n }\n\n public static List<User> fromJSONArray(JSONArray jsonArray){\n List<User> users = new ArrayList<User>();\n\n for (int i = 0; i < jsonArray.length(); i++){\n try {\n User user = User.fromJSON(jsonArray.getJSONObject(i));\n users.add(user);\n }catch (JSONException e){\n e.printStackTrace();\n continue;\n }\n }\n\n return users;\n }\n\n public int getId() {\n return id;\n }\n\n public String getName() {\n return name;\n }\n\n public String getHeadline() {\n return headline;\n }\n\n public String getUsername() {\n return username;\n }\n\n public String getTwitterName() {\n return twitterName;\n }\n\n public String getWebsiteUrl() {\n return websiteUrl;\n }\n\n public String getSmallProfileImageUrl() {\n return smallProfileImageUrl;\n }\n\n public String getMediumProfileImageUrl() {\n return mediumProfileImageUrl;\n }\n\n public String getLargeProfileImageUrl() {\n return largeProfileImageUrl;\n }\n\n public String getBackgroundImageUrl() {\n return backgroundImageUrl;\n }\n\n public int getVotesCount() {\n return votesCount;\n }\n\n public int getPostsCount() {\n return postsCount;\n }\n\n public int getMakerCount() {\n return makerCount;\n }\n\n public int getCollectionsCount() {\n return collectionsCount;\n }\n\n public int getFollowersCount() {\n return followersCount;\n }\n\n public int getFollowingCount() {\n return followingCount;\n }\n}"
] | import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.hhua.android.producthunt.ProductHuntApplication;
import com.hhua.android.producthunt.ProductHuntClient;
import com.hhua.android.producthunt.R;
import com.hhua.android.producthunt.activities.UserActivity;
import com.hhua.android.producthunt.adapters.EndlessScrollListener;
import com.hhua.android.producthunt.adapters.FollowersArrayAdapter;
import com.hhua.android.producthunt.models.Follower;
import com.hhua.android.producthunt.models.User;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.Header; | package com.hhua.android.producthunt.fragments;
public class FollowingFragment extends Fragment {
private final String LOG_D = "FollowingFragment";
private ProductHuntClient client;
private ListView lvUsers;
private List<Follower> followers;
private FollowersArrayAdapter followersArrayAdapter;
private int userId;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_users, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
client = ProductHuntApplication.getRestClient();
lvUsers = (ListView) view.findViewById(R.id.lvUsers);
lvUsers.setOnScrollListener(new EndlessScrollListener() {
@Override
public boolean onLoadMore(int page, int totalItemsCount) {
customLoadMoreDataFromApi(page);
return true;
}
});
lvUsers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
User user = followers.get(position).getUser(); | Intent intent = new Intent(getContext(), UserActivity.class); | 2 |
kesenhoo/Camera2 | src/com/android/camera/VideoModule.java | [
"public interface CameraPictureCallback {\n public void onPictureTaken(byte[] data, CameraProxy camera);\n}",
"public interface CameraProxy {\n\n /**\n * Returns the underlying {@link android.hardware.Camera} object used\n * by this proxy. This method should only be used when handing the\n * camera device over to {@link android.media.MediaRecorder} for\n * recording.\n */\n public android.hardware.Camera getCamera();\n\n /**\n * Releases the camera device synchronously.\n * This function must be synchronous so the caller knows exactly when the camera\n * is released and can continue on.\n */\n public void release();\n\n /**\n * Reconnects to the camera device.\n * @see android.hardware.Camera#reconnect()\n *\n * @param handler The {@link android.os.Handler} in which the callback\n * was handled.\n * @param cb The callback when any error happens.\n * @return {@code false} on errors.\n */\n public boolean reconnect(Handler handler, CameraOpenErrorCallback cb);\n\n /**\n * Unlocks the camera device.\n *\n * @see android.hardware.Camera#unlock()\n */\n public void unlock();\n\n /**\n * Locks the camera device.\n * @see android.hardware.Camera#lock()\n */\n public void lock();\n\n /**\n * Sets the {@link android.graphics.SurfaceTexture} for preview.\n *\n * @param surfaceTexture The {@link SurfaceTexture} for preview.\n */\n public void setPreviewTexture(final SurfaceTexture surfaceTexture);\n\n /**\n * Sets the {@link android.view.SurfaceHolder} for preview.\n *\n * @param surfaceHolder The {@link SurfaceHolder} for preview.\n */\n public void setPreviewDisplay(final SurfaceHolder surfaceHolder);\n\n /**\n * Starts the camera preview.\n */\n public void startPreview();\n\n /**\n * Stops the camera preview synchronously.\n * {@code stopPreview()} must be synchronous to ensure that the caller can\n * continues to release resources related to camera preview.\n */\n public void stopPreview();\n\n /**\n * Sets the callback for preview data.\n *\n * @param handler The {@link android.os.Handler} in which the callback was handled.\n * @param cb The callback to be invoked when the preview data is available.\n * @see android.hardware.Camera#setPreviewCallback(android.hardware.Camera.PreviewCallback)\n */\n public void setPreviewDataCallback(Handler handler, CameraPreviewDataCallback cb);\n\n /**\n * Sets the callback for preview data.\n *\n * @param handler The handler in which the callback will be invoked.\n * @param cb The callback to be invoked when the preview data is available.\n * @see android.hardware.Camera#setPreviewCallbackWithBuffer(android.hardware.Camera.PreviewCallback)\n */\n public void setPreviewDataCallbackWithBuffer(Handler handler, CameraPreviewDataCallback cb);\n\n /**\n * Adds buffer for the preview callback.\n *\n * @param callbackBuffer The buffer allocated for the preview data.\n */\n public void addCallbackBuffer(byte[] callbackBuffer);\n\n /**\n * Starts the auto-focus process. The result will be returned through the callback.\n *\n * @param handler The handler in which the callback will be invoked.\n * @param cb The auto-focus callback.\n */\n public void autoFocus(Handler handler, CameraAFCallback cb);\n\n /**\n * Cancels the auto-focus process.\n */\n public void cancelAutoFocus();\n\n /**\n * Sets the auto-focus callback\n *\n * @param handler The handler in which the callback will be invoked.\n * @param cb The callback to be invoked when the preview data is available.\n */\n @TargetApi(Build.VERSION_CODES.JELLY_BEAN)\n public void setAutoFocusMoveCallback(Handler handler, CameraAFMoveCallback cb);\n\n /**\n * Instrument the camera to take a picture.\n *\n * @param handler The handler in which the callback will be invoked.\n * @param shutter The callback for shutter action, may be null.\n * @param raw The callback for uncompressed data, may be null.\n * @param postview The callback for postview image data, may be null.\n * @param jpeg The callback for jpeg image data, may be null.\n * @see android.hardware.Camera#takePicture(\n * android.hardware.Camera.ShutterCallback,\n * android.hardware.Camera.PictureCallback,\n * android.hardware.Camera.PictureCallback)\n */\n public void takePicture(\n Handler handler,\n CameraShutterCallback shutter,\n CameraPictureCallback raw,\n CameraPictureCallback postview,\n CameraPictureCallback jpeg);\n\n /**\n * Sets the display orientation for camera to adjust the preview orientation.\n *\n * @param degrees The rotation in degrees. Should be 0, 90, 180 or 270.\n */\n public void setDisplayOrientation(int degrees);\n\n /**\n * Sets the listener for zoom change.\n *\n * @param listener The listener.\n */\n public void setZoomChangeListener(OnZoomChangeListener listener);\n\n /**\n * Sets the face detection listener.\n *\n * @param handler The handler in which the callback will be invoked.\n * @param callback The callback for face detection results.\n */\n public void setFaceDetectionCallback(Handler handler, CameraFaceDetectionCallback callback);\n\n /**\n * Starts the face detection.\n */\n public void startFaceDetection();\n\n /**\n * Stops the face detection.\n */\n public void stopFaceDetection();\n\n /**\n * Registers an error callback.\n *\n * @param cb The error callback.\n * @see android.hardware.Camera#setErrorCallback(android.hardware.Camera.ErrorCallback)\n */\n public void setErrorCallback(ErrorCallback cb);\n\n /**\n * Sets the camera parameters.\n *\n * @param params The camera parameters to use.\n */\n public void setParameters(Parameters params);\n\n /**\n * Gets the current camera parameters synchronously. This method is\n * synchronous since the caller has to wait for the camera to return\n * the parameters. If the parameters are already cached, it returns\n * immediately.\n */\n public Parameters getParameters();\n\n /**\n * Forces {@code CameraProxy} to update the cached version of the camera\n * parameters regardless of the dirty bit.\n */\n public void refreshParameters();\n\n /**\n * Enables/Disables the camera shutter sound.\n *\n * @param enable {@code true} to enable the shutter sound,\n * {@code false} to disable it.\n */\n public void enableShutterSound(boolean enable);\n}",
"public class RotateTextToast {\n private static final int TOAST_DURATION = 5000; // milliseconds\n ViewGroup mLayoutRoot;\n RotateLayout mToast;\n Handler mHandler;\n\n public RotateTextToast(Activity activity, int textResourceId, int orientation) {\n mLayoutRoot = (ViewGroup) activity.getWindow().getDecorView();\n LayoutInflater inflater = activity.getLayoutInflater();\n View v = inflater.inflate(R.layout.rotate_text_toast, mLayoutRoot);\n mToast = (RotateLayout) v.findViewById(R.id.rotate_toast);\n TextView tv = (TextView) mToast.findViewById(R.id.message);\n tv.setText(textResourceId);\n mToast.setOrientation(orientation, false);\n mHandler = new Handler();\n }\n\n private final Runnable mRunnable = new Runnable() {\n @Override\n public void run() {\n CameraUtil.fadeOut(mToast);\n mLayoutRoot.removeView(mToast);\n mToast = null;\n }\n };\n\n public void show() {\n mToast.setVisibility(View.VISIBLE);\n mHandler.postDelayed(mRunnable, TOAST_DURATION);\n }\n}",
"public class AccessibilityUtils {\n @TargetApi(Build.VERSION_CODES.JELLY_BEAN)\n public static void makeAnnouncement(View view, CharSequence announcement) {\n if (view == null)\n return;\n if (ApiHelper.HAS_ANNOUNCE_FOR_ACCESSIBILITY) {\n view.announceForAccessibility(announcement);\n } else {\n // For API 15 and earlier, we need to construct an accessibility event\n Context ctx = view.getContext();\n AccessibilityManager am = (AccessibilityManager) ctx.getSystemService(\n Context.ACCESSIBILITY_SERVICE);\n if (!am.isEnabled()) return;\n AccessibilityEvent event = AccessibilityEvent.obtain(\n AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);\n AccessibilityRecordCompat arc = new AccessibilityRecordCompat(event);\n arc.setSource(view);\n event.setClassName(view.getClass().getName());\n event.setPackageName(view.getContext().getPackageName());\n event.setEnabled(view.isEnabled());\n event.getText().add(announcement);\n am.sendAccessibilityEvent(event);\n }\n }\n}",
"public class ApiHelper {\n public static final boolean AT_LEAST_16 = Build.VERSION.SDK_INT >= 16;\n\n public static final boolean HAS_APP_GALLERY =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;\n\n public static final boolean HAS_ANNOUNCE_FOR_ACCESSIBILITY =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;\n public static final boolean HAS_AUTO_FOCUS_MOVE_CALLBACK =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;\n public static final boolean HAS_MEDIA_ACTION_SOUND =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;\n public static final boolean HAS_MEDIA_COLUMNS_WIDTH_AND_HEIGHT =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;\n public static final boolean HAS_SET_BEAM_PUSH_URIS =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;\n public static final boolean HAS_SURFACE_TEXTURE_RECORDING =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;\n\n public static final boolean HAS_CAMERA_HDR_PLUS = isKitKatOrHigher();\n public static final boolean HAS_CAMERA_HDR =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;\n public static final boolean HAS_DISPLAY_LISTENER =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;\n\n public static final boolean HAS_ORIENTATION_LOCK =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;\n public static final boolean HAS_ROTATION_ANIMATION =\n Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;\n\n public static final boolean HAS_HIDEYBARS = isKitKatOrHigher();\n\n public static int getIntFieldIfExists(Class<?> klass, String fieldName,\n Class<?> obj, int defaultVal) {\n try {\n Field f = klass.getDeclaredField(fieldName);\n return f.getInt(obj);\n } catch (Exception e) {\n return defaultVal;\n }\n }\n\n public static boolean isKitKatOrHigher() {\n // TODO: Remove CODENAME check as soon as VERSION_CODES.KITKAT is final.\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT\n || \"KeyLimePie\".equals(Build.VERSION.CODENAME);\n }\n}",
"public class CameraUtil {\n private static final String TAG = \"Util\";\n\n // For calculate the best fps range for still image capture.\n private final static int MAX_PREVIEW_FPS_TIMES_1000 = 400000;\n private final static int PREFERRED_PREVIEW_FPS_TIMES_1000 = 30000;\n\n // For creating crop intents.\n public static final String KEY_RETURN_DATA = \"return-data\";\n public static final String KEY_SHOW_WHEN_LOCKED = \"showWhenLocked\";\n\n // Orientation hysteresis amount used in rounding, in degrees\n public static final int ORIENTATION_HYSTERESIS = 5;\n\n public static final String REVIEW_ACTION = \"com.android.camera.action.REVIEW\";\n // See android.hardware.Camera.ACTION_NEW_PICTURE.\n public static final String ACTION_NEW_PICTURE = \"android.hardware.action.NEW_PICTURE\";\n // See android.hardware.Camera.ACTION_NEW_VIDEO.\n public static final String ACTION_NEW_VIDEO = \"android.hardware.action.NEW_VIDEO\";\n\n // Broadcast Action: The camera application has become active in picture-taking mode.\n public static final String ACTION_CAMERA_STARTED = \"com.android.camera.action.CAMERA_STARTED\";\n // Broadcast Action: The camera application is no longer in active picture-taking mode.\n public static final String ACTION_CAMERA_STOPPED = \"com.android.camera.action.CAMERA_STOPPED\";\n // When the camera application is active in picture-taking mode, it listens for this intent,\n // which upon receipt will trigger the shutter to capture a new picture, as if the user had\n // pressed the shutter button.\n public static final String ACTION_CAMERA_SHUTTER_CLICK =\n \"com.android.camera.action.SHUTTER_CLICK\";\n\n // Fields from android.hardware.Camera.Parameters\n public static final String FOCUS_MODE_CONTINUOUS_PICTURE = \"continuous-picture\";\n public static final String RECORDING_HINT = \"recording-hint\";\n private static final String AUTO_EXPOSURE_LOCK_SUPPORTED = \"auto-exposure-lock-supported\";\n private static final String AUTO_WHITE_BALANCE_LOCK_SUPPORTED = \"auto-whitebalance-lock-supported\";\n private static final String VIDEO_SNAPSHOT_SUPPORTED = \"video-snapshot-supported\";\n public static final String SCENE_MODE_HDR = \"hdr\";\n public static final String TRUE = \"true\";\n public static final String FALSE = \"false\";\n\n // Fields for the show-on-maps-functionality\n private static final String MAPS_PACKAGE_NAME = \"com.google.android.apps.maps\";\n private static final String MAPS_CLASS_NAME = \"com.google.android.maps.MapsActivity\";\n\n /** Has to be in sync with the receiving MovieActivity. */\n public static final String KEY_TREAT_UP_AS_BACK = \"treat-up-as-back\";\n\n public static boolean isSupported(String value, List<String> supported) {\n return supported == null ? false : supported.indexOf(value) >= 0;\n }\n\n public static boolean isAutoExposureLockSupported(Parameters params) {\n return TRUE.equals(params.get(AUTO_EXPOSURE_LOCK_SUPPORTED));\n }\n\n public static boolean isAutoWhiteBalanceLockSupported(Parameters params) {\n return TRUE.equals(params.get(AUTO_WHITE_BALANCE_LOCK_SUPPORTED));\n }\n\n public static boolean isVideoSnapshotSupported(Parameters params) {\n return TRUE.equals(params.get(VIDEO_SNAPSHOT_SUPPORTED));\n }\n\n public static boolean isCameraHdrSupported(Parameters params) {\n List<String> supported = params.getSupportedSceneModes();\n return (supported != null) && supported.contains(SCENE_MODE_HDR);\n }\n\n public static boolean isMeteringAreaSupported(Parameters params) {\n return params.getMaxNumMeteringAreas() > 0;\n }\n\n public static boolean isFocusAreaSupported(Parameters params) {\n return (params.getMaxNumFocusAreas() > 0\n && isSupported(Parameters.FOCUS_MODE_AUTO,\n params.getSupportedFocusModes()));\n }\n\n // Private intent extras. Test only.\n private static final String EXTRAS_CAMERA_FACING =\n \"android.intent.extras.CAMERA_FACING\";\n\n private static float sPixelDensity = 1;\n private static ImageFileNamer sImageFileNamer;\n\n private CameraUtil() {\n }\n\n public static void initialize(Context context) {\n DisplayMetrics metrics = new DisplayMetrics();\n WindowManager wm = (WindowManager)\n context.getSystemService(Context.WINDOW_SERVICE);\n wm.getDefaultDisplay().getMetrics(metrics);\n sPixelDensity = metrics.density;\n sImageFileNamer = new ImageFileNamer(\n context.getString(R.string.image_file_name_format));\n }\n\n public static int dpToPixel(int dp) {\n return Math.round(sPixelDensity * dp);\n }\n\n // Rotates the bitmap by the specified degree.\n // If a new bitmap is created, the original bitmap is recycled.\n public static Bitmap rotate(Bitmap b, int degrees) {\n return rotateAndMirror(b, degrees, false);\n }\n\n // Rotates and/or mirrors the bitmap. If a new bitmap is created, the\n // original bitmap is recycled.\n public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) {\n if ((degrees != 0 || mirror) && b != null) {\n Matrix m = new Matrix();\n // Mirror first.\n // horizontal flip + rotation = -rotation + horizontal flip\n if (mirror) {\n m.postScale(-1, 1);\n degrees = (degrees + 360) % 360;\n if (degrees == 0 || degrees == 180) {\n m.postTranslate(b.getWidth(), 0);\n } else if (degrees == 90 || degrees == 270) {\n m.postTranslate(b.getHeight(), 0);\n } else {\n throw new IllegalArgumentException(\"Invalid degrees=\" + degrees);\n }\n }\n if (degrees != 0) {\n // clockwise\n m.postRotate(degrees,\n (float) b.getWidth() / 2, (float) b.getHeight() / 2);\n }\n\n try {\n Bitmap b2 = Bitmap.createBitmap(\n b, 0, 0, b.getWidth(), b.getHeight(), m, true);\n if (b != b2) {\n b.recycle();\n b = b2;\n }\n } catch (OutOfMemoryError ex) {\n // We have no memory to rotate. Return the original bitmap.\n }\n }\n return b;\n }\n\n /*\n * Compute the sample size as a function of minSideLength\n * and maxNumOfPixels.\n * minSideLength is used to specify that minimal width or height of a\n * bitmap.\n * maxNumOfPixels is used to specify the maximal size in pixels that is\n * tolerable in terms of memory usage.\n *\n * The function returns a sample size based on the constraints.\n * Both size and minSideLength can be passed in as -1\n * which indicates no care of the corresponding constraint.\n * The functions prefers returning a sample size that\n * generates a smaller bitmap, unless minSideLength = -1.\n *\n * Also, the function rounds up the sample size to a power of 2 or multiple\n * of 8 because BitmapFactory only honors sample size this way.\n * For example, BitmapFactory downsamples an image by 2 even though the\n * request is 3. So we round up the sample size to avoid OOM.\n */\n public static int computeSampleSize(BitmapFactory.Options options,\n int minSideLength, int maxNumOfPixels) {\n int initialSize = computeInitialSampleSize(options, minSideLength,\n maxNumOfPixels);\n\n int roundedSize;\n if (initialSize <= 8) {\n roundedSize = 1;\n while (roundedSize < initialSize) {\n roundedSize <<= 1;\n }\n } else {\n roundedSize = (initialSize + 7) / 8 * 8;\n }\n\n return roundedSize;\n }\n\n private static int computeInitialSampleSize(BitmapFactory.Options options,\n int minSideLength, int maxNumOfPixels) {\n double w = options.outWidth;\n double h = options.outHeight;\n\n int lowerBound = (maxNumOfPixels < 0) ? 1 :\n (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));\n int upperBound = (minSideLength < 0) ? 128 :\n (int) Math.min(Math.floor(w / minSideLength),\n Math.floor(h / minSideLength));\n\n if (upperBound < lowerBound) {\n // return the larger one when there is no overlapping zone.\n return lowerBound;\n }\n\n if (maxNumOfPixels < 0 && minSideLength < 0) {\n return 1;\n } else if (minSideLength < 0) {\n return lowerBound;\n } else {\n return upperBound;\n }\n }\n\n public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) {\n try {\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,\n options);\n if (options.mCancel || options.outWidth == -1\n || options.outHeight == -1) {\n return null;\n }\n options.inSampleSize = computeSampleSize(\n options, -1, maxNumOfPixels);\n options.inJustDecodeBounds = false;\n\n options.inDither = false;\n options.inPreferredConfig = Bitmap.Config.ARGB_8888;\n return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,\n options);\n } catch (OutOfMemoryError ex) {\n Log.e(TAG, \"Got oom exception \", ex);\n return null;\n }\n }\n\n public static void closeSilently(Closeable c) {\n if (c == null) return;\n try {\n c.close();\n } catch (Throwable t) {\n // do nothing\n }\n }\n\n public static void Assert(boolean cond) {\n if (!cond) {\n throw new AssertionError();\n }\n }\n\n private static void throwIfCameraDisabled(Activity activity) throws CameraDisabledException {\n // Check if device policy has disabled the camera.\n DevicePolicyManager dpm = (DevicePolicyManager) activity.getSystemService(\n Context.DEVICE_POLICY_SERVICE);\n if (dpm.getCameraDisabled(null)) {\n throw new CameraDisabledException();\n }\n }\n\n public static CameraManager.CameraProxy openCamera(\n Activity activity, final int cameraId,\n Handler handler, final CameraManager.CameraOpenErrorCallback cb) {\n try {\n throwIfCameraDisabled(activity);\n return CameraHolder.instance().open(handler, cameraId, cb);\n } catch (CameraDisabledException ex) {\n handler.post(new Runnable() {\n @Override\n public void run() {\n cb.onCameraDisabled(cameraId);\n }\n });\n }\n return null;\n }\n\n public static void showErrorAndFinish(final Activity activity, int msgId) {\n DialogInterface.OnClickListener buttonListener =\n new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n activity.finish();\n }\n };\n TypedValue out = new TypedValue();\n activity.getTheme().resolveAttribute(android.R.attr.alertDialogIcon, out, true);\n new AlertDialog.Builder(activity)\n .setCancelable(false)\n .setTitle(R.string.camera_error_title)\n .setMessage(msgId)\n .setNeutralButton(R.string.dialog_ok, buttonListener)\n .setIcon(out.resourceId)\n .show();\n }\n\n public static <T> T checkNotNull(T object) {\n if (object == null) throw new NullPointerException();\n return object;\n }\n\n public static boolean equals(Object a, Object b) {\n return (a == b) || (a == null ? false : a.equals(b));\n }\n\n public static int nextPowerOf2(int n) {\n n -= 1;\n n |= n >>> 16;\n n |= n >>> 8;\n n |= n >>> 4;\n n |= n >>> 2;\n n |= n >>> 1;\n return n + 1;\n }\n\n public static float distance(float x, float y, float sx, float sy) {\n float dx = x - sx;\n float dy = y - sy;\n return (float) Math.sqrt(dx * dx + dy * dy);\n }\n\n public static int clamp(int x, int min, int max) {\n if (x > max) return max;\n if (x < min) return min;\n return x;\n }\n\n public static float clamp(float x, float min, float max) {\n if (x > max) return max;\n if (x < min) return min;\n return x;\n }\n\n public static int getDisplayRotation(Activity activity) {\n int rotation = activity.getWindowManager().getDefaultDisplay()\n .getRotation();\n switch (rotation) {\n case Surface.ROTATION_0: return 0;\n case Surface.ROTATION_90: return 90;\n case Surface.ROTATION_180: return 180;\n case Surface.ROTATION_270: return 270;\n }\n return 0;\n }\n\n /**\n * Calculate the default orientation of the device based on the width and\n * height of the display when rotation = 0 (i.e. natural width and height)\n * @param activity the activity context\n * @return whether the default orientation of the device is portrait\n */\n public static boolean isDefaultToPortrait(Activity activity) {\n Display currentDisplay = activity.getWindowManager().getDefaultDisplay();\n Point displaySize = new Point();\n currentDisplay.getSize(displaySize);\n int orientation = currentDisplay.getRotation();\n int naturalWidth, naturalHeight;\n if (orientation == Surface.ROTATION_0 || orientation == Surface.ROTATION_180) {\n naturalWidth = displaySize.x;\n naturalHeight = displaySize.y;\n } else {\n naturalWidth = displaySize.y;\n naturalHeight = displaySize.x;\n }\n return naturalWidth < naturalHeight;\n }\n\n public static int getDisplayOrientation(int degrees, int cameraId) {\n // See android.hardware.Camera.setDisplayOrientation for\n // documentation.\n Camera.CameraInfo info = new Camera.CameraInfo();\n Camera.getCameraInfo(cameraId, info);\n int result;\n if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {\n result = (info.orientation + degrees) % 360;\n result = (360 - result) % 360; // compensate the mirror\n } else { // back-facing\n result = (info.orientation - degrees + 360) % 360;\n }\n return result;\n }\n\n public static int getCameraOrientation(int cameraId) {\n Camera.CameraInfo info = new Camera.CameraInfo();\n Camera.getCameraInfo(cameraId, info);\n return info.orientation;\n }\n\n public static int roundOrientation(int orientation, int orientationHistory) {\n boolean changeOrientation = false;\n if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {\n changeOrientation = true;\n } else {\n int dist = Math.abs(orientation - orientationHistory);\n dist = Math.min( dist, 360 - dist );\n changeOrientation = ( dist >= 45 + ORIENTATION_HYSTERESIS );\n }\n if (changeOrientation) {\n return ((orientation + 45) / 90 * 90) % 360;\n }\n return orientationHistory;\n }\n\n private static Point getDefaultDisplaySize(Activity activity, Point size) {\n activity.getWindowManager().getDefaultDisplay().getSize(size);\n return size;\n }\n\n public static Size getOptimalPreviewSize(Activity currentActivity,\n List<Size> sizes, double targetRatio) {\n\n Point[] points = new Point[sizes.size()];\n\n int index = 0;\n for (Size s : sizes) {\n points[index++] = new Point(s.width, s.height);\n }\n\n int optimalPickIndex = getOptimalPreviewSize(currentActivity, points, targetRatio);\n return (optimalPickIndex == -1) ? null : sizes.get(optimalPickIndex);\n }\n\n public static int getOptimalPreviewSize(Activity currentActivity,\n Point[] sizes, double targetRatio) {\n // Use a very small tolerance because we want an exact match.\n final double ASPECT_TOLERANCE = 0.01;\n if (sizes == null) return -1;\n\n int optimalSizeIndex = -1;\n double minDiff = Double.MAX_VALUE;\n\n // Because of bugs of overlay and layout, we sometimes will try to\n // layout the viewfinder in the portrait orientation and thus get the\n // wrong size of preview surface. When we change the preview size, the\n // new overlay will be created before the old one closed, which causes\n // an exception. For now, just get the screen size.\n Point point = getDefaultDisplaySize(currentActivity, new Point());\n int targetHeight = Math.min(point.x, point.y);\n // Try to find an size match aspect ratio and size\n for (int i = 0; i < sizes.length; i++) {\n Point size = sizes[i];\n double ratio = (double) size.x / size.y;\n if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;\n if (Math.abs(size.y - targetHeight) < minDiff) {\n optimalSizeIndex = i;\n minDiff = Math.abs(size.y - targetHeight);\n }\n }\n // Cannot find the one match the aspect ratio. This should not happen.\n // Ignore the requirement.\n if (optimalSizeIndex == -1) {\n Log.w(TAG, \"No preview size match the aspect ratio\");\n minDiff = Double.MAX_VALUE;\n for (int i = 0; i < sizes.length; i++) {\n Point size = sizes[i];\n if (Math.abs(size.y - targetHeight) < minDiff) {\n optimalSizeIndex = i;\n minDiff = Math.abs(size.y - targetHeight);\n }\n }\n }\n return optimalSizeIndex;\n }\n\n // Returns the largest picture size which matches the given aspect ratio.\n public static Size getOptimalVideoSnapshotPictureSize(\n List<Size> sizes, double targetRatio) {\n // Use a very small tolerance because we want an exact match.\n final double ASPECT_TOLERANCE = 0.001;\n if (sizes == null) return null;\n\n Size optimalSize = null;\n\n // Try to find a size matches aspect ratio and has the largest width\n for (Size size : sizes) {\n double ratio = (double) size.width / size.height;\n if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;\n if (optimalSize == null || size.width > optimalSize.width) {\n optimalSize = size;\n }\n }\n\n // Cannot find one that matches the aspect ratio. This should not happen.\n // Ignore the requirement.\n if (optimalSize == null) {\n Log.w(TAG, \"No picture size match the aspect ratio\");\n for (Size size : sizes) {\n if (optimalSize == null || size.width > optimalSize.width) {\n optimalSize = size;\n }\n }\n }\n return optimalSize;\n }\n\n public static void dumpParameters(Parameters parameters) {\n String flattened = parameters.flatten();\n StringTokenizer tokenizer = new StringTokenizer(flattened, \";\");\n Log.d(TAG, \"Dump all camera parameters:\");\n while (tokenizer.hasMoreElements()) {\n Log.d(TAG, tokenizer.nextToken());\n }\n }\n\n /**\n * Returns whether the device is voice-capable (meaning, it can do MMS).\n */\n public static boolean isMmsCapable(Context context) {\n TelephonyManager telephonyManager = (TelephonyManager)\n context.getSystemService(Context.TELEPHONY_SERVICE);\n if (telephonyManager == null) {\n return false;\n }\n\n try {\n Class<?> partypes[] = new Class[0];\n Method sIsVoiceCapable = TelephonyManager.class.getMethod(\n \"isVoiceCapable\", partypes);\n\n Object arglist[] = new Object[0];\n Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);\n return (Boolean) retobj;\n } catch (java.lang.reflect.InvocationTargetException ite) {\n // Failure, must be another device.\n // Assume that it is voice capable.\n } catch (IllegalAccessException iae) {\n // Failure, must be an other device.\n // Assume that it is voice capable.\n } catch (NoSuchMethodException nsme) {\n }\n return true;\n }\n\n // This is for test only. Allow the camera to launch the specific camera.\n public static int getCameraFacingIntentExtras(Activity currentActivity) {\n int cameraId = -1;\n\n int intentCameraId =\n currentActivity.getIntent().getIntExtra(CameraUtil.EXTRAS_CAMERA_FACING, -1);\n\n if (isFrontCameraIntent(intentCameraId)) {\n // Check if the front camera exist\n int frontCameraId = CameraHolder.instance().getFrontCameraId();\n if (frontCameraId != -1) {\n cameraId = frontCameraId;\n }\n } else if (isBackCameraIntent(intentCameraId)) {\n // Check if the back camera exist\n int backCameraId = CameraHolder.instance().getBackCameraId();\n if (backCameraId != -1) {\n cameraId = backCameraId;\n }\n }\n return cameraId;\n }\n\n private static boolean isFrontCameraIntent(int intentCameraId) {\n return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);\n }\n\n private static boolean isBackCameraIntent(int intentCameraId) {\n return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);\n }\n\n private static int sLocation[] = new int[2];\n\n // This method is not thread-safe.\n public static boolean pointInView(float x, float y, View v) {\n v.getLocationInWindow(sLocation);\n return x >= sLocation[0] && x < (sLocation[0] + v.getWidth())\n && y >= sLocation[1] && y < (sLocation[1] + v.getHeight());\n }\n\n public static int[] getRelativeLocation(View reference, View view) {\n reference.getLocationInWindow(sLocation);\n int referenceX = sLocation[0];\n int referenceY = sLocation[1];\n view.getLocationInWindow(sLocation);\n sLocation[0] -= referenceX;\n sLocation[1] -= referenceY;\n return sLocation;\n }\n\n public static boolean isUriValid(Uri uri, ContentResolver resolver) {\n if (uri == null) return false;\n\n try {\n ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, \"r\");\n if (pfd == null) {\n Log.e(TAG, \"Fail to open URI. URI=\" + uri);\n return false;\n }\n pfd.close();\n } catch (IOException ex) {\n return false;\n }\n return true;\n }\n\n public static void dumpRect(RectF rect, String msg) {\n Log.v(TAG, msg + \"=(\" + rect.left + \",\" + rect.top\n + \",\" + rect.right + \",\" + rect.bottom + \")\");\n }\n\n public static void rectFToRect(RectF rectF, Rect rect) {\n rect.left = Math.round(rectF.left);\n rect.top = Math.round(rectF.top);\n rect.right = Math.round(rectF.right);\n rect.bottom = Math.round(rectF.bottom);\n }\n\n public static Rect rectFToRect(RectF rectF) {\n Rect rect = new Rect();\n rectFToRect(rectF, rect);\n return rect;\n }\n\n public static RectF rectToRectF(Rect r) {\n return new RectF(r.left, r.top, r.right, r.bottom);\n }\n\n public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,\n int viewWidth, int viewHeight) {\n // Need mirror for front camera.\n matrix.setScale(mirror ? -1 : 1, 1);\n // This is the value for android.hardware.Camera.setDisplayOrientation.\n matrix.postRotate(displayOrientation);\n // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).\n // UI coordinates range from (0, 0) to (width, height).\n matrix.postScale(viewWidth / 2000f, viewHeight / 2000f);\n matrix.postTranslate(viewWidth / 2f, viewHeight / 2f);\n }\n\n public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,\n Rect previewRect) {\n // Need mirror for front camera.\n matrix.setScale(mirror ? -1 : 1, 1);\n // This is the value for android.hardware.Camera.setDisplayOrientation.\n matrix.postRotate(displayOrientation);\n\n // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).\n // We need to map camera driver coordinates to preview rect coordinates\n Matrix mapping = new Matrix();\n mapping.setRectToRect(new RectF(-1000, -1000, 1000, 1000), rectToRectF(previewRect),\n Matrix.ScaleToFit.FILL);\n matrix.setConcat(mapping, matrix);\n }\n\n public static String createJpegName(long dateTaken) {\n synchronized (sImageFileNamer) {\n return sImageFileNamer.generateName(dateTaken);\n }\n }\n\n public static void broadcastNewPicture(Context context, Uri uri) {\n context.sendBroadcast(new Intent(ACTION_NEW_PICTURE, uri));\n // Keep compatibility\n context.sendBroadcast(new Intent(\"com.android.camera.NEW_PICTURE\", uri));\n }\n\n public static void fadeIn(View view, float startAlpha, float endAlpha, long duration) {\n if (view.getVisibility() == View.VISIBLE) return;\n\n view.setVisibility(View.VISIBLE);\n Animation animation = new AlphaAnimation(startAlpha, endAlpha);\n animation.setDuration(duration);\n view.startAnimation(animation);\n }\n\n public static void fadeIn(View view) {\n fadeIn(view, 0F, 1F, 400);\n\n // We disabled the button in fadeOut(), so enable it here.\n view.setEnabled(true);\n }\n\n public static void fadeOut(View view) {\n if (view.getVisibility() != View.VISIBLE) return;\n\n // Since the button is still clickable before fade-out animation\n // ends, we disable the button first to block click.\n view.setEnabled(false);\n Animation animation = new AlphaAnimation(1F, 0F);\n animation.setDuration(400);\n view.startAnimation(animation);\n view.setVisibility(View.GONE);\n }\n\n public static int getJpegRotation(int cameraId, int orientation) {\n // See android.hardware.Camera.Parameters.setRotation for\n // documentation.\n int rotation = 0;\n if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {\n CameraInfo info = CameraHolder.instance().getCameraInfo()[cameraId];\n if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {\n rotation = (info.orientation - orientation + 360) % 360;\n } else { // back-facing camera\n rotation = (info.orientation + orientation) % 360;\n }\n }\n return rotation;\n }\n\n /**\n * Down-samples a jpeg byte array.\n * @param data a byte array of jpeg data\n * @param downSampleFactor down-sample factor\n * @return decoded and down-sampled bitmap\n */\n public static Bitmap downSample(final byte[] data, int downSampleFactor) {\n final BitmapFactory.Options opts = new BitmapFactory.Options();\n // Downsample the image\n opts.inSampleSize = downSampleFactor;\n return BitmapFactory.decodeByteArray(data, 0, data.length, opts);\n }\n\n public static void setGpsParameters(Parameters parameters, Location loc) {\n // Clear previous GPS location from the parameters.\n parameters.removeGpsData();\n\n // We always encode GpsTimeStamp\n parameters.setGpsTimestamp(System.currentTimeMillis() / 1000);\n\n // Set GPS location.\n if (loc != null) {\n double lat = loc.getLatitude();\n double lon = loc.getLongitude();\n boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);\n\n if (hasLatLon) {\n Log.d(TAG, \"Set gps location\");\n parameters.setGpsLatitude(lat);\n parameters.setGpsLongitude(lon);\n parameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());\n if (loc.hasAltitude()) {\n parameters.setGpsAltitude(loc.getAltitude());\n } else {\n // for NETWORK_PROVIDER location provider, we may have\n // no altitude information, but the driver needs it, so\n // we fake one.\n parameters.setGpsAltitude(0);\n }\n if (loc.getTime() != 0) {\n // Location.getTime() is UTC in milliseconds.\n // gps-timestamp is UTC in seconds.\n long utcTimeSeconds = loc.getTime() / 1000;\n parameters.setGpsTimestamp(utcTimeSeconds);\n }\n } else {\n loc = null;\n }\n }\n }\n\n /**\n * For still image capture, we need to get the right fps range such that the\n * camera can slow down the framerate to allow for less-noisy/dark\n * viewfinder output in dark conditions.\n *\n * @param params Camera's parameters.\n * @return null if no appropiate fps range can't be found. Otherwise, return\n * the right range.\n */\n public static int[] getPhotoPreviewFpsRange(Parameters params) {\n return getPhotoPreviewFpsRange(params.getSupportedPreviewFpsRange());\n }\n\n public static int[] getPhotoPreviewFpsRange(List<int[]> frameRates) {\n if (frameRates.size() == 0) {\n Log.e(TAG, \"No suppoted frame rates returned!\");\n return null;\n }\n\n // Find the lowest min rate in supported ranges who can cover 30fps.\n int lowestMinRate = MAX_PREVIEW_FPS_TIMES_1000;\n for (int[] rate : frameRates) {\n int minFps = rate[Parameters.PREVIEW_FPS_MIN_INDEX];\n int maxFps = rate[Parameters.PREVIEW_FPS_MAX_INDEX];\n if (maxFps >= PREFERRED_PREVIEW_FPS_TIMES_1000 &&\n minFps <= PREFERRED_PREVIEW_FPS_TIMES_1000 &&\n minFps < lowestMinRate) {\n lowestMinRate = minFps;\n }\n }\n\n // Find all the modes with the lowest min rate found above, the pick the\n // one with highest max rate.\n int resultIndex = -1;\n int highestMaxRate = 0;\n for (int i = 0; i < frameRates.size(); i++) {\n int[] rate = frameRates.get(i);\n int minFps = rate[Parameters.PREVIEW_FPS_MIN_INDEX];\n int maxFps = rate[Parameters.PREVIEW_FPS_MAX_INDEX];\n if (minFps == lowestMinRate && highestMaxRate < maxFps) {\n highestMaxRate = maxFps;\n resultIndex = i;\n }\n }\n\n if (resultIndex >= 0) {\n return frameRates.get(resultIndex);\n }\n Log.e(TAG, \"Can't find an appropiate frame rate range!\");\n return null;\n }\n\n public static int[] getMaxPreviewFpsRange(Parameters params) {\n List<int[]> frameRates = params.getSupportedPreviewFpsRange();\n if (frameRates != null && frameRates.size() > 0) {\n // The list is sorted. Return the last element.\n return frameRates.get(frameRates.size() - 1);\n }\n return new int[0];\n }\n\n private static class ImageFileNamer {\n private final SimpleDateFormat mFormat;\n\n // The date (in milliseconds) used to generate the last name.\n private long mLastDate;\n\n // Number of names generated for the same second.\n private int mSameSecondCount;\n\n public ImageFileNamer(String format) {\n mFormat = new SimpleDateFormat(format);\n }\n\n public String generateName(long dateTaken) {\n Date date = new Date(dateTaken);\n String result = mFormat.format(date);\n\n // If the last name was generated for the same second,\n // we append _1, _2, etc to the name.\n if (dateTaken / 1000 == mLastDate / 1000) {\n mSameSecondCount++;\n result += \"_\" + mSameSecondCount;\n } else {\n mLastDate = dateTaken;\n mSameSecondCount = 0;\n }\n\n return result;\n }\n }\n\n public static void playVideo(Activity activity, Uri uri, String title) {\n try {\n boolean isSecureCamera = ((CameraActivity)activity).isSecureCamera();\n UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,\n UsageStatistics.ACTION_PLAY_VIDEO, null);\n if (!isSecureCamera) {\n Intent intent = IntentHelper.getVideoPlayerIntent(activity, uri)\n .putExtra(Intent.EXTRA_TITLE, title)\n .putExtra(KEY_TREAT_UP_AS_BACK, true);\n activity.startActivityForResult(intent, CameraActivity.REQ_CODE_DONT_SWITCH_TO_PREVIEW);\n } else {\n // In order not to send out any intent to be intercepted and\n // show the lock screen immediately, we just let the secure\n // camera activity finish.\n activity.finish();\n }\n } catch (ActivityNotFoundException e) {\n Toast.makeText(activity, activity.getString(R.string.video_err),\n Toast.LENGTH_SHORT).show();\n }\n }\n\n /**\n * Starts GMM with the given location shown. If this fails, and GMM could\n * not be found, we use a geo intent as a fallback.\n *\n * @param activity the activity to use for launching the Maps intent.\n * @param latLong a 2-element array containing {latitude/longitude}.\n */\n public static void showOnMap(Activity activity, double[] latLong) {\n try {\n // We don't use \"geo:latitude,longitude\" because it only centers\n // the MapView to the specified location, but we need a marker\n // for further operations (routing to/from).\n // The q=(lat, lng) syntax is suggested by geo-team.\n String uri = String.format(Locale.ENGLISH, \"http://maps.google.com/maps?f=q&q=(%f,%f)\",\n latLong[0], latLong[1]);\n ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,\n MAPS_CLASS_NAME);\n Intent mapsIntent = new Intent(Intent.ACTION_VIEW,\n Uri.parse(uri)).setComponent(compName);\n activity.startActivityForResult(mapsIntent,\n CameraActivity.REQ_CODE_DONT_SWITCH_TO_PREVIEW);\n } catch (ActivityNotFoundException e) {\n // Use the \"geo intent\" if no GMM is installed\n Log.e(TAG, \"GMM activity not found!\", e);\n String url = String.format(Locale.ENGLISH, \"geo:%f,%f\", latLong[0], latLong[1]);\n Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));\n activity.startActivity(mapsIntent);\n }\n }\n\n /**\n * Dumps the stack trace.\n *\n * @param level How many levels of the stack are dumped. 0 means all.\n * @return A {@link java.lang.String} of all the output with newline\n * between each.\n */\n public static String dumpStackTrace(int level) {\n StackTraceElement[] elems = Thread.currentThread().getStackTrace();\n // Ignore the first 3 elements.\n level = (level == 0 ? elems.length : Math.min(level + 3, elems.length));\n String ret = new String();\n for (int i = 3; i < level; i++) {\n ret = ret + \"\\t\" + elems[i].toString() + '\\n';\n }\n return ret;\n }\n}"
] | import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.location.Location;
import android.media.CamcorderProfile;
import android.media.CameraProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.view.KeyEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.android.camera.CameraManager.CameraPictureCallback;
import com.android.camera.CameraManager.CameraProxy;
import com.android.camera.app.OrientationManager;
import com.android.camera.exif.ExifInterface;
import com.android.camera.ui.RotateTextToast;
import com.android.camera.util.AccessibilityUtils;
import com.android.camera.util.ApiHelper;
import com.android.camera.util.CameraUtil;
import com.android.camera.util.UsageStatistics;
import com.android.camera2.R;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List; | }
private void saveVideo() {
if (mVideoFileDescriptor == null) {
long duration = SystemClock.uptimeMillis() - mRecordingStartTime;
if (duration > 0) {
if (mCaptureTimeLapse) {
duration = getTimeLapseVideoLength(duration);
}
} else {
Log.w(TAG, "Video duration <= 0 : " + duration);
}
mActivity.getMediaSaveService().addVideo(mCurrentVideoFilename,
duration, mCurrentVideoValues,
mOnVideoSavedListener, mContentResolver);
}
mCurrentVideoValues = null;
}
private void deleteVideoFile(String fileName) {
Log.v(TAG, "Deleting video " + fileName);
File f = new File(fileName);
if (!f.delete()) {
Log.v(TAG, "Could not delete " + fileName);
}
}
private PreferenceGroup filterPreferenceScreenByIntent(
PreferenceGroup screen) {
Intent intent = mActivity.getIntent();
if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
CameraSettings.removePreferenceFromScreen(screen,
CameraSettings.KEY_VIDEO_QUALITY);
}
if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) {
CameraSettings.removePreferenceFromScreen(screen,
CameraSettings.KEY_VIDEO_QUALITY);
}
return screen;
}
// from MediaRecorder.OnErrorListener
@Override
public void onError(MediaRecorder mr, int what, int extra) {
Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra);
if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) {
// We may have run out of space on the sdcard.
stopVideoRecording();
mActivity.updateStorageSpaceAndHint();
}
}
// from MediaRecorder.OnInfoListener
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
if (mMediaRecorderRecording) onStopVideoRecording();
} else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
if (mMediaRecorderRecording) onStopVideoRecording();
// Show the toast.
Toast.makeText(mActivity, R.string.video_reach_size_limit,
Toast.LENGTH_LONG).show();
}
}
/*
* Make sure we're not recording music playing in the background, ask the
* MediaPlaybackService to pause playback.
*/
private void pauseAudioPlayback() {
// Shamelessly copied from MediaPlaybackService.java, which
// should be public, but isn't.
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
mActivity.sendBroadcast(i);
}
// For testing.
public boolean isRecording() {
return mMediaRecorderRecording;
}
private void startVideoRecording() {
Log.v(TAG, "startVideoRecording");
mUI.cancelAnimations();
mUI.setSwipingEnabled(false);
mActivity.updateStorageSpaceAndHint();
if (mActivity.getStorageSpaceBytes() <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
Log.v(TAG, "Storage issue, ignore the start request");
return;
}
//??
//if (!mCameraDevice.waitDone()) return;
mCurrentVideoUri = null;
initializeRecorder();
if (mMediaRecorder == null) {
Log.e(TAG, "Fail to initialize media recorder");
return;
}
pauseAudioPlayback();
try {
mMediaRecorder.start(); // Recording is now started
} catch (RuntimeException e) {
Log.e(TAG, "Could not start media recorder. ", e);
releaseMediaRecorder();
// If start fails, frameworks will not lock the camera for us.
mCameraDevice.lock();
return;
}
// Make sure the video recording has started before announcing
// this in accessibility. | AccessibilityUtils.makeAnnouncement(mUI.getShutterButton(), | 3 |
fauu/HelixEngine | core/src/com/github/fauu/helix/manager/AreaManager.java | [
"public enum AreaType {\n\n INDOOR,\n OUTDOOR\n\n}",
"public enum PassageAction {\n\n ENTRY, EXIT;\n\n}",
"public enum TilePermission {\n\n OBSTACLE(\"Obstacle\", -1),\n PASSAGE(\"Area Passage\", -1),\n RAMP(\"Ramp\", -1),\n LEVEL0(\"Level 0\", 0),\n LEVEL1(\"Level 1\", 1),\n LEVEL2(\"Level 2\", 2),\n LEVEL3(\"Level 3\", 3),\n LEVEL4(\"Level 4\", 4),\n LEVEL5(\"Level 5\", 5),\n LEVEL6(\"Level 6\", 6),\n LEVEL7(\"Level 7\", 7);\n\n private String name;\n\n private int elevation;\n\n private static final Map<String, TilePermission> nameToValue\n = new HashMap<String, TilePermission>();\n\n static {\n for (TilePermission permission : TilePermission.values()) {\n nameToValue.put(permission.name, permission);\n }\n }\n\n private TilePermission(String name, int elevation) {\n this.name = name;\n this.elevation = elevation;\n }\n\n public String getName() {\n return name;\n }\n\n public int getElevation() {\n return elevation;\n }\n\n public static TilePermission fromString(String name) {\n if (nameToValue.containsKey(name)) {\n return nameToValue.get(name);\n }\n\n throw new NoSuchElementException(name + \" not found\");\n }\n\n}",
"public class Tile {\n\n private TilePermission permissions;\n\n private TileAreaPassage areaPassage;\n\n public Tile() {\n setPermissions(TilePermission.LEVEL0);\n }\n\n public TilePermission getPermissions() {\n return permissions;\n }\n\n public void setPermissions(TilePermission permissions) {\n this.permissions = permissions;\n }\n\n public TileAreaPassage getAreaPassage() {\n return areaPassage;\n }\n\n public void setAreaPassage(TileAreaPassage passage) {\n areaPassage = passage;\n }\n\n public static Tile get(Tile[][] tiles, IntVector2 coords) {\n return tiles[coords.y][coords.x];\n }\n\n}",
"public class TileAreaPassage {\n\n private String targetAreaName;\n\n private IntVector2 targetCoords;\n\n public TileAreaPassage() { }\n\n public TileAreaPassage(String targetAreaName, IntVector2 targetCoords) {\n this.targetAreaName = targetAreaName;\n this.targetCoords = targetCoords;\n }\n\n public String getTargetAreaName() {\n return targetAreaName;\n }\n\n public void setTargetAreaName(String targetAreaName) {\n this.targetAreaName = targetAreaName;\n }\n\n public IntVector2 getTargetCoords() {\n return targetCoords;\n }\n\n public void setTargetCoords(IntVector2 targetCoords) {\n this.targetCoords = targetCoords;\n }\n\n}",
"public class AreaDisplayable extends ModelDisplayable {\n\n public AreaDisplayable(Model model) {\n instance = new ModelInstance(model);\n\n animationController = new AnimationController(instance);\n\n instance.transform.rotate(new Vector3(1, 0, 0), 90);\n\n for (Material material : instance.materials) {\n TextureAttribute ta\n = (TextureAttribute) material.get(TextureAttribute.Diffuse);\n\n ta.textureDescription.magFilter = Texture.TextureFilter.Nearest;\n ta.textureDescription.minFilter = Texture.TextureFilter.Nearest;\n\n material.set(ta);\n material.set(ColorAttribute.createDiffuse(Color.WHITE));\n\n BlendingAttribute ba = new BlendingAttribute(GL20.GL_SRC_ALPHA,\n GL20.GL_ONE_MINUS_SRC_ALPHA);\n\n material.set(ba);\n }\n }\n\n @Override\n public void getRenderables(Array<Renderable> renderables,\n Pool<Renderable> pool) {\n instance.getRenderables(renderables, pool);\n }\n\n}",
"public class AreaWrapper {\n\n public int width;\n\n public int length;\n\n public AreaType type;\n \n public ArrayList<TileWrapper> tiles;\n\n}",
"public class TileWrapper {\n\n public TilePermission permissions;\n\n public TileAreaPassageWrapper passage;\n\n}",
"public class IntVector2 {\n\n public int x;\n\n public int y;\n\n public IntVector2() { }\n\n public IntVector2(int x, int y) {\n set(x, y);\n }\n\n public IntVector2(IntVector2 source) {\n set(source);\n }\n\n public void set(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public void set(IntVector2 source) {\n set(source.x, source.y);\n }\n\n public IntVector2 add(IntVector2 other) {\n set(x + other.x, y + other.y);\n\n return this;\n }\n\n public IntVector2 sub(IntVector2 other) {\n set(x - other.x, y - other.y);\n\n return this;\n }\n\n public IntVector2 cpy() {\n return new IntVector2(x, y);\n }\n\n public IntVector2 scl(int value) {\n x *= value;\n y *= value;\n\n return this;\n }\n\n public Vector2 toVector2() {\n return new Vector2(x, y);\n }\n\n public Vector3 toVector3() {\n return new Vector3(x, y, 0);\n }\n\n @Override\n public String toString() {\n return \"[\" + x + \",\" + y + \"]\";\n }\n\n}"
] | import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.Manager;
import com.artemis.annotations.Wire;
import com.artemis.managers.TagManager;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonWriter;
import com.github.fauu.helix.AreaType;
import com.github.fauu.helix.PassageAction;
import com.github.fauu.helix.TilePermission;
import com.github.fauu.helix.component.*;
import com.github.fauu.helix.datum.Tile;
import com.github.fauu.helix.datum.TileAreaPassage;
import com.github.fauu.helix.displayable.AreaDisplayable;
import com.github.fauu.helix.json.wrapper.AreaWrapper;
import com.github.fauu.helix.json.wrapper.TileWrapper;
import com.github.fauu.helix.util.IntVector2;
import java.io.FileWriter;
import java.io.IOException; | /*
* Copyright (C) 2014-2016 Helix Engine Developers
* (http://github.com/fauu/HelixEngine)
*
* This software is licensed under the GNU General Public License
* (version 3 or later). See the COPYING file in this distribution.
*
* You should have received a copy of the GNU Library General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Piotr Grabowski <[email protected]>
*/
package com.github.fauu.helix.manager;
public class AreaManager extends Manager {
@Wire
private ComponentMapper<AreaTypeComponent> areaTypeMapper;
@Wire
private ComponentMapper<DimensionsComponent> dimensionsMapper;
@Wire
private ComponentMapper<DisplayableComponent> displayableMapper;
@Wire
private ComponentMapper<NameComponent> nameMapper;
@Wire
private ComponentMapper<TilesComponent> tilesMapper;
@Wire
private AssetManager assetManager;
private Entity area;
// FIXME: Add area type
public void create(String name, int width, int length) {
Json json = new Json();
IntVector2 dimensions = new IntVector2(width, length);
FileHandle file = Gdx.files.internal("area/" + name + ".json");
try {
json.setWriter(new JsonWriter(new FileWriter(file.file())));
} catch (IOException e) {
e.printStackTrace();
}
json.writeObjectStart();
json.writeValue("width", dimensions.x);
json.writeValue("length", dimensions.y);
json.writeArrayStart("tiles");
for (int y = 0; y < dimensions.y; y++) {
for (int x = 0; x < dimensions.x; x++) {
json.writeObjectStart();
json.writeValue("permissions", TilePermission.LEVEL0.toString());
json.writeObjectEnd();
}
}
json.writeArrayEnd();
json.writeObjectEnd();
try {
json.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void load(String name) {
loadFromFile(Gdx.files.internal("area/" + name + ".json"), name);
}
public void loadFromFile(FileHandle file, String name) {
Json json = new Json();
json.setIgnoreUnknownFields(true);
| AreaWrapper areaWrapper = json.fromJson(AreaWrapper.class, file); | 6 |
sritchie/kryo | src/com/esotericsoftware/kryo/serializers/JavaSerializer.java | [
"public class Kryo {\r\n\tstatic public final byte NAME = -1;\r\n\tstatic public final byte NULL = 0;\r\n\tstatic public final byte NOT_NULL = 1;\r\n\r\n\tprivate Class<? extends Serializer> defaultSerializer = FieldSerializer.class;\r\n\tprivate final ArrayList<DefaultSerializerEntry> defaultSerializers = new ArrayList(32);\r\n\tprivate int lowPriorityDefaultSerializerCount;\r\n\tprivate ArraySerializer arraySerializer = new ArraySerializer();\r\n\tprivate InstantiatorStrategy strategy;\r\n\r\n\tprivate int depth, nextRegisterID;\r\n\tprivate final IntMap<Registration> idToRegistration = new IntMap();\r\n\tprivate final ObjectMap<Class, Registration> classToRegistration = new ObjectMap();\r\n\tprivate Class memoizedType;\r\n\tprivate Registration memoizedRegistration;\r\n\tprivate ObjectMap context, graphContext;\r\n\r\n\tprivate boolean registrationRequired;\r\n\tprivate final IdentityObjectIntMap<Class> classToNameId = new IdentityObjectIntMap();\r\n\tprivate final IntMap<Class> nameIdToClass = new IntMap();\r\n\tprivate int nextNameId;\r\n\tprivate ClassLoader classLoader = getClass().getClassLoader();\r\n\r\n\tprivate boolean references = true;\r\n\tprivate final InstanceId instanceId = new InstanceId(null, 0);\r\n\tprivate final IdentityObjectIntMap<Class> classToNextInstanceId = new IdentityObjectIntMap();\r\n\tprivate final IdentityObjectIntMap objectToInstanceId = new IdentityObjectIntMap();\r\n\tprivate final ObjectMap<InstanceId, Object> instanceIdToObject = new ObjectMap();\r\n\r\n\tpublic Kryo () {\r\n\t\taddDefaultSerializer(byte[].class, ByteArraySerializer.class);\r\n\t\taddDefaultSerializer(BigInteger.class, BigIntegerSerializer.class);\r\n\t\taddDefaultSerializer(BigDecimal.class, BigDecimalSerializer.class);\r\n\t\taddDefaultSerializer(Class.class, ClassSerializer.class);\r\n\t\taddDefaultSerializer(Date.class, DateSerializer.class);\r\n\t\taddDefaultSerializer(Enum.class, EnumSerializer.class);\r\n\t\taddDefaultSerializer(Currency.class, CurrencySerializer.class);\r\n\t\taddDefaultSerializer(StringBuffer.class, StringBufferSerializer.class);\r\n\t\taddDefaultSerializer(StringBuilder.class, StringBuilderSerializer.class);\r\n\t\taddDefaultSerializer(Collections.EMPTY_LIST.getClass(), CollectionsEmptyListSerializer.class);\r\n\t\taddDefaultSerializer(Collections.EMPTY_MAP.getClass(), CollectionsEmptyMapSerializer.class);\r\n\t\taddDefaultSerializer(Collections.EMPTY_SET.getClass(), CollectionsEmptySetSerializer.class);\r\n\t\taddDefaultSerializer(Collections.singletonList(null).getClass(), CollectionsSingletonListSerializer.class);\r\n\t\taddDefaultSerializer(Collections.singletonMap(null, null).getClass(), CollectionsSingletonMapSerializer.class);\r\n\t\taddDefaultSerializer(Collections.singleton(null).getClass(), CollectionsSingletonSetSerializer.class);\r\n\t\taddDefaultSerializer(Collection.class, CollectionSerializer.class);\r\n\t\taddDefaultSerializer(Map.class, MapSerializer.class);\r\n\t\taddDefaultSerializer(KryoSerializable.class, KryoSerializableSerializer.class);\r\n\t\tlowPriorityDefaultSerializerCount = defaultSerializers.size();\r\n\r\n\t\t// Primitives and string. Primitive wrappers automatically use the same registration as primitives.\r\n\t\tregister(boolean.class, new BooleanSerializer());\r\n\t\tregister(byte.class, new ByteSerializer());\r\n\t\tregister(char.class, new CharSerializer());\r\n\t\tregister(short.class, new ShortSerializer());\r\n\t\tregister(int.class, new IntSerializer());\r\n\t\tregister(long.class, new LongSerializer());\r\n\t\tregister(float.class, new FloatSerializer());\r\n\t\tregister(double.class, new DoubleSerializer());\r\n\t\tregister(String.class, new StringSerializer());\r\n\t}\r\n\r\n\t// --- Default serializers ---\r\n\r\n\t/** Sets the serailzer to use when no {@link #addDefaultSerializer(Class, Class) default serializers} match an object's type.\r\n\t * Default is {@link FieldSerializer}. */\r\n\tpublic void setDefaultSerializer (Class<Serializer> serializer) {\r\n\t\tif (serializer == null) throw new IllegalArgumentException(\"serializer cannot be null.\");\r\n\t\tdefaultSerializer = serializer;\r\n\t}\r\n\r\n\t/** Instances of the specified class will use the specified serializer.\r\n\t * @see #setDefaultSerializer(Class) */\r\n\tpublic void addDefaultSerializer (Class type, Serializer serializer) {\r\n\t\tif (type == null) throw new IllegalArgumentException(\"type cannot be null.\");\r\n\t\tif (serializer == null) throw new IllegalArgumentException(\"serializer cannot be null.\");\r\n\t\tDefaultSerializerEntry entry = new DefaultSerializerEntry();\r\n\t\tentry.type = type;\r\n\t\tentry.serializer = serializer;\r\n\t\tdefaultSerializers.add(defaultSerializers.size() - lowPriorityDefaultSerializerCount, entry);\r\n\t}\r\n\r\n\t/** Instances of the specified class will use the specified serializer. Serializer instances are created as needed via\r\n\t * {@link #newSerializer(Class, Class)}. By default, the following classes have a default serializer set:\r\n\t * <p>\r\n\t * <table>\r\n\t * <tr>\r\n\t * <td>boolean</td>\r\n\t * <td>Boolean</td>\r\n\t * <td>byte</td>\r\n\t * <td>Byte</td>\r\n\t * <td>char</td>\r\n\t * <td>Character</td>\r\n\t * <tr>\r\n\t * </tr>\r\n\t * <td>short</td>\r\n\t * <td>Short</td>\r\n\t * <td>int</td>\r\n\t * <td>Integer</td>\r\n\t * <td>long</td>\r\n\t * <td>Long</td>\r\n\t * <tr>\r\n\t * </tr>\r\n\t * <td>float</td>\r\n\t * <td>Float</td>\r\n\t * <td>double</td>\r\n\t * <td>Double</td>\r\n\t * <td>byte[]</td>\r\n\t * <td>String</td>\r\n\t * <tr>\r\n\t * </tr>\r\n\t * <td>BigInteger</td>\r\n\t * <td>BigDecimal</td>\r\n\t * <td>Class</td>\r\n\t * <td>Date</td>\r\n\t * <td>Enum</td>\r\n\t * <td>Currency</td>\r\n\t * </tr>\r\n\t * <tr>\r\n\t * <td>Map</td>\r\n\t * <td>Collection</td>\r\n\t * <td>Collections.emptyList</td>\r\n\t * <td>Collections.emptyMap</td>\r\n\t * <td>Collections.emptySet</td>\r\n\t * <td>KryoSerializable</td>\r\n\t * </tr>\r\n\t * <tr>\r\n\t * <td>StringBuffer</td>\r\n\t * <td>StringBuilder</td>\r\n\t * <td>Collections.singletonList</td>\r\n\t * <td>Collections.singletonMap</td>\r\n\t * <td>Collections.singleton</td>\r\n\t * </tr>\r\n\t * </table>\r\n\t * <p>\r\n\t * Note that the order default serializers are added is important for a class that may match multiple types. The above default\r\n\t * serializers always have a lower priority than subsequent default serializers that are added. */\r\n\tpublic void addDefaultSerializer (Class type, Class<? extends Serializer> serializerClass) {\r\n\t\tif (type == null) throw new IllegalArgumentException(\"type cannot be null.\");\r\n\t\tif (serializerClass == null) throw new IllegalArgumentException(\"serializerClass cannot be null.\");\r\n\t\tDefaultSerializerEntry entry = new DefaultSerializerEntry();\r\n\t\tentry.type = type;\r\n\t\tentry.serializerClass = serializerClass;\r\n\t\tdefaultSerializers.add(defaultSerializers.size() - lowPriorityDefaultSerializerCount, entry);\r\n\t}\r\n\r\n\t/** Returns the best matching serializer for a class. This method can be overridden to implement custom logic to choose a\r\n\t * serializer. */\r\n\tpublic Serializer getDefaultSerializer (Class type) {\r\n\t\tif (type == null) throw new IllegalArgumentException(\"type cannot be null.\");\r\n\r\n\t\tif (type.isAnnotationPresent(DefaultSerializer.class))\r\n\t\t\treturn newSerializer(((DefaultSerializer)type.getAnnotation(DefaultSerializer.class)).value(), type);\r\n\r\n\t\tfor (int i = 0, n = defaultSerializers.size(); i < n; i++) {\r\n\t\t\tDefaultSerializerEntry entry = defaultSerializers.get(i);\r\n\t\t\tif (entry.type.isAssignableFrom(type)) {\r\n\t\t\t\tif (entry.serializer != null) return entry.serializer;\r\n\t\t\t\treturn newSerializer(entry.serializerClass, type);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (type.isArray()) return arraySerializer;\r\n\r\n\t\treturn newSerializer(defaultSerializer, type);\r\n\t}\r\n\r\n\t/** Creates a new instance of the specified serializer for serializing the specified class. Serializers */\r\n\tpublic Serializer newSerializer (Class<? extends Serializer> serializerClass, Class type) {\r\n\t\ttry {\r\n\t\t\ttry {\r\n\t\t\t\treturn serializerClass.getConstructor(Kryo.class, Class.class).newInstance(this, type);\r\n\t\t\t} catch (NoSuchMethodException ex1) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\treturn serializerClass.getConstructor(Kryo.class).newInstance(this);\r\n\t\t\t\t} catch (NoSuchMethodException ex2) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\treturn serializerClass.getConstructor(Class.class).newInstance(type);\r\n\t\t\t\t\t} catch (NoSuchMethodException ex3) {\r\n\t\t\t\t\t\treturn serializerClass.newInstance();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception ex) {\r\n\t\t\tthrow new IllegalArgumentException(\"Unable to create serializer \\\"\" + serializerClass.getName() + \"\\\" for class: \"\r\n\t\t\t\t+ className(type), ex);\r\n\t\t}\r\n\t}\r\n\r\n\t// --- Registration ---\r\n\r\n\t/** Registers the class using the next available, lowest integer ID and the {@link #getDefaultSerializer(Class) default\r\n\t * serializer}. If the class is already registered, the existing entry is updated with the new serializer. Because the ID\r\n\t * assigned is affected by the IDs registered before it, the order classes are registered is important when using this method.\r\n\t * The order must be the same at deserialization as it was for serialization. Registering a primitive also affects the\r\n\t * corresponding primitive wrapper. */\r\n\tpublic Registration register (Class type) {\r\n\t\treturn register(type, getDefaultSerializer(type));\r\n\t}\r\n\r\n\t/** Registers the class using the specified ID and the {@link #getDefaultSerializer(Class) default serializer}. If the ID is\r\n\t * already in use by the same type, the old entry is overwritten. If the ID is already in use by a different type, a\r\n\t * {@link KryoException} is thrown. IDs are written with {@link Output#writeInt(int, boolean)} called with true, so smaller\r\n\t * positive integers use fewer bytes. IDs must be the same at deserialization as they were for serialization. Registering a\r\n\t * primitive also affects the corresponding primitive wrapper.\r\n\t * @param id Must not be -1 or -2. */\r\n\tpublic Registration register (Class type, int id) {\r\n\t\treturn register(type, getDefaultSerializer(type), id);\r\n\t}\r\n\r\n\t/** Registers the class using the next available, lowest integer ID. If the class is already registered, the existing entry is\r\n\t * updated with the new serializer. Because the ID assigned is affected by the IDs registered before it, the order classes are\r\n\t * registered is important when using this method. The order must be the same at deserialization as it was for serialization.\r\n\t * Registering a primitive also affects the corresponding primitive wrapper. */\r\n\tpublic Registration register (Class type, Serializer serializer) {\r\n\t\tRegistration registration = classToRegistration.get(type);\r\n\t\tif (registration != null) {\r\n\t\t\tregistration.setSerializer(serializer);\r\n\t\t\treturn registration;\r\n\t\t}\r\n\t\tint id;\r\n\t\twhile (true) {\r\n\t\t\tid = nextRegisterID++;\r\n\t\t\t// Disallow -1 and -2, which are used for NAME and NULL (stored as id + 2 == 1 and 0).\r\n\t\t\tif (nextRegisterID == -2) nextRegisterID = 0;\r\n\t\t\tif (!idToRegistration.containsKey(id)) break;\r\n\t\t}\r\n\t\treturn registerInternal(new Registration(type, serializer, id));\r\n\t}\r\n\r\n\t/** Registers the class using the specified ID. If the ID is already in use by the same type, the old entry is overwritten. If\r\n\t * the ID is already in use by a different type, a {@link KryoException} is thrown. IDs are written with\r\n\t * {@link Output#writeInt(int, boolean)} called with true, so smaller positive integers use fewer bytes. IDs must be the same\r\n\t * at deserialization as they were for serialization. Registering a primitive also affects the corresponding primitive wrapper.\r\n\t * @param id Must not be -1 or -2. */\r\n\tpublic Registration register (Class type, Serializer serializer, int id) {\r\n\t\tif (id == -1 || id == -2) throw new IllegalArgumentException(\"id cannot be -1 or -2\");\r\n\t\treturn register(new Registration(type, serializer, id));\r\n\t}\r\n\r\n\t/** Stores the specified registration. This can be used to efficiently store per type information needed for serialization,\r\n\t * accessible in serializers via {@link #getRegistration(Class)}. If the ID is already in use by the same type, the old entry\r\n\t * is overwritten. If the ID is already in use by a different type, a {@link KryoException} is thrown. IDs are written with\r\n\t * {@link Output#writeInt(int, boolean)} called with true, so smaller positive integers use fewer bytes. IDs must be the same\r\n\t * at deserialization as they were for serialization. Registering a primitive also affects the corresponding primitive wrapper.\r\n\t * @param registration The id must not be -1 or -2. */\r\n\tpublic Registration register (Registration registration) {\r\n\t\tif (registration == null) throw new IllegalArgumentException(\"registration cannot be null.\");\r\n\t\tint id = registration.getId();\r\n\t\tif (id == -1 || id == -2) throw new IllegalArgumentException(\"id cannot be -1 or -2\");\r\n\r\n\t\tRegistration existing = getRegistration(registration.getType());\r\n\t\tif (existing != null && existing.getType() != registration.getType()) {\r\n\t\t\tthrow new KryoException(\"An existing registration with a different type already uses ID: \" + registration.getId()\r\n\t\t\t\t+ \"\\nExisting registration: \" + existing + \"\\nUnable to set registration: \" + registration);\r\n\t\t}\r\n\r\n\t\tregisterInternal(registration);\r\n\t\treturn registration;\r\n\t}\r\n\r\n\tprivate Registration registerInternal (Registration registration) {\r\n\t\tif (TRACE) {\r\n\t\t\tif (registration.getId() == NAME) {\r\n\t\t\t\ttrace(\"kryo\", \"Register class name: \" + className(registration.getType()) + \" (\"\r\n\t\t\t\t\t+ registration.getSerializer().getClass().getName() + \")\");\r\n\t\t\t} else {\r\n\t\t\t\ttrace(\"kryo\", \"Register class ID \" + registration.getId() + \": \" + className(registration.getType()) + \" (\"\r\n\t\t\t\t\t+ registration.getSerializer().getClass().getName() + \")\");\r\n\t\t\t}\r\n\t\t}\r\n\t\tclassToRegistration.put(registration.getType(), registration);\r\n\t\tidToRegistration.put(registration.getId(), registration);\r\n\t\tif (registration.getType().isPrimitive()) classToRegistration.put(getWrapperClass(registration.getType()), registration);\r\n\t\treturn registration;\r\n\t}\r\n\r\n\t/** Returns the registration for the specified class. If the class is not registered {@link #setRegistrationRequired(boolean)}\r\n\t * is false, it is automatically registered using the {@link #addDefaultSerializer(Class, Class) default serializer}.\r\n\t * @throws IllegalArgumentException if the class is not registered and {@link #setRegistrationRequired(boolean)} is true. */\r\n\tpublic Registration getRegistration (Class type) {\r\n\t\tif (type == null) throw new IllegalArgumentException(\"type cannot be null.\");\r\n\r\n\t\tif (type == memoizedType) return memoizedRegistration;\r\n\t\tRegistration registration = classToRegistration.get(type);\r\n\t\tif (registration == null) {\r\n\t\t\tif (Proxy.isProxyClass(type)) {\r\n\t\t\t\t// If a Proxy class, treat it like an InvocationHandler because the concrete class for a proxy is generated.\r\n\t\t\t\tregistration = getRegistration(InvocationHandler.class);\r\n\t\t\t} else if (!type.isEnum() && Enum.class.isAssignableFrom(type)) {\r\n\t\t\t\t// This handles an enum value that is an inner class. Eg: enum A {b{}};\r\n\t\t\t\tregistration = getRegistration(type.getEnclosingClass());\r\n\t\t\t} else if (registrationRequired) {\r\n\t\t\t\tthrow new IllegalArgumentException(\"Class is not registered: \" + className(type)\r\n\t\t\t\t\t+ \"\\nNote: To register this class use: kryo.register(\" + className(type) + \".class);\");\r\n\t\t\t} else\r\n\t\t\t\tregistration = registerInternal(new Registration(type, getDefaultSerializer(type), NAME));\r\n\t\t}\r\n\t\tmemoizedType = type;\r\n\t\tmemoizedRegistration = registration;\r\n\t\treturn registration;\r\n\t}\r\n\r\n\t/** Returns the registration for the specified ID, or null if no class is registered with that ID. */\r\n\tpublic Registration getRegistration (int classID) {\r\n\t\treturn idToRegistration.get(classID);\r\n\t}\r\n\r\n\t/** Returns the serializer for the registration for the specified class.\r\n\t * @see #getRegistration(Class)\r\n\t * @see Registration#getSerializer() */\r\n\tpublic Serializer getSerializer (Class type) {\r\n\t\treturn getRegistration(type).getSerializer();\r\n\t}\r\n\r\n\t// --- Serialization ---\r\n\r\n\t/** Writes a class and returns its registration.\r\n\t * @param type May be null.\r\n\t * @return Will be null if type is null. */\r\n\tpublic Registration writeClass (Output output, Class type) {\r\n\t\tif (output == null) throw new IllegalArgumentException(\"output cannot be null.\");\r\n\t\ttry {\r\n\t\t\tif (type == null) {\r\n\t\t\t\tif (DEBUG) log(\"Write\", null);\r\n\t\t\t\toutput.writeByte(NULL);\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t\tRegistration registration = getRegistration(type);\r\n\t\t\tif (registration.getId() == NAME) {\r\n\t\t\t\toutput.writeByte(NAME + 2);\r\n\t\t\t\tint nameId = classToNameId.get(type, -1);\r\n\t\t\t\tif (nameId != -1) {\r\n\t\t\t\t\tif (TRACE) trace(\"kryo\", \"Write class name reference \" + nameId + \": \" + className(type));\r\n\t\t\t\t\toutput.writeInt(nameId, true);\r\n\t\t\t\t\treturn registration;\r\n\t\t\t\t}\r\n\t\t\t\t// Only write the class name the first time encountered in object graph.\r\n\t\t\t\tif (TRACE) trace(\"kryo\", \"Write class name: \" + className(type));\r\n\t\t\t\tnameId = nextNameId++;\r\n\t\t\t\tclassToNameId.put(type, nameId);\r\n\t\t\t\toutput.write(nameId);\r\n\t\t\t\toutput.writeString(type.getName());\r\n\t\t\t} else {\r\n\t\t\t\tif (TRACE) trace(\"kryo\", \"Write class \" + registration.getId() + \": \" + className(type));\r\n\t\t\t\toutput.writeInt(registration.getId() + 2, true);\r\n\t\t\t}\r\n\t\t\treturn registration;\r\n\t\t} finally {\r\n\t\t\tif (depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Writes an object using the registered serializer. */\r\n\tpublic void writeObject (Output output, Object object) {\r\n\t\tif (output == null) throw new IllegalArgumentException(\"output cannot be null.\");\r\n\t\tif (object == null) throw new IllegalArgumentException(\"object cannot be null.\");\r\n\t\tdepth++;\r\n\t\ttry {\r\n\t\t\tif (references && writeReferenceOrNull(output, object, false)) return;\r\n\t\t\tif (DEBUG) log(\"Write\", object);\r\n\t\t\tgetRegistration(object.getClass()).getSerializer().write(this, output, object);\r\n\t\t} finally {\r\n\t\t\tif (--depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Writes an object using the specified serializer. The registered serializer is ignored. */\r\n\tpublic void writeObject (Output output, Object object, Serializer serializer) {\r\n\t\tif (output == null) throw new IllegalArgumentException(\"output cannot be null.\");\r\n\t\tif (object == null) throw new IllegalArgumentException(\"object cannot be null.\");\r\n\t\tif (serializer == null) throw new IllegalArgumentException(\"serializer cannot be null.\");\r\n\t\tdepth++;\r\n\t\ttry {\r\n\t\t\tif (references && writeReferenceOrNull(output, object, false)) return;\r\n\t\t\tif (DEBUG) log(\"Write\", object);\r\n\t\t\tserializer.write(this, output, object);\r\n\t\t} finally {\r\n\t\t\tif (--depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Writes an object or null using the registered serializer.\r\n\t * @param object May be null. */\r\n\tpublic void writeObjectOrNull (Output output, Object object) {\r\n\t\tif (output == null) throw new IllegalArgumentException(\"output cannot be null.\");\r\n\t\tdepth++;\r\n\t\ttry {\r\n\t\t\tSerializer serializer = getRegistration(object.getClass()).getSerializer();\r\n\t\t\tif (references) {\r\n\t\t\t\tif (writeReferenceOrNull(output, object, true)) return;\r\n\t\t\t} else if (!serializer.getAcceptsNull()) {\r\n\t\t\t\tif (object == null) {\r\n\t\t\t\t\tif (DEBUG) log(\"Write\", object);\r\n\t\t\t\t\toutput.writeByte(NULL);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\toutput.writeByte(Kryo.NOT_NULL);\r\n\t\t\t}\r\n\t\t\tif (DEBUG) log(\"Write\", object);\r\n\t\t\tserializer.write(this, output, object);\r\n\t\t} finally {\r\n\t\t\tif (--depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Writes an object or null using the specified serializer. The registered serializer is ignored.\r\n\t * @param object May be null. */\r\n\tpublic void writeObjectOrNull (Output output, Object object, Serializer serializer) {\r\n\t\tif (output == null) throw new IllegalArgumentException(\"output cannot be null.\");\r\n\t\tif (serializer == null) throw new IllegalArgumentException(\"serializer cannot be null.\");\r\n\t\tdepth++;\r\n\t\ttry {\r\n\t\t\tif (references) {\r\n\t\t\t\tif (writeReferenceOrNull(output, object, true)) return;\r\n\t\t\t} else if (!serializer.getAcceptsNull()) {\r\n\t\t\t\tif (object == null) {\r\n\t\t\t\t\tif (DEBUG) log(\"Write\", null);\r\n\t\t\t\t\toutput.writeByte(NULL);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\toutput.writeByte(Kryo.NOT_NULL);\r\n\t\t\t}\r\n\t\t\tif (DEBUG) log(\"Write\", object);\r\n\t\t\tserializer.write(this, output, object);\r\n\t\t} finally {\r\n\t\t\tif (--depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Writes the class and object or null using the registered serializer.\r\n\t * @param object May be null. */\r\n\tpublic void writeClassAndObject (Output output, Object object) {\r\n\t\tif (output == null) throw new IllegalArgumentException(\"output cannot be null.\");\r\n\t\tdepth++;\r\n\t\ttry {\r\n\t\t\tif (object == null) {\r\n\t\t\t\twriteClass(output, null);\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tRegistration registration = writeClass(output, object.getClass());\r\n\t\t\tif (references && writeReferenceOrNull(output, object, false)) return;\r\n\t\t\tif (DEBUG) log(\"Write\", object);\r\n\t\t\tregistration.getSerializer().write(this, output, object);\r\n\t\t} finally {\r\n\t\t\tif (--depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** @param object May be null if mayBeNull is true. */\r\n\tprivate boolean writeReferenceOrNull (Output output, Object object, boolean mayBeNull) {\r\n\t\tif (object == null) {\r\n\t\t\tif (DEBUG) log(\"Write\", null);\r\n\t\t\toutput.writeByte(NULL);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tClass type = object.getClass();\r\n\t\tif (!useReferences(type)) {\r\n\t\t\tif (mayBeNull) output.writeByte(Kryo.NOT_NULL);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tint instanceId = objectToInstanceId.get(object, -1);\r\n\t\tif (instanceId != -1) {\r\n\t\t\tif (DEBUG) debug(\"kryo\", \"Write object reference \" + instanceId + \": \" + string(object));\r\n\t\t\toutput.writeInt(instanceId, true);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\t// Only write the object the first time encountered in object graph.\r\n\t\tinstanceId = classToNextInstanceId.getAndIncrement(type, 1, 1);\r\n\t\tif (TRACE) trace(\"kryo\", \"Write initial object reference \" + instanceId + \": \" + string(object));\r\n\t\tobjectToInstanceId.put(object, instanceId);\r\n\t\toutput.writeInt(instanceId, true);\r\n\t\treturn false;\r\n\t}\r\n\r\n\t/** Reads a class and returns its registration.\r\n\t * @return May be null. */\r\n\tpublic Registration readClass (Input input) {\r\n\t\tif (input == null) throw new IllegalArgumentException(\"input cannot be null.\");\r\n\t\ttry {\r\n\t\t\tint classID = input.readInt(true);\r\n\t\t\tswitch (classID) {\r\n\t\t\tcase NULL:\r\n\t\t\t\tif (DEBUG) log(\"Read\", null);\r\n\t\t\t\treturn null;\r\n\t\t\tcase NAME + 2: // Offset for NAME and NULL.\r\n\t\t\t\tint nameId = input.readInt(true);\r\n\t\t\t\tClass type = nameIdToClass.get(nameId);\r\n\t\t\t\tif (type == null) {\r\n\t\t\t\t\t// Only read the class name the first time encountered in object graph.\r\n\t\t\t\t\tString className = input.readString();\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\ttype = Class.forName(className, false, classLoader);\r\n\t\t\t\t\t} catch (ClassNotFoundException ex) {\r\n\t\t\t\t\t\tthrow new KryoException(\"Unable to find class: \" + className, ex);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tnameIdToClass.put(nameId, type);\r\n\t\t\t\t\tif (TRACE) trace(\"kryo\", \"Read class name: \" + className);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (TRACE) trace(\"kryo\", \"Read class name reference \" + nameId + \": \" + className(type));\r\n\t\t\t\t}\r\n\t\t\t\treturn getRegistration(type);\r\n\t\t\t}\r\n\t\t\tRegistration registration = idToRegistration.get(classID - 2);\r\n\t\t\tif (registration == null) throw new KryoException(\"Encountered unregistered class ID: \" + (classID - 2));\r\n\t\t\tif (TRACE) trace(\"kryo\", \"Read class \" + (classID - 2) + \": \" + className(registration.getType()));\r\n\t\t\treturn registration;\r\n\t\t} finally {\r\n\t\t\tif (depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Reads an object using the registered serializer. */\r\n\tpublic <T> T readObject (Input input, Class<T> type) {\r\n\t\tif (input == null) throw new IllegalArgumentException(\"input cannot be null.\");\r\n\t\tif (type == null) throw new IllegalArgumentException(\"type cannot be null.\");\r\n\t\tdepth++;\r\n\t\ttry {\r\n\t\t\tInstanceId instanceId = null;\r\n\t\t\tif (references) {\r\n\t\t\t\tinstanceId = readReferenceOrNull(input, type, false);\r\n\t\t\t\tif (instanceId == this.instanceId) return (T)instanceId.object;\r\n\t\t\t}\r\n\r\n\t\t\tSerializer serializer = getRegistration(type).getSerializer();\r\n\t\t\tT object = (T)serializer.create(this, input, type);\r\n\t\t\tif (instanceId != null) instanceIdToObject.put(instanceId, object);\r\n\t\t\tserializer.read(this, input, object);\r\n\t\t\tif (DEBUG) log(\"Read\", object);\r\n\t\t\treturn object;\r\n\t\t} finally {\r\n\t\t\tif (--depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Reads an object using the specified serializer. The registered serializer is ignored. */\r\n\tpublic <T> T readObject (Input input, Class<T> type, Serializer serializer) {\r\n\t\tif (input == null) throw new IllegalArgumentException(\"input cannot be null.\");\r\n\t\tif (type == null) throw new IllegalArgumentException(\"type cannot be null.\");\r\n\t\tif (serializer == null) throw new IllegalArgumentException(\"serializer cannot be null.\");\r\n\t\tdepth++;\r\n\t\ttry {\r\n\t\t\tInstanceId instanceId = null;\r\n\t\t\tif (references) {\r\n\t\t\t\tinstanceId = readReferenceOrNull(input, type, false);\r\n\t\t\t\tif (instanceId == this.instanceId) return (T)instanceId.object;\r\n\t\t\t}\r\n\r\n\t\t\tT object = (T)serializer.create(this, input, type);\r\n\t\t\tif (instanceId != null) instanceIdToObject.put(instanceId, object);\r\n\t\t\tserializer.read(this, input, object);\r\n\t\t\tif (DEBUG) log(\"Read\", object);\r\n\t\t\treturn object;\r\n\t\t} finally {\r\n\t\t\tif (--depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Reads an object or null using the registered serializer.\r\n\t * @return May be null. */\r\n\tpublic <T> T readObjectOrNull (Input input, Class<T> type) {\r\n\t\tif (input == null) throw new IllegalArgumentException(\"input cannot be null.\");\r\n\t\tif (type == null) throw new IllegalArgumentException(\"type cannot be null.\");\r\n\t\tdepth++;\r\n\t\ttry {\r\n\t\t\tSerializer serializer = getRegistration(type).getSerializer();\r\n\r\n\t\t\tInstanceId instanceId = null;\r\n\t\t\tif (references) {\r\n\t\t\t\tinstanceId = readReferenceOrNull(input, type, true);\r\n\t\t\t\tif (instanceId == this.instanceId) return (T)instanceId.object;\r\n\t\t\t} else if (!serializer.getAcceptsNull()) {\r\n\t\t\t\tif (input.readByte() == NULL) {\r\n\t\t\t\t\tif (DEBUG) log(\"Read\", null);\r\n\t\t\t\t\treturn null;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tT object = (T)serializer.create(this, input, type);\r\n\t\t\tif (instanceId != null) instanceIdToObject.put(instanceId, object);\r\n\t\t\tserializer.read(this, input, object);\r\n\t\t\tif (DEBUG) log(\"Read\", object);\r\n\t\t\treturn object;\r\n\t\t} finally {\r\n\t\t\tif (--depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Reads an object or null using the specified serializer. The registered serializer is ignored.\r\n\t * @return May be null. */\r\n\tpublic <T> T readObjectOrNull (Input input, Class<T> type, Serializer serializer) {\r\n\t\tif (input == null) throw new IllegalArgumentException(\"input cannot be null.\");\r\n\t\tif (type == null) throw new IllegalArgumentException(\"type cannot be null.\");\r\n\t\tif (serializer == null) throw new IllegalArgumentException(\"serializer cannot be null.\");\r\n\t\tdepth++;\r\n\t\ttry {\r\n\t\t\tInstanceId instanceId = null;\r\n\t\t\tif (references) {\r\n\t\t\t\tinstanceId = readReferenceOrNull(input, type, true);\r\n\t\t\t\tif (instanceId == this.instanceId) return (T)instanceId.object;\r\n\t\t\t} else if (!serializer.getAcceptsNull()) {\r\n\t\t\t\tif (input.readByte() == NULL) {\r\n\t\t\t\t\tif (DEBUG) log(\"Read\", null);\r\n\t\t\t\t\treturn null;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tT object = (T)serializer.create(this, input, type);\r\n\t\t\tif (instanceId != null) instanceIdToObject.put(instanceId, object);\r\n\t\t\tserializer.read(this, input, object);\r\n\t\t\tif (DEBUG) log(\"Read\", object);\r\n\t\t\treturn object;\r\n\t\t} finally {\r\n\t\t\tif (--depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Reads the class and object or null using the registered serializer.\r\n\t * @return May be null. */\r\n\tpublic Object readClassAndObject (Input input) {\r\n\t\tif (input == null) throw new IllegalArgumentException(\"input cannot be null.\");\r\n\t\tdepth++;\r\n\t\ttry {\r\n\t\t\tRegistration registration = readClass(input);\r\n\t\t\tif (registration == null) return null;\r\n\t\t\tClass type = registration.getType();\r\n\r\n\t\t\tInstanceId instanceId = null;\r\n\t\t\tif (references) {\r\n\t\t\t\tinstanceId = readReferenceOrNull(input, type, false);\r\n\t\t\t\tif (instanceId == this.instanceId) return instanceId.object;\r\n\t\t\t}\r\n\r\n\t\t\tSerializer serializer = registration.getSerializer();\r\n\t\t\tObject object = serializer.create(this, input, type);\r\n\t\t\tif (instanceId != null) instanceIdToObject.put(instanceId, object);\r\n\t\t\tserializer.read(this, input, object);\r\n\t\t\tif (DEBUG) log(\"Read\", object);\r\n\t\t\treturn object;\r\n\t\t} finally {\r\n\t\t\tif (--depth == 0) reset();\r\n\t\t}\r\n\t}\r\n\r\n\t/** @return Null if references for the type is not supported. this.instanceId if the object field should be used. A new\r\n\t * InstanceId if this is the first time the object appears in the graph. */\r\n\tprivate InstanceId readReferenceOrNull (Input input, Class type, boolean mayBeNull) {\r\n\t\tif (type.isPrimitive()) type = getWrapperClass(type);\r\n\t\tboolean referencesSupported = useReferences(type);\r\n\t\tint id;\r\n\t\tif (mayBeNull) {\r\n\t\t\tid = input.readInt(true);\r\n\t\t\tif (id == NULL) {\r\n\t\t\t\tif (DEBUG) log(\"Read\", null);\r\n\t\t\t\tinstanceId.object = null;\r\n\t\t\t\treturn instanceId;\r\n\t\t\t}\r\n\t\t\tif (!referencesSupported) return null;\r\n\t\t} else {\r\n\t\t\tif (!referencesSupported) return null;\r\n\t\t\tid = input.readInt(true);\r\n\t\t}\r\n\t\tinstanceId.id = id;\r\n\t\tinstanceId.type = type;\r\n\t\tObject object = instanceIdToObject.get(instanceId);\r\n\t\tif (object != null) {\r\n\t\t\tif (DEBUG) debug(\"kryo\", \"Read object reference \" + id + \": \" + string(object));\r\n\t\t\tinstanceId.object = object;\r\n\t\t\treturn instanceId;\r\n\t\t}\r\n\t\tif (TRACE) trace(\"kryo\", \"Read initial object reference \" + id + \": \" + className(type));\r\n\t\treturn new InstanceId(type, id);\r\n\t}\r\n\r\n\t/** Called when an object graph has been completely serialized or deserialized, allowing any state only needed per object graph\r\n\t * to be reset. If overridden, the super method must be called. */\r\n\tprotected void reset () {\r\n\t\tdepth = 0;\r\n\t\tif (graphContext != null) graphContext.clear();\r\n\t\tif (!registrationRequired) {\r\n\t\t\tclassToNameId.clear();\r\n\t\t\tnameIdToClass.clear();\r\n\t\t\tnextNameId = 0;\r\n\t\t}\r\n\t\tif (references) {\r\n\t\t\tobjectToInstanceId.clear();\r\n\t\t\tinstanceIdToObject.clear();\r\n\t\t\tclassToNextInstanceId.clear();\r\n\t\t}\r\n\t\tif (TRACE) trace(\"kryo\", \"Object graph complete.\");\r\n\t}\r\n\r\n\t/** Sets the classloader to resolve unregistered class names to classes. */\r\n\tpublic void setClassLoader (ClassLoader classLoader) {\r\n\t\tif (classLoader == null) throw new IllegalArgumentException(\"classLoader cannot be null.\");\r\n\t\tthis.classLoader = classLoader;\r\n\t}\r\n\r\n\t/** If true, an exception is thrown when an unregistered class is encountered. Default is false.\r\n\t * <p>\r\n\t * If false, when an unregistered class is encountered, its fully qualified class name will be serialized and the\r\n\t * {@link #addDefaultSerializer(Class, Class) default serializer} for the class used to serialize the object. Subsequent\r\n\t * appearances of the class within the same object graph are serialized as an int id.\r\n\t * <p>\r\n\t * Registered classes are serialized as an int id, avoiding the overhead of serializing the class name, but have the drawback\r\n\t * of needing to know the classes to be serialized up front. */\r\n\tpublic void setRegistrationRequired (boolean registrationRequired) {\r\n\t\tthis.registrationRequired = registrationRequired;\r\n\t\tif (TRACE) trace(\"kryo\", \"Registration required: \" + registrationRequired);\r\n\t}\r\n\r\n\t/** If true, each appearance of an object in the graph after the first is stored as an integer ordinal. This enables references\r\n\t * to the same object and cyclic graphs to be serialized, but has the overhead of one byte per object. Default is true. */\r\n\tpublic void setReferences (boolean references) {\r\n\t\tthis.references = references;\r\n\t\tif (TRACE) trace(\"kryo\", \"References: \" + references);\r\n\t}\r\n\r\n\t/** Returns true if references will be written for the specified type when references are enabled. The default implementation\r\n\t * returns false for Boolean, Byte, Character, and Short.\r\n\t * @param type Will never be a primitive type, but may be a primitive type wrapper. */\r\n\tprotected boolean useReferences (Class type) {\r\n\t\treturn type != Boolean.class && type != Byte.class && type != Character.class && type != Short.class;\r\n\t}\r\n\r\n\t/** Sets the serializer to use for arrays. */\r\n\tpublic void setArraySerializer (ArraySerializer arraySerializer) {\r\n\t\tif (arraySerializer == null) throw new IllegalArgumentException(\"arraySerializer cannot be null.\");\r\n\t\tthis.arraySerializer = arraySerializer;\r\n\t\tif (TRACE) trace(\"kryo\", \"Array serializer set: \" + arraySerializer.getClass().getName());\r\n\t}\r\n\r\n\tpublic ArraySerializer getArraySerializer () {\r\n\t\treturn arraySerializer;\r\n\t}\r\n\r\n\t/** Sets the strategy used by {@link #newInstantiator(Class)} for creating objects. See {@link StdInstantiatorStrategy} to\r\n\t * create objects via without calling any constructor. See {@link SerializingInstantiatorStrategy} to mimic Java's built-in\r\n\t * serialization.\r\n\t * @param strategy May be null. */\r\n\tpublic void setInstantiatorStrategy (InstantiatorStrategy strategy) {\r\n\t\tthis.strategy = strategy;\r\n\t}\r\n\r\n\t/** Returns a new instantiator for creating new instances of the specified type. By default, an instantiator is returned that\r\n\t * uses reflection if the class has a zero argument constructor, an exception is thrown. If a\r\n\t * {@link #setInstantiatorStrategy(InstantiatorStrategy) strategy} is set, it will be used instead of throwing an exception. */\r\n\tprotected ObjectInstantiator newInstantiator (final Class type) {\r\n\t\ttry {\r\n\t\t\tfinal Constructor constructor = type.getDeclaredConstructor((Class[])null);\r\n\t\t\treturn new ObjectInstantiator() {\r\n\t\t\t\tpublic Object newInstance () {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\treturn constructor.newInstance();\r\n\t\t\t\t\t} catch (Exception ex) {\r\n\t\t\t\t\t\tthrow new KryoException(\"Error constructing instance of class: \" + className(type), ex);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t} catch (Exception ignored) {\r\n\t\t}\r\n\t\tif (strategy == null) {\r\n\t\t\tif (type.isMemberClass() && !Modifier.isStatic(type.getModifiers()))\r\n\t\t\t\tthrow new KryoException(\"Class cannot be created (non-static member class): \" + className(type));\r\n\t\t\telse\r\n\t\t\t\tthrow new KryoException(\"Class cannot be created (missing no-arg constructor): \" + className(type));\r\n\t\t}\r\n\t\treturn strategy.newInstantiatorOf(type);\r\n\t}\r\n\r\n\t/** Creates a new instance of a class using {@link Registration#getInstantiator()}. If the registration's instantiator is null,\r\n\t * a new one is set using {@link #newInstantiator(Class)}. */\r\n\tpublic <T> T newInstance (Class<T> type) {\r\n\t\tRegistration registration = getRegistration(type);\r\n\t\tObjectInstantiator instantiator = registration.getInstantiator();\r\n\t\tif (instantiator == null) {\r\n\t\t\tinstantiator = newInstantiator(type);\r\n\t\t\tregistration.setInstantiator(instantiator);\r\n\t\t}\r\n\t\treturn (T)instantiator.newInstance();\r\n\t}\r\n\r\n\t/** Name/value pairs that are available to all serializers. */\r\n\tpublic ObjectMap getContext () {\r\n\t\tif (context == null) context = new ObjectMap();\r\n\t\treturn context;\r\n\t}\r\n\r\n\t/** Name/value pairs that are available to all serializers and are cleared after each object graph is serialized or\r\n\t * deserialized. */\r\n\tpublic ObjectMap getGraphContext () {\r\n\t\tif (graphContext == null) graphContext = new ObjectMap();\r\n\t\treturn graphContext;\r\n\t}\r\n\r\n\t// --- Utility ---\r\n\r\n\t/** Returns true if the specified type is final, or if it is an array of a final type. Final types can be serialized more\r\n\t * efficiently because they are non-polymorphic.\r\n\t * <p>\r\n\t * This can be overridden to force non-final classes to be treated as final. Eg, if an application uses ArrayList extensively\r\n\t * but never uses an ArrayList subclass, treating ArrayList as final would allow FieldSerializer to save 1-2 bytes per\r\n\t * ArrayList field. */\r\n\tpublic boolean isFinal (Class type) {\r\n\t\tif (type == null) throw new IllegalArgumentException(\"type cannot be null.\");\r\n\t\tif (type.isArray()) return Modifier.isFinal(ArraySerializer.getElementClass(type).getModifiers());\r\n\t\treturn Modifier.isFinal(type.getModifiers());\r\n\t}\r\n\r\n\tstatic final class InstanceId {\r\n\t\tClass type;\r\n\t\tint id;\r\n\t\tObject object; // Set in readReferenceOrNull() for use as a return value.\r\n\r\n\t\tpublic InstanceId (Class type, int id) {\r\n\t\t\tthis.type = type;\r\n\t\t\tthis.id = id;\r\n\t\t}\r\n\r\n\t\tpublic int hashCode () {\r\n\t\t\treturn 31 * (31 + id) + type.hashCode();\r\n\t\t}\r\n\r\n\t\tpublic boolean equals (Object obj) {\r\n\t\t\tif (obj == null) return false;\r\n\t\t\tInstanceId other = (InstanceId)obj;\r\n\t\t\tif (id != other.id) return false;\r\n\t\t\tif (type != other.type) return false;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\r\n\tstatic final class DefaultSerializerEntry {\r\n\t\tClass type;\r\n\t\tSerializer serializer;\r\n\t\tClass<? extends Serializer> serializerClass;\r\n\t}\r\n}\r",
"public interface KryoSerializable {\r\n\tpublic void write (Kryo kryo, Output output);\r\n\r\n\tpublic void read (Kryo kryo, Input input);\r\n}\r",
"public abstract class Serializer<T> {\r\n\tprivate boolean acceptsNull;\r\n\r\n\t/** Writes the bytes for the object to the output.\r\n\t * @param object May be null if {@link #getAcceptsNull()} is true. */\r\n\tabstract public void write (Kryo kryo, Output output, T object);\r\n\r\n\t/** Creates a new object of the specified type. The object may be uninitialized. This method may read from input to populate the\r\n\t * object, but it must not call {@link Kryo} methods to deserialize nested objects. That must be done in\r\n\t * {@link #read(Kryo, Input, Object)}. The default implementation uses {@link Kryo#newInstance(Class)} to create a new object.\r\n\t * @return May be null if {@link #getAcceptsNull()} is true. */\r\n\tpublic T create (Kryo kryo, Input input, Class<T> type) {\r\n\t\treturn kryo.newInstance(type);\r\n\t}\r\n\r\n\t/** Populates the object. This method may call {@link Kryo} methods to deserialize nested objects, unlike\r\n\t * {@link #create(Kryo, Input, Class)}. The default implementation is empty.\r\n\t * <p>\r\n\t * Any serializer that uses {@link Kryo} to serialize another object may need to be reentrant. */\r\n\tpublic void read (Kryo kryo, Input input, T object) {\r\n\t}\r\n\r\n\tpublic boolean getAcceptsNull () {\r\n\t\treturn acceptsNull;\r\n\t}\r\n\r\n\t/** If true, this serializer will handle writing and reading null values. If false, the Kryo framework handles null values. */\r\n\tpublic void setAcceptsNull (boolean acceptsNull) {\r\n\t\tthis.acceptsNull = acceptsNull;\r\n\t}\r\n}\r",
"public class Input extends InputStream {\r\n\tprivate byte[] buffer;\r\n\tprivate int capacity, position, limit, total;\r\n\tprivate char[] chars = new char[32];\r\n\tprivate InputStream inputStream;\r\n\r\n\t/** Creates a new Input for reading from a byte array.\r\n\t * @param bufferSize The size of the buffer. An exception is thrown if more bytes than this are read. */\r\n\tpublic Input (int bufferSize) {\r\n\t\tthis.capacity = bufferSize;\r\n\t\tbuffer = new byte[bufferSize];\r\n\t}\r\n\r\n\t/** Creates a new Input for reading from a byte array.\r\n\t * @param buffer An exception is thrown if more bytes than this are read. */\r\n\tpublic Input (byte[] buffer) {\r\n\t\tsetBuffer(buffer, 0, buffer.length);\r\n\t}\r\n\r\n\t/** Creates a new Input for reading from a byte array.\r\n\t * @param buffer An exception is thrown if more bytes than this are read. */\r\n\tpublic Input (byte[] buffer, int offset, int count) {\r\n\t\tsetBuffer(buffer, offset, count);\r\n\t}\r\n\r\n\t/** Creates a new Input for reading from an InputStream with a buffer size of 4096. */\r\n\tpublic Input (InputStream inputStream) {\r\n\t\tthis(4096);\r\n\t\tif (inputStream == null) throw new IllegalArgumentException(\"inputStream cannot be null.\");\r\n\t\tthis.inputStream = inputStream;\r\n\t}\r\n\r\n\t/** Creates a new Input for reading from an InputStream. */\r\n\tpublic Input (InputStream inputStream, int bufferSize) {\r\n\t\tthis(bufferSize);\r\n\t\tif (inputStream == null) throw new IllegalArgumentException(\"inputStream cannot be null.\");\r\n\t\tthis.inputStream = inputStream;\r\n\t}\r\n\r\n\t/** Sets a new buffer. The position and total are reset, discarding any buffered bytes. */\r\n\tpublic void setBuffer (byte[] bytes) {\r\n\t\tsetBuffer(bytes, 0, bytes.length);\r\n\t}\r\n\r\n\t/** Sets a new buffer. The position and total are reset, discarding any buffered bytes. */\r\n\tpublic void setBuffer (byte[] bytes, int offset, int count) {\r\n\t\tif (bytes == null) throw new IllegalArgumentException(\"bytes cannot be null.\");\r\n\t\tbuffer = bytes;\r\n\t\tposition = offset;\r\n\t\tlimit = count;\r\n\t\tcapacity = bytes.length;\r\n\t\ttotal = 0;\r\n\t\tinputStream = null;\r\n\t}\r\n\r\n\tpublic InputStream getInputStream () {\r\n\t\treturn inputStream;\r\n\t}\r\n\r\n\t/** Sets a new InputStream. The position and total are reset, discarding any buffered bytes. */\r\n\tpublic void setInputStream (InputStream inputStream) {\r\n\t\tif (inputStream == null) throw new IllegalArgumentException(\"inputStream cannot be null.\");\r\n\t\tthis.inputStream = inputStream;\r\n\t\tlimit = 0;\r\n\t\trewind();\r\n\t}\r\n\r\n\t/** Returns the number of bytes read. */\r\n\tpublic int total () {\r\n\t\treturn total + position;\r\n\t}\r\n\r\n\t/** Returns the current position in the buffer. */\r\n\tpublic int position () {\r\n\t\treturn position;\r\n\t}\r\n\r\n\t/** Sets the current position in the buffer. */\r\n\tpublic void setPosition (int position) {\r\n\t\tthis.position = position;\r\n\t}\r\n\r\n\t/** Sets the position and total to zero. */\r\n\tpublic void rewind () {\r\n\t\tposition = 0;\r\n\t\ttotal = 0;\r\n\t}\r\n\r\n\t/** Discards the specified number of bytes. */\r\n\tpublic void skip (int count) throws KryoException {\r\n\t\tint skipCount = Math.min(limit - position, count);\r\n\t\twhile (true) {\r\n\t\t\tposition += skipCount;\r\n\t\t\tcount -= skipCount;\r\n\t\t\tif (count == 0) break;\r\n\t\t\tskipCount = Math.min(count, capacity);\r\n\t\t\trequire(skipCount);\r\n\t\t}\r\n\t}\r\n\r\n\t/** Fills the buffer with more bytes. Can be overridden to fill the bytes from a source other than the InputStream. */\r\n\tprotected int fill (byte[] buffer, int offset, int count) throws KryoException {\r\n\t\tif (inputStream == null) return -1;\r\n\t\ttry {\r\n\t\t\treturn inputStream.read(buffer, offset, count);\r\n\t\t} catch (IOException ex) {\r\n\t\t\tthrow new KryoException(ex);\r\n\t\t}\r\n\t}\r\n\r\n\t/** @param required Must be > 0. The buffer is filled until it has at least this many bytes.\r\n\t * @return the number of bytes remaining.\r\n\t * @throws KryoException if EOS is reached before required bytes are read (buffer underflow). */\r\n\tprivate int require (int required) throws KryoException {\r\n\t\tint remaining = limit - position;\r\n\t\tif (remaining >= required) return remaining;\r\n\t\tif (required > capacity) throw new KryoException(\"Buffer too small: capacity: \" + capacity + \", required: \" + required);\r\n\r\n\t\t// Compact.\r\n\t\tSystem.arraycopy(buffer, position, buffer, 0, remaining);\r\n\t\ttotal += position;\r\n\t\tposition = 0;\r\n\r\n\t\twhile (true) {\r\n\t\t\tint count = fill(buffer, remaining, capacity - remaining);\r\n\t\t\tif (count == -1) {\r\n\t\t\t\tif (remaining >= required) break;\r\n\t\t\t\tthrow new KryoException(\"Buffer underflow.\");\r\n\t\t\t}\r\n\t\t\tremaining += count;\r\n\t\t\tif (remaining >= required) break; // Enough has been read.\r\n\t\t}\r\n\t\tlimit = remaining;\r\n\t\treturn remaining;\r\n\t}\r\n\r\n\t/** @param optional Try to fill the buffer with this many bytes.\r\n\t * @return the number of bytes remaining, but not more than optional, or -1 if the EOS was reached and the buffer is empty. */\r\n\tprivate int optional (int optional) throws KryoException {\r\n\t\tint remaining = limit - position;\r\n\t\tif (remaining >= optional) return optional;\r\n\t\toptional = Math.min(optional, capacity);\r\n\r\n\t\t// Compact.\r\n\t\tSystem.arraycopy(buffer, position, buffer, 0, remaining);\r\n\t\ttotal += position;\r\n\t\tposition = 0;\r\n\r\n\t\twhile (true) {\r\n\t\t\tint count = fill(buffer, remaining, capacity - remaining);\r\n\t\t\tif (count == -1) break;\r\n\t\t\tremaining += count;\r\n\t\t\tif (remaining >= optional) break; // Enough has been read.\r\n\t\t}\r\n\t\tlimit = remaining;\r\n\t\treturn remaining == 0 ? -1 : Math.min(remaining, optional);\r\n\t}\r\n\r\n\t// InputStream\r\n\r\n\t/** Reads a byte. */\r\n\tpublic int read () throws KryoException {\r\n\t\trequire(1);\r\n\t\treturn buffer[position++];\r\n\t}\r\n\r\n\tpublic int read (byte[] bytes) throws KryoException {\r\n\t\treturn read(bytes, 0, bytes.length);\r\n\t}\r\n\r\n\tpublic int read (byte[] bytes, int offset, int count) throws KryoException {\r\n\t\tif (bytes == null) throw new IllegalArgumentException(\"bytes cannot be null.\");\r\n\t\tint startingCount = count;\r\n\t\tint copyCount = Math.min(limit - position, count);\r\n\t\twhile (true) {\r\n\t\t\tSystem.arraycopy(buffer, position, bytes, offset, copyCount);\r\n\t\t\tposition += copyCount;\r\n\t\t\tcount -= copyCount;\r\n\t\t\tif (count == 0) break;\r\n\t\t\toffset += copyCount;\r\n\t\t\tcopyCount = optional(count);\r\n\t\t\tif (copyCount == -1) {\r\n\t\t\t\t// End of data.\r\n\t\t\t\tif (startingCount == count) return -1;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (position == limit) break;\r\n\t\t}\r\n\t\treturn startingCount - count;\r\n\t}\r\n\r\n\t/** Discards the specified number of bytes. */\r\n\tpublic long skip (long count) throws KryoException {\r\n\t\tlong remaining = count;\r\n\t\twhile (remaining > 0) {\r\n\t\t\tint skip = Math.max(Integer.MAX_VALUE, (int)remaining);\r\n\t\t\tskip(skip);\r\n\t\t\tremaining -= skip;\r\n\t\t}\r\n\t\treturn count;\r\n\t}\r\n\r\n\t/** Closes the underlying InputStream, if any. */\r\n\tpublic void close () throws KryoException {\r\n\t\tif (inputStream != null) {\r\n\t\t\ttry {\r\n\t\t\t\tinputStream.close();\r\n\t\t\t} catch (IOException ignored) {\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// byte\r\n\r\n\tpublic byte readByte () throws KryoException {\r\n\t\trequire(1);\r\n\t\treturn buffer[position++];\r\n\t}\r\n\r\n\t/** Reads a byte as an int from 0 to 255. */\r\n\tpublic int readByteUnsigned () throws KryoException {\r\n\t\trequire(1);\r\n\t\treturn buffer[position++] & 0xFF;\r\n\t}\r\n\r\n\tpublic byte[] readBytes (int length) throws KryoException {\r\n\t\tbyte[] bytes = new byte[length];\r\n\t\treadBytes(bytes, 0, length);\r\n\t\treturn bytes;\r\n\t}\r\n\r\n\tpublic void readBytes (byte[] bytes) throws KryoException {\r\n\t\treadBytes(bytes, 0, bytes.length);\r\n\t}\r\n\r\n\tpublic void readBytes (byte[] bytes, int offset, int count) throws KryoException {\r\n\t\tif (bytes == null) throw new IllegalArgumentException(\"bytes cannot be null.\");\r\n\t\tint copyCount = Math.min(limit - position, count);\r\n\t\twhile (true) {\r\n\t\t\tSystem.arraycopy(buffer, position, bytes, offset, copyCount);\r\n\t\t\tposition += copyCount;\r\n\t\t\tcount -= copyCount;\r\n\t\t\tif (count == 0) break;\r\n\t\t\toffset += copyCount;\r\n\t\t\tcopyCount = Math.min(count, capacity);\r\n\t\t\trequire(copyCount);\r\n\t\t}\r\n\t}\r\n\r\n\t// int\r\n\r\n\t/** Reads a 4 byte int. */\r\n\tpublic int readInt () throws KryoException {\r\n\t\trequire(4);\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\treturn (buffer[position++] & 0xFF) << 24 //\r\n\t\t\t| (buffer[position++] & 0xFF) << 16 //\r\n\t\t\t| (buffer[position++] & 0xFF) << 8 //\r\n\t\t\t| buffer[position++] & 0xFF;\r\n\t}\r\n\r\n\t/** Reads a 1-5 byte int. */\r\n\tpublic int readInt (boolean optimizePositive) throws KryoException {\r\n\t\tif (require(1) < 5) return readInt_slow(optimizePositive);\r\n\t\tint b = buffer[position++];\r\n\t\tint result = b & 0x7F;\r\n\t\tif ((b & 0x80) != 0) {\r\n\t\t\tb = buffer[position++];\r\n\t\t\tresult |= (b & 0x7F) << 7;\r\n\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\tb = buffer[position++];\r\n\t\t\t\tresult |= (b & 0x7F) << 14;\r\n\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\tresult |= (b & 0x7F) << 21;\r\n\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\tresult |= (b & 0x7F) << 28;\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\treturn optimizePositive ? result : ((result >>> 1) ^ -(result & 1));\r\n\t}\r\n\r\n\tprivate int readInt_slow (boolean optimizePositive) {\r\n\t\t// The buffer is guaranteed to have at least 1 byte.\r\n\t\tint b = buffer[position++];\r\n\t\tint result = b & 0x7F;\r\n\t\tif ((b & 0x80) != 0) {\r\n\t\t\trequire(1);\r\n\t\t\tb = buffer[position++];\r\n\t\t\tresult |= (b & 0x7F) << 7;\r\n\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\trequire(1);\r\n\t\t\t\tb = buffer[position++];\r\n\t\t\t\tresult |= (b & 0x7F) << 14;\r\n\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\trequire(1);\r\n\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\tresult |= (b & 0x7F) << 21;\r\n\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\trequire(1);\r\n\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\tresult |= (b & 0x7F) << 28;\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\treturn optimizePositive ? result : ((result >>> 1) ^ -(result & 1));\r\n\t}\r\n\r\n\t/** Returns true if enough bytes are available to read an int with {@link #readInt(boolean)}. */\r\n\tpublic boolean canReadInt () throws KryoException {\r\n\t\tif (limit - position >= 5) return true;\r\n\t\tif (optional(5) <= 0) return false;\r\n\t\tint p = position;\r\n\t\tif ((buffer[p++] & 0x80) == 0) return true;\r\n\t\tif (p == limit) return false;\r\n\t\tif ((buffer[p++] & 0x80) == 0) return true;\r\n\t\tif (p == limit) return false;\r\n\t\tif ((buffer[p++] & 0x80) == 0) return true;\r\n\t\tif (p == limit) return false;\r\n\t\tif ((buffer[p++] & 0x80) == 0) return true;\r\n\t\tif (p == limit) return false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\t// string\r\n\r\n\t/** Reads the length and string of UTF8 characters, or null.\r\n\t * @return May be null. */\r\n\tpublic String readString () throws KryoException {\r\n\t\tint charCount = readInt(true);\r\n\t\tswitch (charCount) {\r\n\t\tcase 0:\r\n\t\t\treturn null;\r\n\t\tcase 1:\r\n\t\t\treturn \"\";\r\n\t\t}\r\n\t\tcharCount--;\r\n\t\tif (chars.length < charCount) chars = new char[charCount];\r\n\t\tchar[] chars = this.chars;\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\t// Try to read 8 bit chars.\r\n\t\tint charIndex = 0, b;\r\n\t\tint count = Math.min(require(1), charCount);\r\n\t\twhile (charIndex < count) {\r\n\t\t\tb = buffer[position++] & 0xFF;\r\n\t\t\tif (b > 127) {\r\n\t\t\t\tposition--;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tchars[charIndex++] = (char)b;\r\n\t\t}\r\n\t\t// If buffer couldn't hold all chars or any were not 8 bit, use slow path.\r\n\t\tif (charIndex < charCount) return readString_slow(charCount, charIndex);\r\n\t\treturn new String(chars, 0, charCount);\r\n\t}\r\n\r\n\tprivate String readString_slow (int charCount, int charIndex) {\r\n\t\tchar[] chars = this.chars;\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\twhile (charIndex < charCount) {\r\n\t\t\tif (position == limit) require(1);\r\n\t\t\tint b = buffer[position++] & 0xFF;\r\n\t\t\tswitch (b >> 4) {\r\n\t\t\tcase 0:\r\n\t\t\tcase 1:\r\n\t\t\tcase 2:\r\n\t\t\tcase 3:\r\n\t\t\tcase 4:\r\n\t\t\tcase 5:\r\n\t\t\tcase 6:\r\n\t\t\tcase 7:\r\n\t\t\t\tchars[charIndex] = (char)b;\r\n\t\t\t\tbreak;\r\n\t\t\tcase 12:\r\n\t\t\tcase 13:\r\n\t\t\t\trequire(1);\r\n\t\t\t\tchars[charIndex] = (char)((b & 0x1F) << 6 | buffer[position++] & 0x3F);\r\n\t\t\t\tbreak;\r\n\t\t\tcase 14:\r\n\t\t\t\trequire(2);\r\n\t\t\t\tchars[charIndex] = (char)((b & 0x0F) << 12 | (buffer[position++] & 0x3F) << 6 | buffer[position++] & 0x3F);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcharIndex++;\r\n\t\t}\r\n\t\treturn new String(chars, 0, charCount);\r\n\t}\r\n\r\n\t/** Reads the length and string of 8 bit characters, or null.\r\n\t * @return May be null.\r\n\t * @see Output#writeString8(String) */\r\n\tpublic String readString8 () throws KryoException {\r\n\t\tint charCount = readInt(true);\r\n\t\tswitch (charCount) {\r\n\t\tcase 0:\r\n\t\t\treturn null;\r\n\t\tcase 1:\r\n\t\t\treturn \"\";\r\n\t\t}\r\n\t\tcharCount--;\r\n\t\tif (chars.length < charCount) chars = new char[charCount];\r\n\t\tif (charCount > require(1)) return readString8_slow(charCount);\r\n\t\tchar[] chars = this.chars;\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\tfor (int charIndex = 0; charIndex < charCount;)\r\n\t\t\tchars[charIndex++] = (char)(buffer[position++] & 0xFF);\r\n\t\treturn new String(chars, 0, charCount);\r\n\t}\r\n\r\n\tprivate String readString8_slow (int charCount) {\r\n\t\tchar[] chars = this.chars;\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\tfor (int charIndex = 0; charIndex < charCount;) {\r\n\t\t\tint count = Math.min(require(1), charCount - charIndex);\r\n\t\t\tfor (int n = charIndex + count; charIndex < n; charIndex++)\r\n\t\t\t\tchars[charIndex] = (char)(buffer[position++] & 0xFF);\r\n\t\t}\r\n\t\treturn new String(chars, 0, charCount);\r\n\t}\r\n\r\n\t/** Reads a string of 7 bit characters. The remaining bit is used to denote if another character is available. The string will\r\n\t * not contain characters 0 (used for empty string) or 7F (used for null).\r\n\t * @return May be null.\r\n\t * @see Output#writeString7(String) */\r\n\tpublic String readString7 () throws KryoException {\r\n\t\tint b = readByte();\r\n\t\tswitch (b) {\r\n\t\tcase 0:\r\n\t\t\treturn \"\";\r\n\t\tcase -1:\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tchar[] chars = this.chars;\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\tint remaining = limit - position;\r\n\t\tchars[0] = (char)(b & 0x7F);\r\n\t\tint charCount = 1;\r\n\t\twhile ((b & 0x80) == 0) {\r\n\t\t\tif (remaining-- == 0 || charCount == chars.length) return readString7_slow(charCount);\r\n\t\t\tb = buffer[position++];\r\n\t\t\tchars[charCount++] = (char)(b & 0x7F);\r\n\t\t}\r\n\t\treturn new String(chars, 0, charCount);\r\n\t}\r\n\r\n\tprivate String readString7_slow (int charCount) {\r\n\t\tchar[] chars = this.chars;\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\twhile (true) {\r\n\t\t\trequire(1);\r\n\t\t\tint b = buffer[position++];\r\n\t\t\tif (charCount == chars.length) {\r\n\t\t\t\tchar[] newChars = new char[charCount * 2];\r\n\t\t\t\tSystem.arraycopy(chars, 0, newChars, 0, charCount);\r\n\t\t\t\tchars = newChars;\r\n\t\t\t\tthis.chars = newChars;\r\n\t\t\t}\r\n\t\t\tchars[charCount++] = (char)(b & 0x7F);\r\n\t\t\tif ((b & 0x80) == 0x80) break;\r\n\t\t}\r\n\t\treturn new String(chars, 0, charCount);\r\n\t}\r\n\r\n\t// float\r\n\r\n\t/** Reads a 4 byte float. */\r\n\tpublic float readFloat () throws KryoException {\r\n\t\treturn Float.intBitsToFloat(readInt());\r\n\t}\r\n\r\n\t/** Reads a 1-5 byte float with reduced precision. */\r\n\tpublic float readFloat (float precision, boolean optimizePositive) throws KryoException {\r\n\t\treturn readInt(optimizePositive) / (float)precision;\r\n\t}\r\n\r\n\t// short\r\n\r\n\t/** Reads a 2 byte short. */\r\n\tpublic short readShort () throws KryoException {\r\n\t\trequire(2);\r\n\t\treturn (short)(((buffer[position++] & 0xFF) << 8) | (buffer[position++] & 0xFF));\r\n\t}\r\n\r\n\t/** Reads a 2 byte short as an int from 0 to 65535. */\r\n\tpublic int readShortUnsigned () throws KryoException {\r\n\t\trequire(2);\r\n\t\treturn ((buffer[position++] & 0xFF) << 8) | (buffer[position++] & 0xFF);\r\n\t}\r\n\r\n\t/** Reads a 1-3 byte short. */\r\n\tpublic short readShort (boolean optimizePositive) throws KryoException {\r\n\t\tint available = require(1);\r\n\t\tbyte value = buffer[position++];\r\n\t\tif (optimizePositive) {\r\n\t\t\tif (value != -1) return (short)(value & 0xFF);\r\n\t\t} else {\r\n\t\t\tif (value != -128) return value;\r\n\t\t}\r\n\t\tif (available < 3) require(2);\r\n\t\treturn (short)(((buffer[position++] & 0xFF) << 8) | (buffer[position++] & 0xFF));\r\n\t}\r\n\r\n\t// long\r\n\r\n\t/** Reads an 8 byte long. */\r\n\tpublic long readLong () throws KryoException {\r\n\t\trequire(8);\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\treturn (long)buffer[position++] << 56 //\r\n\t\t\t| (long)(buffer[position++] & 0xFF) << 48 //\r\n\t\t\t| (long)(buffer[position++] & 0xFF) << 40 //\r\n\t\t\t| (long)(buffer[position++] & 0xFF) << 32 //\r\n\t\t\t| (long)(buffer[position++] & 0xFF) << 24 //\r\n\t\t\t| (buffer[position++] & 0xFF) << 16 //\r\n\t\t\t| (buffer[position++] & 0xFF) << 8 //\r\n\t\t\t| buffer[position++] & 0xFF;\r\n\r\n\t}\r\n\r\n\t/** Reads a 1-10 byte long. */\r\n\tpublic long readLong (boolean optimizePositive) throws KryoException {\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\tif (require(1) < 10) return readLong_slow(optimizePositive);\r\n\t\tint b = buffer[position++];\r\n\t\tlong result = b & 0x7F;\r\n\t\tif ((b & 0x80) != 0) {\r\n\t\t\tb = buffer[position++];\r\n\t\t\tresult |= (long)(b & 0x7F) << 7;\r\n\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\tb = buffer[position++];\r\n\t\t\t\tresult |= (long)(b & 0x7F) << 14;\r\n\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\tresult |= (long)(b & 0x7F) << 21;\r\n\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 28;\r\n\t\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 35;\r\n\t\t\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 42;\r\n\t\t\t\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 49;\r\n\t\t\t\t\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 56;\r\n\t\t\t\t\t\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 63;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\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\tif (!optimizePositive) result = (result >>> 1) ^ -(result & 1);\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprivate long readLong_slow (boolean optimizePositive) {\r\n\t\t// The buffer is guaranteed to have at least 1 byte.\r\n\t\tint b = buffer[position++];\r\n\t\tlong result = b & 0x7F;\r\n\t\tif ((b & 0x80) != 0) {\r\n\t\t\trequire(1);\r\n\t\t\tb = buffer[position++];\r\n\t\t\tresult |= (long)(b & 0x7F) << 7;\r\n\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\trequire(1);\r\n\t\t\t\tb = buffer[position++];\r\n\t\t\t\tresult |= (long)(b & 0x7F) << 14;\r\n\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\trequire(1);\r\n\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\tresult |= (long)(b & 0x7F) << 21;\r\n\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\trequire(1);\r\n\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 28;\r\n\t\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\t\trequire(1);\r\n\t\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 35;\r\n\t\t\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\t\t\trequire(1);\r\n\t\t\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 42;\r\n\t\t\t\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\t\t\t\trequire(1);\r\n\t\t\t\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 49;\r\n\t\t\t\t\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\t\t\t\t\trequire(1);\r\n\t\t\t\t\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 56;\r\n\t\t\t\t\t\t\t\t\t\tif ((b & 0x80) != 0) {\r\n\t\t\t\t\t\t\t\t\t\t\trequire(1);\r\n\t\t\t\t\t\t\t\t\t\t\tb = buffer[position++];\r\n\t\t\t\t\t\t\t\t\t\t\tresult |= (long)(b & 0x7F) << 63;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\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\tif (!optimizePositive) result = (result >>> 1) ^ -(result & 1);\r\n\t\treturn result;\r\n\t}\r\n\r\n\t// boolean\r\n\r\n\t/** Reads a 1 byte boolean. */\r\n\tpublic boolean readBoolean () throws KryoException {\r\n\t\trequire(1);\r\n\t\treturn buffer[position++] == 1;\r\n\t}\r\n\r\n\t// char\r\n\r\n\t/** Reads a 2 byte char. */\r\n\tpublic char readChar () throws KryoException {\r\n\t\trequire(2);\r\n\t\treturn (char)(((buffer[position++] & 0xFF) << 8) | (buffer[position++] & 0xFF));\r\n\t}\r\n\r\n\t// double\r\n\r\n\t/** Reads an 8 bytes double. */\r\n\tpublic double readDouble () throws KryoException {\r\n\t\treturn Double.longBitsToDouble(readLong());\r\n\t}\r\n\r\n\t/** Reads a 1-10 byte double with reduced precision. */\r\n\tpublic double readDouble (double precision, boolean optimizePositive) throws KryoException {\r\n\t\treturn readLong(optimizePositive) / (double)precision;\r\n\t}\r\n}\r",
"public class Output extends OutputStream {\r\n\tprivate final int maxCapacity;\r\n\tprivate int capacity, position, total;\r\n\tprivate byte[] buffer;\r\n\tprivate OutputStream outputStream;\r\n\tprivate char[] chars = new char[32];\r\n\r\n\t/** Creates a new Output for writing to a byte array.\r\n\t * @param bufferSize The initial and maximum size of the buffer. An exception is thrown if this size is exceeded. */\r\n\tpublic Output (int bufferSize) {\r\n\t\tthis(bufferSize, bufferSize);\r\n\t}\r\n\r\n\t/** Creates a new Output for writing to a byte array.\r\n\t * @param bufferSize The initial size of the buffer.\r\n\t * @param maxBufferSize The buffer is doubled as needed until it exceeds maxBufferSize and an exception is thrown. */\r\n\tpublic Output (int bufferSize, int maxBufferSize) {\r\n\t\tthis.capacity = bufferSize;\r\n\t\tthis.maxCapacity = maxBufferSize == -1 ? Integer.MAX_VALUE : maxBufferSize;\r\n\t\tbuffer = new byte[bufferSize];\r\n\t}\r\n\r\n\t/** Creates a new Output for writing to a byte array.\r\n\t * @param buffer An exception is thrown if more bytes are written than the length of this buffer. */\r\n\tpublic Output (byte[] buffer) {\r\n\t\tthis(buffer, buffer.length);\r\n\t}\r\n\r\n\t/** Creates a new Output for writing to a byte array.\r\n\t * @param maxBufferSize The buffer is doubled as needed until it exceeds maxBufferSize and an exception is thrown. */\r\n\tpublic Output (byte[] buffer, int maxBufferSize) {\r\n\t\tif (buffer == null) throw new IllegalArgumentException(\"buffer cannot be null.\");\r\n\t\tthis.buffer = buffer;\r\n\t\tthis.maxCapacity = maxBufferSize;\r\n\t\tcapacity = buffer.length;\r\n\t}\r\n\r\n\t/** Creates a new Output for writing to an OutputStream. A buffer size of 4096 is used. */\r\n\tpublic Output (OutputStream outputStream) {\r\n\t\tthis(4096, 4096);\r\n\t\tif (outputStream == null) throw new IllegalArgumentException(\"outputStream cannot be null.\");\r\n\t\tthis.outputStream = outputStream;\r\n\t}\r\n\r\n\t/** Creates a new Output for writing to an OutputStream. */\r\n\tpublic Output (OutputStream outputStream, int bufferSize) {\r\n\t\tthis(bufferSize, bufferSize);\r\n\t\tif (outputStream == null) throw new IllegalArgumentException(\"outputStream cannot be null.\");\r\n\t\tthis.outputStream = outputStream;\r\n\t}\r\n\r\n\tpublic OutputStream getOutputStream () {\r\n\t\treturn outputStream;\r\n\t}\r\n\r\n\t/** Sets a new OutputStream. The position and total are reset, discarding any buffered bytes. */\r\n\tpublic void setOutputStream (OutputStream outputStream) {\r\n\t\tif (outputStream == null) throw new IllegalArgumentException(\"outputStream cannot be null.\");\r\n\t\tthis.outputStream = outputStream;\r\n\t\tposition = 0;\r\n\t\ttotal = 0;\r\n\t}\r\n\r\n\tpublic byte[] getBuffer () {\r\n\t\treturn buffer;\r\n\t}\r\n\r\n\t/** Returns a new byte array containing the bytes currently in the buffer. */\r\n\tpublic byte[] toBytes () {\r\n\t\tbyte[] newBuffer = new byte[position];\r\n\t\tSystem.arraycopy(buffer, 0, newBuffer, 0, position);\r\n\t\treturn newBuffer;\r\n\t}\r\n\r\n\t/** Returns the current position in the buffer. This is the number of bytes that have not been flushed. */\r\n\tpublic int position () {\r\n\t\treturn position;\r\n\t}\r\n\r\n\t/** Returns the total number of bytes written. This may include bytes that have not been flushed. */\r\n\tpublic int total () {\r\n\t\treturn total + position;\r\n\t}\r\n\r\n\t/** Sets the position and total to zero. */\r\n\tpublic void clear () {\r\n\t\tposition = 0;\r\n\t\ttotal = 0;\r\n\t}\r\n\r\n\t/** @return true if the buffer has been resized. */\r\n\tprivate boolean require (int required) throws KryoException {\r\n\t\tif (capacity - position >= required) return false;\r\n\t\tif (required > maxCapacity)\r\n\t\t\tthrow new KryoException(\"Buffer overflow. Max capacity: \" + maxCapacity + \", required: \" + required);\r\n\t\tflush();\r\n\t\twhile (capacity - position < required) {\r\n\t\t\tif (capacity == maxCapacity)\r\n\t\t\t\tthrow new KryoException(\"Buffer overflow. Available: \" + (capacity - position) + \", required: \" + required);\r\n\t\t\t// Grow buffer.\r\n\t\t\tcapacity = Math.min(capacity * 2, maxCapacity);\r\n\t\t\tbyte[] newBuffer = new byte[capacity];\r\n\t\t\tSystem.arraycopy(buffer, 0, newBuffer, 0, position);\r\n\t\t\tbuffer = newBuffer;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t// OutputStream\r\n\r\n\t/** Writes the buffered bytes to the underlying OutputStream, if any. */\r\n\tpublic void flush () throws KryoException {\r\n\t\tif (outputStream == null) return;\r\n\t\ttry {\r\n\t\t\toutputStream.write(buffer, 0, position);\r\n\t\t} catch (IOException ex) {\r\n\t\t\tthrow new KryoException(ex);\r\n\t\t}\r\n\t\ttotal += position;\r\n\t\tposition = 0;\r\n\t}\r\n\r\n\t/** Flushes any buffered bytes and closes the underlying OutputStream, if any. */\r\n\tpublic void close () throws KryoException {\r\n\t\tflush();\r\n\t\tif (outputStream != null) {\r\n\t\t\ttry {\r\n\t\t\t\toutputStream.close();\r\n\t\t\t} catch (IOException ignored) {\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/** Writes a byte. */\r\n\tpublic void write (int value) throws KryoException {\r\n\t\tif (position == capacity) require(1);\r\n\t\tbuffer[position++] = (byte)value;\r\n\t}\r\n\r\n\tpublic void write (byte[] bytes) throws KryoException {\r\n\t\twriteBytes(bytes, 0, bytes.length);\r\n\t}\r\n\r\n\tpublic void write (byte[] bytes, int offset, int length) throws KryoException {\r\n\t\twriteBytes(bytes, offset, length);\r\n\t}\r\n\r\n\t// byte\r\n\r\n\tpublic void writeByte (byte value) throws KryoException {\r\n\t\tif (position == capacity) require(1);\r\n\t\tbuffer[position++] = value;\r\n\t}\r\n\r\n\tpublic void writeByte (int value) throws KryoException {\r\n\t\tif (position == capacity) require(1);\r\n\t\tbuffer[position++] = (byte)value;\r\n\t}\r\n\r\n\tpublic void writeBytes (byte[] bytes) throws KryoException {\r\n\t\twriteBytes(bytes, 0, bytes.length);\r\n\t}\r\n\r\n\tpublic void writeBytes (byte[] bytes, int offset, int count) throws KryoException {\r\n\t\tif (bytes == null) throw new IllegalArgumentException(\"bytes cannot be null.\");\r\n\t\tint copyCount = Math.min(capacity - position, count);\r\n\t\twhile (true) {\r\n\t\t\tSystem.arraycopy(bytes, offset, buffer, position, copyCount);\r\n\t\t\tposition += copyCount;\r\n\t\t\tcount -= copyCount;\r\n\t\t\tif (count == 0) return;\r\n\t\t\toffset += copyCount;\r\n\t\t\tcopyCount = Math.min(capacity, count);\r\n\t\t\trequire(copyCount);\r\n\t\t}\r\n\t}\r\n\r\n\t// int\r\n\r\n\t/** Writes a 4 byte int. */\r\n\tpublic void writeInt (int value) throws KryoException {\r\n\t\trequire(4);\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\tbuffer[position++] = (byte)(value >> 24);\r\n\t\tbuffer[position++] = (byte)(value >> 16);\r\n\t\tbuffer[position++] = (byte)(value >> 8);\r\n\t\tbuffer[position++] = (byte)value;\r\n\t}\r\n\r\n\t/** Writes a 1-5 byte int.\r\n\t * @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be\r\n\t * inefficient (5 bytes). */\r\n\tpublic int writeInt (int value, boolean optimizePositive) throws KryoException {\r\n\t\tif (!optimizePositive) value = (value << 1) ^ (value >> 31);\r\n\t\tint length;\r\n\t\tif ((value & ~0x7F) == 0)\r\n\t\t\tlength = 1;\r\n\t\telse if ((value >>> 7 & ~0x7F) == 0)\r\n\t\t\tlength = 2;\r\n\t\telse if ((value >>> 14 & ~0x7F) == 0)\r\n\t\t\tlength = 3;\r\n\t\telse if ((value >>> 21 & ~0x7F) == 0)\r\n\t\t\tlength = 4;\r\n\t\telse\r\n\t\t\tlength = 5;\r\n\t\trequire(length);\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\tswitch (length) {\r\n\t\tcase 5:\r\n\t\t\tbuffer[position++] = (byte)((value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 4:\r\n\t\t\tbuffer[position++] = (byte)((value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 3:\r\n\t\t\tbuffer[position++] = (byte)((value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 2:\r\n\t\t\tbuffer[position++] = (byte)((value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 1:\r\n\t\t\tbuffer[position++] = (byte)value;\r\n\t\t}\r\n\t\treturn length;\r\n\t}\r\n\r\n\t// string\r\n\r\n\t/** Writes the length and string using UTF8, or null.\r\n\t * @param value May be null. */\r\n\tpublic void writeString (String value) throws KryoException {\r\n\t\tif (value == null) {\r\n\t\t\twriteByte(0);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tint charCount = value.length();\r\n\t\tif (chars.length < charCount) chars = new char[charCount];\r\n\t\tchar[] chars = this.chars;\r\n\t\tvalue.getChars(0, charCount, chars, 0);\r\n\t\twriteInt(charCount + 1, true);\r\n\t\tint charIndex = 0;\r\n\t\tif (capacity - position >= charCount) {\r\n\t\t\t// Try to write 8 bit chars.\r\n\t\t\tfor (; charIndex < charCount; charIndex++) {\r\n\t\t\t\tint c = chars[charIndex];\r\n\t\t\t\tif (c > 127) break;\r\n\t\t\t\tbuffer[position++] = (byte)c;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (charIndex < charCount) writeString_slow(charCount, charIndex);\r\n\t}\r\n\r\n\tprivate void writeString_slow (int charCount, int charIndex) {\r\n\t\tchar[] chars = this.chars;\r\n\t\tfor (; charIndex < charCount; charIndex++) {\r\n\t\t\tif (position == capacity) require(Math.min(capacity, charCount - charIndex));\r\n\t\t\tint c = chars[charIndex];\r\n\t\t\tif (c <= 0x007F) {\r\n\t\t\t\tbuffer[position++] = (byte)c;\r\n\t\t\t} else if (c > 0x07FF) {\r\n\t\t\t\tbuffer[position++] = (byte)(0xE0 | c >> 12 & 0x0F);\r\n\t\t\t\trequire(2);\r\n\t\t\t\tbuffer[position++] = (byte)(0x80 | c >> 6 & 0x3F);\r\n\t\t\t\tbuffer[position++] = (byte)(0x80 | c & 0x3F);\r\n\t\t\t} else {\r\n\t\t\t\tbuffer[position++] = (byte)(0xC0 | c >> 6 & 0x1F);\r\n\t\t\t\trequire(1);\r\n\t\t\t\tbuffer[position++] = (byte)(0x80 | c & 0x3F);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/** Writes the length and string using 8 bits per character, or null. This is slightly less space efficient and very slightly\r\n\t * faster than {@link #writeString7(String)}.\r\n\t * @param value May be null. */\r\n\tpublic void writeString8 (String value) throws KryoException {\r\n\t\tif (value == null) {\r\n\t\t\twriteByte(0);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tint charCount = value.length();\r\n\t\twriteInt(charCount + 1, true);\r\n\t\tif (capacity - position < charCount)\r\n\t\t\twriteString8_slow(value, charCount);\r\n\t\telse {\r\n\t\t\tvalue.getBytes(0, charCount, buffer, position);\r\n\t\t\tposition += charCount;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void writeString8_slow (String value, int charCount) throws KryoException {\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\tint charsToWrite = capacity - position;\r\n\t\tint charIndex = 0;\r\n\t\twhile (charIndex < charCount) {\r\n\t\t\tvalue.getBytes(charIndex, charIndex + charsToWrite, buffer, position);\r\n\t\t\tcharIndex += charsToWrite;\r\n\t\t\tposition += charsToWrite;\r\n\t\t\tcharsToWrite = Math.min(charCount - charIndex, capacity);\r\n\t\t\tif (require(charsToWrite)) buffer = this.buffer;\r\n\t\t}\r\n\t}\r\n\r\n\t/** Writes the string using 7 bits per character. The remaining bit is used to denote if another character is available. The\r\n\t * string must not contain characters 0 (used for empty string) or 7F (used for null). This is slightly more space efficient\r\n\t * and very slightly slower than {@link #writeString8(String)}.\r\n\t * @param value May be null. */\r\n\tpublic void writeString7 (String value) throws KryoException {\r\n\t\tif (value == null) {\r\n\t\t\twriteByte(-1);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tint charCount = value.length();\r\n\t\tif (charCount == 0) {\r\n\t\t\twriteByte(0);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (capacity - position < charCount)\r\n\t\t\twriteString7_slow(value, charCount);\r\n\t\telse {\r\n\t\t\tvalue.getBytes(0, charCount, buffer, position);\r\n\t\t\tposition += charCount;\r\n\t\t\tbuffer[position - 1] |= 0x80;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void writeString7_slow (String value, int charCount) throws KryoException {\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\tint charsToWrite = capacity - position;\r\n\t\tint charIndex = 0;\r\n\t\tcharCount--;\r\n\t\twhile (charIndex < charCount) {\r\n\t\t\tvalue.getBytes(charIndex, charIndex + charsToWrite, buffer, position);\r\n\t\t\tcharIndex += charsToWrite;\r\n\t\t\tposition += charsToWrite;\r\n\t\t\tcharsToWrite = Math.min(charCount - charIndex, capacity);\r\n\t\t\tif (require(charsToWrite)) buffer = this.buffer;\r\n\t\t}\r\n\t\twriteByte(value.charAt(charCount) | 0x80);\r\n\t}\r\n\r\n\t// float\r\n\r\n\t/** Writes a 4 byte float. */\r\n\tpublic void writeFloat (float value) throws KryoException {\r\n\t\twriteInt(Float.floatToIntBits(value));\r\n\t}\r\n\r\n\t/** Writes a 1-5 byte float with reduced precision.\r\n\t * @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be\r\n\t * inefficient (5 bytes). */\r\n\tpublic int writeFloat (float value, float precision, boolean optimizePositive) throws KryoException {\r\n\t\treturn writeInt((int)(value * precision), optimizePositive);\r\n\t}\r\n\r\n\t// short\r\n\r\n\t/** Writes a 2 byte short. */\r\n\tpublic void writeShort (int value) throws KryoException {\r\n\t\trequire(2);\r\n\t\tbuffer[position++] = (byte)(value >>> 8);\r\n\t\tbuffer[position++] = (byte)value;\r\n\t}\r\n\r\n\t/** Writes a 1-3 byte short.\r\n\t * @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be\r\n\t * inefficient (3 bytes). */\r\n\tpublic int writeShort (int value, boolean optimizePositive) throws KryoException {\r\n\t\tif (optimizePositive) {\r\n\t\t\tif (value >= 0 && value <= 254) {\r\n\t\t\t\trequire(1);\r\n\t\t\t\tbuffer[position++] = (byte)value;\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t\trequire(3);\r\n\t\t\tbuffer[position++] = -1; // short positive\r\n\t\t} else {\r\n\t\t\tif (value >= -127 && value <= 127) {\r\n\t\t\t\trequire(1);\r\n\t\t\t\tbuffer[position++] = (byte)value;\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t\trequire(3);\r\n\t\t\tbuffer[position++] = -128; // short\r\n\t\t}\r\n\t\tbuffer[position++] = (byte)(value >>> 8);\r\n\t\tbuffer[position++] = (byte)value;\r\n\t\treturn 3;\r\n\t}\r\n\r\n\t// long\r\n\r\n\t/** Writes an 8 byte long. */\r\n\tpublic void writeLong (long value) throws KryoException {\r\n\t\trequire(8);\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\tbuffer[position++] = (byte)(value >>> 56);\r\n\t\tbuffer[position++] = (byte)(value >>> 48);\r\n\t\tbuffer[position++] = (byte)(value >>> 40);\r\n\t\tbuffer[position++] = (byte)(value >>> 32);\r\n\t\tbuffer[position++] = (byte)(value >>> 24);\r\n\t\tbuffer[position++] = (byte)(value >>> 16);\r\n\t\tbuffer[position++] = (byte)(value >>> 8);\r\n\t\tbuffer[position++] = (byte)value;\r\n\t}\r\n\r\n\t/** Writes a 1-10 byte long.\r\n\t * @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be\r\n\t * inefficient (10 bytes). */\r\n\tpublic int writeLong (long value, boolean optimizePositive) throws KryoException {\r\n\t\tif (!optimizePositive) value = (value << 1) ^ (value >> 63);\r\n\t\tint length;\r\n\t\tif ((value & ~0x7Fl) == 0)\r\n\t\t\tlength = 1;\r\n\t\telse if ((value >>> 7 & ~0x7Fl) == 0)\r\n\t\t\tlength = 2;\r\n\t\telse if ((value >>> 14 & ~0x7Fl) == 0)\r\n\t\t\tlength = 3;\r\n\t\telse if ((value >>> 21 & ~0x7Fl) == 0)\r\n\t\t\tlength = 4;\r\n\t\telse if ((value >>> 28 & ~0x7Fl) == 0)\r\n\t\t\tlength = 5;\r\n\t\telse if ((value >>> 35 & ~0x7Fl) == 0)\r\n\t\t\tlength = 6;\r\n\t\telse if ((value >>> 42 & ~0x7Fl) == 0)\r\n\t\t\tlength = 7;\r\n\t\telse if ((value >>> 49 & ~0x7Fl) == 0)\r\n\t\t\tlength = 8;\r\n\t\telse if ((value >>> 56 & ~0x7Fl) == 0)\r\n\t\t\tlength = 9;\r\n\t\telse\r\n\t\t\tlength = 10;\r\n\t\trequire(length);\r\n\t\tbyte[] buffer = this.buffer;\r\n\t\tswitch (length) {\r\n\t\tcase 10:\r\n\t\t\tbuffer[position++] = (byte)(((int)value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 9:\r\n\t\t\tbuffer[position++] = (byte)(((int)value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 8:\r\n\t\t\tbuffer[position++] = (byte)(((int)value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 7:\r\n\t\t\tbuffer[position++] = (byte)(((int)value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 6:\r\n\t\t\tbuffer[position++] = (byte)(((int)value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 5:\r\n\t\t\tbuffer[position++] = (byte)(((int)value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 4:\r\n\t\t\tbuffer[position++] = (byte)(((int)value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 3:\r\n\t\t\tbuffer[position++] = (byte)(((int)value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 2:\r\n\t\t\tbuffer[position++] = (byte)(((int)value & 0x7F) | 0x80);\r\n\t\t\tvalue >>>= 7;\r\n\t\tcase 1:\r\n\t\t\tbuffer[position++] = (byte)value;\r\n\t\t}\r\n\t\treturn length;\r\n\t}\r\n\r\n\t// boolean\r\n\r\n\t/** Writes a 1 byte boolean. */\r\n\tpublic void writeBoolean (boolean value) throws KryoException {\r\n\t\trequire(1);\r\n\t\tbuffer[position++] = (byte)(value ? 1 : 0);\r\n\t}\r\n\r\n\t// char\r\n\r\n\t/** Writes a 2 byte char. */\r\n\tpublic void writeChar (char value) throws KryoException {\r\n\t\trequire(2);\r\n\t\tbuffer[position++] = (byte)(value >>> 8);\r\n\t\tbuffer[position++] = (byte)value;\r\n\t}\r\n\r\n\t// double\r\n\r\n\t/** Writes an 8 byte double. */\r\n\tpublic void writeDouble (double value) throws KryoException {\r\n\t\twriteLong(Double.doubleToLongBits(value));\r\n\t}\r\n\r\n\t/** Writes a 1-10 byte double with reduced precision.\r\n\t * @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be\r\n\t * inefficient (10 bytes). */\r\n\tpublic int writeDouble (double value, double precision, boolean optimizePositive) throws KryoException {\r\n\t\treturn writeLong((long)(value * precision), optimizePositive);\r\n\t}\r\n}\r"
] | import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.KryoSerializable;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
|
package com.esotericsoftware.kryo.serializers;
/** Serializes objects using Java's built in serialization mechanism. Note that this is very inefficient and should be avoided if
* possible.
* @see Serializer
* @see FieldSerializer
* @see KryoSerializable
* @author Nathan Sweet <[email protected]> */
public class JavaSerializer extends Serializer {
private ObjectOutputStream objectStream;
private Output lastOutput;
public void write (Kryo kryo, Output output, Object object) {
try {
if (output != lastOutput) {
objectStream = new ObjectOutputStream(output);
lastOutput = output;
} else
objectStream.reset();
objectStream.writeObject(object);
objectStream.flush();
} catch (Exception ex) {
throw new KryoException("Error during Java serialization.", ex);
}
}
| public Object create (Kryo kryo, Input input, Class type) {
| 3 |
paoding-code/jade-plugin-sql | src/main/java/net/paoding/rose/jade/plugin/sql/PlumSQLInterpreter.java | [
"public interface IDialect {\n\n\t/**\n\t * 将指定的操作转换为目标数据库的查询语句\n\t * @param operation 操作映射对象\n\t * @param runtime Statement运行时\n\t * \n\t * @return 查询语句\n\t * \n\t * @see IOperationMapper\n\t * @see StatementRuntime\n\t */\n\tpublic <T extends IOperationMapper> String translate(T operation, StatementRuntime runtime);\n}",
"public class MySQLDialect implements IDialect {\n\t\n\tprivate Map<String, ISQLGenerator<? extends IOperationMapper>> generators;\n\t\n\tpublic MySQLDialect() {\n\t\tgenerators = new HashMap<String, ISQLGenerator<? extends IOperationMapper>>();\n\t\tgenerators.put(IOperationMapper.OPERATION_SELECT, new SelectGenerator());\n\t\tgenerators.put(IOperationMapper.OPERATION_INSERT, new InsertGenerator());\n\t\tgenerators.put(IOperationMapper.OPERATION_UPDATE, new UpdateGenerator());\n\t\tgenerators.put(IOperationMapper.OPERATION_DELETE, new DeleteGenerator());\n\t}\n\n\t/* (non-Javadoc)\n\t * @see com.cainiao.depot.project.biz.common.jade.dialect.IDialect#translate(com.cainiao.depot.project.biz.common.jade.mapper.IOperationMapper)\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic <T extends IOperationMapper> String translate(T operation, StatementRuntime runtime) {\n\t\tISQLGenerator<T> gen = (ISQLGenerator<T>) generators.get(operation.getName());\n\t\tif(gen != null) {\n\t\t\treturn gen.generate(operation, runtime);\n\t\t}\n\t\treturn null;\n\t}\n\n}",
"public class EntityMapperManager extends AbstractCachedMapperManager<Class<?>, IEntityMapper> {\n\t\n\tpublic IEntityMapper create(Class<?> clazz) {\n\t\tIEntityMapper entityMapper = new EntityMapper(clazz);\n\t\tentityMapper.map();\n\t\treturn entityMapper;\n\t}\n\n}",
"public interface IOperationMapper extends IMapper<StatementMetaData> {\n\t\n\tpublic static final String OPERATION_SELECT = \"SELECT\";\n\tpublic static final String OPERATION_INSERT = \"INSERT\";\n\tpublic static final String OPERATION_DELETE = \"DELETE\";\n\tpublic static final String OPERATION_UPDATE = \"UPDATE\";\n\t\n\tstatic final String[] OPERATION_KEYS = {\n\t\tOPERATION_SELECT,\n\t\tOPERATION_INSERT,\n\t\tOPERATION_DELETE,\n\t\tOPERATION_UPDATE\n\t};\n\t\n\tstatic final String OPERATION_PREFIX[][] = {\n\t\t/* [0][] = SELECT */ {\"get\", \"find\", \"query\", \"count\"},\n\t\t/* [1][] = INSERT */ {\"save\", \"insert\"},\n\t\t/* [2][] = DELETE */ {\"delete\", \"remove\"},\n\t\t/* [3][] = UPDATE */ {\"update\", \"modify\"}\n\t};\n\t\n\tIEntityMapper getTargetEntityMapper();\n\t\n\tList<IParameterMapper> getParameters();\n\t\n\tboolean containsParameter();\n\t\n\tvoid setEntityMapperManager(EntityMapperManager entityMapperManager);\n\t\n\tboolean isIgnoreNull();\n\t\n\tIgnoreNull getIgnoreNull();\n\t\n}",
"public class OperationMapperManager extends AbstractCachedMapperManager<StatementMetaData, IOperationMapper> {\n\t\n\tprivate EntityMapperManager entityMapperManager;\n\t\n\tprivate static final String[] INSERT_PREFIX = IOperationMapper.OPERATION_PREFIX[1];\n\n\t@Override\n\tpublic IOperationMapper create(StatementMetaData source) {\n\t\tIOperationMapper mapper = null;\n\t\t\n\t\tif(isInsert(source.getMethod())) {\n\t\t\tmapper = new OperationMapper(source);\n\t\t} else {\n\t\t\tmapper = new ConditionalOperationMapper(source);\n\t\t}\n\t\t\n\t\tmapper.setEntityMapperManager(entityMapperManager);\n\t\tmapper.map();\n\t\treturn mapper;\n\t}\n\t\n\tprivate boolean isInsert(Method method) {\n\t\tfor(String prefix : INSERT_PREFIX) {\n\t\t\tif(method.getName().startsWith(prefix)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic void setEntityMapperManager(EntityMapperManager entityMapperManager) {\n\t\tthis.entityMapperManager = entityMapperManager;\n\t}\n\n}",
"public class BasicSQLFormatter {\n\n\tprivate static final Set<String> BEGIN_CLAUSES = new HashSet<String>();\n\tprivate static final Set<String> END_CLAUSES = new HashSet<String>();\n\tprivate static final Set<String> LOGICAL = new HashSet<String>();\n\tprivate static final Set<String> QUANTIFIERS = new HashSet<String>();\n\tprivate static final Set<String> DML = new HashSet<String>();\n\tprivate static final Set<String> MISC = new HashSet<String>();\n\t\n\tpublic static final String WHITESPACE = \" \\n\\r\\f\\t\";\n\n\tstatic {\n\t\tBEGIN_CLAUSES.add( \"left\" );\n\t\tBEGIN_CLAUSES.add( \"right\" );\n\t\tBEGIN_CLAUSES.add( \"inner\" );\n\t\tBEGIN_CLAUSES.add( \"outer\" );\n\t\tBEGIN_CLAUSES.add( \"group\" );\n\t\tBEGIN_CLAUSES.add( \"order\" );\n\n\t\tEND_CLAUSES.add( \"where\" );\n\t\tEND_CLAUSES.add( \"set\" );\n\t\tEND_CLAUSES.add( \"having\" );\n\t\tEND_CLAUSES.add( \"join\" );\n\t\tEND_CLAUSES.add( \"from\" );\n\t\tEND_CLAUSES.add( \"by\" );\n\t\tEND_CLAUSES.add( \"join\" );\n\t\tEND_CLAUSES.add( \"into\" );\n\t\tEND_CLAUSES.add( \"union\" );\n\n\t\tLOGICAL.add( \"and\" );\n\t\tLOGICAL.add( \"or\" );\n\t\tLOGICAL.add( \"when\" );\n\t\tLOGICAL.add( \"else\" );\n\t\tLOGICAL.add( \"end\" );\n\n\t\tQUANTIFIERS.add( \"in\" );\n\t\tQUANTIFIERS.add( \"all\" );\n\t\tQUANTIFIERS.add( \"exists\" );\n\t\tQUANTIFIERS.add( \"some\" );\n\t\tQUANTIFIERS.add( \"any\" );\n\n\t\tDML.add( \"insert\" );\n\t\tDML.add( \"update\" );\n\t\tDML.add( \"delete\" );\n\n\t\tMISC.add( \"select\" );\n\t\tMISC.add( \"on\" );\n\t}\n\n\tstatic final String indentString = \" \";\n\tstatic final String initial = \"\\n \";\n\n\tpublic String format(String source) {\n\t\treturn new FormatProcess( source ).perform();\n\t}\n\n\tprivate static class FormatProcess {\n\t\tboolean beginLine = true;\n\t\tboolean afterBeginBeforeEnd = false;\n\t\tboolean afterByOrSetOrFromOrSelect = false;\n\t\tboolean afterOn = false;\n\t\tboolean afterBetween = false;\n\t\tboolean afterInsert = false;\n\t\tint inFunction = 0;\n\t\tint parensSinceSelect = 0;\n\t\tprivate LinkedList<Integer> parenCounts = new LinkedList<Integer>();\n\t\tprivate LinkedList<Boolean> afterByOrFromOrSelects = new LinkedList<Boolean>();\n\n\t\tint indent = 1;\n\n\t\tStringBuffer result = new StringBuffer();\n\t\tStringTokenizer tokens;\n\t\tString lastToken;\n\t\tString token;\n\t\tString lcToken;\n\n\t\tpublic FormatProcess(String sql) {\n\t\t\ttokens = new StringTokenizer(\n\t\t\t\t\tsql,\n\t\t\t\t\t\"()+*/-=<>'`\\\"[],\" + WHITESPACE,\n\t\t\t\t\ttrue\n\t\t\t);\n\t\t}\n\n\t\tpublic String perform() {\n\n\t\t\tresult.append( initial );\n\n\t\t\twhile ( tokens.hasMoreTokens() ) {\n\t\t\t\ttoken = tokens.nextToken();\n\t\t\t\tlcToken = token.toLowerCase();\n\n\t\t\t\tif ( \"'\".equals( token ) ) {\n\t\t\t\t\tString t;\n\t\t\t\t\tdo {\n\t\t\t\t\t\tt = tokens.nextToken();\n\t\t\t\t\t\ttoken += t;\n\t\t\t\t\t}\n\t\t\t\t\twhile ( !\"'\".equals( t ) && tokens.hasMoreTokens() ); // cannot handle single quotes\n\t\t\t\t}\n\t\t\t\telse if ( \"\\\"\".equals( token ) ) {\n\t\t\t\t\tString t;\n\t\t\t\t\tdo {\n\t\t\t\t\t\tt = tokens.nextToken();\n\t\t\t\t\t\ttoken += t;\n\t\t\t\t\t}\n\t\t\t\t\twhile ( !\"\\\"\".equals( t ) );\n\t\t\t\t}\n\n\t\t\t\tif ( afterByOrSetOrFromOrSelect && \",\".equals( token ) ) {\n\t\t\t\t\tcommaAfterByOrFromOrSelect();\n\t\t\t\t}\n\t\t\t\telse if ( afterOn && \",\".equals( token ) ) {\n\t\t\t\t\tcommaAfterOn();\n\t\t\t\t}\n\n\t\t\t\telse if ( \"(\".equals( token ) ) {\n\t\t\t\t\topenParen();\n\t\t\t\t}\n\t\t\t\telse if ( \")\".equals( token ) ) {\n\t\t\t\t\tcloseParen();\n\t\t\t\t}\n\n\t\t\t\telse if ( BEGIN_CLAUSES.contains( lcToken ) ) {\n\t\t\t\t\tbeginNewClause();\n\t\t\t\t}\n\n\t\t\t\telse if ( END_CLAUSES.contains( lcToken ) ) {\n\t\t\t\t\tendNewClause();\n\t\t\t\t}\n\n\t\t\t\telse if ( \"select\".equals( lcToken ) ) {\n\t\t\t\t\tselect();\n\t\t\t\t}\n\n\t\t\t\telse if ( DML.contains( lcToken ) ) {\n\t\t\t\t\tupdateOrInsertOrDelete();\n\t\t\t\t}\n\n\t\t\t\telse if ( \"values\".equals( lcToken ) ) {\n\t\t\t\t\tvalues();\n\t\t\t\t}\n\n\t\t\t\telse if ( \"on\".equals( lcToken ) ) {\n\t\t\t\t\ton();\n\t\t\t\t}\n\n\t\t\t\telse if ( afterBetween && lcToken.equals( \"and\" ) ) {\n\t\t\t\t\tmisc();\n\t\t\t\t\tafterBetween = false;\n\t\t\t\t}\n\n\t\t\t\telse if ( LOGICAL.contains( lcToken ) ) {\n\t\t\t\t\tlogical();\n\t\t\t\t}\n\n\t\t\t\telse if ( isWhitespace( token ) ) {\n\t\t\t\t\twhite();\n\t\t\t\t}\n\n\t\t\t\telse {\n\t\t\t\t\tmisc();\n\t\t\t\t}\n\n\t\t\t\tif ( !isWhitespace( token ) ) {\n\t\t\t\t\tlastToken = lcToken;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn result.toString();\n\t\t}\n\n\t\tprivate void commaAfterOn() {\n\t\t\tout();\n\t\t\tindent--;\n\t\t\tnewline();\n\t\t\tafterOn = false;\n\t\t\tafterByOrSetOrFromOrSelect = true;\n\t\t}\n\n\t\tprivate void commaAfterByOrFromOrSelect() {\n\t\t\tout();\n\t\t\tnewline();\n\t\t}\n\n\t\tprivate void logical() {\n\t\t\tif ( \"end\".equals( lcToken ) ) {\n\t\t\t\tindent--;\n\t\t\t}\n\t\t\tnewline();\n\t\t\tout();\n\t\t\tbeginLine = false;\n\t\t}\n\n\t\tprivate void on() {\n\t\t\tindent++;\n\t\t\tafterOn = true;\n\t\t\tnewline();\n\t\t\tout();\n\t\t\tbeginLine = false;\n\t\t}\n\n\t\tprivate void misc() {\n\t\t\tout();\n\t\t\tif ( \"between\".equals( lcToken ) ) {\n\t\t\t\tafterBetween = true;\n\t\t\t}\n\t\t\tif ( afterInsert ) {\n\t\t\t\tnewline();\n\t\t\t\tafterInsert = false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbeginLine = false;\n\t\t\t\tif ( \"case\".equals( lcToken ) ) {\n\t\t\t\t\tindent++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprivate void white() {\n\t\t\tif ( !beginLine ) {\n\t\t\t\tresult.append( \" \" );\n\t\t\t}\n\t\t}\n\n\t\tprivate void updateOrInsertOrDelete() {\n\t\t\tout();\n\t\t\tindent++;\n\t\t\tbeginLine = false;\n\t\t\tif ( \"update\".equals( lcToken ) ) {\n\t\t\t\tnewline();\n\t\t\t}\n\t\t\tif ( \"insert\".equals( lcToken ) ) {\n\t\t\t\tafterInsert = true;\n\t\t\t}\n\t\t}\n\n\t\tprivate void select() {\n\t\t\tout();\n\t\t\tindent++;\n\t\t\tnewline();\n\t\t\tparenCounts.addLast( new Integer( parensSinceSelect ) );\n\t\t\tafterByOrFromOrSelects.addLast( Boolean.valueOf( afterByOrSetOrFromOrSelect ) );\n\t\t\tparensSinceSelect = 0;\n\t\t\tafterByOrSetOrFromOrSelect = true;\n\t\t}\n\n\t\tprivate void out() {\n\t\t\tresult.append( token );\n\t\t}\n\n\t\tprivate void endNewClause() {\n\t\t\tif ( !afterBeginBeforeEnd ) {\n\t\t\t\tindent--;\n\t\t\t\tif ( afterOn ) {\n\t\t\t\t\tindent--;\n\t\t\t\t\tafterOn = false;\n\t\t\t\t}\n\t\t\t\tnewline();\n\t\t\t}\n\t\t\tout();\n\t\t\tif ( !\"union\".equals( lcToken ) ) {\n\t\t\t\tindent++;\n\t\t\t}\n\t\t\tnewline();\n\t\t\tafterBeginBeforeEnd = false;\n\t\t\tafterByOrSetOrFromOrSelect = \"by\".equals( lcToken )\n\t\t\t\t\t|| \"set\".equals( lcToken )\n\t\t\t\t\t|| \"from\".equals( lcToken );\n\t\t}\n\n\t\tprivate void beginNewClause() {\n\t\t\tif ( !afterBeginBeforeEnd ) {\n\t\t\t\tif ( afterOn ) {\n\t\t\t\t\tindent--;\n\t\t\t\t\tafterOn = false;\n\t\t\t\t}\n\t\t\t\tindent--;\n\t\t\t\tnewline();\n\t\t\t}\n\t\t\tout();\n\t\t\tbeginLine = false;\n\t\t\tafterBeginBeforeEnd = true;\n\t\t}\n\n\t\tprivate void values() {\n\t\t\tindent--;\n\t\t\tnewline();\n\t\t\tout();\n\t\t\tindent++;\n\t\t\tnewline();\n\t\t}\n\n\t\tprivate void closeParen() {\n\t\t\tparensSinceSelect--;\n\t\t\tif ( parensSinceSelect < 0 ) {\n\t\t\t\tindent--;\n\t\t\t\tparensSinceSelect = ( ( Integer ) parenCounts.removeLast() ).intValue();\n\t\t\t\tafterByOrSetOrFromOrSelect = ( ( Boolean ) afterByOrFromOrSelects.removeLast() ).booleanValue();\n\t\t\t}\n\t\t\tif ( inFunction > 0 ) {\n\t\t\t\tinFunction--;\n\t\t\t\tout();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif ( !afterByOrSetOrFromOrSelect ) {\n\t\t\t\t\tindent--;\n\t\t\t\t\tnewline();\n\t\t\t\t}\n\t\t\t\tout();\n\t\t\t}\n\t\t\tbeginLine = false;\n\t\t}\n\n\t\tprivate void openParen() {\n\t\t\tif ( isFunctionName( lastToken ) || inFunction > 0 ) {\n\t\t\t\tinFunction++;\n\t\t\t}\n\t\t\tbeginLine = false;\n\t\t\tif ( inFunction > 0 ) {\n\t\t\t\tout();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tout();\n\t\t\t\tif ( !afterByOrSetOrFromOrSelect ) {\n\t\t\t\t\tindent++;\n\t\t\t\t\tnewline();\n\t\t\t\t\tbeginLine = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tparensSinceSelect++;\n\t\t}\n\n\t\tprivate static boolean isFunctionName(String tok) {\n\t\t\tfinal char begin = tok.charAt( 0 );\n\t\t\tfinal boolean isIdentifier = Character.isJavaIdentifierStart( begin ) || '\"' == begin;\n\t\t\treturn isIdentifier &&\n\t\t\t\t\t!LOGICAL.contains( tok ) &&\n\t\t\t\t\t!END_CLAUSES.contains( tok ) &&\n\t\t\t\t\t!QUANTIFIERS.contains( tok ) &&\n\t\t\t\t\t!DML.contains( tok ) &&\n\t\t\t\t\t!MISC.contains( tok );\n\t\t}\n\n\t\tprivate static boolean isWhitespace(String token) {\n\t\t\treturn WHITESPACE.indexOf( token ) >= 0;\n\t\t}\n\n\t\tprivate void newline() {\n\t\t\tresult.append( \"\\n\" );\n\t\t\tfor ( int i = 0; i < indent; i++ ) {\n\t\t\t\tresult.append( indentString );\n\t\t\t}\n\t\t\tbeginLine = true;\n\t\t}\n\t}\n\n}",
"public class PlumUtils {\n\n /**\n * Null-safe check if the specified collection is empty.\n * <p>\n * Null returns true.\n *\n * @param coll the collection to check, may be null\n * @return true if empty or null\n */\n public static boolean isEmpty(final Collection<?> coll) {\n return coll == null || coll.isEmpty();\n }\n\n /**\n * Null-safe check if the specified collection is not empty.\n * <p>\n * Null returns false.\n *\n * \n * @param coll the collection to check, may be null\n * @return true if non-null and non-empty\n */\n public static boolean isNotEmpty(final Collection<?> coll) {\n return !isEmpty(coll);\n }\n\n /**\n * <p>Checks if a String is whitespace, empty (\"\") or null.</p>\n *\n * <pre>\n * StringUtils.isBlank(null) = true\n * StringUtils.isBlank(\"\") = true\n * StringUtils.isBlank(\" \") = true\n * StringUtils.isBlank(\"bob\") = false\n * StringUtils.isBlank(\" bob \") = false\n * </pre>\n *\n * @param str the String to check, may be null\n * @return <code>true</code> if the String is null, empty or whitespace\n * @since 2.0\n */\n public static boolean isBlank(String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if ((Character.isWhitespace(str.charAt(i)) == false)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * <p>Checks if a String is not empty (\"\"), not null and not whitespace only.</p>\n *\n * <pre>\n * StringUtils.isNotBlank(null) = false\n * StringUtils.isNotBlank(\"\") = false\n * StringUtils.isNotBlank(\" \") = false\n * StringUtils.isNotBlank(\"bob\") = true\n * StringUtils.isNotBlank(\" bob \") = true\n * </pre>\n *\n * @param str the String to check, may be null\n * @return <code>true</code> if the String is\n * not empty and not null and not whitespace\n * @since 2.0\n */\n public static boolean isNotBlank(String str) {\n return !StringUtils.isBlank(str);\n }\n\n}"
] | import java.util.Arrays;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.Order;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import net.paoding.rose.jade.annotation.SQL;
import net.paoding.rose.jade.plugin.sql.annotations.Table;
import net.paoding.rose.jade.plugin.sql.dialect.IDialect;
import net.paoding.rose.jade.plugin.sql.dialect.MySQLDialect;
import net.paoding.rose.jade.plugin.sql.mapper.EntityMapperManager;
import net.paoding.rose.jade.plugin.sql.mapper.IOperationMapper;
import net.paoding.rose.jade.plugin.sql.mapper.OperationMapperManager;
import net.paoding.rose.jade.plugin.sql.util.BasicSQLFormatter;
import net.paoding.rose.jade.plugin.sql.util.PlumUtils;
import net.paoding.rose.jade.statement.DAOMetaData;
import net.paoding.rose.jade.statement.Interpreter;
import net.paoding.rose.jade.statement.StatementMetaData;
import net.paoding.rose.jade.statement.StatementRuntime; | /**
*
*/
package net.paoding.rose.jade.plugin.sql;
/**
* Plum插件用于生成SQL的拦截器。
*
* @author Alan.Geng[[email protected]]
*/
@Order(-1)
public class PlumSQLInterpreter implements Interpreter, InitializingBean, ApplicationContextAware {
private static final Log logger = LogFactory.getLog(PlumSQLInterpreter.class);
private ApplicationContext applicationContext;
private OperationMapperManager operationMapperManager;
private IDialect dialect;
public void setDialect(IDialect dialect) {
this.dialect = dialect;
}
public void setOperationMapperManager(OperationMapperManager operationMapperManager) {
this.operationMapperManager = operationMapperManager;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
if (operationMapperManager == null) {
operationMapperManager = new OperationMapperManager();
operationMapperManager.setEntityMapperManager(new EntityMapperManager());
}
if (dialect == null) {
// 将来可能扩展点:不同的DAO可以有不同的Dialect哦,而且是自动知道,不需要外部设置。
dialect = new MySQLDialect();
}
//
if (logger.isInfoEnabled()) {
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(//
applicationContext, GenericDAO.class);
logger.info("[jade-plugin-sql] found " + beanNames.length + " GenericDAOs: "
+ Arrays.toString(beanNames));
}
}
/**
* 对 {@link GenericDAO} 及其子DAO接口中没有注解®SQL或仅仅®SQL("")的方法进行解析,根据实际参数情况自动动态生成SQL语句
*/
@Override
public void interpret(StatementRuntime runtime) {
final String interpreterAttribute = "jade-plugin-sql.interpreter";
Interpreter interpreter = runtime.getMetaData().getAttribute(interpreterAttribute);
if (interpreter == null) {
StatementMetaData smd = runtime.getMetaData();
synchronized (smd) {
interpreter = smd.getAttribute(interpreterAttribute);
if (interpreter == null) {
interpreter = PassThroughInterpreter;
if (GenericDAO.class.isAssignableFrom(smd.getDAOMetaData().getDAOClass())) {
interpreter = VariableResolverInterpreter;
SQL sqlAnnotation = smd.getMethod().getAnnotation(SQL.class);
if (sqlAnnotation == null // 没有注解@SQL | || PlumUtils.isBlank(sqlAnnotation.value()) // 虽注解但没有写SQL | 6 |
AmadeusITGroup/sonar-stash | src/main/java/org/sonar/plugins/stash/issue/collector/StashCollector.java | [
"public enum IssueType {\r\n CONTEXT,\r\n REMOVED,\r\n ADDED,\r\n}\r",
"public class StashComment {\r\n\r\n private final long id;\r\n private final String message;\r\n private final StashUser author;\r\n private final long version;\r\n private long line;\r\n private String path;\r\n private List<StashTask> tasks;\r\n\r\n public StashComment(long id, String message, String path, Long line, StashUser author, long version) {\r\n this.id = id;\r\n this.message = message;\r\n this.path = path;\r\n this.author = author;\r\n this.version = version;\r\n\r\n // Stash comment can be null if comment is global to all the file\r\n if (line == null) {\r\n this.line = 0;\r\n } else {\r\n this.line = line.longValue();\r\n }\r\n\r\n tasks = new ArrayList<>();\r\n }\r\n\r\n public long getId() {\r\n return id;\r\n }\r\n\r\n public void setLine(long line) {\r\n this.line = line;\r\n }\r\n\r\n public void setPath(String path) {\r\n this.path = path;\r\n }\r\n\r\n public String getMessage() {\r\n return message;\r\n }\r\n\r\n public String getPath() {\r\n return path;\r\n }\r\n\r\n public long getLine() {\r\n return line;\r\n }\r\n\r\n public StashUser getAuthor() {\r\n return author;\r\n }\r\n\r\n public long getVersion() {\r\n return version;\r\n }\r\n\r\n public List<StashTask> getTasks() {\r\n return Collections.unmodifiableList(tasks);\r\n }\r\n\r\n public void addTask(StashTask task) {\r\n tasks.add(task);\r\n }\r\n\r\n public boolean containsPermanentTasks() {\r\n boolean result = false;\r\n\r\n for (StashTask task : tasks) {\r\n if (!task.isDeletable()) {\r\n result = true;\r\n break;\r\n }\r\n }\r\n\r\n return result;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object object) {\r\n boolean result = false;\r\n if (object instanceof StashComment) {\r\n StashComment stashComment = (StashComment)object;\r\n result = this.getId() == stashComment.getId();\r\n }\r\n\r\n return result;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return (int)this.getId();\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return MoreObjects.toStringHelper(this)\r\n .add(\"id\", id)\r\n .add(\"message\", message)\r\n .add(\"author\", author)\r\n .add(\"version\", version)\r\n .add(\"line\", line)\r\n .add(\"path\", path)\r\n .add(\"tasks\", tasks)\r\n .toString();\r\n }\r\n}\r",
"public class StashCommentReport {\r\n\r\n private static final Logger LOGGER = Loggers.get(StashCommentReport.class);\r\n\r\n private List<StashComment> comments;\r\n\r\n public StashCommentReport() {\r\n this.comments = new ArrayList<>();\r\n }\r\n\r\n public List<StashComment> getComments() {\r\n return comments;\r\n }\r\n\r\n public void add(StashComment comment) {\r\n comments.add(comment);\r\n }\r\n\r\n public void add(StashCommentReport report) {\r\n for (StashComment comment : report.getComments()) {\r\n comments.add(comment);\r\n }\r\n }\r\n\r\n public boolean contains(String message, String path, long line) {\r\n boolean result = false;\r\n for (StashComment comment : comments) {\r\n\r\n if (Objects.equals(comment.getMessage(), message)\r\n && Objects.equals(comment.getPath(), path)\r\n && comment.getLine() == line) {\r\n\r\n result = true;\r\n break;\r\n }\r\n }\r\n\r\n return result;\r\n }\r\n\r\n public StashCommentReport applyDiffReport(StashDiffReport diffReport) {\r\n for (StashComment comment : comments) {\r\n StashDiff diff = diffReport.getDiffByComment(comment.getId());\r\n if ((diff != null) && diff.getType() == IssueType.CONTEXT) {\r\n\r\n // By default comment line, with type == CONTEXT, is set to FROM value.\r\n // Set comment line to TO value to be compared with SonarQube issue.\r\n long destination = diff.getDestination();\r\n comment.setLine(destination);\r\n\r\n LOGGER.debug(\"Update Stash comment \\\"{}\\\": set comment line to destination diff line ({})\",\r\n comment.getId(),\r\n comment.getLine());\r\n }\r\n }\r\n\r\n return this;\r\n }\r\n\r\n public int size() {\r\n return comments.size();\r\n }\r\n\r\n}\r",
"public class StashDiff {\r\n\r\n private final IssueType type;\r\n private final String path;\r\n private final long source;\r\n private final long destination;\r\n private final List<StashComment> comments;\r\n\r\n public StashDiff(IssueType type, String path, long source, long destination) {\r\n this.type = type;\r\n this.path = path;\r\n this.source = source;\r\n this.destination = destination;\r\n this.comments = new ArrayList<>();\r\n }\r\n\r\n public void addComment(StashComment comment) {\r\n this.comments.add(comment);\r\n }\r\n\r\n public String getPath() {\r\n return path;\r\n }\r\n\r\n public long getSource() {\r\n return source;\r\n }\r\n\r\n public long getDestination() {\r\n return destination;\r\n }\r\n\r\n public IssueType getType() {\r\n return type;\r\n }\r\n\r\n public List<StashComment> getComments() {\r\n return Collections.unmodifiableList(comments);\r\n }\r\n\r\n public boolean containsComment(long commentId) {\r\n return comments.stream().anyMatch(c -> c.getId() == commentId);\r\n }\r\n}\r",
"public class StashDiffReport {\r\n\r\n public static final int VICINITY_RANGE_NONE = 0;\r\n\r\n private List<StashDiff> diffs;\r\n\r\n public StashDiffReport() {\r\n this.diffs = new ArrayList<>();\r\n }\r\n\r\n public List<StashDiff> getDiffs() {\r\n return Collections.unmodifiableList(diffs);\r\n }\r\n\r\n public void add(StashDiff diff) {\r\n diffs.add(diff);\r\n }\r\n\r\n public void add(StashDiffReport report) {\r\n diffs.addAll(report.getDiffs());\r\n }\r\n\r\n private static boolean inVicinityOfChangedDiff(StashDiff diff, long destination, int range) {\r\n if (range <= 0) {\r\n return false;\r\n }\r\n long lower = Math.min(diff.getSource(), diff.getDestination());\r\n long upper = Math.max(diff.getSource(), diff.getDestination());\r\n return Range.closed(lower - range, upper + range).contains(destination);\r\n }\r\n\r\n private static boolean isChangedDiff(StashDiff diff, long destination) {\r\n return diff.getDestination() == destination;\r\n }\r\n\r\n private static boolean lineIsChangedDiff(StashDiff diff) {\r\n return !diff.getType().equals(IssueType.CONTEXT);\r\n }\r\n\r\n public IssueType getType(String path, long destination, int vicinityRange) {\r\n boolean isInContextDiff = false;\r\n for (StashDiff diff : diffs) {\r\n if (Objects.equals(diff.getPath(), path)) {\r\n // Line 0 never belongs to Stash Diff view.\r\n // It is a global comment with a type set to CONTEXT.\r\n if (destination == 0) {\r\n return IssueType.CONTEXT;\r\n } else if (!lineIsChangedDiff(diff)) {\r\n // We only care about changed diff\r\n continue;\r\n } else if (isChangedDiff(diff, destination)) {\r\n return diff.getType();\r\n } else if (inVicinityOfChangedDiff(diff, destination, vicinityRange)) {\r\n isInContextDiff = true;\r\n }\r\n }\r\n }\r\n return isInContextDiff ? IssueType.CONTEXT : null;\r\n }\r\n\r\n /**\r\n * Depends on the type of the diff.\r\n * If type == \"CONTEXT\", return the source line of the diff.\r\n * If type == \"ADDED\", return the destination line of the diff.\r\n */\r\n public long getLine(String path, long destination) {\r\n for (StashDiff diff : diffs) {\r\n if (Objects.equals(diff.getPath(), path) && (diff.getDestination() == destination)) {\r\n\r\n if (diff.getType() == IssueType.CONTEXT) {\r\n return diff.getSource();\r\n } else {\r\n return diff.getDestination();\r\n }\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public StashDiff getDiffByComment(long commentId) {\r\n for (StashDiff diff : diffs) {\r\n if (diff.containsComment(commentId)) {\r\n return diff;\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Get all comments from the Stash differential report.\r\n */\r\n public List<StashComment> getComments() {\r\n List<StashComment> result = new ArrayList<>();\r\n\r\n for (StashDiff diff : this.diffs) {\r\n List<StashComment> comments = diff.getComments();\r\n\r\n for (StashComment comment : comments) {\r\n if (!result.contains(comment)) {\r\n result.add(comment);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n}\r"
] | import com.github.cliftonlabs.json_simple.JsonArray;
import com.github.cliftonlabs.json_simple.JsonObject;
import java.math.BigDecimal;
import org.sonar.plugins.stash.PullRequestRef;
import org.sonar.plugins.stash.StashPlugin.IssueType;
import org.sonar.plugins.stash.exceptions.StashReportExtractionException;
import org.sonar.plugins.stash.issue.StashComment;
import org.sonar.plugins.stash.issue.StashCommentReport;
import org.sonar.plugins.stash.issue.StashDiff;
import org.sonar.plugins.stash.issue.StashDiffReport;
import org.sonar.plugins.stash.issue.StashPullRequest;
import org.sonar.plugins.stash.issue.StashTask;
import org.sonar.plugins.stash.issue.StashUser;
| package org.sonar.plugins.stash.issue.collector;
public final class StashCollector {
private static final String AUTHOR = "author";
private static final String VERSION = "version";
private StashCollector() {
// Hiding implicit public constructor with an explicit private one (squid:S1118)
}
public static StashCommentReport extractComments(JsonObject jsonComments) {
StashCommentReport result = new StashCommentReport();
JsonArray jsonValues = (JsonArray)jsonComments.get("values");
if (jsonValues != null) {
for (Object obj : jsonValues.toArray()) {
JsonObject jsonComment = (JsonObject)obj;
StashComment comment = extractComment(jsonComment);
result.add(comment);
}
}
return result;
}
public static StashComment extractComment(JsonObject jsonComment, String path, Long line) {
long id = getLong(jsonComment, "id");
String message = (String)jsonComment.get("text");
long version = getLong(jsonComment, VERSION);
JsonObject jsonAuthor = (JsonObject)jsonComment.get(AUTHOR);
StashUser stashUser = extractUser(jsonAuthor);
return new StashComment(id, message, path, line, stashUser, version);
}
public static StashComment extractComment(JsonObject jsonComment) {
JsonObject jsonAnchor = (JsonObject)jsonComment.get("anchor");
if (jsonAnchor == null) {
throw new StashReportExtractionException("JSON Comment does not contain any \"anchor\" tag"
+ " to describe comment \"line\" and \"path\"");
}
String path = (String)jsonAnchor.get("path");
// can be null if comment is attached to the global file
Long line = getLong(jsonAnchor, "line");
return extractComment(jsonComment, path, line);
}
public static StashPullRequest extractPullRequest(PullRequestRef pr,
JsonObject jsonPullRequest) {
StashPullRequest result = new StashPullRequest(pr);
long version = getLong(jsonPullRequest, VERSION);
result.setVersion(version);
JsonArray jsonReviewers = (JsonArray)jsonPullRequest.get("reviewers");
if (jsonReviewers != null) {
for (Object objReviewer : jsonReviewers.toArray()) {
JsonObject jsonReviewer = (JsonObject)objReviewer;
JsonObject jsonUser = (JsonObject)jsonReviewer.get("user");
if (jsonUser != null) {
StashUser reviewer = extractUser(jsonUser);
result.addReviewer(reviewer);
}
}
}
return result;
}
public static StashUser extractUser(JsonObject jsonUser) {
long id = getLong(jsonUser, "id");
String name = (String)jsonUser.get("name");
String slug = (String)jsonUser.get("slug");
String email = (String)jsonUser.get("email");
return new StashUser(id, name, slug, email);
}
| public static StashDiffReport extractDiffs(JsonObject jsonObject) {
| 4 |
KostyaSha/github-integration-plugin | github-pullrequest-plugin/src/test/java/org/jenkinsci/plugins/github/pullrequest/events/impl/GitHubPRCommentEventTest.java | [
"public class GitHubPRCause extends GitHubCause<GitHubPRCause> {\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRCause.class);\n\n private String headSha;\n private int number;\n private boolean mergeable;\n private String targetBranch;\n private String sourceBranch;\n private String prAuthorEmail;\n private String body;\n\n private String sourceRepoOwner;\n private String triggerSenderName = \"\";\n private String triggerSenderEmail = \"\";\n private Set<String> labels;\n /**\n * In case triggered because of commit. See\n * {@link org.jenkinsci.plugins.github.pullrequest.events.impl.GitHubPROpenEvent}\n */\n private String commitAuthorName;\n private String commitAuthorEmail;\n\n private String condRef;\n private String state;\n private String commentAuthorName;\n private String commentAuthorEmail;\n private String commentBody;\n private String commentBodyMatch;\n\n public GitHubPRCause() {\n }\n\n public GitHubPRCause(GHPullRequest remotePr,\n GitHubPRRepository localRepo,\n String reason,\n boolean skip) {\n this(new GitHubPRPullRequest(remotePr), remotePr.getUser(), localRepo, skip, reason);\n withRemoteData(remotePr);\n if (localRepo != null) {\n withLocalRepo(localRepo);\n }\n }\n\n @Deprecated\n public GitHubPRCause(GHPullRequest remotePr,\n String reason,\n boolean skip) {\n this(remotePr, null, reason, skip);\n }\n\n public GitHubPRCause(GitHubPRPullRequest pr,\n GHUser triggerSender,\n GitHubPRRepository localRepo,\n boolean skip,\n String reason) {\n this(pr.getHeadSha(), pr.getNumber(),\n pr.isMergeable(), pr.getBaseRef(), pr.getHeadRef(),\n pr.getUserEmail(), pr.getTitle(), pr.getHtmlUrl(), pr.getSourceRepoOwner(),\n pr.getLabels(),\n triggerSender, skip, reason, \"\", \"\", pr.getState());\n this.body = pr.getBody();\n if (localRepo != null) {\n withLocalRepo(localRepo);\n }\n }\n\n @Deprecated\n public GitHubPRCause(GitHubPRPullRequest pr,\n GHUser triggerSender,\n boolean skip,\n String reason) {\n this(pr, triggerSender, null, skip, reason);\n }\n\n // FIXME (sizes) ParameterNumber: More than 7 parameters (found 15).\n // CHECKSTYLE:OFF\n public GitHubPRCause(String headSha, int number, boolean mergeable,\n String targetBranch, String sourceBranch, String prAuthorEmail,\n String title, URL htmlUrl, String sourceRepoOwner, Set<String> labels,\n GHUser triggerSender, boolean skip, String reason,\n String commitAuthorName, String commitAuthorEmail,\n String state) {\n // CHECKSTYLE:ON\n this.headSha = headSha;\n this.number = number;\n this.mergeable = mergeable;\n this.targetBranch = targetBranch;\n this.sourceBranch = sourceBranch;\n this.prAuthorEmail = prAuthorEmail;\n withTitle(title);\n withHtmlUrl(htmlUrl);\n this.sourceRepoOwner = sourceRepoOwner;\n this.labels = labels;\n withSkip(skip);\n withReason(reason);\n this.commitAuthorName = commitAuthorName;\n this.commitAuthorEmail = commitAuthorEmail;\n\n if (nonNull(triggerSender)) {\n try {\n this.triggerSenderName = triggerSender.getName();\n } catch (IOException e) {\n LOGGER.error(\"Can't get trigger sender name from remote PR\");\n }\n\n try {\n this.triggerSenderEmail = triggerSender.getEmail();\n } catch (IOException e) {\n LOGGER.error(\"Can't get trigger sender email from remote PR\");\n }\n }\n\n this.condRef = mergeable ? \"merge\" : \"head\";\n\n this.state = state;\n }\n\n @Override\n public GitHubPRCause withLocalRepo(@NonNull GitHubRepository localRepo) {\n withGitUrl(localRepo.getGitUrl());\n withSshUrl(localRepo.getSshUrl());\n // html url is set from constructor and points to pr\n // withHtmlUrl(localRepo.getGithubUrl());\n return this;\n }\n\n /**\n * Copy constructor\n */\n public GitHubPRCause(GitHubPRCause orig) {\n this(orig.getHeadSha(), orig.getNumber(), orig.isMergeable(),\n orig.getTargetBranch(), orig.getSourceBranch(),\n orig.getPRAuthorEmail(), orig.getTitle(),\n orig.getHtmlUrl(), orig.getSourceRepoOwner(), orig.getLabels(), null,\n orig.isSkip(), orig.getReason(), orig.getCommitAuthorName(), orig.getCommitAuthorEmail(), orig.getState());\n withTriggerSenderName(orig.getTriggerSenderEmail());\n withTriggerSenderEmail(orig.getTriggerSenderEmail());\n withBody(orig.getBody());\n withCommentAuthorName(orig.getCommentAuthorName());\n withCommentAuthorEmail(orig.getCommentAuthorEmail());\n withCommentBody(orig.getCommentBody());\n withCommentBodyMatch(orig.getCommentBodyMatch());\n withCommitAuthorName(orig.getCommitAuthorName());\n withCommitAuthorEmail(orig.getCommitAuthorEmail());\n withCondRef(orig.getCondRef());\n withGitUrl(orig.getGitUrl());\n withSshUrl(orig.getSshUrl());\n withPollingLog(orig.getPollingLog());\n }\n\n public static GitHubPRCause newGitHubPRCause() {\n return new GitHubPRCause();\n }\n\n /**\n * @see #headSha\n */\n public GitHubPRCause withHeadSha(String headSha) {\n this.headSha = headSha;\n return this;\n }\n\n /**\n * @see #number\n */\n public GitHubPRCause withNumber(int number) {\n this.number = number;\n return this;\n }\n\n /**\n * @see #mergeable\n */\n public GitHubPRCause withMergeable(boolean mergeable) {\n this.mergeable = mergeable;\n return this;\n }\n\n /**\n * @see #targetBranch\n */\n public GitHubPRCause withTargetBranch(String targetBranch) {\n this.targetBranch = targetBranch;\n return this;\n }\n\n /**\n * @see #sourceBranch\n */\n public GitHubPRCause withSourceBranch(String sourceBranch) {\n this.sourceBranch = sourceBranch;\n return this;\n }\n\n /**\n * @see #prAuthorEmail\n */\n public GitHubPRCause withPrAuthorEmail(String prAuthorEmail) {\n this.prAuthorEmail = prAuthorEmail;\n return this;\n }\n\n /**\n * @see #sourceRepoOwner\n */\n public GitHubPRCause withSourceRepoOwner(String sourceRepoOwner) {\n this.sourceRepoOwner = sourceRepoOwner;\n return this;\n }\n\n /**\n * @see #triggerSenderName\n */\n public GitHubPRCause withTriggerSenderName(String triggerSenderName) {\n this.triggerSenderName = triggerSenderName;\n return this;\n }\n\n /**\n * @see #triggerSenderEmail\n */\n public GitHubPRCause withTriggerSenderEmail(String triggerSenderEmail) {\n this.triggerSenderEmail = triggerSenderEmail;\n return this;\n }\n\n /**\n * @see #labels\n */\n public GitHubPRCause withLabels(Set<String> labels) {\n this.labels = labels;\n return this;\n }\n\n /**\n * @see #commitAuthorName\n */\n public GitHubPRCause withCommitAuthorName(String commitAuthorName) {\n this.commitAuthorName = commitAuthorName;\n return this;\n }\n\n /**\n * @see #commitAuthorEmail\n */\n public GitHubPRCause withCommitAuthorEmail(String commitAuthorEmail) {\n this.commitAuthorEmail = commitAuthorEmail;\n return this;\n }\n\n /**\n * @see #condRef\n */\n public GitHubPRCause withCondRef(String condRef) {\n this.condRef = condRef;\n return this;\n }\n\n public GitHubPRCause withCommentAuthorName(String commentAuthorName) {\n this.commentAuthorName = commentAuthorName;\n return this;\n }\n\n public GitHubPRCause withCommentAuthorEmail(String commentAuthorEmail) {\n this.commentAuthorEmail = commentAuthorEmail;\n return this;\n }\n\n public GitHubPRCause withCommentBody(String commentBody) {\n this.commentBody = commentBody;\n return this;\n }\n\n public GitHubPRCause withCommentBodyMatch(String commentBodyMatch) {\n this.commentBodyMatch = commentBodyMatch;\n return this;\n }\n\n public String getBody() {\n return body;\n }\n\n public GitHubPRCause withBody(String body) {\n this.body = body;\n return this;\n }\n\n @Override\n public String getShortDescription() {\n return \"GitHub PR #\" + number + \": \" + getReason();\n }\n\n public String getHeadSha() {\n return headSha;\n }\n\n public boolean isMergeable() {\n return mergeable;\n }\n\n public int getNumber() {\n return number;\n }\n\n public String getTargetBranch() {\n return targetBranch;\n }\n\n public String getSourceBranch() {\n return sourceBranch;\n }\n\n public String getPRAuthorEmail() {\n return prAuthorEmail;\n }\n\n public String getSourceRepoOwner() {\n return sourceRepoOwner;\n }\n\n @NonNull\n public Set<String> getLabels() {\n return isNull(labels) ? Collections.emptySet() : labels;\n }\n\n public String getTriggerSenderName() {\n return triggerSenderName;\n }\n\n public String getTriggerSenderEmail() {\n return triggerSenderEmail;\n }\n\n public String getPrAuthorEmail() {\n return prAuthorEmail;\n }\n\n public String getCommitAuthorName() {\n return commitAuthorName;\n }\n\n public String getCommitAuthorEmail() {\n return commitAuthorEmail;\n }\n\n public String getState() {\n return state;\n }\n\n @NonNull\n public String getCondRef() {\n return condRef;\n }\n\n /**\n * When trigger by comment, author of comment.\n */\n public String getCommentAuthorName() {\n return commentAuthorName;\n }\n\n /**\n * When trigger by comment, author email of comment.\n */\n public String getCommentAuthorEmail() {\n return commentAuthorEmail;\n }\n\n /**\n * When trigger by comment, body of comment.\n */\n public String getCommentBody() {\n return commentBody;\n }\n\n /**\n * When trigger by comment, string matched to pattern.\n */\n public String getCommentBodyMatch() {\n return commentBodyMatch;\n }\n\n @Override\n public void fillParameters(List<ParameterValue> params) {\n GitHubPREnv.getParams(this, params);\n }\n\n @Override\n public GitHubSCMHead<GitHubPRCause> createSCMHead(String sourceId) {\n return new GitHubPRSCMHead(number, targetBranch, sourceId);\n }\n\n @Override\n public void onAddedTo(@NonNull Run run) {\n if (run.getParent().getParent() instanceof SCMSourceOwner) {\n // skip multibranch\n return;\n }\n\n // move polling log from cause to action\n try {\n GitHubPRPollingLogAction action = new GitHubPRPollingLogAction(run);\n FileUtils.writeStringToFile(action.getPollingLogFile(), getPollingLog());\n run.replaceAction(action);\n } catch (IOException e) {\n LOGGER.warn(\"Failed to persist the polling log\", e);\n }\n setPollingLog(null);\n }\n\n @Override\n public boolean equals(Object o) {\n return EqualsBuilder.reflectionEquals(this, o);\n }\n\n @Override\n public int hashCode() {\n return HashCodeBuilder.reflectionHashCode(this);\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);\n }\n\n}",
"public class GitHubPRLabel implements Describable<GitHubPRLabel> {\n private Set<String> labels;\n\n @DataBoundConstructor\n public GitHubPRLabel(String labels) {\n this(new HashSet<>(Arrays.asList(labels.split(\"\\n\"))));\n }\n\n public GitHubPRLabel(Set<String> labels) {\n this.labels = labels;\n }\n\n // for UI binding\n public String getLabels() {\n return Joiner.on(\"\\n\").skipNulls().join(labels);\n }\n\n @NonNull\n public Set<String> getLabelsSet() {\n return nonNull(labels) ? labels : Collections.<String>emptySet();\n }\n\n public DescriptorImpl getDescriptor() {\n return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);\n }\n\n @Symbol(\"labels\")\n @Extension\n public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {\n @NonNull\n @Override\n public String getDisplayName() {\n return \"Labels\";\n }\n }\n}",
"public class GitHubPRPullRequest {\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRPullRequest.class);\n\n private final int number;\n // https://github.com/kohsuke/github-api/issues/178\n private final Date issueUpdatedAt;\n private String title;\n private String body;\n private Date prUpdatedAt;\n private String headSha;\n private String headRef;\n private Boolean mergeable;\n private String baseRef;\n private String userEmail;\n private String userLogin;\n private URL htmlUrl;\n private Set<String> labels;\n @CheckForNull\n private Date lastCommentCreatedAt;\n private String sourceRepoOwner;\n private String state;\n\n private boolean inBadState = false;\n\n /**\n * Save only what we need for next comparison\n */\n public GitHubPRPullRequest(GHPullRequest pr) {\n userLogin = pr.getUser().getLogin();\n number = pr.getNumber();\n try {\n prUpdatedAt = pr.getUpdatedAt();\n issueUpdatedAt = pr.getIssueUpdatedAt();\n } catch (IOException e) {\n // those methods never actually throw IOExceptions\n throw new IllegalStateException(e);\n }\n\n GHCommitPointer prHead = pr.getHead();\n headSha = prHead.getSha();\n headRef = prHead.getRef();\n sourceRepoOwner = prHead.getRepository().getOwnerName();\n\n title = pr.getTitle();\n baseRef = pr.getBase().getRef();\n htmlUrl = pr.getHtmlUrl();\n\n try {\n Date maxDate = new Date(0);\n List<GHIssueComment> comments = execute(pr::getComments);\n for (GHIssueComment comment : comments) {\n if (comment.getCreatedAt().compareTo(maxDate) > 0) {\n maxDate = comment.getCreatedAt();\n }\n }\n lastCommentCreatedAt = maxDate.getTime() == 0 ? null : new Date(maxDate.getTime());\n } catch (IOException e) {\n LOGGER.error(\"Can't get comments for PR: {}\", pr.getNumber(), e);\n lastCommentCreatedAt = null;\n }\n\n try {\n userEmail = execute(() -> pr.getUser().getEmail());\n } catch (Exception e) {\n LOGGER.error(\"Can't get GitHub user email.\", e);\n userEmail = \"\";\n }\n\n GHRepository remoteRepo = pr.getRepository();\n\n try {\n updateLabels(execute(() -> remoteRepo.getIssue(number).getLabels()));\n } catch (IOException e) {\n LOGGER.error(\"Can't retrieve label list: {}\", e);\n inBadState = true;\n }\n\n // see https://github.com/kohsuke/github-api/issues/111\n try {\n mergeable = execute(pr::getMergeable);\n } catch (IOException e) {\n LOGGER.error(\"Can't get mergeable status.\", e);\n mergeable = false;\n }\n\n state = pr.getState().toString();\n body = pr.getBody();\n }\n\n public int getNumber() {\n return number;\n }\n\n public String getHeadSha() {\n return headSha;\n }\n\n public boolean isMergeable() {\n return isNull(mergeable) ? false : mergeable;\n }\n\n public String getBaseRef() {\n return baseRef;\n }\n\n public String getHeadRef() {\n return headRef;\n }\n\n public String getUserEmail() {\n return userEmail;\n }\n\n public String getTitle() {\n return title;\n }\n\n public String getBody() {\n return body;\n }\n\n @NonNull\n public Set<String> getLabels() {\n return isNull(labels) ? Collections.<String>emptySet() : labels;\n }\n\n @CheckForNull\n public Date getLastCommentCreatedAt() {\n return lastCommentCreatedAt;\n }\n\n /**\n * URL to the Github Pull Request.\n */\n public URL getHtmlUrl() {\n return htmlUrl;\n }\n\n public Date getPrUpdatedAt() {\n return new Date(prUpdatedAt.getTime());\n }\n\n public Date getIssueUpdatedAt() {\n return issueUpdatedAt;\n }\n\n public String getUserLogin() {\n return userLogin;\n }\n\n public String getSourceRepoOwner() {\n return sourceRepoOwner;\n }\n\n /**\n * @see #state\n */\n @CheckForNull\n public String getState() {\n return state;\n }\n\n /**\n * as is\n */\n public void setLabels(Set<String> labels) {\n this.labels = labels;\n }\n\n private void updateLabels(Collection<GHLabel> labels) {\n this.labels = new HashSet<>();\n for (GHLabel label : labels) {\n this.labels.add(label.getName());\n }\n }\n\n /**\n * Indicates that remote PR wasn't fully saved locally during last check.\n */\n public boolean isInBadState() {\n return inBadState || isNull(labels);\n }\n\n public static String getIconFileName() {\n return Functions.getResourcePath() + \"/plugin/github-pullrequest/git-pull-request.svg\";\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this, SHORT_PREFIX_STYLE);\n }\n\n @Override\n public boolean equals(Object o) {\n return EqualsBuilder.reflectionEquals(this, o);\n }\n\n @Override\n public int hashCode() {\n return HashCodeBuilder.reflectionHashCode(this);\n }\n}",
"public class GitHubPRTrigger extends GitHubTrigger<GitHubPRTrigger> {\n private static final Logger LOG = LoggerFactory.getLogger(GitHubPRTrigger.class);\n public static final String FINISH_MSG = \"Finished GitHub Pull Request trigger check\";\n\n @CheckForNull\n private List<GitHubPREvent> events = new ArrayList<>();\n /**\n * Set PR(commit) status before build. No configurable message for it.\n */\n private boolean preStatus = false;\n\n @CheckForNull\n private GitHubPRUserRestriction userRestriction;\n @CheckForNull\n private GitHubPRBranchRestriction branchRestriction;\n\n @CheckForNull\n private transient GitHubPRPollingLogAction pollingLogAction;\n\n /**\n * For groovy UI\n */\n @Restricted(value = NoExternalUse.class)\n public GitHubPRTrigger() throws ANTLRException {\n super(\"\");\n }\n\n @DataBoundConstructor\n public GitHubPRTrigger(String spec,\n GitHubPRTriggerMode triggerMode,\n List<GitHubPREvent> events) throws ANTLRException {\n super(spec);\n setTriggerMode(triggerMode);\n this.events = Util.fixNull(events);\n }\n\n @DataBoundSetter\n public void setPreStatus(boolean preStatus) {\n this.preStatus = preStatus;\n }\n\n @DataBoundSetter\n public void setUserRestriction(GitHubPRUserRestriction userRestriction) {\n this.userRestriction = userRestriction;\n }\n\n @DataBoundSetter\n public void setBranchRestriction(GitHubPRBranchRestriction branchRestriction) {\n this.branchRestriction = branchRestriction;\n }\n\n public boolean isPreStatus() {\n return preStatus;\n }\n\n @NonNull\n public List<GitHubPREvent> getEvents() {\n return nonNull(events) ? events : emptyList();\n }\n\n public GitHubPRUserRestriction getUserRestriction() {\n return userRestriction;\n }\n\n public GitHubPRBranchRestriction getBranchRestriction() {\n return branchRestriction;\n }\n\n @Override\n public void start(Job<?, ?> job, boolean newInstance) {\n LOG.info(\"Starting GitHub Pull Request trigger for project {}\", job.getFullName());\n super.start(job, newInstance);\n\n if (newInstance && getRepoProvider().isManageHooks(this) && withHookTriggerMode().apply(job)) {\n try {\n getRepoProvider().registerHookFor(this);\n getErrorsAction().removeErrors(GitHubHookRegistrationError.class);\n } catch (Throwable error) {\n getErrorsAction().addOrReplaceError(new GitHubHookRegistrationError(\n String.format(\"Failed register hook for %s. <br/> Because %s\",\n job.getFullName(), error.toString())\n ));\n throw error;\n }\n }\n }\n\n /**\n * Blocking run.\n */\n @Override\n public void doRun() {\n doRun(null);\n }\n\n /**\n * non-blocking run.\n */\n @Override\n public void run() {\n if (getTriggerMode() != LIGHT_HOOKS) {\n // don't consume Timer threads\n queueRun(null);\n }\n }\n\n @CheckForNull\n @Override\n public GitHubPRPollingLogAction getPollingLogAction() {\n if (isNull(pollingLogAction) && nonNull(job)) {\n pollingLogAction = new GitHubPRPollingLogAction(job);\n }\n\n return pollingLogAction;\n }\n\n @Override\n public DescriptorImpl getDescriptor() {\n return (DescriptorImpl) Jenkins.getInstance().getDescriptor(this.getClass());\n }\n\n /**\n * For running from external places. Goes to queue.\n * <p>\n *\n * @deprecated Why do we need to pass job here? Trigger.start() should happen when job is configured/loaded...\n */\n @Deprecated\n public void queueRun(Job<?, ?> job, final int prNumber) {\n this.job = job;\n queueRun(prNumber);\n }\n\n public void queueRun(final Integer prNumber) {\n getDescriptor().getQueue().execute(() -> doRun(prNumber));\n }\n\n /**\n * Runs check.\n * Synchronised because localRepository state is persisted after trigger decisions were made.\n * When multiple events triggering runs in queue they triggering builds in parallel.\n * TODO implement special queue for parallel prNumbers scans and make polling long async.\n *\n * @param prNumber - PR number for check, if null - then all PRs\n */\n public synchronized void doRun(Integer prNumber) {\n if (not(isBuildable()).apply(job)) {\n LOG.debug(\"Job {} is disabled, but trigger run!\", isNull(job) ? \"<no job>\" : job.getFullName());\n return;\n }\n\n if (!isSupportedTriggerMode(getTriggerMode())) {\n LOG.warn(\"Trigger mode {} is not supported yet ({})\", getTriggerMode(), job.getFullName());\n return;\n }\n\n GitHubPRRepository localRepository = job.getAction(GitHubPRRepository.class);\n if (isNull(localRepository)) {\n LOG.warn(\"Can't get repository info, maybe project {} misconfigured?\", job.getFullName());\n return;\n }\n\n List<GitHubPRCause> causes;\n\n try (LoggingTaskListenerWrapper listener =\n new LoggingTaskListenerWrapper(getPollingLogAction().getPollingLogFile(), UTF_8)) {\n long startTime = System.currentTimeMillis();\n listener.debug(\"Running GitHub Pull Request trigger check for {} on {}\",\n getDateTimeInstance().format(new Date(startTime)), localRepository.getFullName());\n try {\n localRepository.actualise(getRemoteRepository(), listener);\n\n causes = readyToBuildCauses(localRepository, listener, prNumber);\n\n localRepository.saveQuietly();\n\n // TODO print triggering to listener?\n from(causes).filter(new JobRunnerForCause(job, this)).toSet();\n } catch (Throwable t) {\n listener.error(\"Can't end trigger check!\", t);\n }\n\n long duration = System.currentTimeMillis() - startTime;\n listener.info(FINISH_MSG + \" for {} at {}. Duration: {}ms\",\n localRepository.getFullName(), getDateTimeInstance().format(new Date()), duration);\n } catch (Exception e) {\n // out of UI/user viewable error\n LOG.error(\"Can't process check ({})\", e.getMessage(), e);\n }\n }\n\n /**\n * runs check of local (last) Repository state (list of PRs) vs current remote state\n * - local state store only last open PRs\n * - if last open PR <-> now closed -> should trigger only when ClosePREvent exist\n * - last open PR <-> now changed -> trigger only\n * - special comment in PR -> trigger\n *\n * @param localRepository persisted data to compare with remote state\n * @param listener logger to write to console and to polling log\n * @param prNumber pull request number to fetch only required num. Can be null\n * @return causes which ready to be converted to job-starts. One cause per repo.\n */\n private List<GitHubPRCause> readyToBuildCauses(@NonNull GitHubPRRepository localRepository,\n @NonNull LoggingTaskListenerWrapper listener,\n @Nullable Integer prNumber) {\n try {\n GitHub github = getRepoProvider().getGitHub(this);\n if (isNull(github)) {\n LOG.error(\"GitHub connection is null, check Repo Providers!\");\n throw new IllegalStateException(\"GitHub connection is null, check Repo Providers!\");\n }\n\n GHRateLimit rateLimitBefore = github.getRateLimit();\n listener.debug(\"GitHub rate limit before check: {}\", rateLimitBefore);\n\n // get local and remote list of PRs\n //FIXME HiddenField: 'remoteRepository' hides a field? renamed to `remoteRepo`\n GHRepository remoteRepo = getRemoteRepository();\n Set<GHPullRequest> remotePulls = pullRequestsToCheck(prNumber, remoteRepo, localRepository);\n\n Set<GHPullRequest> prepared = from(remotePulls)\n .filter(badState(localRepository, listener))\n .filter(notUpdated(localRepository, listener))\n .toSet();\n\n List<GitHubPRCause> causes = from(prepared)\n .filter(and(\n ifSkippedFirstRun(listener, isSkipFirstRun()),\n withBranchRestriction(listener, getBranchRestriction()),\n withUserRestriction(listener, getUserRestriction())\n ))\n .transform(toGitHubPRCause(localRepository, listener, this))\n .filter(notNull())\n .toList();\n\n LOG.trace(\"Causes count for {}: {}\", localRepository.getFullName(), causes.size());\n\n // refresh all PRs because user may add events that may trigger unexpected builds.\n from(remotePulls).transform(updateLocalRepo(localRepository)).toSet();\n\n saveIfSkipFirstRun();\n\n GHRateLimit rateLimitAfter = github.getRateLimit();\n int consumed = rateLimitBefore.remaining - rateLimitAfter.remaining;\n LOG.info(\"GitHub rate limit after check {}: {}, consumed: {}, checked PRs: {}\",\n localRepository.getFullName(), rateLimitAfter, consumed, remotePulls.size());\n\n return causes;\n } catch (IOException e) {\n listener.error(\"Can't get build causes: \", e);\n return emptyList();\n }\n }\n\n private static boolean isSupportedTriggerMode(GitHubPRTriggerMode mode) {\n return mode != LIGHT_HOOKS;\n }\n\n /**\n * @return remote pull requests for future analysing.\n */\n private static Set<GHPullRequest> pullRequestsToCheck(@Nullable Integer prNumber,\n @NonNull GHRepository remoteRepo,\n @NonNull GitHubPRRepository localRepo) throws IOException {\n if (prNumber != null) {\n return execute(() -> singleton(remoteRepo.getPullRequest(prNumber)));\n } else {\n List<GHPullRequest> remotePulls = execute(() -> remoteRepo.getPullRequests(GHIssueState.OPEN));\n\n Set<Integer> remotePRNums = from(remotePulls).transform(extractPRNumber()).toSet();\n\n return from(localRepo.getPulls().keySet())\n // add PRs that was closed on remote\n .filter(not(in(remotePRNums)))\n .transform(fetchRemotePR(remoteRepo))\n .filter(notNull())\n .append(remotePulls)\n .toSet();\n }\n }\n\n @Override\n public String getFinishMsg() {\n return FINISH_MSG;\n }\n\n @Symbol(\"githubPullRequests\")\n @Extension\n public static class DescriptorImpl extends GitHubTriggerDescriptor {\n\n public DescriptorImpl() {\n load();\n }\n\n @NonNull\n @Override\n public String getDisplayName() {\n return \"GitHub Pull Requests\";\n }\n\n // list all available descriptors for choosing in job configuration\n public static List<GitHubPREventDescriptor> getEventDescriptors() {\n return GitHubPREventDescriptor.all();\n }\n\n public static DescriptorImpl get() {\n return Trigger.all().get(DescriptorImpl.class);\n }\n }\n}",
"@NonNull\npublic static Builder newGitHubPRDecisionContext() {\n return new Builder();\n}"
] | import hudson.model.TaskListener;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRCause;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRPullRequest;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRTrigger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kohsuke.github.GHCommitPointer;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHIssueComment;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.github.GHLabel;
import org.kohsuke.github.GHPullRequest;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GHUser;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import static com.github.kostyasha.github.integration.generic.GitHubPRDecisionContext.newGitHubPRDecisionContext;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | package org.jenkinsci.plugins.github.pullrequest.events.impl;
/**
* @author Kanstantsin Shautsou
*/
@RunWith(MockitoJUnitRunner.class)
public class GitHubPRCommentEventTest {
@Mock
private GHPullRequest remotePr;
@Mock
private GitHubPRPullRequest localPR;
@Mock
private GitHubPRLabel labels;
@Mock
private GHRepository repository;
@Mock
private GHIssue issue;
@Mock
private GHLabel mergeLabel;
@Mock
private GHLabel reviewedLabel;
@Mock
private GHLabel testLabel;
@Mock
private TaskListener listener;
@Mock
private PrintStream logger;
@Mock
private GitHubPRTrigger trigger;
@Mock
private GHUser author;
@Mock
private GHUser author2;
@Mock
private GHIssueComment comment;
@Mock
private GHIssueComment comment2;
@Test
public void testNullLocalComment() throws IOException {
when(listener.getLogger()).thenReturn(logger);
when(issue.getCreatedAt()).thenReturn(new Date());
when(comment.getBody()).thenReturn("body");
final ArrayList<GHIssueComment> ghIssueComments = new ArrayList<>();
ghIssueComments.add(comment);
when(remotePr.getComments()).thenReturn(ghIssueComments);
| GitHubPRCause cause = new GitHubPRCommentEvent("Comment") | 0 |
jentrata/jentrata | ebms-msh-jdbc-store/src/test/java/org/jentrata/ebms/messaging/internal/JDBCMessageStoreTest.java | [
"public class EbmsConstants {\n\n public static final String JENTRATA_VERSION = \"JentrataVersion\";\n\n //Jentrata Message Header keys\n public static final String SOAP_VERSION = \"JentrataSOAPVersion\";\n public static final String EBMS_VERSION = \"JentrataEBMSVersion\";\n public static final String VALID_PARTNER_AGREEMENT = \"JentrataIsValidPartnerAgreement\";\n public static final String EBMS_MESSAGE_MEP = \"JentrataMEP\";\n\n public static final String SOAP_VERSION_1_1 = \"1.1\";\n public static final String SOAP_VERSION_1_2 = \"1.2\";\n\n public static final String SOAP_1_1_NAMESPACE = \"http://schemas.xmlsoap.org/soap/envelope/\";\n\n public static final String SOAP_1_2_NAMESPACE = \"http://www.w3.org/2003/05/soap-envelope\";\n public static final String EBXML_V2_NAMESPACE = \"http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd\";\n\n public static final String EBXML_V3_NAMESPACE = \"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/\";\n\n public static final String EBMS_V2 = \"ebMSV2\";\n public static final String EBMS_V3 = \"ebMSV3\";\n\n public static final String EBMS_V3_MEP_ONE_WAY = \"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/oneWay\";\n public static final String EBMS_V3_MEP_TWO_WAY = \"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/twoWay\";\n\n public static final String EBMS_V3_MEP_BINDING_PUSH = \"ttp://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/push\";\n\n public static final String EBMS_RECEIPT_REQUIRED = \"JentrataReceiptRequired\";\n\n public static final String CONTENT_ID = \"Content-ID\";\n public static final String CONTENT_LENGTH = Exchange.CONTENT_LENGTH;\n public static final String CONTENT_TRANSFER_ENCODING = \"Content-Transfer-Encoding\";\n public static final String CONTENT_DISPOSITION = \"Content-Disposition\";\n public static final String CONTENT_TYPE = Exchange.CONTENT_TYPE;\n\n public static final String SOAP_XML_CONTENT_TYPE = \"application/soap+xml\";\n public static final String TEXT_XML_CONTENT_TYPE = \"text/xml\";\n public static final String MESSAGE_ID = \"JentrataMessageID\";\n public static final String REF_TO_MESSAGE_ID = \"JentrataRefMessageID\";\n public static final String MESSAGE_FROM = \"JentrataFrom\";\n public static final String MESSAGE_FROM_TYPE = \"JentrataFromPartyIdType\";\n public static final String MESSAGE_FROM_ROLE = \"JentrataPartyFromRole\";\n public static final String MESSAGE_TO = \"JentrataTo\";\n public static final String MESSAGE_TO_TYPE = \"JentrataToPartyIdType\";\n public static final String MESSAGE_TO_ROLE = \"JentrataPartyToRole\";\n public static final String MESSAGE_AGREEMENT_REF = \"JentrataAgreementRef\";\n public static final String MESSAGE_PART_PROPERTIES = \"JentraraPartProperties\";\n public static final String MESSAGE_PAYLOAD_SCHEMA = \"JentrataPayloadSchema\";\n public static final String MESSAGE_DIRECTION = \"JentrataMessageDirection\";\n public static final String MESSAGE_DIRECTION_INBOUND = \"inbox\";\n public static final String MESSAGE_DIRECTION_OUTBOUND = \"outbox\";\n public static final String MESSAGE_STATUS = \"JentrataMessageStatus\";\n public static final String MESSAGE_STATUS_DESCRIPTION = \"JentrataMessageStatusDesc\";\n public static final String MESSAGE_TYPE = \"JentrataMessageType\";\n public static final String MESSAGE_SERVICE = \"JentrataService\";\n public static final String MESSAGE_ACTION = \"JentrataAction\";\n public static final String MESSAGE_CONVERSATION_ID = \"JentrataConversationId\";\n public static final String CPA = \"JentrataCPA\";\n public static final String CPA_ID = \"JentrataCPAId\";\n public static final String PAYLOAD_ID = \"JentrataPayloadId\";\n public static final String PAYLOAD_FILENAME = \"JentrataPayloadFilename\";\n public static final String PAYLOAD_COMPRESSION = \"JentrataPayloadCompression\";\n public static final String CPA_ID_UNKNOWN = \"UNKNOWN\";\n public static final String CONTENT_CHAR_SET = \"JentrataCharSet\";\n public static final String SOAP_BODY_PAYLOAD_ID = \"soapbodypart\";\n public static final String SECURITY_CHECK = \"JentrataSecurityCheck\";\n public static final String SECURITY_RESULTS = \"JentrataSecurityResults\";\n\n public static final String SECURITY_ERROR_CODE = \"JentrataSecurityErrorCode\";\n public static final String EBMS_ERROR = \"JentrataEbmsError\";\n public static final String EBMS_ERROR_CODE = \"JentrataEbmsErrorCode\";\n public static final String EBMS_ERROR_DESCRIPTION = \"JentrataEbmsErrorDesc\";\n public static final String MESSAGE_PAYLOADS = \"JentrataPayloads\";\n public static final String COMPRESSION_TYPE = \"CompressionType\";\n public static final String GZIP = \"application/gzip\";\n public static final String MESSAGE_DATE = \"JentrataMessageDate\";\n public static final String MESSAGE_RECEIPT_PATTERN = \"JentrataMessageReceipt\";\n public static final String MESSAGE_DUP_DETECTION = \"JentrataDupDetection\";\n public static final String DUPLICATE_MESSAGE = \"JentrataIsDuplicateMessage\";\n public static final String DUPLICATE_MESSAGE_ID = \"JentrataDuplicateMessageId\";\n public static final String VALIDATION_ERROR_DESC = \"JentrataValidationErrorDesc\";\n public static final String EBMS_VALIDATION_ERROR = \"JentrataValidationError\";\n\n public static final String DEFAULT_CPA_ID = \"JentrataDefaultCPAId\";\n public static final String DELIVERY_ERROR = \"JentrataDeliveryError\";\n}",
"public enum MessageStatusType {\n RECEIVED,\n DELIVER,\n DELIVERED,\n FAILED,\n DONE,\n IGNORED,\n ERROR;\n}",
"public enum MessageType {\n\n USER_MESSAGE,\n SIGNAL_MESSAGE,\n SIGNAL_MESSAGE_WITH_USER_MESSAGE,\n SIGNAL_MESSAGE_ERROR,\n UNKNOWN\n\n}",
"public interface Message {\n\n String getMessageId();\n String getDirection();\n String getCpaId();\n String getRefMessageId();\n String getConversationId();\n MessageStatusType getStatus();\n String getStatusDescription();\n Date getMessageDate();\n\n}",
"public interface MessageStore {\n\n public static final String DEFAULT_MESSAGE_STORE_ENDPOINT = \"direct:storeMessage\";\n public static final String DEFAULT_MESSAGE_INSERT_ENDPOINT = \"direct:insertMessage\";\n public static final String DEFAULT_MESSAGE_UPDATE_ENDPOINT = \"direct:updateMessage\";\n\n public static final String MESSAGE_STORE_REF = \"JentrataMessageStoreRef\";\n public static final String JENTRATA_MESSAGE_ID = \"JentrataMessageId\";\n\n void store(@Body InputStream message, Exchange exchange);\n\n void storeMessage(Exchange exchange);\n\n void updateMessage(@Header(EbmsConstants.MESSAGE_ID)String messageId,\n @Header(EbmsConstants.MESSAGE_DIRECTION)String messageDirection,\n @Header(EbmsConstants.MESSAGE_STATUS)MessageStatusType status,\n @Header(EbmsConstants.MESSAGE_STATUS_DESCRIPTION)String statusDescription);\n\n Message findByMessageId(@Header(EbmsConstants.MESSAGE_ID)String messageId, @Header(EbmsConstants.MESSAGE_DIRECTION) String messageDirection);\n InputStream findPayloadById(@Header(EbmsConstants.MESSAGE_ID)String messageId);\n List<Message> findByMessageStatus(@Header(EbmsConstants.MESSAGE_DIRECTION)String messageDirection, @Header(EbmsConstants.MESSAGE_STATUS)String status);\n}",
"public class UUIDGenerator {\n\n private String prefix = \"\";\n private String sufffix = \"@jentrata.org\";\n\n public String generateId() {\n String uuid = UUID.randomUUID().toString();\n return prefix + uuid + sufffix;\n }\n}",
"public class RepositoryManagerFactory {\n\n private DataSource dataSource;\n private String databaseType = \"H2\";\n\n public RepositoryManager createRepositoryManager() {\n if(databaseType == null) {\n throw new IllegalArgumentException(\"databaseType can not be null\");\n }\n RepositoryManager repositoryManager;\n switch (databaseType.toUpperCase()) {\n case \"POSTGRES\":\n repositoryManager = new PostgresRepositoryManager(dataSource);\n break;\n case \"H2\":\n repositoryManager = new H2RepositoryManager(dataSource);\n break;\n default:\n throw new UnsupportedOperationException(databaseType + \" is currently not a supported database\");\n }\n return repositoryManager;\n }\n\n public DataSource getDataSource() {\n return dataSource;\n }\n\n public void setDataSource(DataSource dataSource) {\n this.dataSource = dataSource;\n }\n\n public String getDatabaseType() {\n return databaseType;\n }\n\n public void setDatabaseType(String databaseType) {\n this.databaseType = databaseType;\n }\n}"
] | import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.commons.io.IOUtils;
import org.h2.jdbcx.JdbcConnectionPool;
import org.jentrata.ebms.EbmsConstants;
import org.jentrata.ebms.MessageStatusType;
import org.jentrata.ebms.MessageType;
import org.jentrata.ebms.messaging.Message;
import org.jentrata.ebms.messaging.MessageStore;
import org.jentrata.ebms.messaging.UUIDGenerator;
import org.jentrata.ebms.messaging.internal.sql.RepositoryManagerFactory;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue; | package org.jentrata.ebms.messaging.internal;
/**
* unit test for org.jentrata.ebms.messaging.internal.JDBCMessageStore
*
* @author aaronwalker
*/
public class JDBCMessageStoreTest extends CamelTestSupport {
private JdbcConnectionPool dataSource;
private JDBCMessageStore messageStore;
@Test
public void testShouldCreateMessageStoreTablesByDefault() throws Exception {
try(Connection conn = dataSource.getConnection()) {
try (Statement st = conn.createStatement()) {
assertTableGotCreated(st,"repository");
assertTableGotCreated(st,"message");
}
}
}
@Test
public void testShouldStoreMimeMessage() throws Exception {
File body = fileFromClasspath("simple-as4-receipt.xml");
String contentType = "Multipart/Related; boundary=\"----=_Part_7_10584188.1123489648993\"; type=\"application/soap+xml\"; start=\"<[email protected]>\"";
String messageId = "testMimeMessage1";
assertStoredMessage(messageId, contentType, body, MessageType.USER_MESSAGE);
}
@Test
public void testShouldStoreSoapMessage() throws Exception {
String contentType = "application/soap+xml";
File body = fileFromClasspath("simple-as4-receipt.xml");
String messageId = "testSoapMessage1";
assertStoredMessage(messageId, contentType, body, MessageType.SIGNAL_MESSAGE_WITH_USER_MESSAGE);
}
@Test
public void testUpdateStoreMimeMessage() throws Exception {
File body = fileFromClasspath("simple-as4-receipt.xml");
String contentType = "Multipart/Related; boundary=\"----=_Part_7_10584188.1123489648993\"; type=\"application/soap+xml\"; start=\"<[email protected]>\"";
String messageId = "testMimeMessage1";
assertStoredMessage(messageId, contentType, body, MessageType.USER_MESSAGE);
messageStore.updateMessage(messageId, EbmsConstants.MESSAGE_DIRECTION_INBOUND, MessageStatusType.RECEIVED,"Message Received");
try(Connection conn = dataSource.getConnection()) {
try (PreparedStatement st = conn.prepareStatement("select * from message where message_id = ?")) {
st.setString(1,messageId);
ResultSet resultSet = st.executeQuery();
assertThat(resultSet.next(),is(true));
assertThat(resultSet.getString("status"),equalTo("RECEIVED"));
assertThat(resultSet.getString("status_description"),equalTo("Message Received"));
}
}
}
@Test
public void testFindByMessageId() throws Exception {
String contentType = "application/soap+xml";
File body = fileFromClasspath("simple-as4-receipt.xml");
String messageId = "testSoapMessage1";
assertStoredMessage(messageId, contentType, body, MessageType.SIGNAL_MESSAGE_WITH_USER_MESSAGE);
messageStore.updateMessage(messageId, EbmsConstants.MESSAGE_DIRECTION_INBOUND, MessageStatusType.RECEIVED,"Message Received"); | Message message = messageStore.findByMessageId("testSoapMessage1",EbmsConstants.MESSAGE_DIRECTION_INBOUND); | 3 |
uvagfx/hipi | core/src/test/java/org/hipi/test/JpegCodecTestCase.java | [
"public class FloatImage extends RasterImage {\n\n public FloatImage() {\n super((PixelArray)(new PixelArrayFloat()));\n }\n\n public FloatImage(int width, int height, int bands) throws IllegalArgumentException {\n super((PixelArray)(new PixelArrayFloat()));\n HipiImageHeader header = new HipiImageHeader(HipiImageFormat.UNDEFINED, HipiColorSpace.UNDEFINED, width, height, bands, null, null);\n setHeader(header);\n }\n\n public FloatImage(int width, int height, int bands, HipiImageFormat imgFormat, HipiColorSpace colorspace) throws IllegalArgumentException {\n super((PixelArray)(new PixelArrayFloat()));\n HipiImageHeader header = new HipiImageHeader(imgFormat, colorspace,\n width, height, bands, null, null);\n setHeader(header);\n }\n\n public FloatImage(int width, int height, int bands, float[] data) \n throws IllegalArgumentException {\n super((PixelArray)(new PixelArrayFloat()));\n HipiImageHeader header = new HipiImageHeader(HipiImageFormat.UNDEFINED, HipiColorSpace.UNDEFINED,\n width, height, bands, null, null);\n setHeader(header);\n if (data == null || data.length != width*height*bands) {\n throw new IllegalArgumentException(\"Size of data buffer does not match image dimensions.\");\n }\n for (int i=0; i<width*height*bands; i++) {\n pixelArray.setElemFloat(i,data[i]);\n }\n }\n\n /**\n * Get object type identifier.\n *\n * @return Type of object.\n */\n public HipiImageType getType() {\n return HipiImageType.FLOAT;\n }\n\n /**\n * Provides direct access to underlying float array of pixel data.\n */\n public float[] getData() {\n return ((PixelArrayFloat)this.pixelArray).getData();\n }\n\n /**\n * Compares two ByteImage objects for equality allowing for some\n * amount of differences in pixel values.\n *\n * @return True if the two images have equal dimensions, color\n * spaces, and are found to deviate by less than a maximum\n * difference, false otherwise.\n */\n public boolean equalsWithTolerance(RasterImage thatImage, float maxDifference) {\n if (thatImage == null) {\n return false;\n }\n // Verify dimensions in headers are equal\n int w = this.getWidth();\n int h = this.getHeight();\n int b = this.getNumBands();\n if (this.getColorSpace() != thatImage.getColorSpace() ||\n\tthatImage.getWidth() != w || thatImage.getHeight() != h || \n\tthatImage.getNumBands() != b) {\n return false;\n }\n\n // Get pointers to pixel arrays\n PixelArray thisPA = this.getPixelArray();\n PixelArray thatPA = thatImage.getPixelArray();\n\n // Check that pixel data is equal.\n for (int i=0; i<w*h*b; i++) {\n double diff = Math.abs(thisPA.getElemFloat(i)-thatPA.getElemFloat(i));\n if (diff > maxDifference) {\n\treturn false;\n }\n }\n\n // Passed, declare equality\n return true;\n }\n\n /**\n * Compares two FloatImage objects for equality.\n *\n * @return True if the two images are found to deviate by less than\n * 1.0/255.0 at each pixel and across each band, false otherwise.\n */\n @Override\n public boolean equals(Object that) {\n // Check for pointer equivalence\n if (this == that)\n return true;\n\n // Verify object types are equal\n if (!(that instanceof FloatImage))\n return false;\n\n return equalsWithTolerance((FloatImage)that, 0.0f);\n }\n\n /**\n * Performs in-place addition with another {@link FloatImage}.\n * \n * @param thatImage target image to add to current image\n *\n * @throws IllegalArgumentException if the image dimensions do not match\n */\n public void add(FloatImage thatImage) throws IllegalArgumentException {\n // Verify input\n checkCompatibleInputImage(thatImage);\n\n // Perform in-place addition\n int w = this.getWidth();\n int h = this.getHeight();\n int b = this.getNumBands();\n float[] thisData = this.getData();\n float[] thatData = thatImage.getData();\n \n for (int i=0; i<w*h*b; i++) {\n thisData[i] += thatData[i];\n }\n }\n\n /**\n * Performs in-place addition of a scalar to each band of every pixel.\n * \n * @param number scalar value to add to each band of each pixel\n */\n public void add(float number) {\n int w = this.getWidth();\n int h = this.getHeight();\n int b = this.getNumBands();\n float[] thisData = this.getData();\n for (int i=0; i<w*h*b; i++) {\n thisData[i] += number;\n }\n }\n\n /**\n * Performs in-place elementwise multiplication of {@link FloatImage} and the current image.\n *\n * @param thatImage target image to use for multiplication\n */\n public void multiply(FloatImage thatImage) throws IllegalArgumentException {\n\n // Verify input\n checkCompatibleInputImage(thatImage);\n\n // Perform in-place elementwise multiply\n int w = this.getWidth();\n int h = this.getHeight();\n int b = this.getNumBands();\n float[] thisData = this.getData();\n float[] thatData = thatImage.getData();\n for (int i=0; i<w*h*b; i++) {\n thisData[i] *= thatData[i];\n }\n }\n\n /**\n * Performs in-place multiplication with scalar.\n *\n * @param value Scalar to multiply with each band of each pixel.\n */\n public void scale(float value) {\n int w = this.getWidth();\n int h = this.getHeight();\n int b = this.getNumBands();\n float[] thisData = this.getData();\n for (int i=0; i<w*h*b; i++) {\n thisData[i] *= value;\n }\n }\n\n /**\n * Computes hash of float array of image pixel data.\n *\n * @return Hash of pixel data represented as a string.\n *\n * @see ByteUtils#asHex is used to compute the hash.\n */\n @Override\n public String hex() {\n float[] pels = this.getData();\n return ByteUtils.asHex(ByteUtils.floatArrayToByteArray(pels));\n }\n\n /**\n * Helper routine that verifies two images have compatible\n * dimensions for common operations (addition, elementwise\n * multiplication, etc.)\n *\n * @param image RasterImage to check\n * \n * @throws IllegalArgumentException if the image do not have\n * compatible dimensions. Otherwise has no effect.\n */\n protected void checkCompatibleInputImage(FloatImage image) throws IllegalArgumentException {\n if (image.getColorSpace() != this.getColorSpace() || image.getWidth() != this.getWidth() || \n\timage.getHeight() != this.getHeight() || image.getNumBands() != this.getNumBands()) {\n throw new IllegalArgumentException(\"Color space and/or image dimensions do not match.\");\n }\n }\n\n} // public class FloatImage...",
"public class PixelArrayByte extends PixelArray {\n\n byte data[];\n\n public PixelArrayByte(int size) {\n super(TYPE_BYTE, size);\n data = new byte[size];\n }\n\n public PixelArrayByte() {\n super(TYPE_BYTE, 0);\n data = null;\n }\n\n public byte[] getData() {\n return data;\n }\n\n public void setSize(int size) throws IllegalArgumentException {\n if (size < 0) {\n throw new IllegalArgumentException(\"Invalid size of pixel array.\");\n }\n this.size = size;\n if (size == 0) {\n this.data = null;\n } else {\n this.data = new byte[size];\n }\n }\n\n public byte[] getByteArray() {\n return data;\n }\n\n public void setFromByteArray(byte[] bytes) throws IllegalArgumentException {\n if (bytes == null || bytes.length == 0) {\n data = null;\n this.size = 0;\n } else {\n data = bytes;\n this.size = data.length;\n }\n }\n\n public int getElem(int i) {\n return data[i] & 0xff;\n }\n\n public int getElemNonLinSRGB(int i) {\n // Assumes values are stored in gamma compressed non-linear sRGB\n // space\n return getElem(i);\n }\n\n public void setElem(int i, int val) {\n data[i] = (byte)(Math.max(0,Math.min(255,val)));\n } \n\n public void setElemNonLinSRGB(int i, int val) {\n // Assumes values are stored in gamma compressed non-linear sRGB\n // space\n setElem(i,val);\n }\n\n public float getElemFloat(int i) {\n return (float)(data[i] & 0xff)/255.0f;\n }\n\n public void setElemFloat(int i, float val) {\n data[i] = (byte)(((int)Math.max(0.0,Math.min(255.0,val*255.0))) & 0xff);\n }\n\n public double getElemDouble(int i) {\n return (double)(data[i] & 0xff)/255.0;\n }\n\n public void setElemDouble(int i, double val) {\n data[i] = (byte)(((int)Math.max(0.0,Math.min(255.0,val*255.0))) & 0xff);\n }\n\n}",
"public abstract class PixelArray {\n\n public static final int TYPE_BYTE = 0;\n public static final int TYPE_USHORT = 1;\n public static final int TYPE_SHORT = 2;\n public static final int TYPE_INT = 3;\n public static final int TYPE_FLOAT = 4;\n public static final int TYPE_DOUBLE = 5;\n public static final int TYPE_UNDEFINED = 32;\n\n private static final int dataTypeSize[] = {1,2,2,4,4,8};\n\n /**\n * Integer value indicating underlying scalar value data type.\n */\n protected int dataType;\n\n /**\n * Size, in bytes, of a single scalar value in pixel array.\n */\n protected int size;\n\n /**\n * Static function that reports size, in bytes, of a single scalar value for different types\n * of pixel arrays.\n *\n * @param type scalar value type\n *\n * @return size, in bytes, of single scalar value for specified type\n */\n public static int getDataTypeSize(int type) {\n if (type < TYPE_BYTE || type > TYPE_DOUBLE) {\n throw new IllegalArgumentException(\"Unknown data type \"+type);\n }\n return dataTypeSize[type];\n }\n\n public PixelArray() {\n this.dataType = TYPE_UNDEFINED;\n this.size = 0;\n }\n\n protected PixelArray(int dataType, int size) {\n this.dataType = dataType;\n this.size = size;\n }\n\n public int getDataType() {\n return dataType;\n }\n\n public int getSize() {\n return size;\n }\n\n public abstract void setSize(int size) throws IllegalArgumentException;\n\n public abstract byte[] getByteArray();\n\n public abstract void setFromByteArray(byte[] bytes) throws IllegalArgumentException;\n\n public abstract int getElem(int i);\n\n public abstract int getElemNonLinSRGB(int i);\n\n public abstract void setElem(int i, int val);\n\n public abstract void setElemNonLinSRGB(int i, int val);\n\n public float getElemFloat(int i) {\n return (float)getElem(i);\n }\n\n public void setElemFloat(int i, float val) {\n setElem(i,(int)val);\n }\n\n public double getElemDouble(int i) {\n return (double)getElem(i);\n }\n\n public void setElemDouble(int i, double val) {\n setElem(i,(int)val);\n }\n\n}",
"public class HipiImageFactory {\n\n private static final HipiImageFactory staticFloatImageFactory = \n new HipiImageFactory(HipiImageType.FLOAT);\n\n public static HipiImageFactory getFloatImageFactory() {\n return staticFloatImageFactory;\n }\n\n private static final HipiImageFactory staticByteImageFactory = \n new HipiImageFactory(HipiImageType.BYTE);\n\n public static HipiImageFactory getByteImageFactory() {\n return staticByteImageFactory;\n }\n\n private Class<?> imageClass = null;\n private HipiImageType imageType = HipiImageType.UNDEFINED;\n\n public HipiImageFactory(Class<? extends Mapper<?,?,?,?>> mapperClass)\n throws InstantiationException,\n\t IllegalAccessException,\n\t ExceptionInInitializerError,\n\t SecurityException,\n\t RuntimeException {\n\n findImageClass(mapperClass);\n \n HipiImage image = (HipiImage)imageClass.newInstance();\n imageType = image.getType();\n }\n\n public HipiImageFactory(HipiImageType imageType)\n throws IllegalArgumentException {\n\n\t// Call appropriate decode function based on type of image object\n switch (imageType) {\n\tcase FLOAT:\n\t imageClass = FloatImage.class;\n\t break;\n\tcase BYTE:\n\t imageClass = ByteImage.class;\n\t break;\n\tcase RAW:\n imageClass = RawImage.class;\n\tcase UNDEFINED:\n\tdefault:\n\t throw new IllegalArgumentException(\"Unexpected image type. Cannot proceed.\");\n\t}\n\n this.imageType = imageType;\n }\n\n private void findImageClass(Class<? extends Mapper<?,?,?,?>> mapperClass) \n throws SecurityException,\n\t RuntimeException {\n\n for (Method method : mapperClass.getMethods()) {\n // Find map method (there will be at least two: one in concrete\n // base class and one in abstract Mapper superclass)\n if (!method.getName().equals(\"map\")) {\n\tcontinue;\n }\n \n // Get parameter list of map method\n Class<?> params[] = method.getParameterTypes();\n if (params.length != 3) {\n\tcontinue;\n }\n\n // Use the fact that first parameter should be ImageHeader\n // object to identify target map method\n if (params[0] != HipiImageHeader.class) {\n\tcontinue;\n }\n \n // Store pointer to requested image class\n imageClass = params[1];\n }\n \n if (imageClass == null) {\n throw new RuntimeException(\"Failed to determine image class used in \" +\n \"mapper (second argument in map method).\");\n }\n\n if (!HipiImage.class.isAssignableFrom(imageClass)) {\n throw new RuntimeException(\"Found image class [\" + imageClass + \"], but it's not \" +\n \"derived from HipiImage as required.\");\n }\n\n }\n\n public HipiImageType getType() {\n return imageType;\n }\n \n public HipiImage createImage(HipiImageHeader imageHeader)\n throws InstantiationException,\n\t IllegalAccessException,\n\t ExceptionInInitializerError,\n\t SecurityException,\n\t IllegalArgumentException {\n \n HipiImage image = (HipiImage)imageClass.newInstance();\n image.setHeader(imageHeader);\n return image;\n \n }\n\n}",
"public class HipiImageHeader implements WritableComparable<HipiImageHeader> {\n\n /**\n * Enumeration of the image storage formats supported in HIPI (e.g, JPEG, PNG, etc.).\n */\n public enum HipiImageFormat {\n UNDEFINED(0x0), JPEG(0x1), PNG(0x2), PPM(0x3);\n\n private int format;\n\n /**\n * Creates an ImageFormat from an int.\n *\n * @param format Integer representation of ImageFormat.\n */\n HipiImageFormat(int format) {\n this.format = format;\n }\n\n /**\n * Creates an ImageFormat from an int.\n *\n * @param format Integer representation of ImageFormat.\n *\n * @return Associated ImageFormat.\n *\n * @throws IllegalArgumentException if the parameter value does not correspond to a valid\n * HipiImageFormat.\n */\n public static HipiImageFormat fromInteger(int format) throws IllegalArgumentException {\n for (HipiImageFormat fmt : values()) {\n if (fmt.format == format) {\n return fmt;\n }\n }\n throw new IllegalArgumentException(String.format(\"There is no HipiImageFormat enum value \" +\n \"associated with integer [%d]\", format));\n }\n\n /** \n * @return Integer representation of ImageFormat.\n */\n public int toInteger() {\n return format;\n }\n\n /**\n * Default HipiImageFormat.\n *\n * @return HipiImageFormat.UNDEFINED\n */\n public static HipiImageFormat getDefault() {\n return UNDEFINED;\n }\n\n } // public enum ImageFormat\n\n /**\n * Enumeration of the color spaces supported in HIPI.\n */\n public enum HipiColorSpace {\n UNDEFINED(0x0), RGB(0x1), LUM(0x2);\n\n private int cspace;\n\n /**\n * Creates a HipiColorSpace from an int\n *\n * @param format Integer representation of ColorSpace.\n */\n HipiColorSpace(int cspace) {\n this.cspace = cspace;\n }\n\n /**\n * Creates a HipiColorSpace from an int.\n *\n * @param cspace Integer representation of ColorSpace.\n *\n * @return Associated HipiColorSpace value.\n *\n * @throws IllegalArgumentException if parameter does not correspond to a valid HipiColorSpace.\n */\n public static HipiColorSpace fromInteger(int cspace) throws IllegalArgumentException {\n for (HipiColorSpace cs : values()) {\n if (cs.cspace == cspace) {\n\t return cs;\n }\n }\n throw new IllegalArgumentException(String.format(\"There is no HipiColorSpace enum value \" +\n \"with an associated integer value of %d\", cspace));\n }\n\n /** \n * Integer representation of ColorSpace.\n *\n * @return Integer representation of ColorSpace.\n */\n public int toInteger() {\n return cspace;\n }\n\n /**\n * Default HipiColorSpace. Currently (linear) RGB.\n *\n * @return Default ColorSpace enum value.\n */\n public static HipiColorSpace getDefault() {\n return RGB;\n }\n\n } // public enum ColorSpace\n\n private HipiImageFormat storageFormat; // format used to store image on HDFS\n private HipiColorSpace colorSpace; // color space of pixel data\n private int width; // width of image\n private int height; // height of image\n private int bands; // number of color bands (aka channels)\n\n /**\n * A map containing key/value pairs of meta data associated with the\n * image. These are (optionally) added during HIB construction and\n * are distinct from the exif data that may be stored within the\n * image file, which is accessed through the IIOMetadata object. For\n * example, this would be the correct place to store the image tile\n * offset and size if you were using a HIB to store a very large\n * image as a collection of smaller image tiles. Another example\n * would be using this dictionary to store the source url for an\n * image downloaded from the Internet.\n */\n private Map<String, String> metaData = new HashMap<String,String>();\n\n /**\n * EXIF data associated with the image represented as a\n * HashMap. {@see hipi.image.io.ExifDataUtils}\n */\n private Map<String, String> exifData = new HashMap<String,String>();\n\n /**\n * Creates an ImageHeader.\n */\n public HipiImageHeader(HipiImageFormat storageFormat, HipiColorSpace colorSpace, \n\t\t\t int width, int height,\n\t\t\t int bands, byte[] metaDataBytes, Map<String,String> exifData)\n throws IllegalArgumentException {\n if (width < 1 || height < 1 || bands < 1) {\n throw new IllegalArgumentException(String.format(\"Invalid spatial dimensions or number \" + \n \"of bands: (%d,%d,%d)\", width, height, bands));\n }\n this.storageFormat = storageFormat;\n this.colorSpace = colorSpace;\n this.width = width;\n this.height = height;\n this.bands = bands;\n if (metaDataBytes != null) {\n setMetaDataFromBytes(metaDataBytes);\n }\n this.exifData = exifData;\n }\n\n /**\n * Creates an ImageHeader by calling #readFields on the data input\n * object. Note that this function does not populate the exifData\n * field. That must be done with a separate method call.\n */\n public HipiImageHeader(DataInput input) throws IOException {\n readFields(input);\n }\n\n /**\n * Get the image storage type.\n *\n * @return Current image storage type.\n */\n public HipiImageFormat getStorageFormat() {\n return storageFormat;\n }\n\n /**\n * Get the image color space.\n *\n * @return Image color space.\n */\n public HipiColorSpace getColorSpace() {\n return colorSpace;\n }\n\n /**\n * Get width of image.\n *\n * @return Width of image.\n */\n public int getWidth() {\n return width;\n }\n\n /**\n * Get height of image.\n *\n * @return Height of image.\n */\n public int getHeight() {\n return height;\n }\n\n /**\n * Get number of color bands.\n *\n * @return Number of image bands.\n */\n public int getNumBands() {\n return bands;\n }\n\n /**\n * Adds an metadata field to this header object. The information consists of a\n * key-value pair where the key is an application-specific field name and the \n * value is the corresponding information for that field.\n * \n * @param key\n * the metadata field name\n * @param value\n * the metadata information\n */\n public void addMetaData(String key, String value) {\n metaData.put(key, value);\n }\n\n /**\n * Sets the entire metadata map structure.\n *\n * @param metaData hash map containing the metadata key/value pairs\n */\n public void setMetaData(HashMap<String, String> metaData) {\n this.metaData = new HashMap<String, String>(metaData);\n }\n\n /**\n * Attempt to retrieve metadata value associated with key.\n *\n * @param key field name of the desired metadata record\n * @return either the value corresponding to the key or null if the\n * key was not found\n */\n public String getMetaData(String key) {\n return metaData.get(key);\n }\n\n /**\n * Get the entire list of all metadata that applications have\n * associated with this image.\n *\n * @return a hash map containing the keys and values of the metadata\n */\n public HashMap<String, String> getAllMetaData() {\n return new HashMap<String, String>(metaData);\n }\n\n /**\n * Create a binary representation of the application-specific\n * metadata, ready to be serialized into a HIB file.\n *\n * @return A byte array containing the serialized hash map\n */\n public byte[] getMetaDataAsBytes() {\n try {\n String jsonText = JSONValue.toJSONString(metaData);\n final byte[] utf8Bytes = jsonText.getBytes(\"UTF-8\");\n return utf8Bytes;\n } catch (java.io.UnsupportedEncodingException e) {\n System.err.println(\"UTF-8 encoding exception in getMetaDataAsBytes()\");\n return null;\n }\n }\n\n /**\n * Recreates the general metadata from serialized bytes, usually\n * from the beginning of a HIB file.\n *\n * @param utf8Bytes UTF-8-encoded bytes of a JSON object\n * representing the data\n */\n @SuppressWarnings(\"unchecked\")\n public void setMetaDataFromBytes(byte[] utf8Bytes) {\n try {\n String jsonText = new String(utf8Bytes, \"UTF-8\");\n JSONObject jsonObject = (JSONObject)JSONValue.parse(jsonText);\n metaData = (HashMap)jsonObject;\n } catch (java.io.UnsupportedEncodingException e) {\n System.err.println(\"UTF-8 encoding exception in setMetaDataAsBytes()\");\n }\n }\n\n /**\n * Attempt to retrieve EXIF data value for specific key.\n *\n * @param key field name of the desired EXIF data record\n * @return either the value corresponding to the key or null if the\n * key was not found\n */\n public String getExifData(String key) {\n return exifData.get(key);\n }\n\n /**\n * Get the entire map of EXIF data.\n *\n * @return a hash map containing the keys and values of the metadata\n */\n public HashMap<String, String> getAllExifData() {\n return new HashMap<String, String>(exifData);\n }\n\n /**\n * Sets the entire EXIF data map structure.\n *\n * @param exifData hash map containing the EXIF data key/value pairs\n */\n public void setExifData(HashMap<String, String> exifData) {\n this.exifData = new HashMap<String, String>(exifData);\n }\n\n /**\n * Sets the current object to be equal to another\n * ImageHeader. Performs deep copy of meta data.\n *\n * @param header Target image header.\n */\n public void set(HipiImageHeader header) {\n this.storageFormat = header.getStorageFormat();\n this.colorSpace = header.getColorSpace();\n this.width = header.getWidth();\n this.height = header.getHeight();\n this.bands = header.getNumBands();\n this.metaData = header.getAllMetaData();\n this.exifData = header.getAllExifData();\n }\n\n /**\n * Produce readable string representation of header.\n * @see java.lang.Object#toString\n */\n @Override\n public String toString() {\n String metaText = JSONValue.toJSONString(metaData);\n return String.format(\"ImageHeader: (%d %d) %d x %d x %d meta: %s\", \n\t\t\t storageFormat.toInteger(), colorSpace.toInteger(), width, height, bands, metaText);\n } \n\n /**\n * Serializes the HipiImageHeader object into a simple uncompressed binary format using the\n * {@link java.io.DataOutput} interface.\n *\n * @see #readFields\n * @see org.apache.hadoop.io.WritableComparable#write\n */\n @Override\n public void write(DataOutput out) throws IOException {\n out.writeInt(storageFormat.toInteger());\n out.writeInt(colorSpace.toInteger());\n out.writeInt(width);\n out.writeInt(height);\n out.writeInt(bands);\n byte[] metaDataBytes = getMetaDataAsBytes();\n if (metaDataBytes == null || metaDataBytes.length == 0) {\n out.writeInt(0);\n } else {\n out.writeInt(metaDataBytes.length);\n out.write(metaDataBytes);\n }\n }\n\n /**\n * Deserializes HipiImageHeader object stored in a simple uncompressed binary format using the\n * {@link java.io.DataInput} interface. The first twenty bytes are the image storage type,\n * color space, width, height, and number of color bands (aka channels), all stored as ints,\n * followed by the meta data stored as a set of key/value pairs in JSON UTF-8 format.\n *\n * @see org.apache.hadoop.io.WritableComparable#readFields\n */\n @Override\n public void readFields(DataInput input) throws IOException {\n this.storageFormat = HipiImageFormat.fromInteger(input.readInt());\n this.colorSpace = HipiColorSpace.fromInteger(input.readInt());\n this.width = input.readInt();\n this.height = input.readInt();\n this.bands = input.readInt();\n int len = input.readInt();\n if (len > 0) {\n byte[] metaDataBytes = new byte[len];\n input.readFully(metaDataBytes, 0, len);\n setMetaDataFromBytes(metaDataBytes);\n }\n }\n\n /**\n * Compare method inherited from the {@link java.lang.Comparable} interface. This method is\n * currently incomplete and uses only the storage format to determine order.\n *\n * @param that another {@link HipiImageHeader} to compare with the current object\n *\n * @return An integer result of the comparison.\n *\n * @see java.lang.Comparable#compareTo\n */\n @Override\n public int compareTo(HipiImageHeader that) {\n\n int thisFormat = this.storageFormat.toInteger();\n int thatFormat = that.storageFormat.toInteger();\n\n return (thisFormat < thatFormat ? -1 : (thisFormat == thatFormat ? 0 : 1));\n }\n\n /**\n * Hash method inherited from the {@link java.lang.Object} base class. This method is\n * currently incomplete and uses only the storage format to determine this hash.\n *\n * @return hash code for this object\n *\n * @see java.lang.Object#hashCode\n */\n @Override\n public int hashCode() {\n return this.storageFormat.toInteger();\n }\n\n}",
"public interface ImageDecoder {\n\n /**\n * Read and decode header for image accessed through a Java {@link java.io.InputStream}.\n * Optionally extracts image EXIF data, if available.\n *\n * @param inputStream input stream containing serialized image data\n * @param includeExifData if true attempts to extract image EXIF data\n *\n * @return image header data represented as a {@link HipiImageHeader}\n *\n * @throws IOException if an error is encountered while reading from input stream\n */\n public HipiImageHeader decodeHeader(InputStream inputStream, boolean includeExifData)\n throws IOException;\n\n /**\n * Read and decode header for image accessed through a Java {@link java.io.InputStream}.\n * Does not attempt to extract image EXIF data. Default implementation in {@link ImageCodec}\n * calls {@link ImageDecoder#decodeHeader} with includeExifData parameter set to false.\n *\n * @param inputStream input stream containing serialized image data\n *\n * @return image header data represented as a {@link HipiImageHeader}\n *\n * @throws IOException if an error is encountered while reading from input stream\n */\n public HipiImageHeader decodeHeader(InputStream inputStream) throws IOException;\n\n /**\n * Read and decode image from a Java {@link java.io.InputStream}.\n *\n * @param inputStream input stream containing serialized image data\n * @param imageHeader image header that was previously initialized\n * @param imageFactory factory object capable of creating objects of desired HipiImage type\n * @param includeExifData if true attempts to extract image EXIF data\n *\n * @return image represented as a {@link HipiImage}\n *\n * @throws IllegalArgumentException if parameters are invalid or do not agree with image data\n * @throws IOException if an error is encountered while reading from the input stream\n */\n public HipiImage decodeImage(InputStream inputStream, HipiImageHeader imageHeader, \n\t\t\t HipiImageFactory imageFactory, boolean includeExifData)\n throws IllegalArgumentException, IOException;\n\n /**\n * Read and decode both image header and image pixel data from a Java {@link java.io.InputStream}.\n * Both of these decoded objects can be accessed through the {@link HipiImage} object returned\n * by this method. See default implementation in {@link ImageCodec}.\n *\n * @param inputStream input stream containing serialized image data\n * @param imageFactory factory object capable of creating objects of desired HipiImage type\n * @param includeExifData if true attempts to extract image EXIF data\n *\n * @return image represented as a {@link HipiImage}\n *\n * @throws IllegalArgumentException if parameters are invalid\n * @throws IOException if an error is encountered while reading from the input stream\n */\n public HipiImage decodeHeaderAndImage(InputStream inputStream,\n HipiImageFactory imageFactory, boolean includeExifData) \n throws IOException, IllegalArgumentException; \n\n}",
"public class JpegCodec extends ImageCodec {\n\n private static final JpegCodec staticObject = new JpegCodec();\n\n public static JpegCodec getInstance() {\n return staticObject;\n }\n\n public HipiImageHeader decodeHeader(InputStream inputStream, boolean includeExifData) \n throws IOException, IllegalArgumentException {\n\n DataInputStream dis = new DataInputStream(new BufferedInputStream(inputStream));\n dis.mark(Integer.MAX_VALUE);\n \n // all JPEGs start with -40\n short magic = dis.readShort();\n if (magic != -40)\n return null;\n\n int width=0, height=0, depth=0;\n \n byte[] data = new byte[6];\n \n // read in each block to determine resolution and bit depth\n for (;;) {\n dis.read(data, 0, 4);\n if ((data[0] & 0xff) != 0xff)\n\treturn null;\n if ((data[1] & 0xff) == 0x01 || ((data[1] & 0xff) >= 0xd0 && (data[1] & 0xff) <= 0xd7))\n\tcontinue;\n long length = (((data[2] & 0xff) << 8) | (data[3] & 0xff)) - 2;\n if ((data[1] & 0xff) == 0xc0 || (data[1] & 0xff) == 0xc2) {\n\tdis.read(data);\n\theight = ((data[1] & 0xff) << 8) | (data[2] & 0xff);\n\twidth = ((data[3] & 0xff) << 8) | (data[4] & 0xff);\n\tdepth = data[0] & 0xff;\n\tbreak;\n } else {\n\twhile (length > 0) {\n\t long skipped = dis.skip(length);\n\t if (skipped == 0)\n\t break;\n\t length -= skipped;\n\t}\n }\n }\n \n if (depth != 8) {\n throw new IllegalArgumentException(String.format(\"Image has unsupported bit depth [%d].\", depth));\n }\n\n HashMap<String,String> exifData = null;\n if (includeExifData) {\n dis.reset();\n exifData = ExifDataReader.extractAndFlatten(dis);\n }\n \n return new HipiImageHeader(HipiImageFormat.JPEG, HipiColorSpace.RGB, \n\t\t\t width, height, 3, null, exifData);\n }\n\n public void encodeImage(HipiImage image, OutputStream outputStream) throws IllegalArgumentException, IOException {\n\n if (!(RasterImage.class.isAssignableFrom(image.getClass()))) {\n throw new IllegalArgumentException(\"JPEG encoder supports only RasterImage input types.\");\n } \n\n if (image.getWidth() <= 0 || image.getHeight() <= 0) {\n throw new IllegalArgumentException(\"Invalid image resolution.\");\n }\n if (image.getColorSpace() != HipiColorSpace.RGB) {\n throw new IllegalArgumentException(\"JPEG encoder supports only RGB color space.\");\n }\n if (image.getNumBands() != 3) {\n throw new IllegalArgumentException(\"JPEG encoder supports only three band images.\");\n }\n\n // Find suitable JPEG writer in javax.imageio.ImageReader\n ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);\n Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(\"jpeg\");\n ImageWriter writer = writers.next();\n System.out.println(\"Using JPEG encoder: \" + writer);\n writer.setOutput(ios);\n\n ImageWriteParam param = writer.getDefaultWriteParam();\n param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n param.setCompressionQuality(0.95F); // highest JPEG quality = 1.0F\n\n encodeRasterImage((RasterImage)image, writer, param);\n }\n\n}",
"public class PpmCodec extends ImageCodec {\n \n private static final PpmCodec staticObject = new PpmCodec();\n\t\n public static PpmCodec getInstance() {\n return staticObject;\n }\n\n private class PpmHeader {\n\n public int width;\n public int height;\n public int numBands;\n public int maxValue;\n public ArrayList<String> comments = new ArrayList<String>();\n public int streamOffset; // byte offset to start of image data\n public byte[] headerBytes = new byte[255];\n\n } // private class PpmHeader\n\n private PpmHeader internalDecodeHeader(InputStream inputStream) throws IOException {\n\n PpmHeader ppmHeader = new PpmHeader();\n ppmHeader.numBands = 3;\n\n inputStream.read(ppmHeader.headerBytes);\n \n // Only P6 supported.\n if (ppmHeader.headerBytes[0] != 'P' || ppmHeader.headerBytes[1] != '6') {\n byte[] format = new byte[2];\n format[0] = ppmHeader.headerBytes[0];\n format[1] = ppmHeader.headerBytes[1];\n throw new IOException(String.format(\"PPM file has invalid or unsupported format [%s]. Only P6 is currently supported.\", new String(format, \"UTF-8\")));\n }\n \n int off = 3;\n \n // TODO: Fix this totally broken way to parse header. It assumes\n // the header ends after the third integer is parsed. This ignores\n // valid comment structure.\n \n ppmHeader.width = 0;\n while (ppmHeader.headerBytes[off] >= '0' && \n\t ppmHeader.headerBytes[off] <= '9') {\n ppmHeader.width = ppmHeader.width * 10 + (ppmHeader.headerBytes[off++] - '0');\n }\n off++;\n\n ppmHeader.height = 0;\n while (ppmHeader.headerBytes[off] >= '0' && \n\t ppmHeader.headerBytes[off] <= '9') {\n ppmHeader.height = ppmHeader.height * 10 + (ppmHeader.headerBytes[off++] - '0');\n }\n off++;\n\n ppmHeader.maxValue = 0;\n while (ppmHeader.headerBytes[off] >= '0' && \n\t ppmHeader.headerBytes[off] <= '9') {\n ppmHeader.maxValue = ppmHeader.maxValue * 10 + (ppmHeader.headerBytes[off++] - '0');\n }\n off++;\n\n ppmHeader.streamOffset = off;\n \n // TODO: Add support for extracting header comments and return in\n // List<String> comments field.\n \n return ppmHeader;\n\n }\n\n public HipiImageHeader decodeHeader(InputStream inputStream, boolean includeExifData) \n throws IOException, IllegalArgumentException {\n\n PpmHeader ppmHeader = internalDecodeHeader(inputStream);\n\n if (ppmHeader.maxValue != 255) {\n throw new IOException(String.format(\"Only 8-bit PPMs are currently supported. Max value reported in PPM header is [%d].\", ppmHeader.maxValue));\n }\n\n if (includeExifData) {\n // TODO: Eventually, populate exifData map with comments\n // extracted from PPM header.\n throw new IllegalArgumentException(\"Support for extracting EXIF data from PPM files not implemented.\");\n }\n\n return new HipiImageHeader(HipiImageFormat.PPM, HipiColorSpace.RGB,\n\t\t\t ppmHeader.width, ppmHeader.height, 3, null, null);\n }\n\n /*\n public HipiImage decodeImage(InputStream inputStream, HipiImageHeader imageHeader,\n\t\t\t HipiImageFactory imageFactory) throws IllegalArgumentException, IOException {\n\n if (!(imageFactory.getType() == HipiImageType.FLOAT || imageFactory.getType() == HipiImageType.BYTE)) {\n throw new IllegalArgumentException(\"PPM decoder supports only FloatImage and ByteImage output types.\");\n }\n\n PpmHeader ppmHeader = internalDecodeHeader(inputStream);\n\n if (ppmHeader.maxValue != 255) {\n throw new IOException(String.format(\"Only 8-bit PPMs are currently supported. Max value reported in PPM header is [%d].\", ppmHeader.maxValue));\n }\n\n // Check that image dimensions in header match those in JPEG\n if (ppmHeader.width != imageHeader.getWidth() || \n\tppmHeader.height != imageHeader.getHeight()) {\n throw new IllegalArgumentException(\"Image dimensions in header do not match those in PPM.\");\n }\n\n if (ppmHeader.numBands != imageHeader.getNumBands()) {\n throw new IllegalArgumentException(\"Number of image bands specified in header does not match number found in PPM.\");\n }\n\n int off = ppmHeader.streamOffset;\n\n // Create output image\n RasterImage image = null;\n try {\n image = (RasterImage)imageFactory.createImage(imageHeader);\n } catch (Exception e) {\n System.err.println(String.format(\"Unrecoverable exception while creating image object [%s]\", e.getMessage()));\n e.printStackTrace();\n System.exit(1);\n }\n\n PixelArray pa = image.getPixelArray();\n\n int w = imageHeader.getWidth();\n int h = imageHeader.getHeight();\n\n byte[] rest = new byte[w * h * 3 - (255 - off)];\n inputStream.read(rest);\n\n for (int i = 0; i < 255 - off; i++) {\n pa.setElemNonLinSRGB(i, ppmHeader.headerBytes[i + off] & 0xff);\n }\n\n for (int i = 0; i < w * h * 3 - (255 - off); i++) {\n pa.setElemNonLinSRGB(i + 255 - off, rest[i] & 0xff);\n }\n\n return image;\n }\n */\n\n public void encodeImage(HipiImage image, OutputStream outputStream) throws IllegalArgumentException, IOException {\n\n if (!(RasterImage.class.isAssignableFrom(image.getClass()))) {\n throw new IllegalArgumentException(\"PPM encoder supports only RasterImage input types.\");\n } \n\n if (image.getWidth() <= 0 || image.getHeight() <= 0) {\n throw new IllegalArgumentException(\"Invalid image resolution.\");\n }\n if (image.getColorSpace() != HipiColorSpace.RGB) {\n throw new IllegalArgumentException(\"PPM encoder supports only linear RGB color space.\");\n }\n if (image.getNumBands() != 3) {\n throw new IllegalArgumentException(\"PPM encoder supports only three band images.\");\n }\n\n int w = image.getWidth();\n int h = image.getHeight();\n\n // http://netpbm.sourceforge.net/doc/ppm.html\n PrintWriter writer = new PrintWriter(outputStream);\n writer.print(\"P6\\r\");\n writer.print(w + \" \" + h + \"\\r\");\n writer.print(\"255\\r\");\n writer.flush();\n\n PixelArray pa = ((RasterImage)image).getPixelArray();\n\n byte[] raw = new byte[w*h*3];\n for (int i=0; i<w*h*3; i++) {\n raw[i] = (byte)pa.getElemNonLinSRGB(i);\n }\n\n outputStream.write(raw);\n\n }\n\n}"
] | import static org.junit.Assert.*;
import static org.junit.Assume.*;
import org.hipi.image.HipiImage;
import org.hipi.image.RasterImage;
import org.hipi.image.ByteImage;
import org.hipi.image.FloatImage;
import org.hipi.image.PixelArrayByte;
import org.hipi.image.PixelArrayFloat;
import org.hipi.image.PixelArray;
import org.hipi.image.HipiImageFactory;
import org.hipi.image.HipiImageHeader;
import org.hipi.image.io.ImageDecoder;
import org.hipi.image.io.ImageEncoder;
import org.hipi.image.io.JpegCodec;
import org.hipi.image.io.PpmCodec;
import org.hipi.util.ByteUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.ArrayUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Ignore;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.ColorConvertOp;
import java.awt.color.ColorSpace;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.System;
import java.util.Scanner;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream; | package org.hipi.test;
public class JpegCodecTestCase {
@BeforeClass
public static void setup() throws IOException {
TestUtils.setupTmpDirectory();
}
private void printExifData(HipiImage image) {
// display EXIF data
for (String key : image.getAllExifData().keySet()) {
String value = image.getExifData(key);
System.out.println(key + " : " + value);
}
}
@Test
public void testTwelveMonkeysPlugIn() {
boolean foundTwelveMonkeys = false;
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG");
while (readers.hasNext()) {
ImageReader imageReader = readers.next();
// System.out.println("ImageReader: " + imageReader);
if (imageReader.toString().startsWith("com.twelvemonkeys.imageio.plugins.jpeg")) {
foundTwelveMonkeys = true;
}
}
assertTrue("FATAL ERROR: failed to locate TwelveMonkeys ImageIO plugins", foundTwelveMonkeys);
}
/**
* Test method for {@link hipi.image.io.JpegCodec#decodeHeader(java.io.InputStream)}.
*
* @throws IOException
*/
@Test
public void testDecodeHeader() throws IOException {
ImageDecoder decoder = JpegCodec.getInstance();
String[] fileName =
{"canon-ixus", "fujifilm-dx10", "fujifilm-finepix40i", "fujifilm-mx1700", "kodak-dc210",
"kodak-dc240", "nikon-e950", "olympus-c960", "ricoh-rdc5300", "sanyo-vpcg250",
"sanyo-vpcsx550", "sony-cybershot", "sony-d700", "fujifilm-x100s"};
String[] model =
{"Canon DIGITAL IXUS", "DX-10", "FinePix40i", "MX-1700ZOOM", "DC210 Zoom (V05.00)",
"KODAK DC240 ZOOM DIGITAL CAMERA", "E950", "C960Z,D460Z", "RDC-5300", "SR6", "SX113",
"CYBERSHOT", "DSC-D700", "X100S"};
int[] width = {640, 1024, 600, 640, 640, 640, 800, 640, 896, 640, 640, 640, 672, 3456};
int[] height = {480, 768, 450, 480, 480, 480, 600, 480, 600, 480, 480, 480, 512, 2304};
for (int i = 0; i < fileName.length; i++) {
String fname = "../testdata/jpeg-exif-test/" + fileName[i] + ".jpg";
FileInputStream fis = new FileInputStream(fname);
HipiImageHeader header = decoder.decodeHeader(fis, true);
assertNotNull("failed to decode header: " + fname, header);
assertEquals("exif model not correct: " + fname, model[i].trim(),
header.getExifData("Model").trim());
assertEquals("width not correct: " + fname, width[i], header.getWidth());
assertEquals("height not correct: " + fname, height[i], header.getHeight());
}
}
@Test
public void testSRGBConversions() throws IOException {
ImageDecoder jpegDecoder = JpegCodec.getInstance();
ImageEncoder ppmEncoder = PpmCodec.getInstance();
File[] cmykFiles = new File("../testdata/jpeg-cmyk").listFiles();
File[] rgbFiles = new File("../testdata/jpeg-rgb").listFiles();
File[] files = (File[])ArrayUtils.addAll(cmykFiles,rgbFiles);
for (File file : files) {
String ext = FilenameUtils.getExtension(file.getName());
if (file.isFile() && ext.equalsIgnoreCase("jpg")) {
String jpgPath = file.getPath();
String ppmPath = FilenameUtils.removeExtension(file.getPath()) + "_hipi.ppm";
System.out.println("Testing linear RGB color conversion for: " + jpgPath);
// Using FloatImage forces conversion from non-linear sRGB to linear RGB by default
FloatImage jpegImage = (FloatImage)jpegDecoder.decodeHeaderAndImage(
new FileInputStream(jpgPath), HipiImageFactory.getFloatImageFactory(), true);
assertNotNull(jpegImage);
BufferedImage javaImage = ImageIO.read(new FileInputStream(jpgPath));
assertNotNull(javaImage);
ColorSpace ics = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
ColorConvertOp cco = new ColorConvertOp(ics, null);
BufferedImage rgbImage = cco.filter(javaImage, null);
assertNotNull(rgbImage);
Raster raster = rgbImage.getData();
DataBuffer dataBuffer = raster.getDataBuffer();
int w = raster.getWidth();
int h = raster.getHeight();
assertEquals(w,jpegImage.getWidth());
assertEquals(h,jpegImage.getHeight());
assertEquals(3,raster.getNumBands());
ppmEncoder.encodeImage(jpegImage, new FileOutputStream(ppmPath));
System.out.println("wrote: " + ppmPath);
String truthPath = FilenameUtils.removeExtension(file.getPath()) + "_photoshop.ppm";
Runtime rt = Runtime.getRuntime();
String cmd = "compare -metric PSNR " + ppmPath + " " + truthPath + " " +
TestUtils.getTmpPath("psnr.png");
System.out.println(cmd);
Process pr = rt.exec(cmd);
Scanner scanner = new Scanner(new InputStreamReader(pr.getErrorStream()));
float psnr = scanner.hasNextFloat() ? scanner.nextFloat() : 0;
System.out.println("PSNR with respect to Photoshop ground truth: " + psnr);
assertTrue("PSNR is too low : " + psnr, psnr > 30);
}
}
}
@Test
public void testDecodeImage() throws IOException {
ImageDecoder jpegDecoder = JpegCodec.getInstance();
ImageDecoder ppmDecoder = PpmCodec.getInstance();
File[] cmykFiles = new File("../testdata/jpeg-cmyk").listFiles();
// File[] rgbFiles = new File("./testimages/jpeg-rgb").listFiles();
File[] rgbFiles = null;
File[] files = (File[])ArrayUtils.addAll(cmykFiles,rgbFiles);
for (int iter=0; iter<=1; iter++) {
for (File file : files) {
String ext = FilenameUtils.getExtension(file.getName());
if (file.isFile() && ext.equalsIgnoreCase("jpg")) {
String jpgPath = file.getPath();
String ppmPath = FilenameUtils.removeExtension(file.getPath()) + "_photoshop.ppm";
System.out.println("Testing JPEG decoder (" + (iter == 0 ? "ByteImage" : "FloatImage") + ") for: " + jpgPath);
FileInputStream fis = new FileInputStream(ppmPath);
RasterImage ppmImage = (RasterImage)ppmDecoder.decodeHeaderAndImage(fis, (iter == 0 ? HipiImageFactory.getByteImageFactory() : HipiImageFactory.getFloatImageFactory()), false);
assumeNotNull(ppmImage);
fis = new FileInputStream(jpgPath);
RasterImage jpegImage = (RasterImage)jpegDecoder.decodeHeaderAndImage(fis, (iter == 0 ? HipiImageFactory.getByteImageFactory() : HipiImageFactory.getFloatImageFactory()), true);
assumeNotNull(jpegImage);
float maxDiff = (iter == 0 ? 45.0f : 45.0f/255.0f);
if (!ppmImage.equalsWithTolerance((RasterImage)jpegImage, maxDiff)) { // allow 3 8-bit values difference to account for color space conversion
System.out.println(ppmImage);
System.out.println(jpegImage);
// Get pointers to pixel arrays | PixelArray ppmPA = ppmImage.getPixelArray(); | 2 |
MazeSolver/MazeSolver | src/es/ull/mazesolver/agent/DStarAgent.java | [
"public interface BlackboardCommunication {\n /**\n * Obtiene la pizarra asociada al agente.\n *\n * @return Pizarra que contiene actualmente el agente.\n */\n public Object getBlackboard ();\n\n /**\n * Cambia la pizarra que tiene el agente.\n *\n * @param blackboard\n * Nueva pizarra para el agente.\n */\n public void setBlackboard (Object blackboard);\n}",
"public abstract class AgentConfigurationPanel extends JPanel implements Translatable {\n private static final long serialVersionUID = 1L;\n\n private JPanel m_root;\n private ArrayList <EventListener> m_listeners;\n private JButton m_accept, m_cancel;\n\n /**\n * Agente que se quiere configurar.\n */\n protected Agent m_agent;\n\n /**\n * Lista de mensajes de error obtenidos al intentar guardar la configuración\n * de un agente.\n */\n protected ArrayList <String> m_errors;\n\n /**\n * Lista de mensajes de éxito obtenidos tras guardar la configuración de un\n * agente.\n */\n protected ArrayList <String> m_success;\n\n /**\n * Interfaz de escucha de eventos.\n */\n public static interface EventListener {\n /**\n * LLamado cuando ocurre el evento de tipo \"Exitoso\". Estos eventos son\n * notificados cuando se guarda el agente y el cambio es aceptado.\n *\n * @param msgs\n * Lista de mensajes que se quieren mostrar al usuario.\n */\n public void onSuccess (ArrayList <String> msgs);\n\n /**\n * LLamado cuando ocurre el evento de tipo \"Cancelar\". Estos eventos son\n * notificados cuando se cancela la edición de las propiedades.\n */\n public void onCancel ();\n\n /**\n * LLamado cuando ocurre el evento de tipo \"Error\". Estos eventos son\n * notificados cuando se intenta guardar y no se aceptan las modificaciones.\n *\n * @param errors\n * Lista de mensajes de error a mostrar al usuario.\n */\n public void onError (ArrayList <String> errors);\n }\n\n /**\n * Construye la interfaz del panel de configuración de agentes.\n *\n * @param agent\n * Agente que se quiere configurar.\n */\n public AgentConfigurationPanel (Agent agent) {\n m_root = new JPanel();\n m_listeners = new ArrayList <EventListener>();\n m_agent = agent;\n m_errors = new ArrayList <String>();\n m_success = new ArrayList <String>();\n\n createGUI(m_root);\n createControls();\n translate();\n }\n\n /**\n * Añade un oyente de eventos.\n *\n * @param listener\n * Clase oyente que se quiere añadir.\n */\n public final void addEventListener (EventListener listener) {\n if (!m_listeners.contains(listener))\n m_listeners.add(listener);\n }\n\n /**\n * Elimina un oyente de eventos. Si no es un oyente, la lista de oyentes\n * permanece intacta.\n *\n * @param listener\n * Clase oyente que se quiere añadir.\n */\n public final void removeEventListener (EventListener listener) {\n m_listeners.remove(listener);\n }\n\n /* (non-Javadoc)\n * @see es.ull.mazesolver.translations.Translatable#translate()\n */\n @Override\n public void translate () {\n ButtonTranslations tr = MainWindow.getTranslations().button();\n\n m_accept.setText(tr.ok());\n m_cancel.setText(tr.cancel());\n }\n\n /**\n * Provoca que la configuración actualmente almacenada en el panel de\n * configuración se guarde en el agente, modificando su comportamiento.\n *\n * Este método debe ser implementado por cada agente.\n *\n * @return <ul>\n * <li><b>true</b> si se pudo guardar el resultado.</li>\n * <li><b>false</b> si la configuración indicada no es válida.</li>\n * </ul>\n */\n protected abstract boolean accept ();\n\n /**\n * Cancela la operación de configuración, dejando al agente en su estado de\n * partida.\n *\n * Este método debe ser implementado por cada agente.\n */\n protected abstract void cancel ();\n\n /**\n * Crea la interfaz gráfica de usuario, que es la que se mostrará al mismo.\n * Estará personalizada para el agente específico, pero no incluirá los\n * botones de \"Aceptar\" y \"Cancelar\", que se proporcionan por defecto.\n *\n * @param root\n * Panel padre de todos los elementos que se creen. Si se intenta\n * utilizar el panel padre de la clase en lugar de éste, el panel de\n * configuración no se mostrará correctamente.\n */\n protected abstract void createGUI (JPanel root);\n\n /**\n * Se crean los controles de \"Aceptar\" y \"Cancelar\" y los coloca en el panel\n * junto a los controles personalizados del agente, que ya deben haber sido\n * creados.\n */\n private void createControls () {\n setLayout(new BorderLayout());\n\n JPanel controls = new JPanel(new FlowLayout(FlowLayout.RIGHT));\n m_accept = new JButton();\n m_cancel = new JButton();\n\n m_accept.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed (ActionEvent e) {\n if (accept())\n onSuccess();\n else\n onError();\n }\n });\n\n m_cancel.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed (ActionEvent e) {\n cancel();\n onCancel();\n }\n });\n\n controls.add(m_accept);\n controls.add(m_cancel);\n\n add(m_root, BorderLayout.CENTER);\n add(controls, BorderLayout.SOUTH);\n }\n\n /**\n * Método llamado cuando el usuario aplica los cambios y éstos son guardados\n * correctamente. Notifica a los {@link EventListener#onSuccess}.\n */\n private void onSuccess () {\n for (EventListener listener: m_listeners)\n listener.onSuccess(m_success);\n }\n\n /**\n * Método llamado cuando el usuario cancela la operación y el agente ha\n * quedado como al principio. Notifica a los {@link EventListener#onCancel}.\n */\n private void onCancel () {\n for (EventListener listener: m_listeners)\n listener.onCancel();\n }\n\n /**\n * Método llamado cuando el usuario intenta aplicar los cambios y no es\n * posible porque la configuración no es válida. Notifica a los {@link\n * EventListener#onError}.\n */\n private void onError () {\n for (EventListener listener: m_listeners)\n listener.onError(m_errors);\n }\n}",
"public class HeuristicAgentConfigurationPanel extends SimpleAgentConfigurationPanel {\n private static final long serialVersionUID = 1L;\n\n private DistanceWidget m_distance;\n private TitledBorder m_title;\n\n /**\n * Crea el panel de configuración para el agente indicado.\n *\n * @param agent\n * El agente que se configurará a través de este panel de\n * configuración.\n */\n public HeuristicAgentConfigurationPanel (HeuristicAgent agent) {\n super(agent);\n }\n\n /* (non-Javadoc)\n * @see\n * es.ull.mazesolver.gui.AgentConfigurationPanel#createGUI(javax.swing.JPanel)\n */\n @Override\n protected void createGUI (JPanel root) {\n super.createGUI(root);\n\n HeuristicAgent agent = (HeuristicAgent) m_agent;\n m_distance = new DistanceWidget(agent.getDistanceCalculator().getType());\n\n m_title = BorderFactory.createTitledBorder(\"\");\n m_distance.setBorder(m_title);\n\n root.add(m_distance);\n }\n\n /* (non-Javadoc)\n * @see es.ull.mazesolver.gui.AgentConfigurationPanel#accept()\n */\n @Override\n protected boolean accept () {\n if (super.accept()) {\n HeuristicAgent agent = (HeuristicAgent) m_agent;\n agent.setDistanceCalculator(DistanceCalculator.fromType(m_distance.getSelectedType()));\n\n return true;\n }\n\n return false;\n }\n\n /* (non-Javadoc)\n * @see es.ull.mazesolver.gui.AgentConfigurationPanel#translate()\n */\n @Override\n public void translate () {\n super.translate();\n m_distance.translate();\n m_title.setTitle(MainWindow.getTranslations().agent().heuristicAgent());\n }\n\n}",
"public class Environment extends BaseInternalFrame {\n private static final long serialVersionUID = 1L;\n private static final int WINDOW_BORDER_WIDTH = 11;\n private static final int WINDOW_BORDER_HEIGHT = 33;\n private static final int WINDOWS_OFFSET = 20;\n\n private static int s_instance = 0;\n private static Point s_start_pos = new Point();\n\n private Maze m_maze;\n private ArrayList <Agent> m_agents;\n private int m_selected, m_hovered;\n\n private BlackboardManager m_blackboard_mgr;\n private MessageManager m_message_mgr;\n\n private MouseListener m_agent_click = new MouseAdapter() {\n @Override\n public void mousePressed (MouseEvent e) {\n m_selected = getAgentIndexUnderMouse(e.getPoint());\n repaint();\n super.mousePressed(e);\n }\n };\n\n private MouseMotionListener m_agent_hover_drag = new MouseMotionListener() {\n @Override\n public void mouseMoved (MouseEvent e) {\n m_hovered = getAgentIndexUnderMouse(e.getPoint());\n repaint();\n }\n\n @Override\n public void mouseDragged (MouseEvent e) {\n Agent ag = getSelectedAgent();\n if (ag != null) {\n Point grid_pos = EnvironmentPanel.screenCoordToGrid(e.getPoint());\n if (m_maze.containsPoint(grid_pos)) {\n ag.setPosition(grid_pos);\n repaint();\n }\n }\n }\n };\n\n private MouseListener m_wall_click = new MouseAdapter() {\n @Override\n public void mousePressed (MouseEvent e) {\n EnvironmentEditionPanel panel = (EnvironmentEditionPanel) getContentPane();\n Pair<Point, Direction> selected = panel.getWallAt(e.getPoint());\n\n if (selected != null) {\n Point pos = selected.first;\n Direction dir = selected.second;\n Point adj = dir.movePoint(pos);\n\n // Si las dos celdas están dentro, se crea/eliminan las dos paredes que\n // las unen\n if (m_maze.containsPoint(adj)) {\n m_maze.get(pos.y, pos.x).toggleWall(dir);\n m_maze.get(adj.y, adj.x).toggleWall(dir.getOpposite());\n }\n // Si sólo una de las dos celdas está dentro hay que cambiar la posición\n // de la salida a ese punto\n else {\n if (dir.isVertical())\n m_maze.setExit(pos.x, dir);\n else // Horizontal\n m_maze.setExit(pos.y, dir);\n }\n }\n\n repaint();\n super.mousePressed(e);\n }\n };\n\n /**\n * Constructor para las clases de tipo entorno.\n *\n * @param maze\n * Laberinto en el que se basa el entorno. Puede ser compartido entre\n * varios entornos.\n * @param name\n * Nombre del entorno.\n */\n public Environment (Maze maze, String name) {\n super(name, false, false, false, false);\n ++s_instance;\n\n setMaze(maze);\n setVisible(true);\n\n setLocation(s_start_pos);\n s_start_pos.x += WINDOWS_OFFSET;\n s_start_pos.y += WINDOWS_OFFSET;\n\n m_selected = m_hovered = -1;\n m_agents = new ArrayList <Agent>();\n\n m_blackboard_mgr = new BlackboardManager();\n m_message_mgr = new MessageManager();\n\n moveToFront();\n }\n\n /**\n * Constructor para las clases de tipo entorno.\n *\n * @param maze\n * Laberinto en el que se basa el entorno. Puede ser compartido entre\n * varios entornos.\n */\n public Environment (Maze maze) {\n this(maze, \"Env \" + (s_instance + 1));\n }\n\n /**\n * Cambia el nombre del entorno.\n *\n * @param name\n * Nuevo nombre del entorno.\n */\n public void setEnvName (String name) {\n setTitle(name);\n }\n\n /**\n * @return El nombre del entorno.\n */\n public String getEnvName () {\n return getTitle();\n }\n\n /**\n * Cambia el modo de interacción con el entorno.\n *\n * @param mode\n * Nuevo modo de interacción con el entorno.\n */\n public void setInteractionMode (InteractionMode mode) {\n Container panel = null;\n\n switch (mode) {\n case SIMULATION:\n panel = new EnvironmentSimulationPanel(this);\n panel.addMouseListener(m_agent_click);\n panel.addMouseMotionListener(m_agent_hover_drag);\n break;\n case EDITION:\n panel = new EnvironmentEditionPanel(this);\n panel.addMouseListener(m_wall_click);\n break;\n }\n\n setContentPane(panel);\n updateSize();\n }\n\n /**\n * Obtiene el laberinto contenido en el entorno.\n *\n * @return Laberinto base del entorno.\n */\n public Maze getMaze () {\n return m_maze;\n }\n\n /**\n * Cambia el laberinto del entorno.\n * <br><br>\n * Esta operación invalidaría la memoria almacenada del/los agentes en caso\n * de que éstos contuvieran información sobre la ruta a llevar a cabo en el\n * entorno, pero no cuando la memoria fuera un conjunto de reglas o una tabla\n * de percepción-acción o cuando el agente no tuviera ninguna memoria.\n *\n * @param maze\n * Laberinto en el que se basa el entorno.\n */\n public void setMaze (Maze maze) {\n if (maze != null) {\n m_maze = maze;\n repaint();\n }\n else\n throw new IllegalArgumentException(\n MainWindow.getTranslations().exception().invalidMaze());\n }\n\n /**\n * Actualiza el tamaño de la ventana con respecto al tamaño de su contenido,\n * que es la representación del entorno.\n */\n public void updateSize () {\n EnvironmentPanel panel = ((EnvironmentPanel) getContentPane());\n panel.updateSize();\n setSize(panel.getWidth() + WINDOW_BORDER_WIDTH, panel.getHeight() + WINDOW_BORDER_HEIGHT);\n repaint();\n }\n\n /**\n * Este método permite saber lo que puede ver un agente si mira en una\n * dirección específica. La versión en la clase principal no maneja agentes,\n * por lo que debe ser sobrecargada para gestionarlos.\n *\n * @param pos\n * Posición desde la que mirar.\n * @param dir\n * Dirección hacia la que mirar.\n * @return Lo que vería un agente en la posición especificada si mirara hacia\n * la dirección indicada.\n */\n public MazeCell.Vision look (Point pos, Direction dir) {\n // Si el agente está fuera del laberinto, no dejamos que se mueva. De esta\n // forma, cuando un agente sale del laberinto se queda quieto fuera del\n // mismo y no vuelve a entrar ni se va lejos de la salida.\n if (!m_maze.containsPoint(pos) || m_maze.get(pos.y, pos.x).hasWall(dir))\n return MazeCell.Vision.WALL;\n\n Point n_pos = dir.movePoint(pos);\n if (!m_maze.containsPoint(n_pos))\n return MazeCell.Vision.OFFLIMITS;\n\n for (Agent ag: m_agents) {\n if (ag.getX() == n_pos.getX() && ag.getY() == n_pos.getY())\n return MazeCell.Vision.AGENT;\n }\n\n return MazeCell.Vision.EMPTY;\n }\n\n /**\n * Indica si a partir de una posición, el movimiento hacia una determinada\n * posición es posible o no.\n *\n * @param pos\n * Posición de partida.\n * @param dir\n * Dirección de movimiento.\n * @return true si se puede y false si no.\n */\n public boolean movementAllowed (Point pos, Direction dir) {\n MazeCell.Vision vision = look(pos, dir);\n return vision == MazeCell.Vision.EMPTY || vision == MazeCell.Vision.OFFLIMITS;\n }\n\n /**\n * Añade un agente al entorno.\n *\n * @param ag\n * Agente que se quiere añadir al entorno.\n */\n public void addAgent (Agent ag) {\n if (ag == null)\n throw new IllegalArgumentException(\n MainWindow.getTranslations().exception().invalidAgent());\n\n if (!m_agents.contains(ag)) {\n ag.setEnvironment(this);\n\n // Buscamos un hueco donde colocar el agente\n loops:\n for (int y = 0; y < m_maze.getHeight(); y++) {\n for (int x = 0; x < m_maze.getWidth(); x++) {\n boolean used = false;\n for (Agent i: m_agents) {\n if (i.getX() == x && i.getY() == y) {\n used = true;\n break;\n }\n }\n if (!used) {\n ag.setPosition(new Point(x, y));\n break loops;\n }\n }\n }\n\n m_agents.add(ag);\n repaint();\n }\n }\n\n /**\n * Elimina un agente del entorno.\n *\n * @param ag\n * Referencia al agente que se quiere eliminar.\n */\n public void removeAgent (Agent ag) {\n // Si se encuentra el agente, se elimina de la lista de agentes y si estaba\n // seleccionado se quita el estado de selección\n if (m_agents.contains(ag)) {\n if (getSelectedAgent() == ag)\n m_selected = -1;\n m_agents.remove(ag);\n }\n else\n throw new IllegalArgumentException(\n MainWindow.getTranslations().exception().agentNotInEnvironment());\n\n repaint();\n }\n\n /**\n * Extrae una referencia al agente seleccionado dentro del entorno.\n *\n * @return Agente seleccionado actualmente en el entorno o null si no hay\n * ninguno seleccionado.\n */\n public Agent getSelectedAgent () {\n if (m_selected == -1)\n return null;\n else\n return m_agents.get(m_selected);\n }\n\n /**\n * Extrae una referencia al agente dentro del entorno que tiene el cursor\n * situado encima.\n *\n * @return Agente sobre el que se tiene el cursor actualmente en el entorno o\n * null si el cursor no está encima de ningún agente.\n */\n public Agent getHoveredAgent () {\n if (m_hovered == -1)\n return null;\n else\n return m_agents.get(m_hovered);\n }\n\n /**\n * Extrae una referencia a un agente del entorno.\n *\n * @param index\n * Índice del agente que se quiere consultar.\n * @return Agente número 'index' dentro del entorno.\n */\n public Agent getAgent (int index) {\n if (index < 0 || index >= m_agents.size())\n throw new IllegalArgumentException(\n MainWindow.getTranslations().exception().indexOutOfRange());\n\n return m_agents.get(index);\n }\n\n /**\n * Extrae una copia profunda de la lista de agentes que hay dentro del\n * entorno. Hay que tener en cuenta que cualquier modificación en esta lista\n * no va a tener ninguna repercusión en los agentes o el entorno original.\n *\n * @return Copia de la lista de agentes dentro del entorno.\n */\n public ArrayList <Agent> getAgents () {\n ArrayList <Agent> agents = new ArrayList <Agent>();\n\n for (Agent i: m_agents)\n agents.add((Agent) i.clone());\n\n return agents;\n }\n\n /**\n * Obtiene el número de agentes que se encuentran en el entorno.\n *\n * @return Número de agentes actualmente en el entorno.\n */\n public int getAgentCount () {\n return m_agents.size();\n }\n\n /**\n * Obtiene el gestor de pizarras del entorno.\n *\n * @return El gestor de pizarras del entorno.\n */\n public BlackboardManager getBlackboardManager () {\n return m_blackboard_mgr;\n }\n\n /**\n * Obtiene el gestor de mensajes del entorno.\n *\n * @return El gestor de mensajes del entorno.\n */\n public MessageManager getMessageManager () {\n return m_message_mgr;\n }\n\n /**\n * Ejecuta un paso de la simulación de ejecución de los agentes en el entorno\n * y devuelve el resultado de la ejecución.\n *\n * @param results\n * Objeto que representa el resultado de la simulación, que será\n * actualizado en este método para notificar de agentes que han\n * llegado a la salida y para contar los pasos que han dado.\n * @return true si todos los agentes han salido del laberinto y false en otro\n * caso.\n */\n public boolean runStep (SimulationResults results) {\n m_message_mgr.flushMessageQueues();\n\n Direction[] movements = new Direction[m_agents.size()];\n\n // Paso 1: Obtener movimientos a partir del estado actual del entorno\n for (int i = 0; i < m_agents.size(); ++i) {\n Agent ag = m_agents.get(i);\n\n // Si el agente ya salió del laberinto no lo movemos, pero si no ha\n // salido hacemos que calcule su siguiente movimiento\n if (m_maze.containsPoint(ag.getPos())) {\n movements[i] = ag.getNextMovement();\n results.agentIterated(ag);\n }\n else\n movements[i] = Direction.NONE;\n }\n\n // Esta variable indica si la simulación ha terminado (todos los agentes\n // han salido del laberinto)\n boolean ended = true;\n\n // Paso 2: Realizar movimientos (modificar el entorno)\n for (int i = 0; i < m_agents.size(); ++i) {\n Agent ag = m_agents.get(i);\n\n // Restringimos el movimiento del agente para que no atraviese paredes\n // u otros agentes independientemente de errores que se hayan podido\n // cometer a la hora de programar a los agentes\n if (movementAllowed(ag.getPos(), movements[i])) {\n ag.doMovement(movements[i]);\n results.agentWalked(ag);\n }\n\n if (m_maze.containsPoint(ag.getPos()))\n ended = false;\n else\n results.agentFinished(ag);\n }\n\n repaint();\n return ended;\n }\n\n /**\n * @return El número de instancias de la clase que han sido creadas.\n */\n public static int getInstancesCreated () {\n return s_instance;\n }\n\n /*\n * (non-Javadoc)\n *\n * @see java.lang.Object#equals(java.lang.Object)\n */\n @Override\n public boolean equals (Object obj) {\n return this == obj;\n }\n\n /*\n * (non-Javadoc)\n *\n * @see java.lang.Object#hashCode()\n */\n @Override\n public int hashCode () {\n return new Integer(s_instance).hashCode();\n }\n\n /**\n * Obtiene el índice de la lista de agentes del agente que está situado bajo\n * el cursor.\n *\n * @param mouse_pos\n * Posición del ratón.\n * @return Índice del agente colocado en la posición indicada dentro del\n * entorno.\n */\n private int getAgentIndexUnderMouse (Point mouse_pos) {\n Point maze_pos = EnvironmentPanel.screenCoordToGrid(mouse_pos);\n int ag_index = -1;\n\n for (int i = 0; i < m_agents.size(); i++) {\n Agent current = m_agents.get(i);\n if (current.getX() == maze_pos.getX() && current.getY() == maze_pos.getY()) {\n ag_index = i;\n break;\n }\n }\n\n return ag_index;\n }\n\n}",
"public class Maze {\n private ArrayList <ArrayList <MazeCell>> m_maze;\n private Point m_exit;\n\n /**\n * Crea un laberinto a partir de un algoritmo de generación de laberintos\n * ya inicializado.\n *\n * @param alg\n * Algoritmo de creación de laberintos ya inicializado\n */\n public Maze (MazeCreationAlgorithm alg) {\n if (alg != null) {\n m_maze = alg.createMaze();\n m_exit = alg.getExit();\n }\n else\n throw new IllegalArgumentException(\n MainWindow.getTranslations().exception().invalidMazeCreationAlgorithm());\n }\n\n /**\n * Crea un laberinto a partir de su versión serializada en un fichero.\n *\n * @param fileName\n * Nombre del fichero del que cargar el laberinto.\n * @throws IOException\n * Cuando no se encuentra el fichero, no se puede abrir para su\n * lectura o no contiene un laberinto válido.\n */\n public Maze (String fileName) throws IOException {\n loadFile(fileName);\n }\n\n /**\n * Obtiene la celda situada en una posición concreta del laberinto.\n *\n * @param row\n * Fila.\n * @param column\n * Columna.\n * @return Celda en la posición indicada.\n */\n public MazeCell get (int row, int column) {\n return m_maze.get(row).get(column);\n }\n\n /**\n * Establece el contenido de una celda en el laberinto.\n *\n * @param row\n * Fila.\n * @param column\n * Columna.\n * @param cell\n * Celda que se quiere introducir.\n */\n public void set (int row, int column, MazeCell cell) {\n m_maze.get(row).set(column, cell);\n }\n\n /**\n * Obtiene el número de columnas (anchura) del laberinto.\n *\n * @return Anchura (en celdas) del laberinto.\n */\n public int getWidth () {\n return m_maze.get(0).size();\n }\n\n /**\n * Obtiene el número de filas (altura) del laberinto.\n *\n * @return Altura (en celdas) del laberinto.\n */\n public int getHeight () {\n return m_maze.size();\n }\n\n /**\n * Cambia la salida del laberinto a otro lugar, añadiendo y eliminando las\n * paredes necesarias.\n *\n * @param pos\n * Índice de la celda en la que se quiere colocar la salida.\n * Dependiendo de la dirección este valor se referirá a una columna\n * (si la dirección es arriba o abajo) o a una fila (si la dirección\n * es izquierda o derecha).\n * @param dir\n * Borde del laberinto donde colocar la salida.\n */\n public void setExit (int pos, Direction dir) {\n // Comprobamos que los parámetros son válidos\n if (pos < 0 || dir == Direction.NONE)\n return;\n if (dir.isVertical() && pos >= getWidth())\n return;\n if (dir.isHorizontal() && pos >= getHeight())\n return;\n\n // Tapamos la salida anterior antes de modificar su posición\n if (m_exit.x < 0)\n m_maze.get(m_exit.y).get(0).setWall(Direction.LEFT);\n else if (m_exit.x >= getWidth())\n m_maze.get(m_exit.y).get(getWidth() - 1).setWall(Direction.RIGHT);\n else if (m_exit.y < 0)\n m_maze.get(0).get(m_exit.x).setWall(Direction.UP);\n else if (m_exit.y >= getHeight())\n m_maze.get(getHeight() - 1).get(m_exit.x).setWall(Direction.DOWN);\n\n // Modificamos la salida del laberinto y abrimos la pared\n switch (dir) {\n case UP:\n m_exit.move(pos, 0);\n break;\n case DOWN:\n m_exit.move(pos, getHeight() - 1);\n break;\n case LEFT:\n m_exit.move(0, pos);\n break;\n case RIGHT:\n m_exit.move(getWidth() - 1, pos);\n break;\n default:\n break;\n }\n\n m_maze.get(m_exit.y).get(m_exit.x).unsetWall(dir);\n m_exit.setLocation(dir.movePoint(m_exit));\n }\n\n /**\n * Obtiene una copia del lugar donde está la salida del laberinto.\n *\n * @return La posición donde se encuentra la salida al laberinto.\n */\n public Point getExit () {\n return new Point(m_exit);\n }\n\n /**\n * Determina si el punto se encuentra dentro del laberinto o no.\n *\n * @param p\n * Punto a testear.\n * @return Si el punto está dentro del laberinto o no.\n */\n public boolean containsPoint (Point p) {\n return p.x >= 0 && p.y >= 0 && p.x < getWidth() && p.y < getHeight();\n }\n\n /**\n * Carga una instancia de laberinto de un fichero que contiene una instancia\n * de esta clase serializada.\n *\n * @param fileName\n * Nombre del fichero del que cargar el laberinto.\n * @throws IOException\n * Cuando no se encuentra el fichero, no se puede abrir para su\n * lectura o no contiene un laberinto válido.\n */\n @SuppressWarnings (\"unchecked\")\n public void loadFile (String fileName) throws IOException {\n try {\n FileInputStream fileIn = new FileInputStream(fileName);\n ObjectInputStream in = new ObjectInputStream(fileIn);\n m_maze = (ArrayList <ArrayList <MazeCell>>) in.readObject();\n m_exit = (Point) in.readObject();\n in.close();\n fileIn.close();\n }\n catch (ClassNotFoundException c) {\n throw new IOException(c);\n }\n }\n\n /**\n * Guarda la actual instancia de la clase {@link Maze} en un fichero mediante\n * su serialización.\n *\n * @param fileName\n * Nombre del fichero donde guardar el laberinto.\n * @throws IOException\n * Cuando el fichero no se puede abrir o no se tienen permisos de\n * escritura en el mismo.\n */\n public void saveFile (String fileName) throws IOException {\n FileOutputStream fileOut = new FileOutputStream(fileName);\n ObjectOutputStream out = new ObjectOutputStream(fileOut);\n out.writeObject(m_maze);\n out.writeObject(m_exit);\n out.close();\n fileOut.close();\n }\n\n /**\n * Calcula el número máximo de aristas que se pueden añadir en un laberinto\n * del tamaño dado. Cada arista se refiere a un pasillo abierto entre 2\n * celdas. Se puede ver como el número de paredes que tiene en su interior un\n * laberinto perfecto, sin contar el contorno.\n *\n * @param rows\n * Número de filas.\n * @param columns\n * Número de columnas.\n * @return Número de paredes en el interior del laberinto.\n */\n public static int perfectMazeWalls (int rows, int columns) {\n return (rows * columns) - rows - columns + 1;\n }\n\n /**\n * Calcula el número de aristas que tiene un laberinto perfecto de las\n * dimensiones dadas. Las aristas representan pasillos entre 2 celdas.\n *\n * @param rows\n * Númnero de filas.\n * @param columns\n * Número de columnas.\n * @return Número de aristas del laberinto perfecto.\n */\n public static int perfectMazeEdges (int rows, int columns) {\n return (rows * columns) - 1;\n }\n}",
"public class MazeCell implements Serializable {\n private static final long serialVersionUID = 4328443829621010840L;\n\n private short m_cell;\n\n /**\n * Constructor por defecto. La celda creada está rodeada de muros.\n */\n public MazeCell () {\n m_cell |= Direction.UP.val;\n m_cell |= Direction.DOWN.val;\n m_cell |= Direction.RIGHT.val;\n m_cell |= Direction.LEFT.val;\n }\n\n /**\n * Cambia el estado de la dirección especificada. Si no había muro, ahora lo\n * hay y viceversa.\n *\n * @param dir\n * Lado de la celda que se quiere modificar.\n */\n public void toggleWall (Direction dir) {\n if (hasWall(dir))\n unsetWall(dir);\n else\n setWall(dir);\n }\n\n /**\n * Pone un muro si no lo hay en la dirección especificada.\n *\n * @param dir\n * Lado de la celda que se quiere modificar.\n */\n public void setWall (Direction dir) {\n m_cell |= dir.val;\n }\n\n /**\n * Quita el muro si lo hay en la dirección especificada.\n *\n * @param dir\n * Lado de la celda que se quiere modificar.\n */\n public void unsetWall (Direction dir) {\n m_cell &= ~dir.val;\n }\n\n /**\n * Elimina todas las paredes de la celda.\n */\n public void removeWalls () {\n m_cell = 0;\n }\n\n /**\n * Indica si hay un muro en la dirección indicada.\n *\n * @param dir\n * Lado de la celda que se quiere consultar.\n * @return Si hay una celda en esa dirección o no.\n */\n public boolean hasWall (Direction dir) {\n return (m_cell & dir.val) != 0;\n }\n\n /**\n * Enumeración de los diferentes estados que puede tener una celda de cara a\n * un agente cualquiera.\n */\n public static enum Vision {\n /**\n * Este estado significa que la celda está vacía y no hay una pared entre\n * las 2 celdas.\n */\n EMPTY,\n\n /**\n * Este estado significa que hay una pared entre la posición actual del\n * agente y la celda.\n */\n WALL,\n\n /**\n * Este estado significa que hay un agente sobre esa celda actualmente y no\n * hay nada interponiéndose en medio.\n */\n AGENT,\n\n /**\n * Este estado significa que la celda referenciada está fuera del laberinto\n * y además no hay una pared en medio.\n */\n OFFLIMITS;\n }\n\n}",
"public class EmptyMaze extends MazeCreationAlgorithm {\n\n /**\n * Constructor. Crea una nueva instancia de la clase.\n *\n * @param rows\n * Número de filas del laberinto que se genere.\n * @param columns\n * Número de columnas del laberinto que se genere.\n */\n public EmptyMaze (int rows, int columns) {\n super(rows, columns);\n }\n\n /*\n * (non-Javadoc)\n *\n * @see maze.MazeCreationAlgorithm#runCreationAlgorithm()\n */\n @Override\n protected void runCreationAlgorithm () {\n // Quitamos todas las paredes, incluidos los bordes\n for (int y = 0; y < m_rows; y++)\n for (int x = 0; x < m_columns; x++)\n m_maze.get(y).get(x).removeWalls();\n }\n\n}",
"public class BlackboardManager {\n private HashMap <String, Object> m_blackboards;\n\n /**\n * Inicializa el gestor de pizarras.\n */\n public BlackboardManager () {\n m_blackboards = new HashMap <String, Object>();\n }\n\n /**\n * Obtiene la pizarra que hay en el canal indicado.\n *\n * @param channel\n * Canal del que se quiere obtener la pizarra.\n * @return El objeto pizarra del canal.\n */\n public Object getBlackboard (String channel) {\n return m_blackboards.get(channel);\n }\n\n /**\n * Añade una nueva pizarra al gestor.\n *\n * @param blackboard\n * Objeto que representa la nueva pizarra. Las modificaciones\n * realizadas a este objeto son visibles para todos los agentes que\n * posean una referencia a la misma.\n * @return El nombre del nuevo canal donde se ha colocado la pizarra.\n */\n public String addBlackboard (Object blackboard) {\n String name = \"\";\n do {\n name = Long.toUnsignedString(((Double) (Math.random() * Long.MAX_VALUE)).longValue());\n }\n while (m_blackboards.containsKey(name));\n\n m_blackboards.put(name, blackboard);\n return name;\n }\n\n /**\n * Intenta añadir la pizarra al canal deseado. Esto será posible sólo si el\n * canal no está ya ocupado.\n *\n * @param blackboard\n * Objeto que representa la pizarra.\n * @param desired_channel\n * Canal donde se quiere colocar la pizarra.\n * @return Canal donde finalmente se ha colocado la pizarra.\n */\n public String addBlackboard (Object blackboard, String desired_channel) {\n if (!m_blackboards.containsKey(desired_channel)) {\n m_blackboards.put(desired_channel, blackboard);\n return desired_channel;\n }\n else\n return addBlackboard(blackboard);\n }\n\n /**\n * Cambia el objeto pizarra asociado a un canal ya creado.\n *\n * @param channel\n * Canal en el que modificar la pizarra.\n * @param blackboard\n * Nueva pizarra que colocar en el canal.\n * @return {@code true} si se ha realizado el cambio y {@code false} si el\n * canal indicado no existía.\n */\n public boolean changeBlackboard (String channel, Object blackboard) {\n if (m_blackboards.containsKey(channel)) {\n m_blackboards.put(channel, blackboard);\n return true;\n }\n return false;\n }\n\n /**\n * Elimina un canal del gestor de pizarras.\n *\n * @param channel\n * Canal que eliminar.\n * @return {@code true} si se ha realizado la eliminación y {@code false} si\n * el canal indicado no existía.\n */\n public boolean removeBlackboard (String channel) {\n if (m_blackboards.containsKey(channel)) {\n m_blackboards.remove(channel);\n return true;\n }\n return false;\n }\n\n /**\n * Indica si un canal está ocupado.\n *\n * @param channel\n * Canal que consultar.\n * @return Si el canal consultado existe para este gestor.\n */\n boolean channelUsed (String channel) {\n return m_blackboards.containsKey(channel);\n }\n}",
"public enum Direction implements Serializable {\n NONE ((short) 0x00),\n UP ((short) 0x01),\n DOWN ((short) 0x02),\n LEFT ((short) 0x04),\n RIGHT ((short) 0x08);\n\n /**\n * Número máximo de direcciones.\n */\n public static int MAX_DIRECTIONS = 5;\n\n /**\n * Valor asociado a una dirección (campo de bits).\n */\n public short val;\n\n private static Direction [] values = Direction.values();\n\n private Direction (short val) {\n this.val = val;\n }\n\n /**\n * Transforma un short en dirección, comparando sus valores directamente.\n *\n * @param value\n * Valor (dentro de los valores posibles de dirección).\n * @return Dirección asociada a ese valor.\n */\n public static Direction fromValue (short value) {\n for (Direction i: values)\n if (i.val == value)\n return i;\n\n return null;\n }\n\n /**\n * Devuelve la dirección asociada a un índice.\n *\n * @param index\n * Índice de la dirección. El orden es el siguiente:\n * <ol start=\"0\">\n * <li>NONE</li>\n * <li>UP</li>\n * <li>DOWN</li>\n * <li>LEFT</li>\n * <li>RIGHT</li>\n * </ol>\n * @return Dirección asociada al índice.\n */\n public static Direction fromIndex (int index) {\n return values[index];\n }\n\n /**\n * Extrae la dirección asociada al paso entre 2 posiciones contiguas.\n *\n * @param p1\n * Posición de inicio.\n * @param p2\n * Posición de destino.\n * @return La dirección que une los 2 puntos contiguos o {@code null} si los\n * puntos no están contiguos,\n */\n public static Direction fromPoints (Point p1, Point p2) {\n Point diff = new Point(p2.x - p1.x, p2.y - p1.y);\n switch (diff.x) {\n case -1: // izquierda\n return diff.y == 0? Direction.LEFT : null;\n case 1: // derecha\n return diff.y == 0? Direction.RIGHT : null;\n case 0: // misma posición en X\n switch (diff.y) {\n case -1: // arriba\n return Direction.UP;\n case 1: // abajo\n return Direction.DOWN;\n case 0: // misma posición\n return Direction.NONE;\n }\n default:\n return null;\n }\n }\n\n /**\n * Crea una dirección de forma aleatoria.\n *\n * @return Una dirección aleatoria. No va a ser {@code Direction.NONE}.\n */\n public static Direction random () {\n return values[1 + (int) (Math.random() * 4.0)];\n }\n\n /**\n * Descompone la dirección en sus componentes x e y, con una magnitud de 1.\n *\n * @return Pareja con la descomposición de la dirección (x, y).\n */\n public Pair <Integer, Integer> decompose () {\n Pair <Integer, Integer> p = new Pair <Integer, Integer>(0, 0);\n switch (this) {\n case NONE:\n break;\n case UP:\n p.second = -1;\n break;\n case DOWN:\n p.second = 1;\n break;\n case LEFT:\n p.first = -1;\n break;\n case RIGHT:\n p.first = 1;\n break;\n }\n return p;\n }\n\n /**\n * Invierte la posición actual.\n *\n * @return Dirección contraria de la actual.\n */\n public Direction getOpposite () {\n switch (this) {\n case UP:\n return DOWN;\n case DOWN:\n return UP;\n case LEFT:\n return RIGHT;\n case RIGHT:\n return LEFT;\n default:\n return NONE;\n }\n }\n\n /**\n * Rota la dirección absoluta actual en el sentido indicado.\n *\n * @param rot\n * Sentido de rotación que aplicar.\n * @return La nueva dirección rotada.\n */\n public Direction rotate (Rotation rot) {\n switch (this) {\n case UP:\n return rot == Rotation.CLOCKWISE? RIGHT : LEFT;\n case DOWN:\n return rot == Rotation.CLOCKWISE? LEFT : RIGHT;\n case LEFT:\n return rot == Rotation.CLOCKWISE? UP : DOWN;\n case RIGHT:\n return rot == Rotation.CLOCKWISE? DOWN : UP;\n default:\n return NONE;\n }\n }\n\n /**\n * Desplaza un punto en la dirección y lo guarda en un punto nuevo.\n *\n * @param p\n * Punto que se desea mover en esta dirección.\n * @return Nuevo punto equivalente al indicado desplazado en esta dirección.\n */\n public Point movePoint (final Point p) {\n Pair <Integer, Integer> desp = decompose();\n return new Point(p.x + desp.first, p.y + desp.second);\n }\n\n /**\n * @return Si la dirección es vertical.\n */\n public boolean isVertical () {\n return this == UP || this == DOWN;\n }\n\n /**\n * @return Si la dirección es horizontal.\n */\n public boolean isHorizontal () {\n return this == LEFT || this == RIGHT;\n }\n\n}"
] | import es.ull.mazesolver.agent.util.BlackboardCommunication;
import es.ull.mazesolver.gui.configuration.AgentConfigurationPanel;
import es.ull.mazesolver.gui.configuration.HeuristicAgentConfigurationPanel;
import es.ull.mazesolver.gui.environment.Environment;
import es.ull.mazesolver.maze.Maze;
import es.ull.mazesolver.maze.MazeCell;
import es.ull.mazesolver.maze.algorithm.EmptyMaze;
import es.ull.mazesolver.util.BlackboardManager;
import es.ull.mazesolver.util.Direction;
import java.awt.Color;
import java.awt.Point;
import java.util.ArrayList;
import java.util.PriorityQueue; | /*
* This file is part of MazeSolver.
*
* 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/>.
*
* Copyright (c) 2014 MazeSolver
* Sergio M. Afonso Fumero <[email protected]>
* Kevin I. Robayna Hernández <[email protected]>
*/
/**
* @file DStarAgent.java
* @date 10/12/2014
*/
package es.ull.mazesolver.agent;
/**
* Agente que implementa el algoritmo D* para calcular la ruta más corta hasta
* la salida teniendo tan sólo conocimiento local del entorno.
*
* @see <a
* href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.15.3683">
* Optimal and Efficient Path Planning for Unknown and Dynamic Environments
* </a>
*/
public class DStarAgent extends HeuristicAgent implements BlackboardCommunication {
private static final long serialVersionUID = 1342168437798267323L;
private static String BLACKBOARD_CHANNEL = "D* Agents Channel";
/**
* Representa el estado del algoritmo, que es lo que es compartido entre
* agentes D* como pizarra.
*/
/**
*
*/
private static class AlgorithmState {
/**
* No se trata del laberinto en el que el agente se mueve, sino la
* representación de lo que el agente conoce sobre el laberinto. Todas
* aquellas zonas que el agente no ha visitado supone que no contienen
* paredes.
*/
public Maze maze;
/**
* Posición de la celda del laberinto más cercana a su salida.
*/
public Point exit;
/**
* Representa la matriz de posiciones del laberinto con el estado del agente
* asociado a cada celda.
*/
public ArrayList <ArrayList <State>> state_maze;
/**
* Lista "open" de estados del algoritmo.
*/
public PriorityQueue <State> open;
/**
* Valor de "k_old" del algoritmo.
*/
public double k_old;
}
private transient AlgorithmState m_st;
/**
* Crea un nuevo agente D* en el entorno indicado.
*
* @param env
* Entorno en el que se va a colocar al agente.
*/
public DStarAgent (Environment env) {
super(env);
}
/*
* (non-Javadoc)
*
* @see agent.Agent#getAlgorithmName()
*/
@Override
public String getAlgorithmName () {
return "D*";
}
/*
* (non-Javadoc)
*
* @see es.ull.mazesolver.agent.Agent#getAlgorithmColor()
*/
@Override
public Color getAlgorithmColor () {
return Color.BLUE;
}
/*
* (non-Javadoc)
*
* @see agent.Agent#setEnvironment(gui.environment.Environment)
*/
@Override
public void setEnvironment (Environment env) {
super.setEnvironment(env);
resetMemory();
BlackboardManager mgr = env.getBlackboardManager();
try {
setBlackboard(mgr.getBlackboard(BLACKBOARD_CHANNEL));
}
catch (Exception e) {
Maze real_maze = env.getMaze();
m_st = new AlgorithmState();
m_st.maze = new Maze(new EmptyMaze(real_maze.getHeight(), real_maze.getWidth()));
// Creamos la matriz de estados, donde cada celda representa un nodo en el
// grafo que manipula el algoritmo. Esto será lo que se comparta entre
// todos los agentes.
m_st.state_maze = new ArrayList <ArrayList <State>>(m_st.maze.getHeight());
for (int i = 0; i < m_st.maze.getHeight(); i++) {
m_st.state_maze.add(new ArrayList <State>(m_st.maze.getWidth()));
for (int j = 0; j < m_st.maze.getWidth(); j++)
m_st.state_maze.get(i).add(new State(new Point(j, i)));
}
// La salida la colocaremos dentro del laberinto para que el agente pueda
// utilizarla como un estado más, luego en el método getNextMovement() se
// encarga de moverse al exterior si está en el punto al lado de la salida
m_st.exit = real_maze.getExit();
if (m_st.exit.x < 0)
m_st.exit.x++;
else if (m_st.exit.x == m_st.maze.getWidth())
m_st.exit.x--;
else if (m_st.exit.y < 0)
m_st.exit.y++;
else /* m_st.exit.y == m_st.maze.getHeight() */
m_st.exit.y--;
BLACKBOARD_CHANNEL = mgr.addBlackboard(m_st, BLACKBOARD_CHANNEL);
}
}
/*
* (non-Javadoc)
*
* @see agent.Agent#getNextMovement()
*/
@Override
public Direction getNextMovement () {
// Si estamos al lado de la salida evitamos cálculos y salimos directamente
for (int i = 1; i < Direction.MAX_DIRECTIONS; i++) {
Direction dir = Direction.fromIndex(i); | if (m_env.look(m_pos, dir) == MazeCell.Vision.OFFLIMITS) | 5 |
justyoyo/Contrast | pdf417/src/main/java/com/justyoyo/contrast/pdf417/PDF417HighLevelEncoder.java | [
"public enum BarcodeFormat {\n\n /** Aztec 2D barcode format. */\n AZTEC,\n\n /** CODABAR 1D format. */\n CODABAR,\n\n /** Code 39 1D format. */\n CODE_39,\n\n /** Code 93 1D format. */\n CODE_93,\n\n /** Code 128 1D format. */\n CODE_128,\n\n /** Data Matrix 2D barcode format. */\n DATA_MATRIX,\n\n /** EAN-8 1D format. */\n EAN_8,\n\n /** EAN-13 1D format. */\n EAN_13,\n\n /** ITF (Interleaved Two of Five) 1D format. */\n ITF,\n\n /** MaxiCode 2D barcode format. */\n MAXICODE,\n\n /** PDF417 format. */\n PDF_417,\n\n /** QR Code 2D barcode format. */\n QR_CODE,\n\n /** RSS 14 */\n RSS_14,\n\n /** RSS EXPANDED */\n RSS_EXPANDED,\n\n /** UPC-A 1D format. */\n UPC_A,\n\n /** UPC-E 1D format. */\n UPC_E,\n\n /** UPC/EAN extension format. Not a stand-alone format. */\n UPC_EAN_EXTENSION\n\n}",
"public enum EncodeHintType {\n\n /**\n * Specifies what degree of error correction to use, for example in QR Codes.\n * Type depends on the encoder. For example for QR codes it's type\n * {@link com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ErrorCorrectionLevel}.\n * For Aztec it is of type {@link Integer}, representing the minimal percentage of error correction words. \n * Note: an Aztec symbol should have a minimum of 25% EC words.\n */\n ERROR_CORRECTION,\n\n /**\n * Specifies what character encoding to use where applicable (type {@link String})\n */\n CHARACTER_SET,\n\n /**\n * Specifies the matrix shape for Data Matrix (type {@link com.google.zxing.datamatrix.encoder.SymbolShapeHint})\n */\n DATA_MATRIX_SHAPE,\n\n /**\n * Specifies a minimum barcode size (type {@link Dimension}). Only applicable to Data Matrix now.\n */\n MIN_SIZE,\n\n /**\n * Specifies a maximum barcode size (type {@link Dimension}). Only applicable to Data Matrix now.\n */\n MAX_SIZE,\n\n /**\n * Specifies margin, in pixels, to use when generating the barcode. The meaning can vary\n * by format; for example it controls margin before and after the barcode horizontally for\n * most 1D formats. (Type {@link Integer}).\n */\n MARGIN,\n\n /**\n * Specifies whether to use compact mode for PDF417 (type {@link Boolean}).\n */\n PDF417_COMPACT,\n\n /**\n * Specifies what compaction mode to use for PDF417 (type\n * {@link com.google.zxing.pdf417.encoder.Compaction Compaction}).\n */\n PDF417_COMPACTION,\n\n /**\n * Specifies the minimum and maximum number of rows and columns for PDF417 (type\n * {@link com.google.zxing.pdf417.encoder.Dimensions Dimensions}).\n */\n PDF417_DIMENSIONS,\n\n /**\n * Specifies the required number of layers for an Aztec code:\n * a negative number (-1, -2, -3, -4) specifies a compact Aztec code\n * 0 indicates to use the minimum number of layers (the default)\n * a positive number (1, 2, .. 32) specifies a normaol (non-compact) Aztec code\n */\n AZTEC_LAYERS,\n\n /**\n * Specifies the foreground colour of the barcode, using {@link android.graphics.Color}\n */\n FOREGROUND_COLOR,\n\n /**\n * Specifies the background colour of the barcode, using {@link android.graphics.Color}\n */\n BACKGROUND_COLOR,\n\n}",
"public final class WriterException extends Exception {\n\n public WriterException() {\n }\n\n public WriterException(String message) {\n super(message);\n }\n\n public WriterException(Throwable cause) {\n super(cause);\n }\n\n}",
"public final class BitMatrix implements Cloneable {\n\n private final int width;\n private final int height;\n private final int rowSize;\n private final int[] bits;\n\n // A helper to construct a square matrix.\n public BitMatrix(int dimension) {\n this(dimension, dimension);\n }\n\n public BitMatrix(int width, int height) {\n if (width < 1 || height < 1) {\n throw new IllegalArgumentException(\"Both dimensions must be greater than 0\");\n }\n this.width = width;\n this.height = height;\n this.rowSize = (width + 31) >> 5;\n bits = new int[rowSize * height];\n }\n\n private BitMatrix(int width, int height, int rowSize, int[] bits) {\n this.width = width;\n this.height = height;\n this.rowSize = rowSize;\n this.bits = bits;\n }\n\n /**\n * <p>Gets the requested bit, where true means black.</p>\n *\n * @param x The horizontal component (i.e. which column)\n * @param y The vertical component (i.e. which row)\n * @return value of given bit in matrix\n */\n public boolean get(int x, int y) {\n int offset = y * rowSize + (x >> 5);\n return ((bits[offset] >>> (x & 0x1f)) & 1) != 0;\n }\n\n /**\n * <p>Sets the given bit to true.</p>\n *\n * @param x The horizontal component (i.e. which column)\n * @param y The vertical component (i.e. which row)\n */\n public void set(int x, int y) {\n int offset = y * rowSize + (x >> 5);\n bits[offset] |= 1 << (x & 0x1f);\n }\n\n /**\n * <p>Flips the given bit.</p>\n *\n * @param x The horizontal component (i.e. which column)\n * @param y The vertical component (i.e. which row)\n */\n public void flip(int x, int y) {\n int offset = y * rowSize + (x >> 5);\n bits[offset] ^= 1 << (x & 0x1f);\n }\n\n /**\n * Clears all bits (sets to false).\n */\n public void clear() {\n int max = bits.length;\n for (int i = 0; i < max; i++) {\n bits[i] = 0;\n }\n }\n\n /**\n * <p>Sets a square region of the bit matrix to true.</p>\n *\n * @param left The horizontal position to begin at (inclusive)\n * @param top The vertical position to begin at (inclusive)\n * @param width The width of the region\n * @param height The height of the region\n */\n public void setRegion(int left, int top, int width, int height) {\n if (top < 0 || left < 0) {\n throw new IllegalArgumentException(\"Left and top must be nonnegative\");\n }\n if (height < 1 || width < 1) {\n throw new IllegalArgumentException(\"Height and width must be at least 1\");\n }\n int right = left + width;\n int bottom = top + height;\n if (bottom > this.height || right > this.width) {\n throw new IllegalArgumentException(\"The region must fit inside the matrix\");\n }\n for (int y = top; y < bottom; y++) {\n int offset = y * rowSize;\n for (int x = left; x < right; x++) {\n bits[offset + (x >> 5)] |= 1 << (x & 0x1f);\n }\n }\n }\n\n /**\n * A fast method to retrieve one row of data from the matrix as a BitArray.\n *\n * @param y The row to retrieve\n * @param row An optional caller-allocated BitArray, will be allocated if null or too small\n * @return The resulting BitArray - this reference should always be used even when passing\n * your own row\n */\n public BitArray getRow(int y, BitArray row) {\n if (row == null || row.getSize() < width) {\n row = new BitArray(width);\n } else {\n row.clear();\n }\n int offset = y * rowSize;\n for (int x = 0; x < rowSize; x++) {\n row.setBulk(x << 5, bits[offset + x]);\n }\n return row;\n }\n\n /**\n * @param y row to set\n * @param row {@link BitArray} to copy from\n */\n public void setRow(int y, BitArray row) {\n System.arraycopy(row.getBitArray(), 0, bits, y * rowSize, rowSize);\n }\n\n /**\n * Modifies this {@code BitMatrix} to represent the same but rotated 180 degrees\n */\n public void rotate180() {\n int width = getWidth();\n int height = getHeight();\n BitArray topRow = new BitArray(width);\n BitArray bottomRow = new BitArray(width);\n for (int i = 0; i < (height+1) / 2; i++) {\n topRow = getRow(i, topRow);\n bottomRow = getRow(height - 1 - i, bottomRow);\n topRow.reverse();\n bottomRow.reverse();\n setRow(i, bottomRow);\n setRow(height - 1 - i, topRow);\n }\n }\n\n /**\n * This is useful in detecting the enclosing rectangle of a 'pure' barcode.\n *\n * @return {@code left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white\n */\n public int[] getEnclosingRectangle() {\n int left = width;\n int top = height;\n int right = -1;\n int bottom = -1;\n\n for (int y = 0; y < height; y++) {\n for (int x32 = 0; x32 < rowSize; x32++) {\n int theBits = bits[y * rowSize + x32];\n if (theBits != 0) {\n if (y < top) {\n top = y;\n }\n if (y > bottom) {\n bottom = y;\n }\n if (x32 * 32 < left) {\n int bit = 0;\n while ((theBits << (31 - bit)) == 0) {\n bit++;\n }\n if ((x32 * 32 + bit) < left) {\n left = x32 * 32 + bit;\n }\n }\n if (x32 * 32 + 31 > right) {\n int bit = 31;\n while ((theBits >>> bit) == 0) {\n bit--;\n }\n if ((x32 * 32 + bit) > right) {\n right = x32 * 32 + bit;\n }\n }\n }\n }\n }\n\n int width = right - left;\n int height = bottom - top;\n\n if (width < 0 || height < 0) {\n return null;\n }\n\n return new int[] {left, top, width, height};\n }\n\n /**\n * This is useful in detecting a corner of a 'pure' barcode.\n *\n * @return {@code x,y} coordinate of top-left-most 1 bit, or null if it is all white\n */\n public int[] getTopLeftOnBit() {\n int bitsOffset = 0;\n while (bitsOffset < bits.length && bits[bitsOffset] == 0) {\n bitsOffset++;\n }\n if (bitsOffset == bits.length) {\n return null;\n }\n int y = bitsOffset / rowSize;\n int x = (bitsOffset % rowSize) << 5;\n\n int theBits = bits[bitsOffset];\n int bit = 0;\n while ((theBits << (31-bit)) == 0) {\n bit++;\n }\n x += bit;\n return new int[] {x, y};\n }\n\n public int[] getBottomRightOnBit() {\n int bitsOffset = bits.length - 1;\n while (bitsOffset >= 0 && bits[bitsOffset] == 0) {\n bitsOffset--;\n }\n if (bitsOffset < 0) {\n return null;\n }\n\n int y = bitsOffset / rowSize;\n int x = (bitsOffset % rowSize) << 5;\n\n int theBits = bits[bitsOffset];\n int bit = 31;\n while ((theBits >>> bit) == 0) {\n bit--;\n }\n x += bit;\n\n return new int[] {x, y};\n }\n\n /**\n * @return The width of the matrix\n */\n public int getWidth() {\n return width;\n }\n\n /**\n * @return The height of the matrix\n */\n public int getHeight() {\n return height;\n }\n\n @Override\n public boolean equals(Object o) {\n if (!(o instanceof BitMatrix)) {\n return false;\n }\n BitMatrix other = (BitMatrix) o;\n return width == other.width && height == other.height && rowSize == other.rowSize &&\n Arrays.equals(bits, other.bits);\n }\n\n @Override\n public int hashCode() {\n int hash = width;\n hash = 31 * hash + width;\n hash = 31 * hash + height;\n hash = 31 * hash + rowSize;\n hash = 31 * hash + Arrays.hashCode(bits);\n return hash;\n }\n\n @Override\n public String toString() {\n StringBuilder result = new StringBuilder(height * (width + 1));\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n result.append(get(x, y) ? \"X \" : \" \");\n }\n result.append('\\n');\n }\n return result.toString();\n }\n\n @Override\n public BitMatrix clone() {\n return new BitMatrix(width, height, rowSize, bits.clone());\n }\n\n}",
"public enum CharacterSetECI {\n\n // Enum name is a Java encoding valid for java.lang and java.io\n Cp437(new int[]{0,2}),\n ISO8859_1(new int[]{1,3}, \"ISO-8859-1\"),\n ISO8859_2(4, \"ISO-8859-2\"),\n ISO8859_3(5, \"ISO-8859-3\"),\n ISO8859_4(6, \"ISO-8859-4\"),\n ISO8859_5(7, \"ISO-8859-5\"),\n ISO8859_6(8, \"ISO-8859-6\"),\n ISO8859_7(9, \"ISO-8859-7\"),\n ISO8859_8(10, \"ISO-8859-8\"),\n ISO8859_9(11, \"ISO-8859-9\"),\n ISO8859_10(12, \"ISO-8859-10\"),\n ISO8859_11(13, \"ISO-8859-11\"),\n ISO8859_13(15, \"ISO-8859-13\"),\n ISO8859_14(16, \"ISO-8859-14\"),\n ISO8859_15(17, \"ISO-8859-15\"),\n ISO8859_16(18, \"ISO-8859-16\"),\n SJIS(20, \"Shift_JIS\"),\n Cp1250(21, \"windows-1250\"),\n Cp1251(22, \"windows-1251\"),\n Cp1252(23, \"windows-1252\"),\n Cp1256(24, \"windows-1256\"),\n UnicodeBigUnmarked(25, \"UTF-16BE\", \"UnicodeBig\"),\n UTF8(26, \"UTF-8\"),\n ASCII(new int[] {27, 170}, \"US-ASCII\"),\n Big5(28),\n GB18030(29, \"GB2312\", \"EUC_CN\", \"GBK\"),\n EUC_KR(30, \"EUC-KR\");\n\n private static final Map<Integer,CharacterSetECI> VALUE_TO_ECI = new HashMap<>();\n private static final Map<String,CharacterSetECI> NAME_TO_ECI = new HashMap<>();\n static {\n for (CharacterSetECI eci : values()) {\n for (int value : eci.values) {\n VALUE_TO_ECI.put(value, eci);\n }\n NAME_TO_ECI.put(eci.name(), eci);\n for (String name : eci.otherEncodingNames) {\n NAME_TO_ECI.put(name, eci);\n }\n }\n }\n\n private final int[] values;\n private final String[] otherEncodingNames;\n\n CharacterSetECI(int value) {\n this(new int[] {value});\n }\n \n CharacterSetECI(int value, String... otherEncodingNames) {\n this.values = new int[] {value};\n this.otherEncodingNames = otherEncodingNames;\n }\n\n CharacterSetECI(int[] values, String... otherEncodingNames) {\n this.values = values;\n this.otherEncodingNames = otherEncodingNames;\n }\n\n public int getValue() {\n return values[0];\n }\n\n /**\n * @param value character set ECI value\n * @return CharacterSetECI representing ECI of given value, or null if it is legal but\n * unsupported\n * @throws IllegalArgumentException if ECI value is invalid\n */\n public static CharacterSetECI getCharacterSetECIByValue(int value) throws FormatException {\n if (value < 0 || value >= 900) {\n throw FormatException.getFormatInstance();\n }\n return VALUE_TO_ECI.get(value);\n }\n\n /**\n * @param name character set ECI encoding name\n * @return CharacterSetECI representing ECI for character encoding, or null if it is legal\n * but unsupported\n */\n public static CharacterSetECI getCharacterSetECIByName(String name) {\n return NAME_TO_ECI.get(name);\n }\n\n}",
"public enum Compaction {\n\n AUTO,\n TEXT,\n BYTE,\n NUMERIC\n\n}"
] | import android.graphics.Bitmap;
import com.justyoyo.contrast.BarcodeFormat;
import com.justyoyo.contrast.EncodeHintType;
import com.justyoyo.contrast.WriterException;
import com.justyoyo.contrast.common.BitMatrix;
import com.justyoyo.contrast.common.CharacterSetECI;
import com.justyoyo.contrast.common.Compaction;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
import static android.graphics.Color.BLACK;
import static android.graphics.Color.WHITE; | package com.justyoyo.contrast.pdf417;
/**
* Created by tiberiugolaes on 08/11/2016.
*/
public final class PDF417HighLevelEncoder {
private int dimension = Integer.MIN_VALUE;
private String displayContents = null;
private String contents = null;
private Map<EncodeHintType, Object> hints = null;
private boolean encoded = false;
public PDF417HighLevelEncoder(String data, int dimension, Map<EncodeHintType, Object> hints) {
this.dimension = dimension;
this.encoded = encodeContents(data);
this.hints = hints;
}
private boolean encodeContents(String data) {
contents = data;
displayContents = data;
return contents != null && contents.length() > 0;
}
public String getContents() {
return contents;
}
/**
* code for Text compaction
*/
private static final int TEXT_COMPACTION = 0;
/**
* code for Byte compaction
*/
private static final int BYTE_COMPACTION = 1;
/**
* code for Numeric compaction
*/
private static final int NUMERIC_COMPACTION = 2;
/**
* Text compaction submode Alpha
*/
private static final int SUBMODE_ALPHA = 0;
/**
* Text compaction submode Lower
*/
private static final int SUBMODE_LOWER = 1;
/**
* Text compaction submode Mixed
*/
private static final int SUBMODE_MIXED = 2;
/**
* Text compaction submode Punctuation
*/
private static final int SUBMODE_PUNCTUATION = 3;
/**
* mode latch to Text Compaction mode
*/
private static final int LATCH_TO_TEXT = 900;
/**
* mode latch to Byte Compaction mode (number of characters NOT a multiple of 6)
*/
private static final int LATCH_TO_BYTE_PADDED = 901;
/**
* mode latch to Numeric Compaction mode
*/
private static final int LATCH_TO_NUMERIC = 902;
/**
* mode shift to Byte Compaction mode
*/
private static final int SHIFT_TO_BYTE = 913;
/**
* mode latch to Byte Compaction mode (number of characters a multiple of 6)
*/
private static final int LATCH_TO_BYTE = 924;
/**
* identifier for a user defined Extended Channel Interpretation (ECI)
*/
private static final int ECI_USER_DEFINED = 925;
/**
* identifier for a general purpose ECO format
*/
private static final int ECI_GENERAL_PURPOSE = 926;
/**
* identifier for an ECI of a character set of code page
*/
private static final int ECI_CHARSET = 927;
/**
* Raw code table for text compaction Mixed sub-mode
*/
private static final byte[] TEXT_MIXED_RAW = {
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 38, 13, 9, 44, 58,
35, 45, 46, 36, 47, 43, 37, 42, 61, 94, 0, 32, 0, 0, 0};
/**
* Raw code table for text compaction: Punctuation sub-mode
*/
private static final byte[] TEXT_PUNCTUATION_RAW = {
59, 60, 62, 64, 91, 92, 93, 95, 96, 126, 33, 13, 9, 44, 58,
10, 45, 46, 36, 47, 34, 124, 42, 40, 41, 63, 123, 125, 39, 0};
private static final byte[] MIXED = new byte[128];
private static final byte[] PUNCTUATION = new byte[128];
private static final Charset DEFAULT_ENCODING = Charset.forName("ISO-8859-1");
public PDF417HighLevelEncoder() {
}
static {
//Construct inverse lookups
Arrays.fill(MIXED, (byte) -1);
for (int i = 0; i < TEXT_MIXED_RAW.length; i++) {
byte b = TEXT_MIXED_RAW[i];
if (b > 0) {
MIXED[b] = (byte) i;
}
}
Arrays.fill(PUNCTUATION, (byte) -1);
for (int i = 0; i < TEXT_PUNCTUATION_RAW.length; i++) {
byte b = TEXT_PUNCTUATION_RAW[i];
if (b > 0) {
PUNCTUATION[b] = (byte) i;
}
}
}
/**
* Performs high-level encoding of a PDF417 message using the algorithm described in annex P
* of ISO/IEC 15438:2001(E). If byte compaction has been selected, then only byte compaction
* is used.
*
* @param msg the message
* @param compaction compaction mode to use
* @param encoding character encoding used to encode in default or byte compaction
* or {@code null} for default / not applicable
* @return the encoded message (the char values range from 0 to 928)
*/ | public static String encodeHighLevel(String msg, Compaction compaction, Charset encoding) throws WriterException { | 2 |
KostyaSha/github-integration-plugin | github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/events/impl/GitHubPRLabelAddedEvent.java | [
"public class GitHubPRDecisionContext extends GitHubDecisionContext<GitHubPREvent, GitHubPRCause> {\n private final GHPullRequest remotePR;\n private final GitHubPRPullRequest localPR;\n private final GitHubPRUserRestriction prUserRestriction;\n private final GitHubPRRepository localRepo;\n\n protected GitHubPRDecisionContext(@CheckForNull GHPullRequest remotePR,\n @CheckForNull GitHubPRPullRequest localPR,\n @CheckForNull GitHubPRRepository localRepo,\n @CheckForNull GitHubPRUserRestriction prUserRestriction,\n GitHubSCMSource source,\n GitHubPRHandler prHandler,\n GitHubPRTrigger prTrigger,\n @NonNull TaskListener listener) {\n super(listener, prTrigger, source, prHandler);\n this.remotePR = remotePR;\n this.localPR = localPR;\n this.localRepo = localRepo;\n this.prUserRestriction = prUserRestriction;\n }\n\n @Deprecated\n protected GitHubPRDecisionContext(@CheckForNull GHPullRequest remotePR,\n @CheckForNull GitHubPRPullRequest localPR,\n @CheckForNull GitHubPRUserRestriction prUserRestriction,\n GitHubSCMSource source,\n GitHubPRHandler prHandler,\n GitHubPRTrigger prTrigger,\n @NonNull TaskListener listener) {\n this(remotePR, localPR, null, prUserRestriction, source, prHandler, prTrigger, listener);\n }\n\n /**\n * remotePR current PR state fetched from GH\n * remotePRs are always existing on gh.\n */\n @NonNull\n public GHPullRequest getRemotePR() {\n return remotePR;\n }\n\n /**\n * PR state from last run saved in jenkins. null when not exist before\n */\n @CheckForNull\n public GitHubPRPullRequest getLocalPR() {\n return localPR;\n }\n\n @CheckForNull\n public GitHubPRRepository getLocalRepo() {\n return localRepo;\n }\n\n @CheckForNull\n public GitHubPRUserRestriction getPrUserRestriction() {\n return prUserRestriction;\n }\n\n @Override\n public GitHubPRTrigger getTrigger() {\n return (GitHubPRTrigger) super.getTrigger();\n }\n\n @Override\n public GitHubPRHandler getHandler() {\n return (GitHubPRHandler) super.getHandler();\n }\n\n @CheckForNull\n @Deprecated\n public GitHubPRTrigger getPrTrigger() {\n return getTrigger();\n }\n\n @Override\n public GitHubPRCause checkEvent(GitHubPREvent event) throws IOException {\n return event.check(this);\n }\n\n @Override\n public GitHubPRCause newCause(String reason, boolean skip) {\n if (remotePR != null) {\n return new GitHubPRCause(remotePR, localRepo, reason, skip);\n }\n return new GitHubPRCause(localPR, null, localRepo, skip, reason);\n }\n\n public static class Builder {\n private GHPullRequest remotePR = null;\n private GitHubPRPullRequest localPR = null;\n private GitHubPRRepository localRepo = null;\n private TaskListener listener;\n private GitHubPRUserRestriction prUserRestriction = null;\n\n // depends on what job type it used\n private GitHubPRHandler prHandler = null;\n private GitHubPRTrigger prTrigger = null;\n private GitHubSCMSource source;\n\n\n public Builder() {\n }\n\n public Builder withRemotePR(@CheckForNull GHPullRequest remotePR) {\n this.remotePR = remotePR;\n return this;\n }\n\n public Builder withLocalPR(@CheckForNull GitHubPRPullRequest localPR) {\n this.localPR = localPR;\n return this;\n }\n\n public Builder withLocalRepo(GitHubPRRepository localRepo) {\n this.localRepo = localRepo;\n return this;\n }\n\n public Builder withListener(@NonNull TaskListener listener) {\n this.listener = listener;\n return this;\n }\n\n public Builder withPrHandler(@CheckForNull GitHubPRHandler prHandler) {\n this.prHandler = prHandler;\n return this;\n }\n\n // TODO abstract?\n public Builder withSCMSource(GitHubSCMSource source) {\n this.source = source;\n return this;\n }\n\n public Builder withPrTrigger(GitHubPRTrigger prTrigger) {\n this.prTrigger = prTrigger;\n return this;\n }\n\n public GitHubPRDecisionContext build() {\n if (isNull(prHandler)) {\n requireNonNull(prTrigger);\n } else {\n requireNonNull(prHandler);\n requireNonNull(source);\n }\n\n requireNonNull(listener);\n\n return new GitHubPRDecisionContext(remotePR, localPR, localRepo, prUserRestriction, source, prHandler, prTrigger, listener);\n }\n\n }\n\n @NonNull\n public static Builder newGitHubPRDecisionContext() {\n return new Builder();\n }\n}",
"public class GitHubPRCause extends GitHubCause<GitHubPRCause> {\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRCause.class);\n\n private String headSha;\n private int number;\n private boolean mergeable;\n private String targetBranch;\n private String sourceBranch;\n private String prAuthorEmail;\n private String body;\n\n private String sourceRepoOwner;\n private String triggerSenderName = \"\";\n private String triggerSenderEmail = \"\";\n private Set<String> labels;\n /**\n * In case triggered because of commit. See\n * {@link org.jenkinsci.plugins.github.pullrequest.events.impl.GitHubPROpenEvent}\n */\n private String commitAuthorName;\n private String commitAuthorEmail;\n\n private String condRef;\n private String state;\n private String commentAuthorName;\n private String commentAuthorEmail;\n private String commentBody;\n private String commentBodyMatch;\n\n public GitHubPRCause() {\n }\n\n public GitHubPRCause(GHPullRequest remotePr,\n GitHubPRRepository localRepo,\n String reason,\n boolean skip) {\n this(new GitHubPRPullRequest(remotePr), remotePr.getUser(), localRepo, skip, reason);\n withRemoteData(remotePr);\n if (localRepo != null) {\n withLocalRepo(localRepo);\n }\n }\n\n @Deprecated\n public GitHubPRCause(GHPullRequest remotePr,\n String reason,\n boolean skip) {\n this(remotePr, null, reason, skip);\n }\n\n public GitHubPRCause(GitHubPRPullRequest pr,\n GHUser triggerSender,\n GitHubPRRepository localRepo,\n boolean skip,\n String reason) {\n this(pr.getHeadSha(), pr.getNumber(),\n pr.isMergeable(), pr.getBaseRef(), pr.getHeadRef(),\n pr.getUserEmail(), pr.getTitle(), pr.getHtmlUrl(), pr.getSourceRepoOwner(),\n pr.getLabels(),\n triggerSender, skip, reason, \"\", \"\", pr.getState());\n this.body = pr.getBody();\n if (localRepo != null) {\n withLocalRepo(localRepo);\n }\n }\n\n @Deprecated\n public GitHubPRCause(GitHubPRPullRequest pr,\n GHUser triggerSender,\n boolean skip,\n String reason) {\n this(pr, triggerSender, null, skip, reason);\n }\n\n // FIXME (sizes) ParameterNumber: More than 7 parameters (found 15).\n // CHECKSTYLE:OFF\n public GitHubPRCause(String headSha, int number, boolean mergeable,\n String targetBranch, String sourceBranch, String prAuthorEmail,\n String title, URL htmlUrl, String sourceRepoOwner, Set<String> labels,\n GHUser triggerSender, boolean skip, String reason,\n String commitAuthorName, String commitAuthorEmail,\n String state) {\n // CHECKSTYLE:ON\n this.headSha = headSha;\n this.number = number;\n this.mergeable = mergeable;\n this.targetBranch = targetBranch;\n this.sourceBranch = sourceBranch;\n this.prAuthorEmail = prAuthorEmail;\n withTitle(title);\n withHtmlUrl(htmlUrl);\n this.sourceRepoOwner = sourceRepoOwner;\n this.labels = labels;\n withSkip(skip);\n withReason(reason);\n this.commitAuthorName = commitAuthorName;\n this.commitAuthorEmail = commitAuthorEmail;\n\n if (nonNull(triggerSender)) {\n try {\n this.triggerSenderName = triggerSender.getName();\n } catch (IOException e) {\n LOGGER.error(\"Can't get trigger sender name from remote PR\");\n }\n\n try {\n this.triggerSenderEmail = triggerSender.getEmail();\n } catch (IOException e) {\n LOGGER.error(\"Can't get trigger sender email from remote PR\");\n }\n }\n\n this.condRef = mergeable ? \"merge\" : \"head\";\n\n this.state = state;\n }\n\n @Override\n public GitHubPRCause withLocalRepo(@NonNull GitHubRepository localRepo) {\n withGitUrl(localRepo.getGitUrl());\n withSshUrl(localRepo.getSshUrl());\n // html url is set from constructor and points to pr\n // withHtmlUrl(localRepo.getGithubUrl());\n return this;\n }\n\n /**\n * Copy constructor\n */\n public GitHubPRCause(GitHubPRCause orig) {\n this(orig.getHeadSha(), orig.getNumber(), orig.isMergeable(),\n orig.getTargetBranch(), orig.getSourceBranch(),\n orig.getPRAuthorEmail(), orig.getTitle(),\n orig.getHtmlUrl(), orig.getSourceRepoOwner(), orig.getLabels(), null,\n orig.isSkip(), orig.getReason(), orig.getCommitAuthorName(), orig.getCommitAuthorEmail(), orig.getState());\n withTriggerSenderName(orig.getTriggerSenderEmail());\n withTriggerSenderEmail(orig.getTriggerSenderEmail());\n withBody(orig.getBody());\n withCommentAuthorName(orig.getCommentAuthorName());\n withCommentAuthorEmail(orig.getCommentAuthorEmail());\n withCommentBody(orig.getCommentBody());\n withCommentBodyMatch(orig.getCommentBodyMatch());\n withCommitAuthorName(orig.getCommitAuthorName());\n withCommitAuthorEmail(orig.getCommitAuthorEmail());\n withCondRef(orig.getCondRef());\n withGitUrl(orig.getGitUrl());\n withSshUrl(orig.getSshUrl());\n withPollingLog(orig.getPollingLog());\n }\n\n public static GitHubPRCause newGitHubPRCause() {\n return new GitHubPRCause();\n }\n\n /**\n * @see #headSha\n */\n public GitHubPRCause withHeadSha(String headSha) {\n this.headSha = headSha;\n return this;\n }\n\n /**\n * @see #number\n */\n public GitHubPRCause withNumber(int number) {\n this.number = number;\n return this;\n }\n\n /**\n * @see #mergeable\n */\n public GitHubPRCause withMergeable(boolean mergeable) {\n this.mergeable = mergeable;\n return this;\n }\n\n /**\n * @see #targetBranch\n */\n public GitHubPRCause withTargetBranch(String targetBranch) {\n this.targetBranch = targetBranch;\n return this;\n }\n\n /**\n * @see #sourceBranch\n */\n public GitHubPRCause withSourceBranch(String sourceBranch) {\n this.sourceBranch = sourceBranch;\n return this;\n }\n\n /**\n * @see #prAuthorEmail\n */\n public GitHubPRCause withPrAuthorEmail(String prAuthorEmail) {\n this.prAuthorEmail = prAuthorEmail;\n return this;\n }\n\n /**\n * @see #sourceRepoOwner\n */\n public GitHubPRCause withSourceRepoOwner(String sourceRepoOwner) {\n this.sourceRepoOwner = sourceRepoOwner;\n return this;\n }\n\n /**\n * @see #triggerSenderName\n */\n public GitHubPRCause withTriggerSenderName(String triggerSenderName) {\n this.triggerSenderName = triggerSenderName;\n return this;\n }\n\n /**\n * @see #triggerSenderEmail\n */\n public GitHubPRCause withTriggerSenderEmail(String triggerSenderEmail) {\n this.triggerSenderEmail = triggerSenderEmail;\n return this;\n }\n\n /**\n * @see #labels\n */\n public GitHubPRCause withLabels(Set<String> labels) {\n this.labels = labels;\n return this;\n }\n\n /**\n * @see #commitAuthorName\n */\n public GitHubPRCause withCommitAuthorName(String commitAuthorName) {\n this.commitAuthorName = commitAuthorName;\n return this;\n }\n\n /**\n * @see #commitAuthorEmail\n */\n public GitHubPRCause withCommitAuthorEmail(String commitAuthorEmail) {\n this.commitAuthorEmail = commitAuthorEmail;\n return this;\n }\n\n /**\n * @see #condRef\n */\n public GitHubPRCause withCondRef(String condRef) {\n this.condRef = condRef;\n return this;\n }\n\n public GitHubPRCause withCommentAuthorName(String commentAuthorName) {\n this.commentAuthorName = commentAuthorName;\n return this;\n }\n\n public GitHubPRCause withCommentAuthorEmail(String commentAuthorEmail) {\n this.commentAuthorEmail = commentAuthorEmail;\n return this;\n }\n\n public GitHubPRCause withCommentBody(String commentBody) {\n this.commentBody = commentBody;\n return this;\n }\n\n public GitHubPRCause withCommentBodyMatch(String commentBodyMatch) {\n this.commentBodyMatch = commentBodyMatch;\n return this;\n }\n\n public String getBody() {\n return body;\n }\n\n public GitHubPRCause withBody(String body) {\n this.body = body;\n return this;\n }\n\n @Override\n public String getShortDescription() {\n return \"GitHub PR #\" + number + \": \" + getReason();\n }\n\n public String getHeadSha() {\n return headSha;\n }\n\n public boolean isMergeable() {\n return mergeable;\n }\n\n public int getNumber() {\n return number;\n }\n\n public String getTargetBranch() {\n return targetBranch;\n }\n\n public String getSourceBranch() {\n return sourceBranch;\n }\n\n public String getPRAuthorEmail() {\n return prAuthorEmail;\n }\n\n public String getSourceRepoOwner() {\n return sourceRepoOwner;\n }\n\n @NonNull\n public Set<String> getLabels() {\n return isNull(labels) ? Collections.emptySet() : labels;\n }\n\n public String getTriggerSenderName() {\n return triggerSenderName;\n }\n\n public String getTriggerSenderEmail() {\n return triggerSenderEmail;\n }\n\n public String getPrAuthorEmail() {\n return prAuthorEmail;\n }\n\n public String getCommitAuthorName() {\n return commitAuthorName;\n }\n\n public String getCommitAuthorEmail() {\n return commitAuthorEmail;\n }\n\n public String getState() {\n return state;\n }\n\n @NonNull\n public String getCondRef() {\n return condRef;\n }\n\n /**\n * When trigger by comment, author of comment.\n */\n public String getCommentAuthorName() {\n return commentAuthorName;\n }\n\n /**\n * When trigger by comment, author email of comment.\n */\n public String getCommentAuthorEmail() {\n return commentAuthorEmail;\n }\n\n /**\n * When trigger by comment, body of comment.\n */\n public String getCommentBody() {\n return commentBody;\n }\n\n /**\n * When trigger by comment, string matched to pattern.\n */\n public String getCommentBodyMatch() {\n return commentBodyMatch;\n }\n\n @Override\n public void fillParameters(List<ParameterValue> params) {\n GitHubPREnv.getParams(this, params);\n }\n\n @Override\n public GitHubSCMHead<GitHubPRCause> createSCMHead(String sourceId) {\n return new GitHubPRSCMHead(number, targetBranch, sourceId);\n }\n\n @Override\n public void onAddedTo(@NonNull Run run) {\n if (run.getParent().getParent() instanceof SCMSourceOwner) {\n // skip multibranch\n return;\n }\n\n // move polling log from cause to action\n try {\n GitHubPRPollingLogAction action = new GitHubPRPollingLogAction(run);\n FileUtils.writeStringToFile(action.getPollingLogFile(), getPollingLog());\n run.replaceAction(action);\n } catch (IOException e) {\n LOGGER.warn(\"Failed to persist the polling log\", e);\n }\n setPollingLog(null);\n }\n\n @Override\n public boolean equals(Object o) {\n return EqualsBuilder.reflectionEquals(this, o);\n }\n\n @Override\n public int hashCode() {\n return HashCodeBuilder.reflectionHashCode(this);\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);\n }\n\n}",
"public class GitHubPRLabel implements Describable<GitHubPRLabel> {\n private Set<String> labels;\n\n @DataBoundConstructor\n public GitHubPRLabel(String labels) {\n this(new HashSet<>(Arrays.asList(labels.split(\"\\n\"))));\n }\n\n public GitHubPRLabel(Set<String> labels) {\n this.labels = labels;\n }\n\n // for UI binding\n public String getLabels() {\n return Joiner.on(\"\\n\").skipNulls().join(labels);\n }\n\n @NonNull\n public Set<String> getLabelsSet() {\n return nonNull(labels) ? labels : Collections.<String>emptySet();\n }\n\n public DescriptorImpl getDescriptor() {\n return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);\n }\n\n @Symbol(\"labels\")\n @Extension\n public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {\n @NonNull\n @Override\n public String getDisplayName() {\n return \"Labels\";\n }\n }\n}",
"public class GitHubPRPullRequest {\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRPullRequest.class);\n\n private final int number;\n // https://github.com/kohsuke/github-api/issues/178\n private final Date issueUpdatedAt;\n private String title;\n private String body;\n private Date prUpdatedAt;\n private String headSha;\n private String headRef;\n private Boolean mergeable;\n private String baseRef;\n private String userEmail;\n private String userLogin;\n private URL htmlUrl;\n private Set<String> labels;\n @CheckForNull\n private Date lastCommentCreatedAt;\n private String sourceRepoOwner;\n private String state;\n\n private boolean inBadState = false;\n\n /**\n * Save only what we need for next comparison\n */\n public GitHubPRPullRequest(GHPullRequest pr) {\n userLogin = pr.getUser().getLogin();\n number = pr.getNumber();\n try {\n prUpdatedAt = pr.getUpdatedAt();\n issueUpdatedAt = pr.getIssueUpdatedAt();\n } catch (IOException e) {\n // those methods never actually throw IOExceptions\n throw new IllegalStateException(e);\n }\n\n GHCommitPointer prHead = pr.getHead();\n headSha = prHead.getSha();\n headRef = prHead.getRef();\n sourceRepoOwner = prHead.getRepository().getOwnerName();\n\n title = pr.getTitle();\n baseRef = pr.getBase().getRef();\n htmlUrl = pr.getHtmlUrl();\n\n try {\n Date maxDate = new Date(0);\n List<GHIssueComment> comments = execute(pr::getComments);\n for (GHIssueComment comment : comments) {\n if (comment.getCreatedAt().compareTo(maxDate) > 0) {\n maxDate = comment.getCreatedAt();\n }\n }\n lastCommentCreatedAt = maxDate.getTime() == 0 ? null : new Date(maxDate.getTime());\n } catch (IOException e) {\n LOGGER.error(\"Can't get comments for PR: {}\", pr.getNumber(), e);\n lastCommentCreatedAt = null;\n }\n\n try {\n userEmail = execute(() -> pr.getUser().getEmail());\n } catch (Exception e) {\n LOGGER.error(\"Can't get GitHub user email.\", e);\n userEmail = \"\";\n }\n\n GHRepository remoteRepo = pr.getRepository();\n\n try {\n updateLabels(execute(() -> remoteRepo.getIssue(number).getLabels()));\n } catch (IOException e) {\n LOGGER.error(\"Can't retrieve label list: {}\", e);\n inBadState = true;\n }\n\n // see https://github.com/kohsuke/github-api/issues/111\n try {\n mergeable = execute(pr::getMergeable);\n } catch (IOException e) {\n LOGGER.error(\"Can't get mergeable status.\", e);\n mergeable = false;\n }\n\n state = pr.getState().toString();\n body = pr.getBody();\n }\n\n public int getNumber() {\n return number;\n }\n\n public String getHeadSha() {\n return headSha;\n }\n\n public boolean isMergeable() {\n return isNull(mergeable) ? false : mergeable;\n }\n\n public String getBaseRef() {\n return baseRef;\n }\n\n public String getHeadRef() {\n return headRef;\n }\n\n public String getUserEmail() {\n return userEmail;\n }\n\n public String getTitle() {\n return title;\n }\n\n public String getBody() {\n return body;\n }\n\n @NonNull\n public Set<String> getLabels() {\n return isNull(labels) ? Collections.<String>emptySet() : labels;\n }\n\n @CheckForNull\n public Date getLastCommentCreatedAt() {\n return lastCommentCreatedAt;\n }\n\n /**\n * URL to the Github Pull Request.\n */\n public URL getHtmlUrl() {\n return htmlUrl;\n }\n\n public Date getPrUpdatedAt() {\n return new Date(prUpdatedAt.getTime());\n }\n\n public Date getIssueUpdatedAt() {\n return issueUpdatedAt;\n }\n\n public String getUserLogin() {\n return userLogin;\n }\n\n public String getSourceRepoOwner() {\n return sourceRepoOwner;\n }\n\n /**\n * @see #state\n */\n @CheckForNull\n public String getState() {\n return state;\n }\n\n /**\n * as is\n */\n public void setLabels(Set<String> labels) {\n this.labels = labels;\n }\n\n private void updateLabels(Collection<GHLabel> labels) {\n this.labels = new HashSet<>();\n for (GHLabel label : labels) {\n this.labels.add(label.getName());\n }\n }\n\n /**\n * Indicates that remote PR wasn't fully saved locally during last check.\n */\n public boolean isInBadState() {\n return inBadState || isNull(labels);\n }\n\n public static String getIconFileName() {\n return Functions.getResourcePath() + \"/plugin/github-pullrequest/git-pull-request.svg\";\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this, SHORT_PREFIX_STYLE);\n }\n\n @Override\n public boolean equals(Object o) {\n return EqualsBuilder.reflectionEquals(this, o);\n }\n\n @Override\n public int hashCode() {\n return HashCodeBuilder.reflectionHashCode(this);\n }\n}",
"public abstract class GitHubPREvent extends AbstractDescribableImpl<GitHubPREvent> implements ExtensionPoint {\n\n /**\n * indicates that PR was changed\n *\n * @return cause object. null when no influence (other events will be checked.\n * If cause.isSkip() == true, then other checks wouldn't influence. And triggering for this branch will be skipped.\n * If cause.isSkip() == false, indicates that branch build should be run.\n */\n @CheckForNull\n public GitHubPRCause check(@NonNull GitHubPRDecisionContext prDecisionContext) throws IOException {\n return null;\n }\n\n /**\n * Check that is used for lightweight hooks (pure GitHub hooks).\n */\n public GitHubPRCause checkHook(GitHubPRTrigger gitHubPRTrigger,\n GHEventPayload payload,\n TaskListener listener) {\n return null;\n }\n\n @Override\n public GitHubPREventDescriptor getDescriptor() {\n return (GitHubPREventDescriptor) super.getDescriptor();\n }\n\n}"
] | import com.github.kostyasha.github.integration.generic.GitHubPRDecisionContext;
import hudson.Extension;
import hudson.model.TaskListener;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRCause;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRPullRequest;
import org.jenkinsci.plugins.github.pullrequest.events.GitHubPREvent;
import org.jenkinsci.plugins.github.pullrequest.events.GitHubPREventDescriptor;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.github.GHLabel;
import org.kohsuke.github.GHPullRequest;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static java.util.Objects.isNull; | package org.jenkinsci.plugins.github.pullrequest.events.impl;
/**
* When label is added to pull request. Set of labels is considered added only when
* at least one label of set was newly added (was not saved in local PR previously)
* AND every label of set exists on remote PR now.
*
* @author Kanstantsin Shautsou
*/
public class GitHubPRLabelAddedEvent extends GitHubPREvent {
private static final String DISPLAY_NAME = "Labels added";
private static final Logger LOG = LoggerFactory.getLogger(GitHubPRLabelAddedEvent.class);
private final GitHubPRLabel label;
@DataBoundConstructor
public GitHubPRLabelAddedEvent(GitHubPRLabel label) {
this.label = label;
}
public GitHubPRLabel getLabel() {
return label;
}
@Override | public GitHubPRCause check(@NonNull GitHubPRDecisionContext prDecisionContext) throws IOException { | 0 |
SecUSo/privacy-friendly-weather | app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestAddCity.java | [
"@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}",
"public enum HttpRequestType {\n POST,\n GET,\n PUT,\n DELETE\n}",
"public interface IHttpRequest {\n\n /**\n * Makes an HTTP request and processes the response.\n *\n * @param URL The target of the HTTP request.\n * @param method Which method to use for the HTTP request (e.g. GET or POST)\n * @param requestProcessor This object with its implemented methods processSuccessScenario and\n * processFailScenario defines how to handle the response in the success\n * and error case respectively.\n */\n void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor);\n\n}",
"public class VolleyHttpRequest implements IHttpRequest {\n\n private Context context;\n\n /**\n * Constructor.\n *\n * @param context Volley needs a context \"for creating the cache dir\".\n * @see Volley#newRequestQueue(Context)\n */\n public VolleyHttpRequest(Context context) {\n this.context = context;\n }\n\n /**\n * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest)\n */\n @Override\n public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) {\n RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory()));\n\n // Set the request method\n int requestMethod;\n switch (method) {\n case POST:\n requestMethod = Request.Method.POST;\n break;\n case GET:\n requestMethod = Request.Method.GET;\n break;\n case PUT:\n requestMethod = Request.Method.PUT;\n break;\n case DELETE:\n requestMethod = Request.Method.DELETE;\n break;\n default:\n requestMethod = Request.Method.GET;\n }\n\n // Execute the request and handle the response\n StringRequest stringRequest = new StringRequest(requestMethod, URL,\n new Response.Listener<String>() {\n @Override\n public void onResponse(String response) {\n requestProcessor.processSuccessScenario(response);\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n requestProcessor.processFailScenario(error);\n }\n }\n );\n\n queue.add(stringRequest);\n }\n\n private SSLSocketFactory getSocketFactory() {\n\n CertificateFactory cf = null;\n try {\n // Load CAs from an InputStream\n cf = CertificateFactory.getInstance(\"X.509\");\n InputStream caInput = new BufferedInputStream(context.getAssets().open(\"SectigoRSADomainValidationSecureServerCA.crt\"));\n\n Certificate ca;\n try {\n ca = cf.generateCertificate(caInput);\n Log.e(\"CERT\", \"ca=\" + ((X509Certificate) ca).getSubjectDN());\n } finally {\n caInput.close();\n }\n\n // Create a KeyStore containing our trusted CAs\n String keyStoreType = KeyStore.getDefaultType();\n KeyStore keyStore = KeyStore.getInstance(keyStoreType);\n keyStore.load(null, null);\n keyStore.setCertificateEntry(\"ca\", ca);\n\n // Create a TrustManager that trusts the CAs in our KeyStore\n String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();\n TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);\n tmf.init(keyStore);\n\n // Create an SSLContext that uses our TrustManager\n SSLContext context = SSLContext.getInstance(\"TLS\");\n context.init(null, tmf.getTrustManagers(), null);\n\n SSLSocketFactory sf = context.getSocketFactory();\n\n return sf;\n\n } catch (CertificateException e) {\n Log.e(\"CERT\", \"CertificateException\");\n e.printStackTrace();\n } catch (NoSuchAlgorithmException e) {\n Log.e(\"CERT\", \"NoSuchAlgorithmException\");\n e.printStackTrace();\n } catch (KeyStoreException e) {\n Log.e(\"CERT\", \"KeyStoreException\");\n e.printStackTrace();\n } catch (FileNotFoundException e) {\n Log.e(\"CERT\", \"FileNotFoundException\");\n e.printStackTrace();\n } catch (IOException e) {\n Log.e(\"CERT\", \"IOException\");\n e.printStackTrace();\n } catch (KeyManagementException e) {\n Log.e(\"CERT\", \"KeyManagementException\");\n e.printStackTrace();\n }\n\n return null;\n }\n\n}",
"public interface IHttpRequestForCityList {\n\n /**\n * @param cities A list of CityToWatch objects to get the latest weather data for. These data\n * are then displayed on the front page of the app.\n */\n void perform(List<CityToWatch> cities);\n\n}"
] | import android.content.Context;
import org.secuso.privacyfriendlyweather.database.data.CityToWatch;
import org.secuso.privacyfriendlyweather.http.HttpRequestType;
import org.secuso.privacyfriendlyweather.http.IHttpRequest;
import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest;
import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForCityList;
import java.util.List; | package org.secuso.privacyfriendlyweather.weather_api.open_weather_map;
/**
* This class provides the functionality for making and processing HTTP requests to the
* OpenWeatherMap to retrieve the latest weather data for a given city and then process the
* response.
*/
public class OwmHttpRequestAddCity extends OwmHttpRequest implements IHttpRequestForCityList {
private Context context;
/**
* @param context The application context.
*/
public OwmHttpRequestAddCity(Context context) {
this.context = context;
}
/**
* @see IHttpRequestForCityList#perform(List)
*/
@Override
public void perform(List<CityToWatch> cities) { | IHttpRequest httpRequest = new VolleyHttpRequest(context); | 2 |
Multiplayer-italia/AuthMe-Reloaded | src/main/java/uk/org/whoami/authme/commands/RegisterCommand.java | [
"public class Utils {\r\n //private Settings settings = Settings.getInstance();\r\n private Player player;\r\n private String currentGroup;\r\n private static Utils singleton;\r\n private String unLoggedGroup = Settings.getUnloggedinGroup;\r\n /* \r\n public Utils(Player player) {\r\n this.player = player;\r\n \r\n }\r\n */\r\n public void setGroup(Player player, groupType group) {\r\n if (!player.isOnline())\r\n return;\r\n if(!Settings.isPermissionCheckEnabled)\r\n return;\r\n \r\n switch(group) {\r\n case UNREGISTERED: {\r\n currentGroup = AuthMe.permission.getPrimaryGroup(player);\r\n AuthMe.permission.playerRemoveGroup(player, currentGroup);\r\n AuthMe.permission.playerAddGroup(player, Settings.unRegisteredGroup);\r\n break;\r\n }\r\n case REGISTERED: {\r\n currentGroup = AuthMe.permission.getPrimaryGroup(player);\r\n AuthMe.permission.playerRemoveGroup(player, currentGroup);\r\n AuthMe.permission.playerAddGroup(player, Settings.getRegisteredGroup);\r\n break;\r\n } \r\n }\r\n return;\r\n }\r\n \r\n public String removeAll(Player player) {\r\n if(!Utils.getInstance().useGroupSystem()){\r\n return null;\r\n }\r\n \r\n /*if (AuthMe.permission.playerAdd(this.player,\"-*\") ) {\r\n AuthMe.permission.playerAdd(this.player,\"authme.login\");\r\n return true;\r\n }*/\r\n \r\n \r\n //System.out.println(\"permissions? \"+ hasPerm);\r\n if( !Settings.getJoinPermissions.isEmpty() ) {\r\n hasPermOnJoin(player);\r\n }\r\n \r\n this.currentGroup = AuthMe.permission.getPrimaryGroup(player.getWorld(),player.getName().toString());\r\n //System.out.println(\"current grop\" + currentGroup);\r\n if(AuthMe.permission.playerRemoveGroup(player.getWorld(),player.getName().toString(), currentGroup) && AuthMe.permission.playerAddGroup(player.getWorld(),player.getName().toString(),this.unLoggedGroup)) {\r\n \r\n return currentGroup;\r\n }\r\n \r\n return null;\r\n \r\n }\r\n \r\n public boolean addNormal(Player player, String group) {\r\n if(!Utils.getInstance().useGroupSystem()){\r\n return false;\r\n }\r\n // System.out.println(\"in add normal\");\r\n /* if (AuthMe.permission.playerRemove(this.player, \"-*\"))\r\n return true;\r\n */ \r\n if(AuthMe.permission.playerRemoveGroup(player.getWorld(),player.getName().toString(),this.unLoggedGroup) && AuthMe.permission.playerAddGroup(player.getWorld(),player.getName().toString(),group)) {\r\n //System.out.println(\"vecchio \"+this.unLoggedGroup+ \"nuovo\" + group);\r\n return true;\r\n \r\n }\r\n return false;\r\n } \r\n\r\n private String hasPermOnJoin(Player player) {\r\n /* if(Settings.getJoinPermissions.isEmpty())\r\n return null; */\r\n Iterator<String> iter = Settings.getJoinPermissions.iterator();\r\n while (iter.hasNext()) {\r\n String permission = iter.next();\r\n // System.out.println(\"permissions? \"+ permission);\r\n \r\n if(AuthMe.permission.playerHas(player, permission)){\r\n // System.out.println(\"player has permissions \" +permission);\r\n AuthMe.permission.playerAddTransient(player, permission);\r\n }\r\n }\r\n return null;\r\n }\r\n \r\n public boolean isUnrestricted(Player player) {\r\n \r\n \r\n if(Settings.getUnrestrictedName.isEmpty() || Settings.getUnrestrictedName == null)\r\n return false;\r\n \r\n // System.out.println(\"name to escape \"+player.getName());\r\n if(Settings.getUnrestrictedName.contains(player.getName())) {\r\n // System.out.println(\"name to escape correctly\"+player.getName());\r\n return true;\r\n }\r\n \r\n return false;\r\n \r\n \r\n }\r\n public static Utils getInstance() {\r\n \r\n singleton = new Utils();\r\n \r\n return singleton;\r\n } \r\n \r\n private boolean useGroupSystem() {\r\n \r\n if(Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty()) {\r\n return true;\r\n } return false;\r\n \r\n }\r\n \r\n /*\r\n * Random Token for passpartu\r\n * \r\n */\r\n public boolean obtainToken() {\r\n File file = new File(\"plugins/AuthMe/passpartu.token\");\r\n\r\n\tif (file.exists())\r\n file.delete();\r\n\r\n\t\tFileWriter writer = null;\r\n\t\ttry {\r\n\t\t\tfile.createNewFile();\r\n\t\t\twriter = new FileWriter(file);\r\n String token = generateToken();\r\n writer.write(token+\":\"+System.currentTimeMillis()/1000+\"\\r\\n\");\r\n writer.flush();\r\n System.out.println(\"[AuthMe] Security passpartu token: \"+ token);\r\n writer.close();\r\n return true;\r\n } catch(Exception e) {\r\n e.printStackTrace(); \r\n }\r\n \r\n \r\n return false;\r\n }\r\n \r\n /*\r\n * Read Toekn\r\n */\r\n public boolean readToken(String inputToken) {\r\n File file = new File(\"plugins/AuthMe/passpartu.token\");\r\n \r\n\tif (!file.exists()) \t\r\n return false;\r\n \r\n if (inputToken.isEmpty() )\r\n return false;\r\n \r\n\t\tScanner reader = null;\r\n\t\ttry {\r\n\t\t\treader = new Scanner(file);\r\n\r\n\t\t\twhile (reader.hasNextLine()) {\r\n\t\t\t\tfinal String line = reader.nextLine();\r\n\r\n\t\t\t\tif (line.contains(\":\")) { \r\n String[] tokenInfo = line.split(\":\");\r\n //System.err.println(\"Authme input token \"+inputToken+\" saved token \"+tokenInfo[0]);\r\n //System.err.println(\"Authme time \"+System.currentTimeMillis()/1000+\"saved time \"+Integer.parseInt(tokenInfo[1]));\r\n if(tokenInfo[0].equals(inputToken) && System.currentTimeMillis()/1000-30 <= Integer.parseInt(tokenInfo[1]) ) { \r\n file.delete();\r\n reader.close();\r\n return true;\r\n }\r\n } \r\n }\r\n } catch(Exception e) {\r\n e.printStackTrace(); \r\n }\r\n \r\n\treader.close(); \r\n return false;\r\n }\r\n /*\r\n * Generate Random Token\r\n */\r\n private String generateToken() {\r\n // obtain new random token \r\n Random rnd = new Random ();\r\n char[] arr = new char[5];\r\n\r\n for (int i=0; i<5; i++) {\r\n int n = rnd.nextInt (36);\r\n arr[i] = (char) (n < 10 ? '0'+n : 'a'+n-10);\r\n }\r\n \r\n return new String(arr); \r\n }\r\n public enum groupType {\r\n UNREGISTERED, REGISTERED, NOTLOGGEDIN, LOGGEDIN\r\n }\r\n \r\n}\r",
"public class PlayerAuth {\r\n\r\n private String nickname;\r\n private String hash;\r\n private String ip;\r\n private long lastLogin;\r\n private int x,y,z;\r\n private String salt = \"\";\r\n private String vBhash = null;\r\n private int groupId;\r\n\r\n public PlayerAuth(String nickname, String hash, String ip, long lastLogin) {\r\n this.nickname = nickname;\r\n this.hash = hash;\r\n this.ip = ip;\r\n this.lastLogin = lastLogin;\r\n \r\n }\r\n \r\n public PlayerAuth(String nickname, int x, int y, int z) {\r\n this.nickname = nickname;\r\n this.x = x;\r\n this.y = y;\r\n this.z = z;\r\n }\r\n \r\n public PlayerAuth(String nickname, String hash, String ip, long lastLogin, int x, int y, int z) {\r\n this.nickname = nickname;\r\n this.hash = hash;\r\n this.ip = ip;\r\n this.lastLogin = lastLogin;\r\n this.x = x;\r\n this.y = y;\r\n this.z = z; \r\n }\r\n \r\n //\r\n // This constructor is needed for Vbulletin board Auth!\r\n //\r\n public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, long lastLogin, int x, int y, int z) {\r\n this.nickname = nickname;\r\n this.hash = hash;\r\n this.ip = ip;\r\n this.lastLogin = lastLogin;\r\n this.x = x;\r\n this.y = y;\r\n this.z = z; \r\n this.salt = salt;\r\n this.groupId = groupId;\r\n //System.out.println(\"[Authme Debug] password hashed from db\"+hash);\r\n //System.out.println(\"[Authme Debug] salt from db\"+salt); \r\n }\r\n \r\n public String getIp() {\r\n return ip;\r\n }\r\n\r\n public String getNickname() {\r\n return nickname;\r\n }\r\n\r\n public String getHash() {\r\n if(!salt.isEmpty())\r\n // Compose Vbullettin Hash System!\r\n return this.vBhash = \"$MD5vb$\"+salt+\"$\"+hash;\r\n else\r\n return hash;\r\n }\r\n \r\n //\r\n // GroupId for unactivated User on Vbullettin Board\r\n //\r\n public int getGroupId() {\r\n return groupId;\r\n }\r\n \r\n public int getQuitLocX() {\r\n return x;\r\n }\r\n public int getQuitLocY() {\r\n return y;\r\n }\r\n public int getQuitLocZ() {\r\n return z;\r\n }\r\n public void setQuitLocX(int x) {\r\n this.x = x;\r\n }\r\n public void setQuitLocY(int y) {\r\n this.y = y;\r\n }\r\n public void setQuitLocZ(int z) {\r\n this.z = z;\r\n } \r\n public long getLastLogin() {\r\n return lastLogin;\r\n }\r\n\r\n public void setHash(String hash) {\r\n this.hash = hash;\r\n }\r\n\r\n public void setIp(String ip) {\r\n this.ip = ip;\r\n }\r\n\r\n public void setLastLogin(long lastLogin) {\r\n this.lastLogin = lastLogin;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (!(obj instanceof PlayerAuth)) {\r\n return false;\r\n }\r\n PlayerAuth other = (PlayerAuth) obj;\r\n \r\n return other.getIp().equals(this.ip) && other.getNickname().equals(this.nickname);\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n int hashCode = 7;\r\n hashCode = 71 * hashCode + (this.nickname != null ? this.nickname.hashCode() : 0);\r\n hashCode = 71 * hashCode + (this.ip != null ? this.ip.hashCode() : 0);\r\n return hashCode;\r\n }\r\n}\r",
"public class LimboCache {\r\n\r\n private static LimboCache singleton = null;\r\n private HashMap<String, LimboPlayer> cache;\r\n //private Settings settings = Settings.getInstance();\r\n private FileCache playerData = new FileCache();\r\n \r\n private LimboCache() {\r\n this.cache = new HashMap<String, LimboPlayer>();\r\n }\r\n\r\n public void addLimboPlayer(Player player) {\r\n String name = player.getName().toLowerCase();\r\n Location loc = player.getLocation();\r\n int gameMode = player.getGameMode().getValue();\r\n ItemStack[] arm;\r\n ItemStack[] inv;\r\n boolean operator;\r\n String playerGroup = \"\";\r\n \r\n if (playerData.doesCacheExist(name)) {\r\n //DataFileCache playerInvArmor = playerData.readCache(name); \r\n inv = playerData.readCache(name).getInventory();\r\n arm = playerData.readCache(name).getArmour();\r\n playerGroup = playerData.readCache(name).getGroup();\r\n operator = playerData.readCache(name).getOperator();\r\n } else {\r\n inv = player.getInventory().getContents();\r\n arm = player.getInventory().getArmorContents();\r\n \r\n // check if player is an operator, then save it to ram if cache dosent exist!\r\n \r\n if(player.isOp() ) {\r\n //System.out.println(\"player is an operator in limboCache\");\r\n operator = true;\r\n }\r\n else operator = false; \r\n }\r\n\r\n \r\n \r\n if(Settings.isForceSurvivalModeEnabled) {\r\n if(Settings.isResetInventoryIfCreative && gameMode != 0 ) {\r\n player.sendMessage(\"Your inventory has been cleaned!\");\r\n inv = new ItemStack[36];\r\n arm = new ItemStack[4];\r\n }\r\n gameMode = 0;\r\n } \r\n if(player.isDead()) {\r\n \tloc = player.getWorld().getSpawnLocation();\r\n }\r\n \r\n if(cache.containsKey(name) && playerGroup.isEmpty()) {\r\n //System.out.println(\"contiene il player \"+name);\r\n LimboPlayer groupLimbo = cache.get(name);\r\n playerGroup = groupLimbo.getGroup();\r\n }\r\n \r\n cache.put(player.getName().toLowerCase(), new LimboPlayer(name, loc, inv, arm, gameMode, operator, playerGroup));\r\n //System.out.println(\"il gruppo in limboChace \"+playerGroup);\r\n }\r\n \r\n public void addLimboPlayer(Player player, String group) {\r\n \r\n cache.put(player.getName().toLowerCase(), new LimboPlayer(player.getName().toLowerCase(), group));\r\n //System.out.println(\"il gruppo in limboChace \"+group);\r\n }\r\n \r\n public void deleteLimboPlayer(String name) {\r\n cache.remove(name);\r\n }\r\n\r\n public LimboPlayer getLimboPlayer(String name) {\r\n return cache.get(name);\r\n }\r\n\r\n public boolean hasLimboPlayer(String name) {\r\n return cache.containsKey(name);\r\n }\r\n \r\n \r\n public static LimboCache getInstance() {\r\n if (singleton == null) {\r\n singleton = new LimboCache();\r\n }\r\n return singleton;\r\n }\r\n}\r",
"public class LimboPlayer {\r\n\r\n private String name;\r\n private ItemStack[] inventory;\r\n private ItemStack[] armour;\r\n private Location loc;\r\n private int timeoutTaskId = -1;\r\n private int gameMode = 0;\r\n private boolean operator;\r\n private String group;\r\n\r\n public LimboPlayer(String name, Location loc, ItemStack[] inventory, ItemStack[] armour, int gameMode, boolean operator, String group) {\r\n this.name = name;\r\n this.loc = loc;\r\n this.inventory = inventory;\r\n this.armour = armour;\r\n this.gameMode = gameMode;\r\n this.operator = operator;\r\n this.group = group;\r\n //System.out.println(\"il gruppo in limboPlayer \"+group);\r\n }\r\n \r\n public LimboPlayer(String name, String group) {\r\n this.name = name;\r\n this.group = group;\r\n }\r\n \r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public Location getLoc() {\r\n return loc;\r\n }\r\n\r\n public ItemStack[] getArmour() {\r\n return armour;\r\n }\r\n\r\n public ItemStack[] getInventory() {\r\n return inventory;\r\n }\r\n\r\n public int getTimeoutTaskId() {\r\n return timeoutTaskId;\r\n }\r\n\r\n public void setTimeoutTaskId(int timeoutTaskId) {\r\n this.timeoutTaskId = timeoutTaskId;\r\n }\r\n\r\n public int getGameMode() {\r\n return gameMode;\r\n }\r\n \r\n public boolean getOperator() {\r\n return operator;\r\n }\r\n \r\n public String getGroup() {\r\n return group;\r\n } \r\n}\r",
"public interface DataSource {\r\n\r\n public enum DataSourceType {\r\n\r\n MYSQL, FILE, SQLITE\r\n }\r\n\r\n boolean isAuthAvailable(String user);\r\n\r\n PlayerAuth getAuth(String user);\r\n\r\n boolean saveAuth(PlayerAuth auth);\r\n\r\n boolean updateSession(PlayerAuth auth);\r\n\r\n boolean updatePassword(PlayerAuth auth);\r\n\r\n int purgeDatabase(long until);\r\n\r\n boolean removeAuth(String user);\r\n \r\n boolean updateQuitLoc(PlayerAuth auth);\r\n \r\n int getIps(String ip);\r\n \r\n void close();\r\n\r\n void reload();\r\n}\r",
"public class PasswordSecurity {\r\n\r\n private static SecureRandom rnd = new SecureRandom();\r\n\r\n private static String getMD5(String message) throws NoSuchAlgorithmException {\r\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\r\n\r\n md5.reset();\r\n md5.update(message.getBytes());\r\n byte[] digest = md5.digest();\r\n\r\n return String.format(\"%0\" + (digest.length << 1) + \"x\", new BigInteger(1,\r\n digest));\r\n }\r\n\r\n private static String getSHA1(String message) throws NoSuchAlgorithmException {\r\n MessageDigest sha1 = MessageDigest.getInstance(\"SHA1\");\r\n sha1.reset();\r\n sha1.update(message.getBytes());\r\n byte[] digest = sha1.digest();\r\n\r\n return String.format(\"%0\" + (digest.length << 1) + \"x\", new BigInteger(1,\r\n digest));\r\n }\r\n\r\n private static String getSHA256(String message) throws NoSuchAlgorithmException {\r\n MessageDigest sha256 = MessageDigest.getInstance(\"SHA-256\");\r\n\r\n sha256.reset();\r\n sha256.update(message.getBytes());\r\n byte[] digest = sha256.digest();\r\n\r\n return String.format(\"%0\" + (digest.length << 1) + \"x\", new BigInteger(1,\r\n digest));\r\n }\r\n\r\n public static String getWhirlpool(String message) {\r\n Whirlpool w = new Whirlpool();\r\n byte[] digest = new byte[Whirlpool.DIGESTBYTES];\r\n w.NESSIEinit();\r\n w.NESSIEadd(message);\r\n w.NESSIEfinalize(digest);\r\n return Whirlpool.display(digest);\r\n }\r\n\r\n private static String getSaltedHash(String message, String salt) throws NoSuchAlgorithmException {\r\n return \"$SHA$\" + salt + \"$\" + getSHA256(getSHA256(message) + salt);\r\n }\r\n \r\n //\r\n // VBULLETIN 3.X 4.X METHOD\r\n //\r\n \r\n private static String getSaltedMd5(String message, String salt) throws NoSuchAlgorithmException {\r\n return \"$MD5vb$\" + salt + \"$\" + getMD5(getMD5(message) + salt);\r\n }\r\n \r\n private static String getXAuth(String message, String salt) {\r\n String hash = getWhirlpool(salt + message).toLowerCase();\r\n int saltPos = (message.length() >= hash.length() ? hash.length() - 1 : message.length());\r\n return hash.substring(0, saltPos) + salt + hash.substring(saltPos);\r\n }\r\n\r\n private static String createSalt(int length) throws NoSuchAlgorithmException {\r\n byte[] msg = new byte[40];\r\n rnd.nextBytes(msg);\r\n\r\n MessageDigest sha1 = MessageDigest.getInstance(\"SHA1\");\r\n sha1.reset();\r\n byte[] digest = sha1.digest(msg);\r\n return String.format(\"%0\" + (digest.length << 1) + \"x\", new BigInteger(1,digest)).substring(0, length);\r\n }\r\n\r\n public static String getHash(HashAlgorithm alg, String password) throws NoSuchAlgorithmException {\r\n switch (alg) {\r\n case MD5:\r\n return getMD5(password);\r\n case SHA1:\r\n return getSHA1(password);\r\n case SHA256:\r\n String salt = createSalt(16);\r\n return getSaltedHash(password, salt);\r\n case MD5VB:\r\n String salt2 = createSalt(16);\r\n return getSaltedMd5(password, salt2);\r\n case WHIRLPOOL:\r\n return getWhirlpool(password);\r\n case XAUTH:\r\n String xsalt = createSalt(12);\r\n return getXAuth(password, xsalt);\r\n case PHPBB:\r\n return getPhpBB(password);\r\n case PLAINTEXT:\r\n return getPlainText(password);\r\n default:\r\n throw new NoSuchAlgorithmException(\"Unknown hash algorithm\");\r\n }\r\n }\r\n\r\n public static boolean comparePasswordWithHash(String password, String hash) throws NoSuchAlgorithmException {\r\n //System.out.println(\"[Authme Debug] debug hashString\"+hash);\r\n if(hash.contains(\"$H$\")) {\r\n PhpBB checkHash = new PhpBB();\r\n return checkHash.phpbb_check_hash(password, hash);\r\n }\r\n // PlainText Password\r\n if(hash.length() < 32 ) {\r\n return hash.equals(password);\r\n }\r\n \r\n if (hash.length() == 32) {\r\n return hash.equals(getMD5(password));\r\n }\r\n\r\n if (hash.length() == 40) {\r\n return hash.equals(getSHA1(password));\r\n }\r\n\r\n if (hash.length() == 140) {\r\n int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length());\r\n String salt = hash.substring(saltPos, saltPos + 12);\r\n return hash.equals(getXAuth(password, salt));\r\n }\r\n\r\n if (hash.contains(\"$\")) {\r\n //System.out.println(\"[Authme Debug] debug hashString\"+hash);\r\n String[] line = hash.split(\"\\\\$\");\r\n if (line.length > 3 && line[1].equals(\"SHA\")) {\r\n return hash.equals(getSaltedHash(password, line[2]));\r\n } else {\r\n if(line[1].equals(\"MD5vb\")) {\r\n //System.out.println(\"[Authme Debug] password hashed from Authme\"+getSaltedMd5(password, line[2]));\r\n //System.out.println(\"[Authme Debug] salt from Authme\"+line[2]);\r\n //System.out.println(\"[Authme Debug] equals? Authme: \"+hash);\r\n //hash = \"$MD5vb$\" + salt + \"$\" + hash;\r\n return hash.equals(getSaltedMd5(password, line[2]));\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n private static String getPhpBB(String password) {\r\n PhpBB hash = new PhpBB();\r\n String phpBBhash = hash.phpbb_hash(password);\r\n return phpBBhash;\r\n }\r\n\r\n private static String getPlainText(String password) {\r\n return password;\r\n }\r\n\r\n public enum HashAlgorithm {\r\n\r\n MD5, SHA1, SHA256, WHIRLPOOL, XAUTH, MD5VB, PHPBB, PLAINTEXT\r\n }\r\n}\r",
"public class Messages extends CustomConfiguration {\r\n\r\n private static Messages singleton = null;\r\n private HashMap<String, String> map;\r\n \r\n\r\n public Messages() {\r\n \r\n super(new File(Settings.MESSAGE_FILE+\"_\"+Settings.messagesLanguage+\".yml\"));\r\n loadDefaults();\r\n loadFile();\r\n singleton = this;\r\n \r\n }\r\n \r\n private void loadDefaults() {\r\n this.set(\"logged_in\", \"&cAlready logged in!\");\r\n this.set(\"not_logged_in\", \"&cNot logged in!\");\r\n this.set(\"reg_disabled\", \"&cRegistration is disabled\");\r\n this.set(\"user_regged\", \"&cUsername already registered\");\r\n this.set(\"usage_reg\", \"&cUsage: /register password ConfirmPassword\");\r\n this.set(\"usage_log\", \"&cUsage: /login password\");\r\n this.set(\"user_unknown\", \"&cUsername not registered\");\r\n this.set(\"pwd_changed\", \"&cPassword changed!\");\r\n this.set(\"reg_only\", \"Registered players only! Please visit http://example.com to register\");\r\n this.set(\"valid_session\", \"&cSession login\");\r\n this.set(\"login_msg\", \"&cPlease login with \\\"/login password\\\"\");\r\n this.set(\"reg_msg\", \"&cPlease register with \\\"/register password ConfirmPassword\\\"\");\r\n this.set(\"timeout\", \"Login Timeout\");\r\n this.set(\"wrong_pwd\", \"&cWrong password\");\r\n this.set(\"logout\", \"&cSuccessful logout\");\r\n this.set(\"usage_unreg\", \"&cUsage: /unregister password\");\r\n this.set(\"registered\", \"&cSuccessfully registered!\");\r\n this.set(\"unregistered\", \"&cSuccessfully unregistered!\");\r\n this.set(\"login\", \"&cSuccessful login!\");\r\n this.set(\"no_perm\", \"&cNo Permission\");\r\n this.set(\"same_nick\", \"Same nick is already playing\");\r\n this.set(\"reg_voluntarily\", \"You can register your nickname with the server with the command \\\"/register password ConfirmPassword\\\"\");\r\n this.set(\"reload\", \"Configuration and database has been reloaded\");\r\n this.set(\"error\", \"An error ocurred; Please contact the admin\");\r\n this.set(\"unknown_user\", \"User is not in database\");\r\n this.set(\"unsafe_spawn\",\"Your Quit location was unsafe, teleporting you to World Spawn\");\r\n this.set(\"unvalid_session\",\"Session Dataes doesnt corrispond Plaese wait the end of session\");\r\n this.set(\"max_reg\",\"You have Exeded the max number of Registration for your Account\"); \r\n this.set(\"password_error\",\"Password doesnt match\");\r\n this.set(\"pass_len\",\"Your password dind't reach the minimum length or exeded the max length\");\r\n this.set(\"vb_nonActiv\",\"Your Account isent Activated yet check your Emails!\");\r\n this.set(\"usage_changepassword\", \"Usage: /changepassword oldPassword newPassword\");\r\n \r\n }\r\n\r\n\tprivate void loadFile() {\r\n this.load();\r\n this.save();\r\n \r\n }\r\n\r\n public String _(String msg) {\r\n String loc = this.getString(msg);\r\n if (loc != null) {\r\n return loc.replace(\"&\", \"\\u00a7\");\r\n }\r\n return msg;\r\n }\r\n \r\n \r\n public static Messages getInstance() {\r\n if (singleton == null) {\r\n singleton = new Messages();\r\n } \r\n return singleton;\r\n }\r\n \r\n}\r",
"public final class Settings extends YamlConfiguration {\r\n\r\n public static final String PLUGIN_FOLDER = \"./plugins/AuthMe\";\r\n public static final String CACHE_FOLDER = Settings.PLUGIN_FOLDER + \"/cache\";\r\n public static final String AUTH_FILE = Settings.PLUGIN_FOLDER + \"/auths.db\";\r\n public static final String MESSAGE_FILE = Settings.PLUGIN_FOLDER + \"/messages\";\r\n public static final String SETTINGS_FILE = Settings.PLUGIN_FOLDER + \"/config.yml\";\r\n public static List<String> getJoinPermissions = null;\r\n public static List<String> getUnrestrictedName = null;\r\n private static List<String> getRestrictedIp;\r\n \r\n private int numSettings = 59;\r\n public final Plugin plugin;\r\n private final File file; \r\n \r\n public static DataSourceType getDataSource;\r\n public static HashAlgorithm getPasswordHash;\r\n \r\n public static Boolean isPermissionCheckEnabled, isRegistrationEnabled, isForcedRegistrationEnabled,\r\n isTeleportToSpawnEnabled, isSessionsEnabled, isChatAllowed, isAllowRestrictedIp, \r\n isMovementAllowed, isKickNonRegisteredEnabled, isForceSingleSessionEnabled,\r\n isForceSpawnLocOnJoinEnabled, isForceExactSpawnEnabled, isSaveQuitLocationEnabled,\r\n isForceSurvivalModeEnabled, isResetInventoryIfCreative, isCachingEnabled, isKickOnWrongPasswordEnabled,\r\n getEnablePasswordVerifier, protectInventoryBeforeLogInEnabled, isBackupActivated, isBackupOnStart,\r\n isBackupOnStop, enablePasspartu;\r\n \r\n \r\n public static String getNickRegex, getUnloggedinGroup, getMySQLHost, getMySQLPort, \r\n getMySQLUsername, getMySQLPassword, getMySQLDatabase, getMySQLTablename, \r\n getMySQLColumnName, getMySQLColumnPassword, getMySQLColumnIp, getMySQLColumnLastLogin,\r\n getMySQLColumnSalt, getMySQLColumnGroup, unRegisteredGroup, backupWindowsPath,\r\n getcUnrestrictedName, getRegisteredGroup, messagesLanguage;\r\n \r\n \r\n public static int getWarnMessageInterval, getSessionTimeout, getRegistrationTimeout, getMaxNickLength,\r\n getMinNickLength, getPasswordMinLen, getMovementRadius, getmaxRegPerIp, getNonActivatedGroup,\r\n passwordMaxLength;\r\n \r\n protected static YamlConfiguration configFile;\r\n \r\n public Settings(Plugin plugin) {\r\n //super(new File(Settings.PLUGIN_FOLDER + \"/config.yml\"), this.plugin);\r\n this.file = new File(plugin.getDataFolder(),\"config.yml\");\r\n \r\n this.plugin = plugin;\r\n\r\n \r\n\r\n //options().indent(4); \r\n // Override to always indent 4 spaces\r\n if(exists()) {\r\n load(); \r\n }\r\n else {\r\n loadDefaults(file.getName());\r\n load();\r\n }\r\n \r\n configFile = (YamlConfiguration) plugin.getConfig();\r\n \r\n //saveDefaults();\r\n \r\n }\r\n \r\n public void loadConfigOptions() {\r\n \r\n plugin.getLogger().info(\"Loading Configuration File...\");\r\n \r\n mergeConfig();\r\n \r\n messagesLanguage = checkLang(configFile.getString(\"settings.messagesLanguage\",\"en\"));\r\n isPermissionCheckEnabled = configFile.getBoolean(\"permission.EnablePermissionCheck\", false);\r\n isForcedRegistrationEnabled = configFile.getBoolean(\"settings.registration.force\", true);\r\n isRegistrationEnabled = configFile.getBoolean(\"settings.registration.enabled\", true);\r\n isTeleportToSpawnEnabled = configFile.getBoolean(\"settings.restrictions.teleportUnAuthedToSpawn\",false);\r\n getWarnMessageInterval = configFile.getInt(\"settings.registration.messageInterval\",5);\r\n isSessionsEnabled = configFile.getBoolean(\"settings.sessions.enabled\",false);\r\n getSessionTimeout = configFile.getInt(\"settings.sessions.timeout\",10);\r\n getRegistrationTimeout = configFile.getInt(\"settings.restrictions.timeout\",30);\r\n isChatAllowed = configFile.getBoolean(\"settings.restrictions.allowChat\",false);\r\n getMaxNickLength = configFile.getInt(\"settings.restrictions.maxNicknameLength\",20);\r\n getMinNickLength = configFile.getInt(\"settings.restrictions.minNicknameLength\",3);\r\n getPasswordMinLen = configFile.getInt(\"settings.security.minPasswordLength\",4);\r\n getNickRegex = configFile.getString(\"settings.restrictions.allowedNicknameCharacters\",\"[a-zA-Z0-9_?]*\");\r\n isAllowRestrictedIp = configFile.getBoolean(\"settings.restrictions.AllowRestrictedUser\",false);\r\n getRestrictedIp = configFile.getStringList(\"settings.restrictions.AllowedRestrictedUser\");\r\n isMovementAllowed = configFile.getBoolean(\"settings.restrictions.allowMovement\",false);\r\n getMovementRadius = configFile.getInt(\"settings.restrictions.allowedMovementRadius\",100);\r\n getJoinPermissions = configFile.getStringList(\"GroupOptions.Permissions.PermissionsOnJoin\");\r\n isKickOnWrongPasswordEnabled = configFile.getBoolean(\"settings.restrictions.kickOnWrongPassword\",false);\r\n isKickNonRegisteredEnabled = configFile.getBoolean(\"settings.restrictions.kickNonRegistered\",false);\r\n isForceSingleSessionEnabled = configFile.getBoolean(\"settings.restrictions.ForceSingleSession\",true);\r\n isForceSpawnLocOnJoinEnabled = configFile.getBoolean(\"settings.restrictions.ForceSpawnLocOnJoinEnabled\",false);\r\n isSaveQuitLocationEnabled = configFile.getBoolean(\"settings.restrictions.SaveQuitLocation\", false);\r\n isForceSurvivalModeEnabled = configFile.getBoolean(\"settings.GameMode.ForceSurvivalMode\", false);\r\n isResetInventoryIfCreative = configFile.getBoolean(\"settings.GameMode.ResetInventotyIfCreative\",false);\r\n getmaxRegPerIp = configFile.getInt(\"settings.restrictions.maxRegPerIp\",1);\r\n getPasswordHash = getPasswordHash();\r\n getUnloggedinGroup = configFile.getString(\"settings.security.unLoggedinGroup\",\"unLoggedInGroup\");\r\n getDataSource = getDataSource();\r\n isCachingEnabled = configFile.getBoolean(\"DataSource.caching\",true);\r\n getMySQLHost = configFile.getString(\"DataSource.mySQLHost\",\"127.0.0.1\");\r\n getMySQLPort = configFile.getString(\"DataSource.mySQLPort\",\"3306\");\r\n getMySQLUsername = configFile.getString(\"DataSource.mySQLUsername\",\"authme\");\r\n getMySQLPassword = configFile.getString(\"DataSource.mySQLPassword\",\"12345\");\r\n getMySQLDatabase = configFile.getString(\"DataSource.mySQLDatabase\",\"authme\");\r\n getMySQLTablename = configFile.getString(\"DataSource.mySQLTablename\",\"authme\");\r\n getMySQLColumnName = configFile.getString(\"DataSource.mySQLColumnName\",\"username\");\r\n getMySQLColumnPassword = configFile.getString(\"DataSource.mySQLColumnPassword\",\"password\");\r\n getMySQLColumnIp = configFile.getString(\"DataSource.mySQLColumnIp\",\"ip\");\r\n getMySQLColumnLastLogin = configFile.getString(\"DataSource.mySQLColumnLastLogin\",\"lastlogin\");\r\n getMySQLColumnSalt = configFile.getString(\"ExternalBoardOptions.mySQLColumnSalt\");\r\n getMySQLColumnGroup = configFile.getString(\"ExternalBoardOptions.mySQLColumnGroup\",\"\");\r\n getNonActivatedGroup = configFile.getInt(\"ExternalBoardOptions.nonActivedUserGroup\", -1);\r\n unRegisteredGroup = configFile.getString(\"GroupOptions.UnregisteredPlayerGroup\",\"\");\r\n getUnrestrictedName = configFile.getStringList(\"settings.unrestrictions.UnrestrictedName\");\r\n getRegisteredGroup = configFile.getString(\"GroupOptions.RegisteredPlayerGroup\",\"\");\r\n getEnablePasswordVerifier = configFile.getBoolean(\"settings.restrictions.enablePasswordVerifier\" , true);\r\n protectInventoryBeforeLogInEnabled = configFile.getBoolean(\"settings.restrictions.ProtectInventoryBeforeLogIn\", true);\r\n passwordMaxLength = configFile.getInt(\"settings.security.passwordMaxLength\", 20);\r\n isBackupActivated = configFile.getBoolean(\"BackupSystem.ActivateBackup\",false);\r\n isBackupOnStart = configFile.getBoolean(\"BackupSystem.OnServerStart\",false);\r\n isBackupOnStop = configFile.getBoolean(\"BackupSystem.OnServeStop\",false);\r\n backupWindowsPath = configFile.getString(\"BackupSystem.MysqlWindowsPath\", \"C:\\\\Program Files\\\\MySQL\\\\MySQL Server 5.1\\\\\");\r\n enablePasspartu = configFile.getBoolean(\"Passpartu.enablePasspartu\",false);\r\n\r\n\r\n saveDefaults();\r\n \r\n //System.out.println(\"[AuthMe debug] Config \" + getEnablePasswordVerifier.toString());\r\n //System.out.println(\"[AuthMe debug] Config \" + getEnablePasswordVerifier.toString());\r\n\r\n \r\n }\r\n \r\n public static void reloadConfigOptions(YamlConfiguration newConfig) {\r\n configFile = newConfig;\r\n \r\n //plugin.getLogger().info(\"RELoading Configuration File...\");\r\n messagesLanguage = checkLang(configFile.getString(\"settings.messagesLanguage\",\"en\"));\r\n isPermissionCheckEnabled = configFile.getBoolean(\"permission.EnablePermissionCheck\", false);\r\n isForcedRegistrationEnabled = configFile.getBoolean(\"settings.registration.force\", true);\r\n isRegistrationEnabled = configFile.getBoolean(\"settings.registration.enabled\", true);\r\n isTeleportToSpawnEnabled = configFile.getBoolean(\"settings.restrictions.teleportUnAuthedToSpawn\",false);\r\n getWarnMessageInterval = configFile.getInt(\"settings.registration.messageInterval\",5);\r\n isSessionsEnabled = configFile.getBoolean(\"settings.sessions.enabled\",false);\r\n getSessionTimeout = configFile.getInt(\"settings.sessions.timeout\",10);\r\n getRegistrationTimeout = configFile.getInt(\"settings.restrictions.timeout\",30);\r\n isChatAllowed = configFile.getBoolean(\"settings.restrictions.allowChat\",false);\r\n getMaxNickLength = configFile.getInt(\"settings.restrictions.maxNicknameLength\",20);\r\n getMinNickLength = configFile.getInt(\"settings.restrictions.minNicknameLength\",3);\r\n getPasswordMinLen = configFile.getInt(\"settings.security.minPasswordLength\",4);\r\n getNickRegex = configFile.getString(\"settings.restrictions.allowedNicknameCharacters\",\"[a-zA-Z0-9_?]*\");\r\n isAllowRestrictedIp = configFile.getBoolean(\"settings.restrictions.AllowRestrictedUser\",false);\r\n getRestrictedIp = configFile.getStringList(\"settings.restrictions.AllowedRestrictedUser\");\r\n isMovementAllowed = configFile.getBoolean(\"settings.restrictions.allowMovement\",false);\r\n getMovementRadius = configFile.getInt(\"settings.restrictions.allowedMovementRadius\",100);\r\n getJoinPermissions = configFile.getStringList(\"GroupOptions.Permissions.PermissionsOnJoin\");\r\n isKickOnWrongPasswordEnabled = configFile.getBoolean(\"settings.restrictions.kickOnWrongPassword\",false);\r\n isKickNonRegisteredEnabled = configFile.getBoolean(\"settings.restrictions.kickNonRegistered\",false);\r\n isForceSingleSessionEnabled = configFile.getBoolean(\"settings.restrictions.ForceSingleSession\",true);\r\n isForceSpawnLocOnJoinEnabled = configFile.getBoolean(\"settings.restrictions.ForceSpawnLocOnJoinEnabled\",false); \r\n isSaveQuitLocationEnabled = configFile.getBoolean(\"settings.restrictions.SaveQuitLocation\",false);\r\n isForceSurvivalModeEnabled = configFile.getBoolean(\"settings.GameMode.ForceSurvivalMode\",false);\r\n isResetInventoryIfCreative = configFile.getBoolean(\"settings.GameMode.ResetInventotyIfCreative\",false);\r\n getmaxRegPerIp = configFile.getInt(\"settings.restrictions.maxRegPerIp\",1);\r\n getPasswordHash = getPasswordHash();\r\n getUnloggedinGroup = configFile.getString(\"settings.security.unLoggedinGroup\",\"unLoggedInGroup\");\r\n getDataSource = getDataSource();\r\n isCachingEnabled = configFile.getBoolean(\"DataSource.caching\",true);\r\n getMySQLHost = configFile.getString(\"DataSource.mySQLHost\",\"127.0.0.1\");\r\n getMySQLPort = configFile.getString(\"DataSource.mySQLPort\",\"3306\");\r\n getMySQLUsername = configFile.getString(\"DataSource.mySQLUsername\",\"authme\");\r\n getMySQLPassword = configFile.getString(\"DataSource.mySQLPassword\",\"12345\");\r\n getMySQLDatabase = configFile.getString(\"DataSource.mySQLDatabase\",\"authme\");\r\n getMySQLTablename = configFile.getString(\"DataSource.mySQLTablename\",\"authme\");\r\n getMySQLColumnName = configFile.getString(\"DataSource.mySQLColumnName\",\"username\");\r\n getMySQLColumnPassword = configFile.getString(\"DataSource.mySQLColumnPassword\",\"password\");\r\n getMySQLColumnIp = configFile.getString(\"DataSource.mySQLColumnIp\",\"ip\");\r\n getMySQLColumnLastLogin = configFile.getString(\"DataSource.mySQLColumnLastLogin\",\"lastlogin\");\r\n getMySQLColumnSalt = configFile.getString(\"ExternalBoardOptions.mySQLColumnSalt\",\"\");\r\n getMySQLColumnGroup = configFile.getString(\"ExternalBoardOptions.mySQLColumnGroup\",\"\");\r\n getNonActivatedGroup = configFile.getInt(\"ExternalBoardOptions.nonActivedUserGroup\", -1);\r\n unRegisteredGroup = configFile.getString(\"GroupOptions.UnregisteredPlayerGroup\",\"\");\r\n getUnrestrictedName = configFile.getStringList(\"settings.unrestrictions.UnrestrictedName\");\r\n getRegisteredGroup = configFile.getString(\"GroupOptions.RegisteredPlayerGroup\",\"\"); \r\n getEnablePasswordVerifier = configFile.getBoolean(\"settings.restrictions.enablePasswordVerifier\" , true);\r\n protectInventoryBeforeLogInEnabled = configFile.getBoolean(\"settings.restrictions.ProtectInventoryBeforeLogIn\", true);\r\n passwordMaxLength = configFile.getInt(\"settings.security.passwordMaxLength\", 20);\r\n isBackupActivated = configFile.getBoolean(\"BackupSystem.ActivateBackup\",false);\r\n isBackupOnStart = configFile.getBoolean(\"BackupSystem.OnServerStart\",false);\r\n isBackupOnStop = configFile.getBoolean(\"BackupSystem.OnServeStop\",false); \r\n backupWindowsPath = configFile.getString(\"BackupSystem.MysqlWindowsPath\", \"C:\\\\Program Files\\\\MySQL\\\\MySQL Server 5.1\\\\\");\r\n enablePasspartu = configFile.getBoolean(\"Passpartu.enablePasspartu\",false);\r\n \r\n //System.out.println(getMySQLDatabase);\r\n \r\n \r\n }\r\n \r\n public void mergeConfig() {\r\n \r\n //options().copyDefaults(false);\r\n //System.out.println(\"merging config?\"+contains(\"settings.restrictions.ProtectInventoryBeforeLogIn\")+checkDefaults());\r\n if(!contains(\"settings.restrictions.ProtectInventoryBeforeLogIn\")) {\r\n set(\"settings.restrictions.enablePasswordVerifier\", true);\r\n set(\"settings.restrictions.ProtectInventoryBeforeLogIn\", true);\r\n } \r\n \r\n if(!contains(\"settings.security.passwordMaxLength\")) {\r\n set(\"settings.security.passwordMaxLength\", 20);\r\n }\r\n \r\n if(!contains(\"BackupSystem.ActivateBackup\")) {\r\n set(\"BackupSystem.ActivateBackup\",false);\r\n set(\"BackupSystem.OnServerStart\",false);\r\n set(\"BackupSystem.OnServeStop\",false);\r\n }\r\n \r\n \r\n if(!contains(\"BackupSystem.MysqlWindowsPath\")) {\r\n set(\"BackupSystem.MysqlWindowsPath\", \"C:\\\\Program Files\\\\MySQL\\\\MySQL Server 5.1\\\\\");\r\n }\r\n \r\n if(!contains(\"settings.messagesLanguage\")) {\r\n set(\"settings.messagesLanguage\",\"en\");\r\n }\r\n \r\n if(!contains(\"passpartu.enablePasspartu\")) {\r\n set(\"Passpartu.enablePasspartu\",false);\r\n } else return;\r\n \r\n plugin.getLogger().info(\"Merge new Config Options..\");\r\n plugin.saveConfig();\r\n \r\n return;\r\n }\r\n /** \r\n * \r\n * \r\n * \r\n */ \r\n private static HashAlgorithm getPasswordHash() {\r\n String key = \"settings.security.passwordHash\";\r\n\r\n try {\r\n return PasswordSecurity.HashAlgorithm.valueOf(configFile.getString(key,\"SHA256\").toUpperCase());\r\n } catch (IllegalArgumentException ex) {\r\n ConsoleLogger.showError(\"Unknown Hash Algorithm; defaulting to SHA256\");\r\n return PasswordSecurity.HashAlgorithm.SHA256;\r\n }\r\n }\r\n \r\n /** \r\n * \r\n * \r\n * \r\n */\r\n private static DataSourceType getDataSource() {\r\n String key = \"DataSource.backend\";\r\n\r\n try {\r\n return DataSource.DataSourceType.valueOf(configFile.getString(key).toUpperCase());\r\n } catch (IllegalArgumentException ex) {\r\n ConsoleLogger.showError(\"Unknown database backend; defaulting to file database\");\r\n return DataSource.DataSourceType.FILE;\r\n }\r\n }\r\n\r\n /**\r\n * Config option for setting and check restricted user by\r\n * username;ip , return false if ip and name doesnt amtch with\r\n * player that join the server, so player has a restricted access\r\n */ \r\n public static Boolean getRestrictedIp(String name, String ip) {\r\n \r\n Iterator<String> iter = getRestrictedIp.iterator();\r\n while (iter.hasNext()) {\r\n String[] args = iter.next().split(\";\");\r\n //System.out.println(\"name restricted \"+args[0]+\"name 2:\"+name+\"ip\"+args[1]+\"ip2\"+ip);\r\n if(args[0].equalsIgnoreCase(name) ) {\r\n if(args[1].equalsIgnoreCase(ip)) {\r\n //System.out.println(\"name restricted \"+args[0]+\"name 2:\"+name+\"ip\"+args[1]+\"ip2\"+ip);\r\n return true;\r\n } else return false;\r\n } \r\n }\r\n return true;\r\n }\r\n\r\n \r\n /**\r\n * Loads the configuration from disk\r\n *\r\n * @return True if loaded successfully\r\n */\r\n public final boolean load() {\r\n try {\r\n load(file);\r\n return true;\r\n } catch (Exception ex) {\r\n return false;\r\n }\r\n }\r\n \r\n public final void reload() {\r\n load();\r\n loadDefaults(file.getName());\r\n }\r\n\r\n /**\r\n * Saves the configuration to disk\r\n *\r\n * @return True if saved successfully\r\n */\r\n public final boolean save() {\r\n try {\r\n save(file);\r\n return true;\r\n } catch (Exception ex) {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Simple function for if the Configuration file exists\r\n *\r\n * @return True if configuration exists on disk\r\n */\r\n public final boolean exists() {\r\n return file.exists();\r\n }\r\n\r\n /**\r\n * Loads a file from the plugin jar and sets as default\r\n *\r\n * @param filename The filename to open\r\n */\r\n public final void loadDefaults(String filename) {\r\n InputStream stream = plugin.getResource(filename);\r\n if(stream == null) return;\r\n\r\n setDefaults(YamlConfiguration.loadConfiguration(stream));\r\n }\r\n\r\n /**\r\n * Saves current configuration (plus defaults) to disk.\r\n *\r\n * If defaults and configuration are empty, saves blank file.\r\n *\r\n * @return True if saved successfully\r\n */\r\n public final boolean saveDefaults() {\r\n options().copyDefaults(true);\r\n options().copyHeader(true);\r\n boolean success = save();\r\n options().copyDefaults(false);\r\n options().copyHeader(false);\r\n\r\n return success;\r\n }\r\n\r\n\r\n /**\r\n * Clears current configuration defaults\r\n */\r\n public final void clearDefaults() {\r\n setDefaults(new MemoryConfiguration());\r\n }\r\n\r\n /**\r\n* Check loaded defaults against current configuration\r\n*\r\n* @return false When all defaults aren't present in config\r\n*/\r\n public boolean checkDefaults() {\r\n if (getDefaults() == null) {\r\n return true;\r\n }\r\n return getKeys(true).containsAll(getDefaults().getKeys(true));\r\n }\r\n /* \r\n public static Settings getInstance() {\r\n if (singleton == null) {\r\n singleton = new Settings();\r\n }\r\n return singleton;\r\n }\r\n*/\r\n public static String checkLang(String lang) {\r\n for(messagesLang language: messagesLang.values()) {\r\n //System.out.println(language.toString());\r\n if(lang.toLowerCase().contains(language.toString())) {\r\n ConsoleLogger.info(\"Set Language: \"+lang);\r\n return lang;\r\n } \r\n }\r\n ConsoleLogger.info(\"Set Default Language: En \");\r\n return \"en\";\r\n }\r\n \r\n public enum messagesLang {\r\n en, de, br, cz\r\n } \r\n}\r"
] | import uk.org.whoami.authme.cache.limbo.LimboPlayer;
import uk.org.whoami.authme.datasource.DataSource;
import uk.org.whoami.authme.security.PasswordSecurity;
import uk.org.whoami.authme.settings.Messages;
import uk.org.whoami.authme.settings.Settings;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import uk.org.whoami.authme.ConsoleLogger;
import uk.org.whoami.authme.Utils;
import uk.org.whoami.authme.cache.auth.PlayerAuth;
import uk.org.whoami.authme.cache.auth.PlayerCache;
import uk.org.whoami.authme.cache.limbo.LimboCache;
| /*
* Copyright 2011 Sebastian Köhler <[email protected]>.
*
* 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 uk.org.whoami.authme.commands;
public class RegisterCommand implements CommandExecutor {
private Messages m = Messages.getInstance();
//private Settings settings = Settings.getInstance();
private DataSource database;
public boolean isFirstTimeJoin;
public RegisterCommand(DataSource database) {
this.database = database;
this.isFirstTimeJoin = false;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!sender.hasPermission("authme." + label.toLowerCase())) {
sender.sendMessage(m._("no_perm"));
return true;
}
Player player = (Player) sender;
String name = player.getName().toLowerCase();
String ip = player.getAddress().getAddress().getHostAddress();
if (PlayerCache.getInstance().isAuthenticated(name)) {
player.sendMessage(m._("logged_in"));
return true;
}
if (!Settings.isRegistrationEnabled) {
player.sendMessage(m._("reg_disabled"));
return true;
}
if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2) ) {
player.sendMessage(m._("usage_reg"));
return true;
}
//System.out.println("pass legth "+args[0].length());
//System.out.println("pass length permit"+Settings.passwordMaxLength);
if(args[0].length() < Settings.getPasswordMinLen || args[0].length() > Settings.passwordMaxLength) {
player.sendMessage(m._("pass_len"));
return true;
}
if (database.isAuthAvailable(player.getName().toLowerCase())) {
player.sendMessage(m._("user_regged"));
return true;
}
//
// Check if player exeded the max number of registration
//
if(Settings.getmaxRegPerIp > 0 ){
String ipAddress = player.getAddress().getAddress().getHostAddress();
if(!sender.hasPermission("authme.allow2accounts") && database.getIps(ipAddress) >= Settings.getmaxRegPerIp) {
//System.out.println("number of reg "+database.getIps(ipAddress));
player.sendMessage(m._("max_reg"));
return true;
}
}
try {
String hash;
if(Settings.getEnablePasswordVerifier) {
if (args[0].equals(args[1])) {
hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[0]);
} else {
player.sendMessage(m._("password_error"));
return true;
}
} else
hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[0]);
PlayerAuth auth = new PlayerAuth(name, hash, ip, new Date().getTime());
if (!database.saveAuth(auth)) {
player.sendMessage(m._("error"));
return true;
}
PlayerCache.getInstance().addPlayer(auth);
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (limbo != null) {
// player.getInventory().setContents(limbo.getInventory());
// player.getInventory().setArmorContents(limbo.getArmour());
player.setGameMode(GameMode.getByValue(limbo.getGameMode()));
if (Settings.isTeleportToSpawnEnabled) {
player.teleport(limbo.getLoc());
}
sender.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId());
LimboCache.getInstance().deleteLimboPlayer(name);
}
if(!Settings.getRegisteredGroup.isEmpty()){
| Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED);
| 0 |
onepf/OPFPush | opfpush/src/main/java/org/onepf/opfpush/backoff/RetryManager.java | [
"public final class ConnectivityChangeReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(@NonNull final Context context, @NonNull final Intent intent) {\n OPFLog.logMethod(context, OPFUtils.toString(intent));\n\n final Set<Pair<String, String>> retryProvidersActions = RetryManager.getInstance()\n .getRetryProvidersActions();\n\n final OPFPushHelper helper = OPFPush.getHelper();\n for (Pair<String, String> retryProviderAction : retryProvidersActions) {\n final String providerName = retryProviderAction.first;\n final String action = retryProviderAction.second;\n switch (action) {\n case ACTION_RETRY_REGISTER:\n helper.register(providerName);\n break;\n case ACTION_RETRY_UNREGISTER:\n helper.unregister(providerName);\n break;\n }\n }\n }\n}",
"public final class RetryBroadcastReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(@NonNull final Context context, @NonNull final Intent intent) {\n OPFLog.logMethod(context, OPFUtils.toString(intent));\n\n final OPFPushHelper helper = OPFPush.getHelper();\n if (helper.isInitDone()) {\n OPFLog.d(\"Initialisation is done\");\n\n final String action = intent.getAction();\n final String providerName = intent.getStringExtra(EXTRA_PROVIDER_NAME);\n switch (action) {\n case ACTION_RETRY_REGISTER:\n helper.register(providerName);\n break;\n case ACTION_RETRY_UNREGISTER:\n helper.unregister(providerName);\n break;\n case ACTION_CHECK_REGISTERING_TIMEOUT:\n checkRegistering(context, helper, providerName);\n break;\n default:\n throw new IllegalStateException(String.format(Locale.US, \"Unknown action '%s'.\", action));\n }\n } else {\n OPFLog.w(\"OPFPush must be initialized\");\n }\n }\n\n private void checkRegistering(@NonNull final Context context,\n @NonNull final OPFPushHelper helper,\n @NonNull final String providerName) {\n OPFLog.logMethod(context, helper, providerName);\n if (helper.isRegistering()) {\n Settings.getInstance(context).saveState(State.UNREGISTERED);\n helper.registerNextAvailableProvider(providerName);\n }\n }\n}",
"public enum Operation {\n REGISTER,\n UNREGISTER\n}",
"public static final String ACTION_RETRY_REGISTER = BuildConfig.APPLICATION_ID + \"intent.RETRY_REGISTER\";",
"public static final String ACTION_RETRY_UNREGISTER = BuildConfig.APPLICATION_ID + \"intent.RETRY_UNREGISTER\";",
"public static final String EXTRA_PROVIDER_NAME = \"org.onepf.opfpush.intent.EXTRA_PROVIDER_NAME\";"
] | import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Pair;
import org.onepf.opfpush.ConnectivityChangeReceiver;
import org.onepf.opfpush.RetryBroadcastReceiver;
import org.onepf.opfpush.model.Operation;
import org.onepf.opfutils.OPFChecks;
import org.onepf.opfutils.OPFLog;
import org.onepf.opfutils.exception.InitException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import static android.content.Context.ALARM_SERVICE;
import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
import static org.onepf.opfpush.OPFConstants.ACTION_RETRY_REGISTER;
import static org.onepf.opfpush.OPFConstants.ACTION_RETRY_UNREGISTER;
import static org.onepf.opfpush.OPFConstants.EXTRA_PROVIDER_NAME;
import static org.onepf.opfpush.model.Operation.REGISTER;
import static org.onepf.opfpush.model.Operation.UNREGISTER; | /*
* Copyright 2012-2015 One Platform Foundation
*
* 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.onepf.opfpush.backoff;
/**
* @author Roman Savin
* @since 06.02.2015
*/
public final class RetryManager implements BackoffManager {
private static volatile RetryManager instance;
@NonNull
private final Context appContext;
@NonNull
private final BackoffManager backoffManager;
@NonNull
private final AlarmManager alarmManager;
private final Set<Pair<String, String>> retryProvidersActions;
@Nullable
private ConnectivityChangeReceiver connectivityChangeReceiver;
private RetryManager(@NonNull final Context context,
@NonNull final BackoffManager backoffManager) {
this.appContext = context.getApplicationContext();
this.backoffManager = backoffManager;
this.alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
this.retryProvidersActions = new HashSet<>();
}
@NonNull
@SuppressWarnings("PMD.NonThreadSafeSingleton")
public static RetryManager init(@NonNull final Context context,
@NonNull final BackoffManager backoffManager) {
OPFChecks.checkThread(true);
checkInit(false);
return instance = new RetryManager(context, backoffManager);
}
@NonNull
public static RetryManager getInstance() {
OPFChecks.checkThread(true);
checkInit(true);
return instance;
}
private static void checkInit(final boolean initExpected) {
final boolean isInit = instance != null;
if (initExpected != isInit) {
throw new InitException(isInit);
}
}
@Override
public boolean hasTries(@NonNull final String providerName,
@NonNull final Operation operation) {
return backoffManager.hasTries(providerName, operation);
}
@Override
public long getTryDelay(@NonNull final String providerName,
@NonNull final Operation operation) {
return backoffManager.getTryDelay(providerName, operation);
}
@Override
public void reset(@NonNull final String providerName, @NonNull final Operation operation) {
backoffManager.reset(providerName, operation);
}
public void postRetryRegister(@NonNull final String providerName) {
OPFLog.logMethod(providerName);
postRetry(providerName, REGISTER, ACTION_RETRY_REGISTER);
}
public void postRetryUnregister(@NonNull final String providerName) {
OPFLog.logMethod(providerName);
postRetry(providerName, UNREGISTER, ACTION_RETRY_UNREGISTER);
}
public void cancelRetryAllOperations(@NonNull final String providerName) {
cancelRetryRegister(providerName);
cancelRetryUnregister(providerName);
}
public void cancelRetryRegister(@NonNull final String providerName) {
OPFLog.logMethod(providerName);
cancelRetry(providerName, REGISTER, ACTION_RETRY_REGISTER);
}
public void cancelRetryUnregister(@NonNull final String providerName) {
OPFLog.logMethod(providerName);
cancelRetry(providerName, UNREGISTER, ACTION_RETRY_UNREGISTER);
}
@NonNull
public Set<Pair<String, String>> getRetryProvidersActions() {
OPFLog.logMethod();
return retryProvidersActions;
}
private void postRetry(@NonNull final String providerName,
@NonNull final Operation operation,
@NonNull final String action) {
final long when = System.currentTimeMillis() + getTryDelay(providerName, operation);
OPFLog.d("Post retry %s provider '%s' at %s",
operation,
providerName,
SimpleDateFormat.getDateTimeInstance(
DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US
).format(new Date(when))
);
retryProvidersActions.add(new Pair<>(providerName, action));
registerConnectivityChangeReceiver();
| final Intent intent = new Intent(appContext, RetryBroadcastReceiver.class); | 1 |
AbrarSyed/SecretRoomsMod-forge | src/main/java/com/wynprice/secretroomsmod/base/interfaces/ISecretBlock.java | [
"@Config(modid = SecretRooms5.MODID, category = \"\")\n@EventBusSubscriber(modid=SecretRooms5.MODID)\npublic final class SecretConfig {\n\n public static final General GENERAL = new General();\n public static final EnergizedPaste ENERGIZED_PASTE = new EnergizedPaste();\n public static final SRMBlockFunctionality BLOCK_FUNCTIONALITY = new SRMBlockFunctionality();\n \n public static final class General {\n @Config.Name(\"update_checker\")\n @Config.Comment(\"Check for mod updates on startup\")\n public boolean updateChecker = true;\n\n @Config.Name(\"survival_mode_helmet\")\n @Config.Comment(\"Allow the helmet to be used in survival mode\")\n public boolean survivalModeHelmet = true;\n }\n\n public static final class EnergizedPaste {\n @Config.Name(\"enable_recipe\")\n @Config.Comment(\"Whether to enable the recipe for energized paste\")\n public boolean enableRecipe = true;\n\n @Config.Name(\"mirror_blacklist\")\n @Config.Comment(\"Blacklist of blocks that should not be mirrored by energized paste\")\n public String[] blacklistMirror = {};\n\n @Config.Name(\"replacement_blacklist\")\n @Config.Comment(\"Blacklist of blocks that should not be replaced by energized paste\")\n public String[] replacementBlacklist = {};\n\n @Config.Name(\"tile_entity_whitelist\")\n @Config.Comment(\"Whitelist of blocks with tile entities that can be copied by energized paste\\nTo apply to a whole mod, do 'modid:*'\")\n public String[] tileEntityWhitelist = {};\n\n @Config.Comment(\"The Sound, Volume and Pitch to play when a block is set to the Energized Paste\")\n @Config.Name(\"sound_set_name\")\n public String soundSetName = \"minecraft:block.sand.place\";\n\n @Config.Name(\"sound_set_volume\")\n public double soundSetVolume = 0.5D;\n\n @Config.Name(\"sound_set_pitch\")\n public double soundSetPitch = 3.0D;\n\n\t\[email protected](\"The Sound, Volume and Pitch to play when Energized Paste is used on another block, changing the appereance of that block.\")\n @Config.Name(\"sound_use_name\")\n public String soundUseName = \"minecraft:block.slime.break\";\n\n @Config.Name(\"sound_use_volume\")\n public double soundUseVolume = 0.2D;\n\n @Config.Name(\"sound_use_pitch\")\n public double soundUsePitch = 3.0D;\n }\n \n public static final class SRMBlockFunctionality {\n \t\n \[email protected](\"Should SRM attempt to copy the light value of the block its mirroring\")\n \[email protected](\"copy_light\")\n \tpublic boolean copyLight = true;\n \t\n \[email protected](\"Should SRM be limited to only full blocks (Like the Classic SecretRoomsMod)\")\n \[email protected](\"only_full_blocks\")\n \tpublic boolean onlyFullBlocks = false;\n \t\n \t\n }\n \n @SubscribeEvent\n public static void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) {\n if(event.getConfigID() != null && event.getConfigID().equals(SecretRooms5.MODID)) {\n ConfigManager.sync(SecretRooms5.MODID, Config.Type.INSTANCE);\n }\n }\n \n}",
"@Deprecated\npublic class ParticleHandler \n{\n\t/**\n\t * Used to keep info of where blocks are being broken, as the tile-entity will no longer exist\n\t */\n\tpublic static final HashMap<BlockPos, IBlockState> BLOCKBRAKERENDERMAP = new HashMap<>();\n}",
"public class FakeBlockAccess implements IBlockAccess\n{\n\t\n\tprivate final IBlockAccess base;\n\t\n\tpublic FakeBlockAccess(IBlockAccess base) {\n\t\tthis.base = base;\n\t}\n\n\t@Override\n\tpublic TileEntity getTileEntity(BlockPos pos) {\n\t\treturn base.getTileEntity(pos);\n\t}\n\n\t@Override\n\tpublic int getCombinedLight(BlockPos pos, int lightValue) {\n\t\treturn base.getCombinedLight(pos, lightValue);\n\t}\n\n\t/**\n\t * If the blockpos holds a SRM block, then the mirrored state will be returned instead\n\t */\n\t@Override\n\tpublic IBlockState getBlockState(BlockPos pos) \n\t{\n\t\treturn base.getTileEntity(pos) instanceof ISecretTileEntity && ((ISecretTileEntity)base.getTileEntity(pos)).getMirrorStateSafely() != null\n\t\t\t\t? ((ISecretTileEntity)base.getTileEntity(pos)).getMirrorStateSafely() : base.getBlockState(pos);\n\t}\n\n\t@Override\n\tpublic boolean isAirBlock(BlockPos pos) {\n\t\treturn base.isAirBlock(pos);\n\t}\n\n\t@Override\n\tpublic Biome getBiome(BlockPos pos) {\n\t\treturn base.getBiome(pos);\n\t}\n\n\t@Override\n\tpublic int getStrongPower(BlockPos pos, EnumFacing direction) {\n\t\treturn base.getStrongPower(pos, direction);\n\t}\n\n\t@Override\n\tpublic WorldType getWorldType() {\n\t\treturn base.getWorldType();\n\t}\n\n\t@Override\n\tpublic boolean isSideSolid(BlockPos pos, EnumFacing side, boolean _default) {\n\t\treturn base.isSideSolid(pos, side, _default);\n\t}\n\n}",
"public class RenderStateUnlistedProperty implements IUnlistedProperty<IBlockState>\n{\n\n\t@Override\n\tpublic String getName() \n\t{\n\t\treturn \"UnlistedMirrorState\";\n\t}\n\n\t@Override\n\tpublic boolean isValid(IBlockState value) \n\t{\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic Class<IBlockState> getType() \n\t{\n\t\treturn IBlockState.class;\n\t}\n\n\t@Override\n\tpublic String valueToString(IBlockState value) \n\t{\n\t\treturn value.toString();\n\t}\n\n}",
"public class FakeBlockModel implements IBakedModel\n{\n\tprotected final IBakedModel model;\n\t\n\t/**\n\t * The actual state of the SRM block in the world\n\t */\n\tprotected IBlockState currentRender;\n\t\n\tprotected IBlockState currentActualState;\n\t\n\tpublic FakeBlockModel(IBlockState overstate) \n\t{\n\t\tthis(Minecraft.getMinecraft().getBlockRendererDispatcher().getModelForState(overstate));\n\t}\n\t\n\tpublic FakeBlockModel(IBakedModel model) \n\t{\n\t\tthis.model = model;\n\t}\n\n\t@Override\n\tpublic List<BakedQuad> getQuads(IBlockState state, EnumFacing side, long rand) \n\t{\n\t\treturn model.getQuads(state, side, rand);\n\t}\n\t\n\t/**\n\t * Used to set the current state of the SRM block thats actually in the world\n\t * @param currentRender The current SRM block thats in the world\n\t * @return this instance\n\t */\n\tpublic FakeBlockModel setCurrentRender(IBlockState currentRender) {\n\t\tthis.currentRender = currentRender;\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Used to set the current actual state of the block being rendered\n\t * @param currentActualState The current actual state of the mirroredState\n\t * @return this instance\n\t */\n\tpublic FakeBlockModel setCurrentActualState(IBlockState currentActualState) {\n\t\tthis.currentActualState = currentActualState;\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic boolean isAmbientOcclusion() {\n\t\treturn model.isAmbientOcclusion();\n\t}\n\n\t@Override\n\tpublic boolean isGui3d() {\n\t\treturn model.isGui3d();\n\t}\n\n\t@Override\n\tpublic boolean isBuiltInRenderer() {\n\t\treturn model.isBuiltInRenderer();\n\t}\n\n\t@Override\n\tpublic TextureAtlasSprite getParticleTexture() {\n\t\treturn model.getParticleTexture();\n\t}\n\n\t@Override\n\tpublic ItemOverrideList getOverrides() {\n\t\treturn model.getOverrides();\n\t}\n\t\n\t/**\n\t * Used to get the model from the IBlockState\n\t * @param state the state to get the model from\n\t * @return the model used to render {@code state}\n\t */\n\tpublic static IBakedModel getModel(IBlockState state)\n\t{\n\t\treturn Minecraft.getMinecraft().getBlockRendererDispatcher().getModelForState(state);\n\t}\n\t\t\n\t/**\n\t * Gets the model from the {@link ResourceLocation}\n\t * @param resourceLocation the location of the model\n\t * @return the model, at the {@link ResourceLocation}\n\t * @throws RuntimeException if the model can't be loaded\n\t */\n\tpublic static IBakedModel getModel(ResourceLocation resourceLocation) throws RuntimeException\n\t{\n\t\tIBakedModel bakedModel;\n\t\tIModel model;\n\t\ttry {\n\t model = ModelLoaderRegistry.getModel(resourceLocation);\n\t\t} catch (Exception e) {\n throw new RuntimeException(e);\n\t\t}\n\t\tbakedModel = model.bake(TRSRTransformation.identity(), DefaultVertexFormats.BLOCK,\n\t\t\t\tlocation -> Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(location.toString()));\n\t return bakedModel;\n\t}\n\t\n}",
"public class SecretBlockModel extends FakeBlockModel\n{\t\n\t\n\tprivate static SecretBlockModel instance;\n\t\n\t/**\n\t * The ThreadLocal used to control what {@link #isAmbientOcclusion()} should return\n\t */\n\tpublic final ThreadLocal<Boolean> AO = ThreadLocal.withInitial(() -> false);\n\t\n\t/**\n\t * The ThreadLocal used to control what SecretRoomsBlock is being rendered at the moment. \n\t */\n\tpublic final ThreadLocal<IBlockState> SRMBLOCK = ThreadLocal.withInitial(() -> null);\n\t\n\t\n\tpublic SecretBlockModel(IBakedModel stone) {\n\t\tsuper(stone);\n\t\tinstance = this;\n\t}\n\t\n\t\n\t@Override\n\tpublic List<BakedQuad> getQuads(IBlockState state, EnumFacing side, long rand) \n\t{\n\t\tif(SRMBLOCK.get() != null) {\n\t\t\tIBlockState secretBlockState = SRMBLOCK.get();\n\t\t\tif(SecretCompatibility.MALISISDOORS && (secretBlockState.getBlock() == SecretBlocks.SECRET_WOODEN_DOOR || secretBlockState.getBlock() == SecretBlocks.SECRET_IRON_DOOR)) {\n\t\t\t\treturn Lists.newArrayList(); //If malisisdoors is enabled, dont render anything\n\t\t\t}\n\t\t\tIBlockState renderActualState = ((IExtendedBlockState)secretBlockState).getValue(ISecretBlock.RENDER_PROPERTY);\n\t\t\tif(renderActualState != null)\n\t\t\t{\n\t\t\t\tFakeBlockModel renderModel = ((ISecretBlock)secretBlockState.getBlock()).phaseModel(new FakeBlockModel(renderActualState));\n\t\t\t\tif(TrueSightHelmet.isHelmet()) {\n \t\t\trenderModel = ((ISecretBlock)secretBlockState.getBlock()).phaseTrueModel(new TrueSightModel(new FakeBlockModel(renderActualState)));\n \t\t}\n\t\t\t\treturn renderModel.setCurrentRender(secretBlockState).setCurrentActualState(renderActualState).getQuads(state, side, rand);\n\t\t\t}\n\t\t}\n\t\treturn this.model.getQuads(state, side, rand);\n\t}\n\n\t@Override\n\tpublic boolean isAmbientOcclusion() {\n\t\treturn AO.get();\n\t}\n\t\n\tpublic static SecretBlockModel instance() {\n\t\treturn instance;\n\t}\n\t\n\tpublic static SecretBlockModel setInstance(IBakedModel stoneModel) {\n\t\tinstance = new SecretBlockModel(stoneModel);\n\t\treturn instance;\n\t}\n}",
"public class TrueSightModel extends BaseTextureSwitchFakeModel\n{\n\n\tpublic TrueSightModel(FakeBlockModel model) {\n\t\tsuper(model);\n\t}\n\t\n\t@Override\n\tprotected RenderInfo getRenderInfo(EnumFacing face, IBlockState teMirrorState, IBlockState teMirrorStateExtended) \n\t{\n\t\treturn new RenderInfo(currentRender, getModel(new ResourceLocation(SecretRooms5.MODID, \"block/\" + currentRender.getBlock().getRegistryName().getResourcePath())));\n\t}\n}",
"public class TileEntityInfomationHolder extends TileEntity implements ITickable, ISecretTileEntity\n{\n\t/**\n\t * The mirrored state\n\t */\n\tprotected IBlockState mirrorState;\n\t\t\n\t\n\t/**\n\t * If the TileEntity is locked then {@link #setMirrorState(IBlockState)} will not work\n\t */\n\tprivate boolean locked;\n\t\n\t@Override\n\tpublic void loadFromNBT(NBTTagCompound compound) {\n\t\treadFromNBT(compound);\n\t}\n\t\n\t@Override\n\tpublic void readFromNBT(NBTTagCompound compound) {\n\t\tsuper.readFromNBT(compound);\n\t\tTileEntityData data = ISecretTileEntity.super.readDataFromNBT(compound, getTileData());\n\t\tmirrorState = data.getMirroredState();\n\t\tlocked = data.isLocked();\t\n\t}\n\t\n\t@Override\n\tpublic void update() {\n\t\tif(mirrorState != null)\n\t\t\tParticleHandler.BLOCKBRAKERENDERMAP.put(pos, mirrorState.getBlock().getStateFromMeta(mirrorState.getBlock().getMetaFromState(mirrorState)));\n\t}\n\t\n\t@Override\n\tpublic AxisAlignedBB getRenderBoundingBox() {\n\t\treturn new AxisAlignedBB(getPos().add(-1, -1, -1), getPos().add(1, 1, 1));\n\t}\n\t\n\t@Override\n\tpublic NBTTagCompound writeToNBT(NBTTagCompound compound) {\n\t\tISecretTileEntity.super.writeDataToNBT(compound, new TileEntityData().setMirroredState(getMirrorStateSafely()).setLocked(locked));\n\t\treturn super.writeToNBT(compound);\n\t}\n\t\n\t@Override\n\tpublic IBlockState getMirrorState() {\n\t\tif(mirrorState == null && ParticleHandler.BLOCKBRAKERENDERMAP.containsKey(pos))\n\t\t\tmirrorState = ParticleHandler.BLOCKBRAKERENDERMAP.get(pos);\n\t\tif(mirrorState == null && RENDER_MAP.containsKey(pos))\n\t\t\tmirrorState = ISecretTileEntity.getMap(world).get(pos);\n\t\treturn mirrorState;\n\t}\n\t\n\t@Override\n\tpublic double getMaxRenderDistanceSquared() \n\t{\n\t\treturn Double.MAX_VALUE;\n\t}\n\t\n\tpublic void setMirrorState(IBlockState mirrorState)\n\t{\n\t\tif(!locked)\n\t\t\tsetMirrorStateForcable(mirrorState);\n\t\tlocked = true;\n\t}\n\t\n\t@Override\n\tpublic void setMirrorStateForcable(IBlockState mirrorState)\n\t{\n\t\tif(mirrorState.getBlock() == null) {\n\t\t\tSecretRooms5.LOGGER.error(\"Null BlockState passed in at: {}, {}, {}. This is most likely doue to world corruption. Setting mirrored state to {}\", getPos().getX(), getPos().getY(), getPos().getZ(), this.mirrorState == null ? \"default (stone)\" : this.mirrorState);\n\t\t\tif(this.mirrorState == null) {\n\t\t\t\tmirrorState = Blocks.STONE.getDefaultState();\n\t\t\t} else {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif(mirrorState.getBlock() instanceof ISecretBlock) {\n\t\t\tmirrorState = Blocks.STONE.getDefaultState();\n\t\t}\n\t\tISecretTileEntity.getMap(world).put(this.pos, mirrorState);\n\t\tthis.mirrorState = mirrorState.getBlock().getStateFromMeta(mirrorState.getBlock().getMetaFromState(mirrorState));\n\t}\n\t\n\t@Override\n\tpublic SPacketUpdateTileEntity getUpdatePacket() {\n\t\tNBTTagCompound nbt = new NBTTagCompound();\n\t\tthis.writeToNBT(nbt);\n\t\tint metadata = getBlockMetadata();\n\t\treturn new SPacketUpdateTileEntity(this.pos, metadata, nbt);\n\t}\n\n\t@Override\n\tpublic void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {\n\t\tthis.readFromNBT(pkt.getNbtCompound());\n\t}\n\n\t@Override\n\tpublic NBTTagCompound getUpdateTag() {\n\t\tNBTTagCompound nbt = new NBTTagCompound();\n\t\tthis.writeToNBT(nbt);\n\t\treturn nbt;\n\t}\n\n\t@Override\n\tpublic void handleUpdateTag(NBTTagCompound tag) {\n\t\tthis.readFromNBT(tag);\n\t}\n\t\n}"
] | import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.wynprice.secretroomsmod.SecretConfig;
import com.wynprice.secretroomsmod.handler.ParticleHandler;
import com.wynprice.secretroomsmod.render.FakeBlockAccess;
import com.wynprice.secretroomsmod.render.RenderStateUnlistedProperty;
import com.wynprice.secretroomsmod.render.fakemodels.FakeBlockModel;
import com.wynprice.secretroomsmod.render.fakemodels.SecretBlockModel;
import com.wynprice.secretroomsmod.render.fakemodels.TrueSightModel;
import com.wynprice.secretroomsmod.tileentity.TileEntityInfomationHolder;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.SoundType;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving.SpawnPlacementType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | package com.wynprice.secretroomsmod.base.interfaces;
/**
* The interface used by all SRM blocks. Most methods here are called directly from the block, as to store all the same code in the same place.
* Extends {@link ITileEntityProvider} as all SRM blocks have TileEntities.
* <br>Not needed but means,
* <br>{@code public class SRMBlock implements ISecretBlock, ITileEntityProvider}
* <br>becomes:
* <br>{@code public class SRMBlock implements ISecretBlock}
* @author Wyn Price
*
*/
public interface ISecretBlock extends ITileEntityProvider
{
/**
* The unlisted property used to store the RenderState
*/
IUnlistedProperty<IBlockState> RENDER_PROPERTY = new RenderStateUnlistedProperty();
/**
* Used to get the renderState from the World and the position
* @param world the world the blocks in
* @param pos the position of the block
* @return the rendered state of the block, or null if there is none
*/
default public IBlockState getState(IBlockAccess world, BlockPos pos)
{
return world.getTileEntity(pos) instanceof ISecretTileEntity ? ISecretTileEntity.getMirrorState(world, pos) : Blocks.STONE.getDefaultState();
}
/**
* Gets the world from the TileEntity at the position
* @param access The world
* @param pos the position of the tilentity
* @return The world, or null if it cant be found
*/
default public World getWorld(IBlockAccess access, BlockPos pos) {
return access.getTileEntity(pos) != null ? access.getTileEntity(pos).getWorld() : null;
}
/**
* Used to force the block render state to the {@link ISecretTileEntity}, if it exists.
* @param world the world the SRM blocks in
* @param tePos the position of the block
* @param state the state of which to force the block to
*/
default public void forceBlockState(World world, BlockPos tePos, IBlockState state)
{
if(world.getTileEntity(tePos) instanceof ISecretTileEntity)
((ISecretTileEntity)world.getTileEntity(tePos)).setMirrorStateForcable(state);
}
@Override
default TileEntity createNewTileEntity(World worldIn, int meta) {
return new TileEntityInfomationHolder();
}
/**
* Used so individual blocks can change the BlockModel for rendering. Used for things like Glass and Doors to make them different
* @param model the original model, will be returned if the Block dosn't need different visuals
* @return the model that will be rendered
*/
@SideOnly(Side.CLIENT)
default FakeBlockModel phaseModel(FakeBlockModel model) {
return model;
}
/**
* Used to get the class from {@link #phaseModel(FakeBlockModel)}
* @return the class that {@link #phaseModel(FakeBlockModel)} uses, with the default being {@link FakeBlockModel}
*/
@SideOnly(Side.CLIENT)
default Class<? extends FakeBlockModel> getModelClass() {
return phaseModel(new FakeBlockModel(Blocks.STONE.getDefaultState())).getClass();
}
@SideOnly(Side.CLIENT)
default boolean isRenderTransparent() {
return getModelClass() != FakeBlockModel.class;
}
/**
* Used so individual blocks can change the BlockModel for rendering, when the Helmet of True Sight is on.
* @param model the original model, will be returned if the Block dosn't need different visuals
* @return the model that will be rendered
*/
@SideOnly(Side.CLIENT)
default TrueSightModel phaseTrueModel(TrueSightModel model) {
return model;
}
/**
* Used as an override to SRM blocks. Used to run {@code Block#canCreatureSpawn(IBlockState, IBlockAccess, BlockPos, SpawnPlacementType)} on Mirrored states
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @param type The Mob Category Type
* @return True to allow a mob of the specified category to spawn, false to prevent it.
*/
default boolean canCreatureSpawn(IBlockState state, IBlockAccess world, BlockPos pos, SpawnPlacementType type) {
return getState(world, pos).getBlock().canCreatureSpawn(getState(world, pos), new FakeBlockAccess(world), pos, type);
}
/**
* Used as an override to SRM blocks. Used to run {@link Block#canHarvestBlock(IBlockAccess, BlockPos, EntityPlayer)} on mirrored states
* @param world The world
* @param player The player damaging the block
* @param pos The block's current position
* @return True to spawn the drops
*/
default boolean canHarvestBlock(IBlockAccess world, BlockPos pos, EntityPlayer player) {
return getState(world, pos).getBlock().canHarvestBlock(new FakeBlockAccess(world), pos, player);
}
/**
* Used as an override to SRM blocks. Used to attempt to get the Mirrored State bounding box
* @param state The input state. not needed what so ever. <b> Exists because {@link Block#getBoundingBox(IBlockState, IBlockAccess, BlockPos)} has the {@link IBlockState} as a field. </b>
* @param source the world
* @param pos the position
* @return the bounding box of the Mirrored State, or {@link Block#FULL_BLOCK_AABB} if does there is no tileEntity at the position.
*/
default AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) {
if(source.getTileEntity(pos) instanceof ISecretTileEntity && ((ISecretTileEntity)source.getTileEntity(pos)).getMirrorStateSafely() != null)
return ((ISecretTileEntity)source.getTileEntity(pos)).getMirrorStateSafely().getBoundingBox(new FakeBlockAccess(source), pos);
return Block.FULL_BLOCK_AABB;
}
/**
* Used as an override to SRM blocks. Used to run {@link Block#canBeConnectedTo(IBlockAccess, BlockPos, EnumFacing)} on the MirrorState
* @param world The current world
* @param pos The position of the block
* @param facing The side the connecting block is on
* @return True to allow another block to connect to this block
*/
default boolean canBeConnectedTo(IBlockAccess world, BlockPos pos, EnumFacing facing) {
return getState(world, pos).getBlock().canBeConnectedTo(new FakeBlockAccess(world), pos, facing);
}
/**
* Used as an override to SRM blocks. Used to run {@link Block#getBlockFaceShape(IBlockAccess, IBlockState, BlockPos, EnumFacing)} on Mirror State.
* @param worldIn The current world
* @param state The {@link IBlockState} of the current position
* @param pos The position of the block
* @param face The side thats being checked
* @return an approximation of the form of the given face.
*/
default BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face) {
return getState(worldIn, pos).getBlockFaceShape(new FakeBlockAccess(worldIn), pos, face);
}
/**
* Used as an override to SRM blocks. Used to run {@link Block#getBlockHardness(IBlockState, World, BlockPos)} on the Mirrored state
* @param worldIn The current world
* @param blockState The {@link IBlockState} of the current position
* @param pos The position of the block
* @return the hardness of the block
*/
default float getBlockHardness(IBlockState blockState, World worldIn, BlockPos pos) {
return ISecretTileEntity.getMirrorState(worldIn, pos).getBlockHardness(worldIn, pos);
}
/**
* Used as an override for SRM blocks. Used to run {@link #canConnectRedstone(IBlockState, IBlockAccess, BlockPos, EnumFacing)} on the mirrored state
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @param side The side that is trying to make the connection, CAN BE NULL
* @return True to make the connection
*/
default public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {
return getState(world, pos).getBlock().canConnectRedstone(getState(world, pos), new FakeBlockAccess(world), pos, side);
}
/**
* Used as an override for SRM blocks. Used to run {@link Block#getSlipperiness(IBlockState, IBlockAccess, BlockPos, Entity)} on the mirrored state
* @param state state of the block
* @param world the world
* @param pos the position in the world
* @param entity the entity in question
* @return the factor by which the entity's motion should be multiplied
*/
default public float getSlipperiness(IBlockState state, IBlockAccess world, BlockPos pos, Entity entity) {
return getState(world, pos).getBlock().getSlipperiness(getState(world, pos), new FakeBlockAccess(world), pos, entity);
}
/**
* Used as an override for SRM block. Used to run {@link Block#canPlaceTorchOnTop(IBlockState, IBlockAccess, BlockPos)} on the mirrored state
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @return True to allow the torch to be placed
*/
default public boolean canPlaceTorchOnTop(IBlockState state, IBlockAccess world, BlockPos pos) {
return getState(world, pos).getBlock().canPlaceTorchOnTop(getState(world, pos), new FakeBlockAccess(world), pos);
}
/**
* Used as an override for SRM blocks. Used to run {@link Block#collisionRayTrace(IBlockState, World, BlockPos, Vec3d, Vec3d)} on the mirrored state
* @param blockState The current state
* @param worldIn the current world
* @param pos the current position
* @param start the start of the raytrace
* @param end the end of the raytrace
* @return the raytrace to use
*/
default public RayTraceResult collisionRayTrace(IBlockState blockState, World worldIn, BlockPos pos, Vec3d start,
Vec3d end) {
return getState(worldIn, pos).collisionRayTrace(worldIn, pos, start, end);
}
/**
* A list of all ISecretTileEntities. Used to get Material and things like that
*/
public static final ArrayList<TileEntity> ALL_SECRET_TILE_ENTITIES = new ArrayList<>();
/**
* Used as an override to SRM blocks. Used to run {@link Block#isSideSolid(IBlockState, IBlockAccess, BlockPos, EnumFacing)} on the mirrored state
* @param base_state The base state, getActualState should be called first
* @param world The current world
* @param pos Block position in world
* @param side The side to check
* @return True if the mirrored state is solid on the specified side.
*/
default boolean isSideSolid(IBlockState base_state, IBlockAccess world, BlockPos pos, EnumFacing side) {
return getState(world, pos).isSideSolid(new FakeBlockAccess(world), pos, side);
}
/**
* Used as an override for SRM blocks. Used to run {@link Block#addCollisionBoxToList(IBlockState, World, BlockPos, AxisAlignedBB, List, Entity, boolean)} on the mirrored state
* @param state The current BlockState
* @param worldIn The current World
* @param pos The current BlockPos
* @param entityBox The colliding Entities bounding box
* @param collidingBoxes The list of bounding boxes
* @param entityIn The Entity Colliding with the block
* @param isActualState Is the {@code state} the actual state
*/
default void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox,
List<AxisAlignedBB> collidingBoxes, Entity entityIn, boolean isActualState)
{
if(worldIn.getTileEntity(pos) instanceof ISecretTileEntity && ISecretTileEntity.getMirrorState(worldIn, pos) != null)
ISecretTileEntity.getMirrorState(worldIn, pos).addCollisionBoxToList(worldIn, pos, entityBox, collidingBoxes, entityIn, isActualState);
else
Blocks.STONE.addCollisionBoxToList(state, worldIn, pos, entityBox, collidingBoxes, entityIn, isActualState);
}
/**
* Used as an override for SRM blocks. Used to run {@link Block#getSoundType(IBlockState, World, BlockPos, Entity)} on the mirrored state
* @param state The state
* @param world The world
* @param pos The position. Note that the world may not necessarily have {@code state} here!
* @param entity The entity that is breaking/stepping on/placing/hitting/falling on this block, or null if no entity is in this context
* @return A SoundType to use
*/
default SoundType getSoundType(IBlockState state, World world, BlockPos pos, Entity entity)
{
return world.getTileEntity(pos) instanceof ISecretTileEntity && ISecretTileEntity.getMirrorState(world, pos) != null ?
ISecretTileEntity.getMirrorState(world, pos).getBlock().getSoundType() : SoundType.STONE;
}
/**
* Used to override the opacity of a block. Used to call {@link Block#getLightOpacity(IBlockState)} on the mirrored state
* @param state the state
* @param world the world
* @param pos the position
* @return the opacity
*/
default int getLightOpacity(IBlockState state, IBlockAccess world, BlockPos pos) { | return SecretConfig.BLOCK_FUNCTIONALITY.copyLight ? ISecretTileEntity.getMirrorState(world, pos).getLightOpacity(new FakeBlockAccess(world), pos) : 255; //Dont use getState as the tileEntity may be null | 0 |
DDoS/JICI | src/main/java/ca/sapon/jici/evaluator/member/ArrayLengthVariable.java | [
"public class LiteralReferenceType extends SingleReferenceType implements LiteralType, TypeArgument {\n public static final LiteralReferenceType THE_STRING = LiteralReferenceType.of(String.class);\n public static final LiteralReferenceType THE_OBJECT = LiteralReferenceType.of(Object.class);\n public static final LiteralReferenceType THE_CLONEABLE = LiteralReferenceType.of(Cloneable.class);\n public static final LiteralReferenceType THE_SERIALIZABLE = LiteralReferenceType.of(Serializable.class);\n private static final Map<Class<?>, PrimitiveType> UNBOXING_CONVERSIONS = new HashMap<>();\n private final Class<?> type;\n private PrimitiveType unbox;\n private boolean unboxCached = false;\n private java.lang.reflect.TypeVariable<?>[] parameters = null;\n\n static {\n UNBOXING_CONVERSIONS.put(Boolean.class, PrimitiveType.THE_BOOLEAN);\n UNBOXING_CONVERSIONS.put(Byte.class, PrimitiveType.THE_BYTE);\n UNBOXING_CONVERSIONS.put(Short.class, PrimitiveType.THE_SHORT);\n UNBOXING_CONVERSIONS.put(Character.class, PrimitiveType.THE_CHAR);\n UNBOXING_CONVERSIONS.put(Integer.class, PrimitiveType.THE_INT);\n UNBOXING_CONVERSIONS.put(Long.class, PrimitiveType.THE_LONG);\n UNBOXING_CONVERSIONS.put(Float.class, PrimitiveType.THE_FLOAT);\n UNBOXING_CONVERSIONS.put(Double.class, PrimitiveType.THE_DOUBLE);\n }\n\n protected LiteralReferenceType(Class<?> type) {\n this.type = type;\n }\n\n @Override\n public String getName() {\n return type.getCanonicalName();\n }\n\n @Override\n public boolean isArray() {\n return type.isArray();\n }\n\n @Override\n public boolean isReifiable() {\n return true;\n }\n\n public boolean isRaw() {\n return getTypeParameters().length > 0;\n }\n\n public boolean isInterface() {\n return type.isInterface();\n }\n\n public boolean isEnum() {\n return type.isEnum();\n }\n\n public boolean isAbstract() {\n return Modifier.isAbstract(type.getModifiers());\n }\n\n public boolean isPublic() {\n return Modifier.isPublic(type.getModifiers());\n }\n\n public boolean isStatic() {\n return Modifier.isStatic(type.getModifiers());\n }\n\n public boolean isInnerClassOf(LiteralReferenceType enclosing) {\n if (enclosing == null) {\n // Enclosing as null means that it should not be an inner class\n return isStatic() || type.getEnclosingClass() == null;\n }\n return !isStatic() && type.getEnclosingClass() == enclosing.getTypeClass();\n }\n\n @Override\n public Class<?> getTypeClass() {\n return type;\n }\n\n protected java.lang.reflect.TypeVariable<?>[] getTypeParameters() {\n if (this.parameters == null) {\n // If this is an array, we need to get to the base component type\n Class<?> base = type;\n while (base.isArray()) {\n base = base.getComponentType();\n }\n this.parameters = base.getTypeParameters();\n }\n return parameters;\n }\n\n public boolean isBox() {\n if (!unboxCached) {\n unbox = UNBOXING_CONVERSIONS.get(type);\n unboxCached = true;\n }\n return unbox != null;\n }\n\n public PrimitiveType unbox() {\n if (isBox()) {\n return unbox;\n }\n throw new UnsupportedOperationException(type.getCanonicalName() + \" is not a box type\");\n }\n\n public LiteralType tryUnbox() {\n if (isBox()) {\n return unbox;\n }\n return this;\n }\n\n @Override\n public LiteralReferenceType getErasure() {\n return this;\n }\n\n @Override\n public Set<LiteralReferenceType> getDirectSuperTypes() {\n final Set<LiteralReferenceType> superTypes = new HashSet<>();\n if (isArray()) {\n // Find the number of dimensions of the array and the base component type\n int dimensions = 0;\n ComponentType componentType = this;\n do {\n if (!(componentType instanceof ReferenceType)) {\n break;\n }\n componentType = ((ReferenceType) componentType).getComponentType();\n dimensions++;\n } while (componentType.isArray());\n if (componentType.equals(LiteralReferenceType.THE_OBJECT)) {\n // For an object component type we use the actual array direct super types\n superTypes.add(LiteralReferenceType.THE_OBJECT.asArray(dimensions - 1));\n superTypes.add(LiteralReferenceType.THE_SERIALIZABLE.asArray(dimensions - 1));\n superTypes.add(LiteralReferenceType.THE_CLONEABLE.asArray(dimensions - 1));\n } else {\n // Add all the component direct super types as arrays of the same dimension\n if (componentType instanceof LiteralReferenceType) {\n for (LiteralReferenceType superType : ((LiteralReferenceType) componentType).getDirectSuperTypes()) {\n superTypes.add(superType.asArray(dimensions));\n }\n }\n }\n } else {\n // Add the direct super class and the directly implemented interfaces\n if (isInterface()) {\n // Interfaces have object as an implicit direct super class\n superTypes.add(LiteralReferenceType.THE_OBJECT);\n } else {\n // This will always return something unless this class is object\n final LiteralReferenceType superClass = getDirectSuperClass();\n if (superClass != null) {\n superTypes.add(superClass);\n }\n }\n Collections.addAll(superTypes, getDirectlyImplementedInterfaces());\n }\n return superTypes;\n }\n\n @Override\n public LinkedHashSet<LiteralReferenceType> getSuperTypes() {\n final LinkedHashSet<LiteralReferenceType> result = new LinkedHashSet<>();\n final Queue<LiteralReferenceType> queue = new ArrayDeque<>();\n queue.add(capture());\n final boolean raw = isRaw();\n while (!queue.isEmpty()) {\n LiteralReferenceType child = queue.remove();\n if (raw) {\n child = child.getErasure();\n }\n if (result.add(child)) {\n queue.addAll(child.getDirectSuperTypes());\n }\n }\n return result;\n }\n\n @Override\n public LiteralReferenceType substituteTypeVariables(Substitutions substitution) {\n return this;\n }\n\n @Override\n public Set<TypeVariable> getTypeVariables() {\n return new HashSet<>();\n }\n\n public LiteralReferenceType getDirectSuperClass() {\n final java.lang.reflect.Type superClass = type.getGenericSuperclass();\n if (superClass != null) {\n final LiteralReferenceType wrappedClass = (LiteralReferenceType) TypeCache.wrapType(superClass);\n return isRaw() ? wrappedClass.getErasure() : wrappedClass;\n }\n return null;\n }\n\n public LiteralReferenceType[] getDirectlyImplementedInterfaces() {\n final java.lang.reflect.Type[] interfaces = type.getGenericInterfaces();\n final boolean raw = isRaw();\n final LiteralReferenceType[] wrapped = new LiteralReferenceType[interfaces.length];\n for (int i = 0; i < interfaces.length; i++) {\n final LiteralReferenceType wrappedInterface = (LiteralReferenceType) TypeCache.wrapType(interfaces[i]);\n wrapped[i] = raw ? wrappedInterface.getErasure() : wrappedInterface;\n }\n return wrapped;\n }\n\n @Override\n public LiteralReferenceType capture() {\n return this;\n }\n\n @Override\n public ComponentType getComponentType() {\n final Class<?> componentType = type.getComponentType();\n if (componentType == null) {\n throw new UnsupportedOperationException(\"Not an array type\");\n }\n return (ComponentType) TypeCache.wrapClass(componentType);\n }\n\n @Override\n public LiteralReferenceType asArray(int dimensions) {\n return of(ReflectionUtil.asArrayType(type, dimensions));\n }\n\n @Override\n public Object newArray(int length) {\n return Array.newInstance(type, length);\n }\n\n @Override\n public Object newArray(int[] lengths) {\n return Array.newInstance(type, lengths);\n }\n\n @Override\n public boolean contains(TypeArgument other) {\n return equals(other);\n }\n\n @Override\n public boolean convertibleTo(Type to) {\n // Literal class types might be convertible to a primitive if they can be unboxed\n if (to.isPrimitive()) {\n return isBox() && unbox().convertibleTo(to);\n }\n // If the target literal type is parametrized, this type must have a parent with\n // the same erasure and compatible type arguments\n if (to instanceof ParametrizedType) {\n final ParametrizedType parametrized = (ParametrizedType) to;\n final LiteralReferenceType erasure = parametrized.getErasure();\n for (LiteralReferenceType superType : getSuperTypes()) {\n if (superType.getErasure().equals(erasure)) {\n return !(superType instanceof ParametrizedType)\n || parametrized.argumentsContain(((ParametrizedType) superType).getArguments());\n }\n }\n return false;\n }\n // Else they can be converted to another literal class if they are a subtype\n if (to instanceof LiteralReferenceType) {\n final LiteralReferenceType target = (LiteralReferenceType) to;\n return target.type.isAssignableFrom(type);\n }\n // They can also be converted to a type variable lower bound\n if (to instanceof TypeVariable) {\n final TypeVariable target = (TypeVariable) to;\n return convertibleTo(target.getLowerBound());\n }\n // They can also be converted to an intersection if they can be converted to each member\n if (to instanceof IntersectionType) {\n final IntersectionType target = (IntersectionType) to;\n for (SingleReferenceType type : target.getTypes()) {\n if (!convertibleTo(type)) {\n return false;\n }\n }\n return true;\n }\n return false;\n }\n\n @Override\n public boolean isUncheckedConversion(Type to) {\n if (!(to instanceof ParametrizedType)) {\n return false;\n }\n final ParametrizedType parametrized = (ParametrizedType) to;\n final LiteralReferenceType erasure = parametrized.getErasure();\n for (LiteralReferenceType superType : getSuperTypes()) {\n if (superType.getErasure().equals(erasure)) {\n return !(superType instanceof ParametrizedType);\n }\n }\n return false;\n }\n\n public LiteralReferenceType getDeclaredInnerClass(String name, TypeArgument[] typeArguments) {\n for (Class<?> _class : type.getDeclaredClasses()) {\n final int modifiers = _class.getModifiers();\n // Ignore non-public classes and synthetic classes generated by the compiler\n // Class must be non-static to be an inner class\n if (!Modifier.isPublic(modifiers) || Modifier.isStatic(modifiers) || _class.isSynthetic()) {\n continue;\n }\n // Check name match\n if (!_class.getSimpleName().equals(name)) {\n continue;\n }\n // If this enclosing class is parametrized, than it is an owner and the inner class is also parametrized\n return typeArguments.length > 0 || this instanceof ParametrizedType ?\n ParametrizedType.of((ParametrizedType) this, _class, Arrays.asList(typeArguments)) :\n LiteralReferenceType.of(_class);\n }\n return null;\n }\n\n public ClassVariable getDeclaredField(String name) {\n // Array length field must be handled specially because the reflection API doesn't declare it\n if (isArray() && \"length\".equals(name)) {\n return ArrayLengthVariable.of(this);\n }\n // Only one field can match the name, not overloads are possible\n for (Field field : type.getDeclaredFields()) {\n // Ignore non-public fields and synthetic fields generated by the compiler\n if (!Modifier.isPublic(field.getModifiers()) || field.isSynthetic()) {\n continue;\n }\n // Check name match\n if (!field.getName().equals(name)) {\n continue;\n }\n return InstanceVariable.of(this, field);\n }\n return null;\n }\n\n public Set<ConstructorCallable> getDeclaredConstructors(TypeArgument[] typeArguments) {\n final Set<ConstructorCallable> constructors = new HashSet<>();\n for (Constructor<?> constructor : type.getDeclaredConstructors()) {\n // Ignore non-public constructors and synthetic constructors generated by the compiler\n if (!Modifier.isPublic(constructor.getModifiers()) || constructor.isSynthetic()) {\n continue;\n }\n // Try to create a callable for the constructor, might fail if the type arguments are out of bounds\n final ConstructorCallable callable = ConstructorCallable.of(this, constructor, typeArguments);\n if (callable != null) {\n constructors.add(callable);\n }\n }\n return constructors;\n }\n\n public Set<? extends Callable> getDeclaredMethods(String name, TypeArgument[] typeArguments) {\n // Array clone method must be handled specially because the reflection API doesn't declare it\n if (isArray() && \"clone\".equals(name)) {\n return Collections.singleton(ArrayCloneCallable.of(this));\n }\n final Set<MethodCallable> methods = new HashSet<>();\n for (Method method : type.getDeclaredMethods()) {\n // Ignore non-public methods and synthetic methods generated by the compiler\n if (!Modifier.isPublic(method.getModifiers()) || method.isSynthetic()) {\n continue;\n }\n // Check name match\n if (!method.getName().equals(name)) {\n continue;\n }\n // Try to create a callable for the method, might fail if the type arguments are out of bounds\n final MethodCallable callable = MethodCallable.of(this, method, typeArguments);\n if (callable != null) {\n methods.add(callable);\n }\n }\n return methods;\n }\n\n @Override\n public LiteralReferenceType getInnerClass(String name, TypeArgument[] typeArguments) {\n final LinkedHashSet<LiteralReferenceType> superTypes = getSuperTypes();\n for (LiteralReferenceType type : superTypes) {\n final LiteralReferenceType innerClass = type.getDeclaredInnerClass(name, typeArguments);\n if (innerClass != null) {\n return innerClass;\n }\n }\n throw new UnsupportedOperationException(\"No inner class for signature \" + name +\n (typeArguments.length > 0 ? '<' + StringUtil.toString(typeArguments, \", \") + '>' : \"\") +\n \" in \" + getName());\n }\n\n @Override\n public ClassVariable getField(String name) {\n final LinkedHashSet<LiteralReferenceType> superTypes = getSuperTypes();\n for (LiteralReferenceType type : superTypes) {\n final ClassVariable field = type.getDeclaredField(name);\n if (field != null) {\n return field;\n }\n }\n throw new UnsupportedOperationException(\"No field named \" + name + \" in \" + getName());\n }\n\n @Override\n public ConstructorCallable getConstructor(TypeArgument[] typeArguments, Type[] arguments) {\n // Get the declared constructors and look for applicable candidates with and without using vararg\n final Set<ConstructorCallable> regularCandidates = new HashSet<>();\n final Set<ConstructorCallable> varargCandidates = new HashSet<>();\n final Set<ConstructorCallable> constructors = getDeclaredConstructors(typeArguments);\n for (ConstructorCallable constructor : constructors) {\n if (constructor.isApplicable(arguments)) {\n regularCandidates.add(constructor);\n }\n if (!constructor.supportsVararg()) {\n continue;\n }\n final ConstructorCallable varargConstructor = constructor.useVararg();\n if (varargConstructor.isApplicable(arguments)) {\n varargCandidates.add(varargConstructor);\n }\n }\n // Resolve overloads\n ConstructorCallable callable = reduceCallableCandidates(regularCandidates, arguments);\n // If the regular callables don't work, try with vararg\n if (callable == null) {\n callable = reduceCallableCandidates(varargCandidates, arguments);\n }\n if (callable != null) {\n return callable.requiresUncheckedConversion(arguments) ? callable.eraseReturnType() : callable;\n }\n throw new UnsupportedOperationException(\"No constructor for signature: \" +\n (typeArguments.length > 0 ? '<' + StringUtil.toString(typeArguments, \", \") + '>' : \"\") +\n type.getSimpleName() + \"(\" + StringUtil.toString(Arrays.asList(arguments), \", \") + \") in \" + getName());\n }\n\n @Override\n public Callable getMethod(String name, TypeArgument[] typeArguments, Type[] arguments) {\n // Get the declared methods and look for applicable candidates with and without using vararg\n final Set<Callable> regularCandidates = new HashSet<>();\n final Set<Callable> varargCandidates = new HashSet<>();\n final LinkedHashSet<LiteralReferenceType> superTypes = getSuperTypes();\n for (LiteralReferenceType type : superTypes) {\n // Check that the type is accessible\n if (!type.isPublic()) {\n // TODO: proper access control, for now exclude non-public types\n continue;\n }\n for (Callable method : type.getDeclaredMethods(name, typeArguments)) {\n if (method.isApplicable(arguments)) {\n regularCandidates.add(method);\n }\n if (!method.supportsVararg()) {\n continue;\n }\n final Callable varargMethod = method.useVararg();\n if (varargMethod.isApplicable(arguments)) {\n varargCandidates.add(varargMethod);\n }\n }\n }\n // Resolve overloads\n Callable callable = reduceCallableCandidates(regularCandidates, arguments);\n // If the regular callables don't work, try with vararg\n if (callable == null) {\n callable = reduceCallableCandidates(varargCandidates, arguments);\n }\n if (callable != null) {\n return callable.requiresUncheckedConversion(arguments) ? callable.eraseReturnType() : callable;\n }\n throw new UnsupportedOperationException(\"No method for signature: \" +\n (typeArguments.length > 0 ? '<' + StringUtil.toString(typeArguments, \", \") + '>' : \"\") +\n name + \"(\" + StringUtil.toString(Arrays.asList(arguments), \", \") + \") in \" + getName());\n }\n\n private static <C extends Callable> C reduceCallableCandidates(Set<C> candidates, Type[] arguments) {\n // Reduce the regular candidates to keep only the most applicable ones\n for (Iterator<C> iterator = candidates.iterator(); iterator.hasNext(); ) {\n final C candidate1 = iterator.next();\n for (C candidate2 : candidates) {\n // Don't compare with itself\n if (candidate1 == candidate2) {\n continue;\n }\n // Remove candidate1 is candidate2 is more applicable\n if (candidate2.isMoreApplicableThan(candidate1, arguments)) {\n iterator.remove();\n break;\n }\n }\n }\n return candidates.size() != 1 ? null : candidates.iterator().next();\n }\n\n public Substitutions getSubstitutions() {\n return Substitutions.NONE;\n }\n\n @Override\n public boolean equals(Object other) {\n return this == other || (other instanceof LiteralReferenceType) && this.type == ((LiteralReferenceType) other).type;\n }\n\n @Override\n public int hashCode() {\n return type.getName().hashCode();\n }\n\n public static LiteralReferenceType of(Class<?> type) {\n checkOwner(null, type);\n return new LiteralReferenceType(type);\n }\n\n protected static ParametrizedType checkOwner(ParametrizedType paramOwner, Class<?> inner) {\n return checkOwner(paramOwner, inner, Collections.<TypeArgument>emptyList());\n }\n\n protected static ParametrizedType checkOwner(ParametrizedType paramOwner, Class<?> inner, List<TypeArgument> arguments) {\n final LiteralReferenceType owner;\n final Class<?> enclosingClass = inner.getEnclosingClass();\n if (paramOwner != null) {\n // If the owner is given, check that it matches what is actually declared in the code\n if (!paramOwner.getTypeClass().equals(enclosingClass)) {\n throw new UnsupportedOperationException(\"Mismatch between given owner and actual one: \" + paramOwner + \" and \" + enclosingClass);\n }\n // Also check that the inner type is selectable (that is, not static)\n if (Modifier.isStatic(inner.getModifiers())) {\n throw new UnsupportedOperationException(\"Inner type \" + inner.getSimpleName() + \" cannot be used in a static context\");\n }\n owner = paramOwner;\n } else if (enclosingClass != null) {\n // If it's not given, check if enclosing class is applicable: the inner class cannot be static\n if (!Modifier.isStatic(inner.getModifiers())) {\n owner = LiteralReferenceType.of(enclosingClass);\n } else {\n // The enclosing class isn't an owner type\n owner = null;\n }\n } else {\n // No enclosing class\n owner = null;\n }\n if (owner != null) {\n // Now that we found an owner, make sure we don't have a partially raw owner/inner combination\n // Owner and inner cannot have one be raw and one not raw\n final boolean ownerParam = owner instanceof ParametrizedType;\n final boolean ownerRaw = owner.isRaw();\n final boolean innerParam = !arguments.isEmpty();\n final boolean innerRaw = inner.getTypeParameters().length > 0 && arguments.isEmpty();\n if ((ownerParam || ownerRaw) && (innerParam || innerRaw) && ownerRaw != innerRaw) {\n throw new UnsupportedOperationException(\"Cannot have a mix of raw and generic outer and inner classes\");\n }\n // We only care of the owner if it is parametrized, as the type arguments are accessible by inner types\n // We want to access those, the rest doesn't matter\n return ownerParam ? (ParametrizedType) owner : null;\n }\n return null;\n }\n}",
"public class PrimitiveType implements LiteralType {\n public static final PrimitiveType THE_BOOLEAN;\n public static final PrimitiveType THE_BYTE;\n public static final PrimitiveType THE_SHORT;\n public static final PrimitiveType THE_CHAR;\n public static final PrimitiveType THE_INT;\n public static final PrimitiveType THE_LONG;\n public static final PrimitiveType THE_FLOAT;\n public static final PrimitiveType THE_DOUBLE;\n private static final Map<Class<?>, PrimitiveType> ALL_TYPES = new HashMap<>();\n private static final Map<Class<?>, Set<Class<?>>> PRIMITIVE_CONVERSIONS = new HashMap<>();\n private static final Map<Class<?>, LiteralReferenceType> BOXING_CONVERSIONS = new HashMap<>();\n private static final Map<Class<?>, RangeChecker> NARROW_CHECKERS = new HashMap<>();\n private static final Set<Class<?>> UNARY_WIDENS_INT = new HashSet<>();\n private static final Map<Class<?>, Widener> BINARY_WIDENERS = new HashMap<>();\n private final Class<?> type;\n private final ValueKind kind;\n\n static {\n THE_BOOLEAN = new PrimitiveType(boolean.class, ValueKind.BOOLEAN);\n THE_BYTE = new PrimitiveType(byte.class, ValueKind.BYTE);\n THE_SHORT = new PrimitiveType(short.class, ValueKind.SHORT);\n THE_CHAR = new PrimitiveType(char.class, ValueKind.CHAR);\n THE_INT = new PrimitiveType(int.class, ValueKind.INT);\n THE_LONG = new PrimitiveType(long.class, ValueKind.LONG);\n THE_FLOAT = new PrimitiveType(float.class, ValueKind.FLOAT);\n THE_DOUBLE = new PrimitiveType(double.class, ValueKind.DOUBLE);\n\n ALL_TYPES.put(boolean.class, THE_BOOLEAN);\n ALL_TYPES.put(byte.class, THE_BYTE);\n ALL_TYPES.put(short.class, THE_SHORT);\n ALL_TYPES.put(char.class, THE_CHAR);\n ALL_TYPES.put(int.class, THE_INT);\n ALL_TYPES.put(long.class, THE_LONG);\n ALL_TYPES.put(float.class, THE_FLOAT);\n ALL_TYPES.put(double.class, THE_DOUBLE);\n\n PRIMITIVE_CONVERSIONS.put(boolean.class, new HashSet<Class<?>>(Collections.singletonList(boolean.class)));\n PRIMITIVE_CONVERSIONS.put(byte.class, new HashSet<Class<?>>(Arrays.asList(byte.class, short.class, int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(short.class, new HashSet<Class<?>>(Arrays.asList(short.class, int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(char.class, new HashSet<Class<?>>(Arrays.asList(char.class, int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(int.class, new HashSet<Class<?>>(Arrays.asList(int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(long.class, new HashSet<Class<?>>(Arrays.asList(long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(float.class, new HashSet<Class<?>>(Arrays.asList(float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(double.class, new HashSet<Class<?>>(Collections.singletonList(double.class)));\n\n BOXING_CONVERSIONS.put(boolean.class, LiteralReferenceType.of(Boolean.class));\n BOXING_CONVERSIONS.put(byte.class, LiteralReferenceType.of(Byte.class));\n BOXING_CONVERSIONS.put(short.class, LiteralReferenceType.of(Short.class));\n BOXING_CONVERSIONS.put(char.class, LiteralReferenceType.of(Character.class));\n BOXING_CONVERSIONS.put(int.class, LiteralReferenceType.of(Integer.class));\n BOXING_CONVERSIONS.put(long.class, LiteralReferenceType.of(Long.class));\n BOXING_CONVERSIONS.put(float.class, LiteralReferenceType.of(Float.class));\n BOXING_CONVERSIONS.put(double.class, LiteralReferenceType.of(Double.class));\n\n NARROW_CHECKERS.put(byte.class, new RangeChecker(-128, 0xFF));\n NARROW_CHECKERS.put(short.class, new RangeChecker(-32768, 0xFFFF));\n NARROW_CHECKERS.put(char.class, new RangeChecker(0, 0xFFFF));\n\n Collections.addAll(UNARY_WIDENS_INT, byte.class, short.class, char.class);\n\n final Widener intWidener = new Widener(int.class, byte.class, short.class, char.class);\n BINARY_WIDENERS.put(byte.class, intWidener);\n BINARY_WIDENERS.put(short.class, intWidener);\n BINARY_WIDENERS.put(char.class, intWidener);\n BINARY_WIDENERS.put(int.class, intWidener);\n BINARY_WIDENERS.put(long.class, new Widener(long.class, byte.class, short.class, char.class, int.class));\n BINARY_WIDENERS.put(float.class, new Widener(float.class, byte.class, short.class, char.class, int.class, long.class));\n BINARY_WIDENERS.put(double.class, new Widener(double.class, byte.class, short.class, char.class, int.class, long.class, float.class));\n }\n\n private PrimitiveType(Class<?> type, ValueKind kind) {\n this.type = type;\n this.kind = kind;\n }\n\n @Override\n public Class<?> getTypeClass() {\n return type;\n }\n\n @Override\n public String getName() {\n return type.getCanonicalName();\n }\n\n @Override\n public ValueKind getKind() {\n return kind;\n }\n\n @Override\n public boolean isVoid() {\n return false;\n }\n\n @Override\n public boolean isNull() {\n return false;\n }\n\n @Override\n public boolean isPrimitive() {\n return true;\n }\n\n @Override\n public boolean isNumeric() {\n return isIntegral() || type == float.class || type == double.class;\n }\n\n @Override\n public boolean isIntegral() {\n return type == byte.class || type == short.class || type == char.class || type == int.class || type == long.class;\n }\n\n @Override\n public boolean isBoolean() {\n return type == boolean.class;\n }\n\n @Override\n public boolean isArray() {\n return false;\n }\n\n @Override\n public boolean isReference() {\n return false;\n }\n\n @Override\n public boolean isReifiable() {\n return true;\n }\n\n @Override\n public LiteralReferenceType asArray(int dimensions) {\n return LiteralReferenceType.of(ReflectionUtil.asArrayType(type, dimensions));\n }\n\n @Override\n public Object newArray(int length) {\n return Array.newInstance(type, length);\n }\n\n @Override\n public Object newArray(int[] lengths) {\n return Array.newInstance(type, lengths);\n }\n\n public SingleReferenceType box() {\n return BOXING_CONVERSIONS.get(type);\n }\n\n public boolean canNarrowFrom(int value) {\n final RangeChecker checker = NARROW_CHECKERS.get(type);\n return checker != null && checker.contains(value);\n }\n\n public PrimitiveType unaryWiden() {\n return of(UNARY_WIDENS_INT.contains(type) ? int.class : type);\n }\n\n public PrimitiveType binaryWiden(PrimitiveType with) {\n return of(BINARY_WIDENERS.get(type).widen(with.getTypeClass()));\n }\n\n @Override\n public boolean convertibleTo(Type to) {\n // Primitive types can be converted to certain primitive types\n // If the target type isn't primitive, box the source and try again\n if (to.isPrimitive()) {\n final PrimitiveType target = (PrimitiveType) to;\n return PRIMITIVE_CONVERSIONS.get(type).contains(target.getTypeClass());\n }\n return box().convertibleTo(to);\n }\n\n @Override\n public PrimitiveType capture() {\n return this;\n }\n\n @Override\n public String toString() {\n return getName();\n }\n\n @Override\n public boolean equals(Object other) {\n return this == other || other instanceof PrimitiveType && this.type == ((PrimitiveType) other).getTypeClass();\n }\n\n @Override\n public int hashCode() {\n return type.getName().hashCode();\n }\n\n public static PrimitiveType of(Class<?> type) {\n return ALL_TYPES.get(type);\n }\n\n private static class RangeChecker {\n private final int minValue;\n private final int invertedMask;\n\n private RangeChecker(int minValue, int mask) {\n this.minValue = minValue;\n invertedMask = ~mask;\n }\n\n private boolean contains(int value) {\n return (value - minValue & invertedMask) == 0;\n }\n }\n\n private static class Widener {\n private final Class<?> wider;\n private final Set<Class<?>> widens = new HashSet<>();\n\n private Widener(Class<?> wider, Class<?>... widens) {\n this.wider = wider;\n Collections.addAll(this.widens, widens);\n }\n\n private Class<?> widen(Class<?> type) {\n return widens.contains(type) ? wider : type;\n }\n }\n}",
"public interface Type {\n String getName();\n\n ValueKind getKind();\n\n boolean isVoid();\n\n boolean isNull();\n\n boolean isPrimitive();\n\n boolean isNumeric();\n\n boolean isIntegral();\n\n boolean isBoolean();\n\n boolean isArray();\n\n boolean isReference();\n\n boolean isReifiable();\n\n boolean convertibleTo(Type to);\n\n Type capture();\n\n @Override\n String toString();\n\n @Override\n boolean equals(Object other);\n\n @Override\n int hashCode();\n}",
"public class IntValue implements Value {\n private static final IntValue[] COMMON_VALUES = new IntValue[256];\n private final int value;\n\n static {\n for (int i = 0; i < 256; i++) {\n COMMON_VALUES[i] = new IntValue(i - 128);\n }\n }\n\n private IntValue(int value) {\n this.value = value;\n }\n\n @Override\n public boolean asBoolean() {\n throw new UnsupportedOperationException(\"Cannot convert an int to a boolean\");\n }\n\n @Override\n public byte asByte() {\n return (byte) value;\n }\n\n @Override\n public short asShort() {\n return (short) value;\n }\n\n @Override\n public char asChar() {\n return (char) value;\n }\n\n @Override\n public int asInt() {\n return value;\n }\n\n @Override\n public long asLong() {\n return value;\n }\n\n @Override\n public float asFloat() {\n return value;\n }\n\n @Override\n public double asDouble() {\n return value;\n }\n\n @Override\n public Integer asObject() {\n return value;\n }\n\n @Override\n public String asString() {\n return Integer.toString(value);\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public <T> T as() {\n return (T) asObject();\n }\n\n @Override\n public ValueKind getKind() {\n return ValueKind.INT;\n }\n\n @Override\n public boolean isPrimitive() {\n return true;\n }\n\n @Override\n public Class<?> getTypeClass() {\n return int.class;\n }\n\n @Override\n public String toString() {\n return asString();\n }\n\n public static IntValue of(int value) {\n final int offsetValue = value + 128;\n if ((offsetValue & ~0xFF) == 0) {\n return COMMON_VALUES[offsetValue];\n }\n return new IntValue(value);\n }\n\n public static IntValue defaultValue() {\n return COMMON_VALUES[128];\n }\n}",
"public interface Value {\n boolean asBoolean();\n\n byte asByte();\n\n short asShort();\n\n char asChar();\n\n int asInt();\n\n long asLong();\n\n float asFloat();\n\n double asDouble();\n\n Object asObject();\n\n String asString();\n\n <T> T as();\n\n ValueKind getKind();\n\n boolean isPrimitive();\n\n Class<?> getTypeClass();\n\n String toString();\n}"
] | import java.lang.reflect.Array;
import ca.sapon.jici.evaluator.type.LiteralReferenceType;
import ca.sapon.jici.evaluator.type.PrimitiveType;
import ca.sapon.jici.evaluator.type.Type;
import ca.sapon.jici.evaluator.value.IntValue;
import ca.sapon.jici.evaluator.value.Value; | /*
* This file is part of JICI, licensed under the MIT License (MIT).
*
* Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/>
*
* 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 ca.sapon.jici.evaluator.member;
/**
*
*/
public class ArrayLengthVariable implements ClassVariable {
private final LiteralReferenceType declaror;
private ArrayLengthVariable(LiteralReferenceType declaror) {
this.declaror = declaror;
}
@Override
public LiteralReferenceType getDeclaringType() {
return declaror;
}
@Override
public String getName() {
return "length";
}
@Override
public Type getType() {
return PrimitiveType.THE_INT;
}
@Override
public Type getTargetType() {
return PrimitiveType.THE_INT;
}
@Override
public boolean isStatic() {
return false;
}
@Override | public Value getValue(Value target) { | 4 |
sih4sing5hong5/han3_ji7_tsoo1_kian3 | src/main/java/idsrend/services/IDSrendServlet.java | [
"public abstract class ExpSequenceLookup\n{\n\t/**\n\t * 查詢其展開式,若無,回傳null。\n\t * \n\t * @param 統一碼控制碼\n\t * 欲查的控制碼\n\t * @return 這字的展開式\n\t */\n\tpublic abstract String 查詢展開式(int 統一碼控制碼);\n\n\t/**\n\t * 查詢字串第一个字的展開式,若無,回傳null。\n\t * \n\t * @param 待查文字\n\t * 欲查的字\n\t * @return 第一个字的展開式\n\t */\n\tpublic String 查詢展開式(String 待查文字)\n\t{\n\t\tint[] 待查控制碼 = String2ControlCode.轉換成控制碼(待查文字);\n\t\treturn 查詢展開式(待查控制碼[0]);\n\t}\n}",
"public class ExpSequenceLookup_byDB extends ExpSequenceLookup\n{\n\t/** 佮資料庫的連線 */\n\tprotected PgsqlConnection 連線;\n\n\t/**\n\t * 初使化物件\n\t * \n\t * @param 連線\n\t * 佮資料庫的連線\n\t */\n\tpublic ExpSequenceLookup_byDB(PgsqlConnection 連線)\n\t{\n\t\tthis.連線 = 連線;\n\t}\n\n\tpublic String 查詢展開式(int 統一碼控制碼)\n\t{\n\t\tString 展開式 = null;\n\t\tStringBuilder 查詢指令 = new StringBuilder(\n\t\t\t\t\"SELECT \\\"展開式\\\" FROM \\\"漢字組建\\\".\\\"檢字表\\\" WHERE \\\"統一碼\\\"='\");\n\t\t查詢指令.append(Integer.toHexString(統一碼控制碼));\n\t\t查詢指令.append('\\'');\n\t\ttry\n\t\t{\n\t\t\tResultSet 查詢結果 = 連線.executeQuery(查詢指令.toString());\n\t\t\tif (查詢結果.next())\n\t\t\t\t展開式 = 查詢結果.getString(\"展開式\");\n\t\t\t查詢結果.close();\n\t\t}\n\t\tcatch (SQLException e)\n\t\t{\n\t\t\t//TODO 優化\n\t\t\t// 直接予下跤回傳控制碼\n\t\t\te.printStackTrace();\n\t\t}\n\t\tcatch (NullPointerException e)\n\t\t{\n\t\t\t// 無連線當作查無\t\t\t\n\t\t}\n\t\treturn 展開式;\n\t}\n}",
"public interface ChineseCharacterTypeSetter\n{\n\t/**\n\t * 產生並初使化獨體活字\n\t * \n\t * @param parent\n\t * 此活字結構的上層活字\n\t * @param chineseCharacterWen\n\t * 要轉化的文(獨體)CharComponent\n\t * @return 獨體活字\n\t */\n\tpublic ChineseCharCompositeMoveabletype setWen(ChineseCharacterMovableTypeTzu parent,\n\t\t\tNonFinalCharComponent chineseCharacterWen);\n\n\t/**\n\t * 產生並初使化合體活字\n\t * \n\t * @param parent\n\t * 此活字結構的上層活字\n\t * @param chineseCharacterTzu\n\t * 要轉化的字(合體)CharComponent\n\t * @return 合體活字\n\t */\n\tpublic ChineseCharCompositeMoveabletype setTzu(ChineseCharacterMovableTypeTzu parent,\n\t\t\tFinalCharComponent chineseCharacterTzu);\n}",
"public class FontRefSettingTool extends ObjMovableTypeBasicSettingTool\n{\n\t/** 用來查展開式的物件 */\n\tCommonFontNoSearch 查通用字型編號;\n\t/** 設定時愛用的字體 */\n\tprotected CommonFont 字體;\n\t/** 活字的渲染屬性 */\n\tprotected FontRenderContext 字體渲染屬性;\n\t/** 佇鬥部件做伙揣現有的字型時,代表空空,遏袂處理的位址號碼 */\n\tprivate final int 空空無物件 = -7;\n\tprotected final double 活字平均闊度;\n\n\t/**\n\t * 準備設定工具。\n\t * \n\t * @param 查通用字型編號\n\t * 用來查展開式的方法\n\t * @param 字體\n\t * 設定時愛用的字體\n\t * @param 字體渲染屬性\n\t * 活字的渲染屬性\n\t */\n\tpublic FontRefSettingTool(CommonFontNoSearch 查通用字型編號, CommonFont 字體, FontRenderContext 字體渲染屬性,\n\t\t\tMkeSeparateMovableType_Bolder 活字加粗)\n\t{\n\t\tsuper(null, null);\n\t\tthis.查通用字型編號 = 查通用字型編號;\n\t\tthis.字體 = 字體;\n\t\tthis.字體渲染屬性 = 字體渲染屬性;\n\n\t\tint 標準字統一碼 = String2ControlCode.轉換成控制碼(ObjMovableTypeBasicSettingTool.tzuModelCharacter)[0];\n\t\tGlyphVector 標準字字型 = 字體.提這个字型(字體渲染屬性, 標準字統一碼);\n\t\tBasicStroke basicStroke = new BasicStroke();\n\t\tRectangle2D 標準字區域;\n\t\t/** 若無「意」,就用全字庫宋體的資料 */\n\t\tif (標準字字型 == null)\n\t\t{\n\t\t\tthis.活字平均闊度 = 2.348851561664724;\n\t\t\t標準字區域 = new Rectangle2D.Double(0.03125, -0.78125, 0.9375, 0.921875);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.活字平均闊度 = 活字加粗.computeBoldCoefficient(new PlaneGeometry(標準字字型\n\t\t\t\t\t.getOutline()));\n\t\t\t標準字區域 = 標準字字型.getOutline().getBounds2D();\n\t\t}\n\t\tthis.pieceForNoBuiltInWen = new Area(\n\t\t\t\tbasicStroke.createStrokedShape(標準字區域));\n\t\tthis.tzuModelTerritory = this.pieceForNoBuiltInWen.getBounds2D();\n\t}\n\n\t@Override\n\tpublic PieceMovableTypeWen setWen(ChineseCharacterMovableTypeTzu parent,\n\t\t\tNonFinalCharComponent chineseCharacterWen)\n\t{\n\t\tSeprateMovabletype 物件活字 = 查物件活字(new CommonFontNo(chineseCharacterWen.Unicode編號()));\n\t\treturn new PieceMovableTypeWen(parent, chineseCharacterWen, 物件活字);\n\t}\n\n\t/**\n\t * 依照字型號碼,設定新的活字物件。\n\t * \n\t * @param 字型號碼\n\t * 愛設定的字型號碼資料\n\t * @return 依照字型號碼的活字物件\n\t */\n\tprivate SeprateMovabletype 查物件活字(CommonFontNo 字型號碼)\n\t{\n\t\tSeprateMovabletype 物件活字 = null;\n\t\tif (字體.有這个字型無(字型號碼))\n\t\t{\n\t\t\tGlyphVector glyphVector = 字體.提這个字型(字體渲染屬性, 字型號碼);\n\t\t\t物件活字 = new SeprateMovabletype(new PlaneGeometry(glyphVector.getOutline()));\n\t\t\t物件活字.設字範圍(tzuModelTerritory);\n\t\t\t物件活字.設目標範圍(物件活字.這馬字範圍());\n\t\t}\n\t\telse\n\t\t{\n\t\t\t物件活字 = findWenForNoBuiltIn(null);\n\t\t}\n\t\t物件活字.徙轉原點();// TODO 伊佮這个資訊攏提掉,交予排版系統去處理,但是會有一字問題。\n\t\treturn 物件活字;\n\t}",
"public class FontCorrespondTable extends MergedFont\n{\n\t/** 統一碼佮逐个字體內部編碼對照表。若無需要,彼格傳<code>null</code> */\n\tprotected ArrayList<HashMap<Integer, Integer>> 對照表集;\n\n\t/** 楷體字體下的所在 */\n\tstatic public final String[] 楷體字體位址表 = new String[] {\n\t\t\t\"/font/WSL_TPS_Font_101/WSL_TPS.ttf\",\n\t\t\t\"/font/CNS11643/TW-Kai-98_1.ttf\",\n\t\t\t\"/font/CNS11643/TW-Kai-98_1.ttf\",\n\t\t\t\"/font/CNS11643/TW-Kai-Ext-B-98_1.ttf\",\n\t\t\t\"/font/CNS11643/TW-Kai-Plus-98_1.ttf\",\n\t\t\t\"/font/cdphanzi-2_7/cdpeudck.tte\", \n\t\t\t\"/font/UnFont/UnGungseo.ttf\", };\n\t/** 宋體字體下的所在 */\n\tstatic public final String[] 宋體字體位址表 = new String[] {\n\t\t\t\"/font/WSL_TPS_Font_101/WSL_TPS.ttf\",\n\t\t\t\"/font/CNS11643/TW-Sung-98_1.ttf\",\n\t\t\t\"/font/CNS11643/TW-Sung-98_1.ttf\",\n\t\t\t\"/font/CNS11643/TW-Sung-Ext-B-98_1.ttf\",\n\t\t\t\"/font/CNS11643/TW-Sung-Plus-98_1.ttf\",\n\t\t\t\"/font/cdphanzi-2_7/cdpeudc.tte\", \n\t\t\t\"/font/NanumFont/NanumMyeongjo.ttf\", };\n\t/** 吳守禮注音字體,統一碼佮伊字體內部編碼的對照表 */\n\tstatic protected final HashMap<Integer, Integer> 吳守禮注音字體對照表;\n\t/** 因為入聲的符號傷細,所以用原本的注音符號,產生入聲編碼佮原本編碼的對照表。 親像「ㆴ」→「ㄅ」、「ㆵ」→「ㄉ」、「ㆶ」→「ㄍ」、「ㆷ」→「ㄏ」。 */\n\tstatic protected final HashMap<Integer, Integer> 入聲注音字體對照表;\n\t/** 楷體字體的物件 */\n\tstatic private final FontCorrespondTable 吳守禮注音摻楷體字體;\n\t/** 宋體字體的物件 */\n\tstatic private final FontCorrespondTable 吳守禮注音摻宋體字體;\n\tstatic\n\t{\n\t\t吳守禮注音字體對照表 = 產生吳守禮注音字體對照表();\n\t\t入聲注音字體對照表 = 產生入聲注音字體對照表();\n\t\t// HashMap<Integer, Integer> 空對照表 = new HashMap<Integer, Integer>();\n\t\tArrayList<HashMap<Integer, Integer>> 注音字體對照表 = new ArrayList<HashMap<Integer, Integer>>();\n\t\t注音字體對照表.add(吳守禮注音字體對照表);\n\t\t注音字體對照表.add(入聲注音字體對照表);\n\t\t注音字體對照表.add(null);\n\t\t注音字體對照表.add(null);\n\t\t注音字體對照表.add(null);\n\t\t注音字體對照表.add(null);\n\t\t注音字體對照表.add(null);\n\t\t注音字體對照表.add(null);\n\n\t\t吳守禮注音摻楷體字體 = new FontCorrespondTable(楷體字體位址表, 注音字體對照表);\n\t\t吳守禮注音摻宋體字體 = new FontCorrespondTable(宋體字體位址表, 注音字體對照表);\n\t}\n\n\t/** 建立一个空的字體,予調參數的時陣會當用。 */\n\tprotected FontCorrespondTable()\n\t{\n\t\tsuper();\n\t\t對照表集 = null;\n\t}\n\n\t/**\n\t * 若有合併字體,加上對照表就會使變對照字體。\n\t *\n\t * @param 字體\n\t * 愛擴充的合併字體\n\t * @param 對照表集\n\t * 統一碼佮逐个字體內部編碼對照表。若無需要,彼格傳<code>null</code>\n\t */\n\tprotected FontCorrespondTable(MergedFont 字體, ArrayList<HashMap<Integer, Integer>> 對照表集)\n\t{\n\t\t字體集 = 字體.字體集;\n\t\tthis.對照表集 = 對照表集;\n\t}",
"public interface CommonFontNoSearch\n{\n\t/**\n\t * 提展開式查字型資料。\n\t * \n\t * @param 展開式\n\t * 愛揣的字型展開式\n\t * @return 佮這个展開式仝款的字型資料\n\t */\n\tpublic CommonFontNo 查通用字型編號(String 展開式);\n}",
"public class CommonFontNoSearchbyDB implements CommonFontNoSearch\n{\n\t/** 佮資料庫的連線 */\n\tprotected PgsqlConnection 連線;\n\n\t/**\n\t * 初使化物件\n\t * \n\t * @param 連線\n\t * 佮資料庫的連線\n\t */\n\tpublic CommonFontNoSearchbyDB(PgsqlConnection 連線)\n\t{\n\t\tthis.連線 = 連線;\n\t}\n\n\t@Override\n\tpublic CommonFontNo 查通用字型編號(String 展開式)\n\t{\n\t\tDBCommandString 查詢命令 = new DBCommandString(\n\t\t\t\t\"SELECT \\\"統一碼\\\", \\\"構型資料庫字體號碼\\\", \\\"構型資料庫字型號碼\\\" \"\n\t\t\t\t\t\t+ \"FROM \\\"漢字組建\\\".\\\"檢字表\\\" \" + \"WHERE \\\"展開式\\\"=\");\n\t\t查詢命令.加變數(展開式);\n\t\t查詢命令.加命令(\" ORDER BY \\\"漢字組建\\\".\\\"檢字表\\\".\\\"構形資料庫編號\\\" ASC\");\n\t\t// System.out.println(查詢命令);\n\t\ttry\n\t\t{\n\t\t\tResultSet 查詢結果 = 連線.executeQuery(查詢命令.toString());\n\t\t\tif (!查詢結果.next())\n\t\t\t\treturn null;\n\t\t\tString 統一碼結果 = 查詢結果.getString(\"統一碼\");\n\t\t\tint 統一碼 = -1;\n\t\t\tif (統一碼結果 != null)\n\t\t\t\t統一碼 = Integer.parseInt(統一碼結果, 16);\n\t\t\tString 字體結果 = 查詢結果.getString(\"構型資料庫字體號碼\");\n\t\t\tint 構型資料庫字體號碼 = -1;\n\t\t\tif (字體結果 != null)\n\t\t\t\t構型資料庫字體號碼 = Integer.parseInt(字體結果);\n\t\t\tString 字型結果 = 查詢結果.getString(\"構型資料庫字型號碼\");\n\t\t\tint 構型資料庫字型號碼 = -1;\n\t\t\tif (字型結果 != null)\n\t\t\t\t構型資料庫字型號碼 = Integer.parseInt(字型結果, 16);\n\t\t\t查詢結果.close();\n\t\t\t// System.out.println(\"查=\" + 展開式 + \" 提著=\" + 統一碼 + \" \" + 構型資料庫字體號碼\n\t\t\t// + \" \" + 字型結果);\n\t\t\treturn new CommonFontNo(統一碼, 構型資料庫字體號碼, 構型資料庫字型號碼);\n\t\t}\n\t\tcatch (SQLException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t}\n\t\tcatch (NullPointerException e)\n\t\t{\n\t\t\t// 無連線當作查無\n\t\t}\n\t\treturn null;\n\t}\n}",
"public class MkeSeparateMovableType_Bolder\n{\n\t/** 物件活字加寬工具 */\n\tprivate final ChineseCharacterTypeBolder chineseCharacterTypeBolder;\n\t/** 合併、調整的精細度 */\n\tprivate final double precision;\n\n\tpublic MkeSeparateMovableType_Bolder(ChineseCharacterTypeBolder chineseCharacterTypeBolder,\n\t\t\tdouble precision)\n\t{\n\t\tthis.chineseCharacterTypeBolder = chineseCharacterTypeBolder;\n\t\tthis.precision = precision;\n\t}\n\n\t/**\n\t * 計算物件活字粗細半徑\n\t * \n\t * @param rectangularArea\n\t * 物件活字\n\t * @return 粗細半徑\n\t */\n\tprotected double computePieceRadius(PlaneGeometry rectangularArea)\n\t{\n\t\tShapeInformation shapeInformation = new ShapeInformation(\n\t\t\t\trectangularArea);\n\t\treturn shapeInformation.getApproximativeRegion()\n\t\t\t\t/ shapeInformation.getApproximativeCircumference();\n\t}\n\n\t/**\n\t * 計算物件活字粗細係數\n\t * \n\t * @param rectangularArea\n\t * 物件活字\n\t * @return 粗細係數\n\t */\n\tpublic double computeBoldCoefficient(PlaneGeometry rectangularArea)\n\t{\n\t\treturn computePieceRadius(rectangularArea);\n\t}\n\n\t/**\n\t * 利用二元搜尋法,找出符合粗細係數的物件活字筆劃加寬度\n\t * \n\t * @param rectangularArea\n\t * 物件活字\n\t * @param originBoldCoefficient\n\t * 粗細係數\n\t * @return 筆劃加寬度\n\t */\n\tprotected PlaneGeometry 依寬度資訊產生外殼(PlaneGeometry 活字物件, MovableTypeWidthInfo 寬度資訊)\n\t{\n\t\tdouble 原來闊度系數 = 寬度資訊.取得活字粗細係數();\n\t\tMovableTypeWidthInfo 這馬闊度資訊 = 取得活字寬度資訊(活字物件);\n\t\tdouble 這馬闊度係數 = 這馬闊度資訊.取得活字粗細係數();\n\t\t// TODO 改成牛頓法可能比較好\n\t\tPlaneGeometry 新殼 = new PlaneGeometry();\n\t\tdouble miniWidth = 0.0, maxiWidth = 原來闊度系數 / 2.0;// TODO 奇怪參數\n\t\twhile (miniWidth + getPrecision() < maxiWidth)\n\t\t{\n\t\t\tdouble middleWidth = 0.5 * (miniWidth + maxiWidth);\n\t\t\t新殼 = getBoldSurface(活字物件, middleWidth);\n\n\t\t\tdouble nowBoldCoefficient = computeBoldCoefficient(新殼);\n\t\t\tif (nowBoldCoefficient / 2.0 + 這馬闊度係數 < 原來闊度系數)\n\t\t\t\tminiWidth = middleWidth;\n\t\t\telse\n\t\t\t\tmaxiWidth = middleWidth;\n\t\t}\n\t\treturn 新殼;// getBoldSurface(活字物件, miniWidth);\n\t}\n\n\t/**\n\t * 給定筆劃加寬度,取得物件活字外框\n\t * \n\t * @param rectangularArea\n\t * 物件活字\n\t * @param strokeWidth\n\t * 筆劃加寬度\n\t * @return 物件活字外框\n\t */\n\tprotected PlaneGeometry getBoldSurface(PlaneGeometry rectangularArea, double strokeWidth)\n\t{\n\t\tif (strokeWidth < getPrecision())\n\t\t\treturn new PlaneGeometry();\n\t\tStroke stroke = chineseCharacterTypeBolder.getStroke(strokeWidth);\n\t\treturn new PlaneGeometry(stroke.createStrokedShape(rectangularArea));\n\t}\n\n\t//\n\t// /**\n\t// * 固定粗細係數的情況下,縮小物件活字\n\t// * <p>\n\t// * 限制:<code>AffineTransform</code>二個縮放比例的絕對值必須小於等於1\n\t// *\n\t// * @param rectangularArea\n\t// * 物件活字\n\t// * @param affineTransform\n\t// * 粗細係數\n\t// */\n\t// void shrinkPieceByFixingStroke(SeprateMovabletype rectangularArea,\n\t// AffineTransform affineTransform)\n\t// {\n\t// // TODO\n\t// // MovableTypeWidthInfo 舊活字寬度資訊 = 取得活字寬度資訊(rectangularArea);\n\t// // // double originBoldCoefficient =\n\t// // // computeBoldCoefficient(rectangularArea);\n\t// // rectangularArea.縮放(affineTransform);\n\t// // 依寬度資訊調整活字(rectangularArea, 舊活字寬度資訊);\n\t// // // double strokeWidth = getStorkeWidthByCoefficient(rectangularArea,\n\t// // // originBoldCoefficient);\n\t// // // RectangularArea boldSurface = getBoldSurface(rectangularArea,\n\t// // // strokeWidth);\n\t// // // rectangularArea.add(boldSurface);\n\t// return;\n\t// }\n\n\t/**\n\t * 取得活字物件的活字寬度資訊\n\t * \n\t * @param 活字物件\n\t * 欲取得資訊的活字物件\n\t * @return MovableTypeWidthInfo\n\t */\n\tMovableTypeWidthInfo 取得活字寬度資訊(PlaneGeometry 活字物件)\n\t{\n\t\treturn new MovableTypeWidthInfo(computeBoldCoefficient(活字物件));\n\t}",
"public class PgsqlConnection\n{\n\t/** 預設資料庫位置 */\n\tstatic public final String url = \"jdbc:postgresql://localhost/漢字組建?useUnicode=true&characterEncoding=utf-8\";\n\t/** 連線物件 */\n\tprivate Connection connection;\n\t/** 連線狀態 */\n\tprivate Statement statement;\n\n\t/**\n\t * 自動連線到資料庫,資料庫設定唯讀,這个帳號就無修改的權限。\n\t * \n\t * <pre>\n\t * ALTER DATABASE \"漢字組建\" set default_transaction_read_only=on;\n\t * </pre>\n\t */\n\tpublic PgsqlConnection()\n\t{\n\t\tthis(url, \"漢字組建\", \"ChineseCharacter\");\n\t}\n\n\t/**\n\t * 連線到資料庫。\n\t * \n\t * @param urls\n\t * 資料庫位置\n\t * @param account\n\t * 資料庫帳號\n\t * @param passwd\n\t * 資料庫密碼\n\t */\n\tpublic PgsqlConnection(String urls, String account, String passwd)\n\t{\n\t\ttry\n\t\t{\n\t\t\tClass.forName(\"org.postgresql.Driver\");\n\t\t}\n\t\tcatch (java.lang.ClassNotFoundException e)\n\t\t{\n\t\t\tSystem.err.print(\"ClassNotFoundException: \");\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t\ttry\n\t\t{\n\t\t\tconnection = DriverManager.getConnection(urls, account, passwd);\n\t\t}\n\t\tcatch (SQLException ex)\n\t\t{\n\t\t\tSystem.err.print(\"SQLException: \");\n\t\t\tSystem.err.println(ex.getMessage());\n\t\t}\n\t\treturn;\n\t}\n\n\t/** 關閉連線。 */\n\tpublic void close()\n\t{\n\t\ttry\n\t\t{\n\t\t\tconnection.close();\n\t\t}\n\t\tcatch (SQLException ex)\n\t\t{\n\t\t\tSystem.err.print(\"SQLException: \");\n\t\t\tSystem.err.println(ex.getMessage());\n\t\t}\n\t\treturn;\n\t}\n\n\t/**\n\t * 查詢資料。\n\t * \n\t * @param query\n\t * 向資料庫提出的要求\n\t * @return 查詢結果\n\t * @throws SQLException\n\t * 資料庫錯誤\n\t */\n\tpublic ResultSet executeQuery(String query) throws SQLException\n\t{\n\t\tstatement = connection.createStatement();\n\t\tResultSet rs = statement.executeQuery(query);\n\t\t// stmt.close();\n\t\treturn rs;\n\t}\n\n\t/**\n\t * 更改資料庫。\n\t * \n\t * @param query\n\t * 向資料庫提出的更改\n\t * @throws SQLException\n\t * 資料庫錯誤\n\t */\n\tpublic void executeUpdate(String query) throws SQLException\n\t{\n\t\tstatement = connection.createStatement();\n\t\tstatement.executeUpdate(query);\n\t\tstatement.close();\n\t\treturn;\n\t}\n}"
] | import java.awt.Font;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import cc.ccomponent_adjuster.ExpSequenceLookup;
import cc.ccomponent_adjuster.ExpSequenceLookup_byDB;
import cc.char_indexingtool.ChineseCharacterTypeSetter;
import cc.char_indexingtool.FontRefSettingTool;
import cc.layouttools.MergePieceAdjuster;
import cc.char_indexingtool.FontCorrespondTable;
import cc.char_indexingtool.CommonFontNoSearch;
import cc.char_indexingtool.CommonFontNoSearchbyDB;
import cc.stroke.FunctinoalBasicBolder;
import cc.stroketool.MkeSeparateMovableType_Bolder;
import cc.tool.database.PgsqlConnection;
import idsrend.CharComponentStructureAdjuster.IDSnormalizer;
import java.lang.System; | package idsrend.services;
/**
* 佮愛規的服務佮提供的字體攏總整合起來。
*
* @author Ihc
*/
public class IDSrendServlet extends HttpServlet
{
/** 序列化編號 */
private static final long serialVersionUID = 1224634082415129183L;
/** 組宋體用的工具 */
protected IDSrendService 宋體組字工具;
/** 組宋體粗體用的工具 */
protected IDSrendService 粗宋組字工具;
/** 組楷體用的工具 */
protected IDSrendService 楷體組字工具;
/** 組楷體粗體用的工具 */
protected IDSrendService 粗楷組字工具;
/** 產生圖形傳予組字介面畫。毋過無X11、圖形介面就袂使用 */
// GraphicsConfiguration 系統圖畫設定;
/** 佮資料庫的連線 */ | protected PgsqlConnection 連線; | 8 |
YTEQ/fixb | fixb-quickfix/src/test/java/org/fixb/quickfix/QuickFixFieldExtractorTest.java | [
"public class FixException extends RuntimeException {\n private static final long serialVersionUID = 1;\n\n /**\n * @param tag the field tag that has not been found\n * @param fixMessage the FIX message that does not contain the tag\n * @return an instance of FixException for a field-not-found case.\n */\n public static FixException fieldNotFound(int tag, String fixMessage) {\n return new FixException(\"Field [\" + tag + \"] was not found in message: \" + fixMessage);\n }\n\n /**\n * @param message the exception message\n * @param cause the exception cause\n */\n public FixException(final String message, final Throwable cause) {\n super(message, cause);\n }\n\n /**\n * @param cause the exception cause\n */\n public FixException(final Throwable cause) {\n super(cause.getMessage(), cause);\n }\n\n /**\n * @param message the exception message\n */\n public FixException(final String message) {\n super(message);\n }\n}",
"public class FixBlockMeta<T> {\n private final Class<T> type;\n private final Optional<Constructor<T>> constructor;\n private final List<FixFieldMeta> fields;\n\n /**\n * The same as FixBlockMeta, but with useConstructor default to false.\n *\n * @param type the domain object type this FixBlockMeta is for\n * @param fields the fields metadata\n */\n public FixBlockMeta(Class<T> type, List<? extends FixFieldMeta> fields) {\n this(type, fields, false);\n }\n\n /**\n * @param type the domain object type this FixBlockMeta is for\n * @param fields the fields metadata\n * @param useConstructor identifies whether to use constructor for instance initialisations\n */\n @SuppressWarnings(\"unchecked\")\n public FixBlockMeta(Class<T> type, List<? extends FixFieldMeta> fields, boolean useConstructor) {\n this.type = type;\n this.constructor = useConstructor ? Optional.of((Constructor<T>) type.getConstructors()[0]) : Optional.<Constructor<T>>absent();\n this.fields = unmodifiableList(fields);\n }\n\n /**\n * @return the related domain object type.\n */\n public Class<T> getType() {\n return type;\n }\n\n /**\n * @return the fields metadata.\n */\n public List<FixFieldMeta> getFields() {\n return fields;\n }\n\n /**\n * @param values constructor parameter values\n * @return a domain object created using given parameter values.\n */\n public T createModel(Map<FixFieldMeta, Object> values) {\n try {\n return (constructor.isPresent()) ?\n createModel(constructor.get(), values, 0) :\n createModel(type, values, 0);\n } catch (Exception e) {\n throw new FixException(\"Unable to create object from FIX parameters: \" + values.values(), e);\n }\n }\n\n private <T> T createModel(Constructor<T> constr, Map<FixFieldMeta, Object> values, int level) throws Exception {\n final List<Object> params = new ArrayList<>(constr.getParameterTypes().length);\n\n final FixFieldMeta[] keys = new FixFieldMeta[values.keySet().size()];\n values.keySet().toArray(keys);\n\n for (int i = 0; i < keys.length; i++) {\n FixFieldMeta meta = keys[i];\n Object value = values.get(meta);\n if (meta instanceof FixDynamicFieldMeta) {\n FixDynamicFieldMeta df = (FixDynamicFieldMeta) meta;\n if (df.getPath().length == 1 + level) {\n params.add(value);\n } else {\n Field rootField = df.getPath()[level];\n Map<FixFieldMeta, Object> componentValues = new LinkedHashMap<>();\n while (df != null && df.getPath()[level] == rootField) {\n componentValues.put(df, value);\n if (i < keys.length) {\n i++;\n if (keys.length > i) {\n df = (FixDynamicFieldMeta) keys[i];\n value = values.get(df);\n } else {\n df = null;\n }\n } else {\n df = null;\n }\n\n }\n params.add(createModel(rootField.getType().getConstructors()[0], componentValues, level + 1));\n\n if (df != null) {\n i--;\n }\n }\n }\n }\n\n return constr.newInstance(params.toArray());\n }\n\n private <T> T createModel(Class<T> clazz, Map<FixFieldMeta, Object> values, int level) throws Exception {\n Map<Field, Object> params = new HashMap<>(clazz.getDeclaredFields().length);\n\n FixFieldMeta[] keys = new FixFieldMeta[values.keySet().size()];\n values.keySet().toArray(keys);\n\n for (int i = 0; i < keys.length; i++) {\n FixFieldMeta meta = keys[i];\n Object value = values.get(meta);\n if (meta instanceof FixDynamicFieldMeta) {\n FixDynamicFieldMeta df = (FixDynamicFieldMeta) meta;\n if (df.getPath().length == 1 + level) {\n params.put(df.getPath()[level], value);\n } else {\n Field rootField = df.getPath()[level];\n Map<FixFieldMeta, Object> componentValues = new LinkedHashMap<>();\n while (df != null && df.getPath()[level] == rootField) {\n componentValues.put(df, value);\n if (i < keys.length) {\n i++;\n if (keys.length > i) {\n df = (FixDynamicFieldMeta) keys[i];\n value = values.get(df);\n } else {\n df = null;\n }\n } else {\n df = null;\n }\n\n }\n params.put(rootField, createModel(rootField.getType().getConstructors()[0], componentValues, level + 1));\n\n if (df != null) {\n i--;\n }\n }\n }\n }\n\n return instantiate(clazz, params);\n }\n\n @SuppressWarnings(\"unchecked\")\n private <T> T instantiate(Class<T> cls, Map<Field, ?> args) throws Exception {\n // Create instance of the given class\n final Constructor<T> constr = (Constructor<T>) cls.getDeclaredConstructors()[0];\n final List<Object> params = new ArrayList<>();\n if (constr.getParameterTypes().length > 0) {\n for (Class<?> pType : constr.getParameterTypes()) {\n params.add(defaultValue(pType));\n }\n }\n final T instance = constr.newInstance(params.toArray());\n // Set separate fields\n for (Map.Entry<Field, ?> pair : args.entrySet()) {\n Field field = pair.getKey();\n field.setAccessible(true);\n field.set(instance, pair.getValue());\n }\n\n return instance;\n }\n\n private static Object defaultValue(Class<?> clazz) {\n if (clazz == int.class) return 0;\n else if (clazz == boolean.class) return false;\n else if (clazz == char.class) return (char) 0;\n else if (clazz == byte.class) return (byte) 0;\n else if (clazz == short.class) return (short) 0;\n else if (clazz == long.class) return (long) 0;\n else if (clazz == float.class) return 0f;\n else if (clazz == double.class) return 0d;\n else return null;\n }\n}",
"public class FixMetaScanner {\n\n /**\n * Scans the given packages for classes annotated with @FixMessage and @FixEnum and adds them to the resulting dictionary.\n *\n * @param packageNames a name of the package containing FIX mapped classes\n */\n public static FixMetaDictionary scanClassesIn(String... packageNames) {\n final MutableFixMetaDictionary dictionary = new MutableFixMetaDictionary();\n for (String packageName : packageNames) {\n try {\n for (Class<?> type : getClasses(packageName)) {\n if (type.isEnum()) {\n dictionary.addMeta(FixEnumMeta.forClass((Class<? extends Enum>) type));\n } else {\n dictionary.addMeta(scanClass(type, dictionary));\n }\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error registering classes in package \" + packageName + \": \" + e.getMessage(), e);\n }\n }\n return dictionary;\n }\n\n /**\n * Scans the given class for FIX mapping annotations.\n *\n * @param model the domain class to scan\n * @param <T> the domain type to scan\n * @return a FixBlockMeta for the given type.\n * @throws FixException if the given class is not properly annotated.\n */\n public static <T> FixBlockMeta<T> scanClass(Class<T> model) {\n return scanClassAndAddToDictionary(model, new MutableFixMetaDictionary());\n }\n\n static <T> FixBlockMeta<T> scanClassAndAddToDictionary(Class<T> model, MutableFixMetaDictionary fixMetaDictionary) {\n if (fixMetaDictionary.containsMeta(model)) {\n return fixMetaDictionary.getComponentMeta(model);\n }\n\n final FixBlockMeta<T> result = scanClass(model, fixMetaDictionary);\n fixMetaDictionary.addMeta(result);\n return result;\n }\n\n static <T> FixBlockMeta<T> scanClass(Class<T> model, MutableFixMetaDictionary dictionary) {\n if (dictionary.containsMeta(model)) {\n return dictionary.getComponentMeta(model);\n }\n\n final FixBlockMeta<T> result;\n\n if (model.getConstructors().length == 0) {\n throw new FixException(\"Class [\" + model.getName() + \"] does not provide a public constructor.\");\n }\n\n @SuppressWarnings(\"unchecked\")\n Optional<Constructor<T>> constructor = Optional.of((Constructor<T>) model.getConstructors()[0]);\n\n final int c = numberOfFixParameters(constructor.get());\n\n if (c == 0) {\n constructor = Optional.absent();\n } else if (c != constructor.get().getParameterTypes().length) {\n throw new FixException(\"Some constructor parameters don't have FIX mapping in class [\" + model.getName() + \"].\");\n }\n\n if (model.isAnnotationPresent(FixMessage.class)) {\n final FixMessage messageAnnotation = model.getAnnotation(FixMessage.class);\n ImmutableList.Builder<FixFieldMeta> allFieldsBuilder = ImmutableList.builder();\n allFieldsBuilder.addAll(processConstantFields(messageAnnotation)); // add constant fields\n allFieldsBuilder.addAll(processFields(model, constructor, dictionary)); // add all other fields\n result = new FixMessageMeta<>(model, messageAnnotation.type(), allFieldsBuilder.build(), constructor.isPresent());\n } else if (model.isAnnotationPresent(FixBlock.class)) {\n final List<FixFieldMeta> fixFields = processFields(model, constructor, dictionary);\n result = new FixBlockMeta<>(model, fixFields, constructor.isPresent());\n } else {\n throw new FixException(\"Neither @FixBlock nor @FixMessage annotation present on class [\" + model.getName() + \"].\");\n }\n\n return result;\n }\n\n /**\n * Scans all classes accessible from the context class loader which belong to the given package and subpackages.\n *\n * @param packageName the base package\n * @return All found classes with FIX bindings.\n */\n private static Set<Class<?>> getClasses(final String packageName) {\n final Reflections reflections = new Reflections(packageName);\n final Set<Class<?>> allClasses = new HashSet<>();\n allClasses.addAll(reflections.getTypesAnnotatedWith(FixMessage.class));\n allClasses.addAll(reflections.getTypesAnnotatedWith(FixEnum.class));\n\n // Process classes in constant order\n final TreeSet<Class<?>> sortedClasses = new TreeSet<>(new Comparator<Class<?>>() {\n @Override\n public int compare(Class<?> o1, Class<?> o2) {\n return o1.getName().compareTo(o2.getName());\n }\n });\n\n sortedClasses.addAll(allClasses);\n\n return sortedClasses;\n }\n\n private static int numberOfFixParameters(Constructor<?> constructor) {\n int fixAnnotationCount = 0;\n for (Annotation[] annotations : constructor.getParameterAnnotations()) {\n if (hasFixParamAnnotation(annotations)) {\n fixAnnotationCount++;\n }\n }\n return fixAnnotationCount;\n }\n\n private static boolean hasFixParamAnnotation(Annotation[] annotations) {\n if (annotations.length == 0) {\n return false;\n }\n final Set<Class<? extends Annotation>> fixAnnotationType = new HashSet<>(asList(FixBlock.class, FixField.class, FixGroup.class));\n for (Annotation annotation : annotations) {\n if (fixAnnotationType.contains(annotation.annotationType())) {\n return true;\n }\n }\n return false;\n }\n\n private static List<FixFieldMeta> processConstantFields(FixMessage messageAnnotation) {\n final List<FixFieldMeta> headerFields = new ArrayList<>();\n headerFields.add(fixFieldMeta(MSG_TYPE_TAG, messageAnnotation.type(), true));\n for (FixMessage.Field f : messageAnnotation.header()) {\n headerFields.add(fixFieldMeta(f.tag(), f.value(), true));\n }\n for (FixMessage.Field f : messageAnnotation.body()) {\n headerFields.add(fixFieldMeta(f.tag(), f.value(), false));\n }\n return headerFields;\n }\n\n private static <T> List<FixFieldMeta> processFields(final Class<T> model,\n final Optional<Constructor<T>> constructor,\n final MutableFixMetaDictionary dictionary) {\n final ImmutableMap<Integer, FixFieldMeta> fixFields = scanFields(model, dictionary);\n\n if (constructor.isPresent()) {\n final FixFieldMeta[] orderedFixFields = new FixFieldMeta[fixFields.size()];\n orderFixFields(constructor.get(), fixFields, orderedFixFields, dictionary, 0);\n return asList(orderedFixFields);\n } else {\n return new ArrayList<>(fixFields.values());\n }\n }\n\n private static int orderFixFields(Constructor<?> constructor,\n ImmutableMap<Integer, FixFieldMeta> fixFields,\n FixFieldMeta[] ordered,\n MutableFixMetaDictionary dictionary,\n int offset) {\n final Annotation[][] annotations = constructor.getParameterAnnotations();\n for (int i = 0; i < annotations.length; i++) {\n if (hasFixAnnotation(annotations[i], FixBlock.class)) {\n final Class<?>[] paramTypes = constructor.getParameterTypes();\n for (FixFieldMeta fixFieldMeta : dictionary.getComponentMeta(paramTypes[i]).getFields()) {\n ordered[offset++] = fixFields.get(fixFieldMeta.getTag());\n }\n } else {\n final Optional<Integer> tag = getFixTagFromAnnotations(annotations[i]);\n if (!tag.isPresent()) {\n throw new FixException(\"Some constructor parameters don't have FIX mapping in class [\"\n + constructor.getDeclaringClass().getName() + \"].\");\n }\n\n final FixFieldMeta fixFieldMeta = fixFields.get(tag.get());\n if (fixFieldMeta == null) {\n throw new FixException(\"No field with tag [\" + tag.get() + \"] found, however constructor parameters exist in class [\"\n + constructor.getDeclaringClass().getName() + \"].\");\n }\n\n ordered[offset++] = fixFieldMeta;\n }\n }\n\n return offset;\n }\n\n private static boolean hasFixAnnotation(Annotation[] annotations, Class<? extends Annotation> annotationType) {\n for (Annotation x : annotations) {\n if (x.annotationType() == annotationType) {\n return true;\n }\n }\n return false;\n }\n\n private static Optional<Integer> getFixTagFromAnnotations(Annotation... annotations) {\n Integer tag = null;\n for (Annotation x : annotations) {\n Class<? extends Annotation> annType = x.annotationType();\n if (annType == FixField.class) {\n tag = ((FixField) x).tag();\n break;\n } else if (annType == FixGroup.class) {\n tag = ((FixGroup) x).tag();\n break;\n }\n }\n\n return Optional.fromNullable(tag);\n }\n\n private static <T> ImmutableMap<Integer, FixFieldMeta> scanFields(final Class<T> model,\n final MutableFixMetaDictionary dictionary,\n final Field... parentPath) {\n Map<Integer, FixFieldMeta> fixFields = Maps.newLinkedHashMap();\n\n for (Field f : model.getDeclaredFields()) {\n final Class<?> type = f.getType();\n final Field[] path = newPath(parentPath, f);\n\n for (Annotation annotation : f.getDeclaredAnnotations()) {\n if (FixField.class == annotation.annotationType()) {\n FixField fixField = (FixField) annotation;\n int tag = fixField.tag();\n if (fixFields.containsKey(tag)) {\n throw new FixException(\"There are more than one fields mapped with FIX tag [\" + tag + \"].\");\n }\n fixFields.put(tag, fixFieldMeta(tag, fixField.header(), fixField.optional(), path));\n\n } else if (FixBlock.class == annotation.annotationType()) {\n for (FixFieldMeta fixFieldMeta : scanClassAndAddToDictionary(type, dictionary).getFields()) {\n Field[] fieldPath = ((FixDynamicFieldMeta) fixFieldMeta).getPath();\n Field[] newFieldPath = Arrays.copyOf(path, path.length + fieldPath.length);\n for (int i = path.length; i < newFieldPath.length; i++) {\n newFieldPath[i] = fieldPath[i - path.length];\n }\n fixFields.put(fixFieldMeta.getTag(), new FixDynamicFieldMeta(\n fixFieldMeta.getTag(),\n fixFieldMeta.isHeader(),\n fixFieldMeta.isOptional(),\n newFieldPath));\n }\n } else if (FixGroup.class == annotation.annotationType()) {\n if (Collection.class.isAssignableFrom(type)) {\n FixGroup fixGroup = (FixGroup) annotation;\n if (!fixFields.containsKey(fixGroup.tag())) {\n Class<?> componentType = getComponentType(fixGroup, f.getGenericType());\n FixFieldMeta fieldMeta = isSimpleType(componentType) ?\n fixGroupMeta(fixGroup.tag(),\n fixGroup.header(),\n fixGroup.optional(),\n fixGroup.componentTag(),\n componentType,\n path) :\n fixGroupMeta(fixGroup.tag(),\n fixGroup.header(),\n fixGroup.optional(),\n dictionary.getOrCreateComponentMeta(componentType),\n path);\n fixFields.put(fixGroup.tag(), fieldMeta);\n }\n } else {\n throw new FixException(\"Only Collection can represent a FIX group: [\"\n + f.getName() + \"] in class [\" + model.getName() + \"].\");\n }\n }\n }\n }\n\n final Class<? super T> superclass = model.getSuperclass();\n if (superclass != null && superclass != Object.class) {\n fixFields.putAll(scanFields(superclass, dictionary));\n }\n\n return ImmutableMap.copyOf(fixFields);\n }\n\n private static Class<?> getComponentType(FixGroup annotation, Type genericType) {\n Class<?> explicitComponent = annotation.component();\n return explicitComponent == Void.class ? getElementType(genericType) : explicitComponent;\n }\n\n private static Class<?> getElementType(Type collectionType) {\n if (collectionType instanceof ParameterizedType) {\n ParameterizedType pType = (ParameterizedType) collectionType;\n Type[] typeArguments = pType.getActualTypeArguments();\n if (typeArguments.length == 1 && typeArguments[0] instanceof Class) {\n return (Class<?>) typeArguments[0];\n }\n }\n return Object.class;\n }\n\n private static Field[] newPath(Field[] parentPath, Field f) {\n Field[] path = Arrays.copyOf(parentPath, parentPath.length + 1);\n path[path.length - 1] = f;\n return path;\n }\n\n private static boolean isSimpleType(Class<?> type) {\n return type.isPrimitive() || SIMPLE_CLASSES.contains(type);\n }\n\n @SuppressWarnings(\"unchecked\")\n private static final List<? extends Class<?>> SIMPLE_CLASSES = asList(\n Boolean.class,\n Character.class,\n Byte.class,\n Short.class,\n Integer.class,\n Long.class,\n Float.class,\n Double.class,\n String.class,\n BigDecimal.class,\n Instant.class,\n LocalDate.class,\n Enum.class);\n}",
"public static QuickFixMessageBuilder fixMessage() {\n return new QuickFixMessageBuilder();\n}",
"@FixBlock\npublic static class Component {\n @FixField(tag = 100)\n public final String value;\n\n public Component(@FixField(tag = 100) final String value) {\n this.value = value;\n }\n\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n final Component component = (Component) o;\n\n if (value != null ? !value.equals(component.value) : component.value != null) {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return value != null ? value.hashCode() : 0;\n }\n}"
] | import static org.fixb.quickfix.test.data.TestModels.Component;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.fixb.FixException;
import org.fixb.meta.FixBlockMeta;
import org.fixb.meta.FixMetaScanner;
import org.joda.time.DateTimeZone;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.junit.Test;
import quickfix.Message;
import java.math.BigDecimal;
import java.util.*;
import static java.util.Arrays.asList;
import static org.fixb.quickfix.QuickFixMessageBuilder.fixMessage; | /*
* Copyright 2013 YTEQ 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 org.fixb.quickfix;
public class QuickFixFieldExtractorTest {
private final QuickFixFieldExtractor extractor = new QuickFixFieldExtractor();
@Test
public void testGetStringFieldValue() {
// Given
Message message = fixMessage().setField(10, "TEST VALUE").build();
// When / Then
assertEquals("TEST VALUE", extractor.getFieldValue(message, String.class, 10, false));
}
@Test
public void testGetIntFieldValue() {
// Given
Message message = fixMessage().setField(10, 123).build();
// When / Then
assertEquals(123, extractor.getFieldValue(message, Integer.class, 10, false).intValue());
assertEquals(123, extractor.getFieldValue(message, int.class, 10, false).intValue());
}
@Test
public void testGetCharFieldValue() {
// Given
Message message = fixMessage().setField(10, 'X').build();
// When / Then
assertEquals('X', extractor.getFieldValue(message, Character.class, 10, false).charValue());
assertEquals('X', extractor.getFieldValue(message, char.class, 10, false).charValue());
}
@Test
public void testGetDoubleFieldValue() {
// Given
Message message = fixMessage().setField(10, 123.456).setField(20, 100.00).build();
// When / Then
assertEquals(123.456, extractor.getFieldValue(message, Double.class, 10, false), 0);
assertEquals(100.00, extractor.getFieldValue(message, double.class, 20, false), 0);
}
@Test
public void testGetBigDecimalFieldValue() {
// Given
Message message = fixMessage().setField(10, new BigDecimal(123.00)).build();
// When / Then
assertEquals(new BigDecimal(123.00), extractor.getFieldValue(message, BigDecimal.class, 10, false));
}
@Test
public void testGetLocalDateFieldValue() {
TimeZone.setDefault(TimeZone.getTimeZone("Australia/Sydney"));
DateTimeZone.setDefault(DateTimeZone.forTimeZone(TimeZone.getDefault()));
// Given
LocalDate date = LocalDate.parse("2012-10-10");
Message message = fixMessage().setField(10, date).build();
// When / Then
assertEquals(date, extractor.getFieldValue(message, LocalDate.class, 10, false));
}
@Test
public void testGetBooleanFieldValue() {
// Given
boolean value = true;
Message message = fixMessage().setField(10, "Y").build();
// When / Then
assertEquals(value, extractor.getFieldValue(message, boolean.class, 10, false));
}
@Test(expected = FixException.class)
public void testGetFieldValueWithIncorrectType() {
// Given
Message message = fixMessage().setField(10, "TEXT").build();
// When / Then
assertEquals("TEXT", extractor.getFieldValue(message, int.class, 10, false));
}
@Test(expected = FixException.class)
public void testGetFieldValueWithIncorrectTag() {
// Given
Message message = fixMessage().setField(10, "TEXT").build();
// When / Then
assertNull(extractor.getFieldValue(message, String.class, 12, true));
assertEquals("TEXT", extractor.getFieldValue(message, String.class, 12, false));
}
@Test(expected = IllegalArgumentException.class)
public void testGetFieldValueWithUnsupportedType() {
// Given
Message message = fixMessage().build();
// When / Then
assertEquals("777", extractor.getFieldValue(message, StringBuilder.class, 10, false));
}
@Test
public void testGetGroupsWithSimpleElements() {
// Given
Message message = fixMessage().setGroups(10, 11, asList("A", "B", "C"), true)
.setGroups(20, 21, asList("D", "E", "F"), false)
.setGroups(30, 31, asList(1, 2, 3, 3), false).build();
// When / Then
assertEquals(asList("A", "B", "C"), extractor.getGroups(message, List.class, 10, String.class, 11, false));
assertEquals(asList("D", "E", "F"), extractor.getGroups(message, List.class, 20, String.class, 21, false));
assertEquals(asSet(1, 2, 3), extractor.getGroups(message, Set.class, 30, Integer.class, 31, false));
assertEquals(asList(), extractor.getGroups(message, Collection.class, 333, Double.class, 444, true));
}
@Test
public void testGetGroupsWithComplexElements() {
// Given | final FixBlockMeta<Component> componentMeta = FixMetaScanner.scanClass(Component.class); | 4 |
xushaomin/apple-deploy | src/main/java/com/appleframework/deploy/plus/ssh/SshDeployPlus.java | [
"public class ProjectWithBLOBs extends Project implements Serializable {\r\n \r\n\tprivate String hosts;\r\n\r\n private String preDeploy;\r\n\r\n private String postDeploy;\r\n\r\n private String afterDeploy;\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n public String getHosts() {\r\n return hosts;\r\n }\r\n\r\n public void setHosts(String hosts) {\r\n this.hosts = hosts == null ? null : hosts.trim();\r\n }\r\n\r\n public String getPreDeploy() {\r\n return preDeploy;\r\n }\r\n\r\n public void setPreDeploy(String preDeploy) {\r\n this.preDeploy = preDeploy == null ? null : preDeploy.trim();\r\n }\r\n\r\n public String getPostDeploy() {\r\n return postDeploy;\r\n }\r\n\r\n public void setPostDeploy(String postDeploy) {\r\n this.postDeploy = postDeploy == null ? null : postDeploy.trim();\r\n }\r\n\r\n public String getAfterDeploy() {\r\n return afterDeploy;\r\n }\r\n\r\n public void setAfterDeploy(String afterDeploy) {\r\n this.afterDeploy = afterDeploy == null ? null : afterDeploy.trim();\r\n }\r\n\r\n}",
"public class Task implements Serializable {\r\n\t\r\n private Integer id;\r\n\r\n private Integer projectId;\r\n\r\n private String projectName;\r\n \r\n private String hosts;\r\n\r\n private String title;\r\n\r\n private Integer action;\r\n\r\n private Integer status;\r\n\r\n private String version;\r\n\r\n private String exVersion;\r\n\r\n private Date createAt;\r\n\r\n private Date updateAt;\r\n\r\n private String createBy;\r\n\r\n private String updateBy;\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n public Integer getId() {\r\n return id;\r\n }\r\n\r\n public void setId(Integer id) {\r\n this.id = id;\r\n }\r\n\r\n public Integer getProjectId() {\r\n return projectId;\r\n }\r\n\r\n public void setProjectId(Integer projectId) {\r\n this.projectId = projectId;\r\n }\r\n\r\n public String getProjectName() {\r\n return projectName;\r\n }\r\n\r\n public void setProjectName(String projectName) {\r\n this.projectName = projectName == null ? null : projectName.trim();\r\n }\r\n\r\n public String getTitle() {\r\n return title;\r\n }\r\n\r\n public void setTitle(String title) {\r\n this.title = title == null ? null : title.trim();\r\n }\r\n\r\n public Integer getAction() {\r\n return action;\r\n }\r\n\r\n public void setAction(Integer action) {\r\n this.action = action;\r\n }\r\n\r\n public Integer getStatus() {\r\n return status;\r\n }\r\n\r\n public void setStatus(Integer status) {\r\n this.status = status;\r\n }\r\n\r\n public String getVersion() {\r\n return version;\r\n }\r\n\r\n public void setVersion(String version) {\r\n this.version = version == null ? null : version.trim();\r\n }\r\n\r\n public String getExVersion() {\r\n return exVersion;\r\n }\r\n\r\n public void setExVersion(String exVersion) {\r\n this.exVersion = exVersion == null ? null : exVersion.trim();\r\n }\r\n\r\n public Date getCreateAt() {\r\n return createAt;\r\n }\r\n\r\n public void setCreateAt(Date createAt) {\r\n this.createAt = createAt;\r\n }\r\n\r\n public Date getUpdateAt() {\r\n return updateAt;\r\n }\r\n\r\n public void setUpdateAt(Date updateAt) {\r\n this.updateAt = updateAt;\r\n }\r\n\r\n public String getCreateBy() {\r\n return createBy;\r\n }\r\n\r\n public void setCreateBy(String createBy) {\r\n this.createBy = createBy == null ? null : createBy.trim();\r\n }\r\n\r\n public String getUpdateBy() {\r\n return updateBy;\r\n }\r\n\r\n public void setUpdateBy(String updateBy) {\r\n this.updateBy = updateBy == null ? null : updateBy.trim();\r\n }\r\n\r\n\tpublic String getHosts() {\r\n\t\treturn hosts;\r\n\t}\r\n\r\n\tpublic void setHosts(String hosts) {\r\n\t\tthis.hosts = hosts;\r\n\t}\r\n \r\n}",
"public enum DeployType {\r\n\r\n\tNEXUS(\"NEXUS部署模式\", (int)1),\r\n\tSHELL(\"SHELL部署模式\", (int)2);\r\n\t\r\n\t// 成员变量\r\n\tprivate String name;\r\n\tprivate Integer index;\r\n\r\n\t// 构造方法\r\n\tprivate DeployType(String name, Integer index) {\r\n\t\tthis.name = name;\r\n\t\tthis.index = index;\r\n\t}\r\n\t\r\n\t// 普通方法\r\n\tpublic static String getName(Integer index) {\r\n\t\tfor (DeployType c : DeployType.values()) {\r\n\t\t\tif (c.getIndex() == index) {\r\n\t\t\t\treturn c.name;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\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\tpublic Integer getIndex() {\r\n\t\treturn index;\r\n\t}\r\n\r\n\tpublic void setIndex(Integer index) {\r\n\t\tthis.index = index;\r\n\t}\t\r\n\r\n}\r",
"public interface DeployPlus {\r\n\r\n\tpublic void doDeploy(Task task, ProjectWithBLOBs project);\r\n}\r",
"public class Constants {\r\n\r\n\tprivate static String BOOT_KEY_SERVICE_SUCCESS = \"com.appleframework.boot.Main->main(121)\";\r\n\tprivate static String BOOT_KEY_SERVICE_SUCCESS2 = \"APPLE-BOOT-SUCCESS\";\r\n\tprivate static String BOOT_KEY_SERVICE_FAILURE = \"com.taobao.diamond.client.impl.DefaultDiamondSubscriber->close(421)\";\r\n\t\r\n\tprivate static String BOOT_KEY_WEB_JETTY_SUCCESS = \"Started SelectChannelConnector@\";\r\n\tprivate static String BOOT_KEY_WEB_JETTY_FAILURE = \"APPLE-BOOT-FAILURE\";\r\n\t\r\n\tpublic static List<String> BOOT_KEY_SUCCESS_LIST = new ArrayList<String>();\r\n\tpublic static List<String> BOOT_KEY_FAILURE_LIST = new ArrayList<String>();\r\n\t\r\n\tpublic static Map<Integer, Boolean> BOOT_STATUS_MAP = new HashMap<Integer, Boolean>();\r\n\t\r\n\tstatic {\r\n\t\tBOOT_KEY_SUCCESS_LIST.add(BOOT_KEY_SERVICE_SUCCESS);\r\n\t\tBOOT_KEY_SUCCESS_LIST.add(BOOT_KEY_SERVICE_SUCCESS2);\r\n\t\tBOOT_KEY_SUCCESS_LIST.add(BOOT_KEY_WEB_JETTY_SUCCESS);\r\n\t\t\r\n\t\tBOOT_KEY_FAILURE_LIST.add(BOOT_KEY_SERVICE_FAILURE);\r\n\t\tBOOT_KEY_FAILURE_LIST.add(BOOT_KEY_WEB_JETTY_FAILURE);\r\n\t}\r\n\r\n}\r",
"public class WebSocketServer extends WebSocketServlet {\r\n\r\n\tprivate static final long serialVersionUID = 4805728426990609124L;\r\n\r\n\tprivate static Map<String, AsyncContext> asyncContexts = new ConcurrentHashMap<String, AsyncContext>();\r\n\tprivate static Queue<PushWebSocket> webSockets = new ConcurrentLinkedQueue<PushWebSocket>();\r\n\tprivate static BlockingQueue<String> messages = new LinkedBlockingQueue<String>();\r\n\tprivate static Thread notifier = new Thread(new Runnable() {\r\n\t\tpublic void run() {\r\n\t\t\twhile (true) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\t// Waits until a message arrives\r\n\t\t\t\t\tString message = messages.take();\r\n\r\n\t\t\t\t\t// Sends the message to all the AsyncContext's response\r\n\t\t\t\t\t/*for (AsyncContext asyncContext : asyncContexts.values()) {\r\n\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\tsendMessage(asyncContext.getResponse().getWriter(), message);\r\n\t\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\t\tasyncContexts.values().remove(asyncContext);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}*/\r\n\r\n\t\t\t\t\t// Sends the message to all the WebSocket's connection\r\n\t\t\t\t\tfor (PushWebSocket webSocket : webSockets) {\r\n\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\twebSocket.connection.sendMessage(message);\r\n\t\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\t\twebSockets.remove(webSocket);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (InterruptedException e) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n\r\n\tpublic static void sendMessage(Integer taskId, String message) {\r\n\t\tfor (PushWebSocket webSocket : webSockets) {\r\n\t\t\ttry {\r\n\t\t\t\tif(webSocket.taskId.equals(taskId)) {\r\n\t\t\t\t\twebSocket.connection.sendMessage(message);\r\n\t\t\t\t}\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\twebSockets.remove(webSocket);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*private static void sendMessage(PrintWriter writer, String message) throws IOException {\r\n\t\t// default message format is message-size ; message-data ;\r\n\t\twriter.print(message.length());\r\n\t\twriter.print(\";\");\r\n\t\twriter.print(message);\r\n\t\twriter.print(\";\");\r\n\t\twriter.flush();\r\n\t}*/\r\n\r\n\t@Override\r\n\tpublic void init(ServletConfig config) throws ServletException {\r\n\t\tsuper.init(config);\r\n\t\tnotifier.start();\r\n\t}\r\n\r\n\t// GET method is used to establish a stream connection\r\n\t@Override\r\n\tprotected void doGet(HttpServletRequest request, HttpServletResponse response)\r\n\t\t\tthrows ServletException, IOException {\r\n\t\tresponse.setContentType(\"text/plain\");\r\n\t\tresponse.setCharacterEncoding(\"utf-8\");\r\n\r\n\t\t// Content-Type header\r\n\t\t/*\r\n\r\n\t\t// Access-Control-Allow-Origin header\r\n\t\tresponse.setHeader(\"Access-Control-Allow-Origin\", \"*\");\r\n\r\n\t\tPrintWriter writer = response.getWriter();\r\n\r\n\t\t// Id\r\n\t\tfinal String id = UUID.randomUUID().toString();\r\n\t\twriter.print(id);\r\n\t\twriter.print(';');\r\n\r\n\t\t// Padding\r\n\t\tfor (int i = 0; i < 1024; i++) {\r\n\t\t\twriter.print(' ');\r\n\t\t}\r\n\t\twriter.print(';');\r\n\t\twriter.flush();\r\n\r\n\t\tfinal AsyncContext ac = request.startAsync();\r\n\t\tac.addListener(new AsyncListener() {\r\n\t\t\tpublic void onComplete(AsyncEvent event) throws IOException {\r\n\t\t\t\tasyncContexts.remove(id);\r\n\t\t\t}\r\n\r\n\t\t\tpublic void onTimeout(AsyncEvent event) throws IOException {\r\n\t\t\t\tasyncContexts.remove(id);\r\n\t\t\t}\r\n\r\n\t\t\tpublic void onError(AsyncEvent event) throws IOException {\r\n\t\t\t\tasyncContexts.remove(id);\r\n\t\t\t}\r\n\r\n\t\t\tpublic void onStartAsync(AsyncEvent event) throws IOException {\r\n\r\n\t\t\t}\r\n\t\t});\r\n\t\tasyncContexts.put(id, ac);*/\r\n\t}\r\n\r\n\t// POST method is used to communicate with the server\r\n\t@Override\r\n\tprotected void doPost(HttpServletRequest request, HttpServletResponse response)\r\n\t\t\tthrows ServletException, IOException {\r\n\t\trequest.setCharacterEncoding(\"utf-8\");\r\n\r\n\t\t/*AsyncContext ac = asyncContexts.get(request.getParameter(\"metadata.id\"));\r\n\t\tif (ac == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// close-request\r\n\t\tif (\"close\".equals(request.getParameter(\"metadata.type\"))) {\r\n\t\t\tac.complete();\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// send-request\r\n\t\tMap<String, String> data = new LinkedHashMap<String, String>();\r\n\t\ttry {\r\n\t\t\tmessages.put(JSONUtils.serializeObject(data));\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new IOException(e);\r\n\t\t}*/\r\n\t}\r\n\r\n\t@Override\r\n\tpublic WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {\r\n\t\treturn new PushWebSocket();\r\n\t}\r\n\r\n\tclass PushWebSocket implements WebSocket.OnTextMessage {\r\n\r\n\t\tConnection connection;\r\n\t\tInteger taskId;\r\n\r\n\t\t@Override\r\n\t\tpublic void onOpen(Connection connection) {\r\n\t\t\tthis.connection = connection;\r\n\t\t\twebSockets.add(this);\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void onClose(int closeCode, String message) {\r\n\t\t\twebSockets.remove(this);\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void onMessage(String queryString) {\r\n\t\t\t// Parses query string\r\n\t\t\tUrlEncoded parameters = new UrlEncoded(queryString);\r\n\r\n\t\t\tInteger taskId = Integer.parseInt(parameters.get(\"taskId\").toString());\r\n\t\t\tthis.taskId = taskId;\r\n\t\t\t\r\n\t\t\t//Map<String, String> data = new LinkedHashMap<String, String>();\r\n\t\t\t//data.put(key, value)\r\n\t\t\tString message = \"任务(id=\" + taskId + \")提交成功,等待部署中...\";\r\n\t\t\ttry {\r\n\t\t\t\tmessages.put(message);\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tthrow new RuntimeException(e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void destroy() {\r\n\t\tmessages.clear();\r\n\t\twebSockets.clear();\r\n\t\tasyncContexts.clear();\r\n\t\tnotifier.interrupt();\r\n\t}\r\n\r\n}\r"
] | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.appleframework.config.core.util.StringUtils;
import com.appleframework.deploy.entity.ProjectWithBLOBs;
import com.appleframework.deploy.entity.Task;
import com.appleframework.deploy.model.DeployType;
import com.appleframework.deploy.plus.DeployPlus;
import com.appleframework.deploy.utils.Constants;
import com.appleframework.deploy.websocket.WebSocketServer;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
| package com.appleframework.deploy.plus.ssh;
public class SshDeployPlus implements DeployPlus {
private static String APPEND = "----------";
public void doDeploy(Task task, ProjectWithBLOBs project) {
Constants.BOOT_STATUS_MAP.put(task.getId(), false);
String hostStr = task.getHosts();
String hosts[] = com.appleframework.deploy.utils.StringUtils.replaceBlank(hostStr).split(",");
for (String host : hosts) {
StringBuffer commandBuffer = new StringBuffer();
commandBuffer.append("mkdir -p " + project.getReleaseTo() + "\n");
// pre deploy
if(!StringUtils.isEmpty(project.getPreDeploy())) {
commandBuffer.append(project.getPreDeploy() + "\n");
}
// post deploy
if (project.getType() == DeployType.NEXUS.getIndex()) {
commandBuffer.append(project.getPostDeploy() + " ");
commandBuffer.append(project.getReleaseTo() + " ");
commandBuffer.append(project.getNexusUrl() + " ");
commandBuffer.append(project.getNexusGroup() + " ");
commandBuffer.append(project.getNexusArtifact() + " ");
commandBuffer.append(project.getVersion() + " ");
}
else {
if(!StringUtils.isEmpty(project.getPostDeploy())) {
commandBuffer.append(project.getPostDeploy() + "\n");
}
}
// after deploy
if(!StringUtils.isEmpty(project.getAfterDeploy())) {
commandBuffer.append(project.getAfterDeploy() + "\n");
}
Session session = null;
ChannelExec openChannel = null;
try {
JSch jsch = new JSch();
jsch.addIdentity("/root/.ssh/id_dsa");
session = jsch.getSession(project.getReleaseUser(), host, 22);
java.util.Properties config = new java.util.Properties();
//设置第一次登陆的时候提示,可选值:(ask | yes | no)
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
//session.setPassword("123456");
session.connect();
openChannel = (ChannelExec) session.openChannel("exec");
openChannel.setCommand(commandBuffer.toString());
int exitStatus = openChannel.getExitStatus();
if(exitStatus != -1) {
| WebSocketServer.sendMessage(task.getId(), host + APPEND + "认证失败:" + exitStatus);
| 5 |
Catalysts/cat-boot | cat-boot-report-pdf/src/main/java/cc/catalysts/boot/report/pdf/impl/PdfReportGenerator.java | [
"public class PdfPageLayout {\n\n private float width;\n private float height;\n private float marginLeft;\n private float marginRight;\n private float marginTop;\n private float marginBottom;\n private float lineDistance;\n private float header;\n private float footer;\n private PositionOfStaticElements footerPosition;\n private PositionOfStaticElements headerPosition;\n\n public static PdfPageLayout getPortraitA4Page() {\n return new PdfPageLayout(595.27563F, 841.8898F, 28.346457F, 10, 100, 20, 1);\n }\n\n public static PdfPageLayout getPortraitA4PageWithSmallTopMargin() {\n return new PdfPageLayout(595.27563F, 841.8898F, 28.346457F, 10, 20, 20, 1);\n }\n\n public static PdfPageLayout getPortraitA4PageWithDoubleMargins() {\n return new PdfPageLayout(595.27563F, 841.8898F, 56.6929F, 56.6929F, 100, 20, 1);\n }\n\n public static PdfPageLayout getLandscapeA4Page() {\n return new PdfPageLayout(841.8898F, 595.27563F, 28.346457F, 10, 100, 20, 1);\n }\n\n public static PdfPageLayout getLandscapeA4PageWithSmallTopMargin() {\n return new PdfPageLayout(841.8898F, 595.27563F, 28.346457F, 10, 20, 20, 1);\n }\n\n public PdfPageLayout(float width, float height, float marginLeft, float marginRight, float marginTop, float marginBottom, float lineDistance) {\n this.width = width;\n this.height = height;\n this.marginLeft = marginLeft;\n this.marginRight = marginRight;\n this.marginTop = marginTop;\n this.marginBottom = marginBottom;\n this.lineDistance = lineDistance;\n }\n\n public float getWidth() {\n return width;\n }\n\n public float getHeight() {\n return height;\n }\n\n public float getMarginLeft() {\n return marginLeft;\n }\n\n public float getMarginRight() {\n return marginRight;\n }\n\n public float getMarginTop() {\n return marginTop;\n }\n\n public float getMarginBottom() {\n return marginBottom;\n }\n\n public float getLineDistance() {\n return lineDistance;\n }\n\n public void setMarginLeft(float marginLeft) {\n this.marginLeft = marginLeft;\n }\n\n public void setMarginRight(float marginRight) {\n this.marginRight = marginRight;\n }\n\n public void setMarginTop(float marginTop) {\n this.marginTop = marginTop;\n }\n\n public void setMarginBottom(float marginBottom) {\n this.marginBottom = marginBottom;\n }\n\n public void setLineDistance(float lineDistance) {\n this.lineDistance = lineDistance;\n }\n\n public PositionOfStaticElements getFooterPosition() {\n return footerPosition;\n }\n\n public void setFooterPosition(PositionOfStaticElements footerPosition) {\n this.footerPosition = footerPosition;\n }\n\n public PositionOfStaticElements getHeaderPosition() {\n return headerPosition;\n }\n\n public void setHeaderPosition(PositionOfStaticElements headerPosition) {\n this.headerPosition = headerPosition;\n }\n\n public void setFooter(float footerSize) {\n this.footer = footerSize;\n }\n\n public void setHeader(float headerSize) {\n this.header = headerSize;\n }\n\n public float getUsableWidth() {\n return width - marginLeft - marginRight;\n }\n\n public float getUsableHeight(int pageNo) {\n return getStartY(pageNo) - getLastY(pageNo);\n }\n\n public PDRectangle getPageSize() {\n return new PDRectangle(width, height);\n }\n\n public float getStartY() {\n return height - marginTop - header;\n }\n\n public float getStartY(int pageNo) {\n return pageNo == 0 && headerPosition == PositionOfStaticElements.ON_ALL_PAGES_BUT_FIRST ? height - marginTop : getStartY();\n }\n\n public float getStartX() {\n return marginLeft;\n }\n\n public float getLastY() {\n return marginBottom + footer;\n }\n\n public float getLastY(int pageNo) {\n return pageNo == 0 && footerPosition == PositionOfStaticElements.ON_ALL_PAGES_BUT_FIRST ? marginBottom : getLastY();\n }\n\n public float getLastX() {\n return width - marginRight;\n }\n}",
"public abstract class PdfStyleSheet {\n\n /**\n * the vertical line distance\n */\n private float lineDistance = 1;\n\n /**\n * the padding after sections (see {@link cc.catalysts.boot.report.pdf.PdfReportBuilder#beginNewSection(String, boolean)}\n */\n private int sectionPadding = 10;\n\n /**\n * the padding after headings\n */\n private int headingPaddingAfter = 4;\n\n /**\n * the text style for heading1 (h1)\n */\n private final PDColor BLACK = new PDColor(new float[]{0.0f, 0.0f, 0.0f}, PDDeviceRGB.INSTANCE);\n\n private PdfTextStyle heading1Text = new PdfTextStyle(20, PdfFont.HELVETICA, BLACK, \"bold\");\n\n /**\n * the text style for the body text\n */\n private PdfTextStyle bodyText = new PdfTextStyle(12, PdfFont.HELVETICA, BLACK, \"regular\");\n\n private PdfTextStyle tableTitleText = new PdfTextStyle(12, PdfFont.HELVETICA, BLACK, \"bold\");\n private PdfTextStyle tableBodyText = new PdfTextStyle(12, PdfFont.HELVETICA, BLACK, \"regular\");\n\n private PdfTextStyle footerText = new PdfTextStyle(7, PdfFont.HELVETICA, BLACK, \"regular\");\n\n public int getSectionPadding() {\n return sectionPadding;\n }\n\n public void setSectionPadding(int sectionPadding) {\n this.sectionPadding = sectionPadding;\n }\n\n public int getHeadingPaddingAfter() {\n return headingPaddingAfter;\n }\n\n public void setHeadingPaddingAfter(int headingPaddingAfter) {\n this.headingPaddingAfter = headingPaddingAfter;\n }\n\n public PdfTextStyle getHeading1Text() {\n return heading1Text;\n }\n\n public void setHeading1Text(PdfTextStyle heading1Text) {\n this.heading1Text = heading1Text;\n }\n\n public PdfTextStyle getBodyText() {\n return bodyText;\n }\n\n public void setBodyText(PdfTextStyle bodyText) {\n this.bodyText = bodyText;\n }\n\n public PdfTextStyle getTableTitleText() {\n return tableTitleText;\n }\n\n public void setTableTitleText(PdfTextStyle tableTitleText) {\n this.tableTitleText = tableTitleText;\n }\n\n public PdfTextStyle getTableBodyText() {\n return tableBodyText;\n }\n\n public void setTableBodyText(PdfTextStyle tableBodyText) {\n this.tableBodyText = tableBodyText;\n }\n\n public PdfTextStyle getFooterText() {\n return footerText;\n }\n\n public void setFooterText(PdfTextStyle footerText) {\n this.footerText = footerText;\n }\n\n public float getLineDistance() {\n return lineDistance;\n }\n\n public void setLineDistance(float lineDistance) {\n this.lineDistance = lineDistance;\n }\n\n}",
"public class ReportCompositeElement implements ReportElement {\n\n private final List<ReportElement> elements = new ArrayList<>();\n private Collection<ReportImage.ImagePrintIntent> intents = new LinkedList<ReportImage.ImagePrintIntent>();\n private boolean isSplitable = false;\n\n public ReportCompositeElement addElement(ReportElement element) {\n elements.add(element);\n return this;\n }\n\n public void setSplitable(boolean splitable) {\n isSplitable = splitable;\n }\n\n @Override\n public float print(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float startY, float allowedWidth) throws IOException {\n float lastY = startY;\n for (ReportElement element : elements) {\n lastY = element.print(document, stream, pageNumber, startX, lastY, allowedWidth);\n intents.addAll(element.getImageIntents());\n }\n return lastY;\n }\n\n @Override\n public float getHeight(float allowedWidth) {\n float height = 0;\n for (ReportElement element : elements) {\n if (element instanceof ReportPadding) {\n height += ((ReportPadding) element).getPadding();\n } else {\n height += element.getHeight(allowedWidth);\n }\n }\n return height;\n }\n\n @Override\n public boolean isSplitable() {\n return isSplitable;\n }\n\n @Override\n public float getFirstSegmentHeight(float allowedWidth) {\n float height = 0;\n for (ReportElement element: elements) {\n if (!element.isSplitable()) {\n if (element instanceof ReportPadding) {\n height += ((ReportPadding) element).getPadding();\n } else {\n height += element.getHeight(allowedWidth);\n }\n } else {\n height += element.getFirstSegmentHeight(allowedWidth);\n break;\n }\n }\n\n return height;\n }\n\n @Override\n public ReportElement[] split(float allowedWidth) {\n throw new UnsupportedOperationException(\"Horizontal split not allowed!\");\n }\n\n @Override\n public ReportElement[] split(float allowedWidth, float allowedHeight) {\n ReportCompositeElement first = new ReportCompositeElement();\n ReportCompositeElement next = new ReportCompositeElement();\n\n boolean foundFirstSplittableElement = false;\n for (ReportElement element: elements) {\n if (foundFirstSplittableElement) {\n next.addElement(element);\n } else {\n if (element.isSplitable()) {\n foundFirstSplittableElement = true;\n ReportElement[] splitted = element.split(allowedWidth, allowedHeight - first.getHeight(allowedWidth));\n first.addElement(splitted[0]);\n next.addElement(splitted[1]);\n } else {\n first.addElement(element);\n }\n }\n }\n\n return new ReportElement[]{first, next};\n }\n\n @Override\n public float getHeightOfElementToSplit(float allowedWidth, float allowedHeight) {\n float heightOfElementToSplit = getHeight(allowedWidth);\n\n float remainingAllowedHeight = allowedHeight;\n for (ReportElement element: elements) {\n if (!element.isSplitable()) {\n remainingAllowedHeight -= element.getHeight(allowedWidth);\n } else {\n heightOfElementToSplit = element.getHeightOfElementToSplit(allowedWidth, remainingAllowedHeight);\n break;\n }\n }\n\n return heightOfElementToSplit;\n }\n\n @Override\n public Collection<ReportImage.ImagePrintIntent> getImageIntents() {\n return intents;\n }\n}",
"public interface ReportElement {\n\n /**\n * @param document PdfBox document\n * @param stream PdfBox stream\n * @param pageNumber current page number (0 based)\n * @param startX starting x\n * @param startY starting y\n * @param allowedWidth maximal width of segment\n * @return the Y position of the next line\n * @throws java.io.IOException in case something happens during printing\n */\n float print(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float startY, float allowedWidth) throws IOException;\n\n /**\n * Height of this segment\n *\n * @param allowedWidth allowed with of the segment\n * @return height of the segment\n */\n float getHeight(float allowedWidth);\n\n /**\n * In case the element may be split over pages, this method should return true\n *\n * @return may the element be split over multiple pages\n */\n boolean isSplitable();\n\n /**\n * in case isSplitable is true, this method will be called.\n *\n * @param allowedWidth the maximum allowed width for this element\n * @return the height of the first nonSplitable segment\n */\n float getFirstSegmentHeight(float allowedWidth);\n\n /**\n * If the element my be split this method should return two elements. The first unsplitable elements, and the rest.\n * The second arrays element may be null\n *\n * @param allowedWidth allowed with of the segment\n * @return Arrays with <b>two</b> report elements\n */\n ReportElement[] split(float allowedWidth);\n\n /**\n * Will split the report element, so the height of the first segment will the maximum value less or equal to the allowed height value.\n *\n * @param allowedWidth width of report element\n * @param allowedHeight max height of first segment.\n * @return two report elements\n */\n ReportElement[] split(float allowedWidth, float allowedHeight);\n\n /**\n * For splittable elements returns the current height of the element that needs to be split.\n *\n * @param allowedWidth width of report element\n * @param allowedHeight max height of first segment.\n */\n float getHeightOfElementToSplit(float allowedWidth, float allowedHeight);\n\n /**\n * Returns all the images that should have been printed by this element\n *\n * @return collection, can't be null, migth be empty\n */\n Collection<ReportImage.ImagePrintIntent> getImageIntents();\n\n}",
"public class ReportElementStatic implements ReportElement {\n\n private ReportElement base;\n private float x;\n private float y;\n private float width;\n private int pageNo;\n private PositionOfStaticElements position;\n\n /**\n * @param base ReportElement to be printed\n * @param pageNo 0-based number of page, where to print element\n * @param x starting X coordinate of print location\n * @param y starting Y coordinate of print location\n * @param width the width of the static element\n */\n public ReportElementStatic(ReportElement base, int pageNo, float x, float y, float width, PositionOfStaticElements position) {\n this.base = base;\n this.x = x;\n this.y = y;\n this.pageNo = pageNo;\n this.width = width;\n this.position = position;\n }\n\n public ReportElement getBase() {\n return base;\n }\n\n /**\n * @param document PdfBox document\n * @param stream IGNORED\n * @param pageNumber IGNORED (taken from constructor)\n * @param startX IGNORED (taken from constructor)\n * @param startY IGNORED (taken from constructor)\n * @param allowedWidth IGNORED (taken from constructor)\n * @return 0\n * @throws java.io.IOException in case something happens in the underlying pdf implementation\n */\n @Override\n public float print(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float startY, float allowedWidth) throws IOException {\n PDPage currPage = document.getDocumentCatalog().getPages().get(pageNo);\n PDPageContentStream pageStream = new PDPageContentStream(document, currPage, PDPageContentStream.AppendMode.APPEND, false);\n base.print(document, pageStream, pageNo, x, y, width);\n pageStream.close();\n return 0F;\n }\n\n @Override\n public float getHeight(float allowedWidth) {\n throw new IllegalStateException(\"Height of static elements is irrelevant\");\n }\n\n @Override\n public boolean isSplitable() {\n return false;\n }\n\n @Override\n public float getFirstSegmentHeight(float allowedWidth) {\n throw new IllegalStateException(\"static elements are not splittable\");\n }\n\n @Override\n public ReportElement[] split(float allowedWidth) {\n throw new IllegalStateException(\"static elements are not splittable\");\n }\n\n @Override\n public ReportElement[] split(float allowedWidth, float allowedHeight) {\n throw new IllegalStateException(\"static elements are not splittable\");\n }\n\n @Override\n public float getHeightOfElementToSplit(float allowedWidth, float allowedHeight) {\n throw new IllegalStateException(\"static elements are not splittable\");\n }\n\n @Override\n public Collection<ReportImage.ImagePrintIntent> getImageIntents() {\n return base.getImageIntents();\n }\n\n public float getX() {\n return x;\n }\n\n public float getY() {\n return y;\n }\n\n public float getWidth() {\n return width;\n }\n\n public int getPageNo() {\n return pageNo;\n }\n\n public PositionOfStaticElements getPosition() {\n return position;\n }\n}",
"public class ReportImage extends AbstractReportElement implements ReportElement {\n\n private BufferedImage img;\n private ImagePrintIntent intent;\n private float width;\n private float height;\n private ReportAlignType align = ReportAlignType.LEFT;\n\n /**\n * The image will be placed as is. Please provide the greatest size as possible.\n *\n * @param img Buffered image\n * @param width width of image on report\n * @param height height of image on report\n */\n public ReportImage(BufferedImage img, float width, float height) {\n this.img = img;\n this.width = width;\n this.height = height;\n }\n\n @Override\n public float print(PDDocument document, PDPageContentStream stream, int pageNumber, float leftX, float startY, float allowedWidth) throws IOException {\n intent = new ImagePrintIntent(this, pageNumber, calcStartX(leftX, allowedWidth, width), startY);\n return startY - height;\n }\n\n @Override\n public float getHeight(float allowedWidth) {\n return height;\n }\n\n /**\n * <p>Call this method to print images. <b>Make sure that the streams are closed before calling this method </b></p>\n * <p>Normal print method doesn't work since: http://stackoverflow.com/questions/9326245/how-to-exactly-position-an-image-inside-an-existing-pdf-page-using-pdfbox</p>\n *\n * @param document the pdDocument.\n * @param pageNumber page of image\n * @param x location of image\n * @param y location of image\n * @throws java.io.IOException in case there are problems at reading or writing the image\n */\n public void printImage(PDDocument document, int pageNumber, float x, float y) throws IOException {\n PDImageXObject obj = LosslessFactory.createFromImage(document, img);\n\n PDPageContentStream currentStream = new PDPageContentStream(document,\n document.getDocumentCatalog().getPages().get(pageNumber), PDPageContentStream.AppendMode.APPEND, false);\n\n currentStream.drawImage(obj, x, y - height, width, height);\n currentStream.close();\n }\n\n private float calcStartX(float leftX, float allowedWidth, float imgWidth) {\n switch (getAlign()) {\n case LEFT:\n return leftX;\n case CENTER:\n return (allowedWidth - imgWidth) / 2 + leftX;\n default:\n throw new IllegalStateException(\"align type not implemented\");\n }\n }\n\n @Override\n public Collection<ImagePrintIntent> getImageIntents() {\n if (intent == null) {\n throw new IllegalStateException(\"print must be called before getImage intents\");\n }\n return Collections.singletonList(intent);\n }\n\n public void setAlign(ReportAlignType align) {\n this.align = align;\n }\n\n public ReportAlignType getAlign() {\n return align;\n }\n\n /**\n * This class is required, since pdf image printing has a bug. The img element must be created before the pdf box stream.\n */\n public static class ImagePrintIntent {\n private ReportImage img;\n private int page;\n private float x;\n private float y;\n\n public ImagePrintIntent(ReportImage img, int page, float x, float y) {\n this.img = img;\n this.page = page;\n this.x = x;\n this.y = y;\n }\n\n public ReportImage getImg() {\n return img;\n }\n\n public int getPage() {\n return page;\n }\n\n public float getX() {\n return x;\n }\n\n public float getY() {\n return y;\n }\n }\n\n public void setWidth(float width) {\n this.width = width;\n }\n\n public void setHeight(float height) {\n this.height = height;\n }\n\n public float getWidth() {\n return width;\n }\n\n public float getHeight() {\n return height;\n }\n}",
"public class ReportTable implements ReportElement {\n private static boolean LAYOUTING_ASSERTIONS_ENABLED = false;\n\n private static final boolean DEFAULT_BORDER = false;\n private static final float DEFAULT_CELL_PADDING_LEFT_RIGHT = 2;\n private static final float DEFAULT_CELL_PADDING_TOP_BOTTOM = 2;\n private final PdfStyleSheet pdfStyleSheet;\n\n private float[] cellWidths;\n private ReportVerticalAlignType[] cellAligns;\n private ReportElement[][] elements;\n private ReportElement[] title;\n private boolean border = DEFAULT_BORDER;\n private boolean noBottomBorder;\n private boolean noTopBorder;\n private boolean drawInnerHorizontal = true;\n private boolean drawInnerVertical = true;\n private boolean drawOuterVertical = true;\n private boolean enableExtraSplitting;\n private boolean isSplitable = true;\n private Collection<ReportImage.ImagePrintIntent> intents = new LinkedList<ReportImage.ImagePrintIntent>();\n\n /**\n * left and right cell padding\n */\n private float cellPaddingX = DEFAULT_CELL_PADDING_LEFT_RIGHT;\n private float cellPaddingY = DEFAULT_CELL_PADDING_TOP_BOTTOM;\n\n /**\n * @param cellWidths width of each column (the sum of elements must be 1)\n * @param elements elements of each cell\n * @param pdfStyleSheet the stylesheet to be used for this table\n * @param title the titles for the report (first row)\n */\n public ReportTable(PdfStyleSheet pdfStyleSheet, float[] cellWidths, ReportElement[][] elements, ReportElement[] title) {\n this.pdfStyleSheet = pdfStyleSheet;\n if (elements == null || cellWidths == null) {\n throw new IllegalArgumentException(\"Arguments cant be null\");\n }\n if (elements.length > 0 && cellWidths.length != elements[0].length) {\n throw new IllegalArgumentException(\"The cell widths must have the same number of elements as 'elements'\");\n }\n if (title != null && title.length != cellWidths.length) {\n throw new IllegalArgumentException(\"Title must be null, or the same size as elements\");\n }\n this.cellWidths = cellWidths;\n this.cellAligns = new ReportVerticalAlignType[cellWidths.length];\n Arrays.fill(cellAligns, ReportVerticalAlignType.TOP);\n this.elements = elements;\n this.title = title;\n }\n\n public void setNoInnerBorders(boolean noInnerBorders) {\n this.drawInnerHorizontal = !noInnerBorders;\n this.drawInnerVertical = !noInnerBorders;\n }\n\n public void setDrawInnerVertical(boolean drawInnerVertical) {\n this.drawInnerVertical = drawInnerVertical;\n }\n\n public void setDrawInnerHorizontal(boolean drawInnerHorizontal) {\n this.drawInnerHorizontal = drawInnerHorizontal;\n }\n\n public void setNoBottomBorder(boolean border) {\n this.noBottomBorder = border;\n }\n\n public void setNoTopBorder(boolean border) {\n this.noTopBorder = border;\n }\n\n public void setDrawOuterVertical(boolean drawOuterVertical) {\n this.drawOuterVertical = drawOuterVertical;\n }\n\n public void setBorder(boolean border) {\n this.border = border;\n }\n\n public void setExtraSplitting(boolean enableExtraSplitting) {\n this.enableExtraSplitting = enableExtraSplitting;\n }\n\n /**\n * @param cellPaddingX for left and right\n */\n public void setCellPaddingX(float cellPaddingX) {\n this.cellPaddingX = cellPaddingX;\n }\n\n /**\n * @param cellPaddingY for top and bottom\n */\n public void setCellPaddingY(float cellPaddingY) {\n this.cellPaddingY = cellPaddingY;\n }\n\n public boolean getExtraSplitting() {\n return enableExtraSplitting;\n }\n\n @Override\n public float print(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float startY, float allowedWidth) throws IOException {\n if (title != null) {\n throw new IllegalStateException(\"title not implemented!\");\n }\n float y = startY;\n float previousY = y;\n int lineIndex = 0;\n\n for (ReportElement[] line : elements) {\n float calculatedHeight = LAYOUTING_ASSERTIONS_ENABLED ? getLineHeight(line, allowedWidth) : -1;\n y = printLine(document, stream, pageNumber, startX, y, allowedWidth, line);\n float actualHeight = previousY - y;\n if (LAYOUTING_ASSERTIONS_ENABLED && calculatedHeight != actualHeight) {\n throw new RuntimeException(String.format(\"Layout algorithm bug: layouting height calculation reported \"\n + \"different height (%s) than painting code (%s) in table with %s lines, current line index: %s\",\n calculatedHeight, actualHeight, elements.length, lineIndex));\n }\n boolean isFirstLine = lineIndex == 0;\n boolean isLastLine = lineIndex == elements.length - 1;\n placeBorders(stream, previousY, y, startX, allowedWidth, isFirstLine, isLastLine);\n previousY = y;\n lineIndex++;\n }\n return y;\n }\n\n private void placeBorders(PDPageContentStream stream, float startY, float endY, float x, float allowedWidth,\n boolean isFirstLine, boolean isLastLine) throws IOException {\n if (!border) {\n return;\n }\n stream.setStrokingColor(0, 0, 0);\n stream.setLineWidth(0.3f);\n float y0 = startY;\n float y1 = endY;\n float x1 = x + allowedWidth;\n if (drawInnerHorizontal) {\n if (!noBottomBorder || noBottomBorder && !isLastLine) {\n drawLine(stream, x, x1, y1, y1);\n }\n }\n\n // top border\n if (!noTopBorder && isFirstLine) {\n drawLine(stream, x, x1, y0, y0);\n }\n // bottom border\n if (!noBottomBorder && isLastLine) {\n drawLine(stream, x, x1, y1, y1);\n }\n\n float currentX = x;\n for (int i = 0; i < cellWidths.length; i++) {\n float width = cellWidths[i];\n if (\n (i == 0 && drawOuterVertical) || // left\n (i > 0 && drawInnerVertical) // inner\n ) {\n drawLine(stream, currentX, currentX, y0, y1);\n }\n currentX += width * allowedWidth;\n }\n // draw last\n if (drawOuterVertical) {\n drawLine(stream, currentX, currentX, y0, y1);\n }\n }\n\n private void drawLine(PDPageContentStream stream, float x0, float x1, float y0, float y1) throws IOException {\n stream.moveTo(x0, y0);\n stream.lineTo(x1, y1);\n stream.stroke();\n }\n\n private float calculateVerticalAlignment(ReportElement[] line, int elementIndex, float y, float allowedWidth) {\n float yPos = 0;\n float lineHeight = getLineHeight(line, allowedWidth);\n switch (cellAligns[elementIndex]) {\n case TOP:\n yPos = y - cellPaddingY;\n break;\n case BOTTOM:\n yPos = y - cellPaddingY - lineHeight + line[elementIndex].getHeight(cellWidths[elementIndex] * allowedWidth - 2 * cellPaddingX);\n break;\n case MIDDLE:\n yPos = y - cellPaddingY - lineHeight / 2 + line[elementIndex].getHeight(cellWidths[elementIndex] * allowedWidth - 2 * cellPaddingX) / 2;\n break;\n default:\n throw new IllegalArgumentException(\"Vertical align type \" + cellAligns[elementIndex] + \" not implemented for tables\");\n }\n return yPos;\n }\n\n /**\n * draws a line.\n *\n * @return the new y position of the bottom of the line just drawn\n */\n private float printLine(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float y, float allowedWidth, ReportElement[] line) throws IOException {\n float x = startX + cellPaddingX;\n // minY = furthest that any cell has expanded to the bottom (min since coordinate system starts at the bottom)\n float minY = y;\n for (int i = 0; i < cellWidths.length; i++) {\n if (line[i] != null) {\n float yi = 0;\n float yPos = calculateVerticalAlignment(line, i, y, allowedWidth);\n\n final float columnNetWidth = getAllowedNetColumnWidth(allowedWidth, i);\n if (line[i] instanceof ReportImage) {\n ReportImage reportImage = (ReportImage) line[i];\n autoShrinkExcessiveImage(columnNetWidth, reportImage);\n\n yi = line[i].print(document, stream, pageNumber, x, yPos, columnNetWidth);\n reportImage.printImage(document, pageNumber, x, yPos);\n } else {\n yi = line[i].print(document, stream, pageNumber, x, yPos, columnNetWidth);\n }\n intents.addAll(line[i].getImageIntents());\n minY = Math.min(minY, yi);\n }\n x += cellWidths[i] * allowedWidth;\n }\n return minY - cellPaddingY;\n }\n\n private void autoShrinkExcessiveImage(float maxWidth, ReportImage reportImage) {\n float initialWidth = reportImage.getWidth();\n final float newHeight = reportImage.getHeight() * maxWidth / initialWidth;\n // only auto-shrink, don't auto-grow\n if (maxWidth <= reportImage.getWidth() || newHeight <= reportImage.getHeight()) {\n reportImage.setWidth(maxWidth);\n reportImage.setHeight(newHeight);\n }\n }\n\n @Override\n public float getHeight(float allowedWidth) {\n float[] maxes = new float[elements.length];\n for (int lineIndex = 0; lineIndex < elements.length; lineIndex++) {\n maxes[lineIndex] = getLineHeight(elements[lineIndex], allowedWidth);\n }\n float max = 0;\n for (float f : maxes) {\n max += f;\n }\n return max;\n }\n\n @Override\n public boolean isSplitable() {\n return isSplitable;\n }\n\n public void setSplitable(boolean isSplitable) {\n this.isSplitable = isSplitable;\n }\n\n @Override\n public float getFirstSegmentHeight(float allowedWidth) {\n if (elements != null && elements.length > 0) {\n final float firstSegmentHeightFromLine = getFirstSegmentHeightFromLine(elements[0], allowedWidth);\n return firstSegmentHeightFromLine + pdfStyleSheet.getLineDistance();\n } else {\n return 0;\n }\n }\n\n private float getFirstSegmentHeightFromLine(ReportElement[] line, float allowedWidth) {\n float maxHeight = 0f;\n for (int i = 0; i < line.length; i++) {\n if (line[i] != null) {\n maxHeight = Math.max(maxHeight, line[i].getFirstSegmentHeight(getAllowedNetColumnWidth(allowedWidth, i)));\n }\n }\n return maxHeight + 2 * cellPaddingY;\n }\n\n private float getLineHeight(ReportElement[] line, float allowedWidth) {\n float maxHeight = 0;\n float currentHeight;\n for (int columnIndex = 0; columnIndex < line.length; columnIndex++) {\n final float columnNetWidth = getAllowedNetColumnWidth(allowedWidth, columnIndex);\n if (line[columnIndex] != null) {\n if (line[columnIndex] instanceof ReportImage) {\n ReportImage reportImage = (ReportImage) line[columnIndex];\n autoShrinkExcessiveImage(columnNetWidth, reportImage);\n currentHeight = reportImage.getHeight();\n } else {\n currentHeight = line[columnIndex].getHeight(columnNetWidth);\n }\n maxHeight = Math.max(maxHeight, currentHeight);\n }\n }\n return maxHeight + 2 * cellPaddingY;\n }\n\n\n private ReportTable createNewTableWithClonedSettings(ReportElement[][] data) {\n ReportTable newTable = new ReportTable(pdfStyleSheet, cellWidths, data, title);\n newTable.setBorder(border);\n newTable.setCellPaddingX(cellPaddingX);\n newTable.setCellPaddingY(cellPaddingY);\n newTable.setExtraSplitting(enableExtraSplitting);\n return newTable;\n }\n\n @Override\n public Collection<ReportImage.ImagePrintIntent> getImageIntents() {\n return intents;\n }\n\n public ReportElement[] splitFirstCell(float allowedHeight, float allowedWidth) {\n ReportElement[] firstLineA = new ReportElement[elements[0].length];\n ReportElement[] firstLineB = new ReportElement[elements[0].length];\n boolean hasSecondPart = false;\n for (int i = 0; i < elements[0].length; i++) {\n ReportElement elem = elements[0][i];\n float width = cellWidths[i] * allowedWidth - 2 * cellPaddingX;\n if (elem != null && elem.isSplitable()) {\n ReportElement[] split = elem.split(width, allowedHeight);\n firstLineA[i] = split[0];\n firstLineB[i] = split[1];\n if (firstLineB[i] != null) {\n hasSecondPart = true;\n }\n } else {\n firstLineA[i] = elem;\n }\n }\n\n if (hasSecondPart) {\n ReportElement[][] newMatrix = new ReportElement[elements.length][elements[0].length];\n newMatrix[0] = firstLineB;\n for (int i = 1; i < elements.length; i++) {\n newMatrix[i] = elements[i];\n }\n\n ReportTable firstLine = createNewTableWithClonedSettings(new ReportElement[][]{firstLineA});\n ReportTable nextLines = createNewTableWithClonedSettings(newMatrix);\n\n return new ReportElement[]{firstLine, nextLines};\n } else {\n return new ReportElement[]{this, null};\n }\n }\n\n @Override\n public float getHeightOfElementToSplit(float allowedWidth, float allowedHeight) {\n float currentHeight = 0f;\n int i = 0;\n while (i < elements.length && (currentHeight + getLineHeight(elements[i], allowedWidth)) < allowedHeight) {\n currentHeight += getLineHeight(elements[i], allowedWidth);\n i++;\n }\n\n return getLineHeight(elements[i], allowedWidth);\n }\n\n @Override\n public ReportElement[] split(float allowedWidth, float allowedHeight) {\n float currentHeight = 0f;\n int lineIndex = 0;\n while (lineIndex < elements.length && (currentHeight + getLineHeight(elements[lineIndex], allowedWidth)) < allowedHeight) {\n currentHeight += getLineHeight(elements[lineIndex], allowedWidth);\n lineIndex++;\n }\n\n if (lineIndex > 0) {\n //they all fit until i-1, inclusive\n //check if the last row can be split\n ReportElement[][] extraRows = new ReportElement[2][elements[0].length];\n boolean splittable = false;\n if (enableExtraSplitting) {\n splittable = true;\n for (int j = 0; j < elements[lineIndex].length; j++) {\n if (!elements[lineIndex][j].isSplitable() || currentHeight + elements[lineIndex][j].getFirstSegmentHeight(getAllowedNetColumnWidth(allowedWidth, j)) + 2 * cellPaddingY >= allowedHeight) {\n splittable = false;\n }\n }\n\n if (splittable) {\n for (int j = 0; j < elements[lineIndex].length; j++) {\n if (elements[lineIndex][j].getHeight(getAllowedNetColumnWidth(allowedWidth, j)) + currentHeight < allowedHeight) {\n extraRows[0][j] = elements[lineIndex][j];\n extraRows[1][j] = new ReportTextBox(pdfStyleSheet.getBodyText(), pdfStyleSheet.getLineDistance(), \"\");\n } else {\n ReportElement[] extraSplit = elements[lineIndex][j].split(getAllowedNetColumnWidth(allowedWidth, j), allowedHeight - currentHeight - 2 * cellPaddingY);\n extraRows[0][j] = extraSplit[0];\n extraRows[1][j] = extraSplit[1];\n }\n }\n }\n }\n\n ReportElement[][] first = new ReportElement[splittable ? lineIndex + 1 : lineIndex][elements[0].length];\n ReportElement[][] next = new ReportElement[elements.length - lineIndex][elements[0].length];\n for (int j = 0; j < elements.length; j++) {\n if (j < lineIndex)\n first[j] = elements[j];\n else\n next[j - lineIndex] = elements[j];\n }\n if (splittable) {\n first[lineIndex] = extraRows[0];\n next[0] = extraRows[1];\n }\n ReportTable firstLine = createNewTableWithClonedSettings(first);\n ReportTable nextLines = createNewTableWithClonedSettings(next);\n\n return new ReportElement[]{firstLine, nextLines};\n } else {\n //this means first row does not fit in the given height\n ReportElement[][] first = new ReportElement[1][elements[0].length];\n ReportElement[][] next = new ReportElement[elements.length][elements[0].length];\n for (lineIndex = 1; lineIndex < elements.length; lineIndex++)\n next[lineIndex] = elements[lineIndex];\n for (lineIndex = 0; lineIndex < elements[0].length; lineIndex++) {\n ReportElement[] splits = elements[0][lineIndex].split(getAllowedNetColumnWidth(allowedWidth, lineIndex), allowedHeight - 2 * cellPaddingY);\n if (splits[0] != null)\n first[0][lineIndex] = splits[0];\n else\n first[0][lineIndex] = new ReportTextBox(pdfStyleSheet.getBodyText(), pdfStyleSheet.getLineDistance(), \"\");\n\n if (splits[1] != null)\n next[0][lineIndex] = splits[1];\n else\n next[0][lineIndex] = new ReportTextBox(pdfStyleSheet.getBodyText(), pdfStyleSheet.getLineDistance(), \"\");\n }\n ReportTable firstLine = createNewTableWithClonedSettings(first);\n ReportTable nextLines = createNewTableWithClonedSettings(next);\n\n return new ReportElement[]{firstLine, nextLines};\n }\n }\n\n /**\n * Gets the net column width (usable space for content, equals column width minus padding).\n */\n private float getAllowedNetColumnWidth(float allowedTableWidth, int columnIndex) {\n return getAllowedGrossColumnWidth(allowedTableWidth, columnIndex) - cellPaddingX * 2;\n }\n\n /**\n * Gets the gross column width (total width of the column).\n */\n private float getAllowedGrossColumnWidth(float allowedWidth, int columnIndex) {\n return cellWidths[columnIndex] * allowedWidth;\n }\n\n @Override\n public ReportElement[] split(float allowedWidth) {\n ReportElement[][] first = new ReportElement[][]{elements[0]};\n ReportElement[][] next = Arrays.copyOfRange(elements, 1, elements.length);\n\n ReportTable firstLine = createNewTableWithClonedSettings(first);\n ReportTable nextLines = createNewTableWithClonedSettings(next);\n\n return new ReportElement[]{firstLine, nextLines};\n }\n\n public void setTextAlignInColumn(int column, ReportAlignType alignType, boolean excludeHeader) {\n for (int i = excludeHeader ? 1 : 0; i < elements.length; i++) {\n ReportElement[] element = elements[i];\n if (element[column] instanceof ReportTextBox) {\n ((ReportTextBox) element[column]).setAlign(alignType);\n }\n }\n }\n\n public void setVerticalAlignInColumn(int column, ReportVerticalAlignType alignType) {\n cellAligns[column] = alignType;\n }\n\n public ReportElement[][] getElements() {\n return elements;\n }\n\n public ReportElement[] getTitle() {\n return title;\n }\n\n public float[] getCellWidths() {\n return cellWidths;\n }\n\n public PdfStyleSheet getPdfStyleSheet() {\n return pdfStyleSheet;\n }\n\n public static void setLayoutingAssertionsEnabled(boolean enabled) {\n LAYOUTING_ASSERTIONS_ENABLED = enabled;\n }\n\n}",
"public class PdfReportGeneratorException extends RuntimeException {\n\n public PdfReportGeneratorException(String message) {\n super(message);\n }\n}",
"public class PdfFontContext implements AutoCloseable {\n\n private static ThreadLocal<PdfFontContext> pdfFontContexts = new ThreadLocal<>();\n\n /**\n * Fonts currently loaded.\n */\n private Map<String, PdfFont> type0Fonts = new HashMap<>();\n\n /**\n * Fallback fonts to use when a target font doesn't support a given glyph.\n */\n private List<PDFont> fallbackFonts = new ArrayList();\n\n private PdfFontEncodingExceptionHandler fontEncodingExceptionHandler = null;\n\n public static PdfFontContext create() {\n final PdfFontContext oldContext = current();\n if (oldContext != null) {\n oldContext.close();\n }\n\n PdfFontContext context = new PdfFontContext();\n pdfFontContexts.set(context);\n return context;\n }\n\n /**\n * Gets the currently set stylesheet from the context or null if none set\n */\n public static PdfFontContext current() {\n return pdfFontContexts.get();\n }\n\n public static PdfFontContext currentOrCreate() {\n final PdfFontContext current = current();\n if (current == null) {\n return create();\n }\n return current;\n }\n\n private PdfFontContext() {\n }\n\n public PdfFont getFont(String fontName) {\n return type0Fonts.get(fontName);\n }\n\n public Collection<String> getAllFontNames() {\n return type0Fonts.keySet();\n }\n\n /**\n * Finds a font (PDFont not PdfFont wrapper) by name or returns null if not found.\n */\n public PDFont getInternalFont(String name) {\n return type0Fonts.values()\n .stream()\n .map(it -> it.getStyleByFontName(name))\n .filter(Objects::nonNull)\n .findFirst()\n .orElseGet(() -> PdfFont.getInternalFont(name));\n }\n\n public PdfFont registerFont(PDType0Font font) {\n String fontBaseName = font.getName();\n String fontStyle = \"regular\";\n\n if (font.getDescendantFont() instanceof PDCIDFontType2) {\n PDCIDFontType2 tmpFont = (PDCIDFontType2) font.getDescendantFont();\n NamingTable ttfNamingTable = (NamingTable) tmpFont.getTrueTypeFont().getTableMap().get(\"name\");\n\n fontBaseName = ttfNamingTable.getFontFamily();\n fontStyle = ttfNamingTable.getFontSubFamily().toLowerCase();\n }\n\n PdfFont f;\n if (type0Fonts.containsKey(fontBaseName)) {\n f = type0Fonts.get(fontBaseName);\n f.addStyle(fontStyle, font);\n } else {\n f = new PdfFont(fontBaseName);\n f.addStyle(fontStyle, font);\n type0Fonts.put(fontBaseName, f);\n }\n\n return f;\n }\n\n /**\n * Set global fallback fonts.\n */\n public void setFallbackFonts(List<PDFont> fallbacks) {\n if (fallbacks.stream().anyMatch(it -> it == null)) {\n throw new IllegalArgumentException(\"Must not pass null fonts.\");\n }\n this.fallbackFonts.clear();\n this.fallbackFonts.addAll(fallbacks);\n }\n\n public List<PDFont> getPossibleFonts(PDFont font) {\n List<PDFont> fonts = new ArrayList();\n fonts.add(font);\n fonts.addAll(fallbackFonts);\n return fonts;\n }\n\n /**\n * Register a custom font encoding exception handler which gives the program a chance to either\n * replace the problematic codepoints or simply log/throw custom exceptions.\n */\n public void registerFontEncodingExceptionHandler(PdfFontEncodingExceptionHandler handler) {\n this.fontEncodingExceptionHandler = handler;\n }\n\n public String handleFontEncodingException(String text, String codePointString, int start, int end) {\n if (this.fontEncodingExceptionHandler != null) {\n return this.fontEncodingExceptionHandler.handleFontEncodingException(text, codePointString, start, end);\n }\n throw new PdfBoxHelperException(\"Cannot encode '\" + codePointString + \"' in '\" + text + \"'.\");\n }\n\n\n @Override\n public void close() {\n type0Fonts.clear();\n\n pdfFontContexts.remove();\n }\n\n}"
] | import cc.catalysts.boot.report.pdf.config.PdfPageLayout;
import cc.catalysts.boot.report.pdf.config.PdfStyleSheet;
import cc.catalysts.boot.report.pdf.elements.ReportCompositeElement;
import cc.catalysts.boot.report.pdf.elements.ReportElement;
import cc.catalysts.boot.report.pdf.elements.ReportElementStatic;
import cc.catalysts.boot.report.pdf.elements.ReportImage;
import cc.catalysts.boot.report.pdf.elements.ReportTable;
import cc.catalysts.boot.report.pdf.exception.PdfReportGeneratorException;
import cc.catalysts.boot.report.pdf.utils.PdfFontContext;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue; | package cc.catalysts.boot.report.pdf.impl;
/**
* @author Paul Klingelhuber
*/
class PdfReportGenerator {
public PdfReportGenerator() {
}
public void printToStream(PdfPageLayout pageConfig, Resource templateResource, PdfReportStructure report, OutputStream stream, PDDocument document) throws IOException {
final DocumentWithResources documentWithResources = generate(pageConfig, templateResource, report, document);
documentWithResources.saveAndClose(stream);
}
public DocumentWithResources generate(PdfPageLayout pageConfig,
Resource templateResource,
PdfReportStructure report) throws IOException {
return generate(pageConfig, templateResource, report, new PDDocument());
}
public DocumentWithResources generate(PdfStyleSheet styleSheet,
PdfPageLayout pageConfig,
Resource templateResource,
PdfReportStructure report) throws IOException {
return generateInternal(pageConfig, templateResource, report, new PDDocument());
}
/**
* @param pageConfig page config
* @param report the report to print
* @return object that contains the printed PdfBox document and resources that need to be closed after finally writing the document
* @throws java.io.IOException
* fallback fonts from PdfStyleSheet.
*/
public DocumentWithResources generate(PdfPageLayout pageConfig,
Resource templateResource,
PdfReportStructure report,
PDDocument document) throws IOException {
try (PdfFontContext context = PdfFontContext.currentOrCreate()) {
return generateInternal(pageConfig, templateResource, report, document);
}
}
private DocumentWithResources generateInternal(PdfPageLayout pageConfig, Resource templateResource, PdfReportStructure report, PDDocument document) throws IOException {
final DocumentWithResources documentWithResources = new DocumentWithResources(document);
PrintData printData = new PrintData(templateResource, pageConfig);
PrintCursor cursor = new PrintCursor();
breakPage(documentWithResources, cursor, printData);
float maxWidth = pageConfig.getUsableWidth();
int reportElementIndex = 0, nrOfReportElements = report.getElements().size();
ReportElement currentReportElement = report.getElements().isEmpty() ? null : report.getElements().get(reportElementIndex);
ReportElement nextReportElement = null;
boolean performedBreakPageForCurrentReportElement = false; // for each element max. one break page allowed
while (currentReportElement != null) {
boolean forceBreak = false;
float height = currentReportElement.getHeight(maxWidth);
if (cursor.yPos - height < pageConfig.getLastY(cursor.currentPageNumber)) {
//out of bounds
if (currentReportElement.isSplitable() && (cursor.yPos - currentReportElement.getFirstSegmentHeight(maxWidth))
>= pageConfig.getLastY(cursor.currentPageNumber)) {
if (currentReportElement instanceof ReportTable) {
//it's a Table out of bounds, so we also do a height split
ReportElement[] twoElements = currentReportElement.split(maxWidth, cursor.yPos -
pageConfig.getLastY(cursor.currentPageNumber));
if (twoElements.length != 2) {
throw new IllegalStateException("The split method should always two parts.");
}
currentReportElement = twoElements[0];
nextReportElement = twoElements[1];
if (((ReportTable) currentReportElement).getExtraSplitting()) {
forceBreak = true;
} | } else if (currentReportElement instanceof ReportCompositeElement) { | 2 |
vangj/jbayes | src/test/java/com/github/vangj/jbayes/inf/exact/graph/pptc/blocks/PropagationTest.java | [
"public class Dag extends Graph {\n\n protected Map<String, List<Node>> parents;\n protected Map<String, List<Node>> children;\n\n public Dag() {\n parents = new HashMap<>();\n children = new HashMap<>();\n }\n\n /**\n * Initializes the potential for each node.\n *\n * @return Dag.\n */\n public Dag initializePotentials() {\n nodes().forEach(node -> {\n Potential potential = getPotential(node, parents(node));\n node.setPotential(potential);\n });\n return this;\n }\n\n @Override\n protected Graph instance() {\n return new Dag();\n }\n\n @Override\n public Graph addEdge(Edge edge) {\n edge.type = Edge.Type.DIRECTED;\n\n if (DagShortestPath.exists(this, edge.right, edge.left, null)) {\n //if right -> -> -> left path alrady exists\n //then adding left -> right will form cycle!\n //do not add it\n return this;\n }\n\n super.addEdge(edge);\n Node n1 = edge.left;\n Node n2 = edge.right;\n\n List<Node> parents = parents(n2);\n if (!parents.contains(n1)) {\n parents.add(n1);\n }\n\n List<Node> children = children(n1);\n if (!children.contains(n2)) {\n children.add(n2);\n }\n return this;\n }\n\n /**\n * Gets the parent of the specified node.\n *\n * @param node Node.\n * @return List of parents.\n */\n public List<Node> parents(Node node) {\n List<Node> parents = this.parents.get(node.id);\n if (null == parents) {\n parents = new ArrayList<>();\n this.parents.put(node.id, parents);\n }\n return parents;\n }\n\n /**\n * Gets the children of the specified node.\n *\n * @param node Node.\n * @return List of children.\n */\n public List<Node> children(Node node) {\n List<Node> children = this.children.get(node.id);\n if (null == children) {\n children = new ArrayList<>();\n this.children.put(node.id, children);\n }\n return children;\n }\n\n /**\n * Gets the coparents of the specified node. Coparents are parents of the specified node's\n * children.\n *\n * @param node Node.\n * @return List of coparents.\n */\n public List<Node> coparents(Node node) {\n Set<Node> copas = new HashSet<>();\n children(node).forEach(n -> {\n copas.addAll(parents(n));\n });\n copas.remove(node);\n return new ArrayList<>(copas);\n }\n\n /**\n * Gets the Markov blanket for the specified node. The Markov blanket is specified as the union of\n * parents, children, and coparents.\n *\n * @param node Node.\n * @return List of nodes in the Markov blanket.\n */\n public List<Node> markovBlanket(Node node) {\n Set<Node> blanket = new HashSet<>();\n blanket.addAll(parents(node));\n blanket.addAll(children(node));\n blanket.addAll(coparents(node));\n blanket.remove(node);\n return new ArrayList<>(blanket);\n }\n}",
"public class Ug extends Graph {\n\n @Override\n protected Graph instance() {\n return new Ug();\n }\n\n @Override\n public Graph addEdge(Edge edge) {\n edge.type = Edge.Type.UNDIRECTED;\n return super.addEdge(edge);\n }\n}",
"public class PotentialEntry {\n\n private final Map<String, String> entries;\n private Double value;\n\n public PotentialEntry() {\n entries = new LinkedHashMap<>();\n value = new Double(1.0d);\n }\n\n private PotentialEntry(Map<String, String> entries, Double value) {\n this.entries = entries;\n this.value = value;\n }\n\n public PotentialEntry duplicate() {\n Map<String, String> entries = new LinkedHashMap<>(this.entries);\n Double value = new Double(this.value);\n return new PotentialEntry(entries, value);\n }\n\n public PotentialEntry add(String id, String value) {\n if (!entries.containsKey(id)) {\n entries.put(id, value);\n }\n return this;\n }\n\n public Double getValue() {\n return value;\n }\n\n public PotentialEntry setValue(Double value) {\n this.value = value;\n return this;\n }\n\n /**\n * Checks if the specified potential entry matches. This potential entry must contain, at the very\n * least, all the same key-value pairs as the specified potential entry passed in.\n *\n * @param that Potential entry.\n * @return Boolean.\n */\n public boolean match(PotentialEntry that) {\n for (Map.Entry<String, String> entry : that.entries.entrySet()) {\n String k = entry.getKey();\n String v = entry.getValue();\n\n if (!this.entries.containsKey(k)) {\n return false;\n } else {\n if (!this.entries.get(k).equalsIgnoreCase(v)) {\n return false;\n }\n }\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n return asString(sortByKeys(entries)).hashCode();\n }\n\n @Override\n public boolean equals(Object object) {\n if (null == object || !(object instanceof PotentialEntry)) {\n return false;\n }\n PotentialEntry that = (PotentialEntry) object;\n return (this.hashCode() == that.hashCode());\n }\n\n @Override\n public String toString() {\n return (new StringBuilder())\n .append(asString(entries))\n .append(\" \")\n .append(value)\n .toString();\n }\n}",
"public class Clique {\n\n protected boolean marked = false;\n protected Map<String, Node> nodes;\n\n public Clique() {\n nodes = new LinkedHashMap<>();\n }\n\n public Clique(Node node, List<Node> nodes) {\n this.nodes = new LinkedHashMap<>();\n for (Node n : nodes) {\n this.nodes.put(n.getId(), n);\n }\n this.nodes.put(node.getId(), node);\n }\n\n public Clique(Node... nodes) {\n this.nodes = new LinkedHashMap<>();\n for (Node n : nodes) {\n this.nodes.put(n.getId(), n);\n }\n }\n\n /**\n * Checks if this clique is marked.\n *\n * @return Boolean.\n */\n public boolean isMarked() {\n return marked;\n }\n\n /**\n * Marks this clique.\n */\n public void mark() {\n marked = true;\n }\n\n /**\n * Unmarks this clique.\n */\n public void unmark() {\n marked = false;\n }\n\n /**\n * Gets all the nodes in this clique minuse the ones specified by the list of nodes passed in.\n *\n * @param nodes List of nodes.\n * @return List of nodes.\n */\n public List<Node> nodesMinus(List<Node> nodes) {\n return nodes().stream()\n .filter(node -> {\n return !nodes.contains(node);\n })\n .collect(Collectors.toList());\n }\n\n /**\n * Checks if this clique is a superset of the specified clique passed in.\n *\n * @param that Clique.\n * @return Boolean.\n */\n public boolean isSuperset(Clique that) {\n Set<Node> set1 = new LinkedHashSet<>(this.nodes.values());\n Set<Node> set2 = new LinkedHashSet<>(that.nodes.values());\n set1.retainAll(set2);\n return set1.size() == set2.size();\n }\n\n @Override\n public int hashCode() {\n return toString().hashCode();\n }\n\n @Override\n public boolean equals(Object object) {\n if (null == object || !(object instanceof Clique)) {\n return false;\n }\n Clique that = (Clique) object;\n return this.hashCode() == that.hashCode();\n }\n\n /**\n * Weight is defined as product of the number of values for each node.\n *\n * @return Weight.\n */\n public int weight() {\n int weight = 1;\n for (Map.Entry<String, Node> entry : nodes.entrySet()) {\n weight *= entry.getValue().weight();\n }\n return weight;\n }\n\n /**\n * Gets the nodes.\n *\n * @return List of nodes\n */\n public List<Node> nodes() {\n return nodes.values().stream().collect(Collectors.toList());\n }\n\n /**\n * Checks if this clique contains the node associated with the specified id.\n *\n * @param id Id.\n * @return Boolean.\n */\n public boolean contains(String id) {\n return nodes.containsKey(id);\n }\n\n /**\n * Creates a separation set from this clique and the clique passed in. The separation set should\n * be the intersection of the nodes between this clique and the one passed in.\n *\n * @param that Clique.\n * @return Separation set.\n */\n public SepSet sepSet(Clique that) {\n return new SepSet(this, that);\n }\n\n /**\n * Gets the id of this node. Composed of the lexicographically ordered ids of the nodes in this\n * clique.\n *\n * @return Id.\n */\n public String id() {\n return NodeUtil.id(nodes());\n }\n\n @Override\n public String toString() {\n return id();\n }\n}",
"public class HuangExample {\n\n protected Dag getDag() {\n return ((Dag) (new Dag()\n .addNode(getNode(\"a\"))\n .addNode(getNode(\"b\"))\n .addNode(getNode(\"c\"))\n .addNode(getNode(\"d\"))\n .addNode(getNode(\"e\"))\n .addNode(getNode(\"f\"))\n .addNode(getNode(\"g\"))\n .addNode(getNode(\"h\"))\n .addEdge(\"a\", \"b\")\n .addEdge(\"a\", \"c\")\n .addEdge(\"b\", \"d\")\n .addEdge(\"c\", \"e\")\n .addEdge(\"d\", \"f\")\n .addEdge(\"e\", \"f\")\n .addEdge(\"c\", \"g\")\n .addEdge(\"e\", \"h\")\n .addEdge(\"g\", \"h\")))\n .initializePotentials();\n\n }\n\n protected Node getNode(String id) {\n if (\"a\".equals(id)) {\n return Node.builder()\n .id(id)\n .name(id)\n .value(\"on\")\n .value(\"off\")\n .probs(Arrays.asList(0.5d, 0.5d))\n .build();\n } else if (\"b\".equalsIgnoreCase(id)) {\n return Node.builder()\n .id(id)\n .name(id)\n .value(\"on\")\n .value(\"off\")\n .probs(Arrays.asList(0.5d, 0.5d, 0.4d, 0.6d))\n .build();\n } else if (\"c\".equalsIgnoreCase(id)) {\n return Node.builder()\n .id(id)\n .name(id)\n .value(\"on\")\n .value(\"off\")\n .probs(Arrays.asList(0.7d, 0.3d, 0.2d, 0.8d))\n .build();\n } else if (\"d\".equalsIgnoreCase(id)) {\n return Node.builder()\n .id(id)\n .name(id)\n .value(\"on\")\n .value(\"off\")\n .probs(Arrays.asList(0.9d, 0.1d, 0.5d, 0.5d))\n .build();\n } else if (\"e\".equalsIgnoreCase(id)) {\n return Node.builder()\n .id(id)\n .name(id)\n .value(\"on\")\n .value(\"off\")\n .probs(Arrays.asList(0.3d, 0.7d, 0.6d, 0.4d))\n .build();\n } else if (\"f\".equalsIgnoreCase(id)) {\n return Node.builder()\n .id(id)\n .name(id)\n .value(\"on\")\n .value(\"off\")\n .probs(Arrays.asList(0.01d, 0.99d, 0.01d, 0.99d, 0.01d, 0.99d, 0.99d, 0.01d))\n .build();\n } else if (\"g\".equalsIgnoreCase(id)) {\n return Node.builder()\n .id(id)\n .name(id)\n .value(\"on\")\n .value(\"off\")\n .probs(Arrays.asList(0.8d, 0.2d, 0.1d, 0.9d))\n .build();\n } else if (\"h\".equalsIgnoreCase(id)) {\n return Node.builder()\n .id(id)\n .name(id)\n .value(\"on\")\n .value(\"off\")\n .probs(Arrays.asList(0.05d, 0.95d, 0.95d, 0.05d, 0.95d, 0.05d, 0.95d, 0.05d))\n .build();\n }\n return Node.builder()\n .id(id)\n .name(id)\n .value(\"on\")\n .value(\"off\")\n .build();\n }\n}",
"public class JoinTree {\n\n private final Map<String, Clique> cliques;\n private final Map<String, Set<Clique>> neighbors;\n private final Set<Edge> edges;\n private final Map<String, Potential> potentials;\n private final Map<String, Map<String, Potential>> evidences;\n private Listener listener;\n\n public JoinTree() {\n this(new ArrayList<>());\n }\n\n public JoinTree(List<Clique> cliques) {\n this.cliques = new HashMap<>();\n neighbors = new HashMap<>();\n edges = new LinkedHashSet<>();\n potentials = new LinkedHashMap<>();\n evidences = new HashMap<>();\n\n for (Clique clique : cliques) {\n addClique(clique);\n }\n }\n\n /**\n * Sets the listener.\n *\n * @param listener Listener.\n * @return Join tree.\n */\n public JoinTree setListener(Listener listener) {\n this.listener = listener;\n return this;\n }\n\n /**\n * Gets the evidence associated with the specified node and value. If none exists, will return a\n * potential with likelihood of 1.0.\n *\n * @param node Node.\n * @param value Value.\n * @return Potential.\n */\n public Potential getEvidencePotential(Node node, String value) {\n Map<String, Potential> nodeEvidences = evidences.get(node.getId());\n if (null == nodeEvidences) {\n nodeEvidences = new HashMap<>();\n evidences.put(node.getId(), nodeEvidences);\n }\n\n Potential potential = nodeEvidences.get(value);\n if (null == potential) {\n potential = new Potential()\n .addEntry(new PotentialEntry().add(node.getId(), value).setValue(1.0d));\n nodeEvidences.put(value, potential);\n }\n\n return potential;\n }\n\n /**\n * Gets the change type.\n *\n * @param evidence Evidence.\n * @return Change type.\n */\n private Evidence.Change getChangeType(Evidence evidence) {\n Node node = evidence.getNode();\n Map<String, Potential> potentials = evidences.get(node.getId());\n Evidence.Change change = evidence.compare(potentials);\n return change;\n }\n\n /**\n * Gets the change type for the list of evidences. Precendence is retraction, update, then none.\n *\n * @param evidences List of evidence.\n * @return Change type.\n */\n private Evidence.Change getChangeType(List<Evidence> evidences) {\n List<Evidence.Change> changes = evidences.stream()\n .map(evidence -> getChangeType(evidence))\n .collect(Collectors.toList());\n int count = (int) changes.stream()\n .filter(change -> (Evidence.Change.Retraction == change))\n .count();\n if (count > 0) {\n return Evidence.Change.Retraction;\n }\n\n count = (int) changes.stream()\n .filter(change -> (Evidence.Change.Update == change))\n .count();\n if (count > 0) {\n return Evidence.Change.Update;\n }\n\n return Evidence.Change.None;\n }\n\n /**\n * Creates evidence where all likelihoods are set to 1 (unobserved).\n *\n * @param node Node.\n * @return Evidence.\n */\n private Evidence getUnobservedEvidence(Node node) {\n Evidence.Builder builder = Evidence.newBuilder()\n .node(node)\n .type(Evidence.Type.Unobserve);\n node.getValues().forEach(value -> builder.value(value, 1.0d));\n return builder.build();\n }\n\n /**\n * Unobserves the specified node.\n *\n * @param node Node.\n * @return Join tree.\n */\n public JoinTree unobserve(Node node) {\n updateEvidence(getUnobservedEvidence(node));\n return this;\n }\n\n /**\n * Unobserves the specified list of nodes.\n *\n * @param nodes List of nodes.\n * @return Join tree.\n */\n public JoinTree unobserve(List<Node> nodes) {\n List<Evidence> evidences = nodes.stream()\n .map(node -> getUnobservedEvidence(node))\n .collect(Collectors.toList());\n updateEvidence(evidences);\n return this;\n }\n\n /**\n * Unobserves all nodes.\n *\n * @return Join tree.\n */\n public JoinTree unobserveAll() {\n unobserve(new ArrayList<>(nodes()));\n return this;\n }\n\n /**\n * Update with a single evidence. Will trigger inference.\n *\n * @param evidence Evidence.\n * @return Join tree.\n */\n public JoinTree updateEvidence(Evidence evidence) {\n Evidence.Change change = getChangeType(evidence);\n update(evidence);\n notifiyListener(change);\n return this;\n }\n\n /**\n * Updates with a list of evidences. Will trigger inference.\n *\n * @param evidences List of evidences.\n * @return Join tree.\n */\n public JoinTree updateEvidence(List<Evidence> evidences) {\n Evidence.Change change = getChangeType(evidences);\n evidences.stream().forEach(evidence -> update(evidence));\n notifiyListener(change);\n return this;\n }\n\n /**\n * Notifies the listener of evidence change.\n *\n * @param change Change.\n */\n private void notifiyListener(Evidence.Change change) {\n if (null != listener) {\n if (Evidence.Change.Retraction == change) {\n listener.evidenceRetracted(this);\n } else if (Evidence.Change.Update == change) {\n listener.evidenceUpdated(this);\n } else {\n listener.evidenceNoChange(this);\n }\n }\n }\n\n private void update(Evidence evidence) {\n Node node = evidence.getNode();\n Map<String, Potential> potentials = evidences.get(node.getId());\n\n evidence.getValues().entrySet().stream().forEach(entry -> {\n Potential potential = potentials.get(entry.getKey());\n potential.entries().get(0).setValue(entry.getValue());\n });\n }\n\n /**\n * Gets the potential (holding the probabilities) for the specified node.\n *\n * @param node Node.\n * @return Potential.\n */\n public Potential getPotential(Node node) {\n Clique clique = (Clique) node.getMetadata(\"parent.clique\");\n return normalize(marginalizeFor(this, clique, Arrays.asList(node)));\n }\n\n /**\n * Unmarks all cliques.\n */\n public void unmarkCliques() {\n allCliques().forEach(Clique::unmark);\n }\n\n /**\n * Gets the potential.\n *\n * @return List of potential.\n */\n public List<Potential> potentials() {\n return potentials.values().stream().collect(Collectors.toList());\n }\n\n /**\n * Gets all the cliques containing the specified node and its parents.\n *\n * @param node Node.\n * @return List of cliques.\n */\n public List<Clique> cliquesContainingNodeAndParents(Node node) {\n return cliques().stream()\n .filter(clique -> {\n if (!clique.contains(node.getId())) {\n return false;\n }\n List<Node> parents = (List<Node>) node.getMetadata(\"parents\");\n if (parents != null && parents.size() > 0) {\n for (Node parent : parents) {\n if (!clique.contains(parent.getId())) {\n return false;\n }\n }\n }\n return true;\n })\n .collect(Collectors.toList());\n }\n\n /**\n * Gest all the nodes in this join tree.\n *\n * @return Set of nodes.\n */\n public Set<Node> nodes() {\n Set<Node> nodes = new HashSet<>();\n cliques().forEach(clique -> {\n nodes.addAll(clique.nodes());\n });\n return nodes;\n }\n\n /**\n * Gets the node associated with the specified id.\n *\n * @param id Id.\n * @return Node.\n */\n public Node node(String id) {\n return nodes().stream()\n .filter(node -> (id.equals(node.getId())))\n .findFirst().get();\n }\n\n /**\n * Gets the potential associated with the specified clique.\n *\n * @param clique Clique.\n * @return Potential.\n */\n public Potential getPotential(Clique clique) {\n return potentials.get(clique.id());\n }\n\n /**\n * Adds potential associated with the specified clique.\n *\n * @param clique Clique.\n * @param potential Potential.\n * @return Join tree.\n */\n public JoinTree addPotential(Clique clique, Potential potential) {\n potentials.put(clique.id(), potential);\n return this;\n }\n\n /**\n * Gets the neighbors of the specified clique.\n *\n * @param clique Clique.\n * @return Set of neighbors. This includes cliques and separation sets.\n */\n public Set<Clique> neighbors(Clique clique) {\n return neighbors.get(clique.id());\n }\n\n /**\n * Gets the clique that matches exactly to the specified nodes.\n *\n * @param nodes Nodes.\n * @return Clique.\n */\n public Clique clique(Node... nodes) {\n String id = NodeUtil.id(Arrays.asList(nodes));\n return cliques.get(id);\n }\n\n /**\n * Gets the separation set that matches exactly to the specifed nodes.\n *\n * @param nodes Nodes.\n * @return Separation set.\n */\n public SepSet sepSet(Node... nodes) {\n String id = NodeUtil.id(Arrays.asList(nodes), \"|\", \"|\");\n return (SepSet) cliques.get(id);\n }\n\n /**\n * Gets the neighbors of the clique that matches exactly with the specified nodes.\n *\n * @param nodes Nodes.\n * @return Set of neighbors. This includes cliques and separation sets.\n */\n public Set<Clique> neighbors(Node... nodes) {\n final String id = NodeUtil.id(Arrays.asList(nodes));\n return neighbors.get(id);\n }\n\n /**\n * Gets all the cliques (cliques + separation sets).\n *\n * @return Cliques.\n */\n public List<Clique> allCliques() {\n return cliques.values().stream().collect(Collectors.toList());\n }\n\n /**\n * Gets the cliques (no separation sets).\n *\n * @return Cliques.\n */\n public List<Clique> cliques() {\n return cliques.values().stream()\n .filter(clique -> !(clique instanceof SepSet))\n .collect(Collectors.toList());\n }\n\n /**\n * Gets the separation sets.\n *\n * @return Separation sets.\n */\n public List<SepSet> sepSets() {\n return cliques.values().stream()\n .filter(clique -> (clique instanceof SepSet))\n .map(clique -> (SepSet) clique)\n .collect(Collectors.toList());\n }\n\n /**\n * Gets the edges.\n *\n * @return Edges.\n */\n public List<Edge> edges() {\n return edges.stream().collect(Collectors.toList());\n }\n\n /**\n * Adds a clique to the join tree if it doesn't exist already.\n *\n * @param clique Clique.\n * @return Join tree.\n */\n public JoinTree addClique(Clique clique) {\n final String id = clique.id();\n if (!cliques.containsKey(id)) {\n cliques.put(id, clique);\n }\n return this;\n }\n\n /**\n * Adds the edge to the join tree if it doesn't exist already.\n *\n * @param edge Edge.\n * @return Join tree.\n */\n public JoinTree addEdge(Edge edge) {\n addClique(edge.left).addClique(edge.right);\n if (!edges.contains(edge)) {\n edges.add(edge);\n\n final String id1 = edge.left.id();\n final String id2 = edge.right.id();\n\n Set<Clique> ne1 = neighbors.get(id1);\n Set<Clique> ne2 = neighbors.get(id2);\n\n if (null == ne1) {\n ne1 = new LinkedHashSet<>();\n neighbors.put(id1, ne1);\n }\n\n if (null == ne2) {\n ne2 = new LinkedHashSet<>();\n neighbors.put(id2, ne2);\n }\n\n ne1.add(edge.right);\n\n ne2.add(edge.left);\n }\n return this;\n }\n\n @Override\n public String toString() {\n String c = allCliques().stream()\n .map(Clique::toString)\n .collect(Collectors.joining(System.lineSeparator()));\n String e = edges().stream()\n .map(Edge::toString)\n .collect(Collectors.joining(System.lineSeparator()));\n String p = potentials.entrySet().stream()\n .map(entry -> {\n Clique clique = cliques.get(entry.getKey());\n Potential potential = entry.getValue();\n return (new StringBuilder())\n .append(clique.toString())\n .append(\" potential\")\n .append(System.lineSeparator())\n .append(potential.toString());\n })\n .collect(Collectors.joining(System.lineSeparator()));\n\n return (new StringBuilder())\n .append(c)\n .append(System.lineSeparator())\n .append(e)\n .append(System.lineSeparator())\n .append(p)\n .toString();\n }\n\n public interface Listener {\n\n void evidenceRetracted(JoinTree joinTree);\n\n void evidenceUpdated(JoinTree joinTree);\n\n void evidenceNoChange(JoinTree joinTree);\n }\n}"
] | import static org.junit.Assert.assertEquals;
import com.github.vangj.jbayes.inf.exact.graph.Dag;
import com.github.vangj.jbayes.inf.exact.graph.Ug;
import com.github.vangj.jbayes.inf.exact.graph.lpd.PotentialEntry;
import com.github.vangj.jbayes.inf.exact.graph.pptc.Clique;
import com.github.vangj.jbayes.inf.exact.graph.pptc.HuangExample;
import com.github.vangj.jbayes.inf.exact.graph.pptc.JoinTree;
import java.util.List;
import org.junit.Test; | package com.github.vangj.jbayes.inf.exact.graph.pptc.blocks;
public class PropagationTest extends HuangExample {
@Test
public void testPropagation() {
Dag dag = getDag();
Ug m = Moralize.moralize(dag); | List<Clique> cliques = Triangulate.triangulate(m); | 3 |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/activity/MyRecordCollect.java | [
"public class ManhuaCollectAdapter extends BaseAdapter {\n\t\n\tprivate Context mContext = null;\n\tprivate LayoutInflater mLayoutInflater = null;\n\tprivate ImageLoader mImageLoader = null;\n\tprivate DisplayImageOptions mOptions = null;\n\tprivate GroupCollect mGroupCollect = null;\n\tprivate Map<String, Manhua> mManhuaMap = null;\n\tprivate List<Manhua> mManhuaList = null;\n\n\tpublic ManhuaCollectAdapter(Context context, GroupCollect groupCollect) {\n\t\tmContext = context;\n\t\tmLayoutInflater = LayoutInflater.from(mContext);\n\t\tmImageLoader = ImageLoader.getInstance();\n\t\tmGroupCollect = groupCollect;\n\t\tmManhuaMap = mGroupCollect.getCollectMap();\n\t\tmManhuaList = mapTransitionList(mManhuaMap);\n\t\tmOptions = new DisplayImageOptions.Builder()\n\t\t.showImageOnLoading(R.drawable.empty_photo)\n\t\t.showImageOnFail(R.drawable.empty_photo)\n\t\t.cacheInMemory(true)\n\t\t.cacheOnDisk(true)\n\t\t.bitmapConfig(Config.RGB_565)\n\t\t.build();\n\t}\n\n\t@Override\n\tpublic int getCount() {\n\t\treturn mManhuaList.size();\n\t}\n\n\t@Override\n\tpublic Manhua getItem(int position) {\n\t\treturn mManhuaList.get(position);\n\t}\n\n\t@Override\n\tpublic long getItemId(int position) {\n\t\treturn position;\n\t}\n\n\t@Override\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n\t\tViewHolder viewHolder = null;\n\t\tif(convertView == null) {\n\t\t\tviewHolder = new ViewHolder();\n\t\t\tconvertView = mLayoutInflater.inflate(R.layout.frag_item_listview , null);\n\t\t\tviewHolder.tv_Manhua_Name = (TextView) convertView.findViewById(R.id.id_manhua_name);\n\t\t\tviewHolder.tv_Manhua_lastUpdate = (TextView) convertView.findViewById(R.id.id_manhua_lastUpdate);\n\t\t\tviewHolder.iv_Manhua_Cover = (ImageView) convertView.findViewById(R.id.id_manhua_Cover);\n\t\t\tconvertView.setTag(viewHolder);\n\t\t}\n\t\telse {\n\t\t\tviewHolder = (ViewHolder) convertView.getTag();\n\t\t\tviewHolder.iv_Manhua_Cover.setImageResource(R.drawable.empty_photo);\n\t\t}\n\t\tManhua manhua = getItem(position);\n\t\tviewHolder.tv_Manhua_Name.setText(manhua.getmName());\n\t\tint manhuaLastUpdate = manhua.getmLastUpdate();\n\t\tint year = manhuaLastUpdate / 10000;\n\t\tint month = manhuaLastUpdate / 100 % 100;\n\t\tint day = manhuaLastUpdate % 100;\n\t\tviewHolder.tv_Manhua_lastUpdate.setText(\"×î½ü¸üР: \" + year + \"Äê\" + month + \"ÔÂ\" + day + \"ÈÕ\");\n\t\tString imageURL = manhua.getmCoverImg();\n\t\tmImageLoader.displayImage(imageURL , viewHolder.iv_Manhua_Cover , mOptions , new SimpleImageLoadingListener() , new ImageLoadingProgressListener() {\n\t\t\t@Override\n\t\t\tpublic void onProgressUpdate(String imageUri, View view, int current, int total) {\n\t\t\t\t\n\t\t\t}\n\t\t});\n\t\treturn convertView;\n\t}\n\t\n\t\n\t\n\tpublic List<Manhua> mapTransitionList(Map<String, Manhua> map) {\n\t\tList<Manhua> list = new ArrayList<Manhua>();\n\t\tIterator<Entry<String, Manhua>> iterator = map.entrySet().iterator();\n\t\twhile(iterator.hasNext()) {\n\t\t\tEntry<String, Manhua> entry = (Entry<String, Manhua>)iterator.next();\n\t\t\tlist.add(entry.getValue());\n\t\t}\n\t\treturn list;\n\t}\n\t\n\t\n\t\n\tclass ViewHolder {\n public TextView tv_Manhua_Name = null;\n public TextView tv_Manhua_lastUpdate = null;\n public ImageView iv_Manhua_Cover = null;\n }\n\n}",
"public class GroupCollect {\n\t\n\tprivate Map<String , Manhua> collectHashMap = null;\n\t\n\tpublic GroupCollect() {\n\t\tthis.collectHashMap = new HashMap<String, Manhua>();\n\t}\n\t\n\tpublic Map<String, Manhua> getCollectMap() {\n\t\treturn this.collectHashMap;\n\t}\n\t\n\tpublic void setCollectMap(Map<String, Manhua> collectHashMap) {\n\t\tthis.collectHashMap = collectHashMap;\n\t}\n\t\n\tpublic void addCollect(Manhua collectHashMap) {\n\t\tString url = collectHashMap.getmCoverImg();\n\t\tString key = MD5Tools.hashKeyForDisk(url);\n\t\tthis.collectHashMap.put(key , collectHashMap);\n\t}\n\t\n\tpublic void removeCollect(String url) {\n\t\tString key = MD5Tools.hashKeyForDisk(url);\n\t\tthis.collectHashMap.remove(key);\n\t}\n\n}",
"public class Manhua {\n\t\n\tprivate String mType = null;\n\tprivate String mName = null;\n\tprivate String mDes = null;\n\tprivate boolean mFinish = false;\n\tprivate int mLastUpdate;\n\tprivate String mCoverImg = null;\n\t\n\t\n\tpublic Manhua() {\n\t\t\n\t}\n\t\n\tpublic Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {\n\t\tsuper();\n\t\tthis.mType = mType;\n\t\tthis.mName = mName;\n\t\tthis.mDes = mDes;\n\t\tthis.mFinish = mFinish;\n\t\tthis.mLastUpdate = mLastUpdate;\n\t\tthis.mCoverImg = mCoverImg;\n\t}\n\t\n\t\n\t\n\n\tpublic String getmType() {\n\t\treturn mType;\n\t}\n\n\tpublic void setmType(String mType) {\n\t\tthis.mType = mType;\n\t}\n\n\tpublic String getmName() {\n\t\treturn mName;\n\t}\n\n\tpublic void setmName(String mName) {\n\t\tthis.mName = mName;\n\t}\n\n\tpublic String getmDes() {\n\t\treturn mDes;\n\t}\n\n\tpublic void setmDes(String mDes) {\n\t\tthis.mDes = mDes;\n\t}\n\n\tpublic boolean ismFinish() {\n\t\treturn mFinish;\n\t}\n\n\tpublic void setmFinish(boolean mFinish) {\n\t\tthis.mFinish = mFinish;\n\t}\n\n\tpublic int getmLastUpdate() {\n\t\treturn mLastUpdate;\n\t}\n\n\tpublic void setmLastUpdate(int mLastUpdate) {\n\t\tthis.mLastUpdate = mLastUpdate;\n\t}\n\n\tpublic String getmCoverImg() {\n\t\treturn mCoverImg;\n\t}\n\n\tpublic void setmCoverImg(String mCoverImg) {\n\t\tthis.mCoverImg = mCoverImg;\n\t}\n\t\n\t\n\t\n\t\n\n}",
"public class Config {\n\t\n\t//¾ÛºÏÊý¾ÝµÄapp key\n\tpublic static final String APP_KEY = \"¾ÛºÏÊý¾ÝµÄapp key\";\n\t//Æѹ«Ó¢µÄapp id\n\tpublic static final String Pgy_ID = \"Æѹ«Ó¢µÄapp id\";\n\tpublic static final int APP_ID = 163;\n\t\n\tpublic static final String JSON_error_code = \"error_code\";\n\tpublic static final String JSON_result = \"result\";\n\tpublic static final String JSON_bookList = \"bookList\";\n\tpublic static final String JSON_name = \"name\";\n\tpublic static final String JSON_id = \"id\";\n\tpublic static final String JSON_type = \"type\";\n\tpublic static final String JSON_des = \"des\";\n\tpublic static final String JSON_finish = \"finish\";\n\tpublic static final String JSON_lastUpdate = \"lastUpdate\";\n\tpublic static final String JSON_coverImg = \"coverImg\";\n\tpublic static final String JSON_chapterList = \"chapterList\";\n\tpublic static final String JSON_comicName = \"comicName\";\n\tpublic static final String JSON_imageList = \"imageList\";\n\tpublic static final String JSON_chapterId = \"chapterId\";\n\tpublic static final String JSON_imageUrl = \"imageUrl\";\n\tpublic static final String JSON_total = \"total\";\n\t\n\tpublic static final String URL_MANHUA_TYPE = \"http://japi.juhe.cn/comic/category\";\n\tpublic static final String URL_MANHUA_BOOK = \"http://japi.juhe.cn/comic/book\";\n\tpublic static final String URL_MANHUA_CHAPTER = \"http://japi.juhe.cn/comic/chapter\";\n\tpublic static final String URL_MANHUA_CONTENT = \"http://japi.juhe.cn/comic/chapterContent\";\n\t\n\t\n\tpublic static final String KEY = \"key\";\n\tpublic static final String KEY_COMICNAME = \"comicName\";\n\tpublic static final String KEY_SKIP = \"skip\";\n\tpublic static final String KEY_ID = \"id\";\n\tpublic static final String KEY_ManhuaName = \"ManhuaName\";\n\tpublic static final String KEY_ManhuaType = \"ManhuaType\";\n\tpublic static final String KEY_ManhuaLastUpdate = \"ManhuaLastUpdate\";\n\tpublic static final String KEY_ManhuaIsFinish = \"ManhuaIsFinish\";\n\tpublic static final String KEY_ChapterId = \"ChapterId\";\n\tpublic static final String KEY_CoverImg = \"ManhuaCover\";\n\tpublic static final String KEY_ManhuaChapterName = \"ManhuaChapterName\";\n\tpublic static final String KEY_Name = \"name\";\n\tpublic static final String KEY_Type = \"type\";\n\t\n\t\n\tpublic static final int RESULT_SUCCESS_CODE = 0x01;\n\tpublic static final int RESULT_FAIL_CODE = 0x02;\n\tpublic static final int RESULT_OFFLINE_CODE = 0x03;\n\t\n\tpublic static final int STATUS_CODE_SUCCESS = 200;\n\tpublic static final int STATUS_CODE_NO_NETWORK = 30002;\n\tpublic static final int STATUS_CODE_NO_INIT = 30003;\n\tpublic static final int STATUS_CODE_NO_FIND_INFORMATION = 216301;\n\t\n\tpublic static final String Disk_Route_PhotoWall = \"bitmap\";\n\tpublic static final String Disk_Route_Chapter = \"bitmap2\";\n\tpublic static final String Disk_Route_Content = \"bitmap3\";\n\t\n\tpublic static final String Path_offline_ChapterContent = \"ChapterContent\";\n\tpublic static final String Path_offline_ManhuaData = \"ManhuaData\";\n\tpublic static final String Path_offline_ManhuaChapter = \"ManhuaChapter\";\n\tpublic static final String Path_offline_SearchManhuaData = \"SearchManhuaData\";\n\t\n\t\n\t\n\t\n\t\n\tpublic static String[] TITLES = new String[] {\n\t\t\"ÍƼö\" , \"ÇàÄê\" , \"ÉÙÄê\" , \"ÉÙÅ®\" , \"µ¢ÃÀ\"\n\t};\n\t\n\tpublic static String[] MYRECORD_TITLES = new String[] {\n\t\t\"ÊÕ²Ø\" , \"ÀúÊ·\"\n\t};\n\t\n\n}",
"public interface UpdateCollectListener {\n\t\n\tpublic void onUpdateCollect();\n\n}"
] | import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zykmanhua.app.R;
import com.zykmanhua.app.adapter.ManhuaCollectAdapter;
import com.zykmanhua.app.bean.GroupCollect;
import com.zykmanhua.app.bean.Manhua;
import com.zykmanhua.app.util.Config;
import com.zykmanhua.app.util.UpdateCollectListener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView; | package com.zykmanhua.app.activity;
public class MyRecordCollect extends Fragment implements OnClickListener , UpdateCollectListener {
private Context mContext = null;
private ListView mListView = null; | private GroupCollect mGroupCollect = null; | 1 |
InfinityRaider/NinjaGear | src/main/java/com/infinityraider/ninjagear/item/ItemSai.java | [
"@Mod(Reference.MOD_ID)\npublic class NinjaGear extends InfinityMod<IProxy, Config> {\n public static NinjaGear instance;\n\n public NinjaGear() {\n super();\n }\n\n @Override\n public String getModId() {\n return Reference.MOD_ID;\n }\n\n @Override\n protected void onModConstructed() {\n instance = this;\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n protected IProxy createClientProxy() {\n return new ClientProxy();\n }\n\n @Override\n @OnlyIn(Dist.DEDICATED_SERVER)\n protected IProxy createServerProxy() {\n return new ServerProxy();\n }\n\n @Override\n public Object getModBlockRegistry() {\n return BlockRegistry.getInstance();\n }\n\n @Override\n public Object getModItemRegistry() {\n return ItemRegistry.getInstance();\n }\n\n @Override\n public Object getModEntityRegistry() {\n return EntityRegistry.getInstance();\n }\n\n @Override\n public Object getModEffectRegistry() {\n return EffectRegistry.getInstance();\n }\n\n @Override\n public void registerMessages(INetworkWrapper wrapper) {\n wrapper.registerMessage(MessageInvisibility.class);\n wrapper.registerMessage(MessageUpdateGadgetRenderMaskClient.class);\n wrapper.registerMessage(MessageUpdateGadgetRenderMaskServer.class);\n }\n\n @Override\n public void initializeAPI() {\n APISelector.init();\n }\n}",
"public interface IHiddenItem {\n /**\n * Checks whether or not equipping this item will reveal a hidden entity\n * @param entity entity equipping the item\n * @param stack stack holding the item\n * @return true to reveal the player\n */\n boolean shouldRevealPlayerWhenEquipped(PlayerEntity entity, ItemStack stack);\n}",
"public class NinjaAuraHandler {\n private static final NinjaAuraHandler INSTANCE = new NinjaAuraHandler();\n\n public static NinjaAuraHandler getInstance() {\n return INSTANCE;\n }\n\n private NinjaAuraHandler() {}\n\n public void revealEntity(PlayerEntity player, int duration, boolean breakSmoke) {\n boolean smoked = player.isPotionActive(EffectRegistry.getInstance().effectNinjaSmoked);\n if (smoked) {\n if(breakSmoke) {\n player.removeActivePotionEffect(EffectRegistry.getInstance().effectNinjaSmoked);\n } else {\n return;\n }\n }\n player.addPotionEffect(new EffectInstance(EffectRegistry.getInstance().effectNinjaRevealed, duration, 0, false, true));\n }\n\n private boolean isWearingFullNinjaArmor(PlayerEntity player) {\n return this.checkEquipment(player.getItemStackFromSlot(EquipmentSlotType.HEAD))\n && this.checkEquipment(player.getItemStackFromSlot(EquipmentSlotType.CHEST))\n && this.checkEquipment(player.getItemStackFromSlot(EquipmentSlotType.LEGS))\n && this.checkEquipment(player.getItemStackFromSlot(EquipmentSlotType.FEET));\n }\n\n private boolean checkEquipment(ItemStack stack) {\n return CapabilityNinjaArmor.isNinjaArmor(stack);\n }\n\n private boolean checkHidingRequirements(PlayerEntity player) {\n boolean revealed = player.isPotionActive(EffectRegistry.getInstance().effectNinjaRevealed);\n boolean smoked = player.isPotionActive(EffectRegistry.getInstance().effectNinjaSmoked);\n if(revealed && !smoked) {\n return false;\n }\n if(!player.isSneaking()) {\n return false;\n }\n ItemStack mainHand = player.getHeldItem(Hand.MAIN_HAND);\n ItemStack offHand = player.getHeldItem(Hand.OFF_HAND);\n if(!mainHand.isEmpty()) {\n if(!(mainHand.getItem() instanceof IHiddenItem) || ((IHiddenItem) mainHand.getItem()).shouldRevealPlayerWhenEquipped(player, mainHand)) {\n return false;\n }\n }\n if(!offHand.isEmpty()) {\n if(!(offHand.getItem() instanceof IHiddenItem) || ((IHiddenItem) offHand.getItem()).shouldRevealPlayerWhenEquipped(player, offHand)) {\n return false;\n }\n }\n if (smoked) {\n return true;\n }\n int light;\n int light_block = player.getEntityWorld().getLightFor(LightType.BLOCK, player.getPosition());\n boolean day = player.getEntityWorld().isDaytime();\n if(day) {\n int light_sky = player.getEntityWorld().getLightFor(LightType.SKY, player.getPosition());\n light = Math.max(light_sky, light_block);\n } else {\n light = light_block;\n }\n return light < NinjaGear.instance.getConfig().getBrightnessLimit();\n }\n\n @SubscribeEvent\n @SuppressWarnings(\"unused\")\n public void onLivingUpdateEvent(LivingEvent.LivingUpdateEvent event) {\n LivingEntity entity = event.getEntityLiving();\n if(entity == null || !(entity instanceof PlayerEntity) || entity.getEntityWorld().isRemote()) {\n return;\n }\n PlayerEntity player = (PlayerEntity) entity;\n if(this.isWearingFullNinjaArmor(player)) {\n boolean shouldBeHidden = this.checkHidingRequirements(player);\n boolean isHidden = player.isPotionActive(EffectRegistry.getInstance().effectNinjaHidden);\n if(shouldBeHidden != isHidden) {\n if(shouldBeHidden) {\n player.addPotionEffect(new EffectInstance(EffectRegistry.getInstance().effectNinjaHidden, Integer.MAX_VALUE, 0, false, true));\n if(!entity.getEntityWorld().isRemote) {\n new MessageInvisibility(player, true).sendToAll();\n }\n } else {\n player.removePotionEffect(EffectRegistry.getInstance().effectNinjaHidden);\n this.revealEntity(player, NinjaGear.instance.getConfig().getHidingCooldown(), true);\n if(!entity.getEntityWorld().isRemote) {\n new MessageInvisibility(player, false).sendToAll();\n }\n }\n }\n } else {\n if(player.isPotionActive(EffectRegistry.getInstance().effectNinjaHidden)) {\n player.removePotionEffect(EffectRegistry.getInstance().effectNinjaHidden);\n }\n if(player.isPotionActive(EffectRegistry.getInstance().effectNinjaRevealed)) {\n player.removePotionEffect(EffectRegistry.getInstance().effectNinjaRevealed);\n }\n }\n }\n}",
"public interface Reference {\n\t\n\tString MOD_NAME = /*^${mod.name}^*/ \"NinjaGear\";\n\tString MOD_ID = /*^${mod.id}^*/ \"ninja_gear\";\n\tString AUTHOR = /*^${mod.author}^*/ \"InfinityRaider\";\n\n\tString VER_MAJOR = /*^${mod.version_major}^*/ \"2\";\n\tString VER_MINOR = /*^${mod.version_minor}^*/ \"0\";\n\tString VER_PATCH = /*^${mod.version_patch}^*/ \"1\";\n\tString MOD_VERSION = /*^${mod.version}^*/ \"2.0.1\";\n\tString VERSION = /*^${mod.version_minecraft}-${mod.version}^*/ \"1.16.5-\" + MOD_VERSION;\n\t\n\tString UPDATE_URL = /*^${mod.update_url}^*/ \"https://www.youtube.com/watch?v=dQw4w9WgXcQ\";\n\t\n}",
"public class ItemRegistry {\n public static final ItemGroup CREATIVE_TAB = new ItemGroup(Reference.MOD_ID.toLowerCase() + \".creative_tab\") {\n @Override\n public ItemStack createIcon() {\n return new ItemStack(ItemRegistry.getInstance().itemShuriken);\n }\n };\n\n private static final ItemRegistry INSTANCE = new ItemRegistry();\n\n public static ItemRegistry getInstance() {\n return INSTANCE;\n }\n\n private ItemRegistry() {\n itemNinjaArmorHead = new ItemNinjaArmor(\"ninja_gear_head\", EquipmentSlotType.HEAD);\n itemNinjaArmorChest = new ItemNinjaArmor(\"ninja_gear_chest\", EquipmentSlotType.CHEST);\n itemNinjaArmorLegs = new ItemNinjaArmor(\"ninja_gear_legs\", EquipmentSlotType.LEGS);\n itemNinjaArmorFeet = new ItemNinjaArmor(\"ninja_gear_feet\", EquipmentSlotType.FEET);\n itemKatana = new ItemKatana();\n itemSai = new ItemSai();\n itemShuriken = new ItemShuriken();\n itemSmokeBomb = new ItemSmokeBomb();\n itemRopeCoil = new ItemRopeCoil();\n itemRope = new ItemRope((IInfinityBlock) BlockRegistry.getInstance().blockRope);\n }\n\n public Item itemNinjaArmorHead;\n public Item itemNinjaArmorChest;\n public Item itemNinjaArmorLegs;\n public Item itemNinjaArmorFeet;\n public Item itemKatana;\n public Item itemSai;\n public Item itemShuriken;\n public Item itemSmokeBomb;\n public Item itemRopeCoil;\n public Item itemRope;\n}",
"public class EffectRegistry {\n private static final EffectRegistry INSTANCE = new EffectRegistry();\n\n public static EffectRegistry getInstance() {\n return INSTANCE;\n }\n\n public Effect effectNinjaHidden = new EffectNinjaHidden();\n public Effect effectNinjaRevealed = new EffectNinjaRevealed();\n public Effect effectNinjaSmoked = new EffectNinjaSmoked();\n\n private EffectRegistry() {}\n}"
] | import com.google.common.collect.ImmutableMultimap;
import com.infinityraider.infinitylib.item.ItemBase;
import com.infinityraider.ninjagear.NinjaGear;
import com.infinityraider.ninjagear.api.v1.IHiddenItem;
import com.infinityraider.ninjagear.handler.NinjaAuraHandler;
import com.infinityraider.ninjagear.reference.Reference;
import com.infinityraider.ninjagear.registry.ItemRegistry;
import com.infinityraider.ninjagear.registry.EffectRegistry;
import com.google.common.collect.Multimap;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.material.Material;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.ai.attributes.Attribute;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.Attributes;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ItemStack;
import net.minecraft.item.UseAction;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.tags.BlockTags;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List; | package com.infinityraider.ninjagear.item;
@MethodsReturnNonnullByDefault
public class ItemSai extends ItemBase implements IHiddenItem {
private final Multimap<Attribute, AttributeModifier> attributeModifiers;
private final Multimap<Attribute, AttributeModifier> attributeModifiersCrit;
private final Multimap<Attribute, AttributeModifier> attributeModifiersIneffective;
public ItemSai() {
super("sai", new Properties()
.maxDamage(1000)
.group(ItemRegistry.CREATIVE_TAB));
ImmutableMultimap.Builder<Attribute, AttributeModifier> builder = ImmutableMultimap.builder();
this.attributeModifiers = builder
.put(Attributes.ATTACK_DAMAGE, new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Sai Attack Damage Modifier",
3.0 + NinjaGear.instance.getConfig().getSaiDamage(), AttributeModifier.Operation.ADDITION))
.put(Attributes.ATTACK_SPEED, new AttributeModifier(ATTACK_SPEED_MODIFIER, "Sai Attack Speed Modifier",
1, AttributeModifier.Operation.ADDITION))
.build();
builder = ImmutableMultimap.builder();
this.attributeModifiersCrit = builder
.put(Attributes.ATTACK_DAMAGE, new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Sai Attack Damage Modifier",
3.0 + NinjaGear.instance.getConfig().getCitMultiplier()*NinjaGear.instance.getConfig().getSaiDamage(),
AttributeModifier.Operation.ADDITION))
.put(Attributes.ATTACK_SPEED, new AttributeModifier(ATTACK_SPEED_MODIFIER, "Sai Attack Speed Modifier",
1, AttributeModifier.Operation.ADDITION))
.build();
builder = ImmutableMultimap.builder();
this.attributeModifiersIneffective = builder
.put(Attributes.ATTACK_DAMAGE, new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Sai Attack Damage Modifier",
3.0, AttributeModifier.Operation.ADDITION))
.put(Attributes.ATTACK_SPEED, new AttributeModifier(ATTACK_SPEED_MODIFIER, "Sai Attack Speed Modifier",
-2, AttributeModifier.Operation.ADDITION))
.build();
}
public UseAction getUseAction(ItemStack stack) {
return UseAction.BLOCK;
}
@Override
public float getDestroySpeed(ItemStack stack, BlockState state) {
if (state.matchesBlock(Blocks.COBWEB)) {
return 15.0F;
} else {
Material material = state.getMaterial();
return material != Material.PLANTS
&& material != Material.TALL_PLANTS
&& material != Material.CORAL
&& !state.isIn(BlockTags.LEAVES)
&& material != Material.GOURD
? 1.0F : 1.5F;
}
}
@Override
public boolean hitEntity(ItemStack stack, LivingEntity target, LivingEntity attacker) {
if(attacker instanceof PlayerEntity) {
NinjaAuraHandler.getInstance().revealEntity((PlayerEntity) attacker, NinjaGear.instance.getConfig().getHidingCooldown(), true);
}
stack.damageItem(1, attacker, (entity) -> {
entity.sendBreakAnimation(EquipmentSlotType.MAINHAND);
});
ItemStack offhand = attacker.getItemStackFromSlot(EquipmentSlotType.OFFHAND);
if(offhand != null && offhand.getItem() instanceof ItemSai) {
offhand.damageItem(1, attacker, (entity) -> {
entity.sendBreakAnimation(EquipmentSlotType.MAINHAND);
});
}
return true;
}
@Override
public boolean onBlockDestroyed(ItemStack stack, World world, BlockState state, BlockPos pos, LivingEntity entity) {
if ((double)state.getBlockHardness(world, pos) != 0.0D) {
stack.damageItem(1, entity, (e) -> {
e.sendBreakAnimation(EquipmentSlotType.MAINHAND);
});
ItemStack offhand = entity.getItemStackFromSlot(EquipmentSlotType.OFFHAND);
if(offhand != null && offhand.getItem() instanceof ItemSai) {
offhand.damageItem(1, entity, (e) -> {
e.sendBreakAnimation(EquipmentSlotType.MAINHAND);
});
}
}
return true;
}
@Override
public boolean canHarvestBlock(BlockState blockIn) {
return blockIn.getBlock() == Blocks.COBWEB;
}
@Override
public int getItemEnchantability() {
return 15;
}
@Override
public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) {
return getRepairItem().test(repair);
}
@Override
public boolean onLeftClickEntity(ItemStack stack, PlayerEntity player, Entity entity) {
ItemStack offHand = player.getItemStackFromSlot(EquipmentSlotType.OFFHAND);
if(offHand != null && offHand.getItem() == this) { | if(player.isPotionActive(EffectRegistry.getInstance().effectNinjaHidden)) { | 5 |
ToroCraft/Minecoprocessors | src/main/java/net/torocraft/minecoprocessors/processor/Processor.java | [
"@Mod(modid = Minecoprocessors.MODID, version = Minecoprocessors.VERSION, name = Minecoprocessors.MODNAME)\npublic class Minecoprocessors {\n\n public static final String MODID = \"minecoprocessors\";\n public static final String VERSION = \"1.12.2-5\";\n public static final String MODNAME = \"Minecoprocessors\";\n\n @Mod.Instance(MODID)\n public static Minecoprocessors INSTANCE;\n\n public static SimpleNetworkWrapper NETWORK = NetworkRegistry.INSTANCE\n .newSimpleChannel(Minecoprocessors.MODID);\n\n @SidedProxy(clientSide = \"net.torocraft.minecoprocessors.ClientProxy\", serverSide = \"net.torocraft.minecoprocessors.CommonProxy\")\n public static CommonProxy proxy;\n\n @EventHandler\n public void preInit(FMLPreInitializationEvent e) {\n proxy.preInit(e);\n }\n\n @EventHandler\n public void init(FMLInitializationEvent e) {\n proxy.init(e);\n }\n\n}",
"public class GuiMinecoprocessor extends net.minecraft.client.gui.inventory.GuiContainer {\n\n private static final ResourceLocation TEXTURES = new ResourceLocation(Minecoprocessors.MODID, \"textures/gui/minecoprocessor.png\");\n\n private final IInventory playerInventory;\n private final TileEntityMinecoprocessor minecoprocessor;\n private final List<String> hoveredFeature = new ArrayList<>(5);\n\n private GuiButton buttonReset;\n private GuiButton buttonPause;\n private GuiButton buttonStep;\n private GuiButton buttonHelp;\n private Processor processor;\n private byte[] registers = new byte[Register.values().length];\n private byte faultCode = FaultCode.FAULT_STATE_NOMINAL;\n\n public BlockPos getPos() {\n return minecoprocessor.getPos();\n }\n\n public static GuiMinecoprocessor INSTANCE;\n\n public GuiMinecoprocessor(IInventory playerInv, TileEntityMinecoprocessor te) {\n super(new ContainerMinecoprocessor(playerInv, te));\n this.playerInventory = playerInv;\n this.minecoprocessor = te;\n INSTANCE = this;\n Minecoprocessors.NETWORK.sendToServer(new MessageEnableGuiUpdates(minecoprocessor.getPos(), true));\n }\n\n public void updateData(NBTTagCompound processorData, String name) {\n if (processor == null) {\n processor = new Processor();\n }\n processor.readFromNBT(processorData);\n minecoprocessor.setName(I18n.format(name));\n registers = processor.getRegisters();\n faultCode = processor.getFaultCode();\n }\n\n @Override\n public void onGuiClosed() {\n super.onGuiClosed();\n Minecoprocessors.NETWORK.sendToServer(new MessageEnableGuiUpdates(minecoprocessor.getPos(), false));\n INSTANCE = null;\n }\n\n /**\n * Draw the foreground layer for the GuiContainer (everything in front of the items)\n */\n @Override\n protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {\n hoveredFeature.clear();\n\n GlStateManager.pushMatrix();\n GlStateManager.scale(0.5d, 0.5d, 0.5d);\n int scale = 2;\n int y;\n\n mouseX = (mouseX - guiLeft) * scale;\n mouseY = (mouseY - guiTop) * scale;\n\n y = 50;\n drawRegister(Register.A, 130 * 2, y, mouseX, mouseY);\n drawRegister(Register.B, 139 * 2, y, mouseX, mouseY);\n drawRegister(Register.C, 148 * 2, y, mouseX, mouseY);\n drawRegister(Register.D, 157 * 2, y, mouseX, mouseY);\n\n y = 82;\n drawFlag(\"Z\", processor == null ? null : processor.isZero(), 130 * 2, y, mouseX, mouseY);\n drawFlag(\"C\", processor == null ? null : processor.isCarry() || processor.isOverflow(), 139 * 2, y, mouseX, mouseY);\n drawFlag(\"F\", processor == null ? null : processor.isFault(), 148 * 2, y, 0xff0000, mouseX, mouseY);\n drawFlag(\"S\", processor == null ? null : processor.isWait(), 157 * 2, y, 0x00ff00, mouseX, mouseY);\n\n y = 114;\n boolean mouseIsOver = drawLabeledShort(\"IP\", processor == null ? null : processor.getIp(), 128 * 2, y, mouseX, mouseY);\n if (mouseIsOver) {\n hoveredFeature.add(\"Instruction Pointer\");\n }\n\n drawRegister(Register.ADC, 142 * 2, y, mouseX, mouseY);\n drawRegister(Register.PORTS, 158 * 2, y, mouseX, mouseY);\n\n drawPortRegister(Register.PF, 176, 47, mouseX, mouseY);\n drawPortRegister(Register.PR, 216, 86, mouseX, mouseY);\n drawPortRegister(Register.PL, 137, 86, mouseX, mouseY);\n drawPortRegister(Register.PB, 176, 125, mouseX, mouseY);\n\n drawCode();\n\n GlStateManager.popMatrix();\n\n drawGuiTitle();\n drawInventoryTitle();\n\n String pauseText = \"gui.button.sleep\";\n if (processor == null || processor.isWait()) {\n pauseText = \"gui.button.wake\";\n }\n buttonPause.displayString = I18n.format(pauseText);\n buttonStep.enabled = processor != null && processor.isWait();\n }\n\n private void drawPortRegister(Register register, int x, int y, int mouseX, int mouseY) {\n byte value = registers[register.ordinal()];\n boolean mouseIsOver = centered(toHex(value), x, y, mouseX, mouseY);\n if (mouseIsOver) {\n\n int portIndex = register.ordinal() - Register.PF.ordinal();\n byte ports = registers[Register.PORTS.ordinal()];\n byte adc = registers[Register.ADC.ordinal()];\n\n switch (register) {\n case PF:\n hoveredFeature.add(\"Front Port - PF\");\n break;\n case PB:\n hoveredFeature.add(\"Back Port - PB\");\n break;\n case PL:\n hoveredFeature.add(\"Left Port - PL\");\n break;\n case PR:\n hoveredFeature.add(\"Right Port - PR\");\n break;\n }\n\n if (TileEntityMinecoprocessor.isInOutputMode(ports, portIndex)) {\n hoveredFeature.add(\"Output Port\");\n } else if (TileEntityMinecoprocessor.isInInputMode(ports, portIndex)) {\n hoveredFeature.add(\"Input Port\");\n } else if (TileEntityMinecoprocessor.isInResetMode(ports, portIndex)) {\n hoveredFeature.add(\"Reset Port\");\n }\n\n if (TileEntityMinecoprocessor.isADCMode(adc, portIndex)) {\n hoveredFeature.add(\"Analog Mode\");\n } else {\n hoveredFeature.add(\"Digital Mode\");\n }\n\n hoveredFeature.add(String.format(\"0x%s %sb %s\", toHex(value), toBinary(value), Integer.toString(value, 10)));\n }\n }\n\n private void drawCode() {\n int x = 22;\n int y = 50;\n\n String label = \"NEXT\";\n\n byte[] a = null;\n if (processor != null) {\n try {\n int ip = processor.getIp();\n List<byte[]> program = processor.getProgram();\n if (ip < program.size()) {\n a = program.get(ip);\n }\n } catch (Exception e) {\n Minecoprocessors.proxy.handleUnexpectedException(e);\n }\n }\n\n int color = 0xffffff;\n\n String value = \"\";\n\n if (a != null) {\n value = InstructionUtil.compileLine(a, processor.getLabels(), (short) -1);\n }\n\n if (value.isEmpty() && processor != null && processor.getError() != null) {\n value = processor.getError();\n color = 0xff0000;\n }\n\n fontRenderer.drawString(label, x - 4, y - 14, 0x404040);\n fontRenderer.drawString(value, x, y, color);\n }\n\n private void drawRegister(Register register, int x, int y, int mouseX, int mouseY) {\n String label = register.toString();\n byte value = registers[register.ordinal()];\n\n boolean mouseIsOver = drawLabeledValue(label, toHex(value), x, y, null, mouseX, mouseY);\n if (mouseIsOver) {\n hoveredFeature.add(label + \" Register\");\n if (Register.PORTS.equals(register)) {\n hoveredFeature.add(\"I/O port direction\");\n } else if (Register.ADC.equals(register)) {\n hoveredFeature.add(\"ADC/DAC switch\");\n } else {\n hoveredFeature.add(\"General Purpose\");\n }\n hoveredFeature.add(String.format(\"0x%s %sb %s\", toHex(value), toBinary(value), Integer.toString(value, 10)));\n }\n }\n\n public static String toBinary(Byte b) {\n if (b == null) {\n return null;\n }\n return maxLength(leftPad(Integer.toBinaryString(b), 8), 8);\n }\n\n private static String maxLength(String s, int l) {\n if (s.length() > l) {\n return s.substring(s.length() - l, s.length());\n }\n return s;\n }\n\n public static String toHex(Byte b) {\n if (b == null) {\n return null;\n }\n String s = Integer.toHexString(b);\n if (s.length() > 2) {\n return s.substring(s.length() - 2, s.length());\n }\n return leftPad(s, 2);\n }\n\n public static String leftPad(final String str, final int size) {\n if (str == null) {\n return null;\n }\n final int pads = size - str.length();\n if (pads <= 0) {\n return str;\n }\n StringBuilder buf = new StringBuilder();\n for (int i = 0; i < pads; i++) {\n buf.append(\"0\");\n }\n buf.append(str);\n return buf.toString();\n }\n\n private static String toHex(Short b) {\n if (b == null) {\n return null;\n }\n String s = Integer.toHexString(b);\n if (s.length() > 4) {\n return s.substring(s.length() - 4, s.length());\n }\n return leftPad(s, 4);\n }\n\n private void drawFlag(String label, Boolean flag, int x, int y, int mouseX, int mouseY) {\n drawFlag(label, flag, x, y, null, mouseX, mouseY);\n }\n\n private void drawFlag(String label, Boolean flag, int x, int y, Integer flashColor, int mouseX, int mouseY) {\n if (flag == null) {\n flag = false;\n }\n boolean mouseIsOver = drawLabeledValue(label, flag ? \"1\" : \"0\", x, y, flag ? flashColor : null, mouseX, mouseY);\n if (mouseIsOver) {\n switch (label) {\n case \"Z\":\n hoveredFeature.add(\"Zero Flag\");\n break;\n case \"C\":\n hoveredFeature.add(\"Carry Flag\");\n break;\n case \"F\":\n hoveredFeature.add(\"Fault Indicator\");\n hoveredFeature.add(\"STATUS 0x\" + toHex(faultCode).toUpperCase());\n break;\n case \"S\":\n hoveredFeature.add(\"Sleep Indicator\");\n break;\n }\n hoveredFeature.add(Boolean.toString(flag).toUpperCase());\n }\n }\n\n @SuppressWarnings(\"unused\")\n private void drawLabeledByte(String label, Byte b, int x, int y, int mouseX, int mouseY) {\n drawLabeledValue(label, toHex(b), x, y, null, mouseX, mouseY);\n }\n\n private boolean drawLabeledShort(String label, Short b, int x, int y, int mouseX, int mouseY) {\n return drawLabeledValue(label, toHex(b), x, y, null, mouseX, mouseY);\n }\n\n private boolean drawLabeledValue(String label, String value, int x, int y, Integer flashColor, int mouseX, int mouseY) {\n\n int wLabel = fontRenderer.getStringWidth(label) / 2;\n int wValue = 0;\n if (value != null) {\n wValue = fontRenderer.getStringWidth(value) / 2;\n }\n\n int color = 0xffffff;\n\n if (flashColor != null && (minecoprocessor.getWorld().getTotalWorldTime() / 10) % 2 == 0) {\n color = flashColor;\n }\n\n fontRenderer.drawString(label, x - wLabel, y - 14, 0x404040);\n if (value != null) {\n fontRenderer.drawString(value, x - wValue, y, color);\n }\n\n int wMax = Math.max(wLabel, wValue);\n boolean mouseIsOver = mouseX > (x - wMax) && mouseX < (x + wMax);\n mouseIsOver = mouseIsOver && mouseY > y - 14 && mouseY < y + 14;\n\n return mouseIsOver;\n }\n\n private boolean centered(String s, float x, float y, int mouseX, int mouseY) {\n int hWidth = fontRenderer.getStringWidth(s) / 2;\n int hHeight = fontRenderer.FONT_HEIGHT / 2;\n int xs = (int) x - hWidth;\n int ys = (int) y - hHeight;\n fontRenderer.drawString(s, xs, ys, 0xffffff);\n\n boolean mouseIsOver = mouseX > (x - hWidth) && mouseX < (x + hWidth);\n mouseIsOver = mouseIsOver && mouseY > y - hHeight - 2 && mouseY < y + hHeight + 2;\n return mouseIsOver;\n }\n\n private void drawInventoryTitle() {\n fontRenderer.drawString(playerInventory.getDisplayName().getUnformattedText(), 8, ySize - 96 + 2, 4210752);\n }\n\n private void drawGuiTitle() {\n String s = minecoprocessor.getDisplayName().getUnformattedText();\n fontRenderer.drawString(s, xSize / 2 - fontRenderer.getStringWidth(s) / 2, 6, 4210752);\n }\n\n @Override\n public void drawScreen(int mouseX, int mouseY, float partialTicks) {\n super.drawScreen(mouseX, mouseY, partialTicks);\n renderHoveredToolTip(mouseX, mouseY);\n renderFeatureToolTip(mouseX, mouseY);\n }\n\n private void renderFeatureToolTip(int x, int y) {\n if (hoveredFeature.size() == 0) {\n return;\n }\n drawHoveringText(hoveredFeature, x, y, fontRenderer);\n }\n\n @Override\n public void initGui() {\n super.initGui();\n drawButtons();\n }\n\n private void drawButtons() {\n int buttonId = 0;\n int x = 8 + guiLeft;\n int y = 34 + guiTop;\n int buttonWidth = 49;\n int buttonHeight = 10;\n\n buttonReset = new ScaledGuiButton(buttonId++, x, y, buttonWidth, buttonHeight, I18n.format(\"gui.button.reset\"));\n buttonPause = new ScaledGuiButton(buttonId++, x, y + 11, buttonWidth, buttonHeight, I18n.format(\"gui.button.sleep\"));\n buttonStep = new ScaledGuiButton(buttonId++, x, y + 22, buttonWidth, buttonHeight, I18n.format(\"gui.button.step\"));\n buttonHelp = new ScaledGuiButton(buttonId++, guiLeft + 133, guiTop + 66, 35, buttonHeight, I18n.format(\"gui.button.help\"));\n\n buttonList.add(buttonReset);\n buttonList.add(buttonStep);\n buttonList.add(buttonPause);\n buttonList.add(buttonHelp);\n }\n\n @Override\n protected void actionPerformed(GuiButton button) {\n if (button == buttonReset) {\n Minecoprocessors.NETWORK.sendToServer(new MessageProcessorAction(minecoprocessor.getPos(), Action.RESET));\n }\n if (button == buttonPause) {\n Minecoprocessors.NETWORK.sendToServer(new MessageProcessorAction(minecoprocessor.getPos(), Action.PAUSE));\n }\n if (button == buttonStep) {\n Minecoprocessors.NETWORK.sendToServer(new MessageProcessorAction(minecoprocessor.getPos(), Action.STEP));\n }\n if (button == buttonHelp) {\n // TODO override the book GUI so that it returns the processor GUI when closed\n this.mc.displayGuiScreen(new GuiScreenBook(mc.player, BookCreator.manual, false));\n }\n }\n\n /**\n * Draws the background layer of this container (behind the items).\n */\n @Override\n protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {\n GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);\n this.mc.getTextureManager().bindTexture(TEXTURES);\n int i = (this.width - this.xSize) / 2;\n int j = (this.height - this.ySize) / 2;\n this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize);\n int k = this.minecoprocessor.getField(1);\n int l = MathHelper.clamp((18 * k + 20 - 1) / 20, 0, 18);\n\n if (l > 0) {\n this.drawTexturedModalRect(i + 60, j + 44, 176, 29, l, 4);\n }\n\n int i1 = this.minecoprocessor.getField(0);\n\n if (i1 > 0) {\n int j1 = (int) (28.0F * (1.0F - i1 / 400.0F));\n\n if (j1 > 0) {\n this.drawTexturedModalRect(i + 97, j + 16, 176, 0, 9, j1);\n }\n\n j1 = 0;\n\n if (j1 > 0) {\n this.drawTexturedModalRect(i + 63, j + 14 + 29 - j1, 185, 29 - j1, 12, j1);\n }\n }\n }\n}",
"public class ByteUtil {\n\n public static boolean getBit(long l, int position) {\n return (l & 1 << position) != 0;\n }\n\n public static byte setBit(byte b, boolean bit, int position) {\n if (bit) {\n return (byte) (b | 1 << position);\n }\n return (byte) (b & ~(1 << position));\n }\n\n public static long setBit(long l, boolean bit, int position) {\n if (bit) {\n return l | 1 << position;\n }\n return l & ~(1 << position);\n }\n\n public static byte getByte(long l, int position) {\n return (byte) (l >> 8 * position);\n }\n\n public static short setByte(short s, byte b, int position) {\n if (position > 1) {\n throw new IndexOutOfBoundsException(\"position of \" + position);\n }\n int mask = ~(0xff << position * 8);\n int insert = (b << position * 8) & ~mask;\n return (short) (s & mask | insert);\n }\n\n public static int setByte(int i, byte b, int position) {\n if (position > 3) {\n throw new IndexOutOfBoundsException(\"byte position of \" + position);\n }\n int mask = ~(0xff << position * 8);\n int insert = (b << position * 8) & ~mask;\n return i & mask | insert;\n }\n\n public static long setByte(long l, byte b, int position) {\n if (position > 7) {\n throw new IndexOutOfBoundsException(\"position of \" + position);\n }\n long mask = ~(0xffL << position * 8);\n long insert = ((long) b << position * 8) & ~mask;\n return l & mask | insert;\n }\n\n public static short getShort(long l, int position) {\n return (short) (l >> position * 16);\n }\n\n public static long setShort(long l, short b, int position) {\n if (position > 3) {\n throw new IndexOutOfBoundsException(\"short position of \" + position);\n }\n long mask = ~(0xffffL << position * 16);\n long insert = ((long) b << position * 16) & ~mask;\n return l & mask | insert;\n }\n\n}",
"public class InstructionUtil {\n\n public static final String ERROR_DOUBLE_REFERENCE = \"only one memory reference allowed\";\n public static final String ERROR_NON_REFERENCE_OFFSET = \"offsets can only be used with labels and references\";\n public static final String ERROR_LABEL_IN_FIRST_OPERAND = \"labels can not be the first of two operands\";\n\n public static List<String> compileFile(List<byte[]> instructions, List<Label> labels) {\n List<String> file = new ArrayList<>();\n\n for (short address = 0; address < instructions.size(); address++) {\n file.add(compileLine(instructions.get(address), labels, address));\n }\n\n return file;\n }\n\n public static String compileLine(byte[] instruction, List<Label> labels, short lineAddress) {\n\n if (instruction == null) {\n return \"\";\n }\n\n StringBuilder line = new StringBuilder();\n\n for (Label label : labels) {\n if (label.address == lineAddress) {\n line.append(label.name).append(\": \");\n }\n }\n\n InstructionCode command = InstructionCode.values()[instruction[0]];\n line.append(command.toString().toLowerCase());\n\n Label label;\n\n switch (command) {\n case MOV:\n case ADD:\n case AND:\n case OR:\n case XOR:\n case CMP:\n case SHL:\n case SHR:\n case SUB:\n case ROR:\n case ROL:\n case SAL:\n case SAR:\n line.append(\" \");\n line.append(compileVariableOperand(instruction, 0, labels));\n line.append(\", \");\n line.append(compileVariableOperand(instruction, 1, labels));\n break;\n case DJNZ:\n line.append(\" \");\n line.append(lower(Register.values()[instruction[1]]));\n line.append(\", \");\n label = labels.get(instruction[2]);\n if (label != null) {\n line.append(label.name.toLowerCase());\n }\n break;\n case JMP:\n case JNZ:\n case JZ:\n case JE:\n case JNE:\n case JG:\n case JGE:\n case JL:\n case JLE:\n case JC:\n case JNC:\n case LOOP:\n case CALL:\n label = labels.get(instruction[1]);\n if (label != null) {\n line.append(\" \");\n line.append(label.name.toLowerCase());\n }\n break;\n case MUL:\n case DIV:\n case NOT:\n case POP:\n case PUSH:\n case INT:\n case INC:\n case DEC:\n line.append(\" \");\n if (ByteUtil.getBit(instruction[3], 0)) {\n line.append(Integer.toString(instruction[1], 10));\n } else {\n line.append(lower(Register.values()[instruction[1]]));\n }\n break;\n case POPA:\n case PUSHA:\n case RET:\n case NOP:\n case WFE:\n case HLT:\n case CLZ:\n case CLC:\n case SEZ:\n case SEC:\n case DUMP:\n break;\n default:\n throw new RuntimeException(\"Command enum had unexpected value\");\n }\n return line.toString();\n }\n\n static String compileMemoryReference(String operand, byte[] instruction, int operandIndex) {\n if (Processor.isMemoryReferenceOperand(instruction, operandIndex)) {\n return \"[\" + operand + \"]\";\n }\n return operand;\n }\n\n static String compileOffset(String operand, byte[] instruction, int operandIndex) {\n if (Processor.isOffsetOperand(instruction, operandIndex)) {\n\n if (instruction[4] < 0) {\n return operand + Byte.toString(instruction[4]);\n } else {\n return operand + \"+\" + Byte.toString(instruction[4]);\n }\n\n\n }\n return operand;\n }\n\n static String compileVariableOperand(byte[] instruction, int operandIndex, List<Label> labels) {\n byte value = instruction[operandIndex + 1];\n String operand = \"\";\n\n if (Processor.isLiteralOperand(instruction, operandIndex)) {\n operand = Integer.toString(value, 10);\n\n } else if (Processor.isRegisterOperand(instruction, operandIndex)) {\n operand = lower(Register.values()[value]);\n\n } else if (Processor.isLabelOperand(instruction, operandIndex)) {\n if (value < labels.size()) {\n Label label = labels.get(value);\n if (label != null) {\n operand = label.name.toLowerCase();\n }\n }\n }\n\n operand = compileOffset(operand, instruction, operandIndex);\n return compileMemoryReference(operand, instruction, operandIndex);\n }\n\n private static String lower(Enum<?> e) {\n return e.toString().toLowerCase();\n }\n\n public static List<byte[]> parseFile(List<String> lines, List<Label> labels) throws ParseException {\n List<byte[]> instructions = new ArrayList<>();\n\n for (String line : lines) {\n parseLineForLabels(line, labels, (short) instructions.size());\n }\n\n for (String line : lines) {\n byte[] instruction = parseLine(line, labels, (short) instructions.size());\n if (instruction != null) {\n instructions.add(instruction);\n }\n }\n\n return instructions;\n }\n\n public static void parseLineForLabels(String line, List<Label> labels, short lineAddress)\n throws ParseException {\n line = removeComments(line);\n if (!line.trim().isEmpty() && isLabelInstruction(line)) {\n parseLabelLine(line, labels, lineAddress);\n }\n }\n\n public static byte[] parseLine(String line, List<Label> labels, short lineAddress)\n throws ParseException {\n line = removeComments(line);\n if (line.trim().length() < 1) {\n return null;\n }\n if (isLabelInstruction(line)) {\n setLabelAddress(line, labels, lineAddress);\n }\n\n line = removeLabels(line);\n\n if (line.trim().length() < 1) {\n return null;\n }\n\n return parseCommandLine(line, labels);\n }\n\n static String removeComments(String line) {\n List<String> l = regex(\"^([^;]*);.*\", line, Pattern.CASE_INSENSITIVE);\n if (l.size() == 1) {\n return l.get(0);\n }\n return line;\n }\n\n static String removeLabels(String line) {\n List<String> l = regex(\"^\\\\s*[A-Za-z0-9-_]+:\\\\s*(.*)$\", line, Pattern.CASE_INSENSITIVE);\n if (l.size() == 1) {\n return l.get(0);\n }\n return line;\n }\n\n private static void setLabelAddress(String line, List<Label> labels, short lineAddress)\n throws ParseException {\n List<String> l = regex(\"^\\\\s*([A-Za-z0-9-_]+):.*$\", line, Pattern.CASE_INSENSITIVE);\n if (l.size() != 1) {\n throw new ParseException(line, \"incorrect label format\");\n }\n String label = l.get(0).toLowerCase();\n setLabelAddress(line, labels, label, lineAddress);\n }\n\n private static void parseLabelLine(String line, List<Label> labels, short lineAddress)\n throws ParseException {\n List<String> l = regex(\"^\\\\s*([A-Za-z0-9-_]+):.*$\", line, Pattern.CASE_INSENSITIVE);\n if (l.size() != 1) {\n throw new ParseException(line, \"incorrect label format\");\n }\n String label = l.get(0).toLowerCase();\n verifyLabelIsUnique(line, labels, label);\n labels.add(new Label(lineAddress, label));\n }\n\n private static void setLabelAddress(String line, List<Label> labels, String label, short address)\n throws ParseException {\n for (Label l : labels) {\n if (l.name.equalsIgnoreCase(label)) {\n l.address = address;\n return;\n }\n }\n throw new ParseException(line, \"label not found\");\n }\n\n private static void verifyLabelIsUnique(String line, List<Label> labels, String label)\n throws ParseException {\n for (Label l : labels) {\n if (l.name.equalsIgnoreCase(label)) {\n throw new ParseException(line, \"label already defined\");\n }\n }\n }\n\n private static boolean isLabelInstruction(String line) {\n return line.matches(\"^\\\\s*[A-Za-z0-9-_]+:.*$\");\n }\n\n private static byte[] parseCommandLine(String line, List<Label> labels)\n throws ParseException {\n InstructionCode instructionCode = parseInstructionCode(line);\n\n byte[] instruction;\n\n switch (instructionCode) {\n\n case MOV:\n case ADD:\n case AND:\n case OR:\n case XOR:\n case CMP:\n case SHL:\n case SHR:\n case SUB:\n case DJNZ:\n case ROR:\n case ROL:\n case SAL:\n case SAR:\n instruction = parseDoubleOperands(line, labels);\n break;\n\n case JMP:\n case JNZ:\n case JL:\n case JLE:\n case JG:\n case JGE:\n case JE:\n case JNE:\n case JZ:\n case JC:\n case JNC:\n case LOOP:\n case CALL:\n instruction = parseLabelOperand(line, labels);\n break;\n\n case MUL:\n case DIV:\n case NOT:\n case POP:\n case PUSH:\n case INT:\n case INC:\n case DEC:\n instruction = parseSingleOperand(line, labels);\n break;\n\n case RET:\n case NOP:\n case WFE:\n case HLT:\n case CLZ:\n case CLC:\n case SEZ:\n case SEC:\n case DUMP:\n case POPA:\n case PUSHA:\n instruction = new byte[1];\n break;\n\n default:\n throw new RuntimeException(\"instructionCode enum had unexpected value\");\n }\n\n instruction[0] = (byte) instructionCode.ordinal();\n return instruction;\n }\n\n private static byte[] parseSingleOperand(String line, List<Label> labels) throws ParseException {\n byte[] instruction = new byte[4];\n List<String> l = regex(\"^\\\\s*[A-Z]+\\\\s+([A-Z0-9]+)\\\\s*$\", line, Pattern.CASE_INSENSITIVE);\n if (l.size() != 1) {\n throw new ParseException(line, \"incorrect operand format\");\n }\n instruction = parseVariableOperand(line, instruction, l.get(0), 0, labels);\n return instruction;\n }\n\n static List<String> splitDoubleOperandString(String line) {\n return regex(\"^\\\\s*[A-Z]+\\\\s+([^,]+)\\\\s*,\\\\s*(.+?)\\\\s*$\", line, Pattern.CASE_INSENSITIVE);\n }\n\n static byte[] parseDoubleOperands(String line, List<Label> labels) throws ParseException {\n byte[] instruction = new byte[4];\n List<String> l = splitDoubleOperandString(line);\n if (l.size() != 2) {\n throw new ParseException(line, \"incorrect operand format\");\n }\n instruction = parseVariableOperand(line, instruction, l.get(0), 0, labels);\n instruction = parseVariableOperand(line, instruction, l.get(1), 1, labels);\n\n if (ByteUtil.getBit(instruction[3], 3) && ByteUtil.getBit(instruction[3], 7)) {\n throw new ParseException(line, ERROR_DOUBLE_REFERENCE);\n }\n\n return instruction;\n }\n\n static byte[] parseVariableOperand(String line, byte[] instruction, String operand,\n int operandIndex, List<Label> labels) throws ParseException {\n\n boolean isMemoryReference = isMemoryReference(operand);\n boolean hasMemoryOffset = hasMemoryOffset(operand);\n\n if (isMemoryReference) {\n instruction[3] = ByteUtil.setBit(instruction[3], true, (operandIndex * 4) + 3);\n operand = stripMemoryReferenceBrackets(operand);\n }\n\n if (hasMemoryOffset) {\n int offset = getMemoryOffset(line, operand);\n instruction = setMemoryOffset(instruction, offset, operandIndex);\n operand = stripMemoryOffset(operand);\n }\n\n if (isLiteral(operand)) {\n instruction[operandIndex + 1] = parseLiteral(line, operand);\n instruction[3] = ByteUtil.setBit(instruction[3], true, operandIndex * 4);\n\n } else if (isRegister(operand)) {\n if (!isMemoryReference && hasMemoryOffset) {\n throw new ParseException(line, ERROR_NON_REFERENCE_OFFSET);\n }\n instruction[operandIndex + 1] = (byte) parseRegister(line, operand).ordinal();\n\n } else {\n instruction[operandIndex + 1] = parseLabel(line, operand.toLowerCase(), labels);\n instruction[3] = ByteUtil.setBit(instruction[3], true, (operandIndex * 4) + 1);\n\n }\n\n return instruction;\n }\n\n static boolean hasMemoryOffset(String operand) {\n return operand.matches(\"[^+^-]+[+-]\\\\s*[0-9]{1,3}]?\");\n }\n\n /**\n * check if the operand has a memory reference offset and if so: <Ul> <li>set the offset bit for the operand</li> <li>add the fifth byte to the instruction with the offset</li> </Ul>\n */\n static byte[] setMemoryOffset(byte[] instructionIn, int offset, int operandIndex) {\n byte[] instruction = new byte[5];\n System.arraycopy(instructionIn, 0, instruction, 0, instructionIn.length);\n instruction[3] = ByteUtil.setBit(instruction[3], true, (operandIndex * 4) + 2);\n instruction[4] = (byte) offset;\n return instruction;\n }\n\n /**\n * Only call this on valid memory offset instructions\n */\n static int getMemoryOffset(String line, String operand) throws ParseException {\n String sOffset = operand.replaceAll(\"[^+^-]*([+-])\\\\s*([0-9]{1,2})]?\", \"$1$2\");\n try {\n return Integer.parseInt(sOffset);\n } catch (NumberFormatException e) {\n throw new ParseException(line, \"Invalid memory offset\", e);\n }\n }\n\n /**\n * Only call this on valid memory offset instructions\n */\n static String stripMemoryOffset(String operand) {\n return operand.replaceAll(\"([^+-^\\\\s]+)\\\\s*[+-]\\\\s*[0-9]{1,3}(]?)\", \"$1$2\");\n }\n\n static boolean isMemoryReference(String operand) {\n return operand.matches(\"\\\\[[^]]+]\");\n }\n\n static String stripMemoryReferenceBrackets(String operand) {\n return operand.replaceAll(\"^\\\\[\", \"\").replaceAll(\"]$\", \"\");\n }\n\n private static byte[] parseLabelOperand(String line, List<Label> labels)\n throws ParseException {\n byte[] instruction = new byte[2];\n List<String> l = regex(\"^\\\\s*[A-Z]+\\\\s+([A-Z_-]+)\\\\s*$\", line, Pattern.CASE_INSENSITIVE);\n if (l.size() != 1) {\n throw new ParseException(line, \"incorrect label format\");\n }\n instruction[1] = parseLabel(line, l.get(0).toLowerCase(), labels);\n return instruction;\n }\n\n private static byte parseLabel(String line, String label, List<Label> labels)\n throws ParseException {\n try {\n for (int i = 0; i < labels.size(); i++) {\n if (labels.get(i).name.equalsIgnoreCase(label)) {\n return (byte) i;\n }\n }\n } catch (Exception e) {\n Minecoprocessors.proxy.handleUnexpectedException(e);\n throw new ParseException(line, \"[\" + label + \"] is not a valid label\", e);\n }\n throw new ParseException(line, \"[\" + label + \"] has not been defined\");\n }\n\n private static Register parseRegister(String line, String s) throws ParseException {\n s = stripMemoryOffset(s).trim().toUpperCase();\n try {\n return Register.valueOf(s);\n } catch (IllegalArgumentException e) {\n throw new ParseException(line, \"[\" + s + \"] is not a valid register\", e);\n }\n }\n\n static boolean isRegister(String operand) {\n if (operand == null) {\n return false;\n }\n operand = stripMemoryOffset(operand);\n try {\n Register.valueOf(operand.toUpperCase());\n return true;\n } catch (@SuppressWarnings(\"unused\") IllegalArgumentException ignore) {\n return false;\n }\n }\n\n static boolean isLiteral(String s) {\n if (s == null) {\n return false;\n }\n\n s = s.trim();\n\n if (s.matches(\"^[0-9-]+$\")) {\n return true;\n }\n\n if (s.matches(\"^0o[0-7]+$\")) {\n return true;\n }\n\n if (s.matches(\"^0x[0-9A-Fa-f]+$\")) {\n return true;\n }\n\n if (s.matches(\"^[0-9-]+d$\")) {\n return true;\n }\n\n return s.matches(\"^[0-1]+b$\");\n }\n\n static byte parseLiteral(String line, String s) throws ParseException {\n int i = parseLiteralToInt(line, s);\n\n if (i < 0) {\n i += 256;\n }\n\n if (i > 255 || i < 0) {\n throw new ParseException(line, \"operand too large [\" + s + \"]\");\n }\n\n return (byte) i;\n }\n\n private static int parseInt(String s, int radix, String line) throws ParseException {\n try {\n return Integer.parseInt(s, radix);\n } catch (NumberFormatException e) {\n throw new ParseException(line, \"[\" + s + \"] is not a valid operand literal\", e);\n }\n }\n\n private static int parseLiteralToInt(String line, String s) throws ParseException {\n s = s.trim();\n List<String> l;\n\n l = regex(\"^([0-9-]+)d?$\", s, Pattern.CASE_INSENSITIVE);\n if (l.size() == 1) {\n return parseInt(l.get(0), 10, line);\n }\n\n l = regex(\"^0o([0-7]+)$\", s, Pattern.CASE_INSENSITIVE);\n if (l.size() == 1) {\n return parseInt(l.get(0), 8, line);\n }\n\n l = regex(\"^0x([0-9A-Fa-f]+)$\", s, Pattern.CASE_INSENSITIVE);\n if (l.size() == 1) {\n return parseInt(l.get(0), 16, line);\n }\n\n l = regex(\"^([0-1]+)b$\", s, Pattern.CASE_INSENSITIVE);\n if (l.size() == 1) {\n return parseInt(l.get(0), 2, line);\n }\n\n throw new ParseException(line, \"invalid operand literal type [\" + s + \"]\");\n }\n\n public static List<String> regex(final String pattern, final String screen, int flags) {\n Pattern p = Pattern.compile(pattern, flags);\n Matcher m = p.matcher(screen);\n List<String> l = new ArrayList<>();\n if (m.find() && m.groupCount() > 0) {\n for (int i = 1; i <= m.groupCount(); i++) {\n String s = m.group(i);\n if (s != null) {\n l.add(s.replaceAll(\"\\\\s+\", \" \").trim());\n }\n }\n return l;\n }\n return l;\n }\n\n private static InstructionCode parseInstructionCode(String line) throws ParseException {\n line = line.toUpperCase().trim().split(\"\\\\s+\")[0];\n try {\n return InstructionCode.valueOf(line);\n } catch (IllegalArgumentException e) {\n throw new ParseException(line, \"invalid command\", e);\n }\n }\n\n}",
"public class Label {\n\n private static final String NBT_ADDRESS = \"address\";\n private static final String NBT_NAME = \"name\";\n\n public short address;\n public String name;\n\n public Label(short address, String name) {\n this.address = address;\n this.name = name;\n }\n\n public NBTTagCompound toNbt() {\n NBTTagCompound c = new NBTTagCompound();\n c.setShort(NBT_ADDRESS, address);\n c.setString(NBT_NAME, name);\n return c;\n }\n\n public static Label fromNbt(NBTTagCompound c) {\n short address = c.getShort(NBT_ADDRESS);\n String name = c.getString(NBT_NAME);\n return new Label(address, name);\n }\n\n @Override\n public String toString() {\n return name + \"[\" + address + \"]\";\n }\n}",
"public class ParseException extends Exception {\n\n private static final long serialVersionUID = 1493829582935568613L;\n\n public String line;\n public String message;\n public int lineNumber;\n public int pageNumber;\n\n public ParseException(String line, String message) {\n super(genMessage(line, message));\n this.line = line;\n this.message = message;\n }\n\n public ParseException(String line, String message, Throwable cause) {\n super(genMessage(line, message), cause);\n this.line = line;\n this.message = message;\n }\n\n private static String genMessage(String line, String message) {\n return line;\n }\n\n}"
] | import java.util.ArrayList;
import java.util.List;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagByteArray;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.torocraft.minecoprocessors.Minecoprocessors;
import net.torocraft.minecoprocessors.gui.GuiMinecoprocessor;
import net.torocraft.minecoprocessors.util.ByteUtil;
import net.torocraft.minecoprocessors.util.InstructionUtil;
import net.torocraft.minecoprocessors.util.Label;
import net.torocraft.minecoprocessors.util.ParseException; |
@Override
public void load(List<String> file) {
try {
flush();
if (file != null) {
program = InstructionUtil.parseFile(file, labels);
} else {
program = new ArrayList<>();
labels = new ArrayList<>();
}
} catch (ParseException e) {
error = e.getMessage();
faultCode = FaultCode.FAULT_UNKNOWN_OPCODE;
fault = true;
}
}
long packFlags() {
long flags = 0;
flags = ByteUtil.setShort(flags, ip, 3);
flags = ByteUtil.setByte(flags, sp, 5);
// byte 4 not currently used
flags = ByteUtil.setBit(flags, fault, 0);
flags = ByteUtil.setBit(flags, zero, 1);
flags = ByteUtil.setBit(flags, overflow, 2);
flags = ByteUtil.setBit(flags, carry, 3);
flags = ByteUtil.setBit(flags, wait, 4);
return flags;
}
void unPackFlags(long flags) {
ip = ByteUtil.getShort(flags, 3);
sp = ByteUtil.getByte(flags, 5);
// byte 4 not currently used
fault = ByteUtil.getBit(flags, 0);
zero = ByteUtil.getBit(flags, 1);
overflow = ByteUtil.getBit(flags, 2);
carry = ByteUtil.getBit(flags, 3);
wait = ByteUtil.getBit(flags, 4);
}
private static byte[] addRegistersIfMissing(byte[] registersIn) {
if (registersIn.length >= Register.values().length) {
return registersIn;
}
byte[] registersNew = new byte[Register.values().length];
System.arraycopy(registersIn, 0, registersNew, 0, registersIn.length);
return registersNew;
}
@Override
public void readFromNBT(NBTTagCompound c) {
stack = c.getByteArray(NBT_STACK);
registers = addRegistersIfMissing(c.getByteArray(NBT_REGISTERS));
faultCode = c.getByte(NBT_FAULTCODE);
unPackFlags(c.getLong(NBT_FLAGS));
error = c.getString(NBT_ERROR);
if (error != null && error.isEmpty()) {
error = null;
}
program = new ArrayList<>();
NBTTagList programTag = (NBTTagList) c.getTag(NBT_PROGRAM);
if (programTag != null) {
for (NBTBase tag : programTag) {
program.add(((NBTTagByteArray) tag).getByteArray());
}
}
labels = new ArrayList<>();
NBTTagList labelTag = (NBTTagList) c.getTag(NBT_LABELS);
if (labelTag != null) {
for (NBTBase tag : labelTag) {
labels.add(Label.fromNbt((NBTTagCompound) tag));
}
}
}
@Override
public NBTTagCompound writeToNBT() {
NBTTagCompound c = new NBTTagCompound();
c.setByteArray(NBT_STACK, stack);
c.setByteArray(NBT_REGISTERS, registers);
c.setByte(NBT_FAULTCODE, faultCode);
c.setLong(NBT_FLAGS, packFlags());
if (error != null) {
c.setString(NBT_ERROR, error);
}
NBTTagList programTag = new NBTTagList();
for (byte[] b : program) {
programTag.appendTag(new NBTTagByteArray(b));
}
c.setTag(NBT_PROGRAM, programTag);
NBTTagList labelTag = new NBTTagList();
for (Label label : labels) {
labelTag.appendTag(label.toNbt());
}
c.setTag(NBT_LABELS, labelTag);
return c;
}
/**
* returns true if GUI should be updated after this tick
*/
@Override
public boolean tick() {
if (fault || (wait && !step)) {
return false;
}
step = false;
try {
process();
// TODO handle parse exception (actually make a new exception type to use in a running processor)
} catch (Exception e) { | Minecoprocessors.proxy.handleUnexpectedException(e); | 0 |
gustav9797/PowerfulPerms | PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/PowerfulPermissionPlayer.java | [
"public abstract class PermissionManagerBase {\n\n protected HashMap<UUID, PermissionPlayer> players = new HashMap<>();\n protected ReentrantLock playersLock = new ReentrantLock();\n\n protected ConcurrentHashMap<UUID, CachedPlayer> cachedPlayers = new ConcurrentHashMap<>();\n\n protected HashMap<Integer, Group> groups = new HashMap<>();\n protected ReentrantLock groupsLock = new ReentrantLock();\n\n private final Database db;\n protected PowerfulPermsPlugin plugin;\n protected int checkTimedTaskId = -1;\n\n protected LinkedHashMap<String, List<CachedGroup>> defaultGroups;\n\n protected EventHandler eventHandler;\n\n protected RedisConnection redis;\n\n public static boolean redisEnabled;\n public static String redis_ip;\n public static int redis_port;\n public static String redis_password;\n\n public static String serverName;\n public static String serverId;\n public static String consolePrefix = \"[PowerfulPerms] \";\n public static String pluginPrefixShort = ChatColor.BLUE + \"PP\" + ChatColor.WHITE + \"> \";\n\n public PermissionManagerBase(Database database, PowerfulPermsPlugin plugin, String serverName) {\n this.db = database;\n this.plugin = plugin;\n\n PermissionManagerBase.serverName = serverName;\n serverId = serverName + (new Random()).nextInt(5000) + (new Date()).getTime();\n\n eventHandler = new PowerfulEventHandler();\n\n final PowerfulPermsPlugin tempPlugin = plugin;\n\n db.applyPatches();\n\n if (!db.tableExists(Database.tblGroupParents))\n db.createTable(Database.tblGroupParents);\n\n if (!db.tableExists(Database.tblGroupPermissions))\n db.createTable(Database.tblGroupPermissions);\n\n if (!db.tableExists(Database.tblGroupPrefixes))\n db.createTable(Database.tblGroupPrefixes);\n\n if (!db.tableExists(Database.tblGroupSuffixes))\n db.createTable(Database.tblGroupSuffixes);\n\n if (!db.tableExists(Database.tblPlayerGroups))\n db.createTable(Database.tblPlayerGroups);\n\n if (!db.tableExists(Database.tblPlayerPermissions))\n db.createTable(Database.tblPlayerPermissions);\n\n if (!db.tableExists(Database.tblGroups)) {\n db.createTable(Database.tblGroups);\n\n try {\n Response response = createGroupBase(\"Guest\", \"default\", 100);\n if (response.succeeded())\n tempPlugin.getLogger().info(\"Created group Guest\");\n else\n tempPlugin.getLogger().info(\"Could not create group Guest\");\n response = setGroupPrefixBase(getGroup(\"Guest\").getId(), \"[Guest] \", \"\");\n if (response.succeeded())\n tempPlugin.getLogger().info(\"Set group Guest prefix to \\\"[Guest] \\\"\");\n else\n tempPlugin.getLogger().info(\"Could not set group Guest prefix to \\\"[Guest] \\\"\");\n response = setGroupSuffixBase(getGroup(\"Guest\").getId(), \": \", \"\");\n if (response.succeeded())\n tempPlugin.getLogger().info(\"Set group Guest suffix to \\\": \\\"\");\n else\n tempPlugin.getLogger().info(\"Coult not set group Guest suffix to \\\": \\\"\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n if (!db.tableExists(Database.tblPlayers)) {\n db.createTable(Database.tblPlayers);\n\n try {\n Response response = createPlayerBase(\"[default]\", DefaultPermissionPlayer.getUUID());\n if (response.succeeded())\n tempPlugin.getLogger().info(\"Inserted player [default]\");\n else\n tempPlugin.getLogger().info(\"Could not insert player [default]\");\n\n Group guest = getGroup(\"Guest\");\n if (guest != null) {\n response = addPlayerGroupBase(DefaultPermissionPlayer.getUUID(), guest.getId(), \"\", false, null);\n if (response.succeeded())\n tempPlugin.getLogger().info(\"Added group Guest to player [default]\");\n else\n tempPlugin.getLogger().info(\"Could not add group Guest to player [default]\");\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n if (redisEnabled)\n this.redis = new RedisConnection(this, plugin, redis_ip, redis_port, redis_password);\n\n checkTimedTaskId = this.getScheduler().runRepeating(() -> {\n List<Group> tempTempGroups;\n groupsLock.lock();\n try {\n tempTempGroups = new ArrayList<>(groups.values());\n } finally {\n groupsLock.unlock();\n }\n final List<Group> tempGroups = tempTempGroups;\n\n HashMap<UUID, PermissionPlayer> tempTempPlayers;\n playersLock.lock();\n try {\n tempTempPlayers = new HashMap<>(players);\n } finally {\n playersLock.unlock();\n }\n final HashMap<UUID, PermissionPlayer> tempPlayers = tempTempPlayers;\n\n getScheduler().runAsync(() -> {\n for (Entry<UUID, PermissionPlayer> e : tempPlayers.entrySet())\n checkPlayerTimedGroupsAndPermissions(e.getKey(), e.getValue());\n for (Group group : tempGroups)\n checkGroupTimedPermissions(group);\n }, false);\n\n }, 60);\n }\n\n protected void checkPlayerTimedGroupsAndPermissions(final UUID uuid, PermissionPlayer player) {\n LinkedHashMap<String, List<CachedGroup>> playerGroups = player.getCachedGroups();\n for (Entry<String, List<CachedGroup>> e : playerGroups.entrySet()) {\n for (final CachedGroup cachedGroup : e.getValue()) {\n if (cachedGroup.getExpireTaskId() == -1 && cachedGroup.willExpire()) {\n final String server = e.getKey();\n Runnable removePlayerGroupRunnable = () -> {\n try {\n debug(\"CachedGroup \" + cachedGroup.getId() + \" in player \" + uuid.toString() + \" expired.\");\n Response response = removePlayerGroupBase(uuid, cachedGroup.getGroupId(), server, cachedGroup.isNegated(), cachedGroup.getExpirationDate());\n if (response.succeeded()) {\n plugin.getLogger().info(\"Group \" + cachedGroup.getGroupId() + \" in player \" + uuid.toString() + \" expired and was removed.\");\n getEventHandler().fireEvent(new PlayerGroupExpiredEvent(uuid, cachedGroup));\n } else\n debug(\"Could not remove expired player group. \" + response.getResponse());\n } catch (Exception e1) {\n e1.printStackTrace();\n }\n };\n\n if (cachedGroup.hasExpired())\n removePlayerGroupRunnable.run();\n else {\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.MINUTE, 5);\n if (cachedGroup.getExpirationDate().before(calendar.getTime())) {\n // CachedGroup will expire within 5 minutes\n int taskId = getScheduler().runDelayed(removePlayerGroupRunnable, cachedGroup.getExpirationDate());\n cachedGroup.setExpireTaskId(taskId);\n }\n }\n }\n }\n }\n\n List<Permission> permissions = player.getPermissions();\n for (final Permission ap : permissions) {\n final PowerfulPermission p = (PowerfulPermission) ap;\n if (p.getExpireTaskId() == -1 && p.willExpire()) {\n Runnable removePlayerPermissionRunnable = () -> {\n try {\n debug(\"Permission \" + p.getId() + \" in player \" + uuid.toString() + \" expired.\");\n Response response = removePlayerPermissionBase(uuid, p.getPermissionString(), p.getWorld(), p.getServer(), p.getExpirationDate());\n if (response.succeeded()) {\n plugin.getLogger().info(\"Permission \" + p.getId() + \" in player \" + uuid.toString() + \" expired and was removed.\");\n getEventHandler().fireEvent(new PlayerPermissionExpiredEvent(uuid, p));\n } else\n debug(\"Could not remove expired player permission. \" + response.getResponse());\n } catch (Exception e) {\n e.printStackTrace();\n }\n };\n\n if (p.hasExpired())\n removePlayerPermissionRunnable.run();\n else {\n\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.MINUTE, 5);\n if (p.getExpirationDate().before(calendar.getTime())) {\n // CachedGroup will expire within 5 minutes\n int taskId = getScheduler().runDelayed(removePlayerPermissionRunnable, p.getExpirationDate());\n p.setExpireTaskId(taskId);\n }\n }\n }\n }\n }\n\n protected void checkGroupTimedPermissions(final Group group) {\n List<Permission> permissions = group.getOwnPermissions();\n for (final Permission ap : permissions) {\n final PowerfulPermission p = (PowerfulPermission) ap;\n if (p.getExpireTaskId() == -1 && p.willExpire()) {\n Runnable removeGroupPermissionRunnable = () -> {\n try {\n debug(\"Permission \" + p.getId() + \" in group \" + group.getId() + \" expired.\");\n Response response = removeGroupPermissionBase(group.getId(), p.getPermissionString(), p.getWorld(), p.getServer(), p.getExpirationDate());\n if (response.succeeded()) {\n plugin.getLogger().info(\"Permission \" + p.getId() + \" in group \" + group.getId() + \" expired and was removed.\");\n getEventHandler().fireEvent(new GroupPermissionExpiredEvent(group, p));\n } else\n debug(\"Could not remove expired group permission. \" + response.getResponse());\n } catch (Exception e) {\n e.printStackTrace();\n }\n };\n\n if (p.hasExpired())\n removeGroupPermissionRunnable.run();\n else {\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.MINUTE, 5);\n if (p.getExpirationDate().before(calendar.getTime())) {\n // CachedGroup will expire within 5 minutes\n int taskId = getScheduler().runDelayed(removeGroupPermissionRunnable, p.getExpirationDate());\n p.setExpireTaskId(taskId);\n }\n }\n }\n }\n }\n\n protected void debug(String msg) {\n plugin.debug(msg);\n }\n\n protected LinkedHashMap<String, List<CachedGroup>> deepCopyDefaultGroups() {\n if (defaultGroups != null) {\n LinkedHashMap<String, List<CachedGroup>> output = new LinkedHashMap<>();\n LinkedHashMap<String, List<CachedGroup>> input = new LinkedHashMap<>(defaultGroups);\n for (Entry<String, List<CachedGroup>> next : input.entrySet()) {\n output.put(next.getKey(), new ArrayList<>(next.getValue()));\n }\n return output;\n }\n return null;\n }\n\n public Jedis getRedisConnection() {\n return redis.getConnection();\n }\n\n public EventHandler getEventHandler() {\n return eventHandler;\n }\n\n public Database getDatabase() {\n return db;\n }\n\n public void notifyReloadGroups() {\n if (redisEnabled && redis != null) {\n plugin.runTaskAsynchronously(() -> {\n Jedis jedis = redis.getConnection();\n if (jedis != null) {\n jedis.publish(\"PowerfulPerms\", \"[groups]\" + \" \" + serverId);\n jedis.close();\n }\n });\n }\n }\n\n public void notifyReloadPlayers() {\n if (redisEnabled && redis != null) {\n plugin.runTaskAsynchronously(() -> {\n Jedis jedis = redis.getConnection();\n if (jedis != null) {\n jedis.publish(\"PowerfulPerms\", \"[players]\" + \" \" + serverId);\n jedis.close();\n }\n });\n }\n }\n\n public void notifyReloadPlayer(final UUID uuid) {\n if (uuid.equals(DefaultPermissionPlayer.getUUID())) {\n notifyReloadPlayers();\n } else if (redisEnabled && redis != null) {\n plugin.runTaskAsynchronously(() -> {\n Jedis jedis = redis.getConnection();\n if (jedis != null) {\n jedis.publish(\"PowerfulPerms\", uuid + \" \" + serverId);\n jedis.close();\n }\n });\n }\n }\n\n public void reloadPlayers() {\n playersLock.lock();\n try {\n ArrayList<UUID> uuids = new ArrayList<>(players.keySet());\n for (UUID uuid : uuids) {\n if (!plugin.isPlayerOnline(uuid)) {\n players.remove(uuid);\n }\n debug(\"Reloading player \" + uuid.toString());\n loadPlayer(uuid, null, false, false);\n }\n } finally {\n playersLock.unlock();\n }\n }\n\n // TODO: add reloadplayer(uuid, samethread) to API, remove this\n public void reloadPlayer(UUID uuid) {\n reloadPlayer(uuid, false);\n }\n\n public void reloadPlayer(String name) {\n if (plugin.isPlayerOnline(name)) {\n UUID uuid = plugin.getPlayerUUID(name);\n if (uuid != null) {\n this.loadPlayer(uuid, name, false, false);\n }\n }\n }\n\n public void reloadPlayer(UUID uuid, boolean sameThread) {\n if (plugin.isPlayerOnline(uuid)) {\n String name = plugin.getPlayerName(uuid);\n if (name != null) {\n this.loadPlayer(uuid, name, false, sameThread);\n plugin.debug(\"Reloaded player \\\"\" + uuid + \"\\\".\");\n }\n } else if (uuid.equals(DefaultPermissionPlayer.getUUID())) {\n reloadDefaultPlayers(sameThread);\n plugin.debug(\"Changes to default player found, players reloaded\");\n }\n }\n\n public void reloadDefaultPlayers(final boolean samethread) {\n LinkedHashMap<String, List<CachedGroup>> result = loadPlayerGroups(DefaultPermissionPlayer.getUUID());\n try {\n if (result != null) {\n defaultGroups = result;\n reloadPlayers();\n debug(\"DEFAULT PLAYER LOADED: \" + (defaultGroups != null));\n } else\n plugin.getLogger().severe(consolePrefix + \"Can not get data from user [default].\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Returns the PermissionsPlayer-object for the specified player, used for getting permissions information about the player. Player has to be online.\n */\n public PermissionPlayer getPermissionPlayer(UUID uuid) {\n playersLock.lock();\n try {\n return players.get(uuid);\n } finally {\n playersLock.unlock();\n }\n }\n\n public PermissionPlayer getPermissionPlayer(String name) {\n UUID uuid = plugin.getPlayerUUID(name);\n return getPermissionPlayer(uuid);\n }\n\n protected void putPermissionPlayer(UUID uuid, PermissionPlayer permissionPlayer) {\n playersLock.lock();\n try {\n players.put(uuid, permissionPlayer);\n } finally {\n playersLock.unlock();\n }\n }\n\n protected void removePermissionPlayer(UUID uuid) {\n playersLock.lock();\n try {\n players.remove(uuid);\n } finally {\n playersLock.unlock();\n }\n }\n\n protected boolean containsPermissionPlayer(UUID uuid) {\n playersLock.lock();\n try {\n return players.containsKey(uuid);\n } finally {\n playersLock.unlock();\n }\n }\n\n public void loadPlayer(final UUID uuid, final String name, final boolean storeCache, final boolean sameThread) {\n debug(\"loadPlayer begin\");\n db.scheduler.runAsync(() -> {\n DBResult result = db.getPlayer(uuid);\n if (result.booleanValue()) {\n final DBDocument row = result.next();\n if (row != null) {\n // The player exists in database.\n\n String playerName_loaded = row.getString(\"name\");\n debug(\"playername_loaded \" + playerName_loaded);\n\n if (name != null) {\n debug(\"playerName \" + name);\n\n // Check if name mismatch, update player name\n if (!playerName_loaded.equals(name)) {\n debug(\"PLAYER NAME MISMATCH.\");\n boolean success = db.setPlayerName(uuid, name);\n if (!success)\n debug(\"COULD NOT UPDATE PLAYER NAME OF PLAYER \" + uuid.toString());\n else\n debug(\"PLAYER NAME UPDATED. NAMECHANGE\");\n loadPlayerFinished(uuid, row, storeCache, sameThread);\n } else\n loadPlayerFinished(uuid, row, storeCache, sameThread);\n } else\n loadPlayerFinished(uuid, row, storeCache, sameThread);\n } else {\n // Could not find player with UUID. Create new player.\n boolean success = db.insertPlayer(uuid, name, \"\", \"\");\n if (!success)\n debug(\"COULD NOT CREATE PLAYER \" + uuid.toString() + \" - \" + name);\n else\n debug(\"NEW PLAYER CREATED\");\n loadPlayerFinished(uuid, null, storeCache, sameThread);\n }\n }\n }, sameThread);\n }\n\n protected void loadPlayerFinished(final UUID uuid, final DBDocument row, final boolean storeCache, final boolean sameThread) {\n db.scheduler.runAsync(() -> {\n debug(\"loadPlayerFinished begin. storeCache: \" + storeCache + \" sameThread: \" + sameThread);\n final String prefix_loaded = (row != null ? row.getString(\"prefix\") : \"\");\n final String suffix_loaded = (row != null ? row.getString(\"suffix\") : \"\");\n\n try {\n LinkedHashMap<String, List<CachedGroup>> tempGroups = loadPlayerGroups(uuid);\n List<Permission> perms = loadPlayerOwnPermissions(uuid);\n if (perms == null)\n perms = new ArrayList<>();\n\n if (storeCache) {\n debug(\"Inserted into cachedPlayers allowing playerjoin to finish\");\n cachedPlayers.put(uuid, new CachedPlayer(tempGroups, prefix_loaded, suffix_loaded, perms));\n } else {\n // Player should be reloaded if \"login\" is false. Reload already loaded player.\n\n PermissionPlayerBase toUpdate = (PermissionPlayerBase) getPermissionPlayer(uuid);\n if (plugin.isPlayerOnline(uuid) && toUpdate != null) {\n debug(\"Player instance \" + toUpdate.toString());\n PermissionPlayerBase base;\n debug(\"loadPlayerFinished reload group count:\" + tempGroups.size());\n if (tempGroups.isEmpty()) {\n // Player has no groups, put default data\n base = new PermissionPlayerBase(deepCopyDefaultGroups(), perms, prefix_loaded, suffix_loaded, plugin, true);\n } else\n base = new PermissionPlayerBase(tempGroups, perms, prefix_loaded, suffix_loaded, plugin, false);\n toUpdate.update(base);\n checkPlayerTimedGroupsAndPermissions(uuid, toUpdate);\n\n cachedPlayers.remove(uuid);\n eventHandler.fireEvent(new PlayerLoadedEvent(uuid, plugin.getPlayerName(uuid)));\n }\n }\n debug(\"loadPlayerFinished runnable end\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, sameThread);\n }\n\n protected PermissionPlayerBase loadCachedPlayer(UUID uuid) {\n debug(\"continueLoadPlayer \" + uuid);\n CachedPlayer cachedPlayer = cachedPlayers.get(uuid);\n if (cachedPlayer == null) {\n plugin.getLogger().severe(consolePrefix + \"Could not continue load player. Cached player is null.\");\n return null;\n }\n\n PermissionPlayerBase base;\n if (cachedPlayer.getGroups().isEmpty()) {\n // Player has no groups, put default data\n base = new PermissionPlayerBase(deepCopyDefaultGroups(), cachedPlayer.getPermissions(), cachedPlayer.getPrefix(), cachedPlayer.getSuffix(), plugin, true);\n } else\n base = new PermissionPlayerBase(cachedPlayer.getGroups(), cachedPlayer.getPermissions(), cachedPlayer.getPrefix(), cachedPlayer.getSuffix(), plugin, false);\n cachedPlayers.remove(uuid);\n return base;\n }\n\n public void onDisable() {\n if (checkTimedTaskId != -1)\n this.getScheduler().stopRepeating(checkTimedTaskId);\n if (redis != null)\n redis.destroy();\n groupsLock.lock();\n try {\n if (groups != null)\n groups.clear();\n } finally {\n groupsLock.unlock();\n }\n playersLock.lock();\n try {\n if (players != null)\n players.clear();\n } finally {\n playersLock.unlock();\n }\n if (cachedPlayers != null)\n cachedPlayers.clear();\n }\n\n public void reloadGroups() {\n loadGroups();\n }\n\n /**\n * Loads groups from MySQL, removes old group data. Will reload all players too.\n */\n public void loadGroups() {\n loadGroups(false);\n }\n\n public void loadGroups(boolean sameThread) {\n loadGroups(sameThread, sameThread);\n }\n\n /**\n * Loads groups from MySQL, removes old group data. Will reload all players too. beginSameThread: Set this to true if you want it to fetch group data on the same thread you call from. Set it to\n * false and it will run asynchronously. endSameThread: Set this to true if you want to finish and insert groups on the same thread. Note: This -MUST- be Bukkit main thread you execute on. Set to\n * false if you want to run it synchronously but scheduled.\n */\n protected void loadGroups(final boolean beginSameThread, final boolean endSameThread) {\n debug(\"loadGroups begin\");\n\n db.scheduler.runAsync(() -> {\n DBResult result = db.getGroups();\n if (result.booleanValue()) {\n final DBResult groupResult = result;\n\n try {\n HashMap<Integer, List<Integer>> parents = loadGroupParents();\n debug(\"loadgroups parents size: \" + parents.size());\n\n final HashMap<Integer, HashMap<String, String>> prefixes = loadGroupPrefixes();\n final HashMap<Integer, HashMap<String, String>> suffixes = loadGroupSuffixes();\n final HashMap<Integer, List<PowerfulPermission>> permissions = loadGroupPermissions();\n\n groupsLock.lock();\n try {\n groups.clear();\n while (groupResult.hasNext()) {\n DBDocument row = groupResult.next();\n final int groupId = row.getInt(\"id\");\n final String name = row.getString(\"name\");\n String ladder1 = row.getString(\"ladder\");\n final String ladder = (ladder1 == null || ladder1.isEmpty() ? \"default\" : ladder1);\n final int rank = row.getInt(\"rank\");\n\n PowerfulGroup group = new PowerfulGroup(groupId, name, permissions.get(groupId), prefixes.get(groupId), suffixes.get(groupId), ladder, rank, plugin);\n group.setParents(parents.get(groupId));\n groups.put(groupId, group);\n\n checkGroupTimedPermissions(group);\n }\n debug(\"loadGroups end\");\n } finally {\n groupsLock.unlock();\n }\n // Reload players too.\n reloadDefaultPlayers(beginSameThread);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }, beginSameThread);\n\n }\n\n public Group getGroup(String groupName) {\n groupsLock.lock();\n try {\n for (Map.Entry<Integer, Group> e : groups.entrySet())\n if (e.getValue().getName().equalsIgnoreCase(groupName))\n return e.getValue();\n } finally {\n groupsLock.unlock();\n }\n return null;\n }\n\n public Group getGroup(int id) {\n groupsLock.lock();\n try {\n return groups.get(id);\n } finally {\n groupsLock.unlock();\n }\n }\n\n public Map<Integer, Group> getGroups() {\n groupsLock.lock();\n try {\n return new HashMap<>(this.groups);\n } finally {\n groupsLock.unlock();\n }\n }\n\n public LinkedHashMap<String, List<CachedGroup>> getPlayerOwnGroupsBase(final UUID uuid) {\n // If player is online, get data directly from player\n PermissionPlayer gp = getPermissionPlayer(uuid);\n if (gp != null && !gp.isDefault())\n return gp.getCachedGroups();\n return loadPlayerGroups(uuid);\n }\n\n public LinkedHashMap<String, List<CachedGroup>> getPlayerCurrentGroupsBase(final UUID uuid) {\n // If player is online, get data directly from player\n PermissionPlayer gp = getPermissionPlayer(uuid);\n if (gp != null)\n return gp.getCachedGroups();\n\n LinkedHashMap<String, List<CachedGroup>> result = loadPlayerGroups(uuid);\n if (result != null) {\n if (result.isEmpty()) {\n result.putAll(deepCopyDefaultGroups());\n }\n }\n return result;\n }\n\n public Group getPlayerPrimaryGroupBase(UUID uuid) {\n // If player is online, get data directly from player\n PermissionPlayer gp = getPermissionPlayer(uuid);\n if (gp != null)\n return gp.getPrimaryGroup();\n\n LinkedHashMap<String, List<CachedGroup>> result = getPlayerCurrentGroupsBase(uuid);\n List<CachedGroup> cachedGroups = PermissionPlayerBase.getCachedGroups(serverName, result);\n List<Group> groups = PermissionPlayerBase.getGroups(cachedGroups, plugin);\n return PermissionPlayerBase.getPrimaryGroup(groups);\n }\n\n public Boolean isPlayerDefaultBase(final UUID uuid) {\n PermissionPlayer permissionPlayer = getPermissionPlayer(uuid);\n if (permissionPlayer != null)\n return permissionPlayer.isDefault();\n\n LinkedHashMap<String, List<CachedGroup>> result = getPlayerOwnGroupsBase(uuid);\n if (result == null || result.isEmpty())\n return true;\n else\n return false;\n }\n\n protected Response copyDefaultGroups(final UUID uuid) {\n LinkedHashMap<String, List<CachedGroup>> result = getPlayerOwnGroupsBase(DefaultPermissionPlayer.getUUID());\n if (result == null || result.isEmpty())\n return new Response(false, \"Could not retrieve the default groups.\");\n else {\n LinkedHashMap<String, List<CachedGroup>> defaultGroups = result;\n for (Entry<String, List<CachedGroup>> entry : defaultGroups.entrySet()) {\n String server = entry.getKey();\n for (CachedGroup toAdd : entry.getValue()) {\n boolean inserted = db.insertPlayerGroup(uuid, toAdd.getGroupId(), server, toAdd.isNegated(), toAdd.getExpirationDate());\n if (!inserted)\n plugin.getLogger().severe(\"Could not copy default group \" + toAdd.getGroupId() + \" to player \" + uuid.toString() + \".\");\n }\n }\n return new Response(true, \"Default groups copied.\");\n }\n }\n\n protected Response copyDefaultGroupsIfDefault(final UUID uuid) {\n if (isPlayerDefaultBase(uuid)) {\n return copyDefaultGroups(uuid);\n } else\n return new Response(false, \"Player is not default.\");\n }\n\n public DBDocument getPlayerDataBase(final UUID uuid) {\n DBResult result = db.getPlayer(uuid);\n if (result.hasNext()) {\n DBDocument row = result.next();\n return row;\n }\n return null;\n }\n\n public List<Permission> getPlayerOwnPermissionsBase(final UUID uuid) {\n // If player is online, get data directly from player\n PermissionPlayer gp = getPermissionPlayer(uuid);\n if (gp != null)\n return gp.getPermissions();\n\n List<Permission> perms = loadPlayerOwnPermissions(uuid);\n if (perms == null)\n perms = new ArrayList<>();\n return perms;\n }\n\n protected List<Permission> loadPlayerOwnPermissions(final UUID uuid) {\n DBResult result = db.getPlayerPermissions(uuid);\n if (result.booleanValue()) {\n ArrayList<Permission> perms = new ArrayList<>();\n while (result.hasNext()) {\n DBDocument row = result.next();\n Permission tempPerm = new PowerfulPermission(row.getInt(\"id\"), row.getString(\"permission\"), row.getString(\"world\"), row.getString(\"server\"), row.getDate(\"expires\"));\n perms.add(tempPerm);\n }\n return perms;\n } else\n plugin.getLogger().severe(\"Could not load player permissions.\");\n return null;\n }\n\n protected LinkedHashMap<String, List<CachedGroup>> loadPlayerGroups(final UUID uuid) {\n DBResult result = db.getPlayerGroups(uuid);\n if (result.booleanValue()) {\n LinkedHashMap<String, List<CachedGroup>> localGroups = new LinkedHashMap<>();\n while (result.hasNext()) {\n DBDocument row = result.next();\n int groupId = row.getInt(\"groupid\");\n Group group = getGroup(groupId);\n if (group == null) {\n plugin.getLogger().warning(\"Could not load stored player group, group does not exist\");\n continue;\n }\n\n if (!localGroups.containsKey(row.getString(\"server\")))\n localGroups.put(row.getString(\"server\"), new ArrayList<>());\n List<CachedGroup> serverGroups = localGroups.get(row.getString(\"server\"));\n serverGroups.add(new CachedGroup(row.getInt(\"id\"), groupId, row.getBoolean(\"negated\"), row.getDate(\"expires\")));\n localGroups.put(row.getString(\"server\"), serverGroups);\n }\n return localGroups;\n } else\n plugin.getLogger().severe(\"Could not load player groups.\");\n return null;\n }\n\n protected HashMap<Integer, List<Integer>> loadGroupParents() {\n DBResult result = db.getGroupParents();\n if (result.booleanValue()) {\n HashMap<Integer, List<Integer>> parents = new HashMap<>();\n while (result.hasNext()) {\n DBDocument row = result.next();\n\n int groupId = row.getInt(\"groupid\");\n int parentId = row.getInt(\"parentgroupid\");\n if (!parents.containsKey(groupId))\n parents.put(groupId, new ArrayList<>());\n List<Integer> localParents = parents.get(groupId);\n localParents.add(parentId);\n parents.put(groupId, localParents);\n }\n return parents;\n } else\n plugin.getLogger().severe(\"Could not load group parents.\");\n return null;\n }\n\n protected HashMap<Integer, HashMap<String, String>> loadGroupPrefixes() {\n DBResult result = db.getGroupPrefixes();\n if (result.booleanValue()) {\n HashMap<Integer, HashMap<String, String>> prefixes = new HashMap<>();\n while (result.hasNext()) {\n DBDocument row = result.next();\n\n int groupId = row.getInt(\"groupid\");\n if (!prefixes.containsKey(groupId))\n prefixes.put(groupId, new HashMap<>());\n HashMap<String, String> localPrefixes = prefixes.get(groupId);\n localPrefixes.put(row.getString(\"server\"), row.getString(\"prefix\"));\n prefixes.put(groupId, localPrefixes);\n }\n return prefixes;\n } else\n plugin.getLogger().severe(\"Could not load group prefixes.\");\n return null;\n }\n\n protected HashMap<Integer, HashMap<String, String>> loadGroupSuffixes() {\n DBResult result = db.getGroupSuffixes();\n if (result.booleanValue()) {\n HashMap<Integer, HashMap<String, String>> suffixes = new HashMap<>();\n while (result.hasNext()) {\n DBDocument row = result.next();\n\n int groupId = row.getInt(\"groupid\");\n if (!suffixes.containsKey(groupId))\n suffixes.put(groupId, new HashMap<>());\n HashMap<String, String> localSuffixes = suffixes.get(groupId);\n localSuffixes.put(row.getString(\"server\"), row.getString(\"suffix\"));\n suffixes.put(groupId, localSuffixes);\n }\n return suffixes;\n } else\n plugin.getLogger().severe(\"Could not load group suffixes.\");\n return null;\n }\n\n protected HashMap<Integer, List<PowerfulPermission>> loadGroupPermissions() {\n DBResult result = db.getGroupPermissions();\n if (result.booleanValue()) {\n HashMap<Integer, List<PowerfulPermission>> permissions = new HashMap<>();\n while (result.hasNext()) {\n DBDocument row = result.next();\n\n int groupId = row.getInt(\"groupid\");\n if (!permissions.containsKey(groupId))\n permissions.put(groupId, new ArrayList<>());\n List<PowerfulPermission> localPermissions = permissions.get(groupId);\n localPermissions.add(new PowerfulPermission(row.getInt(\"id\"), row.getString(\"permission\"), row.getString(\"world\"), row.getString(\"server\"), row.getDate(\"expires\")));\n permissions.put(groupId, localPermissions);\n }\n return permissions;\n } else\n plugin.getLogger().severe(\"Could not load group permissions.\");\n return null;\n }\n\n public String getPlayerPrefixBase(final UUID uuid, final String ladder) {\n // If player is online, get data directly from player\n PermissionPlayer gp = getPermissionPlayer(uuid);\n if (gp != null) {\n if (ladder != null)\n return gp.getPrefix(ladder);\n return gp.getPrefix();\n }\n\n LinkedHashMap<String, List<CachedGroup>> currentGroups = getPlayerCurrentGroupsBase(uuid);\n List<CachedGroup> cachedGroups = PermissionPlayerBase.getCachedGroups(serverName, currentGroups);\n List<Group> groups = PermissionPlayerBase.getGroups(cachedGroups, plugin);\n String prefix = \"\";\n if (ladder != null)\n prefix = PermissionPlayerBase.getPrefix(ladder, groups);\n else\n prefix = PermissionPlayerBase.getPrefix(groups, getPlayerOwnPrefixBase(uuid));\n return prefix;\n }\n\n public String getPlayerSuffixBase(final UUID uuid, final String ladder) {\n // If player is online, get data directly from player\n PermissionPlayer gp = getPermissionPlayer(uuid);\n if (gp != null) {\n if (ladder != null)\n return gp.getSuffix(ladder);\n return gp.getSuffix();\n }\n\n LinkedHashMap<String, List<CachedGroup>> currentGroups = getPlayerCurrentGroupsBase(uuid);\n List<CachedGroup> cachedGroups = PermissionPlayerBase.getCachedGroups(serverName, currentGroups);\n List<Group> groups = PermissionPlayerBase.getGroups(cachedGroups, plugin);\n String suffix = \"\";\n if (ladder != null)\n suffix = PermissionPlayerBase.getSuffix(ladder, groups);\n else\n suffix = PermissionPlayerBase.getSuffix(groups, getPlayerOwnSuffixBase(uuid));\n return suffix;\n }\n\n public String getPlayerOwnPrefixBase(final UUID uuid) {\n // If player is online, get data directly from player\n PermissionPlayer gp = getPermissionPlayer(uuid);\n if (gp != null)\n return gp.getOwnPrefix();\n\n DBResult result = db.getPlayer(uuid);\n if (result.hasNext()) {\n DBDocument row = result.next();\n return row.getString(\"prefix\");\n }\n return null;\n }\n\n public String getPlayerOwnSuffixBase(final UUID uuid) {\n // If player is online, get data directly from player\n PermissionPlayer gp = getPermissionPlayer(uuid);\n if (gp != null)\n return gp.getOwnSuffix();\n\n DBResult result = db.getPlayer(uuid);\n if (result.hasNext()) {\n DBDocument row = result.next();\n return row.getString(\"suffix\");\n }\n return null;\n }\n\n public String getGroupPrefix(int groupId, String server) {\n Group g = getGroup(groupId);\n if (g != null)\n return g.getPrefix(server);\n return null;\n }\n\n public String getGroupSuffix(int groupId, String server) {\n Group g = getGroup(groupId);\n if (g != null)\n return g.getSuffix(server);\n return null;\n }\n\n public HashMap<String, String> getGroupServerPrefix(int groupId) {\n Group g = getGroup(groupId);\n if (g != null)\n return g.getPrefixes();\n return null;\n }\n\n public HashMap<String, String> getGroupServerSuffix(int groupId) {\n Group g = getGroup(groupId);\n if (g != null)\n return g.getSuffixes();\n return null;\n }\n\n public UUID getConvertUUIDBase(final String playerName) {\n if (playerName.equalsIgnoreCase(\"[default]\") || playerName.equalsIgnoreCase(\"{default}\"))\n return DefaultPermissionPlayer.getUUID();\n\n // If player name is UUID, return it directly\n try {\n UUID uuid = UUID.fromString(playerName);\n return uuid;\n } catch (Exception e) {\n }\n\n // If player is online, get UUID directly\n if (plugin.isPlayerOnline(playerName))\n return plugin.getPlayerUUID(playerName);\n\n // If player UUID exists in database, use that\n DBResult result;\n if (plugin.getServerMode() == ServerMode.ONLINE)\n result = db.getPlayersCaseInsensitive(playerName);\n else\n result = db.getPlayers(playerName);\n\n if (result.hasNext()) {\n final DBDocument row = result.next();\n if (row != null) {\n String stringUUID = row.getString(\"uuid\");\n UUID uuid = UUID.fromString(stringUUID);\n if (uuid != null) {\n debug(\"UUID found in DB, skipping mojang api lookup\");\n return uuid;\n }\n }\n }\n\n // Check if DB contains online uuid. If so, return it.\n // Check if DB contains offline uuid. If so, return it. If not, return online uuid.\n if (plugin.getServerMode() == ServerMode.MIXED) {\n // Generate offline UUID and check database if it exists. If so, return it.\n final UUID offlineuuid = java.util.UUID.nameUUIDFromBytes((\"OfflinePlayer:\" + playerName).getBytes(Charsets.UTF_8));\n debug(\"Generated mixed mode offline UUID \" + offlineuuid);\n\n // Get online UUID.\n\n debug(\"Begin UUID retrieval...\");\n ArrayList<String> list = new ArrayList<>();\n list.add(playerName);\n UUIDFetcher fetcher = new UUIDFetcher(list);\n try {\n Map<String, UUID> result2 = fetcher.call();\n if (result2 != null && result2.containsKey(playerName)) {\n final UUID onlineuuid = result2.get(playerName);\n debug(\"Retrieved UUID \" + onlineuuid);\n // Check if database contains online UUID.\n\n DBResult result3 = db.getPlayer(onlineuuid);\n if (result3.hasNext()) {\n // Database contains online UUID. Return it.\n debug(\"online UUID found in DB\");\n return onlineuuid;\n } else {\n // Could not find online UUID in database.\n // Check if offline UUID exists.\n debug(\"online UUID not found in DB\");\n DBResult offline = db.getPlayer(offlineuuid);\n if (offline.hasNext()) {\n // Found offline UUID in database. Return it.\n debug(\"offline UUID found in DB, return offline\");\n return offlineuuid;\n } else {\n // Could not find neither of offline or online UUIDs in database.\n // Online UUID exists for player name so return it.\n debug(\"offline UUID not found in DB, return online\");\n return onlineuuid;\n }\n }\n } else {\n // Could not find online UUID for specified name\n debug(\"Did not find online UUID for player name \" + playerName + \", return offline\");\n return offlineuuid;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n } else {\n if (plugin.getServerMode() == ServerMode.ONLINE) {\n // Convert player name to UUID using Mojang API\n debug(\"Begin UUID retrieval...\");\n ArrayList<String> list = new ArrayList<>();\n list.add(playerName);\n UUIDFetcher fetcher = new UUIDFetcher(list);\n try {\n Map<String, UUID> result2 = fetcher.call();\n if (result2 != null) {\n for (Entry<String, UUID> e : result2.entrySet()) {\n if (e.getKey().equalsIgnoreCase(playerName)) {\n debug(\"Retrieved UUID \" + e.getValue());\n return e.getValue();\n }\n }\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n } else {\n // Generate UUID from player name\n UUID uuid = java.util.UUID.nameUUIDFromBytes((\"OfflinePlayer:\" + playerName).getBytes(Charsets.UTF_8));\n debug(\"Generated offline mode UUID \" + uuid);\n return uuid;\n }\n }\n return null;\n }\n\n public IScheduler getScheduler() {\n return db.scheduler;\n }\n\n public Response createPlayerBase(final String name, final UUID uuid) {\n loadPlayer(uuid, name, true, true);\n return new Response(true, \"Player created.\");\n }\n\n // -------------------------------------------------------------------//\n // //\n // ------------PLAYER PERMISSION MODIFYING FUNCTIONS BELOW------------//\n // //\n // -------------------------------------------------------------------//\n\n public Response addPlayerPermissionBase(final UUID uuid, final String permission, final String world, final String server, final Date expires) {\n final Date now = new Date();\n if (uuid.equals(DefaultPermissionPlayer.getUUID()))\n return new Response(false, \"You can not add permissions to the default player. Add them to a group instead and add the group to the default player.\");\n\n // Check if the same permission already exists.\n boolean hasPermission = db.playerHasPermission(uuid, permission, world, server, expires);\n if (hasPermission)\n return new Response(false, \"Player already has the specified permission.\");\n else {\n DBResult result = db.getPlayer(uuid);\n if (result.hasNext()) {\n if (expires != null) {\n for (Permission p : getPlayerOwnPermissionsBase(uuid)) {\n if (p.willExpire()) {\n if (p.getPermissionString().equals(permission) && p.getServer().equalsIgnoreCase(server) && p.getWorld().equalsIgnoreCase(world)) {\n final Date newExpiry = new Date(p.getExpirationDate().getTime() + (expires.getTime() - now.getTime()));\n DBResult result2 = db.deletePlayerPermission(uuid, p.getPermissionString(), p.getWorld(), p.getServer(), p.getExpirationDate());\n if (!result2.booleanValue())\n return new Response(false, \"Could not update permission expiration date. Check console for any errors.\");\n else {\n boolean inserted = db.insertPlayerPermission(uuid, permission, world, server, newExpiry);\n if (!inserted) {\n return new Response(false, \"Could not update permission expiration date. Check console for any errors.\");\n } else {\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Permission expiration changed.\");\n }\n }\n }\n }\n }\n }\n boolean inserted = db.insertPlayerPermission(uuid, permission, world, server, expires);\n if (inserted) {\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Permission added to player.\");\n } else\n return new Response(false, \"Could not add permission. Check console for any errors.\");\n } else\n return new Response(false, \"Could not add permission. Player doesn't exist.\");\n }\n }\n\n public Response removePlayerPermissionBase(final UUID uuid, final String permission, final String world, final String server, final Date expires) {\n boolean anyServer = false;\n if (server.equalsIgnoreCase(\"any\"))\n anyServer = true;\n String tempServer = server;\n if (server.equalsIgnoreCase(\"all\"))\n tempServer = \"\";\n\n boolean anyWorld = false;\n if (world.equalsIgnoreCase(\"any\"))\n anyWorld = true;\n String tempWorld = world;\n if (world.equalsIgnoreCase(\"all\"))\n tempWorld = \"\";\n\n List<Permission> result = getPlayerOwnPermissionsBase(uuid);\n if (result != null) {\n List<Permission> toDelete = new ArrayList<>();\n for (Permission e : result) {\n if (e.getPermissionString().equalsIgnoreCase(permission)) {\n if (anyServer || e.getServer().equalsIgnoreCase(tempServer)) {\n if (anyWorld || e.getWorld().equalsIgnoreCase(tempWorld)) {\n if (Utils.dateApplies(e.getExpirationDate(), expires)) {\n toDelete.add(e);\n }\n }\n }\n }\n }\n\n if (toDelete.isEmpty())\n return new Response(false, \"Player does not have this permission.\");\n\n int deleted = 0;\n for (Permission e : toDelete) {\n DBResult dbresult = db.deletePlayerPermission(uuid, e.getPermissionString(), e.getWorld(), e.getServer(), e.getExpirationDate());\n if (dbresult.booleanValue())\n deleted += dbresult.rowsChanged();\n }\n\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n if (deleted > 0)\n return new Response(true, \"Removed \" + deleted + \" of \" + toDelete.size() + \" player permissions.\");\n else\n return new Response(false, \"Removed \" + deleted + \" of \" + toDelete.size() + \" player permissions.\");\n } else\n return new Response(false, \"Player does not exist.\");\n }\n\n public Response removePlayerPermissionsBase(final UUID uuid) {\n DBResult result = db.deletePlayerPermissions(uuid);\n if (result.booleanValue()) {\n int amount = result.rowsChanged();\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Removed \" + amount + \" permissions from the player.\");\n } else\n return new Response(false, \"Player does not have any permissions.\");\n }\n\n public Response setPlayerPrefixBase(final UUID uuid, final String prefix) {\n if (uuid.equals(DefaultPermissionPlayer.getUUID()))\n return new Response(false, \"You can not set the prefix of the default player. Add it to a group instead and add the group to the default player.\");\n\n boolean success = db.setPlayerPrefix(uuid, prefix);\n if (success) {\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Player prefix set.\");\n } else\n return new Response(false, \"Could not set player prefix. Check console for errors.\");\n }\n\n public Response setPlayerSuffixBase(final UUID uuid, final String suffix) {\n if (uuid.equals(DefaultPermissionPlayer.getUUID()))\n return new Response(false, \"You can not set the suffix of the default player. Add it to a group instead and add the group to the default player.\");\n\n boolean success = db.setPlayerSuffix(uuid, suffix);\n if (success) {\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Player suffix set.\");\n } else\n return new Response(false, \"Could not set player suffix. Check console for errors.\");\n }\n\n public Response removePlayerGroupBase(final UUID uuid, final int groupId, final String server, final boolean negated, final Date expires) {\n String tempServer = server;\n if (server.equalsIgnoreCase(\"all\"))\n tempServer = \"\";\n boolean any = false;\n if (server.equalsIgnoreCase(\"any\"))\n any = true;\n\n final String serverFinal = tempServer;\n\n final Group group = getGroup(groupId);\n if (group == null)\n return new Response(false, \"Group does not exist.\");\n\n LinkedHashMap<String, List<CachedGroup>> result = getPlayerCurrentGroupsBase(uuid);\n if (result != null) {\n\n // Calc amount to see if there are any to remove at all.\n int amountToDelete = 0;\n for (Entry<String, List<CachedGroup>> e : result.entrySet()) {\n if (any || e.getKey().equalsIgnoreCase(serverFinal)) {\n for (CachedGroup cachedGroup : e.getValue()) {\n if (cachedGroup.getGroupId() == groupId && cachedGroup.isNegated() == negated && Utils.dateApplies(cachedGroup.getExpirationDate(), expires))\n ++amountToDelete;\n }\n }\n }\n\n if (amountToDelete == 0)\n return new Response(false, \"Player does not have this group.\");\n\n // Important: copy default groups\n copyDefaultGroupsIfDefault(uuid);\n\n // Reset amount and actually remove.\n int amount = 0;\n for (Entry<String, List<CachedGroup>> e : result.entrySet()) {\n if (any || e.getKey().equalsIgnoreCase(serverFinal)) {\n for (CachedGroup cachedGroup : e.getValue()) {\n if (cachedGroup.getGroupId() == groupId && cachedGroup.isNegated() == negated && Utils.dateApplies(cachedGroup.getExpirationDate(), expires)) {\n if (db.deletePlayerGroup(uuid, cachedGroup.getGroupId(), e.getKey(), cachedGroup.isNegated(), cachedGroup.getExpirationDate()))\n ++amount;\n }\n }\n }\n }\n\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n if (amount > 0)\n return new Response(true, \"Removed \" + amount + \" of \" + amountToDelete + \" player groups.\");\n else\n return new Response(false, \"Removed \" + amount + \" of \" + amountToDelete + \" player groups.\");\n } else\n return new Response(false, \"Player does not exist.\");\n }\n\n public Response addPlayerGroupBase(final UUID uuid, final int groupId, final String server, final boolean negated, final Date expires) {\n final Date now = new Date();\n String tempServer = server;\n if (server.equalsIgnoreCase(\"all\"))\n tempServer = \"\";\n\n final String serverFinal = tempServer;\n\n final Group group = getGroup(groupId);\n if (group == null)\n return new Response(false, \"Group does not exist.\");\n\n LinkedHashMap<String, List<CachedGroup>> result = getPlayerCurrentGroupsBase(uuid);\n if (result != null) {\n List<CachedGroup> groupList = result.get(serverFinal);\n if (groupList == null)\n groupList = new ArrayList<>();\n for (CachedGroup cachedGroup : groupList) {\n if (cachedGroup.getGroupId() == groupId && cachedGroup.isNegated() == negated) {\n // Update expiration date instead\n final Date newExpiry = (expires == null || cachedGroup.getExpirationDate() == null ? expires\n : new Date(cachedGroup.getExpirationDate().getTime() + (expires.getTime() - now.getTime())));\n if (newExpiry == cachedGroup.getExpirationDate() || (newExpiry != null && newExpiry.equals(cachedGroup.getExpirationDate())))\n return new Response(false, \"Player already has this group.\");\n boolean deleted = db.deletePlayerGroup(uuid, cachedGroup.getGroupId(), serverFinal, cachedGroup.isNegated(), cachedGroup.getExpirationDate());\n if (!deleted) {\n return new Response(false, \"Could not update player group expiration date. Check console for any errors.\");\n } else {\n boolean inserted = db.insertPlayerGroup(uuid, groupId, serverFinal, negated, newExpiry);\n if (!inserted) {\n return new Response(false, \"Could not update player group expiration date. Check console for any errors.\");\n } else {\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Group expiration changed.\");\n }\n }\n } else if (cachedGroup.getGroupId() == groupId && cachedGroup.isNegated() == negated && Utils.dateApplies(cachedGroup.getExpirationDate(), expires))\n return new Response(false, \"Player already has this group.\");\n }\n\n copyDefaultGroupsIfDefault(uuid);\n\n boolean inserted = db.insertPlayerGroup(uuid, groupId, serverFinal, negated, expires);\n if (inserted) {\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Player group added.\");\n } else\n return new Response(false, \"Could not add player group. Check console for errors.\");\n } else\n return new Response(false, \"Player does not exist.\");\n }\n\n public Response setPlayerRankBase(final UUID uuid, final int groupId) {\n // Get player groups on specified ladder\n // Use the group type of the first one of those groups\n // replace old group with group \"groupname\"\n\n final Group group = getGroup(groupId);\n if (group == null)\n return new Response(false, \"Group does not exist.\");\n\n LinkedHashMap<String, List<CachedGroup>> result = getPlayerCurrentGroupsBase(uuid);\n if (result != null) {\n copyDefaultGroupsIfDefault(uuid);\n\n Iterator<Entry<String, List<CachedGroup>>> it = result.entrySet().iterator();\n boolean changed = false;\n Group toUse = null;\n while (it.hasNext()) {\n Entry<String, List<CachedGroup>> next = it.next();\n final String server = next.getKey();\n List<CachedGroup> playerCurrentGroups = next.getValue();\n for (CachedGroup current : playerCurrentGroups) {\n final Group currentGroup = getGroup(current.getGroupId());\n if (currentGroup.getLadder().equals(group.getLadder()) && current.getExpirationDate() == null) {\n if (toUse == null)\n toUse = currentGroup;\n // Replace with new group if they are on the same ladder and if toUse and current is the same group\n if (toUse.getId() == currentGroup.getId()) {\n boolean deleted = db.deletePlayerGroup(uuid, currentGroup.getId(), server, current.isNegated(), null);\n debug(\"(setrank) removed group \" + currentGroup.getId());\n if (!deleted)\n return new Response(false, \"Could not remove group with ID \" + currentGroup.getId() + \".\");\n else {\n boolean inserted = db.insertPlayerGroup(uuid, groupId, server, current.isNegated(), null);\n debug(\"(setrank) added group \" + groupId);\n if (!inserted)\n return new Response(false, \"Could not add group with ID \" + groupId + \".\");\n }\n changed = true;\n } else // Prevents multiple different groups in the same ladder\n db.deletePlayerGroup(uuid, currentGroup.getId(), server, current.isNegated(), null);\n }\n }\n }\n\n if (!changed) {\n boolean inserted = db.insertPlayerGroup(uuid, groupId, \"\", false, null);\n debug(\"(setrank) added group \" + groupId + \". had no groups in ladder\");\n if (!inserted)\n return new Response(false, \"Could not add group with ID \" + groupId + \".\");\n }\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Player rank set on ladder \\\"\" + group.getLadder() + \"\\\".\");\n } else\n return new Response(false, \"Player does not exist.\");\n }\n\n public Group getHigherGroup(Group group) {\n List<Group> groups;\n groupsLock.lock();\n try {\n groups = new ArrayList<>(this.groups.values());\n } finally {\n groupsLock.unlock();\n }\n\n TreeMap<Integer, Group> sortedGroups = new TreeMap<>();\n for (Group current : groups) {\n if (current.getLadder().equals(group.getLadder()))\n sortedGroups.put(current.getRank(), current);\n }\n\n Iterator<Entry<Integer, Group>> it = sortedGroups.entrySet().iterator();\n while (it.hasNext()) {\n Entry<Integer, Group> entry = it.next();\n if (entry.getKey() == group.getRank() && entry.getValue().getName().equals(group.getName())) {\n if (it.hasNext()) {\n Group next = it.next().getValue();\n if (next.getId() == group.getId())\n return null;\n return next;\n } else\n return null;\n }\n }\n return null;\n }\n\n public Group getLowerGroup(Group group) {\n List<Group> groups;\n groupsLock.lock();\n try {\n groups = new ArrayList<>(this.groups.values());\n } finally {\n groupsLock.unlock();\n }\n\n TreeMap<Integer, Group> sortedGroups = new TreeMap<>(Collections.reverseOrder());\n for (Group current : groups) {\n if (current.getLadder().equals(group.getLadder()))\n sortedGroups.put(current.getRank(), current);\n }\n\n Iterator<Entry<Integer, Group>> it = sortedGroups.entrySet().iterator();\n while (it.hasNext()) {\n\n Entry<Integer, Group> entry = it.next();\n if (entry.getKey() == group.getRank() && entry.getValue().getName().equals(group.getName())) {\n if (it.hasNext()) {\n Group next = it.next().getValue();\n if (next.getId() == group.getId())\n return null;\n return next;\n } else\n return null;\n }\n }\n return null;\n }\n\n public Response promotePlayerBase(final UUID uuid, final String ladder) {\n LinkedHashMap<String, List<CachedGroup>> result = getPlayerCurrentGroupsBase(uuid);\n copyDefaultGroupsIfDefault(uuid);\n if (result != null) {\n if (!result.isEmpty()) {\n Iterator<Entry<String, List<CachedGroup>>> it = result.entrySet().iterator();\n boolean changed = false;\n Group toUse = null;\n Group toPromoteTo = null;\n while (it.hasNext()) {\n Entry<String, List<CachedGroup>> next = it.next();\n final String server = next.getKey();\n List<CachedGroup> playerCurrentGroups = next.getValue();\n\n for (CachedGroup current : playerCurrentGroups) {\n final Group currentGroup = getGroup(current.getGroupId());\n if (currentGroup.getLadder().equalsIgnoreCase(ladder) && !current.willExpire() && !current.isNegated()) {\n if (toUse == null) {\n toUse = currentGroup;\n toPromoteTo = getHigherGroup(toUse);\n if (toPromoteTo == null)\n return new Response(false, \"There is no group on this ladder with a higher rank.\");\n }\n // Replace with new group if they are on the same ladder and if toUse and current is the same group\n if (toUse.getId() == currentGroup.getId()) {\n // This is the group to promote from\n final Group toPromoteToFinal = toPromoteTo;\n boolean deleted = db.deletePlayerGroup(uuid, currentGroup.getId(), server, current.isNegated(), null);\n debug(\"(promote) removed group \" + currentGroup.getId() + \" \" + currentGroup.getName());\n if (!deleted)\n return new Response(false, \"Could not remove group with ID \" + currentGroup.getId() + \".\");\n else {\n boolean inserted = db.insertPlayerGroup(uuid, toPromoteToFinal.getId(), server, current.isNegated(), null);\n debug(\"(promote) added group \" + toPromoteToFinal.getId() + \" \" + toPromoteToFinal.getName());\n if (!inserted)\n return new Response(false, \"Could not add group with ID \" + toPromoteToFinal.getId() + \".\");\n }\n changed = true;\n }\n }\n }\n }\n\n if (!changed) {\n return new Response(false, \"Player has no groups on the specified ladder.\");\n } else {\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Player was promoted to \\\"\" + toPromoteTo.getName() + \"\\\".\");\n }\n\n } else\n return new Response(false, \"Player has no groups.\");\n } else\n return new Response(false, \"Player does not exist.\");\n }\n\n public Response demotePlayerBase(final UUID uuid, final String ladder) {\n LinkedHashMap<String, List<CachedGroup>> result = getPlayerCurrentGroupsBase(uuid);\n copyDefaultGroupsIfDefault(uuid);\n if (result != null) {\n if (!result.isEmpty()) {\n Iterator<Entry<String, List<CachedGroup>>> it = result.entrySet().iterator();\n boolean changed = false;\n Group toUse = null;\n Group toDemoteTo = null;\n while (it.hasNext()) {\n Entry<String, List<CachedGroup>> next = it.next();\n final String server = next.getKey();\n List<CachedGroup> playerCurrentGroups = next.getValue();\n\n for (CachedGroup current : playerCurrentGroups) {\n final Group currentGroup = getGroup(current.getGroupId());\n if (currentGroup.getLadder().equalsIgnoreCase(ladder) && !current.willExpire() && !current.isNegated()) {\n if (toUse == null) {\n toUse = currentGroup;\n toDemoteTo = getLowerGroup(toUse);\n if (toDemoteTo == null)\n return new Response(false, \"There is no group on this ladder with a lower rank.\");\n }\n // Remove old group and add lower group if they are on the same ladder and if toUse and current is the same group\n if (toUse.getId() == currentGroup.getId()) {\n final Group toDemoteToFinal = toDemoteTo;\n boolean deleted = db.deletePlayerGroup(uuid, currentGroup.getId(), server, current.isNegated(), null);\n debug(\"(demote) removed group \" + currentGroup.getId());\n if (!deleted)\n return new Response(false, \"Could not remove group with ID \" + currentGroup.getId() + \".\");\n else {\n boolean inserted = db.insertPlayerGroup(uuid, toDemoteToFinal.getId(), server, current.isNegated(), null);\n debug(\"(demote) added group \" + toDemoteToFinal.getId());\n if (!inserted)\n return new Response(false, \"Could not add group with ID \" + toDemoteToFinal.getId() + \".\");\n }\n changed = true;\n }\n }\n }\n }\n\n if (!changed) {\n return new Response(false, \"Player has no groups on the specified ladder.\");\n } else {\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Player was demoted to \\\"\" + toDemoteTo.getName() + \"\\\".\");\n }\n } else\n return new Response(false, \"Player has no groups.\");\n } else\n return new Response(false, \"Player does not exist.\");\n }\n\n public Response deletePlayerBase(UUID uuid) {\n DBResult result = db.deletePlayer(uuid);\n if (result.rowsChanged() > 0) {\n reloadPlayer(uuid, true);\n notifyReloadPlayer(uuid);\n return new Response(true, \"Deleted \" + result.rowsChanged() + \" player\" + (result.rowsChanged() > 1 ? \"s\" : \"\") + \".\");\n } else\n return new Response(false, \"Player does not exist.\");\n\n }\n\n // -------------------------------------------------------------------//\n // //\n // ------------GROUP PERMISSION MODIFYING FUNCTIONS BELOW-------------//\n // //\n // -------------------------------------------------------------------//\n\n public Response createGroupBase(final String name, final String ladder, final int rank) {\n Map<Integer, Group> groupsClone;\n groupsLock.lock();\n try {\n groupsClone = new HashMap<>(groups);\n } finally {\n groupsLock.unlock();\n }\n for (Entry<Integer, Group> e : groupsClone.entrySet()) {\n if (e.getValue().getName().equalsIgnoreCase(name))\n return new Response(false, \"Group already exists.\");\n }\n\n boolean inserted = db.insertGroup(-1, name, ladder, rank);\n if (inserted) {\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Created group.\");\n } else\n return new Response(false, \"Group already exists.\");\n }\n\n public Response deleteGroupBase(final int groupId) {\n boolean deleted = db.deleteGroup(groupId);\n if (deleted) {\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Deleted group.\");\n } else\n return new Response(false, \"Group does not exist.\");\n }\n\n public Response addGroupPermissionBase(final int groupId, final String permission, final String world, final String server, final Date expires) {\n Date now = new Date();\n Group group = getGroup(groupId);\n if (group != null) {\n List<Permission> groupPermissions = group.getOwnPermissions();\n\n if (expires != null) {\n List<Permission> result = group.getOwnPermissions();\n for (Permission p : result) {\n if (p.willExpire()) {\n if (p.getPermissionString().equals(permission) && p.getServer().equalsIgnoreCase(server) && p.getWorld().equalsIgnoreCase(world)) {\n final Date newExpiry = new Date(p.getExpirationDate().getTime() + (expires.getTime() - now.getTime()));\n DBResult result2 = db.deleteGroupPermission(groupId, p.getPermissionString(), p.getWorld(), p.getServer(), p.getExpirationDate());\n if (!result2.booleanValue())\n return new Response(false, \"Could not update permission expiration date. Check console for any errors.\");\n else {\n boolean inserted = db.insertGroupPermission(groupId, permission, world, server, newExpiry);\n if (!inserted) {\n return new Response(false, \"Could not update permission expiration date. Check console for any errors.\");\n } else {\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Permission expiration changed.\");\n }\n }\n }\n }\n }\n }\n\n for (Permission temp : groupPermissions) {\n if (temp.getPermissionString().equals(permission) && temp.getServer().equals(server) && temp.getWorld().equals(world)\n && (expires == null ? true : (expires.equals(temp.getExpirationDate())))) {\n return new Response(false, \"Group already has the specified permission.\");\n }\n }\n\n boolean inserted = db.insertGroupPermission(groupId, permission, world, server, expires);\n if (inserted) {\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Added permission to group.\");\n } else\n return new Response(false, \"Could not add permission to group. Check console for errors.\");\n } else\n return new Response(false, \"Group does not exist.\");\n }\n\n public Response removeGroupPermissionBase(final int groupId, final String permission, final String world, final String server, final Date expires) {\n Group group = getGroup(groupId);\n if (group != null) {\n\n boolean anyServer = false;\n if (server.equalsIgnoreCase(\"any\"))\n anyServer = true;\n String tempServer = server;\n if (server.equalsIgnoreCase(\"all\"))\n tempServer = \"\";\n\n boolean anyWorld = false;\n if (world.equalsIgnoreCase(\"any\"))\n anyWorld = true;\n String tempWorld = world;\n if (world.equalsIgnoreCase(\"all\"))\n tempWorld = \"\";\n\n List<Permission> groupPermissions = group.getOwnPermissions();\n List<Permission> toDelete = new ArrayList<>();\n for (Permission e : groupPermissions) {\n if (e.getPermissionString().equalsIgnoreCase(permission)) {\n if (anyServer || e.getServer().equalsIgnoreCase(tempServer)) {\n if (anyWorld || e.getWorld().equalsIgnoreCase(tempWorld)) {\n if (Utils.dateApplies(e.getExpirationDate(), expires)) {\n toDelete.add(e);\n }\n }\n }\n }\n }\n\n if (toDelete.isEmpty())\n return new Response(false, \"The group does not have this permission.\");\n\n int deleted = 0;\n for (Permission e : toDelete) {\n DBResult result = db.deleteGroupPermission(groupId, e.getPermissionString(), e.getWorld(), e.getServer(), e.getExpirationDate());\n if (result.booleanValue())\n deleted += result.rowsChanged();\n }\n\n loadGroups(true);\n notifyReloadGroups();\n if (deleted > 0)\n return new Response(true, \"Removed \" + deleted + \" of \" + toDelete.size() + \" group permissions.\");\n else\n return new Response(false, \"Removed \" + deleted + \" of \" + toDelete.size() + \" group permissions.\");\n\n } else\n return new Response(false, \"Group does not exist.\");\n }\n\n public Response removeGroupPermissionsBase(final int groupId) {\n Group group = getGroup(groupId);\n if (group != null) {\n List<Permission> groupPermissions = group.getOwnPermissions();\n\n if (groupPermissions.size() <= 0)\n return new Response(false, \"Group does not have any permissions.\");\n\n DBResult result = db.deleteGroupPermissions(groupId);\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Removed \" + result.rowsChanged() + \" permissions from the group.\");\n\n } else\n return new Response(false, \"Group does not exist.\");\n }\n\n public Response addGroupParentBase(final int groupId, final int parentGroupId) {\n Group group = getGroup(groupId);\n if (group != null) {\n Group parentGroup = getGroup(parentGroupId);\n if (parentGroup != null) {\n if (group.getParents().contains(parentGroup))\n return new Response(false, \"Group already has the specified parent.\");\n\n boolean inserted = db.insertGroupParent(groupId, parentGroupId);\n if (inserted) {\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Added parent to group.\");\n } else\n return new Response(false, \"Could not add parent to group. Check console for errors.\");\n\n } else\n return new Response(false, \"Parent group does not exist.\");\n } else\n return new Response(false, \"Group does not exist.\");\n }\n\n public Response removeGroupParentBase(final int groupId, final int parentGroupId) {\n Group group = getGroup(groupId);\n if (group != null) {\n Group parentGroup = getGroup(parentGroupId);\n if (parentGroup != null) {\n if (!group.getParents().contains(parentGroup))\n return new Response(false, \"Group does not have the specified parent.\");\n boolean deleted = db.deleteGroupParent(groupId, parentGroupId);\n if (deleted) {\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Removed parent from group.\");\n } else\n return new Response(false, \"Could not remove parent from group. Check console for errors.\");\n } else\n return new Response(false, \"Parent group does not exist.\");\n } else\n return new Response(false, \"Group does not exist.\");\n }\n\n public Response setGroupPrefixBase(final int groupId, final String prefix, final String server) {\n String tempServer = server;\n if (server.equalsIgnoreCase(\"all\"))\n tempServer = \"\";\n tempServer = tempServer.toLowerCase();\n final String finalServer = server;\n\n final Group group = getGroup(groupId);\n if (group == null)\n return new Response(false, \"Group does not exist.\");\n\n // Run async while editing db\n HashMap<String, String> currentPrefix = group.getPrefixes();\n if (prefix.isEmpty() || currentPrefix.containsKey(finalServer)) {\n boolean deleted = db.deleteGroupPrefix(groupId, currentPrefix.get(finalServer), finalServer);\n if (!deleted)\n return new Response(false, \"Could not delete group prefix. Check console for errors.\");\n }\n if (!prefix.isEmpty()) {\n boolean inserted = db.insertGroupPrefix(groupId, prefix, finalServer);\n if (!inserted)\n return new Response(false, \"Could not add group prefix. Check console for errors.\");\n }\n\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Group prefix set.\");\n }\n\n public Response setGroupSuffixBase(final int groupId, final String suffix, final String server) {\n String tempServer = server;\n if (server.equalsIgnoreCase(\"all\"))\n tempServer = \"\";\n tempServer = tempServer.toLowerCase();\n final String finalServer = server;\n\n final Group group = getGroup(groupId);\n if (group == null)\n return new Response(false, \"Group does not exist.\");\n // Run async while editing db\n HashMap<String, String> currentSuffix = group.getPrefixes();\n if (suffix.isEmpty() || currentSuffix.containsKey(finalServer)) {\n boolean deleted = db.deleteGroupSuffix(groupId, currentSuffix.get(finalServer), finalServer);\n if (!deleted)\n return new Response(false, \"Could not delete group suffix. Check console for errors.\");\n }\n if (!suffix.isEmpty()) {\n boolean inserted = db.insertGroupSuffix(groupId, suffix, finalServer);\n if (!inserted)\n return new Response(false, \"Could not add group suffix. Check console for errors.\");\n }\n\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Group suffix set.\");\n }\n\n public Response setGroupLadderBase(final int groupId, final String ladder) {\n String tempLadder = ladder;\n if (ladder == null || ladder.isEmpty())\n tempLadder = \"default\";\n\n Group group = getGroup(groupId);\n if (group == null)\n return new Response(false, \"Group does not exist.\");\n\n boolean success = db.setGroupLadder(groupId, tempLadder);\n if (success) {\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Group ladder set.\");\n } else\n return new Response(false, \"Could not set group ladder. Check console for errors.\");\n }\n\n public Response setGroupRankBase(final int groupId, final int rank) {\n Group group = getGroup(groupId);\n if (group == null)\n return new Response(false, \"Group does not exist.\");\n\n boolean success = db.setGroupRank(groupId, rank);\n if (success) {\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Group rank set.\");\n } else\n return new Response(false, \"Could not set group rank. Check console for errors.\");\n }\n\n public Response setGroupNameBase(final int groupId, final String name) {\n Group group = getGroup(groupId);\n if (group == null)\n return new Response(false, \"Group does not exist.\");\n\n boolean success = db.setGroupName(groupId, name);\n if (success) {\n loadGroups(true);\n notifyReloadGroups();\n return new Response(true, \"Group name set.\");\n } else\n return new Response(false, \"Could not set group name. Check console for errors.\");\n }\n\n}",
"public class PermissionPlayerBase extends PermissionContainer implements PermissionPlayer {\n\n protected LinkedHashMap<String, List<CachedGroup>> groups = new LinkedHashMap<>(); // Contains -all- groups for this player.\n\n protected List<Group> currentGroups = new ArrayList<>();\n\n protected String prefix = \"\";\n protected String suffix = \"\";\n protected static PowerfulPermsPlugin plugin;\n protected boolean isDefault = false;\n\n protected ReentrantLock asyncGroupLock = new ReentrantLock();\n\n public PermissionPlayerBase(LinkedHashMap<String, List<CachedGroup>> groups, List<Permission> permissions, String prefix, String suffix, PowerfulPermsPlugin plugin, boolean isDefault) {\n super(permissions);\n this.groups = groups;\n this.prefix = prefix;\n this.suffix = suffix;\n PermissionPlayerBase.plugin = plugin;\n this.isDefault = isDefault;\n }\n\n public void update(PermissionPlayerBase base) {\n this.groups = base.groups;\n this.ownPermissions = base.ownPermissions;\n this.prefix = base.prefix;\n this.suffix = base.suffix;\n this.isDefault = base.isDefault;\n }\n\n public void updateGroups(String server) {\n if (server == null || server.equalsIgnoreCase(\"all\"))\n server = \"\";\n\n this.currentGroups = getGroups(server);\n }\n\n public void setGroups(LinkedHashMap<String, List<CachedGroup>> groups) {\n asyncGroupLock.lock();\n try {\n this.groups = groups;\n } finally {\n asyncGroupLock.unlock();\n }\n }\n\n /**\n * Returns all groups a player has, including primary groups, indexed by server name.\n */\n @Override\n public LinkedHashMap<String, List<CachedGroup>> getCachedGroups() {\n LinkedHashMap<String, List<CachedGroup>> output = new LinkedHashMap<>();\n asyncGroupLock.lock();\n try {\n for (Entry<String, List<CachedGroup>> entry : this.groups.entrySet()) {\n output.put(entry.getKey(), new ArrayList<>(entry.getValue()));\n }\n } finally {\n asyncGroupLock.unlock();\n }\n return output;\n }\n\n public static List<CachedGroup> getCachedGroups(String server, LinkedHashMap<String, List<CachedGroup>> groups) {\n List<CachedGroup> tempGroups = new ArrayList<>();\n\n // Get server specific groups and add them\n List<CachedGroup> serverGroupsTemp = groups.get(server);\n if (serverGroupsTemp != null)\n tempGroups.addAll(serverGroupsTemp);\n\n // Get groups that apply on all servers and add them\n if (!server.isEmpty()) {\n List<CachedGroup> all = groups.get(\"\");\n if (all != null)\n tempGroups.addAll(all);\n }\n\n return tempGroups;\n }\n\n /**\n * Returns a list of cached groups which apply to a specific server.\n */\n @Override\n public List<CachedGroup> getCachedGroups(String server) {\n asyncGroupLock.lock();\n try {\n return getCachedGroups(server, this.groups);\n } finally {\n asyncGroupLock.unlock();\n }\n }\n\n public static List<Group> getGroups(List<CachedGroup> groups, PowerfulPermsPlugin plugin) {\n List<Group> output = new ArrayList<>();\n\n Iterator<CachedGroup> it1 = groups.iterator();\n while (it1.hasNext()) {\n CachedGroup cachedGroup = it1.next();\n if (!cachedGroup.isNegated()) {\n Group group = plugin.getPermissionManager().getGroup(cachedGroup.getGroupId());\n if (group != null) {\n output.add(group);\n it1.remove();\n }\n }\n }\n\n // Remaining groups are negated\n for (CachedGroup cachedGroup : groups) {\n Iterator<Group> it2 = output.iterator();\n while (it2.hasNext()) {\n Group temp = it2.next();\n if (temp.getId() == cachedGroup.getGroupId()) {\n it2.remove();\n plugin.debug(\"Removed negated group \" + temp.getId());\n }\n }\n }\n return output;\n }\n\n /**\n * Returns a list of groups which apply to a specific server. Removes negated groups.\n */\n @Override\n public List<Group> getGroups(String server) {\n return getGroups(getCachedGroups(server), plugin);\n }\n\n /**\n * Returns a list of groups which apply to the current server.\n */\n @Override\n public List<Group> getGroups() {\n return new ArrayList<>(this.currentGroups);\n }\n\n /**\n * Returns the player's group on a specific ladder.\n */\n @Override\n public Group getGroup(String ladder) {\n List<Group> input = getGroups();\n TreeMap<Integer, Group> sortedGroups = new TreeMap<>();\n // Sort groups by rank if same ladder\n for (Group group : input) {\n if (group.getLadder().equalsIgnoreCase(ladder)) {\n sortedGroups.put(group.getRank(), group);\n }\n }\n\n Iterator<Group> it = sortedGroups.descendingMap().values().iterator();\n if (it.hasNext()) {\n return it.next();\n }\n return null;\n }\n\n public static Group getPrimaryGroup(List<Group> input) {\n TreeMap<Integer, List<Group>> sortedGroups = new TreeMap<>();\n\n for (Group group : input) {\n List<Group> temp = sortedGroups.get(group.getRank());\n if (temp == null)\n temp = new ArrayList<>();\n temp.add(group);\n sortedGroups.put(group.getRank(), temp);\n }\n\n for (List<Group> tempGroups : sortedGroups.descendingMap().values()) {\n for (Group group : tempGroups) {\n if (group != null)\n return group;\n }\n }\n return null;\n }\n\n /**\n * Returns the group with highest rank value across all ladders of the player.\n */\n @Override\n public Group getPrimaryGroup() {\n return getPrimaryGroup(getGroups());\n }\n\n public static String getPrefix(String ladder, List<Group> input) {\n TreeMap<Integer, List<Group>> sortedGroups = new TreeMap<>();\n\n // Insert groups by rank value\n for (Group group : input) {\n if (ladder == null || group.getLadder().equalsIgnoreCase(ladder)) {\n List<Group> temp = sortedGroups.get(group.getRank());\n if (temp == null)\n temp = new ArrayList<>();\n temp.add(group);\n sortedGroups.put(group.getRank(), temp);\n }\n }\n\n // Return prefix from group with highest rank, if not found, move on to next rank\n for (List<Group> tempGroups : sortedGroups.descendingMap().values()) {\n for (Group group : tempGroups) {\n String prefix = group.getPrefix(PermissionManagerBase.serverName);\n if (!prefix.isEmpty())\n return prefix;\n }\n }\n return null;\n }\n\n /**\n * Returns the player's prefix on a specific ladder.\n */\n @Override\n public String getPrefix(String ladder) {\n return getPrefix(ladder, getGroups());\n }\n\n public static String getSuffix(String ladder, List<Group> input) {\n TreeMap<Integer, List<Group>> sortedGroups = new TreeMap<>();\n\n // Insert groups by rank value\n for (Group group : input) {\n if (ladder == null || group.getLadder().equalsIgnoreCase(ladder)) {\n List<Group> temp = sortedGroups.get(group.getRank());\n if (temp == null)\n temp = new ArrayList<>();\n temp.add(group);\n sortedGroups.put(group.getRank(), temp);\n }\n }\n\n // Return suffix from group with highest rank, if not found, move on to next rank\n for (List<Group> tempGroups : sortedGroups.descendingMap().values()) {\n for (Group group : tempGroups) {\n String suffix = group.getSuffix(PermissionManagerBase.serverName);\n if (!suffix.isEmpty())\n return suffix;\n }\n }\n return null;\n }\n\n /**\n * Returns the player's suffix on a specific ladder.\n */\n @Override\n public String getSuffix(String ladder) {\n return getSuffix(ladder, getGroups());\n }\n\n public static String getPrefix(List<Group> input, String ownPrefix) {\n if (!ownPrefix.isEmpty())\n return ownPrefix;\n return getPrefix(null, input);\n }\n\n /**\n * Returns the player's prefix from the group with highest rank across all ladders.\n */\n @Override\n public String getPrefix() {\n if (!prefix.isEmpty())\n return prefix;\n return getPrefix(null, getGroups());\n }\n\n public static String getSuffix(List<Group> input, String ownSuffix) {\n if (!ownSuffix.isEmpty())\n return ownSuffix;\n return getSuffix(null, input);\n }\n\n /**\n * Returns the player's suffix from the group with highest rank across all ladders.\n */\n @Override\n public String getSuffix() {\n if (!suffix.isEmpty())\n return suffix;\n return getSuffix(null, getGroups());\n }\n\n /**\n * Returns the player's own prefix.\n */\n @Override\n public String getOwnPrefix() {\n return prefix;\n }\n\n /**\n * Returns the player's own suffix.\n */\n @Override\n public String getOwnSuffix() {\n return suffix;\n }\n\n public static List<Permission> getAllPermissions(List<Group> input, PermissionContainer out, PowerfulPermsPlugin plugin) {\n ArrayList<Permission> unprocessedPerms = new ArrayList<>();\n\n // Add permissions from groups in normal order.\n plugin.debug(\"groups count \" + input.size());\n TreeMap<Integer, List<Group>> sortedGroups = new TreeMap<>();\n\n // Insert groups by rank value\n for (Group group : input) {\n List<Group> temp = sortedGroups.get(group.getRank());\n if (temp == null)\n temp = new ArrayList<>();\n temp.add(group);\n sortedGroups.put(group.getRank(), temp);\n }\n\n // Add permissions from sorted groups\n for (List<Group> tempGroups : sortedGroups.values()) {\n for (Group group : tempGroups) {\n unprocessedPerms.addAll(group.getPermissions());\n }\n }\n\n // Add own permissions.\n unprocessedPerms.addAll(out.ownPermissions);\n return unprocessedPerms;\n }\n\n public static List<String> calculatePermissions(String playerServer, String playerWorld, List<Group> input, PermissionContainer out, PowerfulPermsPlugin plugin) {\n return calculatePermissions(playerServer, playerWorld, input, out, getAllPermissions(input, out, plugin), plugin);\n }\n\n public static List<String> calculatePermissions(String playerServer, String playerWorld, List<Group> input, PermissionContainer out, List<Permission> unprocessedPerms,\n PowerfulPermsPlugin plugin) {\n List<String> output = new ArrayList<>();\n\n for (Permission e : unprocessedPerms) {\n if (PermissionContainer.permissionApplies(e, playerServer, playerWorld)) {\n output.add(e.getPermissionString());\n }\n }\n\n if (plugin.isDebug()) {\n for (String perm : output) {\n plugin.debug(\"base added perm \" + perm);\n }\n }\n\n return output;\n }\n\n @Override\n public boolean isDefault() {\n return isDefault;\n }\n\n}",
"public class CachedGroup {\n private int id;\n private int groupId;\n private boolean negated;\n private Date expires;\n private int expireTaskId = -1;\n\n public CachedGroup(int id, int groupId, boolean negated, Date expires) {\n this.id = id;\n this.groupId = groupId;\n this.negated = negated;\n this.expires = expires;\n }\n\n public int getId() {\n return this.id;\n }\n\n public int getGroupId() {\n return this.groupId;\n }\n\n public boolean isNegated() {\n return this.negated;\n }\n\n public Date getExpirationDate() {\n return expires;\n }\n\n public boolean willExpire() {\n return expires != null;\n }\n\n public boolean hasExpired() {\n return willExpire() && getExpirationDate().before(new Date());\n }\n\n public int getExpireTaskId() {\n return expireTaskId;\n }\n\n public void setExpireTaskId(int taskId) {\n this.expireTaskId = taskId;\n }\n}",
"public interface Permission {\n\n /**\n * Returns the ID of this permission as it is stored in the database.\n */\n public int getId();\n\n /**\n * Returns the permission string.\n */\n public String getPermissionString();\n\n /**\n * Returns the name of the world the permission applies to.\n */\n public String getWorld();\n\n /**\n * Returns the name of the server the permission applies to. If empty or \"all\", applies to all servers.\n */\n public String getServer();\n\n /**\n * Returns the date when this permission expires. If no expiration date, it is null.\n */\n public Date getExpirationDate();\n\n /*\n * Returns true if this is a timed permission.\n */\n public boolean willExpire();\n\n /*\n * Returns true if this is a timed permission and has expired.\n */\n public boolean hasExpired();\n\n}",
"public interface PowerfulPermsPlugin {\n\n public PermissionManager getPermissionManager();\n\n public Logger getLogger();\n\n public void runTaskAsynchronously(Runnable runnable);\n\n public void runTaskLater(Runnable runnable, int delay);\n\n public boolean isDebug();\n\n public ServerMode getServerMode();\n\n public boolean isPlayerOnline(UUID uuid);\n\n public boolean isPlayerOnline(String name);\n\n public UUID getPlayerUUID(String name);\n\n public String getPlayerName(UUID uuid);\n\n public Map<UUID, String> getOnlinePlayers();\n\n public void sendPlayerMessage(String name, String message);\n\n public void debug(String message);\n\n public int getOldVersion();\n\n public String getVersion();\n\n public void loadConfig();\n \n public boolean isBungeeCord();\n}"
] | import com.github.gustav9797.PowerfulPerms.common.PermissionManagerBase;
import com.github.gustav9797.PowerfulPerms.common.PermissionPlayerBase;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.github.gustav9797.PowerfulPermsAPI.CachedGroup;
import com.github.gustav9797.PowerfulPermsAPI.Permission;
import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin; | package com.github.gustav9797.PowerfulPerms;
public class PowerfulPermissionPlayer extends PermissionPlayerBase {
private Player player;
| public PowerfulPermissionPlayer(Player p, LinkedHashMap<String, List<CachedGroup>> serverGroups, List<Permission> permissions, String prefix, String suffix, PowerfulPermsPlugin plugin, | 3 |
treasure-lau/CSipSimple | app/src/main/java/com/csipsimple/ui/incall/InCallCard.java | [
"public abstract class UtilityWrapper {\n\n private static UtilityWrapper instance;\n\n public static UtilityWrapper getInstance() {\n if (instance == null) {\n if (Build.VERSION.SDK_INT >= 16) {\n instance = new Utility16();\n } else if (Build.VERSION.SDK_INT >= 14) {\n instance = new Utility14();\n } else if (Build.VERSION.SDK_INT >= 11) {\n instance = new Utility11();\n } else if (Build.VERSION.SDK_INT >= 8) {\n instance = new Utility8();\n } else if (Build.VERSION.SDK_INT >= 7) {\n instance = new Utility7();\n } else {\n instance = new Utility4();\n }\n }\n\n return instance;\n }\n \n public abstract void viewSetActivated(View view, boolean activated);\n \n public abstract boolean hasPermanentMenuKey(ViewConfiguration vcfg);\n \n public abstract void jumpDrawablesToCurrentState(View v);\n \n public abstract Drawable getActivityLogo(Context context);\n \n public abstract CharSequence stringToUpper(CharSequence text);\n \n public abstract PopupWindow buildPopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes);\n\n public abstract void jumpToCurrentState(Drawable indeterminateDrawable);\n \n public abstract int resolveSizeAndState(int size, int measureSpec, int state);\n \n public abstract int getMeasuredState(View child);\n \n public abstract int combineMeasuredStates(int curState, int newState);\n \n public abstract boolean isLongPressEvent(KeyEvent evt);\n \n public abstract void setBackgroundDrawable(View v, Drawable d);\n \n public abstract void setLinearLayoutDividerPadding(LinearLayout l, int padding);\n \n public abstract void setLinearLayoutDividerDrawable(LinearLayout l, Drawable drawable);\n \n public static Method safelyGetSuperclassMethod(Class<?> cls, String methodName, Class<?>... parametersType) {\n Class<?> sCls = cls.getSuperclass();\n while(sCls != Object.class) {\n try {\n return sCls.getDeclaredMethod(methodName, parametersType);\n } catch (NoSuchMethodException e) {\n // Just super it again\n }\n sCls = sCls.getSuperclass();\n }\n throw new RuntimeException(\"Method not found \" + methodName);\n }\n \n public static Object safelyInvokeMethod(Method method, Object receiver, Object... args) {\n try {\n return method.invoke(receiver, args);\n } catch (IllegalArgumentException e) {\n Log.e(\"Safe invoke fail\", \"Invalid args\", e);\n } catch (IllegalAccessException e) {\n Log.e(\"Safe invoke fail\", \"Invalid access\", e);\n } catch (InvocationTargetException e) {\n Log.e(\"Safe invoke fail\", \"Invalid target\", e);\n }\n \n return null;\n }\n \n}",
"public class ActionMenuPresenter extends BaseMenuPresenter\n implements ActionProvider.SubUiVisibilityListener {\n //UNUSED private static final String TAG = \"ActionMenuPresenter\";\n\n private View mOverflowButton;\n private boolean mReserveOverflow;\n private boolean mReserveOverflowSet;\n private int mWidthLimit;\n private int mActionItemWidthLimit;\n private int mMaxItems;\n private boolean mMaxItemsSet;\n private boolean mStrictWidthLimit;\n private boolean mWidthLimitSet;\n private boolean mExpandedActionViewsExclusive;\n\n private int mMinCellSize;\n\n // Group IDs that have been added as actions - used temporarily, allocated here for reuse.\n private final SparseBooleanArray mActionButtonGroups = new SparseBooleanArray();\n\n private View mScrapActionButtonView;\n\n private OverflowPopup mOverflowPopup;\n private ActionButtonSubmenu mActionButtonPopup;\n\n private OpenOverflowRunnable mPostedOpenRunnable;\n\n final PopupPresenterCallback mPopupPresenterCallback = new PopupPresenterCallback();\n int mOpenSubMenuId;\n\n public ActionMenuPresenter(Context context) {\n super(context, R.layout.abs__action_menu_layout,\n R.layout.abs__action_menu_item_layout);\n }\n\n @Override\n public void initForMenu(Context context, MenuBuilder menu) {\n super.initForMenu(context, menu);\n\n final Resources res = context.getResources();\n\n if (!mReserveOverflowSet) {\n mReserveOverflow = reserveOverflow(mContext);\n }\n\n if (!mWidthLimitSet) {\n mWidthLimit = res.getDisplayMetrics().widthPixels / 2;\n }\n\n // Measure for initial configuration\n if (!mMaxItemsSet) {\n mMaxItems = getResources_getInteger(context, R.integer.abs__max_action_buttons);\n }\n\n int width = mWidthLimit;\n if (mReserveOverflow) {\n if (mOverflowButton == null) {\n mOverflowButton = new OverflowMenuButton(mSystemContext);\n final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);\n mOverflowButton.measure(spec, spec);\n }\n width -= mOverflowButton.getMeasuredWidth();\n } else {\n mOverflowButton = null;\n }\n\n mActionItemWidthLimit = width;\n\n mMinCellSize = (int) (ActionMenuView.MIN_CELL_SIZE * res.getDisplayMetrics().density);\n\n // Drop a scrap view as it may no longer reflect the proper context/config.\n mScrapActionButtonView = null;\n }\n\n public static boolean reserveOverflow(Context context) {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB);\n } else {\n return !HasPermanentMenuKey.get(context);\n }\n }\n\n private static class HasPermanentMenuKey {\n public static boolean get(Context context) {\n return ViewConfiguration.get(context).hasPermanentMenuKey();\n }\n }\n\n public void onConfigurationChanged(Configuration newConfig) {\n if (!mMaxItemsSet) {\n mMaxItems = getResources_getInteger(mContext,\n R.integer.abs__max_action_buttons);\n if (mMenu != null) {\n mMenu.onItemsChanged(true);\n }\n }\n }\n\n public void setWidthLimit(int width, boolean strict) {\n mWidthLimit = width;\n mStrictWidthLimit = strict;\n mWidthLimitSet = true;\n }\n\n public void setReserveOverflow(boolean reserveOverflow) {\n mReserveOverflow = reserveOverflow;\n mReserveOverflowSet = true;\n }\n\n public void setItemLimit(int itemCount) {\n mMaxItems = itemCount;\n mMaxItemsSet = true;\n }\n\n public void setExpandedActionViewsExclusive(boolean isExclusive) {\n mExpandedActionViewsExclusive = isExclusive;\n }\n\n @Override\n public MenuView getMenuView(ViewGroup root) {\n MenuView result = super.getMenuView(root);\n ((ActionMenuView) result).setPresenter(this);\n return result;\n }\n\n @Override\n public View getItemView(MenuItemImpl item, View convertView, ViewGroup parent) {\n View actionView = item.getActionView();\n if (actionView == null || item.hasCollapsibleActionView()) {\n if (!(convertView instanceof ActionMenuItemView)) {\n convertView = null;\n }\n actionView = super.getItemView(item, convertView, parent);\n }\n actionView.setVisibility(item.isActionViewExpanded() ? View.GONE : View.VISIBLE);\n\n final ActionMenuView menuParent = (ActionMenuView) parent;\n final ViewGroup.LayoutParams lp = actionView.getLayoutParams();\n if (!menuParent.checkLayoutParams(lp)) {\n actionView.setLayoutParams(menuParent.generateLayoutParams(lp));\n }\n return actionView;\n }\n\n @Override\n public void bindItemView(MenuItemImpl item, MenuView.ItemView itemView) {\n itemView.initialize(item, 0);\n\n final ActionMenuView menuView = (ActionMenuView) mMenuView;\n ActionMenuItemView actionItemView = (ActionMenuItemView) itemView;\n actionItemView.setItemInvoker(menuView);\n }\n\n @Override\n public boolean shouldIncludeItem(int childIndex, MenuItemImpl item) {\n return item.isActionButton();\n }\n\n @Override\n public void updateMenuView(boolean cleared) {\n super.updateMenuView(cleared);\n\n if (mMenu != null) {\n final ArrayList<MenuItemImpl> actionItems = mMenu.getActionItems();\n final int count = actionItems.size();\n for (int i = 0; i < count; i++) {\n final ActionProvider provider = actionItems.get(i).getActionProvider();\n if (provider != null) {\n provider.setSubUiVisibilityListener(this);\n }\n }\n }\n\n final ArrayList<MenuItemImpl> nonActionItems = mMenu != null ?\n mMenu.getNonActionItems() : null;\n\n boolean hasOverflow = false;\n if (mReserveOverflow && nonActionItems != null) {\n final int count = nonActionItems.size();\n if (count == 1) {\n hasOverflow = !nonActionItems.get(0).isActionViewExpanded();\n } else {\n hasOverflow = count > 0;\n }\n }\n\n if (hasOverflow) {\n if (mOverflowButton == null) {\n mOverflowButton = new OverflowMenuButton(mSystemContext);\n }\n ViewGroup parent = (ViewGroup) mOverflowButton.getParent();\n if (parent != mMenuView) {\n if (parent != null) {\n parent.removeView(mOverflowButton);\n }\n ActionMenuView menuView = (ActionMenuView) mMenuView;\n menuView.addView(mOverflowButton, menuView.generateOverflowButtonLayoutParams());\n }\n } else if (mOverflowButton != null && mOverflowButton.getParent() == mMenuView) {\n ((ViewGroup) mMenuView).removeView(mOverflowButton);\n }\n\n ((ActionMenuView) mMenuView).setOverflowReserved(mReserveOverflow);\n }\n\n @Override\n public boolean filterLeftoverView(ViewGroup parent, int childIndex) {\n if (parent.getChildAt(childIndex) == mOverflowButton) return false;\n return super.filterLeftoverView(parent, childIndex);\n }\n\n public boolean onSubMenuSelected(SubMenuBuilder subMenu) {\n if (!subMenu.hasVisibleItems()) return false;\n\n SubMenuBuilder topSubMenu = subMenu;\n while (topSubMenu.getParentMenu() != mMenu) {\n topSubMenu = (SubMenuBuilder) topSubMenu.getParentMenu();\n }\n View anchor = findViewForItem(topSubMenu.getItem());\n if (anchor == null) {\n if (mOverflowButton == null) return false;\n anchor = mOverflowButton;\n }\n\n mOpenSubMenuId = subMenu.getItem().getItemId();\n mActionButtonPopup = new ActionButtonSubmenu(mContext, subMenu);\n mActionButtonPopup.setAnchorView(anchor);\n mActionButtonPopup.show();\n super.onSubMenuSelected(subMenu);\n return true;\n }\n\n private View findViewForItem(MenuItem item) {\n final ViewGroup parent = (ViewGroup) mMenuView;\n if (parent == null) return null;\n\n final int count = parent.getChildCount();\n for (int i = 0; i < count; i++) {\n final View child = parent.getChildAt(i);\n if (child instanceof MenuView.ItemView &&\n ((MenuView.ItemView) child).getItemData() == item) {\n return child;\n }\n }\n return null;\n }\n\n /**\n * Display the overflow menu if one is present.\n * @return true if the overflow menu was shown, false otherwise.\n */\n public boolean showOverflowMenu() {\n if (mReserveOverflow && !isOverflowMenuShowing() && mMenu != null && mMenuView != null &&\n mPostedOpenRunnable == null && !mMenu.getNonActionItems().isEmpty()) {\n OverflowPopup popup = new OverflowPopup(mContext, mMenu, mOverflowButton, true);\n mPostedOpenRunnable = new OpenOverflowRunnable(popup);\n // Post this for later; we might still need a layout for the anchor to be right.\n ((View) mMenuView).post(mPostedOpenRunnable);\n\n // ActionMenuPresenter uses null as a callback argument here\n // to indicate overflow is opening.\n super.onSubMenuSelected(null);\n\n return true;\n }\n return false;\n }\n\n /**\n * Hide the overflow menu if it is currently showing.\n *\n * @return true if the overflow menu was hidden, false otherwise.\n */\n public boolean hideOverflowMenu() {\n if (mPostedOpenRunnable != null && mMenuView != null) {\n ((View) mMenuView).removeCallbacks(mPostedOpenRunnable);\n mPostedOpenRunnable = null;\n return true;\n }\n\n MenuPopupHelper popup = mOverflowPopup;\n if (popup != null) {\n popup.dismiss();\n return true;\n }\n return false;\n }\n\n /**\n * Dismiss all popup menus - overflow and submenus.\n * @return true if popups were dismissed, false otherwise. (This can be because none were open.)\n */\n public boolean dismissPopupMenus() {\n boolean result = hideOverflowMenu();\n result |= hideSubMenus();\n return result;\n }\n\n /**\n * Dismiss all submenu popups.\n *\n * @return true if popups were dismissed, false otherwise. (This can be because none were open.)\n */\n public boolean hideSubMenus() {\n if (mActionButtonPopup != null) {\n mActionButtonPopup.dismiss();\n return true;\n }\n return false;\n }\n\n /**\n * @return true if the overflow menu is currently showing\n */\n public boolean isOverflowMenuShowing() {\n return mOverflowPopup != null && mOverflowPopup.isShowing();\n }\n\n /**\n * @return true if space has been reserved in the action menu for an overflow item.\n */\n public boolean isOverflowReserved() {\n return mReserveOverflow;\n }\n\n public boolean flagActionItems() {\n final ArrayList<MenuItemImpl> visibleItems = mMenu.getVisibleItems();\n final int itemsSize = visibleItems.size();\n int maxActions = mMaxItems;\n int widthLimit = mActionItemWidthLimit;\n final int querySpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);\n final ViewGroup parent = (ViewGroup) mMenuView;\n\n int requiredItems = 0;\n int requestedItems = 0;\n int firstActionWidth = 0;\n boolean hasOverflow = false;\n for (int i = 0; i < itemsSize; i++) {\n MenuItemImpl item = visibleItems.get(i);\n if (item.requiresActionButton()) {\n requiredItems++;\n } else if (item.requestsActionButton()) {\n requestedItems++;\n } else {\n hasOverflow = true;\n }\n if (mExpandedActionViewsExclusive && item.isActionViewExpanded()) {\n // Overflow everything if we have an expanded action view and we're\n // space constrained.\n maxActions = 0;\n }\n }\n\n // Reserve a spot for the overflow item if needed.\n if (mReserveOverflow &&\n (hasOverflow || requiredItems + requestedItems > maxActions)) {\n maxActions--;\n }\n maxActions -= requiredItems;\n\n final SparseBooleanArray seenGroups = mActionButtonGroups;\n seenGroups.clear();\n\n int cellSize = 0;\n int cellsRemaining = 0;\n if (mStrictWidthLimit) {\n cellsRemaining = widthLimit / mMinCellSize;\n final int cellSizeRemaining = widthLimit % mMinCellSize;\n cellSize = mMinCellSize + cellSizeRemaining / cellsRemaining;\n }\n\n // Flag as many more requested items as will fit.\n for (int i = 0; i < itemsSize; i++) {\n MenuItemImpl item = visibleItems.get(i);\n\n if (item.requiresActionButton()) {\n View v = getItemView(item, mScrapActionButtonView, parent);\n if (mScrapActionButtonView == null) {\n mScrapActionButtonView = v;\n }\n if (mStrictWidthLimit) {\n cellsRemaining -= ActionMenuView.measureChildForCells(v,\n cellSize, cellsRemaining, querySpec, 0);\n } else {\n v.measure(querySpec, querySpec);\n }\n final int measuredWidth = v.getMeasuredWidth();\n widthLimit -= measuredWidth;\n if (firstActionWidth == 0) {\n firstActionWidth = measuredWidth;\n }\n final int groupId = item.getGroupId();\n if (groupId != 0) {\n seenGroups.put(groupId, true);\n }\n item.setIsActionButton(true);\n } else if (item.requestsActionButton()) {\n // Items in a group with other items that already have an action slot\n // can break the max actions rule, but not the width limit.\n final int groupId = item.getGroupId();\n final boolean inGroup = seenGroups.get(groupId);\n boolean isAction = (maxActions > 0 || inGroup) && widthLimit > 0 &&\n (!mStrictWidthLimit || cellsRemaining > 0);\n\n if (isAction) {\n View v = getItemView(item, mScrapActionButtonView, parent);\n if (mScrapActionButtonView == null) {\n mScrapActionButtonView = v;\n }\n if (mStrictWidthLimit) {\n final int cells = ActionMenuView.measureChildForCells(v,\n cellSize, cellsRemaining, querySpec, 0);\n cellsRemaining -= cells;\n if (cells == 0) {\n isAction = false;\n }\n } else {\n v.measure(querySpec, querySpec);\n }\n final int measuredWidth = v.getMeasuredWidth();\n widthLimit -= measuredWidth;\n if (firstActionWidth == 0) {\n firstActionWidth = measuredWidth;\n }\n\n if (mStrictWidthLimit) {\n isAction &= widthLimit >= 0;\n } else {\n // Did this push the entire first item past the limit?\n isAction &= widthLimit + firstActionWidth > 0;\n }\n }\n\n if (isAction && groupId != 0) {\n seenGroups.put(groupId, true);\n } else if (inGroup) {\n // We broke the width limit. Demote the whole group, they all overflow now.\n seenGroups.put(groupId, false);\n for (int j = 0; j < i; j++) {\n MenuItemImpl areYouMyGroupie = visibleItems.get(j);\n if (areYouMyGroupie.getGroupId() == groupId) {\n // Give back the action slot\n if (areYouMyGroupie.isActionButton()) maxActions++;\n areYouMyGroupie.setIsActionButton(false);\n }\n }\n }\n\n if (isAction) maxActions--;\n\n item.setIsActionButton(isAction);\n }\n }\n return true;\n }\n\n @Override\n public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {\n dismissPopupMenus();\n super.onCloseMenu(menu, allMenusAreClosing);\n }\n\n @Override\n public Parcelable onSaveInstanceState() {\n SavedState state = new SavedState();\n state.openSubMenuId = mOpenSubMenuId;\n return state;\n }\n\n @Override\n public void onRestoreInstanceState(Parcelable state) {\n SavedState saved = (SavedState) state;\n if (saved.openSubMenuId > 0) {\n MenuItem item = mMenu.findItem(saved.openSubMenuId);\n if (item != null) {\n SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu();\n onSubMenuSelected(subMenu);\n }\n }\n }\n\n @Override\n public void onSubUiVisibilityChanged(boolean isVisible) {\n if (isVisible) {\n // Not a submenu, but treat it like one.\n super.onSubMenuSelected(null);\n } else {\n mMenu.close(false);\n }\n }\n\n private static class SavedState implements Parcelable {\n public int openSubMenuId;\n\n SavedState() {\n }\n\n SavedState(Parcel in) {\n openSubMenuId = in.readInt();\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.writeInt(openSubMenuId);\n }\n\n @SuppressWarnings(\"unused\")\n public static final Creator<SavedState> CREATOR\n = new Creator<SavedState>() {\n public SavedState createFromParcel(Parcel in) {\n return new SavedState(in);\n }\n\n public SavedState[] newArray(int size) {\n return new SavedState[size];\n }\n };\n }\n\n private class OverflowMenuButton extends ImageButton implements ActionMenuChildView, View_HasStateListenerSupport {\n private final Set<View_OnAttachStateChangeListener> mListeners = new HashSet<View_OnAttachStateChangeListener>();\n\n public OverflowMenuButton(Context context) {\n super(context, null, R.attr.actionOverflowButtonStyle);\n\n setClickable(true);\n setFocusable(true);\n setVisibility(VISIBLE);\n setEnabled(true);\n }\n\n @Override\n public boolean performClick() {\n if (super.performClick()) {\n return true;\n }\n\n playSoundEffect(SoundEffectConstants.CLICK);\n showOverflowMenu();\n return true;\n }\n\n public boolean needsDividerBefore() {\n return false;\n }\n\n public boolean needsDividerAfter() {\n return false;\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n for (View_OnAttachStateChangeListener listener : mListeners) {\n listener.onViewAttachedToWindow(this);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n for (View_OnAttachStateChangeListener listener : mListeners) {\n listener.onViewDetachedFromWindow(this);\n }\n\n if (mOverflowPopup != null) mOverflowPopup.dismiss();\n }\n\n @Override\n public void addOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) {\n mListeners.add(listener);\n }\n\n @Override\n public void removeOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) {\n mListeners.remove(listener);\n }\n }\n\n private class OverflowPopup extends MenuPopupHelper {\n public OverflowPopup(Context context, MenuBuilder menu, View anchorView,\n boolean overflowOnly) {\n super(context, menu, anchorView, overflowOnly);\n setCallback(mPopupPresenterCallback);\n }\n\n @Override\n public void onDismiss() {\n super.onDismiss();\n mMenu.close();\n mOverflowPopup = null;\n }\n }\n\n private class ActionButtonSubmenu extends MenuPopupHelper {\n //UNUSED private SubMenuBuilder mSubMenu;\n\n public ActionButtonSubmenu(Context context, SubMenuBuilder subMenu) {\n super(context, subMenu);\n //UNUSED mSubMenu = subMenu;\n\n MenuItemImpl item = (MenuItemImpl) subMenu.getItem();\n if (!item.isActionButton()) {\n // Give a reasonable anchor to nested submenus.\n setAnchorView(mOverflowButton == null ? (View) mMenuView : mOverflowButton);\n }\n\n setCallback(mPopupPresenterCallback);\n\n boolean preserveIconSpacing = false;\n final int count = subMenu.size();\n for (int i = 0; i < count; i++) {\n MenuItem childItem = subMenu.getItem(i);\n if (childItem.isVisible() && childItem.getIcon() != null) {\n preserveIconSpacing = true;\n break;\n }\n }\n setForceShowIcon(preserveIconSpacing);\n }\n\n @Override\n public void onDismiss() {\n super.onDismiss();\n mActionButtonPopup = null;\n mOpenSubMenuId = 0;\n }\n }\n\n private class PopupPresenterCallback implements Callback {\n\n @Override\n public boolean onOpenSubMenu(MenuBuilder subMenu) {\n if (subMenu == null) return false;\n\n mOpenSubMenuId = ((SubMenuBuilder) subMenu).getItem().getItemId();\n return false;\n }\n\n @Override\n public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {\n if (menu instanceof SubMenuBuilder) {\n ((SubMenuBuilder) menu).getRootMenu().close(false);\n }\n }\n }\n\n private class OpenOverflowRunnable implements Runnable {\n private OverflowPopup mPopup;\n\n public OpenOverflowRunnable(OverflowPopup popup) {\n mPopup = popup;\n }\n\n public void run() {\n mMenu.changeMenuMode();\n final View menuView = (View) mMenuView;\n if (menuView != null && menuView.getWindowToken() != null && mPopup.tryShow()) {\n mOverflowPopup = mPopup;\n }\n mPostedOpenRunnable = null;\n }\n }\n}",
"public interface MenuItem {\n /*\n * These should be kept in sync with attrs.xml enum constants for showAsAction\n */\n /** Never show this item as a button in an Action Bar. */\n public static final int SHOW_AS_ACTION_NEVER = android.view.MenuItem.SHOW_AS_ACTION_NEVER;\n /** Show this item as a button in an Action Bar if the system decides there is room for it. */\n public static final int SHOW_AS_ACTION_IF_ROOM = android.view.MenuItem.SHOW_AS_ACTION_IF_ROOM;\n /**\n * Always show this item as a button in an Action Bar.\n * Use sparingly! If too many items are set to always show in the Action Bar it can\n * crowd the Action Bar and degrade the user experience on devices with smaller screens.\n * A good rule of thumb is to have no more than 2 items set to always show at a time.\n */\n public static final int SHOW_AS_ACTION_ALWAYS = android.view.MenuItem.SHOW_AS_ACTION_ALWAYS;\n\n /**\n * When this item is in the action bar, always show it with a text label even if\n * it also has an icon specified.\n */\n public static final int SHOW_AS_ACTION_WITH_TEXT = android.view.MenuItem.SHOW_AS_ACTION_WITH_TEXT;\n\n /**\n * This item's action view collapses to a normal menu item.\n * When expanded, the action view temporarily takes over\n * a larger segment of its container.\n */\n public static final int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = android.view.MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW;\n\n /**\n * Interface definition for a callback to be invoked when a menu item is\n * clicked.\n *\n * @see Activity#onContextItemSelected(MenuItem)\n * @see Activity#onOptionsItemSelected(MenuItem)\n */\n public interface OnMenuItemClickListener {\n /**\n * Called when a menu item has been invoked. This is the first code\n * that is executed; if it returns true, no other callbacks will be\n * executed.\n *\n * @param item The menu item that was invoked.\n *\n * @return Return true to consume this click and prevent others from\n * executing.\n */\n public boolean onMenuItemClick(MenuItem item);\n }\n\n /**\n * Interface definition for a callback to be invoked when a menu item\n * marked with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} is\n * expanded or collapsed.\n *\n * @see MenuItem#expandActionView()\n * @see MenuItem#collapseActionView()\n * @see MenuItem#setShowAsActionFlags(int)\n */\n public interface OnActionExpandListener {\n /**\n * Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}\n * is expanded.\n * @param item Item that was expanded\n * @return true if the item should expand, false if expansion should be suppressed.\n */\n public boolean onMenuItemActionExpand(MenuItem item);\n\n /**\n * Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}\n * is collapsed.\n * @param item Item that was collapsed\n * @return true if the item should collapse, false if collapsing should be suppressed.\n */\n public boolean onMenuItemActionCollapse(MenuItem item);\n }\n\n /**\n * Return the identifier for this menu item. The identifier can not\n * be changed after the menu is created.\n *\n * @return The menu item's identifier.\n */\n public int getItemId();\n\n /**\n * Return the group identifier that this menu item is part of. The group\n * identifier can not be changed after the menu is created.\n *\n * @return The menu item's group identifier.\n */\n public int getGroupId();\n\n /**\n * Return the category and order within the category of this item. This\n * item will be shown before all items (within its category) that have\n * order greater than this value.\n * <p>\n * An order integer contains the item's category (the upper bits of the\n * integer; set by or/add the category with the order within the\n * category) and the ordering of the item within that category (the\n * lower bits). Example categories are {@link Menu#CATEGORY_SYSTEM},\n * {@link Menu#CATEGORY_SECONDARY}, {@link Menu#CATEGORY_ALTERNATIVE},\n * {@link Menu#CATEGORY_CONTAINER}. See {@link Menu} for a full list.\n *\n * @return The order of this item.\n */\n public int getOrder();\n\n /**\n * Change the title associated with this item.\n *\n * @param title The new text to be displayed.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setTitle(CharSequence title);\n\n /**\n * Change the title associated with this item.\n * <p>\n * Some menu types do not sufficient space to show the full title, and\n * instead a condensed title is preferred. See {@link Menu} for more\n * information.\n *\n * @param title The resource id of the new text to be displayed.\n * @return This Item so additional setters can be called.\n * @see #setTitleCondensed(CharSequence)\n */\n\n public MenuItem setTitle(int title);\n\n /**\n * Retrieve the current title of the item.\n *\n * @return The title.\n */\n public CharSequence getTitle();\n\n /**\n * Change the condensed title associated with this item. The condensed\n * title is used in situations where the normal title may be too long to\n * be displayed.\n *\n * @param title The new text to be displayed as the condensed title.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setTitleCondensed(CharSequence title);\n\n /**\n * Retrieve the current condensed title of the item. If a condensed\n * title was never set, it will return the normal title.\n *\n * @return The condensed title, if it exists.\n * Otherwise the normal title.\n */\n public CharSequence getTitleCondensed();\n\n /**\n * Change the icon associated with this item. This icon will not always be\n * shown, so the title should be sufficient in describing this item. See\n * {@link Menu} for the menu types that support icons.\n *\n * @param icon The new icon (as a Drawable) to be displayed.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setIcon(Drawable icon);\n\n /**\n * Change the icon associated with this item. This icon will not always be\n * shown, so the title should be sufficient in describing this item. See\n * {@link Menu} for the menu types that support icons.\n * <p>\n * This method will set the resource ID of the icon which will be used to\n * lazily get the Drawable when this item is being shown.\n *\n * @param iconRes The new icon (as a resource ID) to be displayed.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setIcon(int iconRes);\n\n /**\n * Returns the icon for this item as a Drawable (getting it from resources if it hasn't been\n * loaded before).\n *\n * @return The icon as a Drawable.\n */\n public Drawable getIcon();\n\n /**\n * Change the Intent associated with this item. By default there is no\n * Intent associated with a menu item. If you set one, and nothing\n * else handles the item, then the default behavior will be to call\n * {@link android.content.Context#startActivity} with the given Intent.\n *\n * <p>Note that setIntent() can not be used with the versions of\n * {@link Menu#add} that take a Runnable, because {@link Runnable#run}\n * does not return a value so there is no way to tell if it handled the\n * item. In this case it is assumed that the Runnable always handles\n * the item, and the intent will never be started.\n *\n * @see #getIntent\n * @param intent The Intent to associated with the item. This Intent\n * object is <em>not</em> copied, so be careful not to\n * modify it later.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setIntent(Intent intent);\n\n /**\n * Return the Intent associated with this item. This returns a\n * reference to the Intent which you can change as desired to modify\n * what the Item is holding.\n *\n * @see #setIntent\n * @return Returns the last value supplied to {@link #setIntent}, or\n * null.\n */\n public Intent getIntent();\n\n /**\n * Change both the numeric and alphabetic shortcut associated with this\n * item. Note that the shortcut will be triggered when the key that\n * generates the given character is pressed alone or along with with the alt\n * key. Also note that case is not significant and that alphabetic shortcut\n * characters will be displayed in lower case.\n * <p>\n * See {@link Menu} for the menu types that support shortcuts.\n *\n * @param numericChar The numeric shortcut key. This is the shortcut when\n * using a numeric (e.g., 12-key) keyboard.\n * @param alphaChar The alphabetic shortcut key. This is the shortcut when\n * using a keyboard with alphabetic keys.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setShortcut(char numericChar, char alphaChar);\n\n /**\n * Change the numeric shortcut associated with this item.\n * <p>\n * See {@link Menu} for the menu types that support shortcuts.\n *\n * @param numericChar The numeric shortcut key. This is the shortcut when\n * using a 12-key (numeric) keyboard.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setNumericShortcut(char numericChar);\n\n /**\n * Return the char for this menu item's numeric (12-key) shortcut.\n *\n * @return Numeric character to use as a shortcut.\n */\n public char getNumericShortcut();\n\n /**\n * Change the alphabetic shortcut associated with this item. The shortcut\n * will be triggered when the key that generates the given character is\n * pressed alone or along with with the alt key. Case is not significant and\n * shortcut characters will be displayed in lower case. Note that menu items\n * with the characters '\\b' or '\\n' as shortcuts will get triggered by the\n * Delete key or Carriage Return key, respectively.\n * <p>\n * See {@link Menu} for the menu types that support shortcuts.\n *\n * @param alphaChar The alphabetic shortcut key. This is the shortcut when\n * using a keyboard with alphabetic keys.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setAlphabeticShortcut(char alphaChar);\n\n /**\n * Return the char for this menu item's alphabetic shortcut.\n *\n * @return Alphabetic character to use as a shortcut.\n */\n public char getAlphabeticShortcut();\n\n /**\n * Control whether this item can display a check mark. Setting this does\n * not actually display a check mark (see {@link #setChecked} for that);\n * rather, it ensures there is room in the item in which to display a\n * check mark.\n * <p>\n * See {@link Menu} for the menu types that support check marks.\n *\n * @param checkable Set to true to allow a check mark, false to\n * disallow. The default is false.\n * @see #setChecked\n * @see #isCheckable\n * @see Menu#setGroupCheckable\n * @return This Item so additional setters can be called.\n */\n public MenuItem setCheckable(boolean checkable);\n\n /**\n * Return whether the item can currently display a check mark.\n *\n * @return If a check mark can be displayed, returns true.\n *\n * @see #setCheckable\n */\n public boolean isCheckable();\n\n /**\n * Control whether this item is shown with a check mark. Note that you\n * must first have enabled checking with {@link #setCheckable} or else\n * the check mark will not appear. If this item is a member of a group that contains\n * mutually-exclusive items (set via {@link Menu#setGroupCheckable(int, boolean, boolean)},\n * the other items in the group will be unchecked.\n * <p>\n * See {@link Menu} for the menu types that support check marks.\n *\n * @see #setCheckable\n * @see #isChecked\n * @see Menu#setGroupCheckable\n * @param checked Set to true to display a check mark, false to hide\n * it. The default value is false.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setChecked(boolean checked);\n\n /**\n * Return whether the item is currently displaying a check mark.\n *\n * @return If a check mark is displayed, returns true.\n *\n * @see #setChecked\n */\n public boolean isChecked();\n\n /**\n * Sets the visibility of the menu item. Even if a menu item is not visible,\n * it may still be invoked via its shortcut (to completely disable an item,\n * set it to invisible and {@link #setEnabled(boolean) disabled}).\n *\n * @param visible If true then the item will be visible; if false it is\n * hidden.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setVisible(boolean visible);\n\n /**\n * Return the visibility of the menu item.\n *\n * @return If true the item is visible; else it is hidden.\n */\n public boolean isVisible();\n\n /**\n * Sets whether the menu item is enabled. Disabling a menu item will not\n * allow it to be invoked via its shortcut. The menu item will still be\n * visible.\n *\n * @param enabled If true then the item will be invokable; if false it is\n * won't be invokable.\n * @return This Item so additional setters can be called.\n */\n public MenuItem setEnabled(boolean enabled);\n\n /**\n * Return the enabled state of the menu item.\n *\n * @return If true the item is enabled and hence invokable; else it is not.\n */\n public boolean isEnabled();\n\n /**\n * Check whether this item has an associated sub-menu. I.e. it is a\n * sub-menu of another menu.\n *\n * @return If true this item has a menu; else it is a\n * normal item.\n */\n public boolean hasSubMenu();\n\n /**\n * Get the sub-menu to be invoked when this item is selected, if it has\n * one. See {@link #hasSubMenu()}.\n *\n * @return The associated menu if there is one, else null\n */\n public SubMenu getSubMenu();\n\n /**\n * Set a custom listener for invocation of this menu item. In most\n * situations, it is more efficient and easier to use\n * {@link Activity#onOptionsItemSelected(MenuItem)} or\n * {@link Activity#onContextItemSelected(MenuItem)}.\n *\n * @param menuItemClickListener The object to receive invokations.\n * @return This Item so additional setters can be called.\n * @see Activity#onOptionsItemSelected(MenuItem)\n * @see Activity#onContextItemSelected(MenuItem)\n */\n public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener);\n\n /**\n * Gets the extra information linked to this menu item. This extra\n * information is set by the View that added this menu item to the\n * menu.\n *\n * @see OnCreateContextMenuListener\n * @return The extra information linked to the View that added this\n * menu item to the menu. This can be null.\n */\n public ContextMenuInfo getMenuInfo();\n\n /**\n * Sets how this item should display in the presence of an Action Bar.\n * The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS},\n * {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should\n * be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}.\n * SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action,\n * it should be shown with a text label.\n *\n * @param actionEnum How the item should display. One of\n * {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or\n * {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default.\n *\n * @see android.app.ActionBar\n * @see #setActionView(View)\n */\n public void setShowAsAction(int actionEnum);\n\n /**\n * Sets how this item should display in the presence of an Action Bar.\n * The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS},\n * {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should\n * be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}.\n * SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action,\n * it should be shown with a text label.\n *\n * <p>Note: This method differs from {@link #setShowAsAction(int)} only in that it\n * returns the current MenuItem instance for call chaining.\n *\n * @param actionEnum How the item should display. One of\n * {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or\n * {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default.\n *\n * @see android.app.ActionBar\n * @see #setActionView(View)\n * @return This MenuItem instance for call chaining.\n */\n public MenuItem setShowAsActionFlags(int actionEnum);\n\n /**\n * Set an action view for this menu item. An action view will be displayed in place\n * of an automatically generated menu item element in the UI when this item is shown\n * as an action within a parent.\n * <p>\n * <strong>Note:</strong> Setting an action view overrides the action provider\n * set via {@link #setActionProvider(ActionProvider)}.\n * </p>\n *\n * @param view View to use for presenting this item to the user.\n * @return This Item so additional setters can be called.\n *\n * @see #setShowAsAction(int)\n */\n public MenuItem setActionView(View view);\n\n /**\n * Set an action view for this menu item. An action view will be displayed in place\n * of an automatically generated menu item element in the UI when this item is shown\n * as an action within a parent.\n * <p>\n * <strong>Note:</strong> Setting an action view overrides the action provider\n * set via {@link #setActionProvider(ActionProvider)}.\n * </p>\n *\n * @param resId Layout resource to use for presenting this item to the user.\n * @return This Item so additional setters can be called.\n *\n * @see #setShowAsAction(int)\n */\n public MenuItem setActionView(int resId);\n\n /**\n * Returns the currently set action view for this menu item.\n *\n * @return This item's action view\n *\n * @see #setActionView(View)\n * @see #setShowAsAction(int)\n */\n public View getActionView();\n\n /**\n * Sets the {@link ActionProvider} responsible for creating an action view if\n * the item is placed on the action bar. The provider also provides a default\n * action invoked if the item is placed in the overflow menu.\n * <p>\n * <strong>Note:</strong> Setting an action provider overrides the action view\n * set via {@link #setActionView(int)} or {@link #setActionView(View)}.\n * </p>\n *\n * @param actionProvider The action provider.\n * @return This Item so additional setters can be called.\n *\n * @see ActionProvider\n */\n public MenuItem setActionProvider(ActionProvider actionProvider);\n\n /**\n * Gets the {@link ActionProvider}.\n *\n * @return The action provider.\n *\n * @see ActionProvider\n * @see #setActionProvider(ActionProvider)\n */\n public ActionProvider getActionProvider();\n\n /**\n * Expand the action view associated with this menu item.\n * The menu item must have an action view set, as well as\n * the showAsAction flag {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}.\n * If a listener has been set using {@link #setOnActionExpandListener(OnActionExpandListener)}\n * it will have its {@link OnActionExpandListener#onMenuItemActionExpand(MenuItem)}\n * method invoked. The listener may return false from this method to prevent expanding\n * the action view.\n *\n * @return true if the action view was expanded, false otherwise.\n */\n public boolean expandActionView();\n\n /**\n * Collapse the action view associated with this menu item.\n * The menu item must have an action view set, as well as the showAsAction flag\n * {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. If a listener has been set using\n * {@link #setOnActionExpandListener(OnActionExpandListener)} it will have its\n * {@link OnActionExpandListener#onMenuItemActionCollapse(MenuItem)} method invoked.\n * The listener may return false from this method to prevent collapsing the action view.\n *\n * @return true if the action view was collapsed, false otherwise.\n */\n public boolean collapseActionView();\n\n /**\n * Returns true if this menu item's action view has been expanded.\n *\n * @return true if the item's action view is expanded, false otherwise.\n *\n * @see #expandActionView()\n * @see #collapseActionView()\n * @see #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW\n * @see OnActionExpandListener\n */\n public boolean isActionViewExpanded();\n\n /**\n * Set an {@link OnActionExpandListener} on this menu item to be notified when\n * the associated action view is expanded or collapsed. The menu item must\n * be configured to expand or collapse its action view using the flag\n * {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}.\n *\n * @param listener Listener that will respond to expand/collapse events\n * @return This menu item instance for call chaining\n */\n public MenuItem setOnActionExpandListener(OnActionExpandListener listener);\n}",
"public class SipCallSession implements Parcelable {\n\n /**\n * Describe the control state of a call <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/group__PJSIP__INV.htm#ga083ffd9c75c406c41f113479cc1ebc1c\"\n * >Pjsip documentation</a>\n */\n public static class InvState {\n /**\n * The call is in an invalid state not syncrhonized with sip stack\n */\n public static final int INVALID = -1;\n /**\n * Before INVITE is sent or received\n */\n public static final int NULL = 0;\n /**\n * After INVITE is sent\n */\n public static final int CALLING = 1;\n /**\n * After INVITE is received.\n */\n public static final int INCOMING = 2;\n /**\n * After response with To tag.\n */\n public static final int EARLY = 3;\n /**\n * After 2xx is sent/received.\n */\n public static final int CONNECTING = 4;\n /**\n * After ACK is sent/received.\n */\n public static final int CONFIRMED = 5;\n /**\n * Session is terminated.\n */\n public static final int DISCONNECTED = 6;\n\n // Should not be constructed, just an older for int values\n // Not an enum because easier to pass to Parcelable\n private InvState() {\n }\n }\n \n /**\n * Option key to flag video use for the call. <br/>\n * The value must be a boolean.\n * \n * @see Boolean\n */\n public static final String OPT_CALL_VIDEO = \"opt_call_video\";\n /**\n * Option key to add custom headers (with X- prefix). <br/>\n * The value must be a bundle with key representing header name, and value representing header value.\n * \n * @see Bundle\n */\n public static final String OPT_CALL_EXTRA_HEADERS = \"opt_call_extra_headers\";\n\n /**\n * Describe the media state of the call <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/group__PJSUA__LIB__CALL.htm#ga0608027241a5462d9f2736e3a6b8e3f4\"\n * >Pjsip documentation</a>\n */\n public static class MediaState {\n /**\n * Call currently has no media\n */\n public static final int NONE = 0;\n /**\n * The media is active\n */\n public static final int ACTIVE = 1;\n /**\n * The media is currently put on hold by local endpoint\n */\n public static final int LOCAL_HOLD = 2;\n /**\n * The media is currently put on hold by remote endpoint\n */\n public static final int REMOTE_HOLD = 3;\n /**\n * The media has reported error (e.g. ICE negotiation)\n */\n public static final int ERROR = 4;\n\n // Should not be constructed, just an older for int values\n // Not an enum because easier to pass to Parcelable\n private MediaState() {\n }\n }\n\n /**\n * Status code of the sip call dialog Actually just shortcuts to SIP codes<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/group__PJSIP__MSG__LINE.htm#gaf6d60351ee68ca0c87358db2e59b9376\"\n * >Pjsip documentation</a>\n */\n public static class StatusCode {\n public static final int TRYING = 100;\n public static final int RINGING = 180;\n public static final int CALL_BEING_FORWARDED = 181;\n public static final int QUEUED = 182;\n public static final int PROGRESS = 183;\n public static final int OK = 200;\n public static final int ACCEPTED = 202;\n public static final int MULTIPLE_CHOICES = 300;\n public static final int MOVED_PERMANENTLY = 301;\n public static final int MOVED_TEMPORARILY = 302;\n public static final int USE_PROXY = 305;\n public static final int ALTERNATIVE_SERVICE = 380;\n public static final int BAD_REQUEST = 400;\n public static final int UNAUTHORIZED = 401;\n public static final int PAYMENT_REQUIRED = 402;\n public static final int FORBIDDEN = 403;\n public static final int NOT_FOUND = 404;\n public static final int METHOD_NOT_ALLOWED = 405;\n public static final int NOT_ACCEPTABLE = 406;\n public static final int INTERVAL_TOO_BRIEF = 423;\n public static final int BUSY_HERE = 486;\n public static final int INTERNAL_SERVER_ERROR = 500;\n public static final int DECLINE = 603;\n /*\n * PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED = 407,\n * PJSIP_SC_REQUEST_TIMEOUT = 408, PJSIP_SC_GONE = 410,\n * PJSIP_SC_REQUEST_ENTITY_TOO_LARGE = 413,\n * PJSIP_SC_REQUEST_URI_TOO_LONG = 414, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE\n * = 415, PJSIP_SC_UNSUPPORTED_URI_SCHEME = 416, PJSIP_SC_BAD_EXTENSION\n * = 420, PJSIP_SC_EXTENSION_REQUIRED = 421,\n * PJSIP_SC_SESSION_TIMER_TOO_SMALL = 422,\n * PJSIP_SC_TEMPORARILY_UNAVAILABLE = 480,\n * PJSIP_SC_CALL_TSX_DOES_NOT_EXIST = 481, PJSIP_SC_LOOP_DETECTED = 482,\n * PJSIP_SC_TOO_MANY_HOPS = 483, PJSIP_SC_ADDRESS_INCOMPLETE = 484,\n * PJSIP_AC_AMBIGUOUS = 485, PJSIP_SC_BUSY_HERE = 486,\n * PJSIP_SC_REQUEST_TERMINATED = 487, PJSIP_SC_NOT_ACCEPTABLE_HERE =\n * 488, PJSIP_SC_BAD_EVENT = 489, PJSIP_SC_REQUEST_UPDATED = 490,\n * PJSIP_SC_REQUEST_PENDING = 491, PJSIP_SC_UNDECIPHERABLE = 493,\n * PJSIP_SC_INTERNAL_SERVER_ERROR = 500, PJSIP_SC_NOT_IMPLEMENTED = 501,\n * PJSIP_SC_BAD_GATEWAY = 502, PJSIP_SC_SERVICE_UNAVAILABLE = 503,\n * PJSIP_SC_SERVER_TIMEOUT = 504, PJSIP_SC_VERSION_NOT_SUPPORTED = 505,\n * PJSIP_SC_MESSAGE_TOO_LARGE = 513, PJSIP_SC_PRECONDITION_FAILURE =\n * 580, PJSIP_SC_BUSY_EVERYWHERE = 600, PJSIP_SC_DOES_NOT_EXIST_ANYWHERE\n * = 604, PJSIP_SC_NOT_ACCEPTABLE_ANYWHERE = 606,\n */\n }\n\n /**\n * The call signaling is not secure\n */\n public static int TRANSPORT_SECURE_NONE = 0;\n /**\n * The call signaling is secure until it arrives on server. After, nothing ensures how it goes.\n */\n public static int TRANSPORT_SECURE_TO_SERVER = 1;\n /**\n * The call signaling is supposed to be secured end to end.\n */\n public static int TRANSPORT_SECURE_FULL = 2;\n\n \n /**\n * Id of an invalid or not existant call\n */\n public static final int INVALID_CALL_ID = -1;\n\n /**\n * Primary key for the parcelable object\n */\n public int primaryKey = -1;\n /**\n * The starting time of the call\n */\n protected long callStart = 0;\n\n protected int callId = INVALID_CALL_ID;\n protected int callState = InvState.INVALID;\n protected String remoteContact;\n protected boolean isIncoming;\n protected int confPort = -1;\n protected long accId = SipProfile.INVALID_ID;\n protected int mediaStatus = MediaState.NONE;\n protected boolean mediaSecure = false;\n protected int transportSecure = 0;\n protected boolean mediaHasVideoStream = false;\n protected long connectStart = 0;\n protected int lastStatusCode = 0;\n protected String lastStatusComment = \"\";\n protected int lastReasonCode = 0;\n protected String mediaSecureInfo = \"\";\n protected boolean canRecord = false;\n protected boolean isRecording = false;\n protected boolean zrtpSASVerified = false;\n protected boolean hasZrtp = false;\n\n /**\n * Construct from parcelable <br/>\n * Only used by {@link #CREATOR}\n * \n * @param in parcelable to build from\n */\n private SipCallSession(Parcel in) {\n initFromParcel(in);\n }\n\n /**\n * Constructor for a sip call session state object <br/>\n * It will contains default values for all flags This class as no\n * setter/getter for members flags <br/>\n * It's aim is to allow to serialize/deserialize easily the state of a sip\n * call, <n>not to modify it</b>\n */\n public SipCallSession() {\n // Nothing to do in default constructor\n }\n\n /**\n * Constructor by copy\n * @param callInfo\n */\n public SipCallSession(SipCallSession callInfo) {\n Parcel p = Parcel.obtain();\n callInfo.writeToParcel(p, 0);\n p.setDataPosition(0);\n initFromParcel(p);\n p.recycle();\n }\n \n private void initFromParcel(Parcel in) {\n primaryKey = in.readInt();\n callId = in.readInt();\n callState = in.readInt();\n mediaStatus = in.readInt();\n remoteContact = in.readString();\n isIncoming = (in.readInt() == 1);\n confPort = in.readInt();\n accId = in.readInt();\n lastStatusCode = in.readInt();\n mediaSecureInfo = in.readString();\n connectStart = in.readLong();\n mediaSecure = (in.readInt() == 1);\n lastStatusComment = in.readString();\n mediaHasVideoStream = (in.readInt() == 1);\n canRecord = (in.readInt() == 1);\n isRecording = (in.readInt() == 1);\n hasZrtp = (in.readInt() == 1);\n zrtpSASVerified = (in.readInt() == 1);\n transportSecure = (in.readInt());\n lastReasonCode = in.readInt();\n }\n\n /**\n * @see Parcelable#describeContents()\n */\n @Override\n public int describeContents() {\n return 0;\n }\n\n\n /**\n * @see Parcelable#writeToParcel(Parcel, int)\n */\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(primaryKey);\n dest.writeInt(callId);\n dest.writeInt(callState);\n dest.writeInt(mediaStatus);\n dest.writeString(remoteContact);\n dest.writeInt(isIncoming() ? 1 : 0);\n dest.writeInt(confPort);\n dest.writeInt((int) accId);\n dest.writeInt(lastStatusCode);\n dest.writeString(mediaSecureInfo);\n dest.writeLong(connectStart);\n dest.writeInt(mediaSecure ? 1 : 0);\n dest.writeString(getLastStatusComment());\n dest.writeInt(mediaHasVideo() ? 1 : 0);\n dest.writeInt(canRecord ? 1 : 0);\n dest.writeInt(isRecording ? 1 : 0);\n dest.writeInt(hasZrtp ? 1 : 0);\n dest.writeInt(zrtpSASVerified ? 1 : 0);\n dest.writeInt(transportSecure);\n dest.writeInt(lastReasonCode);\n }\n\n /**\n * Parcelable creator. So that it can be passed as an argument of the aidl\n * interface\n */\n public static final Creator<SipCallSession> CREATOR = new Creator<SipCallSession>() {\n public SipCallSession createFromParcel(Parcel in) {\n return new SipCallSession(in);\n }\n\n public SipCallSession[] newArray(int size) {\n return new SipCallSession[size];\n }\n };\n\n\n \n\n /**\n * A sip call session is equal to another if both means the same callId\n */\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof SipCallSession)) {\n return false;\n }\n SipCallSession ci = (SipCallSession) o;\n if (ci.getCallId() == callId) {\n return true;\n }\n return false;\n }\n\n // Getters / Setters\n /**\n * Get the call id of this call info\n * \n * @return id of this call\n */\n public int getCallId() {\n return callId;\n }\n\n /**\n * Get the call state of this call info\n * \n * @return the invitation state\n * @see InvState\n */\n public int getCallState() {\n return callState;\n }\n\n public int getMediaStatus() {\n return mediaStatus;\n }\n\n /**\n * Get the remote Contact for this call info\n * \n * @return string representing the remote contact\n */\n public String getRemoteContact() {\n return remoteContact;\n }\n\n /**\n * Get the call way\n * \n * @return true if the remote party was the caller\n */\n public boolean isIncoming() {\n return isIncoming;\n }\n\n /**\n * Get the start time of the connection of the call\n * \n * @return duration in milliseconds\n * @see SystemClock#elapsedRealtime()\n */\n public long getConnectStart() {\n return connectStart;\n }\n\n /**\n * Check if the call state indicates that it is an active call in\n * progress. \n * This is equivalent to state incoming or early or calling or confirmed or connecting\n * \n * @return true if the call can be considered as in progress/active\n */\n public boolean isActive() {\n return (callState == InvState.INCOMING || callState == InvState.EARLY ||\n callState == InvState.CALLING || callState == InvState.CONFIRMED || callState == InvState.CONNECTING);\n }\n \n /**\n * Chef if the call state indicates that it's an ongoing call.\n * This is equivalent to state confirmed.\n * @return true if the call can be considered as ongoing.\n */\n public boolean isOngoing() {\n return callState == InvState.CONFIRMED;\n }\n\n /**\n * Get the sounds conference board port <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/group__PJSUA__LIB__BASE.htm#gaf5d44947e4e62dc31dfde88884534385\"\n * >Pjsip documentation</a>\n * \n * @return the conf port of the audio media of this call\n */\n public int getConfPort() {\n return confPort;\n }\n\n /**\n * Get the identifier of the account corresponding to this call <br/>\n * This identifier is the one you have in {@link SipProfile#id} <br/>\n * It may return {@link SipProfile#INVALID_ID} if no account detected for\n * this call. <i>Example, case of peer to peer call</i>\n * \n * @return The {@link SipProfile#id} of the account use for this call\n */\n public long getAccId() {\n return accId;\n }\n\n /**\n * Get the secure level of the signaling of the call.\n * \n * @return one of {@link #TRANSPORT_SECURE_NONE}, {@link #TRANSPORT_SECURE_TO_SERVER}, {@link #TRANSPORT_SECURE_FULL}\n */\n public int getTransportSecureLevel() {\n return transportSecure;\n }\n \n /**\n * Get the secure level of the media of the call\n * \n * @return true if the call has a <b>media</b> encrypted\n */\n public boolean isMediaSecure() {\n return mediaSecure;\n }\n\n /**\n * Get the information about the <b>media</b> security of this call\n * \n * @return the information about the <b>media</b> security\n */\n public String getMediaSecureInfo() {\n return mediaSecureInfo;\n }\n\n /**\n * Get the information about local held state of this call\n * \n * @return the information about local held state of media\n */\n public boolean isLocalHeld() {\n return mediaStatus == MediaState.LOCAL_HOLD;\n }\n\n /**\n * Get the information about remote held state of this call\n * \n * @return the information about remote held state of media\n */\n public boolean isRemoteHeld() {\n return (mediaStatus == MediaState.NONE && isActive() && !isBeforeConfirmed());\n }\n\n /**\n * Check if the specific call info indicates that it is a call that has not yet been confirmed by both ends.<br/>\n * In other worlds if the call is in state, calling, incoming early or connecting.\n * \n * @return true if the call can be considered not yet been confirmed\n */\n public boolean isBeforeConfirmed() {\n return (callState == InvState.CALLING || callState == InvState.INCOMING\n || callState == InvState.EARLY || callState == InvState.CONNECTING);\n }\n\n\n /**\n * Check if the specific call info indicates that it is a call that has been ended<br/>\n * In other worlds if the call is in state, disconnected, invalid or null\n * \n * @return true if the call can be considered as already ended\n */\n public boolean isAfterEnded() {\n return (callState == InvState.DISCONNECTED || callState == InvState.INVALID || callState == InvState.NULL);\n }\n\n /**\n * Get the latest status code of the sip dialog corresponding to this call\n * call\n * \n * @return the status code\n * @see StatusCode\n */\n public int getLastStatusCode() {\n return lastStatusCode;\n }\n\n /**\n * Get the last status comment of the sip dialog corresponding to this call\n * \n * @return the last status comment string from server\n */\n public String getLastStatusComment() {\n return lastStatusComment;\n }\n\n /**\n * Get the latest SIP reason code if any. \n * For now only supports 200 (if SIP reason is set to 200) or 0 in other cases (no SIP reason / sip reason set to something different).\n * \n * @return the status code\n */\n public int getLastReasonCode() {\n return lastReasonCode;\n }\n \n /**\n * Get whether the call has a video media stream connected\n * \n * @return true if the call has a video media stream\n */\n public boolean mediaHasVideo() {\n return mediaHasVideoStream;\n }\n\n /**\n * Get the current call recording status for this call.\n * \n * @return true if we are currently recording this call to a file\n */\n public boolean isRecording() {\n return isRecording;\n }\n \n /**\n * Get the capability to record the call to a file.\n * \n * @return true if it should be possible to record the call to a file\n */\n public boolean canRecord() {\n return canRecord;\n }\n\n /**\n * @return the zrtpSASVerified\n */\n public boolean isZrtpSASVerified() {\n return zrtpSASVerified;\n }\n\n /**\n * @return whether call has Zrtp encryption active\n */\n public boolean getHasZrtp() {\n return hasZrtp;\n }\n\n /**\n * Get the start time of the call.\n * @return the callStart start time of the call.\n */\n public long getCallStart() {\n return callStart;\n }\n\n}",
"public static class MediaState {\n /**\n * Call currently has no media\n */\n public static final int NONE = 0;\n /**\n * The media is active\n */\n public static final int ACTIVE = 1;\n /**\n * The media is currently put on hold by local endpoint\n */\n public static final int LOCAL_HOLD = 2;\n /**\n * The media is currently put on hold by remote endpoint\n */\n public static final int REMOTE_HOLD = 3;\n /**\n * The media has reported error (e.g. ICE negotiation)\n */\n public static final int ERROR = 4;\n\n // Should not be constructed, just an older for int values\n // Not an enum because easier to pass to Parcelable\n private MediaState() {\n }\n}",
"public final class SipManager {\n // -------\n // Static constants\n // PERMISSION\n /**\n * Permission that allows to use sip : place call, control call etc.\n */\n public static final String PERMISSION_USE_SIP = \"android.permission.USE_SIP\";\n /**\n * Permission that allows to configure sip engine : preferences, accounts.\n */\n public static final String PERMISSION_CONFIGURE_SIP = \"android.permission.CONFIGURE_SIP\";\n\n // SERVICE intents\n /**\n * Used to bind sip service to configure it.<br/>\n * This method has been deprected and should not be used anymore. <br/>\n * Use content provider approach instead\n * \n * @see SipConfigManager\n */\n public static final String INTENT_SIP_CONFIGURATION = \"com.csipsimple.service.SipConfiguration\";\n /**\n * Bind sip service to control calls.<br/>\n * If you start the service using {@link android.content.Context#startService(android.content.Intent intent)}\n * , you may want to pass {@link #EXTRA_OUTGOING_ACTIVITY} to specify you\n * are starting the service in order to make outgoing calls. You are then in\n * charge to unregister for outgoing calls when user finish with your\n * activity or when you are not anymore in calls using\n * {@link #ACTION_OUTGOING_UNREGISTER}<br/>\n * If you actually make a call or ask service to do something but wants to\n * unregister, you must defer unregister of your activity using\n * {@link #ACTION_DEFER_OUTGOING_UNREGISTER}.\n * \n * @see ISipService\n * @see #EXTRA_OUTGOING_ACTIVITY\n */\n public static final String INTENT_SIP_SERVICE = \"com.csipsimple.service.SipService\";\n \n /**\n * Shortcut to turn on / off a sip account.\n * <p>\n * Expected Extras :\n * <ul>\n * <li>{@link SipProfile#FIELD_ID} as Long to choose the account to\n * activate/deactivate</li>\n * <li><i>{@link SipProfile#FIELD_ACTIVE} - optional </i> as boolean to\n * choose if should be activated or deactivated</li>\n * </ul>\n * </p>\n */\n public static final String INTENT_SIP_ACCOUNT_ACTIVATE = \"com.csipsimple.accounts.activate\";\n\n /**\n * Scheme for csip uri.\n */\n public static final String PROTOCOL_CSIP = \"csip\";\n /**\n * Scheme for sip uri.\n */\n public static final String PROTOCOL_SIP = \"sip\";\n /**\n * Scheme for sips (sip+tls) uri.\n */\n public static final String PROTOCOL_SIPS = \"sips\";\n // -------\n // ACTIONS\n /**\n * Action launched when a sip call is ongoing.\n * <p>\n * Provided extras :\n * <ul>\n * <li>{@link #EXTRA_CALL_INFO} a {@link SipCallSession} containing infos of\n * the call</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_CALL_UI = \"com.csipsimple.phone.action.INCALL\";\n /**\n * Action launched when the status icon clicked.<br/>\n * Should raise the dialer.\n */\n public static final String ACTION_SIP_DIALER = \"com.csipsimple.phone.action.DIALER\";\n /**\n * Action launched when a missed call notification entry is clicked.<br/>\n * Should raise call logs list.\n */\n public static final String ACTION_SIP_CALLLOG = \"com.csipsimple.phone.action.CALLLOG\";\n /**\n * Action launched when a sip message notification entry is clicked.<br/>\n * Should raise the sip message list.\n */\n public static final String ACTION_SIP_MESSAGES = \"com.csipsimple.phone.action.MESSAGES\";\n /**\n * Action launched when user want to go in sip favorites.\n * Should raise the sip favorites view.\n */\n public static final String ACTION_SIP_FAVORITES = \"com.csipsimple.phone.action.FAVORITES\";\n /**\n * Action launched to enter fast settings.<br/>\n */\n public static final String ACTION_UI_PREFS_FAST = \"com.csipsimple.ui.action.PREFS_FAST\";\n /**\n * Action launched to enter global csipsimple settings.<br/>\n */\n public static final String ACTION_UI_PREFS_GLOBAL = \"com.csipsimple.ui.action.PREFS_GLOBAL\";\n \n // SERVICE BROADCASTS\n /**\n * Broadcastsent when a call is about to be launched.\n * <p>\n * Receiver of this ordered broadcast might rewrite and add new headers.\n * </p>\n */\n public static final String ACTION_SIP_CALL_LAUNCH = \"com.csipsimple.service.CALL_LAUNCHED\";\n /**\n * Broadcast sent when call state has changed.\n * <p>\n * Provided extras :\n * <ul>\n * <li>{@link #EXTRA_CALL_INFO} a {@link SipCallSession} containing infos of\n * the call</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_CALL_CHANGED = \"com.csipsimple.service.CALL_CHANGED\";\n /**\n * Broadcast sent when sip account has been changed.\n * <p>\n * Provided extras :\n * <ul>\n * <li>{@link SipProfile#FIELD_ID} the long id of the account</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_ACCOUNT_CHANGED = \"com.csipsimple.service.ACCOUNT_CHANGED\";\n /**\n * Broadcast sent when a sip account has been deleted\n * <p>\n * <ul>\n * <li>{@link SipProfile#FIELD_ID} the long id of the account</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_ACCOUNT_DELETED = \"com.csipsimple.service.ACCOUNT_DELETED\";\n /**\n * Broadcast sent when sip account registration has changed.\n * <p>\n * Provided extras :\n * <ul>\n * <li>{@link SipProfile#FIELD_ID} the long id of the account</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_REGISTRATION_CHANGED = \"com.csipsimple.service.REGISTRATION_CHANGED\";\n /**\n * Broadcast sent when the state of device media has been changed.\n */\n public static final String ACTION_SIP_MEDIA_CHANGED = \"com.csipsimple.service.MEDIA_CHANGED\";\n /**\n * Broadcast sent when a ZRTP SAS\n */\n public static final String ACTION_ZRTP_SHOW_SAS = \"com.csipsimple.service.SHOW_SAS\";\n /**\n * Broadcast sent when a message has been received.<br/>\n * By message here, we mean a SIP SIMPLE message of the sip simple protocol. Understand a chat / im message.\n */\n public static final String ACTION_SIP_MESSAGE_RECEIVED = \"com.csipsimple.service.MESSAGE_RECEIVED\";\n /**\n * Broadcast sent when a conversation has been recorded.<br/>\n * This is linked to the call record feature of CSipSimple available through {@link ISipService#startRecording(int)}\n * <p>\n * Provided extras :\n * <ul>\n * <li>{@link SipManager#EXTRA_FILE_PATH} the path to the recorded file</li>\n * <li>{@link SipManager#EXTRA_CALL_INFO} the information on the call recorded</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_CALL_RECORDED = \"com.csipsimple.service.CALL_RECORDED\";\n\n // REGISTERED BROADCASTS\n /**\n * Broadcast to send when the sip service can be stopped.\n */\n public static final String ACTION_SIP_CAN_BE_STOPPED = \"com.csipsimple.service.ACTION_SIP_CAN_BE_STOPPED\";\n /**\n * Broadcast to send when the sip service should be restarted.\n */\n public static final String ACTION_SIP_REQUEST_RESTART = \"com.csipsimple.service.ACTION_SIP_REQUEST_RESTART\";\n /**\n * Broadcast to send when your activity doesn't allow anymore user to make outgoing calls.<br/>\n * You have to pass registered {@link #EXTRA_OUTGOING_ACTIVITY} \n * \n * @see #EXTRA_OUTGOING_ACTIVITY\n */\n public static final String ACTION_OUTGOING_UNREGISTER = \"com.csipsimple.service.ACTION_OUTGOING_UNREGISTER\";\n /**\n * Broadcast to send when you have launched a sip action (such as make call), but that your app will not anymore allow user to make outgoing calls actions.<br/>\n * You have to pass registered {@link #EXTRA_OUTGOING_ACTIVITY} \n * \n * @see #EXTRA_OUTGOING_ACTIVITY\n */\n public static final String ACTION_DEFER_OUTGOING_UNREGISTER = \"com.csipsimple.service.ACTION_DEFER_OUTGOING_UNREGISTER\";\n\n // PLUGINS BROADCASTS\n /**\n * Plugin action for themes.\n */\n public static final String ACTION_GET_DRAWABLES = \"com.csipsimple.themes.GET_DRAWABLES\";\n /**\n * Plugin action for call handlers.<br/>\n * You can expect {@link android.content.Intent#EXTRA_PHONE_NUMBER} as argument for the\n * number to call. <br/>\n * Your receiver must\n * {@link android.content.BroadcastReceiver#getResultExtras(boolean)} with parameter true to\n * fill response. <br/>\n * Your response contains :\n * <ul>\n * <li>{@link android.content.Intent#EXTRA_SHORTCUT_ICON} with\n * {@link android.graphics.Bitmap} (mandatory) : Icon representing the call\n * handler</li>\n * <li>{@link android.content.Intent#EXTRA_TITLE} with\n * {@link String} (mandatory) : Title representing the call\n * handler</li>\n * <li>{@link android.content.Intent#EXTRA_REMOTE_INTENT_TOKEN} with\n * {@link android.app.PendingIntent} (mandatory) : The intent to fire when\n * this action is choosen</li>\n * <li>{@link android.content.Intent#EXTRA_PHONE_NUMBER} with\n * {@link String} (optional) : Phone number if the pending intent\n * launch a call intent. Empty if the pending intent launch something not\n * related to a GSM call.</li>\n * </ul>\n */\n public static final String ACTION_GET_PHONE_HANDLERS = \"com.csipsimple.phone.action.HANDLE_CALL\";\n \n /**\n * Plugin action for call management extension. <br/>\n * Any app that register this plugin and has rights to {@link #PERMISSION_USE_SIP} will appear \n * in the call cards. <br/>\n * The activity entry in manifest may have following metadata\n * <ul>\n * <li>{@link #EXTRA_SIP_CALL_MIN_STATE} minimum call state for this plugin to be active. Default {@link SipCallSession.InvState#EARLY}.</li>\n * <li>{@link #EXTRA_SIP_CALL_MAX_STATE} maximum call state for this plugin to be active. Default {@link SipCallSession.InvState#CONFIRMED}.</li>\n * <li>{@link #EXTRA_SIP_CALL_CALL_WAY} bitmask flag for selecting only one way. \n * {@link #BITMASK_IN} for incoming; \n * {@link #BITMASK_OUT} for outgoing.\n * Default ({@link #BITMASK_IN} | {@link #BITMASK_OUT}) (any way).</li>\n * </ul> \n * Receiver activity will get an extra with key {@value #EXTRA_CALL_INFO} with a {@link SipCallSession}.\n */\n public static final String ACTION_INCALL_PLUGIN = \"com.csipsimple.sipcall.action.HANDLE_CALL_PLUGIN\";\n \n public static final String EXTRA_SIP_CALL_MIN_STATE = \"com.csipsimple.sipcall.MIN_STATE\";\n public static final String EXTRA_SIP_CALL_MAX_STATE = \"com.csipsimple.sipcall.MAX_STATE\";\n public static final String EXTRA_SIP_CALL_CALL_WAY = \"com.csipsimple.sipcall.CALL_WAY\";\n \n /**\n * Bitmask to keep media/call coming from outside\n */\n public final static int BITMASK_IN = 1 << 0;\n /**\n * Bitmask to keep only media/call coming from the app\n */\n public final static int BITMASK_OUT = 1 << 1;\n /**\n * Bitmask to keep all media/call whatever incoming/outgoing\n */\n public final static int BITMASK_ALL = BITMASK_IN | BITMASK_OUT;\n \n /**\n * Plugin action for rewrite numbers. <br/> \n * You can expect {@link android.content.Intent#EXTRA_PHONE_NUMBER} as argument for the\n * number to rewrite. <br/>\n * Your receiver must\n * {@link android.content.BroadcastReceiver#getResultExtras(boolean)} with parameter true to\n * fill response. <br/>\n * Your response contains :\n * <ul>\n * <li>{@link android.content.Intent#EXTRA_PHONE_NUMBER} with\n * {@link String} (optional) : Rewritten phone number.</li>\n * </ul>\n */\n public final static String ACTION_REWRITE_NUMBER = \"com.csipsimple.phone.action.REWRITE_NUMBER\"; \n /**\n * Plugin action for audio codec.\n */\n public static final String ACTION_GET_EXTRA_CODECS = \"com.csipsimple.codecs.action.REGISTER_CODEC\";\n /**\n * Plugin action for video codec.\n */\n public static final String ACTION_GET_EXTRA_VIDEO_CODECS = \"com.csipsimple.codecs.action.REGISTER_VIDEO_CODEC\";\n /**\n * Plugin action for video.\n */\n public static final String ACTION_GET_VIDEO_PLUGIN = \"com.csipsimple.plugins.action.REGISTER_VIDEO\";\n /**\n * Meta constant name for library name.\n */\n public static final String META_LIB_NAME = \"lib_name\";\n /**\n * Meta constant name for the factory name.\n */\n public static final String META_LIB_INIT_FACTORY = \"init_factory\";\n /**\n * Meta constant name for the factory deinit name.\n */\n public static final String META_LIB_DEINIT_FACTORY = \"deinit_factory\";\n\n // Content provider\n /**\n * Authority for regular database of the application.\n */\n public static final String AUTHORITY = \"com.csipsimple.db\";\n /**\n * Base content type for csipsimple objects.\n */\n public static final String BASE_DIR_TYPE = \"vnd.android.cursor.dir/vnd.csipsimple\";\n /**\n * Base item content type for csipsimple objects.\n */\n public static final String BASE_ITEM_TYPE = \"vnd.android.cursor.item/vnd.csipsimple\";\n\n // Content Provider - call logs\n /**\n * Table name for call logs.\n */\n public static final String CALLLOGS_TABLE_NAME = \"calllogs\";\n /**\n * Content type for call logs provider.\n */\n public static final String CALLLOG_CONTENT_TYPE = BASE_DIR_TYPE + \".calllog\";\n /**\n * Item type for call logs provider.\n */\n public static final String CALLLOG_CONTENT_ITEM_TYPE = BASE_ITEM_TYPE + \".calllog\";\n /**\n * Uri for call log content provider.\n */\n public static final Uri CALLLOG_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + AUTHORITY + \"/\"\n + CALLLOGS_TABLE_NAME);\n /**\n * Base uri for a specific call log. Should be appended with id of the call log.\n */\n public static final Uri CALLLOG_ID_URI_BASE = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + AUTHORITY + \"/\"\n + CALLLOGS_TABLE_NAME + \"/\");\n // -- Extra fields for call logs\n /**\n * The account used for this call\n */\n public static final String CALLLOG_PROFILE_ID_FIELD = \"account_id\";\n /**\n * The final latest status code for this call.\n */\n public static final String CALLLOG_STATUS_CODE_FIELD = \"status_code\";\n /**\n * The final latest status text for this call.\n */\n public static final String CALLLOG_STATUS_TEXT_FIELD = \"status_text\";\n\n // Content Provider - filter\n /**\n * Table name for filters/rewriting rules.\n */\n public static final String FILTERS_TABLE_NAME = \"outgoing_filters\";\n /**\n * Content type for filter provider.\n */\n public static final String FILTER_CONTENT_TYPE = BASE_DIR_TYPE + \".filter\";\n /**\n * Item type for filter provider.\n */\n public static final String FILTER_CONTENT_ITEM_TYPE = BASE_ITEM_TYPE + \".filter\";\n /**\n * Uri for filters provider.\n */\n public static final Uri FILTER_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + AUTHORITY + \"/\"\n + FILTERS_TABLE_NAME);\n /**\n * Base uri for a specific filter. Should be appended with filter id.\n */\n public static final Uri FILTER_ID_URI_BASE = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + AUTHORITY + \"/\"\n + FILTERS_TABLE_NAME + \"/\");\n\n // EXTRAS\n /**\n * Extra key to contains infos about a sip call.<br/>\n * @see SipCallSession\n */\n public static final String EXTRA_CALL_INFO = \"call_info\";\n \n\n /**\n * Tell sip service that it's an user interface requesting for outgoing call.<br/>\n * It's an extra to add to sip service start as string representing unique key for your activity.<br/>\n * We advise to use your own component name {@link android.content.ComponentName} to avoid collisions.<br/>\n * Each activity is in charge unregistering broadcasting {@link #ACTION_OUTGOING_UNREGISTER} or {@link #ACTION_DEFER_OUTGOING_UNREGISTER}<br/>\n * \n * @see android.content.ComponentName\n */\n public static final String EXTRA_OUTGOING_ACTIVITY = \"outgoing_activity\";\n \n /**\n * Extra key to contain an string to path of a file.<br/>\n * @see String\n */\n public static final String EXTRA_FILE_PATH = \"file_path\";\n \n /**\n * Target in a sip launched call.\n * @see #ACTION_SIP_CALL_LAUNCH\n */\n public static final String EXTRA_SIP_CALL_TARGET = \"call_target\";\n /**\n * Options of a sip launched call.\n * @see #ACTION_SIP_CALL_LAUNCH\n */\n public static final String EXTRA_SIP_CALL_OPTIONS = \"call_options\";\n \n /**\n * Extra key to contain behavior of outgoing call chooser activity.<br/>\n * In case an account is specified in the outgoing call intent with {@link SipProfile#FIELD_ACC_ID}\n * and the application doesn't find this account,\n * this extra parameter allows to determine what is the fallback behavior of\n * the activity. <br/>\n * By default {@link #FALLBACK_ASK}.\n * Other options : \n */\n public static final String EXTRA_FALLBACK_BEHAVIOR = \"fallback_behavior\";\n /**\n * Parameter for {@link #EXTRA_FALLBACK_BEHAVIOR}.\n * Prompt user with other choices without calling automatically.\n */\n public static final int FALLBACK_ASK = 0;\n /**\n * Parameter for {@link #EXTRA_FALLBACK_BEHAVIOR}.\n * Warn user about the fact current account not valid and exit.\n * WARNING : not yet implemented, will behaves just like {@link #FALLBACK_ASK} for now\n */\n public static final int FALLBACK_PREVENT = 1;\n /**\n * Parameter for {@link #EXTRA_FALLBACK_BEHAVIOR}\n * Automatically fallback to any other available account in case requested sip profile is not there.\n */\n public static final int FALLBACK_AUTO_CALL_OTHER = 2;\n \n // Constants\n /**\n * Constant for success return\n */\n public static final int SUCCESS = 0;\n /**\n * Constant for network errors return\n */\n public static final int ERROR_CURRENT_NETWORK = 10;\n\n /**\n * Possible presence status.\n */\n public enum PresenceStatus {\n /**\n * Unknown status\n */\n UNKNOWN,\n /**\n * Online status\n */\n ONLINE,\n /**\n * Offline status\n */\n OFFLINE,\n /**\n * Busy status\n */\n BUSY,\n /**\n * Away status\n */\n AWAY,\n }\n\n /**\n * Current api version number.<br/>\n * Major version x 1000 + minor version. <br/>\n * Major version are backward compatible.\n */\n public static final int CURRENT_API = 2005;\n\n /**\n * Ensure capability of the remote sip service to reply our requests <br/>\n * \n * @param service the bound service to check\n * @return true if we can safely use the API\n */\n public static boolean isApiCompatible(ISipService service) {\n if (service != null) {\n try {\n int version = service.getVersion();\n return (Math.floor(version / 1000) == Math.floor(CURRENT_API % 1000));\n } catch (RemoteException e) {\n // We consider this is a bad api version that does not have\n // versionning at all\n return false;\n }\n }\n\n return false;\n }\n}",
"public class SipProfile implements Parcelable {\n private static final String THIS_FILE = \"SipProfile\";\n\n // Constants\n /**\n * Constant for an invalid account id.\n */\n public final static long INVALID_ID = -1;\n\n // Transport choices\n /**\n * Automatically choose transport.<br/>\n * By default it uses UDP, if packet is higher than UDP limit it will switch\n * to TCP.<br/>\n * Take care with that , because not all sip servers support udp/tcp\n * correclty.\n */\n public final static int TRANSPORT_AUTO = 0;\n /**\n * Force UDP transport.\n */\n public final static int TRANSPORT_UDP = 1;\n /**\n * Force TCP transport.\n */\n public final static int TRANSPORT_TCP = 2;\n /**\n * Force TLS transport.\n */\n public final static int TRANSPORT_TLS = 3;\n\n // Stack choices\n /**\n * Use pjsip as backend.<br/>\n * For now it's the only one supported\n */\n public static final int PJSIP_STACK = 0;\n /**\n * @deprecated Use google google android 2.3 backend.<br/>\n * This is not supported for now.\n */\n public static final int GOOGLE_STACK = 1;\n\n // Password type choices\n /**\n * Plain password mode.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a8b1e563c814bdf8012f0bdf966d0ad9d\"\n * >Pjsip documentation</a>\n * \n * @see #datatype\n */\n public static final int CRED_DATA_PLAIN_PASSWD = 0;\n /**\n * Digest mode.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a8b1e563c814bdf8012f0bdf966d0ad9d\"\n * >Pjsip documentation</a>\n * \n * @see #datatype\n */\n public static final int CRED_DATA_DIGEST = 1;\n /**\n * @deprecated This mode is not supported by csipsimple for now.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a8b1e563c814bdf8012f0bdf966d0ad9d\"\n * >Pjsip documentation</a>\n * @see #datatype\n */\n public static final int CRED_CRED_DATA_EXT_AKA = 2;\n\n // Scheme credentials choices\n /**\n * Digest scheme for credentials.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#ae31c9ec1c99fb1ffa20be5954ee995a7\"\n * >Pjsip documentation</a>\n * \n * @see #scheme\n */\n public static final String CRED_SCHEME_DIGEST = \"Digest\";\n /**\n * PGP scheme for credentials.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#ae31c9ec1c99fb1ffa20be5954ee995a7\"\n * >Pjsip documentation</a>\n * \n * @see #scheme\n */\n public static final String CRED_SCHEME_PGP = \"PGP\";\n\n /**\n * Separator for proxy field once stored in database.<br/>\n * It's the pipe char.\n * \n * @see #FIELD_PROXY\n */\n public static final String PROXIES_SEPARATOR = \"|\";\n\n // Content Provider - account\n /**\n * Table name of content provider for accounts storage\n */\n public final static String ACCOUNTS_TABLE_NAME = \"accounts\";\n /**\n * Content type for account / sip profile\n */\n public final static String ACCOUNT_CONTENT_TYPE = SipManager.BASE_DIR_TYPE + \".account\";\n /**\n * Item type for account / sip profile\n */\n public final static String ACCOUNT_CONTENT_ITEM_TYPE = SipManager.BASE_ITEM_TYPE + \".account\";\n /**\n * Uri of accounts / sip profiles\n */\n public final static Uri ACCOUNT_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + SipManager.AUTHORITY + \"/\" + ACCOUNTS_TABLE_NAME);\n /**\n * Base uri for the account / sip profile. <br/>\n * To append with {@link #FIELD_ID}\n * \n * @see ContentUris#appendId(Uri.Builder, long)\n */\n public final static Uri ACCOUNT_ID_URI_BASE = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + SipManager.AUTHORITY + \"/\" + ACCOUNTS_TABLE_NAME + \"/\");\n\n // Content Provider - account status\n /**\n * Virutal table name for sip profile adding/registration table.<br/>\n * An application should use it in read only mode.\n */\n public final static String ACCOUNTS_STATUS_TABLE_NAME = \"accounts_status\";\n /**\n * Content type for sip profile adding/registration state\n */\n public final static String ACCOUNT_STATUS_CONTENT_TYPE = SipManager.BASE_DIR_TYPE\n + \".account_status\";\n /**\n * Content type for sip profile adding/registration state item\n */\n public final static String ACCOUNT_STATUS_CONTENT_ITEM_TYPE = SipManager.BASE_ITEM_TYPE\n + \".account_status\";\n /**\n * Uri for the sip profile adding/registration state.\n */\n public final static Uri ACCOUNT_STATUS_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + SipManager.AUTHORITY + \"/\" + ACCOUNTS_STATUS_TABLE_NAME);\n /**\n * Base uri for the sip profile adding/registration state. <br/>\n * To append with {@link #FIELD_ID}\n * \n * @see ContentUris#appendId(Uri.Builder, long)\n */\n public final static Uri ACCOUNT_STATUS_ID_URI_BASE = Uri.parse(ContentResolver.SCHEME_CONTENT\n + \"://\"\n + SipManager.AUTHORITY + \"/\" + ACCOUNTS_STATUS_TABLE_NAME + \"/\");\n\n // Fields for table accounts\n /**\n * Primary key identifier of the account in the database.\n * \n * @see Long\n */\n public static final String FIELD_ID = \"id\";\n /**\n * Activation state of the account.<br/>\n * If false this account will be ignored by the sip stack.\n * \n * @see Boolean\n */\n public static final String FIELD_ACTIVE = \"active\";\n /**\n * The wizard associated to this account.<br/>\n * Used for icon and edit layout view.\n * \n * @see String\n */\n public static final String FIELD_WIZARD = \"wizard\";\n /**\n * The display name of the account. <br/>\n * This is used in the application interface to show the label representing\n * the account.\n * \n * @see String\n */\n public static final String FIELD_DISPLAY_NAME = \"display_name\";\n /**\n * The priority of the account.<br/>\n * This is used in the interface when presenting list of accounts.<br/>\n * This can also be used to choose the default account. <br/>\n * Higher means highest priority.\n * \n * @see Integer\n */\n public static final String FIELD_PRIORITY = \"priority\";\n /**\n * The full SIP URL for the account. <br/>\n * The value can take name address or URL format, and will look something\n * like \"sip:account@serviceprovider\".<br/>\n * This field is mandatory.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#ab290b04e8150ed9627335a67e6127b7c\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_ACC_ID = \"acc_id\";\n \n /**\n * Data useful for the wizard internal use.\n * The format here is specific to the wizard and no assumption is made.\n * Could be simplestring, json, base64 encoded stuff etc.\n * \n * @see String\n */\n public static final String FIELD_WIZARD_DATA = \"wizard_data\";\n \n /**\n * This is the URL to be put in the request URI for the registration, and\n * will look something like \"sip:serviceprovider\".<br/>\n * This field should be specified if registration is desired. If the value\n * is empty, no account registration will be performed.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a08473de6401e966d23f34d3a9a05bdd0\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_REG_URI = \"reg_uri\";\n /**\n * Subscribe to message waiting indication events (RFC 3842).<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a0158ae24d72872a31a0b33c33450a7ab\"\n * >Pjsip documentation</a>\n * \n * @see Boolean\n */\n public static final String FIELD_MWI_ENABLED = \"mwi_enabled\";\n /**\n * If this flag is set, the presence information of this account will be\n * PUBLISH-ed to the server where the account belongs.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a0d4128f44963deffda4ea9c15183a787\"\n * >Pjsip documentation</a>\n * 1 for true, 0 for false\n * \n * @see Integer\n */\n public static final String FIELD_PUBLISH_ENABLED = \"publish_enabled\";\n /**\n * Optional interval for registration, in seconds. <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a2c097b9ae855783bfbb00056055dd96c\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_REG_TIMEOUT = \"reg_timeout\";\n /**\n * Specify the number of seconds to refresh the client registration before\n * the registration expires.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a52a35fdf8c17263b2a27d2b17111c040\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_REG_DELAY_BEFORE_REFRESH = \"reg_dbr\";\n /**\n * Set the interval for periodic keep-alive transmission for this account. <br/>\n * If this value is zero, keep-alive will be disabled for this account.<br/>\n * The keep-alive transmission will be sent to the registrar's address,\n * after successful registration.<br/>\n * Note that in csipsimple this value is not applied anymore in flavor to\n * {@link SipConfigManager#KEEP_ALIVE_INTERVAL_MOBILE} and\n * {@link SipConfigManager#KEEP_ALIVE_INTERVAL_WIFI} <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a98722b6464d16b5a76aec81f2d2a0694\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_KA_INTERVAL = \"ka_interval\";\n /**\n * Optional PIDF tuple ID for outgoing PUBLISH and NOTIFY. <br/>\n * If this value is not specified, a random string will be used. <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#aa603989566022840b4671f0171b6cba1\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_PIDF_TUPLE_ID = \"pidf_tuple_id\";\n /**\n * Optional URI to be put as Contact for this account.<br/>\n * It is recommended that this field is left empty, so that the value will\n * be calculated automatically based on the transport address.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a5dfdfba40038e33af95819fbe2b896f9\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_FORCE_CONTACT = \"force_contact\";\n\n /**\n * This option is used to update the transport address and the Contact\n * header of REGISTER request.<br/>\n * When this option is enabled, the library will keep track of the public IP\n * address from the response of REGISTER request. <br/>\n * Once it detects that the address has changed, it will unregister current\n * Contact, update the Contact with transport address learned from Via\n * header, and register a new Contact to the registrar.<br/>\n * This will also update the public name of UDP transport if STUN is\n * configured.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a22961bb72ea75f7ca7008464f081ca06\"\n * >Pjsip documentation</a>\n * \n * @see Boolean\n */\n public static final String FIELD_ALLOW_CONTACT_REWRITE = \"allow_contact_rewrite\";\n /**\n * Specify how Contact update will be done with the registration, if\n * allow_contact_rewrite is enabled.<br/>\n * <ul>\n * <li>If set to 1, the Contact update will be done by sending\n * unregistration to the currently registered Contact, while simultaneously\n * sending new registration (with different Call-ID) for the updated\n * Contact.</li>\n * <li>If set to 2, the Contact update will be done in a single, current\n * registration session, by removing the current binding (by setting its\n * Contact's expires parameter to zero) and adding a new Contact binding,\n * all done in a single request.</li>\n * </ul>\n * Value 1 is the legacy behavior.<br/>\n * Value 2 is the default behavior.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a73b69a3a8d225147ce386e310e588285\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_CONTACT_REWRITE_METHOD = \"contact_rewrite_method\";\n\n /**\n * Additional parameters that will be appended in the Contact header for\n * this account.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#abef88254f9ef2a490503df6d3b297e54\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_CONTACT_PARAMS = \"contact_params\";\n /**\n * Additional URI parameters that will be appended in the Contact URI for\n * this account.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#aced70341308928ae951525093bf47562\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_CONTACT_URI_PARAMS = \"contact_uri_params\";\n /**\n * Transport to use for this account.<br/>\n * \n * @see #TRANSPORT_AUTO\n * @see #TRANSPORT_UDP\n * @see #TRANSPORT_TCP\n * @see #TRANSPORT_TLS\n */\n public static final String FIELD_TRANSPORT = \"transport\";\n /**\n * Default scheme to automatically add for this account when calling without uri scheme.<br/>\n * \n * This is free field but should be one of :\n * sip, sips, tel\n * If invalid (or empty) will automatically fallback to sip\n */\n public static final String FIELD_DEFAULT_URI_SCHEME = \"default_uri_scheme\";\n /**\n * Way the application should use SRTP. <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a34b00edb1851924a99efd8fedab917ba\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_USE_SRTP = \"use_srtp\";\n /**\n * Way the application should use SRTP. <br/>\n * -1 means use default global value of {@link SipConfigManager#USE_ZRTP} <br/>\n * 0 means disabled for this account <br/>\n * 1 means enabled for this account\n * \n * @see Integer\n */\n public static final String FIELD_USE_ZRTP = \"use_zrtp\";\n\n /**\n * Optional URI of the proxies to be visited for all outgoing requests that\n * are using this account (REGISTER, INVITE, etc).<br/>\n * If multiple separate it by {@link #PROXIES_SEPARATOR}. <br/>\n * Warning, for now api doesn't allow multiple credentials so if you have\n * one credential per proxy may not work.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a93ad0699020c17ddad5eb98dea69f699\"\n * >Pjsip documentation</a>\n * \n * @see String\n * @see #PROXIES_SEPARATOR\n */\n public static final String FIELD_PROXY = \"proxy\";\n /**\n * Specify how the registration uses the outbound and account proxy\n * settings. <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#ad932bbb3c2c256f801c775319e645717\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_REG_USE_PROXY = \"reg_use_proxy\";\n\n // For now, assume unique credential\n /**\n * Realm to filter on for credentials.<br/>\n * Put star \"*\" char if you want it to match all requests.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a96eee6bdc2b0e7e3b7eea9b4e1c15674\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_REALM = \"realm\";\n /**\n * Scheme (e.g. \"digest\").<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#ae31c9ec1c99fb1ffa20be5954ee995a7\"\n * >Pjsip documentation</a>\n * \n * @see String\n * @see #CRED_SCHEME_DIGEST\n * @see #CRED_SCHEME_PGP\n */\n public static final String FIELD_SCHEME = \"scheme\";\n /**\n * Credential username.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a3e1f72a171886985c6dfcd57d4bc4f17\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_USERNAME = \"username\";\n /**\n * Type of the data for credentials.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a8b1e563c814bdf8012f0bdf966d0ad9d\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n * @see #CRED_DATA_PLAIN_PASSWD\n * @see #CRED_DATA_DIGEST\n * @see #CRED_CRED_DATA_EXT_AKA\n */\n public static final String FIELD_DATATYPE = \"datatype\";\n /**\n * The data, which can be a plaintext password or a hashed digest.<br/>\n * This is available on in read only for third party application for obvious\n * security reason.<br/>\n * If you update the content provider without passing this parameter it will\n * not override it. <br/>\n * If in a third party app you want to store the password to allow user to\n * see it, you have to manage this by your own. <br/>\n * However, it's highly recommanded to not store it by your own, and keep it\n * stored only in csipsimple.<br/>\n * It available for write/overwrite. <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#ab3947a7800c51d28a1b25f4fdaea78bd\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_DATA = \"data\";\n \n /**\n * If this flag is set, the authentication client framework will send an empty Authorization header in each initial request. Default is no.\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/docs/latest/pjsip/docs/html/structpjsip__auth__clt__pref.htm#ac3487e53d8d6b3ea392315b08e2aac4a\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_AUTH_INITIAL_AUTH = \"initial_auth\";\n \n /**\n * If this flag is set, the authentication client framework will send an empty Authorization header in each initial request. Default is no.\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/docs/latest/pjsip/docs/html/structpjsip__auth__clt__pref.htm#ac3487e53d8d6b3ea392315b08e2aac4a\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_AUTH_ALGO = \"auth_algo\";\n\n // Android stuff\n /**\n * The backend sip stack to use for this account.<br/>\n * For now only pjsip backend is supported.\n * \n * @see Integer\n * @see #PJSIP_STACK\n * @see #GOOGLE_STACK\n */\n public static final String FIELD_SIP_STACK = \"sip_stack\";\n /**\n * Sip contact to call if user want to consult his voice mail.<br/>\n * \n * @see String\n */\n public static final String FIELD_VOICE_MAIL_NBR = \"vm_nbr\";\n /**\n * Associated contact group for buddy list of this account.<br/>\n * Users of this group will be considered as part of the buddy list of this\n * account and will automatically try to subscribe presence if activated.<br/>\n * Warning : not implemented for now.\n * \n * @see String\n */\n public static final String FIELD_ANDROID_GROUP = \"android_group\";\n\n // Sip outbound\n /**\n * Control the use of SIP outbound feature. <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a306e4641988606f1ef0993e398ff98e7\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_USE_RFC5626 = \"use_rfc5626\";\n /**\n * Specify SIP outbound (RFC 5626) instance ID to be used by this\n * application.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#ae025bf4538d1f9f9506b45015a46a8f6\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_RFC5626_INSTANCE_ID = \"rfc5626_instance_id\";\n /**\n * Specify SIP outbound (RFC 5626) registration ID.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a71376e1f32e35401fc6c2c3bcb2087d8\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_RFC5626_REG_ID = \"rfc5626_reg_id\";\n\n // Video config\n /**\n * Auto show video of the remote party.<br/>\n * TODO : complete when pjsip-2.x stable documentation out\n */\n public static final String FIELD_VID_IN_AUTO_SHOW = \"vid_in_auto_show\";\n /**\n * Auto transmit video of our party.<br/>\n * TODO : complete when pjsip-2.x stable documentation out\n */\n public static final String FIELD_VID_OUT_AUTO_TRANSMIT = \"vid_out_auto_transmit\";\n\n // RTP config\n /**\n * Begin RTP port for the media of this account.<br/>\n * By default it will use {@link SipConfigManager#RTP_PORT}\n * \n * @see Integer\n */\n public static final String FIELD_RTP_PORT = \"rtp_port\";\n /**\n * Public address to announce in SDP as self media address.<br/>\n * Only use if you have static and known public ip on your device regarding\n * the sip server. <br/>\n * May be helpful in VPN configurations.\n */\n public static final String FIELD_RTP_PUBLIC_ADDR = \"rtp_public_addr\";\n /**\n * Address to bound from client to enforce on interface to be used. <br/>\n * By default the application bind all addresses. (0.0.0.0).<br/>\n * This is only useful if you want to avoid one interface to be bound, but\n * is useless to get audio path correctly working use\n * {@link #FIELD_RTP_PUBLIC_ADDR}\n */\n public static final String FIELD_RTP_BOUND_ADDR = \"rtp_bound_addr\";\n /**\n * Should the QoS be enabled on this account.<br/>\n * By default it will use {@link SipConfigManager#ENABLE_QOS}.<br/>\n * Default value is -1 to use global setting. 0 means disabled, 1 means\n * enabled.<br/>\n * \n * @see Integer\n * @see SipConfigManager#ENABLE_QOS\n */\n public static final String FIELD_RTP_ENABLE_QOS = \"rtp_enable_qos\";\n /**\n * The value of DSCP.<br/>\n * \n * @see Integer\n * @see SipConfigManager#DSCP_VAL\n */\n public static final String FIELD_RTP_QOS_DSCP = \"rtp_qos_dscp\";\n\n /**\n * Should the application try to clean registration of all sip clients if no\n * registration found.<br/>\n * This is useful if the sip server manage limited serveral concurrent\n * registrations.<br/>\n * Since in this case the registrations may leak in case of failing\n * unregisters, this option will unregister all contacts previously\n * registred.\n * \n * @see Boolean\n */\n public static final String FIELD_TRY_CLEAN_REGISTERS = \"try_clean_reg\";\n \n \n /**\n * This option is used to overwrite the \"sent-by\" field of the Via header\n * for outgoing messages with the same interface address as the one in\n * the REGISTER request, as long as the request uses the same transport\n * instance as the previous REGISTER request. <br/>\n *\n * Default: false <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm\"\n * >Pjsip documentation</a>\n * \n * @see Boolean\n */\n public static final String FIELD_ALLOW_VIA_REWRITE = \"allow_via_rewrite\";\n\n /**\n * This option controls whether the IP address in SDP should be replaced\n * with the IP address found in Via header of the REGISTER response, ONLY\n * when STUN and ICE are not used. If the value is FALSE (the original\n * behavior), then the local IP address will be used. If TRUE, and when\n * STUN and ICE are disabled, then the IP address found in registration\n * response will be used.\n *\n * Default:no\n * \n * @see Boolean\n */\n public static final String FIELD_ALLOW_SDP_NAT_REWRITE = \"allow_sdp_nat_rewrite\";\n \n /**\n * Control the use of STUN for the SIP signaling.\n */\n public static final String FIELD_SIP_STUN_USE = \"sip_stun_use\";\n \n /**\n * Control the use of STUN for the transports.\n */\n public static final String FIELD_MEDIA_STUN_USE = \"media_stun_use\";\n \n /**\n * Control the use of ICE in the account. \n * By default, the settings in the pjsua_media_config will be used. \n */\n public static final String FIELD_ICE_CFG_USE = \"ice_cfg_use\";\n\n /**\n * Enable ICE. \n */\n public static final String FIELD_ICE_CFG_ENABLE = \"ice_cfg_enable\";\n \n /**\n * Control the use of TURN in the account. \n * By default, the settings in the pjsua_media_config will be used. \n */\n public static final String FIELD_TURN_CFG_USE = \"turn_cfg_use\";\n \n /**\n * Enable TURN.\n */\n public static final String FIELD_TURN_CFG_ENABLE = \"turn_cfg_enable\";\n \n /**\n * TURN server.\n */\n public static final String FIELD_TURN_CFG_SERVER = \"turn_cfg_server\";\n \n /**\n * TURN username.\n */\n public static final String FIELD_TURN_CFG_USER = \"turn_cfg_user\";\n \n /**\n * TURN password.\n */\n public static final String FIELD_TURN_CFG_PASSWORD = \"turn_cfg_pwd\";\n \n /**\n * Should media use ipv6?\n */\n public static final String FIELD_IPV6_MEDIA_USE = \"ipv6_media_use\";\n \n /**\n * Simple project to use if you want to list accounts with basic infos on it\n * only.\n * \n * @see #FIELD_ACC_ID\n * @see #FIELD_ACTIVE\n * @see #FIELD_WIZARD\n * @see #FIELD_DISPLAY_NAME\n * @see #FIELD_WIZARD\n * @see #FIELD_PRIORITY\n * @see #FIELD_REG_URI\n */\n public static final String[] LISTABLE_PROJECTION = new String[] {\n SipProfile.FIELD_ID,\n SipProfile.FIELD_ACC_ID,\n SipProfile.FIELD_ACTIVE,\n SipProfile.FIELD_DISPLAY_NAME,\n SipProfile.FIELD_WIZARD,\n SipProfile.FIELD_PRIORITY,\n SipProfile.FIELD_REG_URI\n };\n\n // Properties\n /**\n * Primary key for serialization of the object.\n */\n public int primaryKey = -1;\n /**\n * @see #FIELD_ID\n */\n public long id = INVALID_ID;\n /**\n * @see #FIELD_DISPLAY_NAME\n */\n public String display_name = \"\";\n /**\n * @see #FIELD_WIZARD\n */\n public String wizard = \"EXPERT\";\n /**\n * @see #FIELD_TRANSPORT\n */\n public Integer transport = 0;\n /**\n * @see #FIELD_DEFAULT_URI_SCHEME\n */\n public String default_uri_scheme = \"sip\";\n /**\n * @see #FIELD_ACTIVE\n */\n public boolean active = true;\n /**\n * @see #FIELD_PRIORITY\n */\n public int priority = 100;\n /**\n * @see #FIELD_ACC_ID\n */\n public String acc_id = null;\n\n /**\n * @see #FIELD_REG_URI\n */\n public String reg_uri = null;\n /**\n * @see #FIELD_PUBLISH_ENABLED\n */\n public int publish_enabled = 0;\n /**\n * @see #FIELD_REG_TIMEOUT\n */\n public int reg_timeout = 900;\n /**\n * @see #FIELD_KA_INTERVAL\n */\n public int ka_interval = 0;\n /**\n * @see #FIELD_PIDF_TUPLE_ID\n */\n public String pidf_tuple_id = null;\n /**\n * @see #FIELD_FORCE_CONTACT\n */\n public String force_contact = null;\n /**\n * @see #FIELD_ALLOW_CONTACT_REWRITE\n */\n public boolean allow_contact_rewrite = true;\n /**\n * @see #FIELD_CONTACT_REWRITE_METHOD\n */\n public int contact_rewrite_method = 2;\n /**\n * @see #FIELD_ALLOW_VIA_REWRITE\n */\n public boolean allow_via_rewrite = false;\n /**\n * @see #FIELD_ALLOW_SDP_NAT_REWRITE\n */\n public boolean allow_sdp_nat_rewrite = false;\n /**\n * Exploded array of proxies\n * \n * @see #FIELD_PROXY\n */\n public String[] proxies = null;\n /**\n * @see #FIELD_REALM\n */\n public String realm = null;\n /**\n * @see #FIELD_USERNAME\n */\n public String username = null;\n /**\n * @see #FIELD_SCHEME\n */\n public String scheme = null;\n /**\n * @see #FIELD_DATATYPE\n */\n public int datatype = 0;\n /**\n * @see #FIELD_DATA\n */\n public String data = null;\n /**\n * @see #FIELD_AUTH_INITIAL_AUTH\n */\n public boolean initial_auth = false;\n /**\n * @see #FIELD_AUTH_ALGO\n */\n public String auth_algo = \"\"; \n /**\n * @see #FIELD_USE_SRTP\n */\n public int use_srtp = -1;\n /**\n * @see #FIELD_USE_ZRTP\n */\n public int use_zrtp = -1;\n /**\n * @see #FIELD_REG_USE_PROXY\n */\n public int reg_use_proxy = 3;\n /**\n * @see #FIELD_SIP_STACK\n */\n public int sip_stack = PJSIP_STACK;\n /**\n * @see #FIELD_VOICE_MAIL_NBR\n */\n public String vm_nbr = null;\n /**\n * @see #FIELD_REG_DELAY_BEFORE_REFRESH\n */\n public int reg_delay_before_refresh = -1;\n /**\n * @see #FIELD_TRY_CLEAN_REGISTERS\n */\n public int try_clean_registers = 1;\n /**\n * Chache holder icon for the account wizard representation.<br/>\n * This will not not be filled by default. You have to get it from wizard\n * infos.\n */\n public Bitmap icon = null;\n /**\n * @see #FIELD_USE_RFC5626\n */\n public boolean use_rfc5626 = true;\n /**\n * @see #FIELD_RFC5626_INSTANCE_ID\n */\n public String rfc5626_instance_id = \"\";\n /**\n * @see #FIELD_RFC5626_REG_ID\n */\n public String rfc5626_reg_id = \"\";\n /**\n * @see #FIELD_VID_IN_AUTO_SHOW\n */\n public int vid_in_auto_show = -1;\n /**\n * @see #FIELD_VID_OUT_AUTO_TRANSMIT\n */\n public int vid_out_auto_transmit = -1;\n /**\n * @see #FIELD_RTP_PORT\n */\n public int rtp_port = -1;\n /**\n * @see #FIELD_RTP_PUBLIC_ADDR\n */\n public String rtp_public_addr = \"\";\n /**\n * @see #FIELD_RTP_BOUND_ADDR\n */\n public String rtp_bound_addr = \"\";\n /**\n * @see #FIELD_RTP_ENABLE_QOS\n */\n public int rtp_enable_qos = -1;\n /**\n * @see #FIELD_RTP_QOS_DSCP\n */\n public int rtp_qos_dscp = -1;\n /**\n * @see #FIELD_ANDROID_GROUP\n */\n public String android_group = \"\";\n /**\n * @see #FIELD_MWI_ENABLED\n */\n public boolean mwi_enabled = true;\n /**\n * @see #FIELD_SIP_STUN_USE\n */\n public int sip_stun_use = -1;\n /**\n * @see #FIELD_MEDIA_STUN_USE\n */\n public int media_stun_use = -1;\n /**\n * @see #FIELD_ICE_CFG_USE\n */\n public int ice_cfg_use = -1;\n /**\n * @see #FIELD_ICE_CFG_ENABLE\n */\n public int ice_cfg_enable = 0;\n /**\n * @see #FIELD_TURN_CFG_USE\n */\n public int turn_cfg_use = -1;\n /**\n * @see #FIELD_TURN_CFG_ENABLE\n */\n public int turn_cfg_enable = 0;\n /**\n * @see #FIELD_TURN_CFG_SERVER\n */\n public String turn_cfg_server = \"\";\n /**\n * @see #FIELD_TURN_CFG_USER\n */\n public String turn_cfg_user = \"\";\n /**\n * @see #FIELD_TURN_CFG_PASSWORD\n */\n public String turn_cfg_password = \"\";\n /**\n * @see #FIELD_IPV6_MEDIA_USE\n */\n public int ipv6_media_use = 0;\n /**\n * @see #FIELD_WIZARD_DATA\n */\n public String wizard_data = \"\";\n \n public SipProfile() {\n display_name = \"\";\n wizard = \"EXPERT\";\n active = true;\n }\n\n /**\n * Construct a sip profile wrapper from a cursor retrieved with a\n * {@link ContentProvider} query on {@link #ACCOUNTS_TABLE_NAME}.\n * \n * @param c the cursor to unpack\n */\n public SipProfile(Cursor c) {\n super();\n createFromDb(c);\n }\n\n /**\n * Construct from parcelable <br/>\n * Only used by {@link #CREATOR}\n * \n * @param in parcelable to build from\n */\n private SipProfile(Parcel in) {\n primaryKey = in.readInt();\n id = in.readInt();\n display_name = in.readString();\n wizard = in.readString();\n transport = in.readInt();\n active = (in.readInt() != 0) ? true : false;\n priority = in.readInt();\n acc_id = getReadParcelableString(in.readString());\n reg_uri = getReadParcelableString(in.readString());\n publish_enabled = in.readInt();\n reg_timeout = in.readInt();\n ka_interval = in.readInt();\n pidf_tuple_id = getReadParcelableString(in.readString());\n force_contact = getReadParcelableString(in.readString());\n proxies = TextUtils.split(getReadParcelableString(in.readString()),\n Pattern.quote(PROXIES_SEPARATOR));\n realm = getReadParcelableString(in.readString());\n username = getReadParcelableString(in.readString());\n datatype = in.readInt();\n data = getReadParcelableString(in.readString());\n use_srtp = in.readInt();\n allow_contact_rewrite = (in.readInt() != 0);\n contact_rewrite_method = in.readInt();\n sip_stack = in.readInt();\n reg_use_proxy = in.readInt();\n use_zrtp = in.readInt();\n vm_nbr = getReadParcelableString(in.readString());\n reg_delay_before_refresh = in.readInt();\n icon = (Bitmap) in.readParcelable(Bitmap.class.getClassLoader());\n try_clean_registers = in.readInt();\n use_rfc5626 = (in.readInt() != 0);\n rfc5626_instance_id = getReadParcelableString(in.readString());\n rfc5626_reg_id = getReadParcelableString(in.readString());\n vid_in_auto_show = in.readInt();\n vid_out_auto_transmit = in.readInt();\n rtp_port = in.readInt();\n rtp_public_addr = getReadParcelableString(in.readString());\n rtp_bound_addr = getReadParcelableString(in.readString());\n rtp_enable_qos = in.readInt();\n rtp_qos_dscp = in.readInt();\n android_group = getReadParcelableString(in.readString());\n mwi_enabled = (in.readInt() != 0);\n allow_via_rewrite = (in.readInt() != 0);\n sip_stun_use = in.readInt();\n media_stun_use = in.readInt();\n ice_cfg_use = in.readInt();\n ice_cfg_enable = in.readInt();\n turn_cfg_use = in.readInt();\n turn_cfg_enable = in.readInt();\n turn_cfg_server = getReadParcelableString(in.readString());\n turn_cfg_user = getReadParcelableString(in.readString());\n turn_cfg_password = getReadParcelableString(in.readString());\n ipv6_media_use = in.readInt();\n initial_auth = (in.readInt() != 0);\n auth_algo = getReadParcelableString(in.readString());\n wizard_data = getReadParcelableString(in.readString());\n default_uri_scheme = getReadParcelableString(in.readString());\n allow_sdp_nat_rewrite = (in.readInt() != 0);\n }\n\n /**\n * Parcelable creator. So that it can be passed as an argument of the aidl\n * interface\n */\n public static final Creator<SipProfile> CREATOR = new Creator<SipProfile>() {\n public SipProfile createFromParcel(Parcel in) {\n return new SipProfile(in);\n }\n\n public SipProfile[] newArray(int size) {\n return new SipProfile[size];\n }\n };\n\n /**\n * @see Parcelable#describeContents()\n */\n @Override\n public int describeContents() {\n return 0;\n }\n\n /**\n * @see Parcelable#writeToParcel(Parcel, int)\n */\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(primaryKey);\n dest.writeInt((int) id);\n dest.writeString(display_name);\n dest.writeString(wizard);\n dest.writeInt(transport);\n dest.writeInt(active ? 1 : 0);\n dest.writeInt(priority);\n dest.writeString(getWriteParcelableString(acc_id));\n dest.writeString(getWriteParcelableString(reg_uri));\n dest.writeInt(publish_enabled);\n dest.writeInt(reg_timeout);\n dest.writeInt(ka_interval);\n dest.writeString(getWriteParcelableString(pidf_tuple_id));\n dest.writeString(getWriteParcelableString(force_contact));\n if (proxies != null) {\n dest.writeString(getWriteParcelableString(TextUtils.join(PROXIES_SEPARATOR, proxies)));\n } else {\n dest.writeString(\"\");\n }\n dest.writeString(getWriteParcelableString(realm));\n dest.writeString(getWriteParcelableString(username));\n dest.writeInt(datatype);\n dest.writeString(getWriteParcelableString(data));\n dest.writeInt(use_srtp);\n dest.writeInt(allow_contact_rewrite ? 1 : 0);\n dest.writeInt(contact_rewrite_method);\n dest.writeInt(sip_stack);\n dest.writeInt(reg_use_proxy);\n dest.writeInt(use_zrtp);\n dest.writeString(getWriteParcelableString(vm_nbr));\n dest.writeInt(reg_delay_before_refresh);\n dest.writeParcelable((Parcelable) icon, flags);\n dest.writeInt(try_clean_registers);\n dest.writeInt(use_rfc5626 ? 1 : 0);\n dest.writeString(getWriteParcelableString(rfc5626_instance_id));\n dest.writeString(getWriteParcelableString(rfc5626_reg_id));\n dest.writeInt(vid_in_auto_show);\n dest.writeInt(vid_out_auto_transmit);\n dest.writeInt(rtp_port);\n dest.writeString(getWriteParcelableString(rtp_public_addr));\n dest.writeString(getWriteParcelableString(rtp_bound_addr));\n dest.writeInt(rtp_enable_qos);\n dest.writeInt(rtp_qos_dscp);\n dest.writeString(getWriteParcelableString(android_group));\n dest.writeInt(mwi_enabled ? 1 : 0);\n dest.writeInt(allow_via_rewrite ? 1 : 0);\n dest.writeInt(sip_stun_use);\n dest.writeInt(media_stun_use);\n dest.writeInt(ice_cfg_use);\n dest.writeInt(ice_cfg_enable);\n dest.writeInt(turn_cfg_use);\n dest.writeInt(turn_cfg_enable);\n dest.writeString(getWriteParcelableString(turn_cfg_server));\n dest.writeString(getWriteParcelableString(turn_cfg_user));\n dest.writeString(getWriteParcelableString(turn_cfg_password));\n dest.writeInt(ipv6_media_use);\n dest.writeInt(initial_auth ? 1 : 0);\n dest.writeString(getWriteParcelableString(auth_algo));\n dest.writeString(getWriteParcelableString(wizard_data));\n dest.writeString(getWriteParcelableString(default_uri_scheme));\n dest.writeInt(allow_sdp_nat_rewrite ? 1 : 0);\n }\n\n // Yes yes that's not clean but well as for now not problem with that.\n // and we send null.\n private String getWriteParcelableString(String str) {\n return (str == null) ? \"null\" : str;\n }\n\n private String getReadParcelableString(String str) {\n return str.equalsIgnoreCase(\"null\") ? null : str;\n }\n\n /**\n * Create account wrapper with cursor datas.\n * \n * @param c cursor on the database\n */\n private final void createFromDb(Cursor c) {\n ContentValues args = new ContentValues();\n DatabaseUtils.cursorRowToContentValues(c, args);\n createFromContentValue(args);\n }\n\n /**\n * Create account wrapper with content values pairs.\n * \n * @param args the content value to unpack.\n */\n private final void createFromContentValue(ContentValues args) {\n Integer tmp_i;\n String tmp_s;\n \n // Application specific settings\n tmp_i = args.getAsInteger(FIELD_ID);\n if (tmp_i != null) {\n id = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_DISPLAY_NAME);\n if (tmp_s != null) {\n display_name = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_WIZARD);\n if (tmp_s != null) {\n wizard = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_TRANSPORT);\n if (tmp_i != null) {\n transport = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_DEFAULT_URI_SCHEME);\n if (tmp_s != null) {\n default_uri_scheme = tmp_s;\n }\n\n tmp_i = args.getAsInteger(FIELD_ACTIVE);\n if (tmp_i != null) {\n active = (tmp_i != 0);\n } else {\n active = true;\n }\n tmp_s = args.getAsString(FIELD_ANDROID_GROUP);\n if (tmp_s != null) {\n android_group = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_WIZARD_DATA);\n if (tmp_s != null) {\n wizard_data = tmp_s;\n }\n\n // General account settings\n tmp_i = args.getAsInteger(FIELD_PRIORITY);\n if (tmp_i != null) {\n priority = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_ACC_ID);\n if (tmp_s != null) {\n acc_id = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_REG_URI);\n if (tmp_s != null) {\n reg_uri = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_PUBLISH_ENABLED);\n if (tmp_i != null) {\n publish_enabled = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_REG_TIMEOUT);\n if (tmp_i != null && tmp_i >= 0) {\n reg_timeout = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_REG_DELAY_BEFORE_REFRESH);\n if (tmp_i != null && tmp_i >= 0) {\n reg_delay_before_refresh = tmp_i;\n }\n\n tmp_i = args.getAsInteger(FIELD_KA_INTERVAL);\n if (tmp_i != null && tmp_i >= 0) {\n ka_interval = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_PIDF_TUPLE_ID);\n if (tmp_s != null) {\n pidf_tuple_id = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_FORCE_CONTACT);\n if (tmp_s != null) {\n force_contact = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_ALLOW_CONTACT_REWRITE);\n if (tmp_i != null) {\n allow_contact_rewrite = (tmp_i == 1);\n }\n tmp_i = args.getAsInteger(FIELD_CONTACT_REWRITE_METHOD);\n if (tmp_i != null) {\n contact_rewrite_method = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_ALLOW_VIA_REWRITE);\n if (tmp_i != null) {\n allow_via_rewrite = (tmp_i == 1);\n }\n tmp_i = args.getAsInteger(FIELD_ALLOW_SDP_NAT_REWRITE);\n if (tmp_i != null) {\n allow_sdp_nat_rewrite = (tmp_i == 1);\n }\n\n tmp_i = args.getAsInteger(FIELD_USE_SRTP);\n if (tmp_i != null && tmp_i >= 0) {\n use_srtp = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_USE_ZRTP);\n if (tmp_i != null && tmp_i >= 0) {\n use_zrtp = tmp_i;\n }\n\n // Proxy\n tmp_s = args.getAsString(FIELD_PROXY);\n if (tmp_s != null) {\n proxies = TextUtils.split(tmp_s, Pattern.quote(PROXIES_SEPARATOR));\n }\n tmp_i = args.getAsInteger(FIELD_REG_USE_PROXY);\n if (tmp_i != null && tmp_i >= 0) {\n reg_use_proxy = tmp_i;\n }\n\n // Auth\n tmp_s = args.getAsString(FIELD_REALM);\n if (tmp_s != null) {\n realm = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_SCHEME);\n if (tmp_s != null) {\n scheme = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_USERNAME);\n if (tmp_s != null) {\n username = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_DATATYPE);\n if (tmp_i != null) {\n datatype = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_DATA);\n if (tmp_s != null) {\n data = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_AUTH_INITIAL_AUTH);\n if (tmp_i != null) {\n initial_auth = (tmp_i == 1);\n }\n tmp_s = args.getAsString(FIELD_AUTH_ALGO);\n if (tmp_s != null) {\n auth_algo = tmp_s;\n }\n \n\n tmp_i = args.getAsInteger(FIELD_SIP_STACK);\n if (tmp_i != null && tmp_i >= 0) {\n sip_stack = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_MWI_ENABLED);\n if(tmp_i != null && tmp_i >= 0) {\n mwi_enabled = (tmp_i == 1);\n }\n tmp_s = args.getAsString(FIELD_VOICE_MAIL_NBR);\n if (tmp_s != null) {\n vm_nbr = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_TRY_CLEAN_REGISTERS);\n if (tmp_i != null && tmp_i >= 0) {\n try_clean_registers = tmp_i;\n }\n\n // RFC 5626\n tmp_i = args.getAsInteger(FIELD_USE_RFC5626);\n if (tmp_i != null && tmp_i >= 0) {\n use_rfc5626 = (tmp_i != 0);\n }\n tmp_s = args.getAsString(FIELD_RFC5626_INSTANCE_ID);\n if (tmp_s != null) {\n rfc5626_instance_id = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_RFC5626_REG_ID);\n if (tmp_s != null) {\n rfc5626_reg_id = tmp_s;\n }\n\n // Video\n tmp_i = args.getAsInteger(FIELD_VID_IN_AUTO_SHOW);\n if (tmp_i != null && tmp_i >= 0) {\n vid_in_auto_show = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_VID_OUT_AUTO_TRANSMIT);\n if (tmp_i != null && tmp_i >= 0) {\n vid_out_auto_transmit = tmp_i;\n }\n\n // RTP cfg\n tmp_i = args.getAsInteger(FIELD_RTP_PORT);\n if (tmp_i != null && tmp_i >= 0) {\n rtp_port = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_RTP_PUBLIC_ADDR);\n if (tmp_s != null) {\n rtp_public_addr = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_RTP_BOUND_ADDR);\n if (tmp_s != null) {\n rtp_bound_addr = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_RTP_ENABLE_QOS);\n if (tmp_i != null && tmp_i >= 0) {\n rtp_enable_qos = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_RTP_QOS_DSCP);\n if (tmp_i != null && tmp_i >= 0) {\n rtp_qos_dscp = tmp_i;\n }\n \n\n tmp_i = args.getAsInteger(FIELD_SIP_STUN_USE);\n if (tmp_i != null && tmp_i >= 0) {\n sip_stun_use = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_MEDIA_STUN_USE);\n if (tmp_i != null && tmp_i >= 0) {\n media_stun_use = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_ICE_CFG_USE);\n if (tmp_i != null && tmp_i >= 0) {\n ice_cfg_use = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_ICE_CFG_ENABLE);\n if (tmp_i != null && tmp_i >= 0) {\n ice_cfg_enable = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_TURN_CFG_USE);\n if (tmp_i != null && tmp_i >= 0) {\n turn_cfg_use = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_TURN_CFG_ENABLE);\n if (tmp_i != null && tmp_i >= 0) {\n turn_cfg_enable = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_TURN_CFG_SERVER);\n if (tmp_s != null) {\n turn_cfg_server = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_TURN_CFG_USER);\n if (tmp_s != null) {\n turn_cfg_user = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_TURN_CFG_PASSWORD);\n if (tmp_s != null) {\n turn_cfg_password = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_IPV6_MEDIA_USE);\n if (tmp_i != null && tmp_i >= 0) {\n ipv6_media_use = tmp_i;\n }\n }\n\n /**\n * Transform pjsua_acc_config into ContentValues that can be insert into\n * database. <br/>\n * Take care that if your SipProfile is incomplete this content value may\n * also be uncomplete and lead to override unwanted values of the existing\n * database. <br/>\n * So if updating, take care on what you actually want to update instead of\n * using this utility method.\n * \n * @return Complete content values from the current wrapper around sip\n * profile.\n */\n public ContentValues getDbContentValues() {\n ContentValues args = new ContentValues();\n\n if (id != INVALID_ID) {\n args.put(FIELD_ID, id);\n }\n // TODO : ensure of non nullity of some params\n\n args.put(FIELD_ACTIVE, active ? 1 : 0);\n args.put(FIELD_WIZARD, wizard);\n args.put(FIELD_DISPLAY_NAME, display_name);\n args.put(FIELD_TRANSPORT, transport);\n args.put(FIELD_DEFAULT_URI_SCHEME, default_uri_scheme);\n args.put(FIELD_WIZARD_DATA, wizard_data);\n\n args.put(FIELD_PRIORITY, priority);\n args.put(FIELD_ACC_ID, acc_id);\n args.put(FIELD_REG_URI, reg_uri);\n\n args.put(FIELD_PUBLISH_ENABLED, publish_enabled);\n args.put(FIELD_REG_TIMEOUT, reg_timeout);\n args.put(FIELD_KA_INTERVAL, ka_interval);\n args.put(FIELD_PIDF_TUPLE_ID, pidf_tuple_id);\n args.put(FIELD_FORCE_CONTACT, force_contact);\n args.put(FIELD_ALLOW_CONTACT_REWRITE, allow_contact_rewrite ? 1 : 0);\n args.put(FIELD_ALLOW_VIA_REWRITE, allow_via_rewrite ? 1 : 0);\n args.put(FIELD_ALLOW_SDP_NAT_REWRITE, allow_sdp_nat_rewrite ? 1 : 0);\n args.put(FIELD_CONTACT_REWRITE_METHOD, contact_rewrite_method);\n args.put(FIELD_USE_SRTP, use_srtp);\n args.put(FIELD_USE_ZRTP, use_zrtp);\n\n // CONTACT_PARAM and CONTACT_PARAM_URI not yet in JNI\n\n if (proxies != null) {\n args.put(FIELD_PROXY, TextUtils.join(PROXIES_SEPARATOR, proxies));\n } else {\n args.put(FIELD_PROXY, \"\");\n }\n args.put(FIELD_REG_USE_PROXY, reg_use_proxy);\n\n // Assume we have an unique credential\n args.put(FIELD_REALM, realm);\n args.put(FIELD_SCHEME, scheme);\n args.put(FIELD_USERNAME, username);\n args.put(FIELD_DATATYPE, datatype);\n if (!TextUtils.isEmpty(data)) {\n args.put(FIELD_DATA, data);\n }\n args.put(FIELD_AUTH_INITIAL_AUTH, initial_auth ? 1 : 0);\n if(!TextUtils.isEmpty(auth_algo)) {\n args.put(FIELD_AUTH_ALGO, auth_algo);\n }\n\n args.put(FIELD_SIP_STACK, sip_stack);\n args.put(FIELD_MWI_ENABLED, mwi_enabled);\n args.put(FIELD_VOICE_MAIL_NBR, vm_nbr);\n args.put(FIELD_REG_DELAY_BEFORE_REFRESH, reg_delay_before_refresh);\n args.put(FIELD_TRY_CLEAN_REGISTERS, try_clean_registers);\n \n \n args.put(FIELD_RTP_BOUND_ADDR, rtp_bound_addr);\n args.put(FIELD_RTP_ENABLE_QOS, rtp_enable_qos);\n args.put(FIELD_RTP_PORT, rtp_port);\n args.put(FIELD_RTP_PUBLIC_ADDR, rtp_public_addr);\n args.put(FIELD_RTP_QOS_DSCP, rtp_qos_dscp);\n \n args.put(FIELD_VID_IN_AUTO_SHOW, vid_in_auto_show);\n args.put(FIELD_VID_OUT_AUTO_TRANSMIT, vid_out_auto_transmit);\n \n args.put(FIELD_RFC5626_INSTANCE_ID, rfc5626_instance_id);\n args.put(FIELD_RFC5626_REG_ID, rfc5626_reg_id);\n args.put(FIELD_USE_RFC5626, use_rfc5626 ? 1 : 0);\n\n args.put(FIELD_ANDROID_GROUP, android_group);\n \n args.put(FIELD_SIP_STUN_USE, sip_stun_use);\n args.put(FIELD_MEDIA_STUN_USE, media_stun_use);\n args.put(FIELD_ICE_CFG_USE, ice_cfg_use);\n args.put(FIELD_ICE_CFG_ENABLE, ice_cfg_enable);\n args.put(FIELD_TURN_CFG_USE, turn_cfg_use);\n args.put(FIELD_TURN_CFG_ENABLE, turn_cfg_enable);\n args.put(FIELD_TURN_CFG_SERVER, turn_cfg_server);\n args.put(FIELD_TURN_CFG_USER, turn_cfg_user);\n args.put(FIELD_TURN_CFG_PASSWORD, turn_cfg_password);\n \n args.put(FIELD_IPV6_MEDIA_USE, ipv6_media_use);\n \n return args;\n }\n\n /**\n * Get the default domain for this account\n * \n * @return the default domain for this account\n */\n public String getDefaultDomain() {\n ParsedSipContactInfos parsedAoR = SipUri.parseSipContact(acc_id);\n ParsedSipUriInfos parsedInfo = null;\n if(TextUtils.isEmpty(parsedAoR.domain)) {\n // Try to fallback\n if (!TextUtils.isEmpty(reg_uri)) {\n parsedInfo = SipUri.parseSipUri(reg_uri);\n } else if (proxies != null && proxies.length > 0) {\n parsedInfo = SipUri.parseSipUri(proxies[0]);\n }\n }else {\n parsedInfo = parsedAoR.getServerSipUri();\n }\n\n if (parsedInfo == null) {\n return null;\n }\n\n if (parsedInfo.domain != null) {\n String dom = parsedInfo.domain;\n if (parsedInfo.port != 5060) {\n dom += \":\" + Integer.toString(parsedInfo.port);\n }\n return dom;\n } else {\n Log.d(THIS_FILE, \"Domain not found for this account\");\n }\n return null;\n }\n\n // Android API\n\n /**\n * Gets the flag of 'Auto Registration'\n * \n * @return true if auto register this account\n */\n public boolean getAutoRegistration() {\n return true;\n }\n\n /**\n * Gets the display name of the user.\n * \n * @return the caller id for this account\n */\n public String getDisplayName() {\n if (acc_id != null) {\n ParsedSipContactInfos parsed = SipUri.parseSipContact(acc_id);\n if (parsed.displayName != null) {\n return parsed.displayName;\n }\n }\n return \"\";\n }\n\n /**\n * Gets the password.\n * \n * @return the password of the sip profile Using this from an external\n * application will always be empty\n */\n public String getPassword() {\n return data;\n }\n\n /**\n * Gets the (user-defined) name of the profile.\n * \n * @return the display name for this profile\n */\n public String getProfileName() {\n return display_name;\n }\n\n /**\n * Gets the network address of the server outbound proxy.\n * \n * @return the first proxy server if any else empty string\n */\n public String getProxyAddress() {\n if (proxies != null && proxies.length > 0) {\n return proxies[0];\n }\n return \"\";\n }\n\n /**\n * Gets the SIP domain when acc_id is username@domain.\n * \n * @return the sip domain for this account\n */\n public String getSipDomain() {\n ParsedSipContactInfos parsed = SipUri.parseSipContact(acc_id);\n if (parsed.domain != null) {\n return parsed.domain;\n }\n return \"\";\n }\n\n /**\n * Gets the SIP URI string of this profile.\n */\n public String getUriString() {\n return acc_id;\n }\n\n /**\n * Gets the username when acc_id is username@domain. WARNING : this is\n * different from username of SipProfile which is the authentication name\n * cause of pjsip naming\n * \n * @return the username of the account sip id. <br/>\n * Example if acc_id is \"Display Name\" <sip:[email protected]>, it\n * will return user.\n */\n public String getSipUserName() {\n ParsedSipContactInfos parsed = SipUri.parseSipContact(acc_id);\n if (parsed.userName != null) {\n return parsed.userName;\n }\n return \"\";\n }\n \n public ParsedSipContactInfos formatCalleeNumber(String fuzzyNumber) {\n ParsedSipContactInfos finalCallee = SipUri.parseSipContact(fuzzyNumber);\n\n if (TextUtils.isEmpty(finalCallee.domain)) {\n String defaultDomain = getDefaultDomain();\n if(TextUtils.isEmpty(defaultDomain)) {\n finalCallee.domain = finalCallee.userName;\n finalCallee.userName = null;\n }else {\n finalCallee.domain = defaultDomain;\n }\n }\n if (TextUtils.isEmpty(finalCallee.scheme)) {\n if (!TextUtils.isEmpty(default_uri_scheme)) {\n finalCallee.scheme = default_uri_scheme;\n } else {\n finalCallee.scheme = SipManager.PROTOCOL_SIP;\n }\n }\n return finalCallee;\n }\n\n // Helpers static factory\n /**\n * Helper method to retrieve a SipProfile object from its account database\n * id.<br/>\n * You have to specify the projection you want to use for to retrieve infos.<br/>\n * As consequence the wrapper SipProfile object you'll get may be\n * incomplete. So take care if you try to reinject it by updating to not\n * override existing values of the database that you don't get here.\n * \n * @param ctxt Your application context. Mainly useful to get the content provider for the request.\n * @param accountId The sip profile {@link #FIELD_ID} you want to retrieve.\n * @param projection The list of fields you want to retrieve. Must be in FIELD_* of this class.<br/>\n * Reducing your requested fields to minimum will improve speed of the request.\n * @return A wrapper SipProfile object on the request you done. If not found an invalid account with an {@link #id} equals to {@link #INVALID_ID}\n */\n public static SipProfile getProfileFromDbId(Context ctxt, long accountId, String[] projection) {\n SipProfile account = new SipProfile();\n if (accountId != INVALID_ID) {\n Cursor c = ctxt.getContentResolver().query(\n ContentUris.withAppendedId(ACCOUNT_ID_URI_BASE, accountId),\n projection, null, null, null);\n\n if (c != null) {\n try {\n if (c.getCount() > 0) {\n c.moveToFirst();\n account = new SipProfile(c);\n }\n } catch (Exception e) {\n Log.e(THIS_FILE, \"Something went wrong while retrieving the account\", e);\n } finally {\n c.close();\n }\n }\n }\n return account;\n }\n\n /**\n * Get the list of sip profiles available.\n * @param ctxt Your application context. Mainly useful to get the content provider for the request.\n * @param onlyActive Pass it to true if you are only interested in active accounts.\n * @return The list of SipProfiles containings only fields of {@link #LISTABLE_PROJECTION} filled.\n * @see #LISTABLE_PROJECTION\n */\n public static ArrayList<SipProfile> getAllProfiles(Context ctxt, boolean onlyActive) {\n return getAllProfiles(ctxt, onlyActive, LISTABLE_PROJECTION);\n }\n \n /**\n * Get the list of sip profiles available.\n * @param ctxt Your application context. Mainly useful to get the content provider for the request.\n * @param onlyActive Pass it to true if you are only interested in active accounts.\n * @param projection The projection to use for cursor\n * @return The list of SipProfiles\n */\n public static ArrayList<SipProfile> getAllProfiles(Context ctxt, boolean onlyActive, String[] projection) {\n ArrayList<SipProfile> result = new ArrayList<SipProfile>();\n\n String selection = null;\n String[] selectionArgs = null;\n if (onlyActive) {\n selection = SipProfile.FIELD_ACTIVE + \"=?\";\n selectionArgs = new String[] {\n \"1\"\n };\n }\n Cursor c = ctxt.getContentResolver().query(ACCOUNT_URI, projection, selection, selectionArgs, null);\n\n if (c != null) {\n try {\n if (c.moveToFirst()) {\n do {\n result.add(new SipProfile(c));\n } while (c.moveToNext());\n }\n } catch (Exception e) {\n Log.e(THIS_FILE, \"Error on looping over sip profiles\", e);\n } finally {\n c.close();\n }\n }\n\n return result;\n }\n}",
"public class SipService extends Service {\n\n\t\n\t// static boolean creating = false;\n\tprivate static final String THIS_FILE = \"SIP SRV\";\n\n\tprivate SipWakeLock sipWakeLock;\n\tprivate boolean autoAcceptCurrent = false;\n\tpublic boolean supportMultipleCalls = false;\n\t\n\t// For video testing -- TODO : remove\n\tprivate static SipService singleton = null;\n\t\n\n\t// Implement public interface for the service\n\tprivate final ISipService.Stub binder = new ISipService.Stub() {\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void sipStart() throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tLog.d(THIS_FILE, \"Start required from third party app/serv\");\n\t\t\tgetExecutor().execute(new StartRunnable());\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void sipStop() throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tgetExecutor().execute(new StopRunnable());\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void forceStopService() throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tLog.d(THIS_FILE, \"Try to force service stop\");\n\t\t\tcleanStop();\n\t\t\t//stopSelf();\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void askThreadedRestart() throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tLog.d(THIS_FILE, \"Restart required from third part app/serv\");\n\t\t\tgetExecutor().execute(new RestartRunnable());\n\t\t};\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void addAllAccounts() throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tpublic void doRun() throws SameThreadException {\n\t\t\t\t\tSipService.this.addAllAccounts();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void removeAllAccounts() throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tpublic void doRun() throws SameThreadException {\n\t\t\t\t\tSipService.this.unregisterAllAccounts(true);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void reAddAllAccounts() throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tpublic void doRun() throws SameThreadException {\n\t\t\t\t\tSipService.this.reAddAllAccounts();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void setAccountRegistration(int accountId, int renew) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\t\n\t\t\tfinal SipProfile acc = getAccount(accountId);\n\t\t\tif(acc != null) {\n\t\t\t\tfinal int ren = renew;\n\t\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void doRun() throws SameThreadException {\n\t\t\t\t\t\tSipService.this.setAccountRegistration(acc, ren, false);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic SipProfileState getSipProfileState(int accountId) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\treturn SipService.this.getSipProfileState(accountId);\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void switchToAutoAnswer() throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tLog.d(THIS_FILE, \"Switch to auto answer\");\n\t\t\tsetAutoAnswerNext(true);\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void makeCall(final String callee, final int accountId) throws RemoteException {\n\t\t\tmakeCallWithOptions(callee, accountId, null);\n\t\t}\n\t\t\n\n @Override\n public void makeCallWithOptions(final String callee, final int accountId, final Bundle options)\n throws RemoteException {\n SipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n //We have to ensure service is properly started and not just binded\n SipService.this.startService(new Intent(SipService.this, SipService.class));\n \n if(pjService == null) {\n Log.e(THIS_FILE, \"Can't place call if service not started\");\n // TODO - we should return a failing status here\n return;\n }\n \n if(!supportMultipleCalls) {\n // Check if there is no ongoing calls if so drop this request by alerting user\n SipCallSession activeCall = pjService.getActiveCallInProgress();\n if(activeCall != null) {\n if(!CustomDistribution.forceNoMultipleCalls()) {\n notifyUserOfMessage(R.string.not_configured_multiple_calls);\n }\n return;\n }\n }\n \n Intent intent = new Intent(SipManager.ACTION_SIP_CALL_LAUNCH);\n intent.putExtra(SipProfile.FIELD_ID, accountId);\n intent.putExtra(SipManager.EXTRA_SIP_CALL_TARGET, callee);\n intent.putExtra(SipManager.EXTRA_SIP_CALL_OPTIONS, options);\n sendOrderedBroadcast (intent , SipManager.PERMISSION_USE_SIP, mPlaceCallResultReceiver, null, Activity.RESULT_OK, null, null);\n \n }\n\t\t\n private BroadcastReceiver mPlaceCallResultReceiver = new BroadcastReceiver() {\n\n @Override\n public void onReceive(Context context, final Intent intent) {\n final Bundle extras = intent.getExtras();\n final String action = intent.getAction();\n if(extras == null) {\n Log.e(THIS_FILE, \"No data in intent retrieved for call\");\n return;\n }\n if(!SipManager.ACTION_SIP_CALL_LAUNCH.equals(action)) {\n Log.e(THIS_FILE, \"Received invalid action \" + action);\n return;\n }\n\n final int accountId = extras.getInt(SipProfile.FIELD_ID, -2);\n final String callee = extras.getString(SipManager.EXTRA_SIP_CALL_TARGET);\n final Bundle options = extras.getBundle(SipManager.EXTRA_SIP_CALL_OPTIONS);\n if(accountId == -2 || callee == null) {\n Log.e(THIS_FILE, \"Invalid rewrite \" + accountId);\n return;\n }\n \n getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n pjService.makeCall(callee, accountId, options);\n }\n });\n }\n };\n\t\t\n\t\t/**\n\t\t * {@inheritDoc}\n\t\t */\n\t\t@Override\n\t\tpublic void sendMessage(final String message, final String callee, final long accountId) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\t//We have to ensure service is properly started and not just binded\n\t\t\tSipService.this.startService(new Intent(SipService.this, SipService.class));\n\t\t\t\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t\tLog.d(THIS_FILE, \"will sms \" + callee);\n\t\t\t\t\tif(pjService != null) {\n \t\t\t\t\tToCall called = pjService.sendMessage(callee, message, accountId);\n \t\t\t\t\tif(called!=null) {\n \t\t\t\t\t\tSipMessage msg = new SipMessage(SipMessage.SELF, \n \t\t\t\t\t\t\t\tSipUri.getCanonicalSipContact(callee), SipUri.getCanonicalSipContact(called.getCallee()), \n \t\t\t\t\t\t\t\tmessage, \"text/plain\", System.currentTimeMillis(), \n \t\t\t\t\t\t\t\tSipMessage.MESSAGE_TYPE_QUEUED, called.getCallee());\n \t\t\t\t\t\tmsg.setRead(true);\n \t\t\t\t\t\tgetContentResolver().insert(SipMessage.MESSAGE_URI, msg.getContentValues());\n \t\t\t\t\t\tLog.d(THIS_FILE, \"Inserted \"+msg.getTo());\n \t\t\t\t\t}else {\n \t\t\t\t\t\tSipService.this.notifyUserOfMessage( getString(R.string.invalid_sip_uri)+ \" : \"+callee );\n \t\t\t\t\t}\n\t\t\t\t\t}else {\n\t\t\t\t\t SipService.this.notifyUserOfMessage( getString(R.string.connection_not_valid) );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic int answer(final int callId, final int status) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tReturnRunnable action = new ReturnRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected Object runWithReturn() throws SameThreadException {\n\t\t\t\t\treturn (Integer) pjService.callAnswer(callId, status);\n\t\t\t\t}\n\t\t\t};\n\t\t\tgetExecutor().execute(action);\n\t\t\t//return (Integer) action.getResult();\n\t\t\treturn SipManager.SUCCESS;\n\t\t}\n\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic int hangup(final int callId, final int status) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tReturnRunnable action = new ReturnRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected Object runWithReturn() throws SameThreadException {\n\t\t\t\t\treturn (Integer) pjService.callHangup(callId, status);\n\t\t\t\t}\n\t\t\t};\n\t\t\tgetExecutor().execute(action);\n\t\t\t//return (Integer) action.getResult();\n\t\t\t\n\t\t\treturn SipManager.SUCCESS;\n\t\t}\n\t\t\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic int xfer(final int callId, final String callee) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tLog.d(THIS_FILE, \"XFER\");\n\t\t\tReturnRunnable action = new ReturnRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected Object runWithReturn() throws SameThreadException {\n\t\t\t\t\treturn (Integer) pjService.callXfer(callId, callee);\n\t\t\t\t}\n\t\t\t};\n\t\t\tgetExecutor().execute(action);\n\t\t\treturn (Integer) action.getResult();\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic int xferReplace(final int callId, final int otherCallId, final int options) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tLog.d(THIS_FILE, \"XFER-replace\");\n\t\t\tReturnRunnable action = new ReturnRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected Object runWithReturn() throws SameThreadException {\n\t\t\t\t\treturn (Integer) pjService.callXferReplace(callId, otherCallId, options);\n\t\t\t\t}\n\t\t\t};\n\t\t\tgetExecutor().execute(action);\n\t\t\treturn (Integer) action.getResult();\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic int sendDtmf(final int callId, final int keyCode) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\n\t\t\tReturnRunnable action = new ReturnRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected Object runWithReturn() throws SameThreadException {\n\t\t\t\t\treturn (Integer) pjService.sendDtmf(callId, keyCode);\n\t\t\t\t}\n\t\t\t};\n\t\t\tgetExecutor().execute(action);\n\t\t\treturn (Integer) action.getResult();\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic int hold(final int callId) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tLog.d(THIS_FILE, \"HOLDING\");\n\t\t\tReturnRunnable action = new ReturnRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected Object runWithReturn() throws SameThreadException {\n\t\t\t\t\treturn (Integer) pjService.callHold(callId);\n\t\t\t\t}\n\t\t\t};\n\t\t\tgetExecutor().execute(action);\n\t\t\treturn (Integer) action.getResult();\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic int reinvite(final int callId, final boolean unhold) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tLog.d(THIS_FILE, \"REINVITING\");\n\t\t\tReturnRunnable action = new ReturnRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected Object runWithReturn() throws SameThreadException {\n\t\t\t\t\treturn (Integer) pjService.callReinvite(callId, unhold);\n\t\t\t\t}\n\t\t\t};\n\t\t\tgetExecutor().execute(action);\n\t\t\treturn (Integer) action.getResult();\n\t\t}\n\t\t\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic SipCallSession getCallInfo(final int callId) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\treturn new SipCallSession(pjService.getCallInfo(callId));\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void setBluetoothOn(final boolean on) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t\tpjService.setBluetoothOn(on);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void setMicrophoneMute(final boolean on) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t\tpjService.setMicrophoneMute(on);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void setSpeakerphoneOn(final boolean on) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t\tpjService.setSpeakerphoneOn(on);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic SipCallSession[] getCalls() throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tif(pjService != null) {\n\t\t\t\tSipCallSession[] listOfCallsImpl = pjService.getCalls();\n\t\t\t\tSipCallSession[] result = new SipCallSession[listOfCallsImpl.length];\n\t\t\t\tfor(int sessIdx = 0; sessIdx < listOfCallsImpl.length; sessIdx++) {\n\t\t\t\t result[sessIdx] = new SipCallSession(listOfCallsImpl[sessIdx]);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\treturn new SipCallSession[0];\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void confAdjustTxLevel(final int port, final float value) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t\tif(pjService == null) {\n\t\t \t\t\treturn;\n\t\t \t\t}\n\t\t\t\t\tpjService.confAdjustTxLevel(port, value);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void confAdjustRxLevel(final int port, final float value) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t\tif(pjService == null) {\n\t\t \t\t\treturn;\n\t\t \t\t}\n\t\t\t\t\tpjService.confAdjustRxLevel(port, value);\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void adjustVolume(SipCallSession callInfo, int direction, int flags) throws RemoteException {\n\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\t\n\t\t\tif(pjService == null) {\n \t\t\treturn;\n \t\t}\n\t\t\t\n \t\tboolean ringing = callInfo.isIncoming() && callInfo.isBeforeConfirmed();\n \t// Mode ringing\n \t\tif(ringing) {\n\t \t// What is expected here is to silence ringer\n \t\t\t//pjService.adjustStreamVolume(AudioManager.STREAM_RING, direction, AudioManager.FLAG_SHOW_UI);\n \t\t\tpjService.silenceRinger();\n \t\t}else {\n\t \t// Mode in call\n\t \tif(prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_SOFT_VOLUME)) {\n\t \t\tIntent adjustVolumeIntent = new Intent(SipService.this, InCallMediaControl.class);\n\t \t\tadjustVolumeIntent.putExtra(Intent.EXTRA_KEY_EVENT, direction);\n\t \t\tadjustVolumeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t \t\tstartActivity(adjustVolumeIntent);\n\t \t}else {\n\t \t\tpjService.adjustStreamVolume(Compatibility.getInCallStream(pjService.mediaManager.doesUserWantBluetooth()), direction, flags);\n\t \t}\n \t\t}\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void setEchoCancellation(final boolean on) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tif(pjService == null) {\n return;\n }\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t\tpjService.setEchoCancellation(on);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void startRecording(final int callId, final int way) throws RemoteException {\n SipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n if (pjService == null) {\n return;\n }\n getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n pjService.startRecording(callId, way);\n }\n });\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void stopRecording(final int callId) throws RemoteException {\n SipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n if (pjService == null) {\n return;\n }\n getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n pjService.stopRecording(callId);\n }\n });\n }\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic boolean isRecording(int callId) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tif(pjService == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tSipCallSession info = pjService.getCallInfo(callId);\n\t\t\tif(info != null) {\n\t\t\t return info.isRecording();\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic boolean canRecord(int callId) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tif(pjService == null) {\n return false;\n }\n\t\t\treturn pjService.canRecord(callId);\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void playWaveFile(final String filePath, final int callId, final int way) throws RemoteException {\n SipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n if(pjService == null) {\n return;\n }\n getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n pjService.playWaveFile(filePath, callId, way);\n }\n });\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void setPresence(final int presenceInt, final String statusText, final long accountId) throws RemoteException {\n SipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n if(pjService == null) {\n return;\n }\n getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n presence = PresenceStatus.values()[presenceInt];\n pjService.setPresence(presence, statusText, accountId);\n }\n });\n }\n \n\n /**\n * {@inheritDoc}\n */\n @Override\n public int getPresence(long accountId) throws RemoteException {\n // TODO Auto-generated method stub\n return 0;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getPresenceStatus(long accountId) throws RemoteException {\n // TODO Auto-generated method stub\n return null;\n }\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic void zrtpSASVerified(final int callId) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t\tpjService.zrtpSASVerified(callId);\n\t\t\t\t\tpjService.zrtpReceiver.updateZrtpInfos(callId);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t\n /**\n * {@inheritDoc}\n */\n @Override\n public void zrtpSASRevoke(final int callId) throws RemoteException {\n SipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n pjService.zrtpSASRevoke(callId);\n pjService.zrtpReceiver.updateZrtpInfos(callId);\n }\n });\n }\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic MediaState getCurrentMediaState() throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_USE_SIP, null);\n\t\t\tMediaState ms = new MediaState();\n\t\t\tif(pjService != null && pjService.mediaManager != null) {\n\t\t\t\tms = pjService.mediaManager.getMediaState();\n\t\t\t}\n\t\t\treturn ms;\n\t\t}\n\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic int getVersion() throws RemoteException {\n\t\t\treturn SipManager.CURRENT_API;\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic String showCallInfosDialog(final int callId) throws RemoteException {\n\t\t\tReturnRunnable action = new ReturnRunnable() {\n\t\t\t\t@Override\n\t\t\t\tprotected Object runWithReturn() throws SameThreadException {\n\t\t\t\t\tString infos = PjSipCalls.dumpCallInfo(callId);\n\t\t\t\t\tLog.d(THIS_FILE, infos);\n\t\t\t\t\treturn infos;\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t\tgetExecutor().execute(action);\n\t\t\treturn (String) action.getResult();\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic int startLoopbackTest() throws RemoteException {\n\t\t\tif(pjService == null) {\n\t\t\t\treturn SipManager.ERROR_CURRENT_NETWORK;\n\t\t\t}\n\t\t\tSipRunnable action = new SipRunnable() {\n\t\t\t\t\n\t\t\t\t@Override\n\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t pjService.startLoopbackTest();\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t\tgetExecutor().execute(action);\n\t\t\treturn SipManager.SUCCESS;\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n\t\t@Override\n\t\tpublic int stopLoopbackTest() throws RemoteException {\n\t\t\tif(pjService == null) {\n\t\t\t\treturn SipManager.ERROR_CURRENT_NETWORK;\n\t\t\t}\n\t\t\tSipRunnable action = new SipRunnable() {\n\t\t\t\t\n\t\t\t\t@Override\n\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t pjService.stopLoopbackTest();\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t\tgetExecutor().execute(action);\n\t\t\treturn SipManager.SUCCESS;\n\t\t}\n\n /**\n * {@inheritDoc}\n */\n @Override\n public long confGetRxTxLevel(final int port) throws RemoteException {\n ReturnRunnable action = new ReturnRunnable() {\n @Override\n protected Object runWithReturn() throws SameThreadException {\n return (Long) pjService.getRxTxLevel(port);\n }\n };\n getExecutor().execute(action);\n return (Long) action.getResult();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void ignoreNextOutgoingCallFor(String number) throws RemoteException {\n OutgoingCall.ignoreNext = number;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void updateCallOptions(final int callId, final Bundle options) throws RemoteException {\n getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n pjService.updateCallOptions(callId, options);\n }\n });\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getLocalNatType() throws RemoteException {\n ReturnRunnable action = new ReturnRunnable() {\n @Override\n protected Object runWithReturn() throws SameThreadException {\n return (String) pjService.getDetectedNatType();\n }\n };\n getExecutor().execute(action);\n return (String) action.getResult();\n }\n\n\n\n\t\t\n\t};\n\n\tprivate final ISipConfiguration.Stub binderConfiguration = new ISipConfiguration.Stub() {\n\n\t\t@Override\n\t\tpublic void setPreferenceBoolean(String key, boolean value) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_CONFIGURE_SIP, null);\n\t\t\tprefsWrapper.setPreferenceBooleanValue(key, value);\n\t\t}\n\n\t\t@Override\n\t\tpublic void setPreferenceFloat(String key, float value) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_CONFIGURE_SIP, null);\n\t\t\tprefsWrapper.setPreferenceFloatValue(key, value);\n\n\t\t}\n\n\t\t@Override\n\t\tpublic void setPreferenceString(String key, String value) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_CONFIGURE_SIP, null);\n\t\t\tprefsWrapper.setPreferenceStringValue(key, value);\n\n\t\t}\n\n\t\t@Override\n\t\tpublic String getPreferenceString(String key) throws RemoteException {\n\t\t\treturn prefsWrapper.getPreferenceStringValue(key);\n\t\t\t\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean getPreferenceBoolean(String key) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_CONFIGURE_SIP, null);\n\t\t\treturn prefsWrapper.getPreferenceBooleanValue(key);\n\t\t\t\n\t\t}\n\n\t\t@Override\n\t\tpublic float getPreferenceFloat(String key) throws RemoteException {\n\t\t\tSipService.this.enforceCallingOrSelfPermission(SipManager.PERMISSION_CONFIGURE_SIP, null);\n\t\t\treturn prefsWrapper.getPreferenceFloatValue(key);\n\t\t}\n\n\t};\n\n\tprivate WakeLock wakeLock;\n\tprivate WifiLock wifiLock;\n\tprivate DynamicReceiver4 deviceStateReceiver;\n\tprivate PreferencesProviderWrapper prefsWrapper;\n\tprivate ServicePhoneStateReceiver phoneConnectivityReceiver;\n\tprivate TelephonyManager telephonyManager;\n//\tprivate ConnectivityManager connectivityManager;\n\n\tpublic SipNotifications notificationManager;\n\tprivate SipServiceExecutor mExecutor;\n\tprivate static PjSipService pjService;\n\tprivate static HandlerThread executorThread;\n\t\n\tprivate AccountStatusContentObserver statusObserver = null;\n //public PresenceManager presenceMgr;\n private BroadcastReceiver serviceReceiver;\n\t\n\tclass AccountStatusContentObserver extends ContentObserver {\n\t\tpublic AccountStatusContentObserver(Handler h) {\n\t\t\tsuper(h);\n\t\t}\n\n\t\tpublic void onChange(boolean selfChange) {\n\t\t\tLog.d(THIS_FILE, \"Accounts status.onChange( \" + selfChange + \")\");\n\t\t\tupdateRegistrationsState();\n\t\t}\n\t}\n\t\n\n public SipServiceExecutor getExecutor() {\n // create mExecutor lazily\n if (mExecutor == null) {\n \tmExecutor = new SipServiceExecutor(this);\n }\n return mExecutor;\n }\n\n\tprivate class ServicePhoneStateReceiver extends PhoneStateListener {\n\t\t\n\t\t//private boolean ignoreFirstConnectionState = true;\n\t\tprivate boolean ignoreFirstCallState = true;\n\t\t/*\n\t\t@Override\n\t\tpublic void onDataConnectionStateChanged(final int state) {\n\t\t\tif(!ignoreFirstConnectionState) {\n\t\t\t\tLog.d(THIS_FILE, \"Data connection state changed : \" + state);\n\t\t\t\tThread t = new Thread(\"DataConnectionDetach\") {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tif(deviceStateReceiver != null) {\n\t\t\t\t\t\t\tdeviceStateReceiver.onChanged(\"MOBILE\", state == TelephonyManager.DATA_CONNECTED);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tt.start();\n\t\t\t}else {\n\t\t\t\tignoreFirstConnectionState = false;\n\t\t\t}\n\t\t\tsuper.onDataConnectionStateChanged(state);\n\t\t}\n\t\t*/\n\n\t\t@Override\n\t\tpublic void onCallStateChanged(final int state, final String incomingNumber) {\n\t\t\tif(!ignoreFirstCallState) {\n\t\t\t\tLog.d(THIS_FILE, \"Call state has changed !\" + state + \" : \" + incomingNumber);\n\t\t\t\tgetExecutor().execute(new SipRunnable() {\n\t\t\t\t\t\n\t\t\t\t\t@Override\n\t\t\t\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\t\t\tif(pjService != null) {\n\t\t\t\t\t\t\tpjService.onGSMStateChanged(state, incomingNumber);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}else {\n\t\t\t\tignoreFirstCallState = false;\n\t\t\t}\n\t\t\tsuper.onCallStateChanged(state, incomingNumber);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\tsingleton = this;\n\n\t\tLog.i(THIS_FILE, \"Create SIP Service\");\n\t\tprefsWrapper = new PreferencesProviderWrapper(this);\n\t\tLog.setLogLevel(prefsWrapper.getLogLevel());\n\t\t\n\t\ttelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);\n//\t\tconnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n\t\tnotificationManager = new SipNotifications(this);\n\t\tnotificationManager.onServiceCreate();\n\t\tsipWakeLock = new SipWakeLock((PowerManager) getSystemService(Context.POWER_SERVICE));\n\t\t\n\t\tboolean hasSetup = prefsWrapper.getPreferenceBooleanValue(PreferencesProviderWrapper.HAS_ALREADY_SETUP_SERVICE, false);\n\t\tLog.d(THIS_FILE, \"Service has been setup ? \"+ hasSetup);\n\t\t\n\t\t//presenceMgr = new PresenceManager();\n registerServiceBroadcasts();\n\t\t\n\t\tif(!hasSetup) {\n\t\t\tLog.e(THIS_FILE, \"RESET SETTINGS !!!!\");\n\t\t\tprefsWrapper.resetAllDefaultValues();\n\t\t}\n\n\n\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\tLog.i(THIS_FILE, \"Destroying SIP Service\");\n\t\tunregisterBroadcasts();\n\t\tunregisterServiceBroadcasts();\n\t\tnotificationManager.onServiceDestroy();\n\t\tgetExecutor().execute(new FinalizeDestroyRunnable());\n\t}\n\t\n\tpublic void cleanStop () {\n\t\tgetExecutor().execute(new DestroyRunnable());\n\t}\n\t\n\tprivate void applyComponentEnablingState(boolean active) {\n\t int enableState = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;\n\t if(active && prefsWrapper.getPreferenceBooleanValue(SipConfigManager.INTEGRATE_TEL_PRIVILEGED) ) {\n // Check whether we should register for stock tel: intents\n // Useful for devices without gsm\n enableState = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;\n\t }\n PackageManager pm = getPackageManager();\n \n ComponentName cmp = new ComponentName(this, \"com.csipsimple.ui.PrivilegedOutgoingCallBroadcaster\");\n try {\n if (pm.getComponentEnabledSetting(cmp) != enableState) {\n pm.setComponentEnabledSetting(cmp, enableState, PackageManager.DONT_KILL_APP);\n }\n } catch (IllegalArgumentException e) {\n Log.d(THIS_FILE,\n \"Current manifest has no PrivilegedOutgoingCallBroadcaster -- you can ignore this if voluntary\", e);\n }\n\t}\n\t\n\tprivate void registerServiceBroadcasts() {\n\t if(serviceReceiver == null) {\n\t IntentFilter intentfilter = new IntentFilter();\n intentfilter.addAction(SipManager.ACTION_DEFER_OUTGOING_UNREGISTER);\n intentfilter.addAction(SipManager.ACTION_OUTGOING_UNREGISTER);\n serviceReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n if(action.equals(SipManager.ACTION_OUTGOING_UNREGISTER)){\n unregisterForOutgoing((ComponentName) intent.getParcelableExtra(SipManager.EXTRA_OUTGOING_ACTIVITY));\n } else if(action.equals(SipManager.ACTION_DEFER_OUTGOING_UNREGISTER)){\n deferUnregisterForOutgoing((ComponentName) intent.getParcelableExtra(SipManager.EXTRA_OUTGOING_ACTIVITY));\n }\n }\n \n };\n registerReceiver(serviceReceiver, intentfilter);\n\t }\n\t}\n\t\n\tprivate void unregisterServiceBroadcasts() {\n\t if(serviceReceiver != null) {\n\t unregisterReceiver(serviceReceiver);\n\t serviceReceiver = null;\n\t }\n\t}\n\t\n\t/**\n\t * Register broadcast receivers.\n\t */\n\tprivate void registerBroadcasts() {\n\t\t// Register own broadcast receiver\n\t\tif (deviceStateReceiver == null) {\n\t\t\tIntentFilter intentfilter = new IntentFilter();\n\t\t\tintentfilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);\n\t\t\tintentfilter.addAction(SipManager.ACTION_SIP_ACCOUNT_CHANGED);\n intentfilter.addAction(SipManager.ACTION_SIP_ACCOUNT_DELETED);\n\t\t\tintentfilter.addAction(SipManager.ACTION_SIP_CAN_BE_STOPPED);\n\t\t\tintentfilter.addAction(SipManager.ACTION_SIP_REQUEST_RESTART);\n\t\t\tintentfilter.addAction(DynamicReceiver4.ACTION_VPN_CONNECTIVITY);\n\t\t\tif(Compatibility.isCompatible(5)) {\n\t\t\t deviceStateReceiver = new DynamicReceiver5(this);\n\t\t\t}else {\n\t\t\t deviceStateReceiver = new DynamicReceiver4(this);\n\t\t\t}\n\t\t\tregisterReceiver(deviceStateReceiver, intentfilter);\n\t\t\tdeviceStateReceiver.startMonitoring();\n\t\t}\n\t\t// Telephony\n\t\tif (phoneConnectivityReceiver == null) {\n\t\t\tLog.d(THIS_FILE, \"Listen for phone state \");\n\t\t\tphoneConnectivityReceiver = new ServicePhoneStateReceiver();\n\t\t\t\n\t\t\ttelephonyManager.listen(phoneConnectivityReceiver, /*PhoneStateListener.LISTEN_DATA_CONNECTION_STATE\n\t\t\t\t\t| */PhoneStateListener.LISTEN_CALL_STATE );\n\t\t}\n\t\t// Content observer\n\t\tif(statusObserver == null) {\n \tstatusObserver = new AccountStatusContentObserver(serviceHandler);\n \t\tgetContentResolver().registerContentObserver(SipProfile.ACCOUNT_STATUS_URI, true, statusObserver);\n\t\t}\n\t\t\n\t}\n\n\t/**\n\t * Remove registration of broadcasts receiver.\n\t */\n\tprivate void unregisterBroadcasts() {\n\t\tif(deviceStateReceiver != null) {\n\t\t\ttry {\n\t\t\t\tLog.d(THIS_FILE, \"Stop and unregister device receiver\");\n\t\t\t\tdeviceStateReceiver.stopMonitoring();\n\t\t\t\tunregisterReceiver(deviceStateReceiver);\n\t\t\t\tdeviceStateReceiver = null;\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\t// This is the case if already unregistered itself\n\t\t\t\t// Python style usage of try ;) : nothing to do here since it could\n\t\t\t\t// be a standard case\n\t\t\t\t// And in this case nothing has to be done\n\t\t\t\tLog.d(THIS_FILE, \"Has not to unregister telephony receiver\");\n\t\t\t}\n\t\t}\n\t\tif (phoneConnectivityReceiver != null) {\n\t\t\tLog.d(THIS_FILE, \"Unregister telephony receiver\");\n\t\t\ttelephonyManager.listen(phoneConnectivityReceiver, PhoneStateListener.LISTEN_NONE);\n\t\t\tphoneConnectivityReceiver = null;\n\t\t}\n\t\tif(statusObserver != null) {\n \t\tgetContentResolver().unregisterContentObserver(statusObserver);\n \t\tstatusObserver = null;\n \t}\n\t\t\n\t}\n\t\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@SuppressWarnings(\"deprecation\")\n @Override\n\tpublic void onStart(Intent intent, int startId) {\n\t\tsuper.onStart(intent, startId);\n\t\tif(intent != null) {\n \t\tParcelable p = intent.getParcelableExtra(SipManager.EXTRA_OUTGOING_ACTIVITY);\n \t\tif(p != null) {\n \t\t ComponentName outActivity = (ComponentName) p;\n \t\t registerForOutgoing(outActivity);\n \t\t}\n\t\t}\n\t\t\n // Check connectivity, else just finish itself\n if (!isConnectivityValid()) {\n notifyUserOfMessage(R.string.connection_not_valid);\n Log.d(THIS_FILE, \"Harakiri... we are not needed since no way to use self\");\n cleanStop();\n return;\n }\n\t\t\n\t\t// Autostart the stack - make sure started and that receivers are there\n\t\t// NOTE : the stack may also be autostarted cause of phoneConnectivityReceiver\n\t\tif (!loadStack()) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t\n\t\t//if(directConnect) {\n\t\t\tLog.d(THIS_FILE, \"Direct sip start\");\n\t\t\tgetExecutor().execute(new StartRunnable());\n\t\t\t/*\n\t\t}else {\n\t\t\tLog.d(THIS_FILE, \"Defered SIP start !!\");\n\t\t\tNetworkInfo netInfo = (NetworkInfo) connectivityManager.getActiveNetworkInfo();\n\t\t\tif(netInfo != null) {\n\t\t\t\tString type = netInfo.getTypeName();\n\t\t\t\tNetworkInfo.State state = netInfo.getState();\n\t\t\t\tif(state == NetworkInfo.State.CONNECTED) {\n\t\t\t\t\tLog.d(THIS_FILE, \">> on changed connected\");\n\t\t\t\t\tdeviceStateReceiver.onChanged(type, true);\n\t\t\t\t}else if(state == NetworkInfo.State.DISCONNECTED) {\n\t\t\t\t\tLog.d(THIS_FILE, \">> on changed disconnected\");\n\t\t\t\t\tdeviceStateReceiver.onChanged(type, false);\n\t\t\t\t}\n\t\t\t}else {\n\t\t\t\tdeviceStateReceiver.onChanged(null, false);\n\t\t\t\tLog.d(THIS_FILE, \">> on changed disconnected\");\n\t\t\t}\n\t\t}\n\t\t*/\n\t}\n\t\n\t\n\tprivate List<ComponentName> activitiesForOutgoing = new ArrayList<ComponentName>();\n private List<ComponentName> deferedUnregisterForOutgoing = new ArrayList<ComponentName>();\n\tpublic void registerForOutgoing(ComponentName activityKey) {\n\t if(!activitiesForOutgoing.contains(activityKey)) {\n\t activitiesForOutgoing.add(activityKey);\n\t }\n\t}\n\tpublic void unregisterForOutgoing(ComponentName activityKey) {\n\t activitiesForOutgoing.remove(activityKey);\n\t \n\t if(!isConnectivityValid()) {\n\t cleanStop();\n\t }\n\t}\n\tpublic void deferUnregisterForOutgoing(ComponentName activityKey) {\n\t if(!deferedUnregisterForOutgoing.contains(activityKey)) {\n\t deferedUnregisterForOutgoing.add(activityKey);\n\t }\n\t}\n\tpublic void treatDeferUnregistersForOutgoing() {\n\t for(ComponentName cmp : deferedUnregisterForOutgoing) {\n\t activitiesForOutgoing.remove(cmp);\n\t }\n\t deferedUnregisterForOutgoing.clear();\n if(!isConnectivityValid()) {\n cleanStop();\n }\n\t}\n\t\n\tpublic boolean isConnectivityValid() {\n\t if(prefsWrapper.getPreferenceBooleanValue(PreferencesWrapper.HAS_BEEN_QUIT, false)) {\n\t return false;\n\t }\n\t boolean valid = prefsWrapper.isValidConnectionForIncoming();\n\t if(activitiesForOutgoing.size() > 0) {\n\t valid |= prefsWrapper.isValidConnectionForOutgoing();\n\t }\n\t return valid;\n\t}\n\t\n\t\n\n\tprivate boolean loadStack() {\n\t\t//Ensure pjService exists\n\t\tif(pjService == null) {\n\t\t\tpjService = new PjSipService();\n\t\t}\n\t\tpjService.setService(this);\n\t\t\n\t\tif (pjService.tryToLoadStack()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\n\t\tString serviceName = intent.getAction();\n\t\tLog.d(THIS_FILE, \"Action is \" + serviceName);\n\t\tif (serviceName == null || serviceName.equalsIgnoreCase(SipManager.INTENT_SIP_SERVICE)) {\n\t\t\tLog.d(THIS_FILE, \"Service returned\");\n\t\t\treturn binder;\n\t\t} else if (serviceName.equalsIgnoreCase(SipManager.INTENT_SIP_CONFIGURATION)) {\n\t\t\tLog.d(THIS_FILE, \"Conf returned\");\n\t\t\treturn binderConfiguration;\n\t\t}\n\t\tLog.d(THIS_FILE, \"Default service (SipService) returned\");\n\t\treturn binder;\n\t}\n\n\t//private KeepAliveTimer kaAlarm;\n\t// This is always done in SipExecutor thread\n\tprivate void startSipStack() throws SameThreadException {\n\t\t//Cache some prefs\n\t\tsupportMultipleCalls = prefsWrapper.getPreferenceBooleanValue(SipConfigManager.SUPPORT_MULTIPLE_CALLS);\n\t\t\n\t\tif(!isConnectivityValid()) {\n\t\t notifyUserOfMessage(R.string.connection_not_valid);\n\t\t\tLog.e(THIS_FILE, \"No need to start sip\");\n\t\t\treturn;\n\t\t}\n\t\tLog.d(THIS_FILE, \"Start was asked and we should actually start now\");\n\t\tif(pjService == null) {\n\t\t\tLog.d(THIS_FILE, \"Start was asked and pjService in not there\");\n\t\t\tif(!loadStack()) {\n\t\t\t\tLog.e(THIS_FILE, \"Unable to load SIP stack !! \");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tLog.d(THIS_FILE, \"Ask pjservice to start itself\");\n\t\t\n\n //presenceMgr.startMonitoring(this);\n\t\tif(pjService.sipStart()) {\n\t\t // This should be done after in acquire resource\n\t\t // But due to http://code.google.com/p/android/issues/detail?id=21635\n\t\t // not a good idea\n\t applyComponentEnablingState(true);\n\t \n\t registerBroadcasts();\n\t\t\tLog.d(THIS_FILE, \"Add all accounts\");\n\t\t\taddAllAccounts();\n\t\t}\n\t}\n\t\n\t/**\n\t * Safe stop the sip stack\n\t * @return true if can be stopped, false if there is a pending call and the sip service should not be stopped\n\t */\n\tpublic boolean stopSipStack() throws SameThreadException {\n\t\tLog.d(THIS_FILE, \"Stop sip stack\");\n\t\tboolean canStop = true;\n\t\tif(pjService != null) {\n\t\t\tcanStop &= pjService.sipStop();\n\t\t\t/*\n\t\t\tif(canStop) {\n\t\t\t\tpjService = null;\n\t\t\t}\n\t\t\t*/\n\t\t}\n\t\tif(canStop) {\n\t\t //if(presenceMgr != null) {\n\t\t // presenceMgr.stopMonitoring();\n\t\t //}\n\t\t \n\t\t // Due to http://code.google.com/p/android/issues/detail?id=21635\n // exclude 14 and upper from auto disabling on stop.\n if(!Compatibility.isCompatible(14)) {\n applyComponentEnablingState(false);\n }\n\n unregisterBroadcasts();\n\t\t\treleaseResources();\n\t\t}\n\n\t\treturn canStop;\n\t}\n\t\n\n public void restartSipStack() throws SameThreadException {\n if(stopSipStack()) {\n startSipStack();\n }else {\n Log.e(THIS_FILE, \"Can't stop ... so do not restart ! \");\n }\n }\n\t\n /**\n * Notify user from a message the sip stack wants to transmit.\n * For now it shows a toaster\n * @param msg String message to display\n */\n\tpublic void notifyUserOfMessage(String msg) {\n\t\tserviceHandler.sendMessage(serviceHandler.obtainMessage(TOAST_MESSAGE, msg));\n\t}\n\t/**\n\t * Notify user from a message the sip stack wants to transmit.\n * For now it shows a toaster\n\t * @param resStringId The id of the string resource to display\n\t */\n\tpublic void notifyUserOfMessage(int resStringId) {\n\t serviceHandler.sendMessage(serviceHandler.obtainMessage(TOAST_MESSAGE, resStringId, 0));\n\t}\n\t\n\tprivate boolean hasSomeActiveAccount = false;\n\t/**\n\t * Add accounts from database\n\t */\n\tprivate void addAllAccounts() throws SameThreadException {\n\t\tLog.d(THIS_FILE, \"We are adding all accounts right now....\");\n\n\t\tboolean hasSomeSuccess = false;\n\t\tCursor c = getContentResolver().query(SipProfile.ACCOUNT_URI, DBProvider.ACCOUNT_FULL_PROJECTION, \n\t\t\t\tSipProfile.FIELD_ACTIVE + \"=?\", new String[] {\"1\"}, null);\n\t\tif (c != null) {\n\t\t\ttry {\n\t\t\t\tint index = 0;\n\t\t\t\tif(c.getCount() > 0) {\n \t\t\t\tc.moveToFirst();\n \t\t\t\tdo {\n \t\t\t\t\tSipProfile account = new SipProfile(c);\n \t\t\t\t\tif (pjService != null && pjService.addAccount(account) ) {\n \t\t\t\t\t\thasSomeSuccess = true;\n \t\t\t\t\t}\n \t\t\t\t\tindex ++;\n \t\t\t\t} while (c.moveToNext() && index < 10);\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tLog.e(THIS_FILE, \"Error on looping over sip profiles\", e);\n\t\t\t} finally {\n\t\t\t\tc.close();\n\t\t\t}\n\t\t}\n\t\t\n\t\thasSomeActiveAccount = hasSomeSuccess;\n\n\t\tif (hasSomeSuccess) {\n\t\t\tacquireResources();\n\t\t\t\n\t\t} else {\n\t\t\treleaseResources();\n\t\t\tif (notificationManager != null) {\n\t\t\t\tnotificationManager.cancelRegisters();\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\n\tpublic boolean setAccountRegistration(SipProfile account, int renew, boolean forceReAdd) throws SameThreadException {\n\t\tboolean status = false;\n\t\tif(pjService != null) {\n\t\t\tstatus = pjService.setAccountRegistration(account, renew, forceReAdd);\n\t\t}\t\t\n\t\t\n\t\treturn status;\n\t}\n\n\t/**\n\t * Remove accounts from database\n\t */\n\tprivate void unregisterAllAccounts(boolean cancelNotification) throws SameThreadException {\n\n\t\treleaseResources();\n\t\t\n\t\tLog.d(THIS_FILE, \"Remove all accounts\");\n\t\t\n\t\tCursor c = getContentResolver().query(SipProfile.ACCOUNT_URI, DBProvider.ACCOUNT_FULL_PROJECTION, null, null, null);\n\t\tif (c != null) {\n\t\t\ttry {\n\t\t\t\tc.moveToFirst();\n\t\t\t\tdo {\n\t\t\t\t\tSipProfile account = new SipProfile(c);\n\t\t\t\t\tsetAccountRegistration(account, 0, false);\n\t\t\t\t} while (c.moveToNext() );\n\t\t\t} catch (Exception e) {\n\t\t\t\tLog.e(THIS_FILE, \"Error on looping over sip profiles\", e);\n\t\t\t} finally {\n\t\t\t\tc.close();\n\t\t\t}\n\t\t}\n\n\n\t\tif (notificationManager != null && cancelNotification) {\n\t\t\tnotificationManager.cancelRegisters();\n\t\t}\n\t}\n\n\tprivate void reAddAllAccounts() throws SameThreadException {\n\t\tLog.d(THIS_FILE, \"RE REGISTER ALL ACCOUNTS\");\n\t\tunregisterAllAccounts(false);\n\t\taddAllAccounts();\n\t}\n\n\n\t\n\t\n\tpublic SipProfileState getSipProfileState(int accountDbId) {\n\t\tfinal SipProfile acc = getAccount(accountDbId);\n\t\tif(pjService != null && acc != null) {\n\t\t\treturn pjService.getProfileState(acc);\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void updateRegistrationsState() {\n\t\tLog.d(THIS_FILE, \"Update registration state\");\n\t\tArrayList<SipProfileState> activeProfilesState = new ArrayList<SipProfileState>();\n\t\tCursor c = getContentResolver().query(SipProfile.ACCOUNT_STATUS_URI, null, null, null, null);\n\t\tif (c != null) {\n\t\t\ttry {\n\t\t\t\tif(c.getCount() > 0) {\n\t\t\t\t\tc.moveToFirst();\n\t\t\t\t\tdo {\n\t\t\t\t\t\tSipProfileState ps = new SipProfileState(c);\n\t\t\t\t\t\tif(ps.isValidForCall()) {\n\t\t\t\t\t\t\tactiveProfilesState.add(ps);\n\t\t\t\t\t\t}\n\t\t\t\t\t} while ( c.moveToNext() );\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tLog.e(THIS_FILE, \"Error on looping over sip profiles\", e);\n\t\t\t} finally {\n\t\t\t\tc.close();\n\t\t\t}\n\t\t}\n\t\t\n\t\tCollections.sort(activeProfilesState, SipProfileState.getComparator());\n\t\t\n\t\t\n\n\t\t// Handle status bar notification\n\t\tif (activeProfilesState.size() > 0 && \n\t\t\t\tprefsWrapper.getPreferenceBooleanValue(SipConfigManager.ICON_IN_STATUS_BAR, true)) {\n\t\t// Testing memory / CPU leak as per issue 676\n\t\t//\tfor(int i=0; i < 10; i++) {\n\t\t//\t\tLog.d(THIS_FILE, \"Notify ...\");\n\t\t\t\tnotificationManager.notifyRegisteredAccounts(activeProfilesState, prefsWrapper.getPreferenceBooleanValue(SipConfigManager.ICON_IN_STATUS_BAR_NBR));\n\t\t//\t\ttry {\n\t\t//\t\t\tThread.sleep(6000);\n\t\t//\t\t} catch (InterruptedException e) {\n\t\t//\t\t\te.printStackTrace();\n\t\t//\t\t}\n\t\t//\t}\n\t\t} else {\n\t\t\tnotificationManager.cancelRegisters();\n\t\t}\n\t\t\n\t\tif(hasSomeActiveAccount) {\n\t\t\tacquireResources();\n\t\t}else {\n\t\t\treleaseResources();\n\t\t}\n\t}\n\t\n\t/**\n\t * Get the currently instanciated prefsWrapper (to be used by\n\t * UAStateReceiver)\n\t * \n\t * @return the preferenceWrapper instanciated\n\t */\n\tpublic PreferencesProviderWrapper getPrefs() {\n\t\t// Is never null when call so ok, just not check...\n\t\treturn prefsWrapper;\n\t}\n\t\n\t//Binders for media manager to sip stack\n\t/**\n\t * Adjust tx software sound level\n\t * @param speakVolume volume 0.0 - 1.0\n\t */\n\tpublic void confAdjustTxLevel(float speakVolume) throws SameThreadException {\n\t\tif(pjService != null) {\n\t\t\tpjService.confAdjustTxLevel(0, speakVolume);\n\t\t}\n\t}\n\t/**\n\t * Adjust rx software sound level\n\t * @param speakVolume volume 0.0 - 1.0\n\t */\n\tpublic void confAdjustRxLevel(float speakVolume) throws SameThreadException {\n\t\tif(pjService != null) {\n\t\t\tpjService.confAdjustRxLevel(0, speakVolume);\n\t\t}\n\t}\n\n\n /**\n * Add a buddy to list \n * @param buddyUri the sip uri of the buddy to add\n */\n public int addBuddy(String buddyUri) throws SameThreadException {\n int retVal = -1;\n if(pjService != null) {\n Log.d(THIS_FILE, \"Trying to add buddy \" + buddyUri);\n retVal = pjService.addBuddy(buddyUri);\n }\n return retVal;\n }\n\n /**\n * Remove a buddy from buddies\n * @param buddyUri the sip uri of the buddy to remove\n */\n public void removeBuddy(String buddyUri) throws SameThreadException {\n if(pjService != null) {\n pjService.removeBuddy(buddyUri);\n }\n }\n\t\n\tprivate boolean holdResources = false;\n\t/**\n\t * Ask to take the control of the wifi and the partial wake lock if\n\t * configured\n\t */\n\tprivate synchronized void acquireResources() {\n\t\tif(holdResources) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// Add a wake lock for CPU if necessary\n\t\tif (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_PARTIAL_WAKE_LOCK)) {\n\t\t\tPowerManager pman = (PowerManager) getSystemService(Context.POWER_SERVICE);\n\t\t\tif (wakeLock == null) {\n\t\t\t\twakeLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, \"com.csipsimple.SipService\");\n\t\t\t\twakeLock.setReferenceCounted(false);\n\t\t\t}\n\t\t\t// Extra check if set reference counted is false ???\n\t\t\tif (!wakeLock.isHeld()) {\n\t\t\t\twakeLock.acquire();\n\t\t\t}\n\t\t}\n\n\t\t// Add a lock for WIFI if necessary\n\t\tWifiManager wman = (WifiManager) getSystemService(Context.WIFI_SERVICE);\n\t\tif (wifiLock == null) {\n\t\t\tint mode = WifiManager.WIFI_MODE_FULL;\n\t\t\tif(Compatibility.isCompatible(9) && prefsWrapper.getPreferenceBooleanValue(SipConfigManager.LOCK_WIFI_PERFS)) {\n\t\t\t\tmode = 0x3; // WIFI_MODE_FULL_HIGH_PERF \n\t\t\t}\n\t\t\twifiLock = wman.createWifiLock(mode, \"com.csipsimple.SipService\");\n\t\t\twifiLock.setReferenceCounted(false);\n\t\t}\n\t\tif (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.LOCK_WIFI) && !wifiLock.isHeld()) {\n\t\t\tWifiInfo winfo = wman.getConnectionInfo();\n\t\t\tif (winfo != null) {\n\t\t\t\tDetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState());\n\t\t\t\t// We assume that if obtaining ip addr, we are almost connected\n\t\t\t\t// so can keep wifi lock\n\t\t\t\tif (dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) {\n\t\t\t\t\tif (!wifiLock.isHeld()) {\n\t\t\t\t\t\twifiLock.acquire();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tholdResources = true;\n\t}\n\n\tprivate synchronized void releaseResources() {\n\t\tif (wakeLock != null && wakeLock.isHeld()) {\n\t\t\twakeLock.release();\n\t\t}\n\t\tif (wifiLock != null && wifiLock.isHeld()) {\n\t\t\twifiLock.release();\n\t\t}\n\t\tholdResources = false;\n\t}\n\n\n\t\n\n\tprivate static final int TOAST_MESSAGE = 0;\n\n\tprivate Handler serviceHandler = new ServiceHandler(this);\n\t \n\tprivate static class ServiceHandler extends Handler {\n\t WeakReference<SipService> s;\n\t\tpublic ServiceHandler(SipService sipService) {\n\t\t s = new WeakReference<SipService>(sipService);\n }\n\n @Override\n\t\tpublic void handleMessage(Message msg) {\n super.handleMessage(msg);\n SipService sipService = s.get();\n if(sipService == null) {\n return;\n }\n\t\t\tif (msg.what == TOAST_MESSAGE) {\n\t\t\t\tif (msg.arg1 != 0) {\n\t\t\t\t\tToast.makeText(sipService, msg.arg1, Toast.LENGTH_LONG).show();\n\t\t\t\t} else {\n\t\t\t\t\tToast.makeText(sipService, (String) msg.obj, Toast.LENGTH_LONG).show();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\t\n\tpublic UAStateReceiver getUAStateReceiver() {\n\t\treturn pjService.userAgentReceiver;\n\t}\n\n\n\n\tpublic int getGSMCallState() {\n\t\treturn telephonyManager.getCallState();\n\t}\n\n\tpublic static final class ToCall {\n\t\tprivate Integer pjsipAccountId;\n\t\tprivate String callee;\n\t\tprivate String dtmf;\n\t\t\n\t\tpublic ToCall(Integer acc, String uri) {\n\t\t\tpjsipAccountId = acc;\n\t\t\tcallee = uri;\n\t\t}\n\t\tpublic ToCall(Integer acc, String uri, String dtmfChars) {\n pjsipAccountId = acc;\n callee = uri;\n dtmf = dtmfChars;\n }\n\t\t/**\n\t\t * @return the pjsipAccountId\n\t\t */\n\t\tpublic Integer getPjsipAccountId() {\n\t\t\treturn pjsipAccountId;\n\t\t}\n\t\t/**\n\t\t * @return the callee\n\t\t */\n\t\tpublic String getCallee() {\n\t\t\treturn callee;\n\t\t}\n\t\t/**\n\t\t * @return the dtmf sequence to automatically dial for this call\n\t\t */\n\t\tpublic String getDtmf() {\n return dtmf;\n }\n\t};\n\t\n\tpublic SipProfile getAccount(long accountId) {\n\t\t// TODO : create cache at this point to not requery each time as far as it's a service query\n\t\treturn SipProfile.getProfileFromDbId(this, accountId, DBProvider.ACCOUNT_FULL_PROJECTION);\n\t}\n\t\n\n // Auto answer feature\n\n\tpublic void setAutoAnswerNext(boolean auto_response) {\n\t\tautoAcceptCurrent = auto_response;\n\t}\n\t\n\t/**\n\t * Should a current incoming call be answered.\n\t * A call to this method will reset internal state\n\t * @param remContact The remote contact to test\n\t * @param acc The incoming guessed account\n\t * @return the sip code to auto-answer with. If > 0 it means that an auto answer must be fired\n\t */\n\tpublic int shouldAutoAnswer(String remContact, SipProfile acc, Bundle extraHdr) {\n\n\t\tLog.d(THIS_FILE, \"Search if should I auto answer for \" + remContact);\n\t\tint shouldAutoAnswer = 0;\n\t\t\n\t\tif(autoAcceptCurrent) {\n\t\t\tLog.d(THIS_FILE, \"I should auto answer this one !!! \");\n\t\t\tautoAcceptCurrent = false;\n\t\t\treturn 200;\n\t\t}\n\t\t\n\t\tif(acc != null) {\n\t\t\tPattern p = Pattern.compile(\"^(?:\\\")?([^<\\\"]*)(?:\\\")?[ ]*(?:<)?sip(?:s)?:([^@]*@[^>]*)(?:>)?\", Pattern.CASE_INSENSITIVE);\n\t\t\tMatcher m = p.matcher(remContact);\n\t\t\tString number = remContact;\n\t\t\tif (m.matches()) {\n\t\t\t\tnumber = m.group(2);\n\t\t\t}\n\t\t\tshouldAutoAnswer = Filter.isAutoAnswerNumber(this, acc.id, number, extraHdr);\n\t\t\t\n\t\t}else {\n\t\t\tLog.e(THIS_FILE, \"Oupps... that come from an unknown account...\");\n\t\t\t// If some user need to auto hangup if comes from unknown account, just needed to add local account and filter on it.\n\t\t}\n\t\treturn shouldAutoAnswer;\n\t}\n\t\n\t// Media direct binders\n\tpublic void setNoSnd() throws SameThreadException {\n\t\tif (pjService != null) {\n\t\t\tpjService.setNoSnd();\n\t\t}\n\t}\n\t\n\tpublic void setSnd() throws SameThreadException {\n\t\tif (pjService != null) {\n\t\t\tpjService.setSnd();\n\t\t}\n\t}\n\n\t\n private static Looper createLooper() {\n //\tsynchronized (executorThread) {\n\t \tif(executorThread == null) {\n\t \t\tLog.d(THIS_FILE, \"Creating new handler thread\");\n\t \t\t// ADT gives a fake warning due to bad parse rule.\n\t\t executorThread = new HandlerThread(\"SipService.Executor\");\n\t\t executorThread.start();\n\t \t}\n\t//\t}\n return executorThread.getLooper();\n }\n \n \n\n // Executes immediate tasks in a single executorThread.\n // Hold/release wake lock for running tasks\n public static class SipServiceExecutor extends Handler {\n WeakReference<SipService> handlerService;\n \n SipServiceExecutor(SipService s) {\n super(createLooper());\n handlerService = new WeakReference<SipService>(s);\n }\n\n public void execute(Runnable task) {\n SipService s = handlerService.get();\n if(s != null) {\n s.sipWakeLock.acquire(task);\n }\n Message.obtain(this, 0/* don't care */, task).sendToTarget();\n }\n\n @Override\n public void handleMessage(Message msg) {\n\t if (msg.obj instanceof Runnable) {\n executeInternal((Runnable) msg.obj);\n } else {\n Log.w(THIS_FILE, \"can't handle msg: \" + msg);\n }\n }\n\n private void executeInternal(Runnable task) {\n try {\n task.run();\n } catch (Throwable t) {\n Log.e(THIS_FILE, \"run task: \" + task, t);\n } finally {\n\n SipService s = handlerService.get();\n if(s != null) {\n s.sipWakeLock.release(task);\n }\n }\n }\n }\n\t\n \n class StartRunnable extends SipRunnable {\n\t\t@Override\n\t\tprotected void doRun() throws SameThreadException {\n \t\tstartSipStack();\n \t}\n }\n \n\n class SyncStartRunnable extends ReturnRunnable {\n @Override\n protected Object runWithReturn() throws SameThreadException {\n startSipStack();\n return null;\n }\n }\n\t\n class StopRunnable extends SipRunnable {\n\t\t@Override\n\t\tprotected void doRun() throws SameThreadException {\n \t\tstopSipStack();\n \t}\n }\n\n class SyncStopRunnable extends ReturnRunnable {\n @Override\n protected Object runWithReturn() throws SameThreadException {\n stopSipStack();\n return null;\n }\n }\n \n\tclass RestartRunnable extends SipRunnable {\n\t\t@Override\n\t\tprotected void doRun() throws SameThreadException {\n\t\t\tif(stopSipStack()) {\n\t\t\t\tstartSipStack();\n\t\t\t}else {\n\t\t\t\tLog.e(THIS_FILE, \"Can't stop ... so do not restart ! \");\n\t\t\t}\n\t\t}\n\t}\n\t\n\tclass SyncRestartRunnable extends ReturnRunnable {\n\t @Override\n\t protected Object runWithReturn() throws SameThreadException {\n\t if(stopSipStack()) {\n startSipStack();\n }else {\n Log.e(THIS_FILE, \"Can't stop ... so do not restart ! \");\n }\n\t return null;\n\t }\n\t}\n\t\n\tclass DestroyRunnable extends SipRunnable {\n\t\t@Override\n\t\tprotected void doRun() throws SameThreadException {\n\t\t\tif(stopSipStack()) {\n\t\t\t\tstopSelf();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tclass FinalizeDestroyRunnable extends SipRunnable {\n\t\t@Override\n\t\tprotected void doRun() throws SameThreadException {\n\t\t\t\n\t\t\tmExecutor = null;\n\t\t\t\n\t\t\tLog.d(THIS_FILE, \"Destroy sip stack\");\n\t\t\t\n\t\t\tsipWakeLock.reset();\n\t\t\t\n\t\t\tif(stopSipStack()) {\n\t\t\t\tnotificationManager.cancelAll();\n\t\t\t\tnotificationManager.cancelCalls();\n\t\t\t}else {\n\t\t\t\tLog.e(THIS_FILE, \"Somebody has stopped the service while there is an ongoing call !!!\");\n\t\t\t}\n\t\t\t/* If we activate that we can get two concurrent executorThread \n\t\t\tsynchronized (executorThread) {\n\t\t\t\tHandlerThread currentHandlerThread = executorThread;\n\t\t\t\texecutorThread = null;\n\t\t\t\tSystem.gc();\n\t\t\t\t// This is a little bit crappy, we are cutting were we sit.\n\t\t\t\tThreading.stopHandlerThread(currentHandlerThread, false);\n\t\t\t}\n\t\t\t*/\n\t\t\t\n\t\t\t// We will not go longer\n\t\t\tLog.i(THIS_FILE, \"--- SIP SERVICE DESTROYED ---\");\n\t\t}\n\t}\n\t\n\t// Enforce same thread contract to ensure we do not call from somewhere else\n\tpublic class SameThreadException extends Exception {\n\t\tprivate static final long serialVersionUID = -905639124232613768L;\n\n\t\tpublic SameThreadException() {\n\t\t\tsuper(\"Should be launched from a single worker thread\");\n\t\t}\n\t}\n\n\tpublic abstract static class SipRunnable implements Runnable {\n\t\tprotected abstract void doRun() throws SameThreadException;\n\t\t\n\t\tpublic void run() {\n\t\t\ttry {\n\t\t\t\tdoRun();\n\t\t\t}catch(SameThreadException e) {\n\t\t\t\tLog.e(THIS_FILE, \"Not done from same thread\");\n\t\t\t}\n\t\t}\n\t}\n\t\n\n public abstract class ReturnRunnable extends SipRunnable {\n \tprivate Semaphore runSemaphore;\n \tprivate Object resultObject;\n \t\n \tpublic ReturnRunnable() {\n\t\t\tsuper();\n\t\t\trunSemaphore = new Semaphore(0);\n\t\t}\n \t\n \tpublic Object getResult() {\n \t\ttry {\n\t\t\t\trunSemaphore.acquire();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tLog.e(THIS_FILE, \"Can't acquire run semaphore... problem...\");\n\t\t\t}\n \t\treturn resultObject;\n \t}\n \t\n \tprotected abstract Object runWithReturn() throws SameThreadException;\n \t\n \t@Override\n \tpublic void doRun() throws SameThreadException {\n \t\tsetResult(runWithReturn());\n \t}\n \t\n \tprivate void setResult(Object obj) {\n \t\tresultObject = obj;\n \t\trunSemaphore.release();\n \t}\n }\n \n private static String UI_CALL_PACKAGE = null;\n public static Intent buildCallUiIntent(Context ctxt, SipCallSession callInfo) {\n // Resolve the package to handle call.\n if(UI_CALL_PACKAGE == null) {\n UI_CALL_PACKAGE = ctxt.getPackageName();\n try {\n Map<String, DynActivityPlugin> callsUis = ExtraPlugins.getDynActivityPlugins(ctxt, SipManager.ACTION_SIP_CALL_UI);\n String preferredPackage = SipConfigManager.getPreferenceStringValue(ctxt, SipConfigManager.CALL_UI_PACKAGE, UI_CALL_PACKAGE);\n String packageName = null;\n boolean foundPref = false;\n for(String activity : callsUis.keySet()) {\n packageName = activity.split(\"/\")[0];\n if(preferredPackage.equalsIgnoreCase(packageName)) {\n UI_CALL_PACKAGE = packageName;\n foundPref = true;\n break;\n }\n }\n if(!foundPref && !TextUtils.isEmpty(packageName)) {\n UI_CALL_PACKAGE = packageName;\n }\n }catch(Exception e) {\n Log.e(THIS_FILE, \"Error while resolving package\", e);\n }\n }\n SipCallSession toSendInfo = new SipCallSession(callInfo);\n Intent intent = new Intent(SipManager.ACTION_SIP_CALL_UI);\n intent.putExtra(SipManager.EXTRA_CALL_INFO, toSendInfo);\n intent.setPackage(UI_CALL_PACKAGE);\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);\n return intent;\n }\n \n \n public static void setVideoWindow(int callId, SurfaceView window, boolean local) {\n if(singleton != null) {\n if(local) {\n singleton.setCaptureVideoWindow(window);\n }else {\n singleton.setRenderVideoWindow(callId, window);\n }\n }\n }\n\n private void setRenderVideoWindow(final int callId, final SurfaceView window) {\n getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n pjService.setVideoAndroidRenderer(callId, window);\n }\n });\n }\n private void setCaptureVideoWindow(final SurfaceView window) {\n getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n pjService.setVideoAndroidCapturer(window);\n }\n });\n }\n \n private PresenceStatus presence = PresenceStatus.ONLINE;\n /**\n * Get current last status for the user\n * @return\n */\n public PresenceStatus getPresence() {\n return presence;\n }\n\n}",
"public class ContactsAsyncHelper extends Handler {\n private static final String THIS_FILE = \"ContactsAsyncHelper\";\n \n // TODO : use LRUCache for bitmaps.\n \n LruCache<Uri, Bitmap> photoCache = new LruCache<Uri, Bitmap>(5 * 1024 * 1024 /* 5MiB */) {\n protected int sizeOf(Uri key, Bitmap value) {\n return value.getRowBytes() * value.getWidth();\n }\n };\n\n /**\n * Interface for a WorkerHandler result return.\n */\n public interface OnImageLoadCompleteListener {\n /**\n * Called when the image load is complete.\n * \n * @param imagePresent true if an image was found\n */\n public void onImageLoadComplete(int token, Object cookie, ImageView iView,\n boolean imagePresent);\n }\n\n // constants\n private static final int EVENT_LOAD_IMAGE = 1;\n private static final int EVENT_LOAD_IMAGE_URI = 2;\n private static final int EVENT_LOAD_CONTACT_URI = 3;\n private static final int DEFAULT_TOKEN = -1;\n private static final int TAG_PHOTO_INFOS = R.id.icon;\n private static ContactsWrapper contactsWrapper;\n\n // static objects\n private static Handler sThreadHandler;\n\n private static final class WorkerArgs {\n public Context context;\n public ImageView view;\n public int defaultResource;\n public Object result;\n public Uri loadedUri;\n public Object cookie;\n public OnImageLoadCompleteListener listener;\n }\n\n private static class PhotoViewTag {\n public Uri uri;\n }\n\n public static final String HIGH_RES_URI_PARAM = \"hiRes\";\n /**\n * Thread worker class that handles the task of opening the stream and\n * loading the images.\n */\n private class WorkerHandler extends Handler {\n\n public WorkerHandler(Looper looper) {\n super(looper);\n }\n\n public void handleMessage(Message msg) {\n WorkerArgs args = (WorkerArgs) msg.obj;\n Uri uri = null;\n if (msg.arg1 == EVENT_LOAD_IMAGE) {\n PhotoViewTag photoTag = (PhotoViewTag) args.view.getTag(TAG_PHOTO_INFOS);\n if (photoTag != null && photoTag.uri != null) {\n uri = photoTag.uri;\n boolean hiRes = false;\n String p = uri.getQueryParameter(HIGH_RES_URI_PARAM);\n if(!TextUtils.isEmpty(p) && p.equalsIgnoreCase(\"1\")) {\n hiRes = true;\n }\n Log.v(THIS_FILE, \"get : \" + uri);\n Bitmap img = null;\n synchronized (photoCache) {\n img = photoCache.get(uri);\n }\n if(img == null) {\n img = contactsWrapper.getContactPhoto(args.context, uri, hiRes,\n args.defaultResource);\n synchronized (photoCache) {\n photoCache.put(uri, img);\n }\n }\n if (img != null) {\n args.result = img;\n } else {\n args.result = null;\n }\n }\n } else if (msg.arg1 == EVENT_LOAD_IMAGE_URI || msg.arg1 == EVENT_LOAD_CONTACT_URI) {\n PhotoViewTag photoTag = (PhotoViewTag) args.view.getTag(TAG_PHOTO_INFOS);\n if (photoTag != null && photoTag.uri != null) {\n uri = photoTag.uri;\n Log.v(THIS_FILE, \"get : \" + uri);\n\n Bitmap img = null;\n\n synchronized (photoCache) {\n img = photoCache.get(uri);\n }\n if (img == null) {\n\n if (msg.arg1 == EVENT_LOAD_IMAGE_URI) {\n\n try {\n byte[] buffer = new byte[1024 * 16];\n InputStream is = args.context.getContentResolver().openInputStream(\n uri);\n if (is != null) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n try {\n int size;\n while ((size = is.read(buffer)) != -1) {\n baos.write(buffer, 0, size);\n }\n } finally {\n is.close();\n }\n byte[] boasBytes = baos.toByteArray();\n img = BitmapFactory.decodeByteArray(boasBytes, 0,\n boasBytes.length,\n null);\n }\n\n } catch (Exception ex) {\n Log.v(THIS_FILE, \"Cannot load photo \" + uri, ex);\n }\n\n } else if (msg.arg1 == EVENT_LOAD_CONTACT_URI) {\n img = ContactsWrapper.getInstance().getContactPhoto(args.context, uri, false, null);\n }\n }\n \n if (img != null) {\n args.result = img;\n synchronized (photoCache) {\n photoCache.put(uri, img);\n }\n } else {\n args.result = null;\n }\n \n }\n }\n args.loadedUri = uri;\n\n // send the reply to the enclosing class.\n Message reply = ContactsAsyncHelper.this.obtainMessage(msg.what);\n reply.arg1 = msg.arg1;\n reply.obj = msg.obj;\n reply.sendToTarget();\n }\n }\n\n /**\n * Private constructor for static class\n */\n private ContactsAsyncHelper() {\n HandlerThread thread = new HandlerThread(\"ContactsAsyncWorker\");\n thread.start();\n sThreadHandler = new WorkerHandler(thread.getLooper());\n contactsWrapper = ContactsWrapper.getInstance();\n }\n\n /**\n * Convenience method for calls that do not want to deal with listeners and\n * tokens.\n */\n public static final void updateImageViewWithContactPhotoAsync(Context context,\n ImageView imageView, CallerInfo person, int placeholderImageResource) {\n // Added additional Cookie field in the callee.\n updateImageViewWithContactPhotoAsync(DEFAULT_TOKEN, null, null, context,\n imageView, person, placeholderImageResource);\n }\n\n /**\n * Start an image load, attach the result to the specified CallerInfo\n * object. Note, when the query is started, we make the ImageView INVISIBLE\n * if the placeholderImageResource value is -1. When we're given a valid (!=\n * -1) placeholderImageResource value, we make sure the image is visible.\n */\n public static final void updateImageViewWithContactPhotoAsync(int token,\n OnImageLoadCompleteListener listener, Object cookie, Context context,\n ImageView imageView, CallerInfo callerInfo, int placeholderImageResource) {\n if (sThreadHandler == null) {\n new ContactsAsyncHelper();\n }\n\n // in case the source caller info is null, the URI will be null as well.\n // just update using the placeholder image in this case.\n if (callerInfo == null || callerInfo.contactContentUri == null) {\n defaultImage(imageView, placeholderImageResource);\n return;\n }\n\n // Check that the view is not already loading for same uri\n if (isAlreadyProcessed(imageView, callerInfo.contactContentUri)) {\n return;\n }\n\n // Added additional Cookie field in the callee to handle arguments\n // sent to the callback function.\n\n // setup arguments\n WorkerArgs args = new WorkerArgs();\n args.cookie = cookie;\n args.context = context;\n args.view = imageView;\n PhotoViewTag photoTag = new PhotoViewTag();\n photoTag.uri = callerInfo.contactContentUri;\n args.view.setTag(TAG_PHOTO_INFOS, photoTag);\n args.defaultResource = placeholderImageResource;\n args.listener = listener;\n\n // setup message arguments\n Message msg = sThreadHandler.obtainMessage(token);\n msg.arg1 = EVENT_LOAD_IMAGE;\n msg.obj = args;\n\n preloadImage(imageView, placeholderImageResource, msg);\n }\n\n public static void updateImageViewWithContactPhotoAsync(Context context, ImageView imageView,\n Uri photoUri, int placeholderImageResource) {\n updateImageViewWithUriAsync(context, imageView, photoUri, placeholderImageResource, EVENT_LOAD_IMAGE_URI);\n }\n \n public static void updateImageViewWithContactAsync(Context context, ImageView imageView,\n Uri contactUri, int placeholderImageResource) {\n updateImageViewWithUriAsync(context, imageView, contactUri, placeholderImageResource, EVENT_LOAD_CONTACT_URI);\n }\n\n private static void updateImageViewWithUriAsync(Context context, ImageView imageView,\n Uri photoUri, int placeholderImageResource, int eventType) {\n if (sThreadHandler == null) {\n Log.v(THIS_FILE, \"Update image view with contact async\");\n new ContactsAsyncHelper();\n }\n\n // in case the source caller info is null, the URI will be null as well.\n // just update using the placeholder image in this case.\n if (photoUri == null) {\n defaultImage(imageView, placeholderImageResource);\n return;\n }\n if (isAlreadyProcessed(imageView, photoUri)) {\n return;\n }\n\n // Added additional Cookie field in the callee to handle arguments\n // sent to the callback function.\n\n // setup arguments\n WorkerArgs args = new WorkerArgs();\n args.context = context;\n args.view = imageView;\n PhotoViewTag photoTag = new PhotoViewTag();\n photoTag.uri = photoUri;\n args.view.setTag(TAG_PHOTO_INFOS, photoTag);\n args.defaultResource = placeholderImageResource;\n\n // setup message arguments\n Message msg = sThreadHandler.obtainMessage();\n msg.arg1 = eventType;\n msg.obj = args;\n\n preloadImage(imageView, placeholderImageResource, msg);\n }\n\n private static void defaultImage(ImageView imageView, int placeholderImageResource) {\n Log.v(THIS_FILE, \"No uri, just display placeholder.\");\n PhotoViewTag photoTag = new PhotoViewTag();\n photoTag.uri = null;\n imageView.setTag(TAG_PHOTO_INFOS, photoTag);\n imageView.setVisibility(View.VISIBLE);\n imageView.setImageResource(placeholderImageResource);\n }\n\n private static void preloadImage(ImageView imageView, int placeholderImageResource, Message msg) {\n // set the default image first, when the query is complete, we will\n // replace the image with the correct one.\n if (placeholderImageResource != -1) {\n imageView.setVisibility(View.VISIBLE);\n imageView.setImageResource(placeholderImageResource);\n } else {\n imageView.setVisibility(View.INVISIBLE);\n }\n\n // notify the thread to begin working\n sThreadHandler.sendMessage(msg);\n }\n\n private static boolean isAlreadyProcessed(ImageView imageView, Uri uri) {\n if(imageView != null) {\n PhotoViewTag vt = (PhotoViewTag) imageView.getTag(TAG_PHOTO_INFOS);\n return (vt != null && UriUtils.areEqual(uri, vt.uri));\n }\n return true;\n }\n\n /**\n * Called when loading is done.\n */\n @Override\n public void handleMessage(Message msg) {\n WorkerArgs args = (WorkerArgs) msg.obj;\n if (msg.arg1 == EVENT_LOAD_IMAGE || msg.arg1 == EVENT_LOAD_IMAGE_URI || msg.arg1 == EVENT_LOAD_CONTACT_URI) {\n boolean imagePresent = false;\n // Sanity check on image view\n PhotoViewTag photoTag = (PhotoViewTag) args.view.getTag(TAG_PHOTO_INFOS);\n if (photoTag == null) {\n Log.w(THIS_FILE, \"Tag has been removed meanwhile\");\n return;\n }\n if (!UriUtils.areEqual(args.loadedUri, photoTag.uri)) {\n Log.w(THIS_FILE, \"Image view has changed uri meanwhile\");\n return;\n }\n\n // if the image has been loaded then display it, otherwise set\n // default.\n // in either case, make sure the image is visible.\n if (args.result != null) {\n args.view.setVisibility(View.VISIBLE);\n args.view.setImageBitmap((Bitmap) args.result);\n imagePresent = true;\n } else if (args.defaultResource != -1) {\n args.view.setVisibility(View.VISIBLE);\n args.view.setImageResource(args.defaultResource);\n }\n // notify the listener if it is there.\n if (args.listener != null) {\n Log.v(THIS_FILE, \"Notifying listener: \" + args.listener.toString() +\n \" image: \" + args.loadedUri + \" completed\");\n args.listener.onImageLoadComplete(msg.what, args.cookie, args.view,\n imagePresent);\n }\n }\n }\n\n}"
] | import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.actionbarsherlock.internal.utils.UtilityWrapper;
import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter;
import com.actionbarsherlock.internal.view.menu.ActionMenuView;
import com.actionbarsherlock.internal.view.menu.MenuBuilder;
import com.actionbarsherlock.internal.view.menu.MenuBuilder.Callback;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.csipsimple.R;
import com.csipsimple.api.SipCallSession;
import com.csipsimple.api.SipCallSession.MediaState;
import com.csipsimple.api.SipConfigManager;
import com.csipsimple.api.SipManager;
import com.csipsimple.api.SipProfile;
import com.csipsimple.api.SipUri;
import com.csipsimple.api.SipUri.ParsedSipContactInfos;
import com.csipsimple.models.CallerInfo;
import com.csipsimple.service.SipService;
import com.csipsimple.utils.ContactsAsyncHelper;
import com.csipsimple.utils.CustomDistribution;
import com.csipsimple.utils.ExtraPlugins;
import com.csipsimple.utils.ExtraPlugins.DynActivityPlugin;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.PreferencesProviderWrapper;
import org.webrtc.videoengine.ViERenderer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | /**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.ui.incall;
public class InCallCard extends FrameLayout implements OnClickListener, Callback {
private static final String THIS_FILE = "InCallCard";
private SipCallSession callInfo;
private String cachedRemoteUri = "";
private int cachedInvState = SipCallSession.InvState.INVALID; | private int cachedMediaState = MediaState.ERROR; | 4 |
gustav9797/PowerfulPerms | PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/command/UserRemoveGroupCommand.java | [
"public interface ICommand {\n public boolean hasPermission(String name, String permission); \n}",
"public interface Group {\n\n public int getId();\n\n public String getName();\n\n public List<Group> getParents();\n\n public String getPrefix(String server);\n\n public String getSuffix(String server);\n\n public HashMap<String, String> getPrefixes();\n\n public HashMap<String, String> getSuffixes();\n\n public List<Permission> getOwnPermissions();\n\n public List<Permission> getPermissions();\n\n public String getLadder();\n\n public int getRank();\n\n public void setParents(List<Integer> parents);\n\n}",
"public interface PermissionManager {\n\n // TODO: replace \"with specified name\"\n\n /*\n * Returns the Redis connection.\n */\n public Jedis getRedisConnection();\n\n /*\n * Returns the executor service.\n */\n public ExecutorService getExecutor();\n\n /*\n * Returns the event handler.\n */\n public EventHandler getEventHandler();\n\n /**\n * If using Redis: Tells other servers to reload groups.\n */\n public void notifyReloadGroups();\n\n /**\n * If using Redis: Tells other servers to reload players.\n */\n public void notifyReloadPlayers();\n\n /**\n * If using Redis: Tells other server to reload a player with the specified UUID.\n */\n public void notifyReloadPlayer(UUID uuid);\n\n /**\n * Reloads permission data for online players.\n */\n public void reloadPlayers();\n\n /**\n * Reloads permission data for an online player with the specified name.\n */\n public void reloadPlayer(String name);\n\n /**\n * Reloads permission data for an online player with the specified UUID.\n */\n public void reloadPlayer(UUID uuid);\n\n /**\n * Reloads data for default players.\n */\n public void reloadDefaultPlayers(boolean samethread);\n\n /**\n * Returns the PermissionPlayer instance for the player with the specified UUID. Player has to be online.\n */\n public PermissionPlayer getPermissionPlayer(UUID uuid);\n\n /**\n * Returns the PermissionPlayer instance for the player with the specified name. Player has to be online.\n */\n public PermissionPlayer getPermissionPlayer(String name);\n\n /**\n * Reloads permission data for groups and finally reloads online players.\n */\n public void reloadGroups();\n\n /**\n * Retrieves a group from its name.\n */\n public Group getGroup(String groupName);\n\n /**\n * Retrieves a group from its ID.\n */\n public Group getGroup(int id);\n\n /**\n * Retrieves a clone of all groups.\n */\n public Map<Integer, Group> getGroups();\n\n /**\n * Retrieves all groups of the player with the specified name as they are in the database.\n */\n public ListenableFuture<LinkedHashMap<String, List<CachedGroup>>> getPlayerOwnGroups(UUID uuid);\n\n /**\n * Retrieves all current groups of the player with the specified name. If player does not have any groups it includes the groups of player [default].\n */\n public ListenableFuture<LinkedHashMap<String, List<CachedGroup>>> getPlayerCurrentGroups(UUID uuid);\n\n /**\n * Retrieves the group with highest rank value of the player.\n */\n public ListenableFuture<Group> getPlayerPrimaryGroup(UUID uuid);\n\n /**\n * Checks if player uses groups from player [default].\n */\n public ListenableFuture<Boolean> isPlayerDefault(UUID uuid);\n\n /**\n * Retrieves a DBDocument with permission data of the player with the specified name.\n */\n public ListenableFuture<DBDocument> getPlayerData(UUID uuid);\n\n /**\n * Retrieves a map containing all the permissions of the player with the specified name.\n */\n public ListenableFuture<List<Permission>> getPlayerOwnPermissions(UUID uuid);\n\n /**\n * Offline permission check.\n */\n public ListenableFuture<Boolean> playerHasPermission(UUID uuid, String permission, String world, String server);\n\n /**\n * Retrieves the prefix of the player with the specified name.\n */\n public ListenableFuture<String> getPlayerPrefix(UUID uuid, String ladder);\n\n /**\n * Retrieves the prefix of the player with the specified name.\n */\n public ListenableFuture<String> getPlayerPrefix(UUID uuid);\n\n /**\n * Retrieves the suffix of the player with the specified name.\n */\n public ListenableFuture<String> getPlayerSuffix(UUID uuid, String ladder);\n\n /**\n * Retrieves the suffix of the player with the specified name.\n */\n public ListenableFuture<String> getPlayerSuffix(UUID uuid);\n\n /**\n * Retrieves the own prefix of the player with the specified name.\n */\n public ListenableFuture<String> getPlayerOwnPrefix(UUID uuid);\n\n /**\n * Retrieves the own suffix of the player with the specified name.\n */\n public ListenableFuture<String> getPlayerOwnSuffix(UUID uuid);\n\n /**\n * Retrieves the prefix of the group with the specified name on the specified server. Set server to an empty String or \"all\" for all servers.\n */\n public String getGroupPrefix(int groupId, String server);\n\n /**\n * Retrieves the suffix of the group with the specified name on the specified server. Set server to an empty String or \"all\" for all servers.\n */\n public String getGroupSuffix(int groupId, String server);\n\n /**\n * Retrieves the prefixes of the group with the specified name. The map is indexed by server name.\n */\n public HashMap<String, String> getGroupServerPrefix(int groupId);\n\n /**\n * Retrieves the suffixes of the group with the specified name. The map is indexed by server name.\n */\n public HashMap<String, String> getGroupServerSuffix(int groupId);\n\n /**\n * Retrieves UUID from player name. If player is not online it uses Mojang API.\n */\n public ListenableFuture<UUID> getConvertUUID(final String playerName);\n\n /**\n * Retrieves the scheduler used for sync and asynchronous operations, working on both BungeeCord and Spigot.\n */\n public IScheduler getScheduler();\n\n // Database accessing functions below\n\n public ListenableFuture<Response> createPlayer(String name, UUID uuid);\n\n public ListenableFuture<Response> addPlayerPermission(UUID uuid, String permission);\n\n public ListenableFuture<Response> addPlayerPermission(UUID uuid, String permission, String world, String server, final Date expires);\n\n public ListenableFuture<Response> removePlayerPermission(UUID uuid, String permission);\n\n public ListenableFuture<Response> removePlayerPermission(UUID uuid, String permission, String world, String server, final Date expires);\n\n public ListenableFuture<Response> removePlayerPermissions(UUID uuid);\n\n public ListenableFuture<Response> setPlayerPrefix(UUID uuid, String prefix);\n\n public ListenableFuture<Response> setPlayerSuffix(UUID uuid, String suffix);\n\n public ListenableFuture<Response> removePlayerGroup(UUID uuid, int groupId);\n\n public ListenableFuture<Response> removePlayerGroup(UUID uuid, int groupId, boolean negated);\n\n public ListenableFuture<Response> removePlayerGroup(UUID uuid, int groupId, String server, boolean negated, final Date expires);\n\n public ListenableFuture<Response> addPlayerGroup(UUID uuid, int groupId);\n\n public ListenableFuture<Response> addPlayerGroup(UUID uuid, int groupId, boolean negated);\n\n public ListenableFuture<Response> addPlayerGroup(UUID uuid, int groupId, String server, boolean negated, final Date expires);\n\n public ListenableFuture<Response> setPlayerRank(UUID uuid, int groupId);\n\n public ListenableFuture<Response> promotePlayer(UUID uuid, String ladder);\n\n public ListenableFuture<Response> demotePlayer(UUID uuid, String ladder);\n\n public ListenableFuture<Response> deletePlayer(UUID uuid);\n\n public ListenableFuture<Response> createGroup(String name, String ladder, int rank);\n\n public ListenableFuture<Response> deleteGroup(int groupId);\n\n public ListenableFuture<Response> addGroupPermission(int groupId, String permission);\n\n public ListenableFuture<Response> addGroupPermission(int groupId, String permission, String world, String server, final Date expires);\n\n public ListenableFuture<Response> removeGroupPermission(int groupId, String permission);\n\n public ListenableFuture<Response> removeGroupPermission(int groupId, String permission, String world, String server, final Date expires);\n\n public ListenableFuture<Response> removeGroupPermissions(int groupId);\n\n public ListenableFuture<Response> addGroupParent(int groupId, int parentGroupId);\n\n public ListenableFuture<Response> removeGroupParent(int groupId, int parentGroupId);\n\n public ListenableFuture<Response> setGroupPrefix(int groupId, String prefix);\n\n public ListenableFuture<Response> setGroupPrefix(int groupId, String prefix, String server);\n\n public ListenableFuture<Response> setGroupSuffix(int groupId, String suffix);\n\n public ListenableFuture<Response> setGroupSuffix(int groupId, String suffix, String server);\n\n public ListenableFuture<Response> setGroupLadder(int groupId, String ladder);\n\n public ListenableFuture<Response> setGroupRank(int groupId, int rank);\n\n public ListenableFuture<Response> setGroupName(int groupId, String name);\n\n}",
"public interface PowerfulPermsPlugin {\n\n public PermissionManager getPermissionManager();\n\n public Logger getLogger();\n\n public void runTaskAsynchronously(Runnable runnable);\n\n public void runTaskLater(Runnable runnable, int delay);\n\n public boolean isDebug();\n\n public ServerMode getServerMode();\n\n public boolean isPlayerOnline(UUID uuid);\n\n public boolean isPlayerOnline(String name);\n\n public UUID getPlayerUUID(String name);\n\n public String getPlayerName(UUID uuid);\n\n public Map<UUID, String> getOnlinePlayers();\n\n public void sendPlayerMessage(String name, String message);\n\n public void debug(String message);\n\n public int getOldVersion();\n\n public String getVersion();\n\n public void loadConfig();\n \n public boolean isBungeeCord();\n}",
"public class Response {\n\n protected boolean success = false;\n protected String response = \"\";\n\n public Response(boolean success, String response) {\n this.success = success;\n this.response = response;\n }\n\n public String getResponse() {\n return this.response;\n }\n\n public boolean succeeded() {\n return this.success;\n }\n}"
] | import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import com.github.gustav9797.PowerfulPerms.common.ICommand;
import com.github.gustav9797.PowerfulPermsAPI.Group;
import com.github.gustav9797.PowerfulPermsAPI.PermissionManager;
import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin;
import com.github.gustav9797.PowerfulPermsAPI.Response; | package com.github.gustav9797.PowerfulPerms.command;
public class UserRemoveGroupCommand extends SubCommand {
public UserRemoveGroupCommand(PowerfulPermsPlugin plugin, PermissionManager permissionManager) {
super(plugin, permissionManager);
usage.add("/pp user <user> removegroup <group> (server) (expires)");
}
@Override
public CommandResult execute(final ICommand invoker, final String sender, final String[] args) throws InterruptedException, ExecutionException {
if (hasBasicPerms(invoker, sender, "powerfulperms.user.removegroup") || (args != null && args.length >= 3 && hasPermission(invoker, sender, "powerfulperms.user.removegroup." + args[2]))) {
if (args != null && args.length >= 2 && args[1].equalsIgnoreCase("removegroup")) {
if (args.length < 3) {
sendSender(invoker, sender, getUsage());
return CommandResult.success;
}
final String playerName = args[0];
String groupName = args[2];
final boolean negated = groupName.startsWith("-");
if (negated)
groupName = groupName.substring(1);
final Group group = permissionManager.getGroup(groupName);
if (group == null) {
sendSender(invoker, sender, "Group does not exist.");
return CommandResult.success;
}
final int groupId = group.getId();
UUID uuid = permissionManager.getConvertUUIDBase(playerName);
if (uuid == null) {
sendSender(invoker, sender, "Could not find player UUID.");
} else {
String server = "";
Date expires = null;
if (args.length >= 4)
server = args[3];
if (args.length >= 5 && !args[4].equalsIgnoreCase("NONE")) {
if (args[4].equalsIgnoreCase("ANY"))
expires = Utils.getAnyDate();
else
expires = Utils.getDate(args[4]);
if (expires == null) {
sendSender(invoker, sender, "Invalid expiration format.");
return CommandResult.success;
}
} | Response response = permissionManager.removePlayerGroupBase(uuid, groupId, server, negated, expires); | 4 |
loklak/loklak_server | src/org/loklak/DumpProcessConversation.java | [
"public class JSONObject {\n /**\n * JSONObject.NULL is equivalent to the value that JavaScript calls null,\n * whilst Java's null is equivalent to the value that JavaScript calls\n * undefined.\n */\n private static final class Null {\n\n /**\n * There is only intended to be a single instance of the NULL object,\n * so the clone method returns itself.\n *\n * @return NULL.\n */\n @Override\n protected final Object clone() {\n return this;\n }\n\n /**\n * A Null object is equal to the null value and to itself.\n *\n * @param object\n * An object to test for nullness.\n * @return true if the object parameter is the JSONObject.NULL object or\n * null.\n */\n @Override\n public boolean equals(Object object) {\n return object == null || object == this;\n }\n /**\n * A Null object is equal to the null value and to itself.\n *\n * @return always returns 0.\n */\n @Override\n public int hashCode() {\n return 0;\n }\n\n /**\n * Get the \"null\" string value.\n *\n * @return The string \"null\".\n */\n @Override\n public String toString() {\n return \"null\";\n }\n }\n \n /**\n * Regular Expression Pattern that matches JSON Numbers. This is primarily used for\n * output to guarantee that we are always writing valid JSON. \n */\n static final Pattern NUMBER_PATTERN = Pattern.compile(\"-?(?:0|[1-9]\\\\d*)(?:\\\\.\\\\d+)?(?:[eE][+-]?\\\\d+)?\");\n\n /**\n * The map where the JSONObject's properties are kept.\n */\n private final Map<String, Object> map;\n\n /**\n * It is sometimes more convenient and less ambiguous to have a\n * <code>NULL</code> object than to use Java's <code>null</code> value.\n * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.\n * <code>JSONObject.NULL.toString()</code> returns <code>\"null\"</code>.\n */\n public static final Object NULL = new Null();\n\n /**\n * Construct an empty JSONObject.\n */\n public JSONObject() {\n // HashMap is used on purpose to ensure that elements are unordered by \n // the specification.\n // JSON tends to be a portable transfer format to allows the container \n // implementations to rearrange their items for a faster element \n // retrieval based on associative access.\n // Therefore, an implementation mustn't rely on the order of the item.\n this.map = new HashMap<String, Object>();\n }\n\n /**\n * Construct an empty JSONObject.\n * \n * @param ordered\n * if ordered == true, then the JSONObject keeps the original order of properties\n */\n public JSONObject(boolean ordered) {\n this.map = ordered ? new LinkedHashMap<String, Object>() : new HashMap<String, Object>();\n }\n\n /**\n * Construct a JSONObject from a subset of another JSONObject. An array of\n * strings is used to identify the keys that should be copied. Missing keys\n * are ignored.\n *\n * @param jo\n * A JSONObject.\n * @param names\n * An array of strings.\n */\n public JSONObject(JSONObject jo, String ... names) {\n this(names.length);\n for (int i = 0; i < names.length; i += 1) {\n try {\n this.putOnce(names[i], jo.opt(names[i]));\n } catch (Exception ignore) {\n }\n }\n }\n\n /**\n * Construct a JSONObject from a JSONTokener.\n *\n * @param x\n * A JSONTokener object containing the source string.\n * @throws JSONException\n * If there is a syntax error in the source string or a\n * duplicated key.\n */\n public JSONObject(JSONTokener x) throws JSONException {\n this(true);\n char c;\n String key;\n\n if (x.nextClean() != '{') {\n throw x.syntaxError(\"A JSONObject text must begin with '{'\");\n }\n for (;;) {\n c = x.nextClean();\n switch (c) {\n case 0:\n throw x.syntaxError(\"A JSONObject text must end with '}'\");\n case '}':\n return;\n default:\n x.back();\n key = x.nextValue().toString();\n }\n\n // The key is followed by ':'.\n\n c = x.nextClean();\n if (c != ':') {\n throw x.syntaxError(\"Expected a ':' after a key\");\n }\n \n // Use syntaxError(..) to include error location\n \n if (key != null) {\n // Check if key exists\n if (this.opt(key) != null) {\n // key already exists\n throw x.syntaxError(\"Duplicate key \\\"\" + key + \"\\\"\");\n }\n // Only add value if non-null\n Object value = x.nextValue();\n if (value!=null) {\n this.put(key, value);\n }\n }\n\n // Pairs are separated by ','.\n\n switch (x.nextClean()) {\n case ';':\n case ',':\n if (x.nextClean() == '}') {\n return;\n }\n x.back();\n break;\n case '}':\n return;\n default:\n throw x.syntaxError(\"Expected a ',' or '}'\");\n }\n }\n }\n\n /**\n * Construct a JSONObject from a Map.\n *\n * @param m\n * A map object that can be used to initialize the contents of\n * the JSONObject.\n * @throws JSONException\n * If a value in the map is non-finite number.\n * @throws NullPointerException\n * If a key in the map is <code>null</code>\n */\n public JSONObject(Map<?, ?> m) {\n if (m == null) {\n this.map = new LinkedHashMap<String, Object>();\n } else {\n this.map = new HashMap<String, Object>(m.size());\n \tfor (final Entry<?, ?> e : m.entrySet()) {\n \t if(e.getKey() == null) {\n \t throw new NullPointerException(\"Null key.\");\n \t }\n final Object value = e.getValue();\n if (value != null) {\n this.map.put(String.valueOf(e.getKey()), wrap(value));\n }\n }\n }\n }\n\n /**\n * Construct a JSONObject from an Object using bean getters. It reflects on\n * all of the public methods of the object. For each of the methods with no\n * parameters and a name starting with <code>\"get\"</code> or\n * <code>\"is\"</code> followed by an uppercase letter, the method is invoked,\n * and a key and the value returned from the getter method are put into the\n * new JSONObject.\n * <p>\n * The key is formed by removing the <code>\"get\"</code> or <code>\"is\"</code>\n * prefix. If the second remaining character is not upper case, then the\n * first character is converted to lower case.\n * <p>\n * Methods that are <code>static</code>, return <code>void</code>,\n * have parameters, or are \"bridge\" methods, are ignored.\n * <p>\n * For example, if an object has a method named <code>\"getName\"</code>, and\n * if the result of calling <code>object.getName()</code> is\n * <code>\"Larry Fine\"</code>, then the JSONObject will contain\n * <code>\"name\": \"Larry Fine\"</code>.\n * <p>\n * The {@link JSONPropertyName} annotation can be used on a bean getter to\n * override key name used in the JSONObject. For example, using the object\n * above with the <code>getName</code> method, if we annotated it with:\n * <pre>\n * @JSONPropertyName(\"FullName\")\n * public String getName() { return this.name; }\n * </pre>\n * The resulting JSON object would contain <code>\"FullName\": \"Larry Fine\"</code>\n * <p>\n * Similarly, the {@link JSONPropertyName} annotation can be used on non-\n * <code>get</code> and <code>is</code> methods. We can also override key\n * name used in the JSONObject as seen below even though the field would normally\n * be ignored:\n * <pre>\n * @JSONPropertyName(\"FullName\")\n * public String fullName() { return this.name; }\n * </pre>\n * The resulting JSON object would contain <code>\"FullName\": \"Larry Fine\"</code>\n * <p>\n * The {@link JSONPropertyIgnore} annotation can be used to force the bean property\n * to not be serialized into JSON. If both {@link JSONPropertyIgnore} and\n * {@link JSONPropertyName} are defined on the same method, a depth comparison is\n * performed and the one closest to the concrete class being serialized is used.\n * If both annotations are at the same level, then the {@link JSONPropertyIgnore}\n * annotation takes precedent and the field is not serialized.\n * For example, the following declaration would prevent the <code>getName</code>\n * method from being serialized:\n * <pre>\n * @JSONPropertyName(\"FullName\")\n * @JSONPropertyIgnore \n * public String getName() { return this.name; }\n * </pre>\n * <p>\n * \n * @param bean\n * An object that has getter methods that should be used to make\n * a JSONObject.\n */\n public JSONObject(Object bean) {\n this();\n this.populateMap(bean);\n }\n\n /**\n * Construct a JSONObject from an Object, using reflection to find the\n * public members. The resulting JSONObject's keys will be the strings from\n * the names array, and the values will be the field values associated with\n * those keys in the object. If a key is not found or not visible, then it\n * will not be copied into the new JSONObject.\n *\n * @param object\n * An object that has fields that should be used to make a\n * JSONObject.\n * @param names\n * An array of strings, the names of the fields to be obtained\n * from the object.\n */\n public JSONObject(Object object, String ... names) {\n this(names.length);\n Class<?> c = object.getClass();\n for (int i = 0; i < names.length; i += 1) {\n String name = names[i];\n try {\n this.putOpt(name, c.getField(name).get(object));\n } catch (Exception ignore) {\n }\n }\n }\n\n /**\n * Construct a JSONObject from a source JSON text string. This is the most\n * commonly used JSONObject constructor.\n *\n * @param source\n * A string beginning with <code>{</code> <small>(left\n * brace)</small> and ending with <code>}</code>\n * <small>(right brace)</small>.\n * @exception JSONException\n * If there is a syntax error in the source string or a\n * duplicated key.\n */\n public JSONObject(String source) throws JSONException {\n this(new JSONTokener(source));\n }\n\n /**\n * Construct a JSONObject from a ResourceBundle.\n *\n * @param baseName\n * The ResourceBundle base name.\n * @param locale\n * The Locale to load the ResourceBundle for.\n * @throws JSONException\n * If any JSONExceptions are detected.\n */\n public JSONObject(String baseName, Locale locale) throws JSONException {\n this();\n ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,\n Thread.currentThread().getContextClassLoader());\n\n// Iterate through the keys in the bundle.\n\n Enumeration<String> keys = bundle.getKeys();\n while (keys.hasMoreElements()) {\n Object key = keys.nextElement();\n if (key != null) {\n\n// Go through the path, ensuring that there is a nested JSONObject for each\n// segment except the last. Add the value using the last segment's name into\n// the deepest nested JSONObject.\n\n String[] path = ((String) key).split(\"\\\\.\");\n int last = path.length - 1;\n JSONObject target = this;\n for (int i = 0; i < last; i += 1) {\n String segment = path[i];\n JSONObject nextTarget = target.optJSONObject(segment);\n if (nextTarget == null) {\n nextTarget = new JSONObject();\n target.put(segment, nextTarget);\n }\n target = nextTarget;\n }\n target.put(path[last], bundle.getString((String) key));\n }\n }\n }\n \n /**\n * Constructor to specify an initial capacity of the internal map. Useful for library \n * internal calls where we know, or at least can best guess, how big this JSONObject\n * will be.\n * \n * @param initialCapacity initial capacity of the internal map.\n */\n protected JSONObject(int initialCapacity){\n this.map = new HashMap<String, Object>(initialCapacity);\n }\n\n /**\n * Accumulate values under a key. It is similar to the put method except\n * that if there is already an object stored under the key then a JSONArray\n * is stored under the key to hold all of the accumulated values. If there\n * is already a JSONArray, then the new value is appended to it. In\n * contrast, the put method replaces the previous value.\n *\n * If only one value is accumulated that is not a JSONArray, then the result\n * will be the same as using put. But if multiple values are accumulated,\n * then the result will be like append.\n *\n * @param key\n * A key string.\n * @param value\n * An object to be accumulated under the key.\n * @return this.\n * @throws JSONException\n * If the value is non-finite number.\n * @throws NullPointerException\n * If the key is <code>null</code>.\n */\n public JSONObject accumulate(String key, Object value) throws JSONException {\n testValidity(value);\n Object object = this.opt(key);\n if (object == null) {\n this.put(key,\n value instanceof JSONArray ? new JSONArray().put(value)\n : value);\n } else if (object instanceof JSONArray) {\n ((JSONArray) object).put(value);\n } else {\n this.put(key, new JSONArray().put(object).put(value));\n }\n return this;\n }\n\n /**\n * Append values to the array under a key. If the key does not exist in the\n * JSONObject, then the key is put in the JSONObject with its value being a\n * JSONArray containing the value parameter. If the key was already\n * associated with a JSONArray, then the value parameter is appended to it.\n *\n * @param key\n * A key string.\n * @param value\n * An object to be accumulated under the key.\n * @return this.\n * @throws JSONException\n * If the value is non-finite number or if the current value associated with\n * the key is not a JSONArray.\n * @throws NullPointerException\n * If the key is <code>null</code>.\n */\n public JSONObject append(String key, Object value) throws JSONException {\n testValidity(value);\n Object object = this.opt(key);\n if (object == null) {\n this.put(key, new JSONArray().put(value));\n } else if (object instanceof JSONArray) {\n this.put(key, ((JSONArray) object).put(value));\n } else {\n throw wrongValueFormatException(key, \"JSONArray\", null, null);\n }\n return this;\n }\n\n /**\n * Produce a string from a double. The string \"null\" will be returned if the\n * number is not finite.\n *\n * @param d\n * A double.\n * @return A String.\n */\n public static String doubleToString(double d) {\n if (Double.isInfinite(d) || Double.isNaN(d)) {\n return \"null\";\n }\n\n// Shave off trailing zeros and decimal point, if possible.\n\n String string = Double.toString(d);\n if (string.indexOf('.') > 0 && string.indexOf('e') < 0\n && string.indexOf('E') < 0) {\n while (string.endsWith(\"0\")) {\n string = string.substring(0, string.length() - 1);\n }\n if (string.endsWith(\".\")) {\n string = string.substring(0, string.length() - 1);\n }\n }\n return string;\n }\n\n /**\n * Get the value object associated with a key.\n *\n * @param key\n * A key string.\n * @return The object associated with the key.\n * @throws JSONException\n * if the key is not found.\n */\n public Object get(String key) throws JSONException {\n if (key == null) {\n throw new JSONException(\"Null key.\");\n }\n Object object = this.opt(key);\n if (object == null) {\n throw new JSONException(\"JSONObject[\" + quote(key) + \"] not found.\");\n }\n return object;\n }\n\n /**\n * Get the enum value associated with a key.\n * \n * @param <E>\n * Enum Type\n * @param clazz\n * The type of enum to retrieve.\n * @param key\n * A key string.\n * @return The enum value associated with the key\n * @throws JSONException\n * if the key is not found or if the value cannot be converted\n * to an enum.\n */\n public <E extends Enum<E>> E getEnum(Class<E> clazz, String key) throws JSONException {\n E val = optEnum(clazz, key);\n if(val==null) {\n // JSONException should really take a throwable argument.\n // If it did, I would re-implement this with the Enum.valueOf\n // method and place any thrown exception in the JSONException\n throw wrongValueFormatException(key, \"enum of type \" + quote(clazz.getSimpleName()), null);\n }\n return val;\n }\n\n /**\n * Get the boolean value associated with a key.\n *\n * @param key\n * A key string.\n * @return The truth.\n * @throws JSONException\n * if the value is not a Boolean or the String \"true\" or\n * \"false\".\n */\n public boolean getBoolean(String key) throws JSONException {\n Object object = this.get(key);\n if (object.equals(Boolean.FALSE)\n || (object instanceof String && ((String) object)\n .equalsIgnoreCase(\"false\"))) {\n return false;\n } else if (object.equals(Boolean.TRUE)\n || (object instanceof String && ((String) object)\n .equalsIgnoreCase(\"true\"))) {\n return true;\n }\n throw wrongValueFormatException(key, \"Boolean\", null);\n }\n\n /**\n * Get the BigInteger value associated with a key.\n *\n * @param key\n * A key string.\n * @return The numeric value.\n * @throws JSONException\n * if the key is not found or if the value cannot \n * be converted to BigInteger.\n */\n public BigInteger getBigInteger(String key) throws JSONException {\n Object object = this.get(key);\n BigInteger ret = objectToBigInteger(object, null);\n if (ret != null) {\n return ret;\n }\n throw wrongValueFormatException(key, \"BigInteger\", object, null);\n }\n\n /**\n * Get the BigDecimal value associated with a key. If the value is float or\n * double, the the {@link BigDecimal#BigDecimal(double)} constructor will\n * be used. See notes on the constructor for conversion issues that may\n * arise.\n *\n * @param key\n * A key string.\n * @return The numeric value.\n * @throws JSONException\n * if the key is not found or if the value\n * cannot be converted to BigDecimal.\n */\n public BigDecimal getBigDecimal(String key) throws JSONException {\n Object object = this.get(key);\n BigDecimal ret = objectToBigDecimal(object, null);\n if (ret != null) {\n return ret;\n }\n throw wrongValueFormatException(key, \"BigDecimal\", object, null);\n }\n\n /**\n * Get the double value associated with a key.\n *\n * @param key\n * A key string.\n * @return The numeric value.\n * @throws JSONException\n * if the key is not found or if the value is not a Number\n * object and cannot be converted to a number.\n */\n public double getDouble(String key) throws JSONException {\n final Object object = this.get(key);\n if(object instanceof Number) {\n return ((Number)object).doubleValue();\n }\n try {\n return Double.parseDouble(object.toString());\n } catch (Exception e) {\n throw wrongValueFormatException(key, \"double\", e);\n }\n }\n\n /**\n * Get the float value associated with a key.\n *\n * @param key\n * A key string.\n * @return The numeric value.\n * @throws JSONException\n * if the key is not found or if the value is not a Number\n * object and cannot be converted to a number.\n */\n public float getFloat(String key) throws JSONException {\n final Object object = this.get(key);\n if(object instanceof Number) {\n return ((Number)object).floatValue();\n }\n try {\n return Float.parseFloat(object.toString());\n } catch (Exception e) {\n throw wrongValueFormatException(key, \"float\", e);\n }\n }\n\n /**\n * Get the Number value associated with a key.\n *\n * @param key\n * A key string.\n * @return The numeric value.\n * @throws JSONException\n * if the key is not found or if the value is not a Number\n * object and cannot be converted to a number.\n */\n public Number getNumber(String key) throws JSONException {\n Object object = this.get(key);\n try {\n if (object instanceof Number) {\n return (Number)object;\n }\n return stringToNumber(object.toString());\n } catch (Exception e) {\n throw wrongValueFormatException(key, \"number\", e);\n }\n }\n\n /**\n * Get the int value associated with a key.\n *\n * @param key\n * A key string.\n * @return The integer value.\n * @throws JSONException\n * if the key is not found or if the value cannot be converted\n * to an integer.\n */\n public int getInt(String key) throws JSONException {\n final Object object = this.get(key);\n if(object instanceof Number) {\n return ((Number)object).intValue();\n }\n try {\n return Integer.parseInt(object.toString());\n } catch (Exception e) {\n throw wrongValueFormatException(key, \"int\", e);\n }\n }\n\n /**\n * Get the JSONArray value associated with a key.\n *\n * @param key\n * A key string.\n * @return A JSONArray which is the value.\n * @throws JSONException\n * if the key is not found or if the value is not a JSONArray.\n */\n public JSONArray getJSONArray(String key) throws JSONException {\n Object object = this.get(key);\n if (object instanceof JSONArray) {\n return (JSONArray) object;\n }\n throw wrongValueFormatException(key, \"JSONArray\", null);\n }\n\n /**\n * Get the JSONObject value associated with a key.\n *\n * @param key\n * A key string.\n * @return A JSONObject which is the value.\n * @throws JSONException\n * if the key is not found or if the value is not a JSONObject.\n */\n public JSONObject getJSONObject(String key) throws JSONException {\n Object object = this.get(key);\n if (object instanceof JSONObject) {\n return (JSONObject) object;\n }\n throw wrongValueFormatException(key, \"JSONObject\", null);\n }\n\n /**\n * Get the long value associated with a key.\n *\n * @param key\n * A key string.\n * @return The long value.\n * @throws JSONException\n * if the key is not found or if the value cannot be converted\n * to a long.\n */\n public long getLong(String key) throws JSONException {\n final Object object = this.get(key);\n if(object instanceof Number) {\n return ((Number)object).longValue();\n }\n try {\n return Long.parseLong(object.toString());\n } catch (Exception e) {\n throw wrongValueFormatException(key, \"long\", e);\n }\n }\n\n /**\n * Get an array of field names from a JSONObject.\n *\n * @param jo\n * JSON object\n * @return An array of field names, or null if there are no names.\n */\n public static String[] getNames(JSONObject jo) {\n if (jo.isEmpty()) {\n return null;\n }\n return jo.keySet().toArray(new String[jo.length()]);\n }\n\n /**\n * Get an array of public field names from an Object.\n *\n * @param object\n * object to read\n * @return An array of field names, or null if there are no names.\n */\n public static String[] getNames(Object object) {\n if (object == null) {\n return null;\n }\n Class<?> klass = object.getClass();\n Field[] fields = klass.getFields();\n int length = fields.length;\n if (length == 0) {\n return null;\n }\n String[] names = new String[length];\n for (int i = 0; i < length; i += 1) {\n names[i] = fields[i].getName();\n }\n return names;\n }\n\n /**\n * Get the string associated with a key.\n *\n * @param key\n * A key string.\n * @return A string which is the value.\n * @throws JSONException\n * if there is no string value for the key.\n */\n public String getString(String key) throws JSONException {\n Object object = this.get(key);\n if (object instanceof String) {\n return (String) object;\n }\n throw wrongValueFormatException(key, \"string\", null);\n }\n\n /**\n * Determine if the JSONObject contains a specific key.\n *\n * @param key\n * A key string.\n * @return true if the key exists in the JSONObject.\n */\n public boolean has(String key) {\n return this.map.containsKey(key);\n }\n\n /**\n * Increment a property of a JSONObject. If there is no such property,\n * create one with a value of 1 (Integer). If there is such a property, and if it is\n * an Integer, Long, Double, Float, BigInteger, or BigDecimal then add one to it.\n * No overflow bounds checking is performed, so callers should initialize the key\n * prior to this call with an appropriate type that can handle the maximum expected\n * value.\n *\n * @param key\n * A key string.\n * @return this.\n * @throws JSONException\n * If there is already a property with this name that is not an\n * Integer, Long, Double, or Float.\n */\n public JSONObject increment(String key) throws JSONException {\n Object value = this.opt(key);\n if (value == null) {\n this.put(key, 1);\n } else if (value instanceof Integer) {\n this.put(key, ((Integer) value).intValue() + 1);\n } else if (value instanceof Long) {\n this.put(key, ((Long) value).longValue() + 1L);\n } else if (value instanceof BigInteger) {\n this.put(key, ((BigInteger)value).add(BigInteger.ONE));\n } else if (value instanceof Float) {\n this.put(key, ((Float) value).floatValue() + 1.0f);\n } else if (value instanceof Double) {\n this.put(key, ((Double) value).doubleValue() + 1.0d);\n } else if (value instanceof BigDecimal) {\n this.put(key, ((BigDecimal)value).add(BigDecimal.ONE));\n } else {\n throw new JSONException(\"Unable to increment [\" + quote(key) + \"].\");\n }\n return this;\n }\n\n /**\n * Determine if the value associated with the key is <code>null</code> or if there is no\n * value.\n *\n * @param key\n * A key string.\n * @return true if there is no value associated with the key or if the value\n * is the JSONObject.NULL object.\n */\n public boolean isNull(String key) {\n return JSONObject.NULL.equals(this.opt(key));\n }\n\n /**\n * Get an enumeration of the keys of the JSONObject. Modifying this key Set will also\n * modify the JSONObject. Use with caution.\n *\n * @see Set#iterator()\n * \n * @return An iterator of the keys.\n */\n public Iterator<String> keys() {\n return this.keySet().iterator();\n }\n\n /**\n * Get a set of keys of the JSONObject. Modifying this key Set will also modify the\n * JSONObject. Use with caution.\n *\n * @see Map#keySet()\n *\n * @return A keySet.\n */\n public Set<String> keySet() {\n return this.map.keySet();\n }\n\n /**\n * Get a set of entries of the JSONObject. These are raw values and may not\n * match what is returned by the JSONObject get* and opt* functions. Modifying \n * the returned EntrySet or the Entry objects contained therein will modify the\n * backing JSONObject. This does not return a clone or a read-only view.\n * \n * Use with caution.\n *\n * @see Map#entrySet()\n *\n * @return An Entry Set\n */\n protected Set<Entry<String, Object>> entrySet() {\n return this.map.entrySet();\n }\n\n /**\n * Get the number of keys stored in the JSONObject.\n *\n * @return The number of keys in the JSONObject.\n */\n public int length() {\n return this.map.size();\n }\n\n /**\n * Check if JSONObject is empty.\n *\n * @return true if JSONObject is empty, otherwise false.\n */\n public boolean isEmpty() {\n return this.map.isEmpty();\n }\n\n /**\n * Produce a JSONArray containing the names of the elements of this\n * JSONObject.\n *\n * @return A JSONArray containing the key strings, or null if the JSONObject\n * is empty.\n */\n public JSONArray names() {\n \tif(this.map.isEmpty()) {\n \t\treturn null;\n \t}\n return new JSONArray(this.map.keySet());\n }\n\n /**\n * Produce a string from a Number.\n *\n * @param number\n * A Number\n * @return A String.\n * @throws JSONException\n * If n is a non-finite number.\n */\n public static String numberToString(Number number) throws JSONException {\n if (number == null) {\n throw new JSONException(\"Null pointer\");\n }\n testValidity(number);\n\n // Shave off trailing zeros and decimal point, if possible.\n\n String string = number.toString();\n if (string.indexOf('.') > 0 && string.indexOf('e') < 0\n && string.indexOf('E') < 0) {\n while (string.endsWith(\"0\")) {\n string = string.substring(0, string.length() - 1);\n }\n if (string.endsWith(\".\")) {\n string = string.substring(0, string.length() - 1);\n }\n }\n return string;\n }\n\n /**\n * Get an optional value associated with a key.\n *\n * @param key\n * A key string.\n * @return An object which is the value, or null if there is no value.\n */\n public Object opt(String key) {\n return key == null ? null : this.map.get(key);\n }\n\n /**\n * Get the enum value associated with a key.\n * \n * @param <E>\n * Enum Type\n * @param clazz\n * The type of enum to retrieve.\n * @param key\n * A key string.\n * @return The enum value associated with the key or null if not found\n */\n public <E extends Enum<E>> E optEnum(Class<E> clazz, String key) {\n return this.optEnum(clazz, key, null);\n }\n\n /**\n * Get the enum value associated with a key.\n * \n * @param <E>\n * Enum Type\n * @param clazz\n * The type of enum to retrieve.\n * @param key\n * A key string.\n * @param defaultValue\n * The default in case the value is not found\n * @return The enum value associated with the key or defaultValue\n * if the value is not found or cannot be assigned to <code>clazz</code>\n */\n public <E extends Enum<E>> E optEnum(Class<E> clazz, String key, E defaultValue) {\n try {\n Object val = this.opt(key);\n if (NULL.equals(val)) {\n return defaultValue;\n }\n if (clazz.isAssignableFrom(val.getClass())) {\n // we just checked it!\n @SuppressWarnings(\"unchecked\")\n E myE = (E) val;\n return myE;\n }\n return Enum.valueOf(clazz, val.toString());\n } catch (IllegalArgumentException e) {\n return defaultValue;\n } catch (NullPointerException e) {\n return defaultValue;\n }\n }\n\n /**\n * Get an optional boolean associated with a key. It returns false if there\n * is no such key, or if the value is not Boolean.TRUE or the String \"true\".\n *\n * @param key\n * A key string.\n * @return The truth.\n */\n public boolean optBoolean(String key) {\n return this.optBoolean(key, false);\n }\n\n /**\n * Get an optional boolean associated with a key. It returns the\n * defaultValue if there is no such key, or if it is not a Boolean or the\n * String \"true\" or \"false\" (case insensitive).\n *\n * @param key\n * A key string.\n * @param defaultValue\n * The default.\n * @return The truth.\n */\n public boolean optBoolean(String key, boolean defaultValue) {\n Object val = this.opt(key);\n if (NULL.equals(val)) {\n return defaultValue;\n }\n if (val instanceof Boolean){\n return ((Boolean) val).booleanValue();\n }\n try {\n // we'll use the get anyway because it does string conversion.\n return this.getBoolean(key);\n } catch (Exception e) {\n return defaultValue;\n }\n }\n\n /**\n * Get an optional BigDecimal associated with a key, or the defaultValue if\n * there is no such key or if its value is not a number. If the value is a\n * string, an attempt will be made to evaluate it as a number. If the value\n * is float or double, then the {@link BigDecimal#BigDecimal(double)}\n * constructor will be used. See notes on the constructor for conversion\n * issues that may arise.\n *\n * @param key\n * A key string.\n * @param defaultValue\n * The default.\n * @return An object which is the value.\n */\n public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) {\n Object val = this.opt(key);\n return objectToBigDecimal(val, defaultValue);\n }\n\n /**\n * @param val value to convert\n * @param defaultValue default value to return is the conversion doesn't work or is null.\n * @return BigDecimal conversion of the original value, or the defaultValue if unable\n * to convert. \n */\n static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue) {\n if (NULL.equals(val)) {\n return defaultValue;\n }\n if (val instanceof BigDecimal){\n return (BigDecimal) val;\n }\n if (val instanceof BigInteger){\n return new BigDecimal((BigInteger) val);\n }\n if (val instanceof Double || val instanceof Float){\n final double d = ((Number) val).doubleValue();\n if(Double.isNaN(d)) {\n return defaultValue;\n }\n return new BigDecimal(((Number) val).doubleValue());\n }\n if (val instanceof Long || val instanceof Integer\n || val instanceof Short || val instanceof Byte){\n return new BigDecimal(((Number) val).longValue());\n }\n // don't check if it's a string in case of unchecked Number subclasses\n try {\n return new BigDecimal(val.toString());\n } catch (Exception e) {\n return defaultValue;\n }\n }\n\n /**\n * Get an optional BigInteger associated with a key, or the defaultValue if\n * there is no such key or if its value is not a number. If the value is a\n * string, an attempt will be made to evaluate it as a number.\n *\n * @param key\n * A key string.\n * @param defaultValue\n * The default.\n * @return An object which is the value.\n */\n public BigInteger optBigInteger(String key, BigInteger defaultValue) {\n Object val = this.opt(key);\n return objectToBigInteger(val, defaultValue);\n }\n\n /**\n * @param val value to convert\n * @param defaultValue default value to return is the conversion doesn't work or is null.\n * @return BigInteger conversion of the original value, or the defaultValue if unable\n * to convert. \n */\n static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) {\n if (NULL.equals(val)) {\n return defaultValue;\n }\n if (val instanceof BigInteger){\n return (BigInteger) val;\n }\n if (val instanceof BigDecimal){\n return ((BigDecimal) val).toBigInteger();\n }\n if (val instanceof Double || val instanceof Float){\n final double d = ((Number) val).doubleValue();\n if(Double.isNaN(d)) {\n return defaultValue;\n }\n return new BigDecimal(d).toBigInteger();\n }\n if (val instanceof Long || val instanceof Integer\n || val instanceof Short || val instanceof Byte){\n return BigInteger.valueOf(((Number) val).longValue());\n }\n // don't check if it's a string in case of unchecked Number subclasses\n try {\n // the other opt functions handle implicit conversions, i.e. \n // jo.put(\"double\",1.1d);\n // jo.optInt(\"double\"); -- will return 1, not an error\n // this conversion to BigDecimal then to BigInteger is to maintain\n // that type cast support that may truncate the decimal.\n final String valStr = val.toString();\n if(isDecimalNotation(valStr)) {\n return new BigDecimal(valStr).toBigInteger();\n }\n return new BigInteger(valStr);\n } catch (Exception e) {\n return defaultValue;\n }\n }\n\n /**\n * Get an optional double associated with a key, or NaN if there is no such\n * key or if its value is not a number. If the value is a string, an attempt\n * will be made to evaluate it as a number.\n *\n * @param key\n * A string which is the key.\n * @return An object which is the value.\n */\n public double optDouble(String key) {\n return this.optDouble(key, Double.NaN);\n }\n\n /**\n * Get an optional double associated with a key, or the defaultValue if\n * there is no such key or if its value is not a number. If the value is a\n * string, an attempt will be made to evaluate it as a number.\n *\n * @param key\n * A key string.\n * @param defaultValue\n * The default.\n * @return An object which is the value.\n */\n public double optDouble(String key, double defaultValue) {\n Number val = this.optNumber(key);\n if (val == null) {\n return defaultValue;\n }\n final double doubleValue = val.doubleValue();\n // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {\n // return defaultValue;\n // }\n return doubleValue;\n }\n\n /**\n * Get the optional double value associated with an index. NaN is returned\n * if there is no value for the index, or if the value is not a number and\n * cannot be converted to a number.\n *\n * @param key\n * A key string.\n * @return The value.\n */\n public float optFloat(String key) {\n return this.optFloat(key, Float.NaN);\n }\n\n /**\n * Get the optional double value associated with an index. The defaultValue\n * is returned if there is no value for the index, or if the value is not a\n * number and cannot be converted to a number.\n *\n * @param key\n * A key string.\n * @param defaultValue\n * The default value.\n * @return The value.\n */\n public float optFloat(String key, float defaultValue) {\n Number val = this.optNumber(key);\n if (val == null) {\n return defaultValue;\n }\n final float floatValue = val.floatValue();\n // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {\n // return defaultValue;\n // }\n return floatValue;\n }\n\n /**\n * Get an optional int value associated with a key, or zero if there is no\n * such key or if the value is not a number. If the value is a string, an\n * attempt will be made to evaluate it as a number.\n *\n * @param key\n * A key string.\n * @return An object which is the value.\n */\n public int optInt(String key) {\n return this.optInt(key, 0);\n }\n\n /**\n * Get an optional int value associated with a key, or the default if there\n * is no such key or if the value is not a number. If the value is a string,\n * an attempt will be made to evaluate it as a number.\n *\n * @param key\n * A key string.\n * @param defaultValue\n * The default.\n * @return An object which is the value.\n */\n public int optInt(String key, int defaultValue) {\n final Number val = this.optNumber(key, null);\n if (val == null) {\n return defaultValue;\n }\n return val.intValue();\n }\n\n /**\n * Get an optional JSONArray associated with a key. It returns null if there\n * is no such key, or if its value is not a JSONArray.\n *\n * @param key\n * A key string.\n * @return A JSONArray which is the value.\n */\n public JSONArray optJSONArray(String key) {\n Object o = this.opt(key);\n return o instanceof JSONArray ? (JSONArray) o : null;\n }\n\n /**\n * Get an optional JSONObject associated with a key. It returns null if\n * there is no such key, or if its value is not a JSONObject.\n *\n * @param key\n * A key string.\n * @return A JSONObject which is the value.\n */\n public JSONObject optJSONObject(String key) {\n Object object = this.opt(key);\n return object instanceof JSONObject ? (JSONObject) object : null;\n }\n\n /**\n * Get an optional long value associated with a key, or zero if there is no\n * such key or if the value is not a number. If the value is a string, an\n * attempt will be made to evaluate it as a number.\n *\n * @param key\n * A key string.\n * @return An object which is the value.\n */\n public long optLong(String key) {\n return this.optLong(key, 0);\n }\n\n /**\n * Get an optional long value associated with a key, or the default if there\n * is no such key or if the value is not a number. If the value is a string,\n * an attempt will be made to evaluate it as a number.\n *\n * @param key\n * A key string.\n * @param defaultValue\n * The default.\n * @return An object which is the value.\n */\n public long optLong(String key, long defaultValue) {\n final Number val = this.optNumber(key, null);\n if (val == null) {\n return defaultValue;\n }\n \n return val.longValue();\n }\n \n /**\n * Get an optional {@link Number} value associated with a key, or <code>null</code>\n * if there is no such key or if the value is not a number. If the value is a string,\n * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method\n * would be used in cases where type coercion of the number value is unwanted.\n *\n * @param key\n * A key string.\n * @return An object which is the value.\n */\n public Number optNumber(String key) {\n return this.optNumber(key, null);\n }\n\n /**\n * Get an optional {@link Number} value associated with a key, or the default if there\n * is no such key or if the value is not a number. If the value is a string,\n * an attempt will be made to evaluate it as a number. This method\n * would be used in cases where type coercion of the number value is unwanted.\n *\n * @param key\n * A key string.\n * @param defaultValue\n * The default.\n * @return An object which is the value.\n */\n public Number optNumber(String key, Number defaultValue) {\n Object val = this.opt(key);\n if (NULL.equals(val)) {\n return defaultValue;\n }\n if (val instanceof Number){\n return (Number) val;\n }\n \n try {\n return stringToNumber(val.toString());\n } catch (Exception e) {\n return defaultValue;\n }\n }\n \n /**\n * Get an optional string associated with a key. It returns an empty string\n * if there is no such key. If the value is not a string and is not null,\n * then it is converted to a string.\n *\n * @param key\n * A key string.\n * @return A string which is the value.\n */\n public String optString(String key) {\n return this.optString(key, \"\");\n }\n\n /**\n * Get an optional string associated with a key. It returns the defaultValue\n * if there is no such key.\n *\n * @param key\n * A key string.\n * @param defaultValue\n * The default.\n * @return A string which is the value.\n */\n public String optString(String key, String defaultValue) {\n Object object = this.opt(key);\n return NULL.equals(object) ? defaultValue : object.toString();\n }\n\n /**\n * Populates the internal map of the JSONObject with the bean properties. The\n * bean can not be recursive.\n *\n * @see JSONObject#JSONObject(Object)\n *\n * @param bean\n * the bean\n */\n private void populateMap(Object bean) {\n Class<?> klass = bean.getClass();\n\n // If klass is a System class then set includeSuperClass to false.\n\n boolean includeSuperClass = klass.getClassLoader() != null;\n\n Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();\n for (final Method method : methods) {\n final int modifiers = method.getModifiers();\n if (Modifier.isPublic(modifiers)\n && !Modifier.isStatic(modifiers)\n && method.getParameterTypes().length == 0\n && !method.isBridge()\n && method.getReturnType() != Void.TYPE\n && isValidMethodName(method.getName())) {\n final String key = getKeyNameFromMethod(method);\n if (key != null && !key.isEmpty()) {\n try {\n final Object result = method.invoke(bean);\n if (result != null) {\n this.map.put(key, wrap(result));\n // we don't use the result anywhere outside of wrap\n // if it's a resource we should be sure to close it\n // after calling toString\n if (result instanceof Closeable) {\n try {\n ((Closeable) result).close();\n } catch (IOException ignore) {\n }\n }\n }\n } catch (IllegalAccessException ignore) {\n } catch (IllegalArgumentException ignore) {\n } catch (InvocationTargetException ignore) {\n }\n }\n }\n }\n }\n\n private static boolean isValidMethodName(String name) {\n return !\"getClass\".equals(name) && !\"getDeclaringClass\".equals(name);\n }\n\n private static String getKeyNameFromMethod(Method method) {\n final int ignoreDepth = getAnnotationDepth(method, JSONPropertyIgnore.class);\n if (ignoreDepth > 0) {\n final int forcedNameDepth = getAnnotationDepth(method, JSONPropertyName.class);\n if (forcedNameDepth < 0 || ignoreDepth <= forcedNameDepth) {\n // the hierarchy asked to ignore, and the nearest name override\n // was higher or non-existent\n return null;\n }\n }\n JSONPropertyName annotation = getAnnotation(method, JSONPropertyName.class);\n if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) {\n return annotation.value();\n }\n String key;\n final String name = method.getName();\n if (name.startsWith(\"get\") && name.length() > 3) {\n key = name.substring(3);\n } else if (name.startsWith(\"is\") && name.length() > 2) {\n key = name.substring(2);\n } else {\n return null;\n }\n // if the first letter in the key is not uppercase, then skip.\n // This is to maintain backwards compatibility before PR406\n // (https://github.com/stleary/JSON-java/pull/406/)\n if (Character.isLowerCase(key.charAt(0))) {\n return null;\n }\n if (key.length() == 1) {\n key = key.toLowerCase(Locale.ROOT);\n } else if (!Character.isUpperCase(key.charAt(1))) {\n key = key.substring(0, 1).toLowerCase(Locale.ROOT) + key.substring(1);\n }\n return key;\n }\n\n /**\n * Searches the class hierarchy to see if the method or it's super\n * implementations and interfaces has the annotation.\n *\n * @param <A>\n * type of the annotation\n *\n * @param m\n * method to check\n * @param annotationClass\n * annotation to look for\n * @return the {@link Annotation} if the annotation exists on the current method\n * or one of it's super class definitions\n */\n private static <A extends Annotation> A getAnnotation(final Method m, final Class<A> annotationClass) {\n // if we have invalid data the result is null\n if (m == null || annotationClass == null) {\n return null;\n }\n\n if (m.isAnnotationPresent(annotationClass)) {\n return m.getAnnotation(annotationClass);\n }\n\n // if we've already reached the Object class, return null;\n Class<?> c = m.getDeclaringClass();\n if (c.getSuperclass() == null) {\n return null;\n }\n\n // check directly implemented interfaces for the method being checked\n for (Class<?> i : c.getInterfaces()) {\n try {\n Method im = i.getMethod(m.getName(), m.getParameterTypes());\n return getAnnotation(im, annotationClass);\n } catch (final SecurityException ex) {\n continue;\n } catch (final NoSuchMethodException ex) {\n continue;\n }\n }\n\n try {\n return getAnnotation(\n c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),\n annotationClass);\n } catch (final SecurityException ex) {\n return null;\n } catch (final NoSuchMethodException ex) {\n return null;\n }\n }\n\n /**\n * Searches the class hierarchy to see if the method or it's super\n * implementations and interfaces has the annotation. Returns the depth of the\n * annotation in the hierarchy.\n *\n * @param <A>\n * type of the annotation\n *\n * @param m\n * method to check\n * @param annotationClass\n * annotation to look for\n * @return Depth of the annotation or -1 if the annotation is not on the method.\n */\n private static int getAnnotationDepth(final Method m, final Class<? extends Annotation> annotationClass) {\n // if we have invalid data the result is -1\n if (m == null || annotationClass == null) {\n return -1;\n }\n\n if (m.isAnnotationPresent(annotationClass)) {\n return 1;\n }\n\n // if we've already reached the Object class, return -1;\n Class<?> c = m.getDeclaringClass();\n if (c.getSuperclass() == null) {\n return -1;\n }\n\n // check directly implemented interfaces for the method being checked\n for (Class<?> i : c.getInterfaces()) {\n try {\n Method im = i.getMethod(m.getName(), m.getParameterTypes());\n int d = getAnnotationDepth(im, annotationClass);\n if (d > 0) {\n // since the annotation was on the interface, add 1\n return d + 1;\n }\n } catch (final SecurityException ex) {\n continue;\n } catch (final NoSuchMethodException ex) {\n continue;\n }\n }\n\n try {\n int d = getAnnotationDepth(\n c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),\n annotationClass);\n if (d > 0) {\n // since the annotation was on the superclass, add 1\n return d + 1;\n }\n return -1;\n } catch (final SecurityException ex) {\n return -1;\n } catch (final NoSuchMethodException ex) {\n return -1;\n }\n }\n\n /**\n * Put a key/boolean pair in the JSONObject.\n *\n * @param key\n * A key string.\n * @param value\n * A boolean which is the value.\n * @return this.\n * @throws JSONException\n * If the value is non-finite number.\n * @throws NullPointerException\n * If the key is <code>null</code>.\n */\n public JSONObject put(String key, boolean value) throws JSONException {\n return this.put(key, value ? Boolean.TRUE : Boolean.FALSE);\n }\n\n /**\n * Put a key/value pair in the JSONObject, where the value will be a\n * JSONArray which is produced from a Collection.\n *\n * @param key\n * A key string.\n * @param value\n * A Collection value.\n * @return this.\n * @throws JSONException\n * If the value is non-finite number.\n * @throws NullPointerException\n * If the key is <code>null</code>.\n */\n public JSONObject put(String key, Collection<?> value) throws JSONException {\n return this.put(key, new JSONArray(value));\n }\n\n /**\n * Put a key/double pair in the JSONObject.\n *\n * @param key\n * A key string.\n * @param value\n * A double which is the value.\n * @return this.\n * @throws JSONException\n * If the value is non-finite number.\n * @throws NullPointerException\n * If the key is <code>null</code>.\n */\n public JSONObject put(String key, double value) throws JSONException {\n return this.put(key, Double.valueOf(value));\n }\n \n /**\n * Put a key/float pair in the JSONObject.\n *\n * @param key\n * A key string.\n * @param value\n * A float which is the value.\n * @return this.\n * @throws JSONException\n * If the value is non-finite number.\n * @throws NullPointerException\n * If the key is <code>null</code>.\n */\n public JSONObject put(String key, float value) throws JSONException {\n return this.put(key, Float.valueOf(value));\n }\n\n /**\n * Put a key/int pair in the JSONObject.\n *\n * @param key\n * A key string.\n * @param value\n * An int which is the value.\n * @return this.\n * @throws JSONException\n * If the value is non-finite number.\n * @throws NullPointerException\n * If the key is <code>null</code>.\n */\n public JSONObject put(String key, int value) throws JSONException {\n return this.put(key, Integer.valueOf(value));\n }\n\n /**\n * Put a key/long pair in the JSONObject.\n *\n * @param key\n * A key string.\n * @param value\n * A long which is the value.\n * @return this.\n * @throws JSONException\n * If the value is non-finite number.\n * @throws NullPointerException\n * If the key is <code>null</code>.\n */\n public JSONObject put(String key, long value) throws JSONException {\n return this.put(key, Long.valueOf(value));\n }\n\n /**\n * Put a key/value pair in the JSONObject, where the value will be a\n * JSONObject which is produced from a Map.\n *\n * @param key\n * A key string.\n * @param value\n * A Map value.\n * @return this.\n * @throws JSONException\n * If the value is non-finite number.\n * @throws NullPointerException\n * If the key is <code>null</code>.\n */\n public JSONObject put(String key, Map<?, ?> value) throws JSONException {\n return this.put(key, new JSONObject(value));\n }\n\n /**\n * Put a key/value pair in the JSONObject. If the value is <code>null</code>, then the\n * key will be removed from the JSONObject if it is present.\n *\n * @param key\n * A key string.\n * @param value\n * An object which is the value. It should be of one of these\n * types: Boolean, Double, Integer, JSONArray, JSONObject, Long,\n * String, or the JSONObject.NULL object.\n * @return this.\n * @throws JSONException\n * If the value is non-finite number.\n * @throws NullPointerException\n * If the key is <code>null</code>.\n */\n public JSONObject put(String key, Object value) throws JSONException {\n if (key == null) {\n throw new NullPointerException(\"Null key.\");\n }\n if (value != null) {\n testValidity(value);\n this.map.put(key, value);\n } else {\n this.remove(key);\n }\n return this;\n }\n\n public void putAll(JSONObject other) {\n this.map.putAll(other.map);\n }\n\n /**\n * Put a key/value pair in the JSONObject, but only if the key and the value\n * are both non-null, and only if there is not already a member with that\n * name.\n *\n * @param key\n * key to insert into\n * @param value\n * value to insert\n * @return this.\n * @throws JSONException\n * if the key is a duplicate\n */\n public JSONObject putOnce(String key, Object value) throws JSONException {\n if (key != null && value != null) {\n if (this.opt(key) != null) {\n throw new JSONException(\"Duplicate key \\\"\" + key + \"\\\"\");\n }\n return this.put(key, value);\n }\n return this;\n }\n\n /**\n * Put a key/value pair in the JSONObject, but only if the key and the value\n * are both non-null.\n *\n * @param key\n * A key string.\n * @param value\n * An object which is the value. It should be of one of these\n * types: Boolean, Double, Integer, JSONArray, JSONObject, Long,\n * String, or the JSONObject.NULL object.\n * @return this.\n * @throws JSONException\n * If the value is a non-finite number.\n */\n public JSONObject putOpt(String key, Object value) throws JSONException {\n if (key != null && value != null) {\n return this.put(key, value);\n }\n return this;\n }\n\n /**\n * Creates a JSONPointer using an initialization string and tries to \n * match it to an item within this JSONObject. For example, given a\n * JSONObject initialized with this document:\n * <pre>\n * {\n * \"a\":{\"b\":\"c\"}\n * }\n * </pre>\n * and this JSONPointer string: \n * <pre>\n * \"/a/b\"\n * </pre>\n * Then this method will return the String \"c\".\n * A JSONPointerException may be thrown from code called by this method.\n * \n * @param jsonPointer string that can be used to create a JSONPointer\n * @return the item matched by the JSONPointer, otherwise null\n */\n public Object query(String jsonPointer) {\n return query(new JSONPointer(jsonPointer));\n }\n /**\n * Uses a user initialized JSONPointer and tries to \n * match it to an item within this JSONObject. For example, given a\n * JSONObject initialized with this document:\n * <pre>\n * {\n * \"a\":{\"b\":\"c\"}\n * }\n * </pre>\n * and this JSONPointer: \n * <pre>\n * \"/a/b\"\n * </pre>\n * Then this method will return the String \"c\".\n * A JSONPointerException may be thrown from code called by this method.\n * \n * @param jsonPointer string that can be used to create a JSONPointer\n * @return the item matched by the JSONPointer, otherwise null\n */\n public Object query(JSONPointer jsonPointer) {\n return jsonPointer.queryFrom(this);\n }\n \n /**\n * Queries and returns a value from this object using {@code jsonPointer}, or\n * returns null if the query fails due to a missing key.\n * \n * @param jsonPointer the string representation of the JSON pointer\n * @return the queried value or {@code null}\n * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax\n */\n public Object optQuery(String jsonPointer) {\n \treturn optQuery(new JSONPointer(jsonPointer));\n }\n \n /**\n * Queries and returns a value from this object using {@code jsonPointer}, or\n * returns null if the query fails due to a missing key.\n * \n * @param jsonPointer The JSON pointer\n * @return the queried value or {@code null}\n * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax\n */\n public Object optQuery(JSONPointer jsonPointer) {\n try {\n return jsonPointer.queryFrom(this);\n } catch (JSONPointerException e) {\n return null;\n }\n }\n\n /**\n * Produce a string in double quotes with backslash sequences in all the\n * right places. A backslash will be inserted within </, producing\n * <\\/, allowing JSON text to be delivered in HTML. In JSON text, a\n * string cannot contain a control character or an unescaped quote or\n * backslash.\n *\n * @param string\n * A String\n * @return A String correctly formatted for insertion in a JSON text.\n */\n public static String quote(String string) {\n StringWriter sw = new StringWriter();\n synchronized (sw.getBuffer()) {\n try {\n return quote(string, sw).toString();\n } catch (IOException ignored) {\n // will never happen - we are writing to a string writer\n return \"\";\n }\n }\n }\n\n public static Writer quote(String string, Writer w) throws IOException {\n if (string == null || string.isEmpty()) {\n w.write(\"\\\"\\\"\");\n return w;\n }\n\n char b;\n char c = 0;\n String hhhh;\n int i;\n int len = string.length();\n\n w.write('\"');\n for (i = 0; i < len; i += 1) {\n b = c;\n c = string.charAt(i);\n switch (c) {\n case '\\\\':\n case '\"':\n w.write('\\\\');\n w.write(c);\n break;\n case '/':\n if (b == '<') {\n w.write('\\\\');\n }\n w.write(c);\n break;\n case '\\b':\n w.write(\"\\\\b\");\n break;\n case '\\t':\n w.write(\"\\\\t\");\n break;\n case '\\n':\n w.write(\"\\\\n\");\n break;\n case '\\f':\n w.write(\"\\\\f\");\n break;\n case '\\r':\n w.write(\"\\\\r\");\n break;\n default:\n if (c < ' ' || (c >= '\\u0080' && c < '\\u00a0')\n || (c >= '\\u2000' && c < '\\u2100')) {\n w.write(\"\\\\u\");\n hhhh = Integer.toHexString(c);\n w.write(\"0000\", 0, 4 - hhhh.length());\n w.write(hhhh);\n } else {\n w.write(c);\n }\n }\n }\n w.write('\"');\n return w;\n }\n\n /**\n * Remove a name and its value, if present.\n *\n * @param key\n * The name to be removed.\n * @return The value that was associated with the name, or null if there was\n * no value.\n */\n public Object remove(String key) {\n return this.map.remove(key);\n }\n\n /**\n * Determine if two JSONObjects are similar.\n * They must contain the same set of names which must be associated with\n * similar values.\n *\n * @param other The other JSONObject\n * @return true if they are equal\n */\n public boolean similar(Object other) {\n try {\n if (!(other instanceof JSONObject)) {\n return false;\n }\n if (!this.keySet().equals(((JSONObject)other).keySet())) {\n return false;\n }\n for (final Entry<String,?> entry : this.entrySet()) {\n String name = entry.getKey();\n Object valueThis = entry.getValue();\n Object valueOther = ((JSONObject)other).get(name);\n if(valueThis == valueOther) {\n \tcontinue;\n }\n if(valueThis == null) {\n \treturn false;\n }\n if (valueThis instanceof JSONObject) {\n if (!((JSONObject)valueThis).similar(valueOther)) {\n return false;\n }\n } else if (valueThis instanceof JSONArray) {\n if (!((JSONArray)valueThis).similar(valueOther)) {\n return false;\n }\n } else if (!valueThis.equals(valueOther)) {\n return false;\n }\n }\n return true;\n } catch (Throwable exception) {\n return false;\n }\n }\n \n /**\n * Tests if the value should be tried as a decimal. It makes no test if there are actual digits.\n * \n * @param val value to test\n * @return true if the string is \"-0\" or if it contains '.', 'e', or 'E', false otherwise.\n */\n protected static boolean isDecimalNotation(final String val) {\n return val.indexOf('.') > -1 || val.indexOf('e') > -1\n || val.indexOf('E') > -1 || \"-0\".equals(val);\n }\n \n /**\n * Converts a string to a number using the narrowest possible type. Possible \n * returns for this function are BigDecimal, Double, BigInteger, Long, and Integer.\n * When a Double is returned, it should always be a valid Double and not NaN or +-infinity.\n * \n * @param val value to convert\n * @return Number representation of the value.\n * @throws NumberFormatException thrown if the value is not a valid number. A public\n * caller should catch this and wrap it in a {@link JSONException} if applicable.\n */\n protected static Number stringToNumber(final String val) throws NumberFormatException {\n char initial = val.charAt(0);\n if ((initial >= '0' && initial <= '9') || initial == '-') {\n // decimal representation\n if (isDecimalNotation(val)) {\n // quick dirty way to see if we need a BigDecimal instead of a Double\n // this only handles some cases of overflow or underflow\n if (val.length()>14) {\n return new BigDecimal(val);\n }\n final Double d = Double.valueOf(val);\n if (d.isInfinite() || d.isNaN()) {\n // if we can't parse it as a double, go up to BigDecimal\n // this is probably due to underflow like 4.32e-678\n // or overflow like 4.65e5324. The size of the string is small\n // but can't be held in a Double.\n return new BigDecimal(val);\n }\n return d;\n }\n // integer representation.\n // This will narrow any values to the smallest reasonable Object representation\n // (Integer, Long, or BigInteger)\n \n // string version\n // The compare string length method reduces GC,\n // but leads to smaller integers being placed in larger wrappers even though not\n // needed. i.e. 1,000,000,000 -> Long even though it's an Integer\n // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long\n //if(val.length()<=9){\n // return Integer.valueOf(val);\n //}\n //if(val.length()<=18){\n // return Long.valueOf(val);\n //}\n //return new BigInteger(val);\n \n // BigInteger version: We use a similar bitLength compare as\n // BigInteger#intValueExact uses. Increases GC, but objects hold\n // only what they need. i.e. Less runtime overhead if the value is\n // long lived. Which is the better tradeoff? This is closer to what's\n // in stringToValue.\n BigInteger bi = new BigInteger(val);\n if(bi.bitLength()<=31){\n return Integer.valueOf(bi.intValue());\n }\n if(bi.bitLength()<=63){\n return Long.valueOf(bi.longValue());\n }\n return bi;\n }\n throw new NumberFormatException(\"val [\"+val+\"] is not a valid number.\");\n }\n\n /**\n * Try to convert a string into a number, boolean, or null. If the string\n * can't be converted, return the string.\n *\n * @param string\n * A String. can not be null.\n * @return A simple JSON value.\n * @throws NullPointerException\n * Thrown if the string is null.\n */\n // Changes to this method must be copied to the corresponding method in\n // the XML class to keep full support for Android\n public static Object stringToValue(String string) {\n if (\"\".equals(string)) {\n return string;\n }\n\n // check JSON key words true/false/null\n if (\"true\".equalsIgnoreCase(string)) {\n return Boolean.TRUE;\n }\n if (\"false\".equalsIgnoreCase(string)) {\n return Boolean.FALSE;\n }\n if (\"null\".equalsIgnoreCase(string)) {\n return JSONObject.NULL;\n }\n\n /*\n * If it might be a number, try converting it. If a number cannot be\n * produced, then the value will just be a string.\n */\n\n char initial = string.charAt(0);\n if ((initial >= '0' && initial <= '9') || initial == '-') {\n try {\n // if we want full Big Number support the contents of this\n // `try` block can be replaced with:\n // return stringToNumber(string);\n if (isDecimalNotation(string)) {\n Double d = Double.valueOf(string);\n if (!d.isInfinite() && !d.isNaN()) {\n return d;\n }\n } else {\n Long myLong = Long.valueOf(string);\n if (string.equals(myLong.toString())) {\n if (myLong.longValue() == myLong.intValue()) {\n return Integer.valueOf(myLong.intValue());\n }\n return myLong;\n }\n }\n } catch (Exception ignore) {\n }\n }\n return string;\n }\n\n /**\n * Throw an exception if the object is a NaN or infinite number.\n *\n * @param o\n * The object to test.\n * @throws JSONException\n * If o is a non-finite number.\n */\n public static void testValidity(Object o) throws JSONException {\n if (o != null) {\n if (o instanceof Double) {\n if (((Double) o).isInfinite() || ((Double) o).isNaN()) {\n throw new JSONException(\n \"JSON does not allow non-finite numbers.\");\n }\n } else if (o instanceof Float) {\n if (((Float) o).isInfinite() || ((Float) o).isNaN()) {\n throw new JSONException(\n \"JSON does not allow non-finite numbers.\");\n }\n }\n }\n }\n\n /**\n * Produce a JSONArray containing the values of the members of this\n * JSONObject.\n *\n * @param names\n * A JSONArray containing a list of key strings. This determines\n * the sequence of the values in the result.\n * @return A JSONArray of values.\n * @throws JSONException\n * If any of the values are non-finite numbers.\n */\n public JSONArray toJSONArray(JSONArray names) throws JSONException {\n if (names == null || names.isEmpty()) {\n return null;\n }\n JSONArray ja = new JSONArray();\n for (int i = 0; i < names.length(); i += 1) {\n ja.put(this.opt(names.getString(i)));\n }\n return ja;\n }\n\n /**\n * Make a JSON text of this JSONObject. For compactness, no whitespace is\n * added. If this would not result in a syntactically correct JSON text,\n * then null will be returned instead.\n * <p><b>\n * Warning: This method assumes that the data structure is acyclical.\n * </b>\n * \n * @return a printable, displayable, portable, transmittable representation\n * of the object, beginning with <code>{</code> <small>(left\n * brace)</small> and ending with <code>}</code> <small>(right\n * brace)</small>.\n */\n @Override\n public String toString() {\n try {\n return this.toString(0);\n } catch (Exception e) {\n return null;\n }\n }\n\n /**\n * Make a pretty-printed JSON text of this JSONObject.\n * \n * <p>If <code>indentFactor > 0</code> and the {@link JSONObject}\n * has only one key, then the object will be output on a single line:\n * <pre>{@code {\"key\": 1}}</pre>\n * \n * <p>If an object has 2 or more keys, then it will be output across\n * multiple lines: <code><pre>{\n * \"key1\": 1,\n * \"key2\": \"value 2\",\n * \"key3\": 3\n * }</pre></code>\n * <p><b>\n * Warning: This method assumes that the data structure is acyclical.\n * </b>\n *\n * @param indentFactor\n * The number of spaces to add to each level of indentation.\n * @return a printable, displayable, portable, transmittable representation\n * of the object, beginning with <code>{</code> <small>(left\n * brace)</small> and ending with <code>}</code> <small>(right\n * brace)</small>.\n * @throws JSONException\n * If the object contains an invalid number.\n */\n public String toString(int indentFactor) throws JSONException {\n StringWriter w = new StringWriter();\n synchronized (w.getBuffer()) {\n return this.write(w, indentFactor, 0).toString();\n }\n }\n\n /**\n * Make a JSON text of an Object value. If the object has an\n * value.toJSONString() method, then that method will be used to produce the\n * JSON text. The method is required to produce a strictly conforming text.\n * If the object does not contain a toJSONString method (which is the most\n * common case), then a text will be produced by other means. If the value\n * is an array or Collection, then a JSONArray will be made from it and its\n * toJSONString method will be called. If the value is a MAP, then a\n * JSONObject will be made from it and its toJSONString method will be\n * called. Otherwise, the value's toString method will be called, and the\n * result will be quoted.\n *\n * <p>\n * Warning: This method assumes that the data structure is acyclical.\n *\n * @param value\n * The value to be serialized.\n * @return a printable, displayable, transmittable representation of the\n * object, beginning with <code>{</code> <small>(left\n * brace)</small> and ending with <code>}</code> <small>(right\n * brace)</small>.\n * @throws JSONException\n * If the value is or contains an invalid number.\n */\n public static String valueToString(Object value) throws JSONException {\n \t// moves the implementation to JSONWriter as:\n \t// 1. It makes more sense to be part of the writer class\n \t// 2. For Android support this method is not available. By implementing it in the Writer\n \t// Android users can use the writer with the built in Android JSONObject implementation.\n return JSONWriter.valueToString(value);\n }\n\n /**\n * Wrap an object, if necessary. If the object is <code>null</code>, return the NULL\n * object. If it is an array or collection, wrap it in a JSONArray. If it is\n * a map, wrap it in a JSONObject. If it is a standard property (Double,\n * String, et al) then it is already wrapped. Otherwise, if it comes from\n * one of the java packages, turn it into a string. And if it doesn't, try\n * to wrap it in a JSONObject. If the wrapping fails, then null is returned.\n *\n * @param object\n * The object to wrap\n * @return The wrapped value\n */\n public static Object wrap(Object object) {\n try {\n if (object == null) {\n return NULL;\n }\n if (object instanceof JSONObject || object instanceof JSONArray\n || NULL.equals(object) || object instanceof JSONString\n || object instanceof Byte || object instanceof Character\n || object instanceof Short || object instanceof Integer\n || object instanceof Long || object instanceof Boolean\n || object instanceof Float || object instanceof Double\n || object instanceof String || object instanceof BigInteger\n || object instanceof BigDecimal || object instanceof Enum) {\n return object;\n }\n\n if (object instanceof Collection) {\n Collection<?> coll = (Collection<?>) object;\n return new JSONArray(coll);\n }\n if (object.getClass().isArray()) {\n return new JSONArray(object);\n }\n if (object instanceof Map) {\n Map<?, ?> map = (Map<?, ?>) object;\n return new JSONObject(map);\n }\n Package objectPackage = object.getClass().getPackage();\n String objectPackageName = objectPackage != null ? objectPackage\n .getName() : \"\";\n if (objectPackageName.startsWith(\"java.\")\n || objectPackageName.startsWith(\"javax.\")\n || object.getClass().getClassLoader() == null) {\n return object.toString();\n }\n return new JSONObject(object);\n } catch (Exception exception) {\n return null;\n }\n }\n\n /**\n * Write the contents of the JSONObject as JSON text to a writer. For\n * compactness, no whitespace is added.\n * <p><b>\n * Warning: This method assumes that the data structure is acyclical.\n * </b>\n * \n * @return The writer.\n * @throws JSONException\n */\n public Writer write(Writer writer) throws JSONException {\n return this.write(writer, 0, 0);\n }\n\n static final Writer writeValue(Writer writer, Object value,\n int indentFactor, int indent) throws JSONException, IOException {\n if (value == null || value.equals(null)) {\n writer.write(\"null\");\n } else if (value instanceof JSONString) {\n Object o;\n try {\n o = ((JSONString) value).toJSONString();\n } catch (Exception e) {\n throw new JSONException(e);\n }\n writer.write(o != null ? o.toString() : quote(value.toString()));\n } else if (value instanceof Number) {\n // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary\n final String numberAsString = numberToString((Number) value);\n if(NUMBER_PATTERN.matcher(numberAsString).matches()) {\n writer.write(numberAsString);\n } else {\n // The Number value is not a valid JSON number.\n // Instead we will quote it as a string\n quote(numberAsString, writer);\n }\n } else if (value instanceof Boolean) {\n writer.write(value.toString());\n } else if (value instanceof Enum<?>) {\n writer.write(quote(((Enum<?>)value).name()));\n } else if (value instanceof JSONObject) {\n ((JSONObject) value).write(writer, indentFactor, indent);\n } else if (value instanceof JSONArray) {\n ((JSONArray) value).write(writer, indentFactor, indent);\n } else if (value instanceof Map) {\n Map<?, ?> map = (Map<?, ?>) value;\n new JSONObject(map).write(writer, indentFactor, indent);\n } else if (value instanceof Collection) {\n Collection<?> coll = (Collection<?>) value;\n new JSONArray(coll).write(writer, indentFactor, indent);\n } else if (value.getClass().isArray()) {\n new JSONArray(value).write(writer, indentFactor, indent);\n } else {\n quote(value.toString(), writer);\n }\n return writer;\n }\n\n static final void indent(Writer writer, int indent) throws IOException {\n for (int i = 0; i < indent; i += 1) {\n writer.write(' ');\n }\n }\n\n /**\n * Write the contents of the JSONObject as JSON text to a writer.\n * \n * <p>If <code>indentFactor > 0</code> and the {@link JSONObject}\n * has only one key, then the object will be output on a single line:\n * <pre>{@code {\"key\": 1}}</pre>\n * \n * <p>If an object has 2 or more keys, then it will be output across\n * multiple lines: <code><pre>{\n * \"key1\": 1,\n * \"key2\": \"value 2\",\n * \"key3\": 3\n * }</pre></code>\n * <p><b>\n * Warning: This method assumes that the data structure is acyclical.\n * </b>\n *\n * @param writer\n * Writes the serialized JSON\n * @param indentFactor\n * The number of spaces to add to each level of indentation.\n * @param indent\n * The indentation of the top level.\n * @return The writer.\n * @throws JSONException\n */\n public Writer write(Writer writer, int indentFactor, int indent)\n throws JSONException {\n try {\n boolean needsComma = false;\n final int length = this.length();\n writer.write('{');\n\n if (length == 1) {\n \tfinal Entry<String,?> entry = this.entrySet().iterator().next();\n final String key = entry.getKey();\n writer.write(quote(key));\n writer.write(':');\n if (indentFactor > 0) {\n writer.write(' ');\n }\n try{\n writeValue(writer, entry.getValue(), indentFactor, indent);\n } catch (Exception e) {\n throw new JSONException(\"Unable to write JSONObject value for key: \" + key, e);\n }\n } else if (length != 0) {\n final int newIndent = indent + indentFactor;\n for (final Entry<String,?> entry : this.entrySet()) {\n if (needsComma) {\n writer.write(',');\n }\n if (indentFactor > 0) {\n writer.write('\\n');\n }\n indent(writer, newIndent);\n final String key = entry.getKey();\n writer.write(quote(key));\n writer.write(':');\n if (indentFactor > 0) {\n writer.write(' ');\n }\n try {\n writeValue(writer, entry.getValue(), indentFactor, newIndent);\n } catch (Exception e) {\n throw new JSONException(\"Unable to write JSONObject value for key: \" + key, e);\n }\n needsComma = true;\n }\n if (indentFactor > 0) {\n writer.write('\\n');\n }\n indent(writer, indent);\n }\n writer.write('}');\n return writer;\n } catch (IOException exception) {\n throw new JSONException(exception);\n }\n }\n\n /**\n * Returns a java.util.Map containing all of the entries in this object.\n * If an entry in the object is a JSONArray or JSONObject it will also\n * be converted.\n * <p>\n * Warning: This method assumes that the data structure is acyclical.\n *\n * @return a java.util.Map containing the entries of this object\n */\n public Map<String, Object> toMap() {\n Map<String, Object> results = new HashMap<String, Object>();\n for (Entry<String, Object> entry : this.entrySet()) {\n Object value;\n if (entry.getValue() == null || NULL.equals(entry.getValue())) {\n value = null;\n } else if (entry.getValue() instanceof JSONObject) {\n value = ((JSONObject) entry.getValue()).toMap();\n } else if (entry.getValue() instanceof JSONArray) {\n value = ((JSONArray) entry.getValue()).toList();\n } else {\n value = entry.getValue();\n }\n results.put(entry.getKey(), value);\n }\n return results;\n }\n \n /**\n * Create a new JSONException in a common format for incorrect conversions.\n * @param key name of the key\n * @param valueType the type of value being coerced to\n * @param cause optional cause of the coercion failure\n * @return JSONException that can be thrown.\n */\n private static JSONException wrongValueFormatException(\n String key,\n String valueType,\n Throwable cause) {\n return new JSONException(\n \"JSONObject[\" + quote(key) + \"] is not a \" + valueType + \".\"\n , cause);\n }\n \n /**\n * Create a new JSONException in a common format for incorrect conversions.\n * @param key name of the key\n * @param valueType the type of value being coerced to\n * @param cause optional cause of the coercion failure\n * @return JSONException that can be thrown.\n */\n private static JSONException wrongValueFormatException(\n String key,\n String valueType,\n Object value,\n Throwable cause) {\n return new JSONException(\n \"JSONObject[\" + quote(key) + \"] is not a \" + valueType + \" (\" + value + \").\"\n , cause);\n }\n}",
"public class DAO {\n\n public final static com.fasterxml.jackson.core.JsonFactory jsonFactory = new com.fasterxml.jackson.core.JsonFactory();\n public final static com.fasterxml.jackson.databind.ObjectMapper jsonMapper = new com.fasterxml.jackson.databind.ObjectMapper(DAO.jsonFactory);\n public final static com.fasterxml.jackson.core.type.TypeReference<HashMap<String,Object>> jsonTypeRef = new com.fasterxml.jackson.core.type.TypeReference<HashMap<String,Object>>() {};\n\n private static Logger logger = LoggerFactory.getLogger(DAO.class);\n \n public final static String MESSAGE_DUMP_FILE_PREFIX = \"messages_\";\n public final static String ACCOUNT_DUMP_FILE_PREFIX = \"accounts_\";\n public final static String USER_DUMP_FILE_PREFIX = \"users_\";\n public final static String ACCESS_DUMP_FILE_PREFIX = \"access_\";\n public final static String FOLLOWERS_DUMP_FILE_PREFIX = \"followers_\";\n public final static String FOLLOWING_DUMP_FILE_PREFIX = \"following_\";\n private static final String IMPORT_PROFILE_FILE_PREFIX = \"profile_\";\n\n public static boolean writeDump;\n\n public final static int CACHE_MAXSIZE = 10000;\n public final static int EXIST_MAXSIZE = 4000000;\n\n public static File data_dir, conf_dir, bin_dir, html_dir;\n private static File external_data, assets, dictionaries;\n public static Settings public_settings, private_settings;\n private static Path message_dump_dir, account_dump_dir, import_profile_dump_dir;\n public static Path push_cache_dir;\n public static JsonRepository message_dump;\n private static JsonRepository account_dump;\n private static JsonRepository import_profile_dump;\n public static JsonDataset user_dump, followers_dump, following_dump;\n public static AccessTracker access;\n private static File schema_dir, conv_schema_dir;\n public static ElasticsearchClient elasticsearch_client;\n //private static Node elasticsearch_node;\n //private static Client elasticsearch_client;\n public static UserFactory users;\n private static AccountFactory accounts;\n public static MessageFactory messages;\n public static MessageFactory messages_hour;\n public static MessageFactory messages_day;\n public static MessageFactory messages_week;\n public static QueryFactory queries;\n private static ImportProfileFactory importProfiles;\n private static Map<String, String> config = new HashMap<>();\n public static GeoNames geoNames = null;\n public static Peers peers = new Peers();\n public static OutgoingMessageBuffer outgoingMessages = new OutgoingMessageBuffer();\n\n // AAA Schema for server usage\n public static JsonTray authentication;\n public static JsonTray authorization;\n public static JsonTray accounting;\n public static UserRoles userRoles;\n public static JsonTray passwordreset;\n public static Map<String, Accounting> accounting_temporary = new HashMap<>();\n public static JsonFile login_keys;\n public static TimelineCache timelineCache;\n\n public static MQTTPublisher mqttPublisher = null;\n public static boolean streamEnabled = false;\n public static List<String> randomTerms = new ArrayList<>();\n\n public static enum IndexName {\n \tmessages_hour(\"messages.json\"), messages_day(\"messages.json\"), messages_week(\"messages.json\"), messages, queries, users, accounts, import_profiles;\n private String schemaFileName;\n \tprivate IndexName() {\n \t schemaFileName = this.name() + \".json\";\n \t}\n \tprivate IndexName(String filename) {\n schemaFileName = filename;\n }\n \tpublic String getSchemaFilename() {\n \t return this.schemaFileName;\n \t}\n }\n\n /**\n * initialize the DAO\n * @param configMap\n * @param dataPath the path to the data directory\n */\n public static void init(Map<String, String> configMap, Path dataPath) throws Exception{\n\n log(\"initializing loklak DAO\");\n\n config = configMap;\n data_dir = dataPath.toFile();\n conf_dir = new File(\"conf\");\n bin_dir = new File(\"bin\");\n html_dir = new File(\"html\");\n\n writeDump = DAO.getConfig(\"dump.write_enabled\", true);\n\n // initialize public and private keys\n\t\tpublic_settings = new Settings(new File(\"data/settings/public.settings.json\"));\n\t\tFile private_file = new File(\"data/settings/private.settings.json\");\n\t\tprivate_settings = new Settings(private_file);\n\t\tOS.protectPath(private_file.toPath());\n\n\t\tif(!private_settings.loadPrivateKey() || !public_settings.loadPublicKey()){\n \tlog(\"Can't load key pair. Creating new one\");\n\n \t// create new key pair\n \tKeyPairGenerator keyGen;\n\t\t\ttry {\n\t\t\t\tString algorithm = \"RSA\";\n\t\t\t\tkeyGen = KeyPairGenerator.getInstance(algorithm);\n\t\t\t\tkeyGen.initialize(2048);\n\t\t\t\tKeyPair keyPair = keyGen.genKeyPair();\n\t\t\t\tprivate_settings.setPrivateKey(keyPair.getPrivate(), algorithm);\n\t\t\t\tpublic_settings.setPublicKey(keyPair.getPublic(), algorithm);\n\t\t\t} catch (NoSuchAlgorithmException e) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tlog(\"Key creation finished. Peer hash: \" + public_settings.getPeerHashAlgorithm() + \" \" + public_settings.getPeerHash());\n }\n else{\n \tlog(\"Key pair loaded from file. Peer hash: \" + public_settings.getPeerHashAlgorithm() + \" \" + public_settings.getPeerHash());\n }\n\n File datadir = dataPath.toFile();\n // check if elasticsearch shall be accessed as external cluster\n String transport = configMap.get(\"elasticsearch_transport.enabled\");\n if (transport != null && \"true\".equals(transport)) {\n String cluster_name = configMap.get(\"elasticsearch_transport.cluster.name\");\n String transport_addresses_string = configMap.get(\"elasticsearch_transport.addresses\");\n if (transport_addresses_string != null && transport_addresses_string.length() > 0) {\n String[] transport_addresses = transport_addresses_string.split(\",\");\n elasticsearch_client = new ElasticsearchClient(transport_addresses, cluster_name);\n }\n } else {\n // use all config attributes with a key starting with \"elasticsearch.\" to set elasticsearch settings\n\n \tESLoggerFactory.setDefaultFactory(new Slf4jESLoggerFactory());\n org.elasticsearch.common.settings.Settings.Builder settings = org.elasticsearch.common.settings.Settings.builder();\n for (Map.Entry<String, String> entry: config.entrySet()) {\n String key = entry.getKey();\n if (key.startsWith(\"elasticsearch.\")) settings.put(key.substring(14), entry.getValue());\n }\n // patch the home path\n settings.put(\"path.home\", datadir.getAbsolutePath());\n settings.put(\"path.data\", datadir.getAbsolutePath());\n settings.build();\n\n // start elasticsearch\n elasticsearch_client = new ElasticsearchClient(settings);\n }\n\n // open AAA storage\n Path settings_dir = dataPath.resolve(\"settings\");\n settings_dir.toFile().mkdirs();\n Path authentication_path = settings_dir.resolve(\"authentication.json\");\n authentication = new JsonTray(authentication_path.toFile(), 10000);\n OS.protectPath(authentication_path);\n Path authorization_path = settings_dir.resolve(\"authorization.json\");\n authorization = new JsonTray(authorization_path.toFile(), 10000);\n OS.protectPath(authorization_path);\n Path passwordreset_path = settings_dir.resolve(\"passwordreset.json\");\n passwordreset = new JsonTray(passwordreset_path.toFile(), 10000);\n OS.protectPath(passwordreset_path);\n Path accounting_path = settings_dir.resolve(\"accounting.json\");\n accounting = new JsonTray(accounting_path.toFile(), 10000);\n OS.protectPath(accounting_path);\n Path login_keys_path = settings_dir.resolve(\"login-keys.json\");\n login_keys = new JsonFile(login_keys_path.toFile());\n OS.protectPath(login_keys_path);\n\n\n DAO.log(\"Initializing user roles\");\n\n Path userRoles_path = settings_dir.resolve(\"userRoles.json\");\n userRoles = new UserRoles(new JsonFile(userRoles_path.toFile()));\n OS.protectPath(userRoles_path);\n\n try{\n userRoles.loadUserRolesFromObject();\n DAO.log(\"Loaded user roles from file\");\n }catch (IllegalArgumentException e){\n DAO.log(\"Load default user roles\");\n userRoles.loadDefaultUserRoles();\n }\n\n // open index\n Path index_dir = dataPath.resolve(\"index\");\n if (index_dir.toFile().exists()) OS.protectPath(index_dir); // no other permissions to this path\n\n // define the index factories\n boolean noio = configMap.containsValue(\"noio\") && configMap.get(\"noio\").equals(\"true\");\n messages = new MessageFactory(noio ? null : elasticsearch_client, IndexName.messages.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);\n messages_hour = new MessageFactory(noio ? null : elasticsearch_client, IndexName.messages_hour.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);\n messages_day = new MessageFactory(noio ? null : elasticsearch_client, IndexName.messages_day.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);\n messages_week = new MessageFactory(noio ? null : elasticsearch_client, IndexName.messages_week.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);\n users = new UserFactory(noio ? null : elasticsearch_client, IndexName.users.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);\n accounts = new AccountFactory(noio ? null : elasticsearch_client, IndexName.accounts.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);\n queries = new QueryFactory(noio ? null : elasticsearch_client, IndexName.queries.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);\n importProfiles = new ImportProfileFactory(noio ? null : elasticsearch_client, IndexName.import_profiles.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);\n\n // create indices and set mapping (that shows how 'elastic' elasticsearch is: it's always good to define data types)\n File mappingsDir = new File(new File(conf_dir, \"elasticsearch\"), \"mappings\");\n int shards = Integer.parseInt(configMap.get(\"elasticsearch.index.number_of_shards\"));\n int replicas = Integer.parseInt(configMap.get(\"elasticsearch.index.number_of_replicas\"));\n for (IndexName index: IndexName.values()) {\n log(\"initializing index '\" + index.name() + \"'...\");\n \ttry {\n \t elasticsearch_client.createIndexIfNotExists(index.name(), shards, replicas);\n \t} catch (Throwable e) {\n \t\tDAO.severe(e);\n \t}\n try {\n elasticsearch_client.setMapping(index.name(), new File(mappingsDir, index.getSchemaFilename()));\n } catch (Throwable e) {\n \tDAO.severe(e);\n }\n }\n // elasticsearch will probably take some time until it is started up. We do some other stuff meanwhile..\n\n // create and document the data dump dir\n assets = new File(datadir, \"assets\").getAbsoluteFile();\n external_data = new File(datadir, \"external\");\n dictionaries = new File(external_data, \"dictionaries\");\n dictionaries.mkdirs();\n\n push_cache_dir = dataPath.resolve(\"pushcache\");\n push_cache_dir.toFile().mkdirs();\n\n // create message dump dir\n String message_dump_readme =\n \"This directory contains dump files for messages which arrived the platform.\\n\" +\n \"There are three subdirectories for dump files:\\n\" +\n \"- own: for messages received with this peer. There is one file for each month.\\n\" +\n \"- import: hand-over directory for message dumps to be imported. Drop dumps here and they are imported.\\n\" +\n \"- imported: dump files which had been processed from the import directory are moved here.\\n\" +\n \"You can import dump files from other peers by dropping them into the import directory.\\n\" +\n \"Each dump file must start with the prefix '\" + MESSAGE_DUMP_FILE_PREFIX + \"' to be recognized.\\n\";\n message_dump_dir = dataPath.resolve(\"dump\");\n message_dump = new JsonRepository(message_dump_dir.toFile(), MESSAGE_DUMP_FILE_PREFIX, message_dump_readme, JsonRepository.COMPRESSED_MODE, true, Runtime.getRuntime().availableProcessors());\n\n account_dump_dir = dataPath.resolve(\"accounts\");\n account_dump_dir.toFile().mkdirs();\n OS.protectPath(account_dump_dir); // no other permissions to this path\n account_dump = new JsonRepository(account_dump_dir.toFile(), ACCOUNT_DUMP_FILE_PREFIX, null, JsonRepository.REWRITABLE_MODE, false, Runtime.getRuntime().availableProcessors());\n\n File user_dump_dir = new File(datadir, \"accounts\");\n user_dump_dir.mkdirs();\n log(\"initializing user dump ...\");\n user_dump = new JsonDataset(\n user_dump_dir,USER_DUMP_FILE_PREFIX,\n new JsonDataset.Column[]{new JsonDataset.Column(\"id_str\", false), new JsonDataset.Column(\"screen_name\", true)},\n \"retrieval_date\", DateParser.PATTERN_ISO8601MILLIS,\n JsonRepository.REWRITABLE_MODE, false, Integer.MAX_VALUE);\n log(\"initializing followers dump ...\");\n followers_dump = new JsonDataset(\n user_dump_dir, FOLLOWERS_DUMP_FILE_PREFIX,\n new JsonDataset.Column[]{new JsonDataset.Column(\"screen_name\", true)},\n \"retrieval_date\", DateParser.PATTERN_ISO8601MILLIS,\n JsonRepository.REWRITABLE_MODE, false, Integer.MAX_VALUE);\n log(\"initializing following dump ...\");\n following_dump = new JsonDataset(\n user_dump_dir, FOLLOWING_DUMP_FILE_PREFIX,\n new JsonDataset.Column[]{new JsonDataset.Column(\"screen_name\", true)},\n \"retrieval_date\", DateParser.PATTERN_ISO8601MILLIS,\n JsonRepository.REWRITABLE_MODE, false, Integer.MAX_VALUE);\n\n Path log_dump_dir = dataPath.resolve(\"log\");\n log_dump_dir.toFile().mkdirs();\n OS.protectPath(log_dump_dir); // no other permissions to this path\n access = new AccessTracker(log_dump_dir.toFile(), ACCESS_DUMP_FILE_PREFIX, 60000, 3000);\n access.start(); // start monitor\n\n timelineCache = new TimelineCache(60000);\n\n import_profile_dump_dir = dataPath.resolve(\"import-profiles\");\n import_profile_dump = new JsonRepository(import_profile_dump_dir.toFile(), IMPORT_PROFILE_FILE_PREFIX, null, JsonRepository.COMPRESSED_MODE, false, Runtime.getRuntime().availableProcessors());\n\n // load schema folder\n conv_schema_dir = new File(\"conf/conversion\");\n schema_dir = new File(\"conf/schema\");\n\n // load dictionaries if they are embedded here\n // read the file allCountries.zip from http://download.geonames.org/export/dump/allCountries.zip\n //File allCountries = new File(dictionaries, \"allCountries.zip\");\n File cities1000 = new File(dictionaries, \"cities1000.zip\");\n if (!cities1000.exists()) {\n // download this file\n ClientConnection.download(\"http://download.geonames.org/export/dump/cities1000.zip\", cities1000);\n }\n\n if(cities1000.exists()){\n\t try{\n\t \tgeoNames = new GeoNames(cities1000, new File(conf_dir, \"iso3166.json\"), 1);\n\t }catch(IOException e){\n\t \tDAO.severe(e.getMessage());\n\t \tcities1000.delete();\n\t \tgeoNames = null;\n\t }\n \t}\n\n // Connect to MQTT message broker\n String mqttAddress = getConfig(\"stream.mqtt.address\", \"tcp://127.0.0.1:1883\");\n streamEnabled = getConfig(\"stream.enabled\", false);\n if (streamEnabled) {\n mqttPublisher = new MQTTPublisher(mqttAddress);\n }\n\n // finally wait for healthy status of elasticsearch shards\n ClusterHealthStatus required_status = ClusterHealthStatus.fromString(config.get(\"elasticsearch_requiredClusterHealthStatus\"));\n boolean ok;\n do {\n log(\"Waiting for elasticsearch \" + required_status.name() + \" status\");\n ok = elasticsearch_client.wait_ready(60000l, required_status);\n } while (!ok);\n /**\n do {\n log(\"Waiting for elasticsearch green status\");\n health = elasticsearch_client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet();\n } while (health.isTimedOut());\n **/\n log(\"elasticsearch has started up!\");\n\n // start the classifier\n new Thread(){\n public void run() {\n log(\"initializing the classifier...\");\n try {\n Classifier.init(10000, 1000);\n } catch (Throwable e) {\n \tDAO.severe(e);\n }\n log(\"classifier initialized!\");\n }\n }.start();\n\n log(\"initializing queries...\");\n File harvestingPath = new File(datadir, \"queries\");\n if (!harvestingPath.exists()) harvestingPath.mkdirs();\n String[] list = harvestingPath.list();\n if (list.length < 10) {\n // use the test data instead\n harvestingPath = new File(new File(datadir.getParentFile(), \"test\"), \"queries\");\n list = harvestingPath.list();\n }\n for (String queryfile: list) {\n if (queryfile.startsWith(\".\") || queryfile.endsWith(\"~\")) continue;\n try {\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(harvestingPath, queryfile))));\n String line;\n List<IndexEntry<QueryEntry>> bulkEntries = new ArrayList<>();\n while ((line = reader.readLine()) != null) {\n line = line.trim().toLowerCase();\n if (line.length() == 0) continue;\n if (line.charAt(0) <= '9') {\n // truncate statistic\n int p = line.indexOf(' ');\n if (p < 0) continue;\n line = line.substring(p + 1).trim();\n }\n // write line into query database\n if (!existQuery(line)) {\n randomTerms.add(line);\n bulkEntries.add(\n new IndexEntry<QueryEntry>(\n line,\n SourceType.TWITTER,\n new QueryEntry(line, 0, 60000, SourceType.TWITTER, false))\n );\n }\n if (bulkEntries.size() > 1000) {\n queries.writeEntries(bulkEntries);\n bulkEntries.clear();\n }\n }\n queries.writeEntries(bulkEntries);\n reader.close();\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n }\n log(\"queries initialized.\");\n\n log(\"finished DAO initialization\");\n }\n\n public static boolean wait_ready(long maxtimemillis) {\n ClusterHealthStatus required_status = ClusterHealthStatus.fromString(config.get(\"elasticsearch_requiredClusterHealthStatus\"));\n return elasticsearch_client.wait_ready(maxtimemillis, required_status);\n }\n\n public static String pendingClusterTasks() {\n return elasticsearch_client.pendingClusterTasks();\n }\n\n public static String clusterStats() {\n return elasticsearch_client.clusterStats();\n }\n\n public static Map<String, String> nodeSettings() {\n return elasticsearch_client.nodeSettings();\n }\n\n public static File getAssetFile(String screen_name, String id_str, String file) {\n String letter0 = (\"\" + screen_name.charAt(0)).toLowerCase();\n String letter1 = (\"\" + screen_name.charAt(1)).toLowerCase();\n Path storage_path = IO.resolvePath(assets.toPath(), letter0, letter1, screen_name);\n return IO.resolvePath(storage_path, id_str + \"_\" + file).toFile(); // all assets for one user in one file\n }\n\n public static Collection<File> getTweetOwnDumps(int count) {\n return message_dump.getOwnDumps(count);\n }\n\n public static void importAccountDumps(int count) throws IOException {\n Collection<File> dumps = account_dump.getImportDumps(count);\n if (dumps == null || dumps.size() == 0) return;\n for (File dump: dumps) {\n JsonReader reader = account_dump.getDumpReader(dump);\n final JsonReader dumpReader = reader;\n Thread[] indexerThreads = new Thread[dumpReader.getConcurrency()];\n for (int i = 0; i < dumpReader.getConcurrency(); i++) {\n indexerThreads[i] = new Thread() {\n public void run() {\n JsonFactory accountEntry;\n try {\n while ((accountEntry = dumpReader.take()) != JsonStreamReader.POISON_JSON_MAP) {\n try {\n JSONObject json = accountEntry.getJSON();\n AccountEntry a = new AccountEntry(json);\n DAO.writeAccount(a, false);\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n }\n } catch (InterruptedException e) {\n \tDAO.severe(e);\n }\n }\n };\n indexerThreads[i].start();\n }\n for (int i = 0; i < dumpReader.getConcurrency(); i++) {\n try {indexerThreads[i].join();} catch (InterruptedException e) {}\n }\n account_dump.shiftProcessedDump(dump.getName());\n }\n }\n\n /**\n * close all objects in this class\n */\n public static void close() {\n DAO.log(\"closing DAO\");\n\n // close the dump files\n message_dump.close();\n account_dump.close();\n import_profile_dump.close();\n user_dump.close();\n followers_dump.close();\n following_dump.close();\n\n // close the tracker\n access.close();\n\n // close the index factories (flushes the caches)\n messages.close();\n messages_hour.close();\n messages_day.close();\n messages_week.close();\n users.close();\n accounts.close();\n queries.close();\n importProfiles.close();\n\n // close the index\n elasticsearch_client.close();\n\n DAO.log(\"closed DAO\");\n }\n\n /**\n * get values from\n * @param key\n * @param default_val\n * @return\n */\n public static String getConfig(String key, String default_val) {\n String value = config.get(key);\n return value == null ? default_val : value;\n }\n\n public static String[] getConfig(String key, String[] default_val, String delim) {\n String value = config.get(key);\n return value == null || value.length() == 0 ? default_val : value.split(delim);\n }\n\n public static long getConfig(String key, long default_val) {\n String value = config.get(key);\n try {\n return value == null ? default_val : Long.parseLong(value);\n } catch (NumberFormatException e) {\n return default_val;\n }\n }\n\n public static double getConfig(String key, double default_val) {\n String value = config.get(key);\n try {\n return value == null ? default_val : Double.parseDouble(value);\n } catch (NumberFormatException e) {\n return default_val;\n }\n }\n\n public static int getConfig(String key, int default_val) {\n String value = config.get(key);\n try {\n return value == null ? default_val : Integer.parseInt(value);\n } catch (NumberFormatException e) {\n return default_val;\n }\n }\n/*\n public static void setConfig(String key, String value) {\n config.put(key, value);\n }\n\n public static void setConfig(String key, long value) {\n setConfig(key, Long.toString(value));\n }\n\n public static void setConfig(String key, double value) {\n setConfig(key, Double.toString(value));\n }\n*/\n public static JsonNode getSchema(String key) throws IOException {\n File schema = new File(schema_dir, key);\n if (!schema.exists()) {\n throw new FileNotFoundException(\"No schema file with name \" + key + \" found\");\n }\n return JsonLoader.fromFile(schema);\n }\n\n public static JSONObject getConversionSchema(String key) throws IOException {\n File schema = new File(conv_schema_dir, key);\n if (!schema.exists()) {\n throw new FileNotFoundException(\"No schema file with name \" + key + \" found\");\n }\n return new JSONObject(com.google.common.io.Files.toString(schema, Charsets.UTF_8));\n }\n\n public static boolean getConfig(String key, boolean default_val) {\n String value = config.get(key);\n return value == null ? default_val : value.equals(\"true\") || value.equals(\"on\") || value.equals(\"1\");\n }\n\n public static Set<String> getConfigKeys() {\n return config.keySet();\n }\n\n public static class MessageWrapper {\n public TwitterTweet t;\n public UserEntry u;\n public boolean dump;\n public MessageWrapper(TwitterTweet t, UserEntry u, boolean dump) {\n this.t = t;\n this.u = u;\n this.dump = dump;\n }\n }\n\n /**\n * Store a message together with a user into the search index\n * @param mw a message wrapper\n * @return true if the record was stored because it did not exist, false if it was not stored because the record existed already\n */\n public static boolean writeMessage(MessageWrapper mw) {\n if (mw.t == null) return false;\n try {\n synchronized (DAO.class) {\n // record tweet into search index and check if this is a new entry\n // and check if the message exists\n boolean exists = false;\n if (mw.t.getCreatedAt().after(DateParser.oneHourAgo())) {\n exists = messages_hour.writeEntry(new IndexEntry<Post>(mw.t.getPostId(), mw.t.getSourceType(), mw.t));\n if (exists) return false;\n }\n if (mw.t.getCreatedAt().after(DateParser.oneDayAgo())) {\n exists = messages_day.writeEntry(new IndexEntry<Post>(mw.t.getPostId(), mw.t.getSourceType(), mw.t));\n if (exists) return false;\n }\n if (mw.t.getCreatedAt().after(DateParser.oneWeekAgo())) {\n exists = messages_week.writeEntry(new IndexEntry<Post>(mw.t.getPostId(), mw.t.getSourceType(), mw.t));\n if (exists) return false;\n }\n exists = messages.writeEntry(new IndexEntry<Post>(mw.t.getPostId(), mw.t.getSourceType(), mw.t));\n if (exists) return false;\n\n // write the user into the index\n users.writeEntryAsync(new IndexEntry<UserEntry>(mw.u.getScreenName(), mw.t.getSourceType(), mw.u));\n\n // record tweet into text file\n if (mw.dump && writeDump) {\n message_dump.write(mw.t.toJSON(mw.u, false, Integer.MAX_VALUE, \"\"), true);\n }\n mw.t.publishToMQTT();\n }\n\n // teach the classifier\n Classifier.learnPhrase(mw.t.getText());\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n return true;\n }\n\n public static Set<String> writeMessageBulk(Collection<MessageWrapper> mws) {\n List<MessageWrapper> noDump = new ArrayList<>();\n List<MessageWrapper> dump = new ArrayList<>();\n for (MessageWrapper mw: mws) {\n if (mw.t == null) continue;\n if (mw.dump) dump.add(mw); else noDump.add(mw);\n }\n Set<String> createdIDs = new HashSet<>();\n createdIDs.addAll(writeMessageBulkNoDump(noDump));\n // does also do an writeMessageBulkNoDump internally\n createdIDs.addAll(writeMessageBulkDump(dump));\n return createdIDs;\n }\n\n public static Set<String> writeMessageBulk(Set<PostTimeline> postBulk) {\n for (PostTimeline postList: postBulk) {\n if (postList.size() < 1) continue;\n if(postList.dump) {\n writeMessageBulkDump(postList);\n }\n writeMessageBulkNoDump(postList);\n }\n //TODO: return total dumped, or IDs dumped to create hash of IDs\n return new HashSet<>();\n }\n\n private static Set<String> writeMessageBulkNoDump(PostTimeline postList) {\n if (postList.size() == 0) return new HashSet<>();\n List<Post> messageBulk = new ArrayList<>();\n\n for (Post post: postList) {\n if (messages.existsCache(post.getPostId())) {\n continue;\n }\n synchronized (DAO.class) {\n messageBulk.add(post);\n }\n }\n BulkWriteResult result = null;\n try {\n Date limitDate = new Date();\n limitDate.setTime(DateParser.oneHourAgo().getTime());\n List<Post> macc = new ArrayList<Post>();\n final Set<String> existed = new HashSet<>();\n long hourLong = limitDate.getTime();\n for(Post post : messageBulk) {\n if(hourLong <= post.getTimestamp()) macc.add(post);\n }\n \n result = messages_hour.writeEntries(macc);\n for (Post i: macc) if (!(result.getCreated().contains(i.getPostId()))) existed.add(i.getPostId());\n\n limitDate.setTime(DateParser.oneDayAgo().getTime());\n macc = messageBulk.stream().filter(i -> !(existed.contains(i.getPostId()))).filter(i -> i.getCreated().after(limitDate)).collect(Collectors.toList());\n result = messages_day.writeEntries(macc);\n for (Post i: macc) if (!(result.getCreated().contains(i.getPostId()))) existed.add(i.getPostId());\n\n limitDate.setTime(DateParser.oneWeekAgo().getTime());\n macc = messageBulk.stream().filter(i -> !(existed.contains(i.getPostId())))\n .filter(i -> i.getCreated().after(limitDate)).collect(Collectors.toList());\n result = messages_week.writeEntries(macc);\n for (Post i: macc) if (!(result.getCreated().contains(i.getPostId()))) existed.add(i.getPostId());\n\n macc = messageBulk.stream().filter(i -> !(existed.contains(i.getPostId()))).collect(Collectors.toList());\n result = messages.writeEntries(macc);\n for (Post i: macc) if (!(result.getCreated().contains(i.getPostId()))) existed.add(i.getPostId());\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n if (result == null) return new HashSet<String>();\n return result.getCreated();\n }\n\n /**\n * write messages without writing them to the dump file\n * @param mws a collection of message wrappers\n * @return a set of message IDs which had been created with this bulk write.\n */\n private static Set<String> writeMessageBulkNoDump(Collection<MessageWrapper> mws) {\n if (mws.size() == 0) return new HashSet<>();\n List<IndexEntry<UserEntry>> userBulk = new ArrayList<>();\n List<IndexEntry<Post>> messageBulk = new ArrayList<>();\n for (MessageWrapper mw: mws) {\n if (messages.existsCache(mw.t.getPostId())) continue; // we omit writing this again\n synchronized (DAO.class) {\n // write the user into the index\n userBulk.add(new IndexEntry<UserEntry>(mw.u.getScreenName(), mw.t.getSourceType(), mw.u));\n\n // record tweet into search index\n messageBulk.add(new IndexEntry<Post>(mw.t.getPostId(), mw.t.getSourceType(), mw.t));\n }\n\n // teach the classifier\n Classifier.learnPhrase(mw.t.getText());\n }\n BulkWriteResult result = null;\n Set<String> created_ids = new HashSet<>();\n try {\n final Date limitDate = new Date();\n List<IndexEntry<Post>> macc;\n final Set<String> existed = new HashSet<>();\n\n //DAO.log(\"***DEBUG messages INIT: \" + messageBulk.size());\n\n limitDate.setTime(DateParser.oneHourAgo().getTime());\n macc = messageBulk.stream().filter(i -> i.getObject().getCreated().after(limitDate)).collect(Collectors.toList());\n //DAO.log(\"***DEBUG messages for HOUR: \" + macc.size());\n result = messages_hour.writeEntries(macc);\n created_ids.addAll(result.getCreated());\n //DAO.log(\"***DEBUG messages for HOUR: \" + result.getCreated().size() + \" created\");\n for (IndexEntry<Post> i: macc) if (!(result.getCreated().contains(i.getId()))) existed.add(i.getId());\n //DAO.log(\"***DEBUG messages for HOUR: \" + existed.size() + \" existed\");\n\n limitDate.setTime(DateParser.oneDayAgo().getTime());\n macc = messageBulk.stream().filter(i -> !(existed.contains(i.getObject().getPostId()))).filter(i -> i.getObject().getCreated().after(limitDate)).collect(Collectors.toList());\n //DAO.log(\"***DEBUG messages for DAY : \" + macc.size());\n result = messages_day.writeEntries(macc);\n created_ids.addAll(result.getCreated());\n //DAO.log(\"***DEBUG messages for DAY: \" + result.getCreated().size() + \" created\");\n for (IndexEntry<Post> i: macc) if (!(result.getCreated().contains(i.getId()))) existed.add(i.getId());\n //DAO.log(\"***DEBUG messages for DAY: \" + existed.size() + \" existed\");\n\n limitDate.setTime(DateParser.oneWeekAgo().getTime());\n macc = messageBulk.stream().filter(i -> !(existed.contains(i.getObject().getPostId()))).filter(i -> i.getObject().getCreated().after(limitDate)).collect(Collectors.toList());\n //DAO.log(\"***DEBUG messages for WEEK: \" + macc.size());\n result = messages_week.writeEntries(macc);\n created_ids.addAll(result.getCreated());\n //DAO.log(\"***DEBUG messages for WEEK: \" + result.getCreated().size() + \" created\");\n for (IndexEntry<Post> i: macc) if (!(result.getCreated().contains(i.getId()))) existed.add(i.getId());\n //DAO.log(\"***DEBUG messages for WEEK: \" + existed.size() + \" existed\");\n\n macc = messageBulk.stream().filter(i -> !(existed.contains(i.getObject().getPostId()))).collect(Collectors.toList());\n //DAO.log(\"***DEBUG messages for ALL : \" + macc.size());\n result = messages.writeEntries(macc);\n created_ids.addAll(result.getCreated());\n //DAO.log(\"***DEBUG messages for ALL: \" + result.getCreated().size() + \" created\");\n for (IndexEntry<Post> i: macc) if (!(result.getCreated().contains(i.getId()))) existed.add(i.getId());\n //DAO.log(\"***DEBUG messages for ALL: \" + existed.size() + \" existed\");\n\n users.writeEntries(userBulk);\n\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n return created_ids;\n }\n\n private static Set<String> writeMessageBulkDump(Collection<MessageWrapper> mws) {\n Set<String> created = writeMessageBulkNoDump(mws);\n\n for (MessageWrapper mw: mws) try {\n mw.t.publishToMQTT();\n if (!created.contains(mw.t.getPostId())) continue;\n synchronized (DAO.class) {\n \n // record tweet into text file\n if (writeDump) {\n message_dump.write(mw.t.toJSON(mw.u, false, Integer.MAX_VALUE, \"\"), true);\n }\n }\n\n // teach the classifier\n if (randomPicker.nextInt(100) == 0) Classifier.learnPhrase(mw.t.getText());\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n\n return created;\n }\n\n private static Set<String> writeMessageBulkDump(PostTimeline postList) {\n Set<String> created = writeMessageBulkNoDump(postList);\n\n for (Post post: postList) try {\n if (!created.contains(post.getPostId())) continue;\n synchronized (DAO.class) {\n // record tweet into text file\n if (writeDump) {\n message_dump.write(post, true);\n }\n }\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n return created;\n }\n\n /**\n * Store an account together with a user into the search index\n * This method is synchronized to prevent concurrent IO caused by this call.\n * @param a an account\n * @param dump\n * @return true if the record was stored because it did not exist, false if it was not stored because the record existed already\n */\n public static boolean writeAccount(AccountEntry a, boolean dump) {\n try {\n // record account into text file\n if (dump && writeDump) {\n account_dump.write(a.toJSON(null), true);\n }\n\n // record account into search index\n accounts.writeEntryAsync(new IndexEntry<AccountEntry>(a.getScreenName(), a.getSourceType(), a));\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n return true;\n }\n\n /**\n * Store an import profile into the search index\n * @param i an import profile\n * @return true if the record was stored because it did not exist, false if it was not stored because the record existed already\n */\n public static boolean writeImportProfile(ImportProfileEntry i, boolean dump) {\n try {\n // record import profile into text file\n if (dump && writeDump) {\n import_profile_dump.write(i.toJSON(), true);\n }\n // record import profile into search index\n importProfiles.writeEntryAsync(new IndexEntry<ImportProfileEntry>(i.getId(), i.getSourceType(), i));\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n return true;\n }\n\n private static long countLocalHourMessages(final long millis, boolean created_at) {\n if (millis > DateParser.HOUR_MILLIS) return countLocalDayMessages(millis, created_at);\n if (created_at && millis == DateParser.HOUR_MILLIS) return elasticsearch_client.count(IndexName.messages_hour.name());\n return elasticsearch_client.count(\n created_at ? IndexName.messages_hour.name() : IndexName.messages_day.name(),\n created_at ? AbstractObjectEntry.CREATED_AT_FIELDNAME : AbstractObjectEntry.TIMESTAMP_FIELDNAME,\n millis);\n }\n\n private static long countLocalDayMessages(final long millis, boolean created_at) {\n if (millis > DateParser.DAY_MILLIS) return countLocalWeekMessages(millis, created_at);\n if (created_at && millis == DateParser.DAY_MILLIS) return elasticsearch_client.count(IndexName.messages_day.name());\n return elasticsearch_client.count(\n created_at ? IndexName.messages_day.name() : IndexName.messages_week.name(),\n created_at ? AbstractObjectEntry.CREATED_AT_FIELDNAME : AbstractObjectEntry.TIMESTAMP_FIELDNAME,\n millis);\n }\n\n private static long countLocalWeekMessages(final long millis, boolean created_at) {\n if (millis > DateParser.WEEK_MILLIS) return countLocalMessages(millis, created_at);\n if (created_at && millis == DateParser.WEEK_MILLIS) return elasticsearch_client.count(IndexName.messages_week.name());\n return elasticsearch_client.count(\n created_at ? IndexName.messages_week.name() : IndexName.messages.name(),\n created_at ? AbstractObjectEntry.CREATED_AT_FIELDNAME : AbstractObjectEntry.TIMESTAMP_FIELDNAME,\n millis);\n }\n\n /**\n * count the messages in the local index\n * @param millis number of milliseconds in the past\n * @param created_at field selector: true -> use CREATED_AT, the time when the tweet was created; false -> use TIMESTAMP, the time when the tweet was harvested\n * @return the number of messages in that time span\n */\n public static long countLocalMessages(final long millis, boolean created_at) {\n if (millis == 0) return 0;\n if (millis > 0) {\n if (millis <= DateParser.HOUR_MILLIS) return countLocalHourMessages(millis, created_at);\n if (millis <= DateParser.DAY_MILLIS) return countLocalDayMessages(millis, created_at);\n if (millis <= DateParser.WEEK_MILLIS) return countLocalWeekMessages(millis, created_at);\n }\n return elasticsearch_client.count(\n IndexName.messages.name(),\n created_at ? AbstractObjectEntry.CREATED_AT_FIELDNAME : AbstractObjectEntry.TIMESTAMP_FIELDNAME,\n millis == Long.MAX_VALUE ? -1 : millis);\n }\n\n public static long countLocalMessages() {\n return elasticsearch_client.count(IndexName.messages.name(), AbstractObjectEntry.TIMESTAMP_FIELDNAME, -1);\n }\n\n public static long countLocalMessages(String provider_hash) {\n return elasticsearch_client.countLocal(IndexName.messages.name(), provider_hash);\n }\n\n public static long countLocalUsers() {\n return elasticsearch_client.count(IndexName.users.name(), AbstractObjectEntry.TIMESTAMP_FIELDNAME, -1);\n }\n\n public static long countLocalQueries() {\n return elasticsearch_client.count(IndexName.queries.name(), AbstractObjectEntry.TIMESTAMP_FIELDNAME, -1);\n }\n\n public static long countLocalAccounts() {\n return elasticsearch_client.count(IndexName.accounts.name(), AbstractObjectEntry.TIMESTAMP_FIELDNAME, -1);\n }\n\n public static Post readMessage(String id) throws IOException {\n Post m = null;\n return messages_hour != null && ((m = messages_hour.read(id)) != null) ? m :\n messages_day != null && ((m = messages_day.read(id)) != null) ? m :\n messages_week != null && ((m = messages_week.read(id)) != null) ? m :\n messages.read(id);\n }\n\n public static boolean existMessage(String id) {\n return messages_hour != null && messages_hour.exists(id) ||\n messages_day != null && messages_day.exists(id) ||\n messages_week != null && messages_week.exists(id) ||\n messages != null && messages.exists(id);\n }\n\n public static boolean existUser(String id) {\n return users.exists(id);\n }\n\n public static boolean existQuery(String id) {\n return queries.exists(id);\n }\n\n public static boolean deleteQuery(String id, SourceType sourceType) {\n return queries.delete(id, sourceType);\n }\n \n public static String getRandomTerm() {\n return randomTerms.size() == 0 ? null : randomTerms.get(randomPicker.nextInt(randomTerms.size()));\n }\n\n public static boolean deleteImportProfile(String id, SourceType sourceType) {\n return importProfiles.delete(id, sourceType);\n }\n\n public static int deleteOld(IndexName indexName, Date createDateLimit) {\n RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery(AbstractObjectEntry.CREATED_AT_FIELDNAME).to(createDateLimit);\n return elasticsearch_client.deleteByQuery(indexName.name(), rangeQuery);\n }\n\n public static class SearchLocalMessages {\n public TwitterTimeline timeline;\n public PostTimeline postList;\n public Map<String, List<Map.Entry<String, AtomicLong>>> aggregations;\n public ElasticsearchClient.Query query;\n\n /**\n * Search the local message cache using a elasticsearch query.\n * @param q - the query, for aggregation this which should include a time frame in the form since:yyyy-MM-dd until:yyyy-MM-dd\n * @param order_field - the field to order the results, i.e. Timeline.Order.CREATED_AT\n * @param timezoneOffset - an offset in minutes that is applied on dates given in the query of the form since:date until:date\n * @param resultCount - the number of messages in the result; can be zero if only aggregations are wanted\n * @param aggregationLimit - the maximum count of facet entities, not search results\n * @param aggregationFields - names of the aggregation fields. If no aggregation is wanted, pass no (zero) field(s)\n * @param filterList - list of filters in String datatype\n */\n public SearchLocalMessages (\n final String q,\n final TwitterTimeline.Order orderField,\n final int timezoneOffset,\n final int resultCount,\n final int aggregationLimit,\n final Set<String> filterList,\n final String... aggregationFields\n ) {\n this.timeline = new TwitterTimeline(orderField);\n QueryEntry.ElasticsearchQuery sq = new QueryEntry.ElasticsearchQuery(q, timezoneOffset, filterList);\n long interval = sq.until.getTime() - sq.since.getTime();\n IndexName resultIndex;\n if (aggregationFields.length > 0 && q.contains(\"since:\")) {\n if (q.contains(\"since:hour\")) {\n this.query = elasticsearch_client.query((resultIndex = IndexName.messages_hour).name(), sq.queryBuilder, orderField.getMessageFieldName(), timezoneOffset, resultCount, interval, AbstractObjectEntry.CREATED_AT_FIELDNAME, aggregationLimit, aggregationFields);\n } else if (q.contains(\"since:day\")) {\n this.query = elasticsearch_client.query((resultIndex = IndexName.messages_day).name(), sq.queryBuilder, orderField.getMessageFieldName(), timezoneOffset, resultCount, interval, AbstractObjectEntry.CREATED_AT_FIELDNAME, aggregationLimit, aggregationFields);\n } else if (q.contains(\"since:week\")) {\n this.query = elasticsearch_client.query((resultIndex = IndexName.messages_week).name(), sq.queryBuilder, orderField.getMessageFieldName(), timezoneOffset, resultCount, interval, AbstractObjectEntry.CREATED_AT_FIELDNAME, aggregationLimit, aggregationFields);\n } else {\n this.query = elasticsearch_client.query((resultIndex = IndexName.messages).name(), sq.queryBuilder, orderField.getMessageFieldName(), timezoneOffset, resultCount, interval, AbstractObjectEntry.CREATED_AT_FIELDNAME, aggregationLimit, aggregationFields);\n }\n } else {\n // use only a time frame that is sufficient for a result\n this.query = elasticsearch_client.query((resultIndex = IndexName.messages_hour).name(), sq.queryBuilder, orderField.getMessageFieldName(), timezoneOffset, resultCount, interval, AbstractObjectEntry.CREATED_AT_FIELDNAME, aggregationLimit, aggregationFields);\n if (!q.contains(\"since:hour\") && insufficient(this.query, resultCount, aggregationLimit, aggregationFields)) {\n ElasticsearchClient.Query aq = elasticsearch_client.query((resultIndex = IndexName.messages_day).name(), sq.queryBuilder, orderField.getMessageFieldName(), timezoneOffset, resultCount, interval, AbstractObjectEntry.CREATED_AT_FIELDNAME, aggregationLimit, aggregationFields);\n this.query.add(aq);\n if (!q.contains(\"since:day\") && insufficient(this.query, resultCount, aggregationLimit, aggregationFields)) {\n this.query.add(aq);\n if (!q.contains(\"since:week\") && insufficient(this.query, resultCount, aggregationLimit, aggregationFields)) {\n aq = elasticsearch_client.query((resultIndex = IndexName.messages).name(), sq.queryBuilder, orderField.getMessageFieldName(), timezoneOffset, resultCount, interval, AbstractObjectEntry.CREATED_AT_FIELDNAME, aggregationLimit, aggregationFields);\n this.query.add(aq);\n }}}\n }\n \n timeline.setHits(query.getHitCount());\n timeline.setResultIndex(resultIndex);\n\n // evaluate search result\n for (Map<String, Object> map: query.getResult()) {\n TwitterTweet tweet = new TwitterTweet(new JSONObject(map));\n try {\n UserEntry user = users.read(tweet.getScreenName());\n assert user != null;\n if (user != null) {\n timeline.add(tweet, user);\n }\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n }\n this.aggregations = query.getAggregations();\n }\n\n public SearchLocalMessages (\n final String q,\n final TwitterTimeline.Order orderField,\n final int timezoneOffset,\n final int resultCount,\n final int aggregationLimit,\n final String... aggregationFields\n ) {\n this(\n q,\n orderField,\n timezoneOffset,\n resultCount,\n aggregationLimit,\n new HashSet<>(),\n aggregationFields\n );\n }\n\n public SearchLocalMessages (\n Map<String, Map<String, String>> inputMap,\n final PostTimeline.Order orderField,\n final int resultCount\n ) {\n this.postList = new PostTimeline(orderField);\n IndexName resultIndex;\n QueryEntry.ElasticsearchQuery sq = new QueryEntry.ElasticsearchQuery(\n inputMap.get(\"get\"), inputMap.get(\"not_get\"), inputMap.get(\"also_get\"));\n\n this.query = elasticsearch_client.query(\n (resultIndex = IndexName.messages_hour).name(),\n sq.queryBuilder,\n orderField.getMessageFieldName(),\n resultCount\n );\n\n if (this.query.getHitCount() < resultCount) {\n this.query = elasticsearch_client.query(\n (resultIndex = IndexName.messages_day).name(),\n sq.queryBuilder,\n orderField.getMessageFieldName(),\n resultCount\n );\n }\n\n if (this.query.getHitCount() < resultCount) {\n this.query = elasticsearch_client.query(\n (resultIndex = IndexName.messages_week).name(),\n sq.queryBuilder,\n orderField.getMessageFieldName(),\n resultCount\n );\n }\n\n if (this.query.getHitCount() < resultCount) {\n this.query = elasticsearch_client.query(\n (resultIndex = IndexName.messages).name(),\n sq.queryBuilder,\n orderField.getMessageFieldName(),\n resultCount\n );\n }\n\n // Feed search results to postList\n this.postList.setResultIndex(resultIndex);\n\n addResults();\n }\n\n private void addResults() {\n Post outputPost;\n for (Map<String, Object> map: this.query.getResult()) {\n outputPost = new Post(map);\n this.postList.addPost(outputPost);\n }\n }\n\n private static boolean insufficient(\n ElasticsearchClient.Query query,\n int resultCount,\n int aggregationLimit,\n String... aggregationFields\n ) {\n return query.getHitCount() < resultCount || (aggregationFields.length > 0\n && getAggregationResultLimit(query.getAggregations()) < aggregationLimit);\n }\n\n public JSONObject getAggregations() {\n JSONObject json = new JSONObject(true);\n if (aggregations == null) return json;\n for (Map.Entry<String, List<Map.Entry<String, AtomicLong>>> aggregation: aggregations.entrySet()) {\n JSONObject facet = new JSONObject(true);\n for (Map.Entry<String, AtomicLong> a: aggregation.getValue()) {\n if (a.getValue().equals(query)) continue; // we omit obvious terms that cannot be used for faceting, like search for \"#abc\" -> most hashtag is \"#abc\"\n facet.put(a.getKey(), a.getValue().get());\n }\n json.put(aggregation.getKey(), facet);\n }\n return json;\n }\n\n private static int getAggregationResultLimit(Map<String, List<Map.Entry<String, AtomicLong>>> agg) {\n if (agg == null) return 0;\n int l = 0;\n for (List<Map.Entry<String, AtomicLong>> a: agg.values()) l = Math.max(l, a.size());\n return l;\n }\n }\n\n public static LinkedHashMap<String, Long> FullDateHistogram(int timezoneOffset) {\n return elasticsearch_client.fullDateHistogram(IndexName.messages.name(), timezoneOffset, AbstractObjectEntry.CREATED_AT_FIELDNAME);\n }\n\n /**\n * Search the local user cache using a elasticsearch query.\n * @param screen_name - the user id\n */\n public static UserEntry searchLocalUserByScreenName(final String screen_name) {\n try {\n return users.read(screen_name);\n } catch (IOException e) {\n \tDAO.severe(e);\n return null;\n }\n }\n\n public static UserEntry searchLocalUserByUserId(final String user_id) {\n if (user_id == null || user_id.length() == 0) return null;\n Map<String, Object> map = elasticsearch_client.query(IndexName.users.name(), UserEntry.field_user_id, user_id);\n if (map == null) return null;\n return new UserEntry(new JSONObject(map));\n }\n\n /**\n * Search the local account cache using an elasticsearch query.\n * @param screen_name - the user id\n */\n public static AccountEntry searchLocalAccount(final String screen_name) {\n try {\n return accounts.read(screen_name);\n } catch (IOException e) {\n \tDAO.severe(e);\n return null;\n }\n }\n\n /**\n * Search the local message cache using a elasticsearch query.\n * @param q - the query, can be empty for a matchall-query\n * @param resultCount - the number of messages in the result\n * @param sort_field - the field name to sort the result list, i.e. \"query_first\"\n * @param sort_order - the sort order (you want to use SortOrder.DESC here)\n */\n public static ResultList<QueryEntry> SearchLocalQueries(final String q, final int resultCount, final String sort_field, final String default_sort_type, final SortOrder sort_order, final Date since, final Date until, final String range_field) {\n ResultList<QueryEntry> queries = new ResultList<>();\n ResultList<Map<String, Object>> result = elasticsearch_client.fuzzyquery(IndexName.queries.name(), \"query\", q, resultCount, sort_field, default_sort_type, sort_order, since, until, range_field);\n queries.setHits(result.getHits());\n for (Map<String, Object> map: result) {\n QueryEntry qe = new QueryEntry(new JSONObject(map));\n // check a flag value for queries that probably never get new messages\n if (qe.getMessagePeriod() != QueryEntry.DAY_MILLIS) {\n queries.add(qe);\n }\n }\n return queries;\n }\n\n public static ImportProfileEntry SearchLocalImportProfiles(final String id) {\n try {\n return importProfiles.read(id);\n } catch (IOException e) {\n \tDAO.severe(e);\n return null;\n }\n }\n\n public static Collection<ImportProfileEntry> SearchLocalImportProfilesWithConstraints(final Map<String, String> constraints, boolean latest) throws IOException {\n List<ImportProfileEntry> rawResults = new ArrayList<>();\n List<Map<String, Object>> result = elasticsearch_client.queryWithConstraints(IndexName.import_profiles.name(), \"active_status\", ImportProfileEntry.EntryStatus.ACTIVE.name().toLowerCase(), constraints, latest);\n for (Map<String, Object> map: result) {\n rawResults.add(new ImportProfileEntry(new JSONObject(map)));\n }\n\n if (!latest) {\n return rawResults;\n }\n\n // filter results to display only latest profiles\n Map<String, ImportProfileEntry> latests = new HashMap<>();\n for (ImportProfileEntry entry : rawResults) {\n String uniqueKey;\n if (entry.getImporter() != null) {\n uniqueKey = entry.getSourceUrl() + entry.getImporter();\n } else {\n uniqueKey = entry.getSourceUrl() + entry.getClientHost();\n }\n if (latests.containsKey(uniqueKey)) {\n if (entry.getLastModified().compareTo(latests.get(uniqueKey).getLastModified()) > 0) {\n latests.put(uniqueKey, entry);\n }\n } else {\n latests.put(uniqueKey, entry);\n }\n }\n return latests.values();\n }\n\n public static TwitterTimeline scrapeTwitter(\n final Query post,\n final String q,\n final TwitterTimeline.Order order,\n final int timezoneOffset,\n boolean byUserQuery,\n long timeout,\n boolean recordQuery) {\n\n return scrapeTwitter(post, new HashSet<>(), q, order, timezoneOffset, byUserQuery, timeout, recordQuery);\n }\n\n /**\n * \n * @param post\n * @param filterList empty or one/several of image, video\n * @param q\n * @param order\n * @param timezoneOffset\n * @param byUserQuery\n * @param timeout\n * @param recordQuery\n * @return\n */\n public static TwitterTimeline scrapeTwitter(\n final Query post,\n final Set<String> filterList,\n final String q,\n final TwitterTimeline.Order order,\n final int timezoneOffset,\n boolean byUserQuery,\n long timeout,\n boolean recordQuery) {\n // retrieve messages from remote server\n\n ArrayList<String> remote = DAO.getFrontPeers();\n TwitterTimeline tl;\n if (remote.size() > 0 && (peerLatency.get(remote.get(0)) == null || peerLatency.get(remote.get(0)).longValue() < 3000)) {\n long start = System.currentTimeMillis();\n tl = searchOnOtherPeers(remote, q, filterList, order, 100, timezoneOffset, \"all\", SearchServlet.frontpeer_hash, timeout); // all must be selected here to catch up missing tweets between intervals\n // at this point the remote list can be empty as a side-effect of the remote search attempt\n if (post != null && remote.size() > 0 && tl != null) post.recordEvent(\"remote_scraper_on_\" + remote.get(0), System.currentTimeMillis() - start);\n if (tl == null || tl.size() == 0) {\n // maybe the remote server died, we try then ourself\n start = System.currentTimeMillis();\n\n tl = TwitterScraper.search(q, filterList, order, true, true, 400);\n if (post != null) post.recordEvent(\"local_scraper_after_unsuccessful_remote\", System.currentTimeMillis() - start);\n } else {\n tl.writeToIndex();\n }\n } else {\n if (post != null && remote.size() > 0) post.recordEvent(\"omitted_scraper_latency_\" + remote.get(0), peerLatency.get(remote.get(0)));\n long start = System.currentTimeMillis();\n\n tl = TwitterScraper.search(q, filterList, order, true, true, 400);\n if (post != null) post.recordEvent(\"local_scraper\", System.currentTimeMillis() - start);\n }\n\n // record the query\n long start2 = System.currentTimeMillis();\n QueryEntry qe = null;\n try {\n qe = queries.read(q);\n } catch (IOException | JSONException e) {\n \tDAO.severe(e);\n }\n\n if (recordQuery && Caretaker.acceptQuery4Retrieval(q) && tl.size() > 0) {\n if (qe == null) {\n // a new query occurred\n qe = new QueryEntry(q, timezoneOffset, tl.period(), SourceType.TWITTER, byUserQuery);\n } else {\n // existing queries are updated\n qe.update(tl.period(), byUserQuery);\n }\n try {\n queries.writeEntryAsync(new IndexEntry<QueryEntry>(q, qe.source_type == null ? SourceType.TWITTER : qe.source_type, qe));\n } catch (IOException e) {\n \tDAO.severe(e);\n }\n } else {\n // accept rules may change, we want to delete the query then in the index\n if (qe != null) queries.delete(q, qe.source_type);\n }\n if (post != null) post.recordEvent(\"query_recorder\", System.currentTimeMillis() - start2);\n //log(\"SCRAPER: TIME LEFT after recording = \" + (termination - System.currentTimeMillis()));\n\n return tl;\n }\n\n\n public static JSONArray scrapeLoklak(\n Map<String, String> inputMap,\n boolean byUserQuery,\n boolean recordQuery,\n JSONObject metadata) {\n PostTimeline.Order order= getOrder(inputMap.get(\"order\"));\n PostTimeline dataSet = new PostTimeline(order);\n List<String> scraperList = Arrays.asList(inputMap.get(\"scraper\").trim().split(\"\\\\s*,\\\\s*\"));\n List<BaseScraper> scraperObjList = getScraperObjects(scraperList, inputMap);\n ExecutorService scraperRunner = Executors.newFixedThreadPool(scraperObjList.size());\n\n try{\n for (BaseScraper scraper : scraperObjList) {\n scraperRunner.execute(() -> {\n dataSet.add(scraper.getData());\n \n });\n }\n } finally {\n scraperRunner.shutdown();\n try {\n scraperRunner.awaitTermination(3000L, TimeUnit.SECONDS);\n } catch (InterruptedException e) { }\n }\n dataSet.collectMetadata(metadata);\n return dataSet.toArray();\n }\n\n public static List<BaseScraper> getScraperObjects(List<String> scraperList, Map<String, String> inputMap) {\n //TODO: use SourceType to get this job done\n List<BaseScraper> scraperObjList = new ArrayList<BaseScraper>();\n BaseScraper scraperObj = null;\n\n if (scraperList.contains(\"github\") || scraperList.contains(\"all\")) {\n scraperObj = new GithubProfileScraper(inputMap);\n scraperObjList.add(scraperObj);\n }\n if (scraperList.contains(\"quora\") || scraperList.contains(\"all\")) {\n scraperObj = new QuoraProfileScraper(inputMap);\n scraperObjList.add(scraperObj);\n }\n if (scraperList.contains(\"instagram\") || scraperList.contains(\"all\")) {\n scraperObj = new InstagramProfileScraper(inputMap);\n scraperObjList.add(scraperObj);\n }\n if (scraperList.contains(\"youtube\") || scraperList.contains(\"all\")) {\n scraperObj = new YoutubeScraper(inputMap);\n scraperObjList.add(scraperObj);\n }\n if (scraperList.contains(\"wordpress\") || scraperList.contains(\"all\")) {\n scraperObj = new WordpressCrawlerService(inputMap);\n scraperObjList.add(scraperObj);\n }\n if (scraperList.contains(\"twitter\") || scraperList.contains(\"all\")) {\n scraperObj = new TweetScraper(inputMap);\n scraperObjList.add(scraperObj);\n }\n //TODO: add more scrapers\n return scraperObjList;\n }\n\n public static PostTimeline.Order getOrder(String orderString) {\n //TODO: order set according to input\n return PostTimeline.parseOrder(\"timestamp\");\n }\n\n public static final Random random = new Random(System.currentTimeMillis());\n private static final Map<String, Long> peerLatency = new HashMap<>();\n private static ArrayList<String> getBestPeers(Collection<String> peers) {\n ArrayList<String> best = new ArrayList<>();\n if (peers == null || peers.size() == 0) return best;\n // first check if any of the given peers has unknown latency\n TreeMap<Long, String> o = new TreeMap<>();\n for (String peer: peers) {\n if (peerLatency.containsKey(peer)) {\n o.put(peerLatency.get(peer) * 1000 + best.size(), peer);\n } else {\n best.add(peer);\n }\n }\n best.addAll(o.values());\n return best;\n }\n public static void healLatency(float factor) {\n for (Map.Entry<String, Long> entry: peerLatency.entrySet()) {\n entry.setValue((long) (factor * entry.getValue()));\n }\n }\n\n private static Set<String> frontPeerCache = ConcurrentHashMap.newKeySet();\n private static Set<String> backendPeerCache = ConcurrentHashMap.newKeySet();\n\n public static void updateFrontPeerCache(RemoteAccess remoteAccess) {\n if (remoteAccess.getLocalHTTPPort() >= 80) {\n frontPeerCache.add(\"http://\" + remoteAccess.getRemoteHost() + (remoteAccess.getLocalHTTPPort() == 80 ? \"\" : \":\" + remoteAccess.getLocalHTTPPort()));\n } else if (remoteAccess.getLocalHTTPSPort() >= 443) {\n frontPeerCache.add(\"https://\" + remoteAccess.getRemoteHost() + (remoteAccess.getLocalHTTPSPort() == 443 ? \"\" : \":\" + remoteAccess.getLocalHTTPSPort()));\n }\n }\n\n /**\n * from all known front peers, generate a list of available peers, ordered by the peer latency\n * @return a list of front peers. only the first one shall be used, but the other are fail-over peers\n */\n public static ArrayList<String> getFrontPeers() {\n String[] remote = DAO.getConfig(\"frontpeers\", new String[0], \",\");\n ArrayList<String> testpeers = new ArrayList<>();\n if (remote.length > 0) {\n for (String peer: remote) testpeers.add(peer);\n return testpeers;\n }\n /*\n if (frontPeerCache.size() == 0) {\n // add dynamically all peers that contacted myself\n for (Map<String, RemoteAccess> hmap: RemoteAccess.history.values()) {\n for (Map.Entry<String, RemoteAccess> peer: hmap.entrySet()) {\n updateFrontPeerCache(peer.getValue());\n }\n }\n }\n testpeers.addAll(frontPeerCache);\n */\n return getBestPeers(testpeers);\n }\n\n public static String[] getBackend() {\n return DAO.getConfig(\"backend\", new String[0], \",\");\n }\n \n public static List<String> getBackendPeers() {\n List<String> testpeers = new ArrayList<>();\n if (backendPeerCache.size() == 0) {\n final String[] remote = DAO.getBackend();\n for (String peer: remote) backendPeerCache.add(peer);\n }\n testpeers.addAll(backendPeerCache);\n return getBestPeers(testpeers);\n }\n\n public static TwitterTimeline searchBackend(final String q,final Set<String> filterList, final TwitterTimeline.Order order, final int count, final int timezoneOffset, final String where, final long timeout) {\n List<String> remote = getBackendPeers();\n\n if (remote.size() > 0 /*&& (peerLatency.get(remote.get(0)) == null || peerLatency.get(remote.get(0)) < 3000)*/) { // condition deactivated because we need always at least one peer\n TwitterTimeline tt = searchOnOtherPeers(remote, q, filterList, order, count, timezoneOffset, where, SearchServlet.backend_hash, timeout);\n if (tt != null) tt.writeToIndex();\n return tt;\n }\n return null;\n }\n\n private final static Random randomPicker = new Random(System.currentTimeMillis());\n\n public static TwitterTimeline searchOnOtherPeers(final List<String> remote, final String q, final Set<String> filterList,final TwitterTimeline.Order order, final int count, final int timezoneOffset, final String source, final String provider_hash, final long timeout) {\n // select remote peer\n while (remote.size() > 0) {\n int pick = randomPicker.nextInt(remote.size());\n String peer = remote.get(pick);\n long start = System.currentTimeMillis();\n try {\n TwitterTimeline tl = SearchServlet.search(new String[]{peer}, q, filterList, order, source, count, timezoneOffset, provider_hash, timeout);\n peerLatency.put(peer, System.currentTimeMillis() - start);\n // to show which peer was used for the retrieval, we move the picked peer to the front of the list\n if (pick != 0) remote.add(0, remote.remove(pick));\n tl.setScraperInfo(tl.getScraperInfo().length() > 0 ? peer + \",\" + tl.getScraperInfo() : peer);\n return tl;\n } catch (IOException e) {\n DAO.log(\"searchOnOtherPeers: no IO to scraping target: \" + e.getMessage());\n // the remote peer seems to be unresponsive, remove it (temporary) from the remote peer list\n peerLatency.put(peer, DateParser.HOUR_MILLIS);\n frontPeerCache.remove(peer);\n backendPeerCache.remove(peer);\n remote.remove(pick);\n }\n }\n return null;\n }\n\n public final static Set<Number> newUserIds = ConcurrentHashMap.newKeySet();\n\n public static void announceNewUserId(TwitterTimeline tl) {\n for (TwitterTweet message: tl) {\n UserEntry user = tl.getUser(message);\n assert user != null;\n if (user == null) continue;\n Number id = user.getUser();\n if (id != null) announceNewUserId(id);\n }\n }\n\n public static void announceNewUserId(Number id) {\n JsonFactory mapcapsule = DAO.user_dump.get(\"id_str\", id.toString());\n JSONObject map = null;\n try {map = mapcapsule == null ? null : mapcapsule.getJSON();} catch (IOException e) {}\n if (map == null) newUserIds.add(id);\n }\n\n public static Set<Number> getNewUserIdsChunk() {\n if (newUserIds.size() < 100) return null;\n Set<Number> chunk = new HashSet<>();\n Iterator<Number> i = newUserIds.iterator();\n for (int j = 0; j < 100; j++) {\n chunk.add(i.next());\n i.remove();\n }\n return chunk;\n }\n\n /**\n * For logging informational events\n */\n public static void log(String line) {\n if (DAO.getConfig(\"flag.log.dao\", \"true\").equals(\"true\")) {\n logger.info(line);\n }\n }\n\n /**\n * For events serious enough to inform and log, but not fatal.\n */\n public static void severe(String line) {\n if (DAO.getConfig(\"flag.severe.dao\", \"true\").equals(\"true\")) {\n logger.warn(line);\n }\n }\n\n public static void severe(String line, Throwable e) {\n if (DAO.getConfig(\"flag.severe.dao\", \"true\").equals(\"true\")) {\n logger.warn(line, e);\n }\n }\n\n public static void severe(Throwable e) {\n if (DAO.getConfig(\"flag.severe.dao\", \"true\").equals(\"true\")) {\n logger.warn(\"\", e);\n }\n }\n\n /**\n * For Debugging events (very noisy).\n */\n public static void debug(Throwable e) {\n if (DAO.getConfig(\"flag.debug.dao\", \"true\").equals(\"true\")) {\n DAO.severe(e);\n }\n }\n\n /**\n * For Stacktracing exceptions (preferred over debug).\n */\n public static void trace(Throwable e) {\n if(DAO.getConfig(\"flag.trace.dao\", \"true\").equals(\"true\")) {\n e.printStackTrace();\n }\n }\n}",
"public static class TwitterTweet extends Post implements Runnable {\n\n public final Semaphore ready;\n public MessageEntry moreData = new MessageEntry();\n public UserEntry user;\n public boolean writeToIndex;\n public boolean writeToBackend;\n\n // a time stamp that is given in loklak upon the arrival of the tweet which is the current local time\n public Date timestampDate;\n // the time given in the tweet which is the time when the user created it.\n // This is also use to do the index partition into minute, hour, week\n public Date created_at;\n // on means 'valid from'\n public Date on;\n // 'to' means 'valid_until' and may not be set\n public Date to;\n\n // where did the message come from\n protected SourceType source_type;\n // who created the message\n protected ProviderType provider_type;\n\n public String provider_hash, screen_name, retweet_from, postId, conversationID, canonical_id, parent, text;\n public Set<String> conversationUserIDs;\n protected URL status_id_url;\n protected long reply_count, retweet_count, favourite_count;\n public Set<String> images, audios, videos;\n protected String place_name, place_id;\n\n // the following fields are either set as a common field or generated by extraction from field 'text' or from field 'place_name'\n // coordinate order is [longitude, latitude]\n protected double[] location_point, location_mark;\n // Value in metres\n protected int location_radius;\n protected LocationSource location_source;\n protected PlaceContext place_context;\n protected String place_country;\n\n // The length of tweets without links, users, hashtags\n // the following can be computed from the tweet data but is stored in the search index\n // to provide statistical data and ranking attributes\n private int without_l_len, without_lu_len, without_luh_len;\n\n // the arrays of links, users, hashtags\n private List<String> users, hosts, links, mentions, hashtags;\n\n private boolean enriched;\n\n public TwitterTweet(\n final String user_screen_name_raw,\n final long created_at_raw,\n final String tweetID, // the ID of the tweet\n final String tweetConversationID, // the ID of a tweet where this is a reply-to tweet\n final Set<String> mentions_screennames,\n final String status_id_url_raw,\n final String text_raw,\n final long replies,\n final long retweets,\n final long favourites,\n final Set<String> images,\n final Set<String> videos,\n final String place_name,\n final String place_id,\n final UserEntry user,\n final boolean writeToIndex,\n final boolean writeToBackend) throws MalformedURLException {\n super();\n this.source_type = SourceType.TWITTER;\n this.provider_type = ProviderType.SCRAPED;\n this.screen_name = user_screen_name_raw;\n this.created_at = new Date(created_at_raw);\n this.status_id_url = new URL(\"https://twitter.com\" + status_id_url_raw);\n int p = status_id_url_raw.lastIndexOf('/');\n this.postId = p >= 0 ? status_id_url_raw.substring(p + 1) : \"-1\";\n assert this.postId.equals(tweetID);\n this.conversationID = tweetConversationID;\n this.conversationUserIDs = mentions_screennames;\n this.reply_count = replies;\n this.retweet_count = retweets;\n this.favourite_count = favourites;\n this.place_name = place_name;\n this.place_id = place_id;\n this.images = images;\n this.videos = videos;\n this.text = text_raw;\n this.user = user;\n this.writeToIndex = writeToIndex;\n this.writeToBackend = writeToBackend;\n\n //Date d = new Date(timemsraw);\n //System.out.println(d);\n\n /* failed to reverse-engineering the place_id :(\n if (place_id.length() == 16) {\n String a = place_id.substring(0, 8);\n String b = place_id.substring(8, 16);\n long an = Long.parseLong(a, 16);\n long bn = Long.parseLong(b, 16);\n System.out.println(\"place = \" + place_name + \", a = \" + an + \", b = \" + bn);\n // Frankfurt a = 3314145750, b = 3979907708, http://www.openstreetmap.org/#map=15/50.1128/8.6835\n // Singapore a = 1487192992, b = 3578663936\n }\n */\n\n // this.text MUST be analysed with analyse(); this is not done here because it should be started concurrently; run run();\n\n this.ready = new Semaphore(0);\n }\n\n public TwitterTweet(JSONObject json) {\n this.moreData = new MessageEntry();\n Object timestamp_obj = lazyGet(json, AbstractObjectEntry.TIMESTAMP_FIELDNAME);\n this.timestampDate = MessageEntry.parseDate(timestamp_obj);\n this.timestamp = this.timestampDate.getTime();\n Object created_at_obj = lazyGet(json, AbstractObjectEntry.CREATED_AT_FIELDNAME);\n this.created_at = MessageEntry.parseDate(created_at_obj);\n Object on_obj = lazyGet(json, \"on\");\n this.on = on_obj == null ? null : MessageEntry.parseDate(on);\n Object to_obj = lazyGet(json, \"to\");\n this.to = to_obj == null ? null : MessageEntry.parseDate(to);\n String source_type_string = (String) lazyGet(json, \"source_type\");\n try {\n this.source_type = source_type_string == null ? SourceType.GENERIC : SourceType.byName(source_type_string);\n } catch (IllegalArgumentException e) {\n this.source_type = SourceType.GENERIC;\n }\n String provider_type_string = (String) lazyGet(json, \"provider_type\");\n if (provider_type_string == null) provider_type_string = ProviderType.NOONE.name();\n try {\n this.provider_type = ProviderType.valueOf(provider_type_string);\n } catch (IllegalArgumentException e) {\n this.provider_type = ProviderType.NOONE;\n }\n this.provider_hash = (String) lazyGet(json, \"provider_hash\");\n this.screen_name = (String) lazyGet(json, \"screen_name\");\n this.retweet_from = (String) lazyGet(json, \"retweet_from\");\n this.postId = (String) lazyGet(json, \"id_str\");\n this.conversationID = (String) lazyGet(json, \"conversationid_str\");\n this.conversationUserIDs = MessageEntry.parseArrayList(lazyGet(json, \"conversation_user\"));\n this.text = (String) lazyGet(json, \"text\");\n try {\n this.status_id_url = new URL((String) lazyGet(json, \"link\"));\n } catch (MalformedURLException e) {\n this.status_id_url = null;\n }\n this.reply_count = MessageEntry.parseLong((Number) lazyGet(json, \"reply_count\"));\n this.retweet_count = MessageEntry.parseLong((Number) lazyGet(json, \"retweet_count\"));\n this.favourite_count = MessageEntry.parseLong((Number) lazyGet(json, \"favourites_count\")); // inconsitency in naming, but twitter api defines so\n this.images = MessageEntry.parseArrayList(lazyGet(json, \"images\"));\n this.audios = MessageEntry.parseArrayList(lazyGet(json, \"audio\"));\n this.videos = MessageEntry.parseArrayList(lazyGet(json, \"videos\"));\n this.place_id = MessageEntry.parseString((String) lazyGet(json, \"place_id\"));\n this.place_name = MessageEntry.parseString((String) lazyGet(json, \"place_name\"));\n this.place_country = MessageEntry.parseString((String) lazyGet(json, \"place_country\"));\n\n if (this.place_country != null && this.place_country.length() != 2) this.place_country = null;\n\n // optional location\n Object location_point_obj = lazyGet(json, \"location_point\");\n Object location_radius_obj = lazyGet(json, \"location_radius\");\n Object location_mark_obj = lazyGet(json, \"location_mark\");\n Object location_source_obj = lazyGet(json, \"location_source\");\n if (location_point_obj == null || location_mark_obj == null ||\n !(location_point_obj instanceof List<?>) ||\n !(location_mark_obj instanceof List<?>)) {\n this.location_point = null;\n this.location_radius = 0;\n this.location_mark = null;\n this.location_source = null;\n } else {\n this.location_point = new double[]{(Double) ((List<?>) location_point_obj).get(0), (Double) ((List<?>) location_point_obj).get(1)};\n this.location_radius = (int) MessageEntry.parseLong((Number) location_radius_obj);\n this.location_mark = new double[]{(Double) ((List<?>) location_mark_obj).get(0), (Double) ((List<?>) location_mark_obj).get(1)};\n this.location_source = LocationSource.valueOf((String) location_source_obj);\n }\n this.enriched = false;\n\n // load enriched data\n enrich();\n\n // may lead to error!!\n this.ready = new Semaphore(0);\n //this.user = null;\n //this.writeToIndex = false;\n //this.writeToBackend = false;\n }\n\n public TwitterTweet() throws MalformedURLException {\n this.moreData = new MessageEntry();\n this.timestamp = new Date().getTime();\n this.timestampDate = new Date(this.timestamp);\n this.created_at = new Date();\n this.on = null;\n this.to = null;\n this.source_type = SourceType.GENERIC;\n this.provider_type = ProviderType.NOONE;\n this.provider_hash = \"\";\n this.screen_name = \"\";\n this.retweet_from = \"\";\n this.postId = \"\";\n this.conversationID = \"\";\n this.conversationUserIDs = new LinkedHashSet<>();\n this.canonical_id = \"\";\n this.parent = \"\";\n this.text = \"\";\n this.status_id_url = null;\n this.reply_count = 0;\n this.retweet_count = 0;\n this.favourite_count = 0;\n this.images = new HashSet<String>();\n this.audios = new HashSet<String>();\n this.videos = new HashSet<String>();\n this.place_id = \"\";\n this.place_name = \"\";\n this.place_context = null;\n this.place_country = null;\n this.location_point = null;\n this.location_radius = 0;\n this.location_mark = null;\n this.location_source = null;\n this.without_l_len = 0;\n this.without_lu_len = 0;\n this.without_luh_len = 0;\n this.hosts = new ArrayList<String>();\n this.links = new ArrayList<String>();\n this.mentions = new ArrayList<String>();\n this.hashtags = new ArrayList<String>();\n this.moreData.classifier = null;\n this.enriched = false;\n\n // may lead to error!!\n this.ready = new Semaphore(0);\n //this.user = null;\n //this.writeToIndex = false;\n //this.writeToBackend = false;\n }\n\n //TODO: fix the location issue and shift to MessageEntry class\n public void getLocation() {\n if (this.text == null) this.text = \"\";\n\n if ((this.location_point == null || this.location_point.length == 0) && DAO.geoNames != null) {\n GeoMark loc = null;\n if (place_name != null && this.place_name.length() > 0 &&\n (this.location_source == null || this.location_source == LocationSource.ANNOTATION || this.location_source == LocationSource.PLACE)) {\n loc = DAO.geoNames.analyse(this.place_name, null, 5, Integer.toString(this.text.hashCode()));\n this.place_context = PlaceContext.FROM;\n this.location_source = LocationSource.PLACE;\n }\n if (loc == null) {\n loc = DAO.geoNames.analyse(this.text, this.hashtags.toArray(new String[0]), 5, Integer.toString(this.text.hashCode()));\n this.place_context = PlaceContext.ABOUT;\n this.location_source = LocationSource.ANNOTATION;\n }\n if (loc != null) {\n if (this.place_name == null || this.place_name.length() == 0) this.place_name = loc.getNames().iterator().next();\n this.location_radius = 0;\n this.location_point = new double[]{loc.lon(), loc.lat()}; //[longitude, latitude]\n this.location_mark = new double[]{loc.mlon(), loc.mlat()}; //[longitude, latitude]\n this.place_country = loc.getISO3166cc();\n }\n }\n }\n\n /**\n * create enriched data, useful for analytics and ranking:\n * - identify all mentioned users, hashtags and links\n * - count message size without links\n * - count message size without links and without users\n */\n public void enrich() {\n if (this.enriched) return;\n this.moreData.classifier = Classifier.classify(this.text);\n \n StringBuilder text = new StringBuilder(this.text);\n this.links = this.moreData.extractLinks(text.toString());\n text = new StringBuilder(MessageEntry.SPACEX_PATTERN.matcher(text).replaceAll(\" \").trim());\n // Text's length without link\n this.without_l_len = text.length();\n\n this.hosts = this.moreData.extractHosts(links);\n\n this.videos = this.moreData.getLinksVideo(this.links, this.videos);\n this.images = this.moreData.getLinksImage(this.links, this.images);\n this.audios = this.moreData.getLinksAudio(this.links, this.audios);\n\n this.users = this.moreData.extractUsers(text.toString());\n text = new StringBuilder(MessageEntry.SPACEX_PATTERN.matcher(text).replaceAll(\" \").trim());\n // Text's length without link and users\n this.without_lu_len = text.length();\n\n this.mentions = new ArrayList<String>();\n for (int i = 0; i < this.users.size(); i++) {\n this.mentions.add(this.users.get(i).substring(1));\n }\n\n this.hashtags = this.moreData.extractHashtags(text.toString());\n text = new StringBuilder(MessageEntry.SPACEX_PATTERN.matcher(text).replaceAll(\" \").trim());\n // Text's length without link, users and hashtags\n this.without_luh_len = text.length();\n\n getLocation();\n this.enriched = true;\n }\n\n /**\n * Channels on which the Tweet will be published -\n * all\n * twitter\n * twitter/mention/*username*\n * twitter/user/*username* (User who posted the Tweet)\n * twitter/hashtag/*hashtag*\n * twitter/country/*country code*\n * twitter/text/*token*\n * @return Array of channels to publish message to\n */\n @Override\n protected String[] getStreamChannels() {\n ArrayList<String> channels = new ArrayList<>();\n\n for (String mention : this.mentions) {\n channels.add(\"twitter/mention/\" + mention);\n }\n\n for (String hashtag : this.hashtags) {\n channels.add(\"twitter/hashtag/\" + hashtag);\n }\n\n channels.add(\"twitter/user/\" + this.getScreenName());\n if (this.place_country != null) {\n channels.add(\"twitter/country/\" + this.place_country);\n }\n\n for (String token : Classifier.normalize(this.text)) {\n channels.add(\"twitter/text/\" + token);\n }\n\n channels.add(\"all\");\n channels.add(\"twitter\");\n\n return channels.toArray(new String[channels.size()]);\n }\n\n @Override\n public void run() {\n //long start = System.currentTimeMillis();\n try {\n //DAO.log(\"TwitterTweet [\" + this.postId + \"] start\");\n this.text = unshorten(this.text);\n this.user.setName(unshorten(this.user.getName()));\n //DAO.log(\"TwitterTweet [\" + this.postId + \"] unshorten after \" + (System.currentTimeMillis() - start) + \"ms\");\n this.enrich();\n\n //DAO.log(\"TwitterTweet [\" + this.postId + \"] enrich after \" + (System.currentTimeMillis() - start) + \"ms\");\n if (this.writeToIndex) IncomingMessageBuffer.addScheduler(this, this.user, true, true);\n //DAO.log(\"TwitterTweet [\" + this.postId + \"] write after \" + (System.currentTimeMillis() - start) + \"ms\");\n if (this.writeToBackend) DAO.outgoingMessages.transmitMessage(this, this.user);\n //DAO.log(\"TwitterTweet [\" + this.postId + \"] transmit after \" + (System.currentTimeMillis() - start) + \"ms\");\n } catch (Throwable e) {\n DAO.severe(e);\n } finally {\n this.ready.release(1000);\n }\n }\n\n public boolean isReady() {\n if (this.ready == null) throw new RuntimeException(\"isReady() should not be called if postprocessing is not started\");\n return this.ready.availablePermits() > 0;\n }\n\n public boolean waitReady(long millis) {\n if (this.ready == null) throw new RuntimeException(\"waitReady() should not be called if postprocessing is not started\");\n if (this.ready.availablePermits() > 0) return true;\n try {\n return this.ready.tryAcquire(millis, TimeUnit.MILLISECONDS);\n } catch (InterruptedException e) {\n return false;\n }\n }\n\n public Post toJSON() {\n // very important to include calculated data here because that is written\n // into the index using the abstract index factory\n return toJSON(null, true, Integer.MAX_VALUE, \"\");\n }\n\n public Post toJSON(final UserEntry user, final boolean calculatedData, final int iflinkexceedslength, final String urlstub) {\n\n // tweet data\n this.put(AbstractObjectEntry.TIMESTAMP_FIELDNAME, AbstractObjectEntry.utcFormatter.print(getTimestampDate().getTime()));\n this.put(AbstractObjectEntry.CREATED_AT_FIELDNAME, AbstractObjectEntry.utcFormatter.print(getCreatedAt().getTime()));\n if (this.on != null) this.put(\"on\", AbstractObjectEntry.utcFormatter.print(this.on.getTime()));\n if (this.to != null) this.put(\"to\", AbstractObjectEntry.utcFormatter.print(this.to.getTime()));\n this.put(\"screen_name\", this.screen_name);\n if (this.retweet_from != null && this.retweet_from.length() > 0) this.put(\"retweet_from\", this.retweet_from);\n // the tweet; the cleanup is a helper function which cleans mistakes from the past in scraping\n MessageEntry.TextLinkMap tlm = this.moreData.getText(iflinkexceedslength, urlstub, this.text, this.getLinks(), this.getPostId());\n this.put(\"text\", tlm);\n if (this.status_id_url != null) this.put(\"link\", this.status_id_url.toExternalForm()); // this is the primary key for retrieval in elasticsearch\n this.put(\"id_str\", this.postId);\n this.put(\"conversation_id\", this.conversationID);\n this.put(\"conversation_user\", this.conversationUserIDs);\n if (this.canonical_id != null) this.put(\"canonical_id\", this.canonical_id);\n if (this.parent != null) this.put(\"parent\", this.parent);\n this.put(\"source_type\", this.source_type.toString());\n this.put(\"provider_type\", this.provider_type.name());\n if (this.provider_hash != null && this.provider_hash.length() > 0) this.put(\"provider_hash\", this.provider_hash);\n this.put(\"reply_count\", this.reply_count);\n this.put(\"retweet_count\", this.retweet_count);\n // there is a slight inconsistency here in the plural naming but thats how it is noted in the twitter api\n this.put(\"favourites_count\", this.favourite_count);\n this.put(\"place_name\", this.place_name);\n this.put(\"place_id\", this.place_id);\n\n // add statistic/calculated data\n if (calculatedData) {\n\n // text length\n this.put(\"text_length\", this.text.length());\n\n // location data\n if (this.place_context != null) this.put(\"place_context\", this.place_context.name());\n if (this.place_country != null && this.place_country.length() == 2) {\n this.put(\"place_country\", DAO.geoNames.getCountryName(this.place_country));\n this.put(\"place_country_code\", this.place_country);\n this.put(\"place_country_center\", DAO.geoNames.getCountryCenter(this.place_country));\n }\n\n // add optional location data. This is written even if calculatedData == false if\n // the source is from REPORT to prevent that it is lost\n if (this.location_point != null && this.location_point.length == 2\n && this.location_mark != null && this.location_mark.length == 2) {\n // reference for this format:\n // https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-geo-point-type.html#_lat_lon_as_array_5\n this.put(\"location_point\", this.location_point); // [longitude, latitude]\n this.put(\"location_radius\", this.location_radius);\n this.put(\"location_mark\", this.location_mark);\n this.put(\"location_source\", this.location_source.name());\n }\n\n // redundant data for enhanced navigation with aggregations\n this.put(\"hosts\", this.hosts);\n this.put(\"hosts_count\", this.hosts.size());\n this.put(\"links\", this.links);\n this.put(\"links_count\", this.links.size());\n this.put(\"unshorten\", tlm.short2long);\n this.put(\"images\", this.images);\n this.put(\"images_count\", this.images.size());\n this.put(\"audio\", this.audios);\n this.put(\"audio_count\", this.audios.size());\n this.put(\"videos\", this.videos);\n this.put(\"videos_count\", this.videos.size());\n this.put(\"mentions\", this.mentions);\n this.put(\"mentions_count\", this.mentions.size());\n this.put(\"hashtags\", this.hashtags);\n this.put(\"hashtags_count\", this.hashtags.size());\n\n // experimental, for ranking\n this.put(\"without_l_len\", this.without_l_len);\n this.put(\"without_lu_len\", this.without_lu_len);\n this.put(\"without_luh_len\", this.without_luh_len);\n\n // text classifier\n if (this.moreData.classifier != null) {\n for (Map.Entry<Context, Classification<String, Category>> c: this.moreData.classifier.entrySet()) {\n assert c.getValue() != null;\n // we don't store non-existing classifications\n if (c.getValue().getCategory() == Classifier.Category.NONE) continue;\n this.put(\"classifier_\" + c.getKey().name(), c.getValue().getCategory());\n this.put(\"classifier_\" + c.getKey().name() + \"_probability\",\n c.getValue().getProbability() == Float.POSITIVE_INFINITY\n ? Float.MAX_VALUE : c.getValue().getProbability());\n }\n }\n } else {\n this.remove(\"text_length\");\n this.remove(\"place_context\");\n this.remove(\"place_country\");\n this.remove(\"place_country_code\");\n this.remove(\"place_country_center\");\n this.remove(\"location_point\");\n this.remove(\"location_radius\");\n this.remove(\"location_mark\");\n this.remove(\"location_source\");\n this.remove(\"hosts\");\n this.remove(\"hosts_count\");\n this.remove(\"links\");\n this.remove(\"links_count\");\n this.remove(\"unshorten\");\n this.remove(\"images\");\n this.remove(\"images_count\");\n this.remove(\"audio\");\n this.remove(\"audio_count\");\n this.remove(\"videos\");\n this.remove(\"videos_count\");\n this.remove(\"mentions\");\n this.remove(\"mentions_count\");\n this.remove(\"hashtags\");\n this.remove(\"hashtags_count\");\n this.remove(\"without_l_len\");\n this.remove(\"without_lu_len\");\n this.remove(\"without_luh_len\");\n if (this.moreData.classifier != null) {\n for (Map.Entry<Context, Classification<String, Category>> c: this.moreData.classifier.entrySet()) {\n this.remove(\"classifier_\" + c.getKey().name());\n this.remove(\"classifier_\" + c.getKey().name() + \"_probability\");\n }\n }\n }\n\n // add user\n if (user != null) this.put(\"user\", user.toJSON());\n return this;\n }\n\n public boolean willBeTimeConsuming() {\n return timeline_link_pattern.matcher(this.text).find();\n }\n\n public Object lazyGet(JSONObject json, String key) {\n try {\n Object o = json.get(key);\n return o;\n } catch (JSONException e) {\n return null;\n }\n }\n\n public UserEntry getUser() {\n return this.user;\n }\n\n public Date getTimestampDate() {\n return this.timestampDate == null ? new Date() : this.timestampDate;\n }\n\n public Date getCreatedAt() {\n return this.created_at == null ? new Date() : this.created_at;\n }\n\n public void setCreatedAt(Date created_at) {\n this.created_at = created_at;\n }\n\n public Date getOn() {\n return this.on;\n }\n\n public void setOn(Date on) {\n this.on = on;\n }\n\n public Date getTo() {\n return this.to;\n }\n\n public void setTo(Date to) {\n this.to = to;\n }\n\n public SourceType getSourceType() {\n return this.source_type;\n }\n\n public void setSourceType(SourceType source_type) {\n this.source_type = source_type;\n }\n\n public ProviderType getProviderType() {\n return provider_type;\n }\n\n public void setProviderType(ProviderType provider_type) {\n this.provider_type = provider_type;\n }\n\n public String getProviderHash() {\n return provider_hash;\n }\n\n public void setProviderHash(String provider_hash) {\n this.provider_hash = provider_hash;\n }\n\n public String getScreenName() {\n return screen_name;\n }\n\n public void setScreenName(String user_screen_name) {\n this.screen_name = user_screen_name;\n }\n\n public String getRetweetFrom() {\n return this.retweet_from;\n }\n\n public void setRetweetFrom(String retweet_from) {\n this.retweet_from = retweet_from;\n }\n\n public URL getStatusIdUrl() {\n return this.status_id_url;\n }\n\n public void setStatusIdUrl(URL status_id_url) {\n this.status_id_url = status_id_url;\n }\n\n public long getRetweetCount() {\n return retweet_count;\n }\n\n public void setRetweetCount(long retweet_count) {\n this.retweet_count = retweet_count;\n }\n\n public long getFavouritesCount() {\n return this.favourite_count;\n }\n\n public void setFavouritesCount(long favourites_count) {\n this.favourite_count = favourites_count;\n }\n\n public String getPlaceName() {\n return place_name;\n }\n\n public void setPlaceName(String place_name, PlaceContext place_context) {\n this.place_name = place_name;\n this.place_context = place_context;\n }\n\n public PlaceContext getPlaceContext () {\n return place_context;\n }\n\n public String getPlaceId() {\n return place_id;\n }\n\n public void setPlaceId(String place_id) {\n this.place_id = place_id;\n }\n\n /**\n * @return [longitude, latitude]\n */\n public double[] getLocationPoint() {\n return location_point;\n }\n\n /**\n * set the location\n * @param location_point in the form [longitude, latitude]\n */\n public void setLocationPoint(double[] location_point) {\n this.location_point = location_point;\n }\n\n public String getPostId() {\n return String.valueOf(this.postId);\n }\n\n //TODO: to implement this method\n private void setPostId() {\n this.postId = String.valueOf(this.timestamp) + String.valueOf(this.created_at.getTime());\n }\n\n /**\n * @return [longitude, latitude] which is inside of getLocationRadius() from getLocationPoint()\n */\n public double[] getLocationMark() {\n return location_mark;\n }\n\n /**\n * Set the location\n * @param location_point in the form [longitude, latitude]\n */\n public void setLocationMark(double[] location_mark) {\n this.location_mark = location_mark;\n }\n\n /**\n * Get the radius in meter\n * @return radius in meter around getLocationPoint() (NOT getLocationMark())\n */\n public int getLocationRadius() {\n return location_radius;\n }\n\n public void setLocationRadius(int location_radius) {\n this.location_radius = location_radius;\n }\n\n public LocationSource getLocationSource() {\n return location_source;\n }\n\n public void setLocationSource(LocationSource location_source) {\n this.location_source = location_source;\n }\n\n public String getText() {\n return this.text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n public int getTextLength() {\n return this.text.length();\n }\n\n public long getId() {\n return Long.parseLong(this.postId);\n }\n\n public List<String> getHosts() {\n return this.hosts;\n }\n\n public Set<String> getVideos() {\n return this.videos;\n }\n\n public Set<String> getAudio() {\n return this.audios;\n }\n\n public Set<String> getImages() {\n return this.images;\n }\n\n public void setImages(String image) {\n if(this.images == null) {\n this.images = new HashSet<String>();\n }\n this.images.add(image);\n }\n\n public String[] getMentions() {\n if(this.mentions == null) {\n return new String[0];\n }\n return this.mentions.toArray(new String[0]);\n }\n\n public String[] getHashtags() {\n return this.hashtags.toArray(new String[0]);\n }\n\n public String[] getLinks() {\n return this.links.toArray(new String[0]);\n }\n\n public Classifier.Category getClassifier(Classifier.Context context) {\n return this.moreData.getClassifier(context);\n }\n\n}",
"public interface JsonFactory {\n\n public String getString() throws IOException;\n public JSONObject getJSON() throws IOException;\n\n}",
"public class JsonStreamReader implements JsonReader {\r\n\r\n private ArrayBlockingQueue<JsonFactory> jsonline;\r\n private InputStream inputStream;\r\n private int concurrency;\r\n private String name;\r\n\r\n public JsonStreamReader(InputStream inputStream, String name, int concurrency) {\r\n this.jsonline = new ArrayBlockingQueue<>(1000);\r\n this.inputStream = inputStream;\r\n this.name = name;\r\n this.concurrency = concurrency;\r\n }\r\n \r\n public String getName() {\r\n return this.name;\r\n }\r\n \r\n public int getConcurrency() {\r\n return this.concurrency;\r\n }\r\n \r\n public JsonFactory take() throws InterruptedException {\r\n return this.jsonline.take();\r\n }\r\n \r\n public static class WrapperJsonFactory implements JsonFactory {\r\n private JSONObject json;\r\n private String original;\r\n private WrapperJsonFactory(final String original, final JSONObject json) {\r\n this.original = original;\r\n this.json = json;\r\n }\r\n\r\n @Override\r\n public String getString() throws IOException {\r\n return this.original;\r\n }\r\n @Override\r\n public JSONObject getJSON() throws IOException {\r\n return this.json;\r\n }\r\n }\r\n\r\n public void run() {\r\n BufferedReader br = null;\r\n try {\r\n String line;\r\n br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));\r\n while ((line = br.readLine()) != null) {\r\n try {\r\n JSONObject json = new JSONObject(line);\r\n this.jsonline.put(new WrapperJsonFactory(line, json));\r\n } catch (Throwable e) {\r\n \tDAO.severe(e);\r\n }\r\n }\r\n } catch (IOException e) {\r\n \tDAO.severe(e);\r\n } finally {\r\n try {\r\n if (br != null) br.close();\r\n } catch (IOException e) {\r\n \tDAO.severe(e);\r\n }\r\n }\r\n for (int i = 0; i < this.concurrency; i++) {\r\n try {this.jsonline.put(JsonReader.POISON_JSON_MAP);} catch (InterruptedException e) {}\r\n }\r\n }\r\n \r\n}\r"
] | import java.util.concurrent.atomic.AtomicLong;
import org.json.JSONObject;
import org.loklak.data.DAO;
import org.loklak.harvester.TwitterScraper.TwitterTweet;
import org.loklak.tools.storage.JsonFactory;
import org.loklak.tools.storage.JsonReader;
import org.loklak.tools.storage.JsonStreamReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap; | /**
* DumpProcessConversation
* Copyright 18.04.2018 by Michael Peter Christen, @0rb1t3r
*
* 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 program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.loklak;
public class DumpProcessConversation extends Thread {
private boolean shallRun = true, isBusy = false;
private int count = Integer.MAX_VALUE;
public DumpProcessConversation(int count) {
this.count = count;
}
/**
* ask the thread to shut down
*/
public void shutdown() {
this.shallRun = false;
this.interrupt();
DAO.log("catched ProcessConversation termination signal");
}
public boolean isBusy() {
return this.isBusy;
}
@Override
public void run() {
Set<File> processedFiles = new HashSet<>();
// work loop
loop: while (this.shallRun) try {
this.isBusy = false;
// scan dump input directory to import files
Collection<File> dumps = DAO.message_dump.getOwnDumps(this.count);
File dump = null;
select: for (File d: dumps) {
if (processedFiles.contains(d)) continue select;
dump = d; break;
}
if (dump == null) {
Thread.currentThread();
Thread.sleep(10000);
continue loop;
}
this.isBusy = true;
// take only one file and process this file
final JsonReader dumpReader = DAO.message_dump.getDumpReader(dump);
final AtomicLong tweetcount = new AtomicLong(0);
DAO.log("started scan of dump file " + dump.getAbsolutePath());
// aggregation object
Map<String, Map<Long, TwitterTweet>> usertweets = new ConcurrentHashMap<>();
// we start concurrent indexing threads to process the json objects
Thread[] indexerThreads = new Thread[dumpReader.getConcurrency()];
for (int i = 0; i < dumpReader.getConcurrency(); i++) {
indexerThreads[i] = new Thread() {
public void run() { | JsonFactory tweet; | 3 |
coverity/pie | pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/fact/PermissionActionFactMetaData.java | [
"public class EqualityStringMatcher implements StringMatcher {\n \n private static final EqualityStringMatcher instance = new EqualityStringMatcher();\n \n private EqualityStringMatcher() {\n }\n \n public static EqualityStringMatcher getInstance() {\n return instance;\n }\n\n @Override\n public boolean matches(String matcher, String matchee) {\n return matcher.equals(matchee);\n }\n\n}",
"public interface FactMetaData {\n /**\n * Returns a StringCollapser appropriate for this fact's semantics. The behavior of the StringCollapser may behave\n * according to particulars of the policyConfig argument.\n *\n * @param policyConfig The policy's configuration, which may have directives relevant to this type of fact.\n * @return The StringCollapser instance appropriate for this fact.\n */\n public StringCollapser getCollapser(PolicyConfig policyConfig);\n\n /**\n * This decides if a concrete instance of a fact matches a fact definition from the security policy.\n * @param matcher The security policy's fact.\n * @param matchee The concrete instance of a fact.\n * @return Whether or not the security policy's fact applies to the instance of a fact.\n */\n public boolean matches(String matcher, String matchee);\n\n /**\n * Gets the metadata object associated with the child fact. The particular semantics of the child may depend on the\n * concrete instance of the fact being handled. For instance, with the Java SecurityManager, the semantics of child\n * facts of a java.io.FilePermission (which represent file paths) are distinct from the child facts of a\n * java.net.SocketPermission (which represent hosts).\n * @param fact The concrete value of the fact for which child metadata is desired.\n * @return The child metadata.\n */\n public FactMetaData getChildFactMetaData(String fact);\n}",
"public class NullStringCollapser implements StringCollapser {\n\n private static final NullStringCollapser instance = new NullStringCollapser();\n \n private NullStringCollapser() {\n }\n \n public static NullStringCollapser getInstance() {\n return instance;\n }\n \n @Override\n public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) {\n return input;\n }\n \n}",
"public class PolicyConfig {\n private final String name;\n private final PieConfig pieConfig;\n \n public PolicyConfig(String name, PieConfig pieConfig) {\n this.name = name;\n this.pieConfig = pieConfig;\n }\n \n public boolean isEnabled() {\n return getBoolean(\"isEnabled\", true);\n }\n \n public boolean isReportOnlyMode() {\n return getBoolean(\"isReportOnlyMode\", true);\n }\n\n public boolean isCollapseEnabled() {\n return getBoolean(\"isCollapseEnabled\", true);\n }\n \n public URL getPolicyFile() {\n String policyFile = getProperty(\"policyFile\");\n if (policyFile != null) {\n try {\n return new URL(policyFile);\n } catch (MalformedURLException e) {\n throw new IllegalStateException(\"Invalid policy URL: \" + policyFile);\n }\n }\n URL resource = this.getClass().getClassLoader().getResource(name + \".policy\");\n if (resource != null) {\n return resource;\n }\n String catalinaHome = System.getProperty(\"catalina.home\");\n if (catalinaHome != null) {\n try {\n return new File(catalinaHome + File.separatorChar + \"conf\" + File.separatorChar + name + \".policy\").toURI().toURL();\n } catch (MalformedURLException e) {\n throw new IllegalStateException(\"Could not build default policy file path.\");\n }\n }\n \n // Default to file in the CWD\n try {\n return new File(name + \".policy\").toURI().toURL();\n } catch (MalformedURLException e) {\n throw new RuntimeException(e);\n }\n }\n \n public boolean getBoolean(String prop, boolean defaultValue) {\n String v = getProperty(prop);\n if (v == null) {\n return defaultValue;\n }\n return Boolean.parseBoolean(v);\n }\n public int getInteger(String prop, int defaultValue) {\n String v = getProperty(prop);\n if (v == null) {\n return defaultValue;\n }\n return Integer.parseInt(v);\n }\n \n \n public String getProperty(String name) {\n return pieConfig.getProperties().getProperty(this.name + \".\" + name);\n }\n}",
"public interface StringCollapser {\n /**\n * Collapses a security policy according to the concrete implementation's rules. It takes a map from facts to their\n * children, and returns a collapsed version of that map. For example, given the map:\n * {\n * A => {'X', 'Y'},\n * B => {'Z'}\n * }\n *\n * If the implementation determines that the facts A and B should be collapsed to fact C, then this would return\n * {\n * C => {'X', 'Y', 'Z'}\n * }\n *\n * @param input A map from facts to a collection of child facts.\n * @param <T> The type of the child facts; irrelevant to the internal procedure of collapsing.\n * @return The collapsed map of facts to their children.\n */\n public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input);\n}",
"public class UnsupportedFactMetaData implements FactMetaData {\n\n private static final UnsupportedFactMetaData instance = new UnsupportedFactMetaData();\n \n private UnsupportedFactMetaData() {\n }\n \n public static UnsupportedFactMetaData getInstance() {\n return instance;\n }\n \n @Override\n public StringCollapser getCollapser(PolicyConfig policyConfig) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean matches(String matcher, String matchee) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public FactMetaData getChildFactMetaData(String fact) {\n throw new UnsupportedOperationException();\n }\n\n}"
] | import com.coverity.security.pie.core.EqualityStringMatcher;
import com.coverity.security.pie.core.FactMetaData;
import com.coverity.security.pie.core.NullStringCollapser;
import com.coverity.security.pie.core.PolicyConfig;
import com.coverity.security.pie.core.StringCollapser;
import com.coverity.security.pie.core.UnsupportedFactMetaData; | package com.coverity.security.pie.policy.securitymanager.fact;
public class PermissionActionFactMetaData implements FactMetaData {
private static final PermissionActionFactMetaData instance = new PermissionActionFactMetaData();
private PermissionActionFactMetaData() {
}
public static PermissionActionFactMetaData getInstance() {
return instance;
}
@Override
public StringCollapser getCollapser(PolicyConfig policyConfig) {
return NullStringCollapser.getInstance();
}
@Override
public boolean matches(String matcher, String matchee) { | return EqualityStringMatcher.getInstance().matches(matcher, matchee); | 0 |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/actions/SearchInFilesAction.java | [
"public class TreeListener extends MouseAdapter implements TreeSelectionListener, TreeWillExpandListener,\n KeyListener, ObserverInterface<MsgTopic> {\n\n private static final Logger logger = LogManager.getLogger(TreeListener.class);\n private static final PluginWorkspace workspace = PluginWorkspaceProvider.getPluginWorkspace();\n\n private final ArgonTree tree;\n private final DefaultTreeModel treeModel;\n private TreePath path;\n private TreeNode node;\n private boolean showErrorMessages = true;\n private boolean newExpandEvent;\n private boolean singleClick = true;\n private boolean doubleClickExpandEnabled = true;\n private Timer timer;\n private final ArgonPopupMenu contextMenu;\n\n public TreeListener(ArgonTree tree, TreeModel treeModel, ArgonPopupMenu contextMenu) {\n this.tree = tree;\n this.treeModel = (DefaultTreeModel) treeModel;\n this.newExpandEvent = true;\n this.contextMenu = contextMenu;\n final ActionListener actionListener = e -> {\n timer.stop();\n if (singleClick) {\n singleClickHandler(e);\n } else {\n try {\n doubleClickHandler(e);\n } catch (ParseException ex) {\n logger.error(ex);\n }\n }\n };\n final int doubleClickDelay = 300;\n timer = new javax.swing.Timer(doubleClickDelay, actionListener);\n timer.setRepeats(false);\n }\n\n public void setShowErrorMessages(boolean show) {\n showErrorMessages = show;\n }\n\n /*\n * methods of MouseAdapter\n */\n\n @Override\n public void mouseClicked(MouseEvent e) {\n if (e.getClickCount() == 1) {\n singleClick = true;\n timer.start();\n } else {\n singleClick = false;\n }\n }\n\n\n private static boolean isRightClick(MouseEvent e) {\n return (e.getButton()==MouseEvent.BUTTON3 ||\n (System.getProperty(\"os.name\").contains(\"Mac OS\") &&\n (e.getModifiers() & InputEvent.BUTTON1_MASK) != 0 &&\n (e.getModifiers() & InputEvent.CTRL_MASK) != 0));\n }\n\n\n @Override\n public void mousePressed(MouseEvent e) {\n path = tree.getPathForLocation(e.getX(), e.getY());\n try {\n if (path != null) {\n node = (TreeNode) path.getLastPathComponent();\n }\n } catch (NullPointerException er) {\n er.printStackTrace();\n }\n if (e.isPopupTrigger()) {\n contextMenu.show(e.getComponent(), e.getX(), e.getY(), path);\n }\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n path = tree.getPathForLocation(e.getX(), e.getY());\n try {\n if (path != null) {\n node = (TreeNode) path.getLastPathComponent();\n }\n } catch (NullPointerException er) {\n er.printStackTrace();\n }\n // if (e.isPopupTrigger()) {\n if (isRightClick(e)) {\n contextMenu.show(e.getComponent(), e.getX(), e.getY(), path);\n }\n }\n\n\n /*\n * methods of interface TreeSelectionListener\n */\n\n @Override\n public void valueChanged(TreeSelectionEvent e) {\n path = e.getNewLeadSelectionPath();\n node = (TreeNode) tree.getLastSelectedPathComponent();\n }\n\n\n /*\n * methods of interface TreeWillExpandListener\n */\n\n @Override\n public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {\n // method is called twice, if new data is loaded--prevent database check in 2nd call\n final boolean newTreeExpandEvent = this.newExpandEvent;\n path = event.getPath();\n node = (TreeNode) path.getLastPathComponent();\n int depth = path.getPathCount();\n if (depth > 1 && node.getAllowsChildren() && this.newExpandEvent) {\n final BaseXSource source = TreeUtils.sourceFromTreePath(path);\n String db_path;\n if (depth > 2) { // get path in source\n db_path = (((String) ((ArgonTreeNode) node).getTag()).split(\":/*\"))[1] + \"/\";\n } else {\n db_path = \"\";\n }\n\n List<BaseXResource> childList;\n try {\n childList = ConnectionWrapper.list(source, db_path);\n } catch (Exception er) {\n childList = new ArrayList<>();\n logger.debug(er);\n String error = er.getMessage();\n if (error == null || error.equals(\"\")) {\n error = \"Database connection could not be established.\";\n }\n if (showErrorMessages) {\n workspace.showInformationMessage(Lang.get(Lang.Keys.warn_failedlist) + \"\\n\" + error);\n }\n }\n\n if (updateExpandedNode((MutableTreeNode) node, childList)) {\n this.newExpandEvent = false;\n tree.expandPath(path);\n }\n\n }\n if (!newTreeExpandEvent) {\n this.newExpandEvent = true;\n }\n }\n\n @Override\n public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {\n }\n\n\n /*\n * methods for MouseAdapter\n */\n\n private void singleClickHandler(ActionEvent e) {\n logger.debug(\"-- single click --\");\n }\n\n private void doubleClickHandler(ActionEvent e) throws ParseException {\n logger.debug(\"-- double click --\");\n TreePath[] paths = tree.getSelectionPaths();\n if (paths != null) {\n for (TreePath path : paths) {\n if (((TreeNode) path.getLastPathComponent()).getAllowsChildren()) {\n if (doubleClickExpandEnabled) {\n try {\n treeWillExpand(new TreeExpansionEvent(this, path));\n } catch (ExpandVetoException eve) {\n logger.debug(\"Expand Veto: \", eve.getMessage());\n }\n }\n } else {\n doubleClickAction(path);\n }\n }\n }\n }\n\n // made public for access with AspectJ\n @SuppressWarnings(\"all\")\n public static void doubleClickAction(TreePath path) {\n //String db_path = ((ArgonTreeNode) path.getLastPathComponent()).getTag();\n final String dbPath = TreeUtils.urlStringFromTreePath(path);\n WorkspaceUtils.openURLString(dbPath);\n }\n\n /*\n * method for interface Observer\n */\n\n @Override\n public void update(MsgTopic type, Object... message) {\n // is notified as observer when changes have been made to the database file structure\n // updates the tree if necessary\n TreeNode currNode;\n TreePath currPath;\n\n logger.info(\"Tree needs to update: \" + message[0]);\n\n if (type instanceof SaveFileEvent || type instanceof NewDirEvent) {\n String[] protocol = ((String) message[0]).split(\":/*\");\n String[] path = protocol[1].split(\"/\");\n currPath = new TreePath(treeModel.getRoot());\n switch (protocol[0]) {\n// case ArgonConst.ARGON_REPO:\n// currPath = TreeUtils.pathByAddingChildAsStr(currPath, Lang.get(Lang.Keys.tree_repo));\n// break;\n// case ArgonConst.ARGON_XQ:\n// currPath = TreeUtils.pathByAddingChildAsStr(currPath, Lang.get(Lang.Keys.tree_restxq));\n// break;\n default:\n currPath = TreeUtils.pathByAddingChildAsStr(currPath, Lang.get(Lang.Keys.tree_DB));\n }\n currNode = (TreeNode) currPath.getLastPathComponent();\n boolean expanded = false;\n Boolean isFile;\n for (int i = 0; i < path.length; i++) {\n if (tree.isExpanded(currPath)) expanded = true;\n if (expanded || (i == path.length - 1)) { // update tree now only if file is in visible path\n if (TreeUtils.isNodeAsStrChild(currNode, path[i]) == -1) {\n isFile = (i + 1 == path.length) && type instanceof SaveFileEvent;\n TreeUtils.insertStrAsNodeLexi(treeModel, path[i], (DefaultMutableTreeNode) currNode, isFile);\n treeModel.reload(currNode);\n }\n currPath = TreeUtils.pathByAddingChildAsStr(currPath, path[i]);\n currNode = (DefaultMutableTreeNode) currPath.getLastPathComponent();\n } else {\n break;\n }\n }\n }\n }\n\n /*\n * other methods\n */\n\n public void setDoubleClickExpand(boolean expand) {\n doubleClickExpandEnabled = expand;\n }\n\n private boolean updateExpandedNode(MutableTreeNode node, List<BaseXResource> newChildrenList) {\n final Set<String> childrenValues = newChildrenList.stream()\n .map(child -> child.name)\n .collect(Collectors.toSet());\n\n DefaultMutableTreeNode newChild;\n final List<String> oldChildren = new ArrayList<>();\n String oldChild;\n boolean treeChanged = false;\n\n // check whether old children are in new list and vice versa\n if (node.getChildCount() > 0) {\n boolean[] inNewList = new boolean[node.getChildCount()];\n if (newChildrenList.size() > 0) {\n for (int i = 0; i < node.getChildCount(); i++) {\n final DefaultMutableTreeNode currNode = (DefaultMutableTreeNode) node.getChildAt(i);\n oldChild = currNode.getUserObject().toString();\n oldChildren.add(oldChild);\n if (childrenValues.contains(oldChild)) {\n inNewList[i] = true;\n }\n }\n }\n for (int i = node.getChildCount() - 1; i > -1; i--) {\n if (!inNewList[i]) {\n treeModel.removeNodeFromParent((MutableTreeNode) node.getChildAt(i));\n treeModel.nodeChanged(node);\n treeChanged = true;\n }\n }\n }\n if (node.getChildCount() == 0) { // if old list was empty skip lexicographic insert (faster)\n for (BaseXResource newPossibleChild : newChildrenList) {\n final String url = ((ArgonTreeNode) node).getTag().toString() + \"/\" + newPossibleChild.name;\n newChild = ClassFactory.getInstance().getTreeNode(newPossibleChild.name, url);\n newChild.setAllowsChildren(newPossibleChild.type == BaseXType.DIRECTORY);\n treeModel.insertNodeInto(newChild, node, node.getChildCount());\n treeChanged = true;\n }\n } else {\n for (BaseXResource newPossibleChild : newChildrenList) {\n if (!oldChildren.contains(newPossibleChild.name)) {\n TreeUtils.insertStrAsNodeLexi(treeModel, newPossibleChild.name, (DefaultMutableTreeNode) node,\n newPossibleChild.type != BaseXType.DIRECTORY);\n treeChanged = true;\n }\n }\n }\n return treeChanged;\n }\n\n public TreePath getPath() {\n return this.path;\n }\n\n public TreeNode getNode() {\n return this.node;\n }\n\n /*\n * methods for interface KeyListener\n */\n\n @Override\n public void keyTyped(KeyEvent e) {\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n int key = e.getKeyCode();\n switch (key) {\n case KeyEvent.VK_DELETE:\n new DeleteAction(tree).actionPerformed(null);\n break;\n case KeyEvent.VK_F5:\n new RefreshTreeAction(tree).actionPerformed(null);\n break;\n case KeyEvent.VK_ENTER:\n try {\n doubleClickHandler(null);\n } catch (ParseException pe) {\n // if URL raises exc eption, just ignore\n }\n break;\n case KeyEvent.VK_INSERT:\n if (TreeUtils.isDir(path) || TreeUtils.isDB(path) || TreeUtils.isFileSource(path)) {\n new AddNewFileAction(tree).actionPerformed(null);\n break;\n }\n if (TreeUtils.isDbSource(path)) {\n new AddDatabaseAction().actionPerformed(null);\n break;\n }\n break;\n default:\n }\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n }\n}",
"public class TreeUtils {\r\n\r\n private static final Logger logger = LogManager.getLogger(TreeUtils.class);\r\n\r\n static final int DEPTH_ROOT = 1;\r\n static final int DEPTH_SOURCE = 2;\r\n static final int DEPTH_DB = 3;\r\n\r\n private static TreeModel model;\r\n\r\n public static void init(TreeModel treeModel) {\r\n model = treeModel;\r\n }\r\n\r\n public static void insertStrAsNodeLexi(TreeModel treeModel, String child, DefaultMutableTreeNode parent, Boolean childIsFile) {\r\n final DefaultMutableTreeNode childNode = newChild(child, parent, childIsFile);\r\n boolean inserted = false;\r\n for (int i = 0; i < parent.getChildCount(); i++) {\r\n final DefaultMutableTreeNode currNode = (DefaultMutableTreeNode) parent.getChildAt(i);\r\n final Boolean nextIsFile = !currNode.getAllowsChildren();\r\n if (((currNode.getUserObject().toString().compareTo(child) > 0) && (nextIsFile.compareTo(childIsFile) == 0)) ||\r\n (nextIsFile.compareTo(childIsFile) > 0)) { // dirs before files\r\n ((DefaultTreeModel) treeModel).insertNodeInto(childNode, parent, i);\r\n inserted = true;\r\n break;\r\n }\r\n }\r\n if (!inserted) {\r\n ((DefaultTreeModel) treeModel).insertNodeInto(childNode, parent, parent.getChildCount());\r\n }\r\n }\r\n\r\n public static DefaultMutableTreeNode insertStrAsNodeLexi(String child, DefaultMutableTreeNode parent, Boolean childIsFile) {\r\n final DefaultMutableTreeNode childNode = newChild(child, parent, childIsFile);\r\n boolean inserted = false;\r\n for (int i = 0; i < parent.getChildCount(); i++) {\r\n final DefaultMutableTreeNode currNode = (DefaultMutableTreeNode) parent.getChildAt(i);\r\n final AtomicReference<Boolean> nextIsFile = new AtomicReference<>();\r\n nextIsFile.set(!currNode.getAllowsChildren());\r\n if (((currNode.getUserObject().toString().compareTo(child) > 0) && (nextIsFile.get().compareTo(childIsFile) == 0)) ||\r\n (nextIsFile.get().compareTo(childIsFile) > 0)) { // dirs before files\r\n parent.insert(childNode, i);\r\n inserted = true;\r\n break;\r\n }\r\n }\r\n if (!inserted) {\r\n parent.insert(childNode, parent.getChildCount());\r\n }\r\n return childNode;\r\n }\r\n\r\n private static DefaultMutableTreeNode newChild(String child, DefaultMutableTreeNode parent, Boolean childIsFile) {\r\n final String delim = (parent.getLevel() < DEPTH_SOURCE) ? \"\" : \"/\";\r\n final DefaultMutableTreeNode childNode = ClassFactory.getInstance().getTreeNode(child,\r\n ((ArgonTreeNode) parent).getTag().toString() + delim + child);\r\n if (childIsFile) {\r\n childNode.setAllowsChildren(false);\r\n } else {\r\n childNode.setAllowsChildren(true);\r\n }\r\n return childNode;\r\n }\r\n\r\n public static int isNodeAsStrChild(TreeNode parent, String child) {\r\n for (int i = 0; i < parent.getChildCount(); i++) {\r\n if (((DefaultMutableTreeNode) parent.getChildAt(i)).getUserObject().toString().equals(child)) {\r\n return i;\r\n }\r\n }\r\n return -DEPTH_ROOT;\r\n }\r\n\r\n public static TreePath pathByAddingChildAsStr(TreePath currPath, String child) {\r\n // returns TreePath to child given by String, if child doesn't exist returns null!\r\n final DefaultMutableTreeNode currNode = (DefaultMutableTreeNode) currPath.getLastPathComponent();\r\n int childNodeIndex = isNodeAsStrChild(currNode, child);\r\n if (childNodeIndex != -DEPTH_ROOT) {\r\n return new TreePath(((DefaultMutableTreeNode) currNode.getChildAt(childNodeIndex)).getPath());\r\n }\r\n return null;\r\n }\r\n\r\n public static TreePath pathFromURLString(String urlString) {\r\n TreePath path = new TreePath(model.getRoot());\r\n final BaseXSource source = CustomProtocolURLUtils.sourceFromURLString(urlString);\r\n switch (source) {\r\n// case REPO:\r\n// path = pathByAddingChildAsStr(path, Lang.get(Lang.Keys.tree_repo));\r\n// break;\r\n// case RESTXQ:\r\n// path = pathByAddingChildAsStr(path, Lang.get(Lang.Keys.tree_restxq));\r\n// break;\r\n default:\r\n path = pathByAddingChildAsStr(path, Lang.get(Lang.Keys.tree_DB));\r\n }\r\n final String[] protocolResource = urlString.split(\":/*\");\r\n if (protocolResource.length > DEPTH_ROOT) {\r\n String[] pathParts = protocolResource[DEPTH_ROOT].split(\"/\");\r\n for (String res : pathParts) {\r\n path = pathByAddingChildAsStr(path, res);\r\n }\r\n }\r\n return path;\r\n }\r\n\r\n public static BaseXSource sourceFromTreePath(TreePath path) {\r\n if (path.getPathCount() > DEPTH_ROOT) {\r\n final String sourceStr = path.getPathComponent(DEPTH_ROOT).toString();\r\n if (sourceStr.equals(Lang.get(Lang.Keys.tree_DB))) {\r\n return BaseXSource.DATABASE;\r\n }\r\n// if (sourceStr.equals(Lang.get(Lang.Keys.tree_restxq)))\r\n// return BaseXSource.RESTXQ;\r\n if (sourceStr.equals(Lang.get(Lang.Keys.tree_repo))) {\r\n return BaseXSource.REPO;\r\n }\r\n return null;\r\n } else {\r\n return null;\r\n }\r\n }\r\n\r\n public static String protocolFromTreePath(TreePath path) {\r\n if (path.getPathCount() > DEPTH_ROOT) {\r\n final String sourceStr = path.getPathComponent(DEPTH_ROOT).toString();\r\n if (sourceStr.equals(Lang.get(Lang.Keys.tree_DB))) {\r\n return ArgonConst.ARGON;\r\n }\r\n// if (sourceStr.equals(Lang.get(Lang.Keys.tree_restxq)))\r\n// return ArgonConst.ARGON_XQ;\r\n if (sourceStr.equals(Lang.get(Lang.Keys.tree_repo))) {\r\n return ArgonConst.ARGON_REPO;\r\n }\r\n return null;\r\n } else {\r\n return null;\r\n }\r\n }\r\n\r\n public static String resourceFromTreePath(TreePath path) {\r\n final StringBuilder resource = new StringBuilder();\r\n if (path.getPathCount() > DEPTH_ROOT) {\r\n for (int i = DEPTH_SOURCE; i < path.getPathCount(); i++) {\r\n if (i > DEPTH_SOURCE) {\r\n resource.append('/');\r\n }\r\n resource.append(path.getPathComponent(i).toString());\r\n }\r\n }\r\n return resource.toString();\r\n }\r\n\r\n public static String urlStringFromTreePath(TreePath path) {\r\n final StringBuilder db_path;\r\n// if (path.getPathComponent(1).toString().equals(Lang.get(Lang.Keys.tree_restxq)))\r\n// db_path = new StringBuilder(ArgonConst.ARGON_XQ + \":\");\r\n// else\r\n// if (path.getPathComponent(1).toString().equals(Lang.get(Lang.Keys.tree_repo)))\r\n// db_path = new StringBuilder(ArgonConst.ARGON_REPO + \":\");\r\n// else\r\n db_path = new StringBuilder(ArgonConst.ARGON + \":\");\r\n for (int i = DEPTH_SOURCE; i < path.getPathCount(); i++) {\r\n if (i > DEPTH_SOURCE) {\r\n db_path.append('/');\r\n }\r\n db_path.append(path.getPathComponent(i).toString());\r\n }\r\n return db_path.toString();\r\n }\r\n\r\n public static String treeStringFromTreePath(TreePath path) {\r\n final StringBuilder db_path = new StringBuilder(Lang.get(Lang.Keys.tree_root));\r\n for (int i = DEPTH_ROOT; i < path.getPathCount(); i++) {\r\n db_path.append(\"/\").append(path.getPathComponent(i).toString());\r\n }\r\n return db_path.toString();\r\n }\r\n\r\n public static String urlStringFromTreeString(String treeString) {\r\n final String[] components = treeString.split(\"/\");\r\n final StringBuilder db_path;\r\n\r\n if (components.length > DEPTH_SOURCE) {\r\n// if (components[1].equals(Lang.get(Lang.Keys.tree_restxq)))\r\n// db_path = new StringBuilder(ArgonConst.ARGON_XQ + \":\");\r\n// else\r\n// if (components[1].equals(Lang.get(Lang.Keys.tree_repo)))\r\n// db_path = new StringBuilder(ArgonConst.ARGON_REPO + \":\");\r\n// else\r\n db_path = new StringBuilder(ArgonConst.ARGON + \":\");\r\n db_path.append(treeString.substring(components[0].length() + components[DEPTH_ROOT].length() + DEPTH_SOURCE));\r\n } else {\r\n db_path = new StringBuilder(\"\");\r\n }\r\n return db_path.toString();\r\n }\r\n\r\n public static String fileStringFromPathString(String path) {\r\n if (path.equals(\"\") || path.endsWith(\"/\") || path.endsWith(\"\\\\\")) {\r\n return \"\";\r\n } else {\r\n String[] nodes = path.split(\"\\\\\\\\|/\");\r\n return nodes[nodes.length - DEPTH_ROOT];\r\n }\r\n }\r\n\r\n public static TreePath pathToDepth(TreePath path, int depth) {\r\n TreePath returnPath = path;\r\n if (path.getPathCount() < depth) {\r\n return new TreePath(new Object[0]);\r\n } else {\r\n for (int i = path.getPathCount(); i > (depth + DEPTH_ROOT); i--) {\r\n returnPath = returnPath.getParentPath();\r\n }\r\n }\r\n return returnPath;\r\n }\r\n\r\n public static boolean isFile(TreePath path) {\r\n// logger.info(\"isFile \" + path);\r\n final DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();\r\n return (!node.getAllowsChildren());\r\n }\r\n\r\n public static boolean isDir(TreePath path) {\r\n// logger.info(\"isDir \" + path);\r\n final DefaultMutableTreeNode clickedNode = (DefaultMutableTreeNode) path.getLastPathComponent();\r\n final int pathCount = path.getPathCount();\r\n return (clickedNode.getAllowsChildren() &&\r\n (((pathCount > DEPTH_DB) &&\r\n (path.getPathComponent(DEPTH_ROOT).toString().equals(Lang.get(Lang.Keys.tree_DB)))) ||\r\n ((pathCount > DEPTH_SOURCE) &&\r\n (!path.getPathComponent(DEPTH_ROOT).toString().equals(Lang.get(Lang.Keys.tree_DB))))));\r\n }\r\n\r\n public static boolean isDB(TreePath path) {\r\n// logger.info(\"isDB \" + path);\r\n final int pathCount = path.getPathCount();\r\n return (pathCount == DEPTH_DB) &&\r\n (path.getPathComponent(DEPTH_ROOT).toString().equals(Lang.get(Lang.Keys.tree_DB)));\r\n }\r\n\r\n public static boolean isInDB(TreePath path) {\r\n// logger.info(\"isInDB \" + path);\r\n final int pathCount = path.getPathCount();\r\n return (pathCount > DEPTH_DB) &&\r\n (path.getPathComponent(DEPTH_ROOT).toString().equals(Lang.get(Lang.Keys.tree_DB)));\r\n }\r\n\r\n// public static boolean isInRestXQ(TreePath path) {\r\n// int pathCount = path.getPathCount();\r\n// return (pathCount > 2) &&\r\n// (path.getPathComponent(1).toString().equals(Lang.get(Lang.Keys.tree_restxq)));\r\n// }\r\n\r\n// public static boolean isInRepo(TreePath path) {\r\n// int pathCount = path.getPathCount();\r\n// return (pathCount > 2) &&\r\n// (path.getPathComponent(1).toString().equals(Lang.get(Lang.Keys.tree_repo)));\r\n// }\r\n\r\n public static boolean isSource(TreePath path) {\r\n// logger.info(\"isSource \" + path);\r\n final int pathCount = path.getPathCount();\r\n return (pathCount == DEPTH_SOURCE);\r\n }\r\n\r\n public static boolean isRoot(TreePath path) {\r\n// logger.info(\"isRoot \" + path);\r\n final int pathCount = path.getPathCount();\r\n return (pathCount == DEPTH_ROOT);\r\n }\r\n\r\n public static boolean isDbSource(TreePath path) {\r\n// logger.info(\"isDBSource \" + path);\r\n final int pathCount = path.getPathCount();\r\n return ((pathCount == DEPTH_SOURCE) && path.getPathComponent(DEPTH_ROOT).toString().equals(Lang.get(Lang.Keys.tree_DB)));\r\n }\r\n\r\n public static boolean isFileSource(TreePath path) {\r\n// logger.info(\"isFileSource \" + path);\r\n return (TreeUtils.isSource(path) && !path.getPathComponent(DEPTH_ROOT).toString().equals(Lang.get(Lang.Keys.tree_DB)));\r\n }\r\n\r\n public static boolean isWEBINF(TreePath path) {\r\n final DefaultMutableTreeNode clickedNode = (DefaultMutableTreeNode) path.getLastPathComponent();\r\n final int pathCount = path.getPathCount();\r\n return TreeUtils.isDir(path)\r\n && clickedNode.getUserObject().toString().equals(\"WEB-INF\")\r\n && (\r\n// ((pathCount == DEPTH_DB) && path.getPathComponent(1).toString().equals(Lang.get(Lang.Keys.tree_restxq))) ||\r\n ((pathCount == 5) && path.getPathComponent(DEPTH_ROOT).toString().equals(Lang.get(Lang.Keys.tree_DB)))\r\n );\r\n }\r\n\r\n}\r",
"public final class ConnectionWrapper {\n\n private static final Logger logger = LogManager.getLogger(ConnectionWrapper.class);\n\n private ConnectionWrapper() {\n }\n\n public static void init() {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.init();\n } catch (IOException | NullPointerException ex) {\n logger.debug(\"Argon initialization failed!\");\n }\n }\n\n public static void create(String db) throws IOException {\n String chop = ArgonOptionPage.getOption(ArgonOptionPage.KEY_BASEX_DB_CREATE_CHOP, false).toLowerCase();\n String ftindex = ArgonOptionPage.getOption(ArgonOptionPage.KEY_BASEX_DB_CREATE_FTINDEX, false).toLowerCase();\n String textindex = ArgonOptionPage.getOption(ArgonOptionPage.KEY_BASEX_DB_CREATE_TEXTINDEX, false).toLowerCase();\n String attrindex = ArgonOptionPage.getOption(ArgonOptionPage.KEY_BASEX_DB_CREATE_ATTRINDEX, false).toLowerCase();\n String tokenindex = ArgonOptionPage.getOption(ArgonOptionPage.KEY_BASEX_DB_CREATE_TOKENINDEX, false).toLowerCase();\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.create(db, chop, ftindex, textindex, attrindex, tokenindex);\n TopicHolder.newDir.postMessage(ArgonConst.ARGON + \":\" + db);\n } catch (NullPointerException ex) {\n String error = ex.getMessage();\n if ((error == null) || error.equals(\"null\"))\n throw new IOException(\"Database connection could not be established.\");\n }\n }\n\n public static void save(URL url, byte[] bytes) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(url, \"UTF-8\")) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(URL url, byte[] bytes, String encoding, boolean versionUp) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(url, encoding, versionUp)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(URL url, byte[] bytes, String encoding) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(url, encoding)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(String owner, URL url, byte[] bytes, String encoding) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(owner, url, encoding)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(String owner, boolean binary, URL url, byte[] bytes) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(owner, binary, url)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(boolean binary, URL url, byte[] bytes) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(binary, url)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(boolean binary, URL url, byte[] bytes, boolean versionUp) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(binary, url, versionUp)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static InputStream getInputStream(URL url) throws IOException {\n ByteArrayInputStream inputStream;\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n logger.info(\"Requested new InputStream: \" + url.toString());\n inputStream = new ByteArrayInputStream(connection.get(CustomProtocolURLUtils.sourceFromURL(url),\n CustomProtocolURLUtils.pathFromURL(url), false));\n } catch (NullPointerException npe) {\n logger.info(\"Error obtaining input stream from \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException io) {\n logger.debug(\"Failed to obtain InputStream: \", io.getMessage());\n throw new IOException(io);\n }\n return inputStream;\n }\n\n public static List<BaseXResource> list(BaseXSource source, String path) throws IOException {\n logger.info(\"list \" + source + \" \"+ path);\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n return connection.list(source, path);\n } catch (NullPointerException npe) {\n final PrintWriter buf = new PrintWriter(new StringWriter());\n npe.printStackTrace(buf);\n logger.info(\"Error listing path \" + path + \": no database connection : \" + buf.toString());\n throw new NoDatabaseConnectionException();\n }\n }\n\n /**\n * lists all resources in the path, including directories\n *\n * @param source source in which path resides\n * @param path path to list\n * @return list of all resources in path, entries contain full path as name, for databases without the database name\n * @throws IOException throws exception if connection returns an exception/error code\n */\n public static List<BaseXResource> listAll(BaseXSource source, String path) throws IOException {\n logger.info(\"listAll\" + source + \" \"+ path);\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n return connection.listAll(source, path);\n } catch (NullPointerException npe) {\n logger.info(\"Error listing path \" + path + \": no database connection\");\n throw new NoDatabaseConnectionException();\n }\n }\n\n public static boolean directoryExists(BaseXSource source, String path) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n List<BaseXResource> resourceList = connection.list(source, path);\n return (resourceList.size() != 0);\n } catch (NullPointerException npe) {\n logger.info(\"Error checking for directory \" + path + \": no database connection\");\n return true;\n } catch (IOException ioe) {\n return false;\n }\n }\n\n public static boolean isLocked(BaseXSource source, String path) {\n boolean isLocked = false;\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n if (connection.locked(source, path))\n isLocked = true;\n } catch (Throwable ie) {\n isLocked = true;\n logger.debug(\"Querying LOCKED returned: \", ie.getMessage());\n }\n return isLocked;\n }\n\n public static boolean isLockedByUser(BaseXSource source, String path) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n return connection.lockedByUser(source, path);\n } catch (Throwable ioe) {\n logger.debug(ioe);\n }\n return false;\n }\n\n public static void lock(BaseXSource source, String path) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.lock(source, path);\n } catch (Throwable ioe) {\n logger.error(\"Failed to lock resource \" + path + \" in \" + source.toString() + \": \" + ioe.getMessage());\n }\n }\n\n public static void unlock(BaseXSource source, String path) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.unlock(source, path);\n } catch (Throwable ioe) {\n logger.error(\"Failed to unlock resource \" + path + \" in \" + source.toString() + \": \" + ioe.getMessage());\n }\n }\n\n public static List<String> findFiles(BaseXSource source, String path, String filter, boolean caseSensitive) throws IOException {\n List<String> result;\n StringBuilder regEx = new StringBuilder(caseSensitive ? \"\" : \"(?i)\");\n for (int i = 0; i < filter.length(); i++) {\n char c = filter.charAt(i);\n switch (c) {\n case '*':\n regEx.append(\".*\");\n break;\n case '?':\n regEx.append('.');\n break;\n case '.':\n regEx.append(\"\\\\.\");\n break;\n default:\n regEx.append(c);\n }\n }\n String regExString = regEx.toString();\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n result = connection.search(source, path, regExString);\n for (int i = result.size() - 1; i > -1; i--) {\n String foundPath = result.get(i);\n String foundFile = TreeUtils.fileStringFromPathString(foundPath);\n Matcher matcher = Pattern.compile(regExString).matcher(foundFile);\n if (!matcher.find())\n result.remove(foundPath);\n }\n } catch (NullPointerException npe) {\n logger.error(\"Error searching for files: no database connection\");\n throw new NoDatabaseConnectionException();\n }\n return result;\n }\n\n public static List<String> parse(String path) throws IOException {\n List<String> result = new ArrayList<>();\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.parse(path);\n } catch (BaseXQueryException ex) {\n result.add(Integer.toString(ex.getLine()));\n result.add(Integer.toString(ex.getColumn()));\n result.add(ex.getInfo());\n }\n return result;\n }\n\n public static String query(String query, String[] parameter) throws IOException {\n return \"<response>\\n\" + sendQuery(query, parameter) + \"\\n</response>\";\n }\n\n private static String sendQuery(String query, String[] parameter) throws IOException {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n return connection.xquery(query, parameter);\n } catch (NullPointerException npe) {\n logger.info(\"Error sending query: no database connection\");\n throw new NoDatabaseConnectionException();\n }\n }\n\n private static List<String> searchInFiles(String query, String path, String filter, boolean wholeMatch, boolean exactCase)\n throws IOException {\n String[] parameter = {\"PATH\", path, \"FILTER\", filter, \"WHOLE\", Boolean.toString(wholeMatch),\n \"EXACTCASE\", Boolean.toString(exactCase)};\n String result = sendQuery(query, parameter);\n String db_name = (path.split(\"/\"))[0];\n final ArrayList<String> list = new ArrayList<>();\n if (!result.isEmpty()) {\n final String[] results = result.split(\"\\r?\\n\");\n for (String res : results) {\n list.add(\"argon:\" + db_name + \"/\" + res);\n }\n }\n return list;\n }\n\n public static List<String> searchAttributes(String path, String filter, boolean wholeMatch, boolean exactCase)\n throws IOException {\n return searchInFiles(ConnectionUtils.getQuery(\"search-attributes\"), path, filter, wholeMatch, exactCase);\n }\n\n public static List<String> searchAttributeValues(String path, String filter, boolean wholeMatch, boolean exactCase)\n throws IOException {\n return searchInFiles(ConnectionUtils.getQuery(\"search-attrvalues\"), path, filter, wholeMatch, exactCase);\n }\n\n public static List<String> searchElements(String path, String filter, boolean wholeMatch, boolean exactCase)\n throws IOException {\n return searchInFiles(ConnectionUtils.getQuery(\"search-elements\"), path, filter, wholeMatch, exactCase);\n }\n\n public static List<String> searchText(String path, String filter, boolean wholeMatch, boolean exactCase)\n throws IOException {\n return searchInFiles(ConnectionUtils.getQuery(\"search-text\"), path, filter, wholeMatch, exactCase);\n }\n\n public static boolean resourceExists(BaseXSource source, String resource) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n return connection.exists(source, resource);\n } catch (Throwable ioe) {\n logger.error(\"Failed to ask BaseX for existence of resource \" + resource + \": \" + ioe.getMessage());\n return false;\n }\n }\n\n public static boolean pathContainsLockedResource(BaseXSource source, String path) {\n byte[] lockFile;\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n lockFile = connection.get(BaseXSource.DATABASE, ArgonConst.ARGON_DB + \"/\" + ArgonConst.LOCK_FILE, false);\n Document dom = XMLUtils.docFromByteArray(lockFile);\n XPathExpression expression = XMLUtils.getXPathExpression(\"*//\" + source.toString());\n NodeList lockedResources = (NodeList) expression.evaluate(dom, XPathConstants.NODESET);\n String[] pathComponents = path.split(\"/\");\n for (int i = 0; i < lockedResources.getLength(); i++) {\n String[] resourceComponents = lockedResources.item(i).getTextContent().split(\"/\");\n if (resourceComponents.length >= pathComponents.length) {\n boolean isEqual = true;\n for (int k = 0; k < pathComponents.length; k++) {\n if (!pathComponents[k].equals(resourceComponents[k]))\n isEqual = false;\n }\n if (isEqual)\n return true;\n }\n }\n } catch (IOException ioe) {\n logger.error(\"Failed to obtain lock list: \" + ioe.getMessage());\n return true;\n } catch (ParserConfigurationException | SAXException | XPathExpressionException xe) {\n logger.error(\"Failed to parse lock file XML: \" + xe.getMessage());\n return true;\n } catch (Throwable t) {\n return true;\n }\n return false;\n }\n\n /**\n * Adds new directory. Side effect: for databases an empty file .empty.xml will be added in the new directory to make\n * the new directory persistent in the database.\n *\n * @param source BaseXSource in which new directory shall be added\n * @param path path of new directory\n */\n public static void newDir(BaseXSource source, String path) {\n if (source.equals(BaseXSource.DATABASE)) {\n String resource = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n<empty/>\";\n String urlString = source.getProtocol() + \":\" +\n path + \"/\" + ArgonConst.EMPTY_FILE;\n try {\n URL url = new URL(urlString);\n ConnectionWrapper.save(url, resource.getBytes(), \"UTF-8\");\n } catch (IOException e1) {\n logger.error(e1);\n }\n } else {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.newDir(source, path);\n } catch (Throwable io) {\n logger.error(\"Failed to create new directory: \" + io.getMessage());\n }\n }\n }\n\n}",
"public class DialogTools {\n\n public static void CenterDialogRelativeToParent(Dialog dialog) {\n Dimension dialogSize = dialog.getSize();\n Container parent = dialog.getParent();\n Dimension parentSize = parent.getSize();\n\n int dx = (parentSize.width - dialogSize.width) / 2;\n int dy = (parentSize.height - dialogSize.height) / 2;\n\n dialog.setLocation(parent.getX() + dx, parent.getY() + dy);\n }\n\n public static void wrapAndShow(JDialog dialog, JPanel content, JFrame parentFrame) {\n wrap(dialog, content, parentFrame);\n dialog.setVisible(true);\n }\n\n public static void wrapAndShow(JDialog dialog, JPanel content, JFrame parentFrame, int width, int height) {\n wrap(dialog, content, parentFrame);\n dialog.setSize(width, height);\n dialog.setVisible(true);\n }\n\n private static void wrap(JDialog dialog, JPanel content, JFrame parentFrame) {\n content.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));\n dialog.setContentPane(content);\n dialog.pack();\n dialog.setLocationRelativeTo(parentFrame);\n dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);\n }\n\n public static JDialog getOxygenDialog(JFrame parentFrame, String title) {\n JDialog dialog = new JDialog(parentFrame, title);\n dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);\n // ToDo: image from map\n dialog.setIconImage(ImageUtils.createImage(\"/images/Oxygen16.png\"));\n dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);\n return dialog;\n }\n\n}",
"public class Lang {\r\n\r\n private static final Logger logger = LogManager.getLogger(Lang.class);\r\n\r\n private static final String PATH = \"/Argon\";\r\n private static final String MISSING_KEY = \"missing_key:\";\r\n private static final String MISSING_RESOURCE = \"missing_resource:\";\r\n private static PluginResourceBundle bundle = null;\r\n\r\n private static final Map<Locale, Bundle> availableResourceBundles = new HashMap<>();\r\n static {\r\n loadBundle(Locale.GERMANY);\r\n loadBundle(Locale.UK);\r\n }\r\n private static Bundle currentBundle = availableResourceBundles.get(Locale.UK);\r\n\r\n public static void init() {\r\n init(Locale.UK);\r\n }\r\n\r\n public static void init(Locale locale) {\r\n setLocale(locale);\r\n }\r\n\r\n private static void loadBundle(final Locale locale) {\r\n try {\r\n final Bundle bundle = new Bundle(PATH, locale);\r\n availableResourceBundles.put(locale, bundle);\r\n } catch (final IOException ex) {\r\n logger.warn(\"Failed to read resource '\" + PATH + \"' for locale: '\" + locale + \"'\", ex);\r\n } catch (final NullPointerException ex) {\r\n logger.warn(\"Missing resource '\" + PATH + \"' for locale: '\" + locale + \"'\", ex);\r\n }\r\n }\r\n\r\n public static void setLocale(Locale locale) {\r\n if (locale.equals(Locale.GERMANY) || locale.equals(Locale.GERMAN)) {\r\n currentBundle = availableResourceBundles.get(Locale.GERMANY);\r\n } else {\r\n currentBundle = availableResourceBundles.get(Locale.UK);\r\n }\r\n }\r\n \r\n public static void init(StandalonePluginWorkspace wsa) {\r\n bundle = wsa.getResourceBundle();\r\n }\r\n\r\n public static String get(Keys key) {\r\n if (bundle != null) {\r\n return bundle.getMessage(key.name());\r\n }\r\n if (currentBundle != null) {\r\n String val = currentBundle.getString(key.name());\r\n if (val != null) {\r\n return val;\r\n } else {\r\n try {\r\n throw new RuntimeException();\r\n } catch (RuntimeException e) {\r\n logger.error(\"Missing key\", e);\r\n }\r\n return MISSING_KEY + key;\r\n }\r\n } else {\r\n try {\r\n throw new RuntimeException();\r\n } catch (RuntimeException e) {\r\n logger.error(\"Missing bundle\", e);\r\n }\r\n return MISSING_RESOURCE + key;\r\n }\r\n }\r\n\r\n public enum Keys {\r\n tree_root, tree_DB,\r\n tree_repo,\r\n// tree_restxq,\r\n cm_open, cm_checkout, cm_checkin, cm_adddb, cm_add, cm_addsimple,\r\n cm_addfile, cm_delete, cm_rename, cm_newversion, cm_showversion, cm_refresh, cm_search, cm_searchsimple, cm_find,\r\n cm_newdir, cm_save, cm_ok, cm_cancel, cm_tofile, cm_todb, cm_export, cm_checkinselected, cm_exit, cm_saveas,\r\n cm_replycomment,\r\n cm_runquery,\r\n cm_yes, cm_no, cm_all, cm_always, cm_never, cm_compare, cm_reset, cm_overwrite,\r\n cm_nosave,\r\n lbl_filename, lbl_filetype, lbl_filestocheck, lbl_delete, lbl_dir, lbl_searchpath, lbl_elements, lbl_text,\r\n lbl_attributes, lbl_attrbvalues, lbl_scope, lbl_options, lbl_whole, lbl_casesens, lbl_snippet,\r\n lbl_search1, lbl_search2, lbl_search3, lbl_search4, lbl_overwrite, lbl_version, lbl_revision, lbl_date, lbl_closed,\r\n lbl_connection, lbl_host, lbl_user, lbl_pwd, lbl_vcs, lbl_fe, lbl_dboptions, lbl_chop, lbl_ftindex, lbl_textindex,\r\n lbl_attributeindex, lbl_tokenindex, lbl_fixdefault, tt_fe,\r\n title_connection, title_connection2, title_history,\r\n warn_failednewdb, warn_failednewfile, warn_faileddeletedb, warn_faileddelete,\r\n warn_failedexport, warn_failednewversion, warn_norename, warn_resource, warn_storing, warn_locked, warn_nosnippet,\r\n warn_nofile, warn_failedsearch, warn_failedlist, warn_notransfer, warn_transfernoread,\r\n warn_transfernowrite1, warn_transfernowrite2, warn_connectionsettings1, warn_connectionsettings2, warn_settingspath1,\r\n warn_settingspath2, warn_settingspath3,\r\n msg_dbexists1, msg_dbexists2, msg_fileexists1, msg_fileexists2, msg_noquery, msg_noeditor, msg_checkpriordelete,\r\n msg_noupdate1, msg_noupdate2, msg_norename1, msg_norename2, msg_norename3, msg_transferlocked, msg_nameexists,\r\n msg_settingsexists, msg_noscopeselected,\r\n dlg_addfileinto, dlg_externalquery, dlg_checkedout, dlg_delete, dlg_newdir, dlg_replycomment, dlg_saveas, dlg_open,\r\n dlg_snippet, dlg_foundresources, dlg_overwrite, dlg_closed, dlg_overwritesetting, dlg_newsetting\r\n }\r\n\r\n}\r"
] | import de.axxepta.oxygen.tree.TreeListener;
import de.axxepta.oxygen.tree.TreeUtils;
import de.axxepta.oxygen.utils.ConnectionWrapper;
import de.axxepta.oxygen.utils.DialogTools;
import de.axxepta.oxygen.utils.Lang;
import ro.sync.ecss.extensions.api.component.AuthorComponentFactory;
import ro.sync.exml.workspace.api.PluginWorkspace;
import ro.sync.exml.workspace.api.PluginWorkspaceProvider;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | package de.axxepta.oxygen.actions;
/**
* @author Markus on 03.11.2016.
*/
public class SearchInFilesAction extends AbstractAction {
private static final PluginWorkspace workspace = PluginWorkspaceProvider.getPluginWorkspace();
private final JTree tree;
private String path = "";
private JDialog searchDialog;
private JTextField searchTermTextField;
private JCheckBox elementCheckBox;
private JCheckBox textCheckBox;
private JCheckBox attributeCheckBox;
private JCheckBox attrValueCheckBox;
private JCheckBox wholeCheckBox;
private JCheckBox caseCheckBox;
private JFrame parentFrame;
public SearchInFilesAction(String name, Icon icon, JTree tree) {
super(name, icon);
this.tree = tree;
}
@Override
public void actionPerformed(ActionEvent e) {
TreePath treePath = ((TreeListener) tree.getTreeSelectionListeners()[0]).getPath();
path = TreeUtils.resourceFromTreePath(treePath);
parentFrame = (JFrame) ((new AuthorComponentFactory()).getWorkspaceUtilities().getParentFrame());
| searchDialog = DialogTools.getOxygenDialog(parentFrame, Lang.get(Lang.Keys.cm_search)); | 3 |
assist-group/assist-mcommerce-sdk-android | sdk/src/main/java/ru/assisttech/sdk/processor/AssistResultProcessor.java | [
"public class AssistResult {\n\n /**\n * Status of payment result\n **/\n private OrderState state;\n /**\n * Result code\n **/\n private String approvalCode;\n /**\n * Number of payment in Assist\n **/\n private String billNumber;\n /**\n * Additional information\n **/\n private String extraInfo;\n /**\n * Order number returned by Assist payment system\n * May differ from the order number sent by mobile application\n * in case if order number auto-generating enabled for certain Merchant ID\n */\n private String orderNumber;\n\n private String amount;\n private String currency;\n private String comment;\n private String email;\n private String firstName;\n private String lastName;\n private String middleName;\n private String signature;\n private String checkValue;\n\n private String meantypeName;\n private String meanNumber;\n private String cardholder;\n private String cardExpirationDate;\n\n\n /**\n * Possible order state values\n */\n public enum OrderState {\n UNKNOWN, /**\n * application level status (does not exist in Assist)\n **/\n IN_PROCESS,\n DELAYED,\n APPROVED,\n PARTIAL_APPROVED,\n PARTIAL_DELAYED,\n CANCELED,\n PARTIAL_CANCELED,\n DECLINED,\n TIMEOUT,\n CANCEL_ERROR, /**\n * application level status (does not exist in Assist)\n **/\n NON_EXISTENT;\n\n /**\n * application level status (does not exist in Assist)\n **/\n\n public String toString() {\n switch (this) {\n case UNKNOWN:\n return \"Unknown\";\n case IN_PROCESS:\n return \"In Process\";\n case DELAYED:\n return \"Delayed\";\n case APPROVED:\n return \"Approved\";\n case PARTIAL_APPROVED:\n return \"PartialApproved\";\n case PARTIAL_DELAYED:\n return \"PartialDelayed\";\n case CANCELED:\n return \"Canceled\";\n case PARTIAL_CANCELED:\n return \"PartialCanceled\";\n case DECLINED:\n return \"Declined\";\n case TIMEOUT:\n return \"Timeout\";\n case CANCEL_ERROR:\n return \"Cancel error\";\n case NON_EXISTENT:\n return \"Non-existent\";\n default:\n return \"Unknown\";\n }\n }\n\n public String toText() {\n\n switch (this) {\n case UNKNOWN:\n return \"Неизвестно\";\n case IN_PROCESS:\n return \"В процессе\";\n case DELAYED:\n return \"Ожидает подтверждения оплаты\";\n case APPROVED:\n return \"Оплачен\";\n case PARTIAL_APPROVED:\n return \"Оплачен частично\";\n case PARTIAL_DELAYED:\n return \"Подтвержден частично\";\n case CANCELED:\n return \"Отменён\";\n case PARTIAL_CANCELED:\n return \"Отменён частично\";\n case DECLINED:\n return \"Отклонён\";\n case TIMEOUT:\n return \"Закрыт по истечении времени\";\n case CANCEL_ERROR:\n return \"Ошибка отмены\";\n case NON_EXISTENT:\n return \"Не существует\";\n default:\n return \"Неизвестно\";\n }\n }\n\n public static OrderState fromString(String value) {\n switch (value) {\n case \"Unknown\":\n case \"Неизвестно\":\n return UNKNOWN;\n case \"In Process\":\n case \"В процессе\":\n return IN_PROCESS;\n case \"Delayed\":\n case \"Ожидает подтверждения оплаты\":\n return DELAYED;\n case \"Approved\":\n case \"Оплачен\":\n return APPROVED;\n case \"PartialApproved\":\n case \"Оплачен частично\":\n return PARTIAL_APPROVED;\n case \"PartialDelayed\":\n case \"Подтвержден частично\":\n return PARTIAL_DELAYED;\n case \"Canceled\":\n case \"Отменён\":\n return CANCELED;\n case \"PartialCanceled\":\n case \"Отменён частично\":\n return PARTIAL_CANCELED;\n case \"Declined\":\n case \"Отклонён\":\n return DECLINED;\n case \"Timeout\":\n case \"Закрыт по истечении времени\":\n return TIMEOUT;\n case \"Cancel error\":\n case \"Ошибка отмены\":\n return CANCEL_ERROR;\n case \"Non-existent\":\n case \"Не существует\":\n return NON_EXISTENT;\n default:\n return UNKNOWN;\n }\n }\n\n }\n\n public AssistResult() {\n state = OrderState.UNKNOWN;\n }\n\n public AssistResult(OrderState os) {\n if (os == null) {\n state = OrderState.UNKNOWN;\n } else {\n state = os;\n }\n }\n\n public AssistResult(OrderState os, String extra) {\n if (os == null) {\n state = OrderState.UNKNOWN;\n } else {\n state = os;\n }\n extraInfo = extra;\n }\n\n /**\n * Set {@link AssistResult#state}\n *\n * @param os\n */\n public void setOrderState(OrderState os) {\n state = os;\n }\n\n /**\n * Set {@link AssistResult#state} as String\n *\n * @param value\n */\n public void setOrderState(String value) {\n if (value == null) {\n setOrderState(OrderState.UNKNOWN);\n } else {\n setOrderState(OrderState.fromString(value));\n }\n }\n\n /**\n * Returns order state\n *\n * @return {@link AssistResult#state} as String\n */\n public OrderState getOrderState() {\n return state;\n }\n\n /**\n * Get payment number in Assist\n *\n * @return {@link AssistResult#billNumber}\n */\n public String getBillNumber() {\n return billNumber;\n }\n\n /**\n * Set {@link AssistResult#billNumber}\n *\n * @param value\n */\n public void setBillNumber(String value) {\n billNumber = value;\n }\n\n /**\n * Set {@link AssistResult#approvalCode}\n *\n * @param code\n */\n public void setApprovalCode(String code) {\n approvalCode = code;\n }\n\n /**\n * Get result code\n *\n * @return {@link AssistResult#approvalCode}\n */\n public String getApprovalCode() {\n return approvalCode;\n }\n\n /**\n * Set {@link AssistResult#extraInfo}\n *\n * @param value\n */\n public void setExtra(String value) {\n extraInfo = value;\n }\n\n /**\n * Get additional information (i.e. error reason, ..)\n *\n * @return {@link AssistResult#extraInfo}\n */\n public String getExtra() {\n return extraInfo;\n }\n\n /**\n * Used in web payment\n *\n * @return order number\n */\n public String getOrderNumber() {\n return orderNumber;\n }\n\n public void setMeantypeName(String value) {\n meantypeName = value;\n }\n\n public String getMeantypeName() {\n return meantypeName;\n }\n\n public void setMeanNumber(String value) {\n meanNumber = value;\n }\n\n public String getMeanNumber() {\n return meanNumber;\n }\n\n public void setCardholder(String value) {\n cardholder = value;\n }\n\n public String getCardholder() {\n return cardholder;\n }\n\n public void setCardExpirationDate(String value) {\n cardExpirationDate = value;\n }\n\n public String getCardExpirationDate() {\n return cardExpirationDate;\n }\n\n /**\n * Used in web payment\n *\n * @param value order number returned by Assist\n */\n public void setOrderNumber(String value) {\n orderNumber = value;\n }\n\n public String getAmount() {\n return amount;\n }\n\n public void setAmount(String amount) {\n this.amount = amount;\n }\n\n public String getCurrency() {\n return currency;\n }\n\n public void setCurrency(String currency) {\n this.currency = currency;\n }\n\n public String getComment() {\n return comment;\n }\n\n public void setComment(String comment) {\n this.comment = comment;\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 getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getMiddleName() {\n return middleName;\n }\n\n public void setMiddleName(String middleName) {\n this.middleName = middleName;\n }\n\n public String getSignature() {\n return signature;\n }\n\n public void setSignature(String signature) {\n this.signature = signature;\n }\n\n public String getCheckValue() {\n return checkValue;\n }\n\n public void setCheckValue(String checkValue) {\n this.checkValue = checkValue;\n }\n\n public boolean isUnknown() {\n return (OrderState.UNKNOWN == state);\n }\n\n public boolean isInProcess() {\n return (OrderState.IN_PROCESS == state);\n }\n\n public boolean isDelayed() {\n return (OrderState.DELAYED == state);\n }\n\n public boolean isApproved() {\n return (OrderState.APPROVED == state);\n }\n\n public boolean isPartialApproved() {\n return (OrderState.PARTIAL_APPROVED == state);\n }\n\n public boolean isPartialDelayed() {\n return (OrderState.PARTIAL_DELAYED == state);\n }\n\n public boolean isCanceled() {\n return (OrderState.CANCELED == state);\n }\n\n public boolean isPartialCanceled() {\n return (OrderState.PARTIAL_CANCELED == state);\n }\n\n public boolean isDeclined() {\n return (OrderState.DECLINED == state);\n }\n\n public boolean isTimeout() {\n return (OrderState.TIMEOUT == state);\n }\n\n public boolean isNonExistent() {\n return (OrderState.NON_EXISTENT == state);\n }\n\n public boolean isPositive() {\n return (isInProcess() ||\n isDelayed() ||\n isApproved() ||\n isPartialApproved() ||\n isPartialDelayed() ||\n isCanceled() ||\n isPartialCanceled());\n }\n\n public boolean isNegative() {\n return (isDeclined() || isTimeout());\n }\n\n public boolean isCancelError() {\n return (OrderState.CANCEL_ERROR == state);\n }\n}",
"public class AssistNetworkEngine {\n\n private static final String TAG = \"AssistNetworkEngine\";\n\n private SSLContextFactory sslContextFactory;\n private SSLContext sslContext;\n private boolean useCustomSslCertificates;\n private String userAgent = \"Mozilla\";\n private CheckHTTPSConnectionTask connectionTask;\n private AssistNetworkTask networkTask;\n\n public interface ConnectionCheckListener {\n void onConnectionSuccess();\n\n void onConnectionFailure(String info);\n }\n\n public interface ConnectionErrorListener {\n void onConnectionError(String info);\n }\n\n public interface NetworkResponseProcessor {\n void asyncProcessing(HttpResponse response); // Supposed to be called on PARALLEL thread\n\n void syncPostProcessing(); // Supposed to be called on MAIN (UI) thread\n }\n\n public AssistNetworkEngine(Context context) {\n userAgent = new WebView(context).getSettings().getUserAgentString();\n try {\n sslContextFactory = new SSLContextFactory(context);\n } catch (SSLContextFactoryException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n\n public boolean addCertificate(Certificate cert) {\n return sslContextFactory.addCertificate(cert);\n }\n\n public boolean isCustomSslCertificateUsed() {\n return useCustomSslCertificates;\n }\n\n public void stopTasks() {\n\n if (connectionTask != null && !connectionTask.isCancelled()) {\n connectionTask.resetListeners();\n connectionTask.cancel(true);\n }\n\n if (networkTask != null && !networkTask.isCancelled()) {\n networkTask.resetListeners();\n networkTask.cancel(true);\n }\n }\n\n /**\n * Checks connection to server\n */\n public void checkHTTPSConnection(URL url, ConnectionCheckListener listener) {\n connectionTask = new CheckHTTPSConnectionTask(listener);\n connectionTask.execute(url);\n }\n\n /**\n *\n */\n public void loadAndProcessPage(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor) {\n networkTask = new HttpGETTask(url, listener, processor);\n networkTask.execute();\n }\n\n /**\n *\n */\n public void sendXPosRequest(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor, String request) {\n networkTask = new SoapPOSTTask(url, listener, processor, request);\n networkTask.execute();\n }\n\n /**\n *\n */\n public void postSOAP(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor, String request) {\n networkTask = new SoapPOSTTask(url, listener, processor, request);\n networkTask.execute();\n }\n\n public void postJSON(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor, String request) {\n postJSON(url, listener, processor, request, null);\n }\n\n public void postJSON(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor, String request, String token) {\n networkTask = new JsonPOSTTask(url, listener, processor, request, token);\n networkTask.execute();\n }\n\n /**\n *\n */\n public void postRequest(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor, String request) {\n networkTask = new HttpPostTask(url, listener, processor, request);\n networkTask.execute();\n }\n\n /**\n * Tries to establish https connection with server\n */\n private class CheckHTTPSConnectionTask extends AsyncTask<URL, Void, Void> {\n\n private ConnectionCheckListener listener;\n private String information;\n private int responseCode;\n private boolean success;\n\n public CheckHTTPSConnectionTask(ConnectionCheckListener listener) {\n this.listener = listener;\n }\n\n public void resetListeners() {\n listener = null;\n }\n\n private HttpsURLConnection createConnection(URL url, boolean useCustomCertificates) throws IOException {\n HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();\n try {\n if (useCustomCertificates) {\n urlConnection.setSSLSocketFactory(new TLSSocketFactory(getSSLContext()));\n } else {\n urlConnection.setSSLSocketFactory(new TLSSocketFactory());\n }\n } catch (KeyManagementException e) {\n e.printStackTrace();\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n urlConnection.setInstanceFollowRedirects(true);\n urlConnection.addRequestProperty(\"Accept\", \"text/html\");\n urlConnection.addRequestProperty(\"Accept-Encoding\", \"gzip, deflate\");\n urlConnection.addRequestProperty(\"User-Agent\", userAgent);\n urlConnection.setRequestMethod(\"GET\");\n return urlConnection;\n }\n\n private boolean checkConnection(HttpsURLConnection urlConnection) throws IOException {\n urlConnection.connect();\n responseCode = urlConnection.getResponseCode();\n Log.d(TAG, \"Server response code: \" + responseCode);\n\n return (responseCode == HttpsURLConnection.HTTP_OK);\n }\n\n @Override\n protected Void doInBackground(URL... urls) {\n\n Log.d(TAG, \"Start server verification...\");\n success = false;\n HttpsURLConnection urlConnection = null;\n\n /* Default sslContextFactory */\n try {\n Log.d(TAG, \"Create connection...\");\n urlConnection = createConnection(urls[0], false);\n\n if (isCancelled()) {\n return null;\n }\n\n Log.d(TAG, \"Check connection\");\n if (checkConnection(urlConnection)) {\n setUseCustomSslCertificates(false);\n success = true;\n return null;\n }\n } catch (IOException e) {\n information = e.getMessage();\n Log.d(TAG, \"Got exception: \" + information);\n } finally {\n if (urlConnection != null) {\n urlConnection.disconnect();\n urlConnection = null;\n }\n }\n\n /* Custom sslContextFactory; uses provided certificates */\n try {\n Log.d(TAG, \"Create connection...\");\n urlConnection = createConnection(urls[0], true);\n\n if (isCancelled()) {\n return null;\n }\n\n Log.d(TAG, \"Check connection\");\n if (checkConnection(urlConnection)) {\n setUseCustomSslCertificates(true);\n success = true;\n return null;\n }\n } catch (IOException e) {\n Log.d(TAG, \"Got exception: \" + information);\n information = e.getMessage();\n } finally {\n if (urlConnection != null) {\n urlConnection.disconnect();\n }\n }\n\n information = \"Server connection error. Response code: \" + responseCode;\n return null;\n }\n\n @Override\n protected void onPostExecute(Void value) {\n if (listener == null) return;\n if (success) {\n listener.onConnectionSuccess();\n } else {\n listener.onConnectionFailure(information);\n }\n }\n }\n\n /**\n * Base class for network task executed in parallel thread\n * Sends request to server and receives response\n */\n private abstract class AssistNetworkTask extends AsyncTask<Void, Void, Void> {\n\n private URL url;\n private ConnectionErrorListener listener;\n private NetworkResponseProcessor processor;\n private HttpResponse response;\n protected boolean connectionError;\n protected String info;\n\n public AssistNetworkTask(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor) {\n this.url = url;\n this.listener = listener;\n this.processor = processor;\n }\n\n public void resetListeners() {\n listener = null;\n processor = null;\n }\n\n protected URL getUrl() {\n return url;\n }\n\n @Override\n protected Void doInBackground(Void... params) {\n\n StringBuilder responseData = new StringBuilder();\n HttpRequest request = getRequest();\n\n HttpsURLConnection connection = null;\n try {\n connection = (HttpsURLConnection) getUrl().openConnection();\n try {\n if (isCustomSslCertificateUsed()) {\n connection.setSSLSocketFactory(new TLSSocketFactory(getSSLContext()));\n } else {\n connection.setSSLSocketFactory(new TLSSocketFactory());\n }\n } catch (KeyManagementException e) {\n e.printStackTrace();\n throw new IOException(\"Connection initialization failed\");\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n throw new IOException(\"Connection initialization failed\");\n }\n connection.setInstanceFollowRedirects(true);\n connection.setUseCaches(false);\n connection.setDoInput(true);\n if (request.hasData())\n connection.setDoOutput(true);\n\n connection.setRequestMethod(request.getMethod());\n if (request.getProperties() != null) {\n Set<Entry<String, String>> set = request.getProperties().entrySet();\n for (Entry<String, String> entry : set) {\n connection.setRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n if (isCancelled()) {\n return null;\n }\n\n if (request.hasData()) {\n Log.d(TAG, request.toString());\n //Send request\n OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());\n wr.write(request.getData());\n wr.flush();\n wr.close();\n\n }\n\n if (isCancelled()) {\n return null;\n }\n\n int responseCode = connection.getResponseCode();\n Map<String, List<String>> responseHeaders = connection.getHeaderFields();\n\n // Get response data\n BufferedReader reader = null;\n try {\n InputStream is = connection.getInputStream();\n if (TextUtils.equals(connection.getContentEncoding(), \"gzip\")) {\n GZIPInputStream gzipIs = new GZIPInputStream(is);\n reader = new BufferedReader(new InputStreamReader(gzipIs, \"UTF-8\"));\n } else {\n reader = new BufferedReader(new InputStreamReader(is));\n }\n\n String line;\n while ((line = reader.readLine()) != null) {\n responseData.append(line);\n if (isCancelled())\n break;\n }\n } catch (IOException e) {\n // Getting response data error. Possibly there is no data\n } finally {\n if (reader != null)\n reader.close();\n }\n connection.disconnect();\n connection = null;\n\n response = new HttpResponse(responseCode, responseHeaders, responseData.toString());\n Log.d(TAG, response.toString());\n if (processor != null) {\n processor.asyncProcessing(response);\n }\n\n } catch (IOException e) {\n connectionError = true;\n info = e.getMessage();\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n return null;\n }\n\n @Override\n protected void onPostExecute(Void value) {\n if (connectionError) {\n if (listener != null)\n listener.onConnectionError(info);\n } else {\n if (processor != null)\n processor.syncPostProcessing();\n }\n }\n\n private HttpRequest getRequest() {\n HttpRequest request = new HttpRequest();\n request.setMethod(\"GET\");\n request.addProperty(\"Accept-Encoding\", \"gzip\");\n return customizeRequest(request);\n }\n\n /**\n * Callback for HTTP request properties providing {@link HttpRequest}}\n */\n protected abstract HttpRequest customizeRequest(HttpRequest request);\n }\n\n /**\n *\n */\n private class HttpGETTask extends AssistNetworkTask {\n public HttpGETTask(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor) {\n super(url, listener, processor);\n }\n\n @Override\n protected HttpRequest customizeRequest(HttpRequest request) {\n request.setMethod(\"GET\");\n request.addProperty(\"Accept\", \"text/html\");\n request.addProperty(\"User-Agent\", userAgent);\n return request;\n }\n }\n\n /**\n *\n */\n private class HttpPostTask extends AssistNetworkTask {\n private String data;\n\n public HttpPostTask(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor, String request) {\n super(url, listener, processor);\n data = request;\n }\n\n @Override\n protected HttpRequest customizeRequest(HttpRequest request) {\n request.setMethod(\"POST\");\n request.setData(data);\n request.addProperty(\"User-Agent\", userAgent);\n request.addProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\n request.addProperty(\"Content-Length\", Integer.toString(data.length()));\n return request;\n }\n }\n\n /**\n * Posts SOAP request and parses response\n */\n private class SoapPOSTTask extends /*DebugWithoutNetworkTask*/AssistNetworkTask {\n private String data;\n\n public SoapPOSTTask(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor, String request) {\n super(url, listener, processor);\n data = request;\n }\n\n @Override\n protected HttpRequest customizeRequest(HttpRequest request) {\n request.setMethod(\"POST\");\n request.setData(data);\n request.addProperty(\"Content-Type\", \"text/xml\");\n request.addProperty(\"Content-Encoding\", \"UTF-8\");\n request.addProperty(\"SOAPAction\", getUrl().toString());\n request.addProperty(\"Content-Length\", Integer.toString(data.getBytes().length));\n return request;\n }\n }\n\n /**\n * Posts JSON request and parses response\n */\n private class JsonPOSTTask extends /*DebugWithoutNetworkTask*/AssistNetworkTask {\n private String data;\n private String authtoken;\n\n public JsonPOSTTask(URL url, ConnectionErrorListener listener, NetworkResponseProcessor processor, String request, String token) {\n super(url, listener, processor);\n data = request;\n authtoken = token;\n }\n\n @Override\n protected HttpRequest customizeRequest(HttpRequest request) {\n request.setMethod(\"POST\");\n request.setData(data);\n request.addProperty(\"Content-Type\", \"application/json\");\n request.addProperty(\"Content-Encoding\", \"UTF-8\");\n if (authtoken != null) {\n request.addProperty(\"Authorization\", \"Bearer \" + authtoken);\n }\n request.addProperty(\"Content-Length\", Integer.toString(data.length()));\n return request;\n }\n }\n\n /**\n * Creates SSL context\n */\n private SSLContext getSSLContext() {\n\n if (sslContext == null) {\n try {\n sslContext = sslContextFactory.createSSLContext();\n } catch (SSLContextFactoryException e) {\n e.printStackTrace();\n }\n }\n return sslContext;\n }\n\n private void setUseCustomSslCertificates(boolean value) {\n useCustomSslCertificates = value;\n }\n\n /**\n * Logs HTTP response headers\n * @param headers HTTP protocol headers\n */\n//\tprivate void debugHeaders(Map<String, List<String>> headers){\n//\n//\t\tSet<Map.Entry<String, List<String>>> entrySet = headers.entrySet();\n//\t\t// Log header\n//\t\tLog.d(TAG, \"Response headers:\");\n//\t\tLog.d(TAG, \"[\");\n//\t\tfor(Map.Entry<String, List<String>> entry: entrySet)\n//\t\t{\n//\t\t\tString str = \"\";\n//\t\t\tList<String> vList = entry.getValue();\n//\t\t\tfor(String val: vList){\n//\t\t\t\tstr += val;\n//\t\t\t\tstr += \" \";\n//\t\t\t}\n//\t\t\tLog.d(TAG, entry.getKey() + \" : \" + str);\n//\t\t}\n//\t\tLog.d(TAG, \"]\");\n//\t}\n}",
"public class HttpResponse {\n\n private int responseCode;\n private Map<String, List<String>> headers;\n private String data;\n\n public HttpResponse(int responseCode, Map<String, List<String>> headers, String data) {\n this.responseCode = responseCode;\n this.headers = headers;\n this.data = data;\n }\n\n public int getResponseCode() {\n return responseCode;\n }\n\n public Map<String, List<String>> getHeaders() {\n return headers;\n }\n\n public List<String> getHeader(String name) {\n return headers.get(name);\n }\n\n public boolean hasHeader(String name) {\n return headers.containsKey(name);\n }\n\n public String getData() {\n return data;\n }\n\n public boolean hasData() {\n return !TextUtils.isEmpty(data);\n }\n\n public String toString() {\n StringBuilder builder = new StringBuilder();\n\n builder.append(\"HttpResponse:\\n[\\n\");\n builder.append(\"Response code: \").append(responseCode).append(\"\\n\");\n builder.append(\"Response headers:\\n\");\n if (headers != null && !headers.isEmpty()) {\n Set<Map.Entry<String, List<String>>> entrySet = headers.entrySet();\n for (Map.Entry<String, List<String>> entry : entrySet) {\n StringBuilder valueBuilder = new StringBuilder();\n List<String> valueList = entry.getValue();\n for (String value : valueList) {\n valueBuilder.append(value).append(\" \");\n }\n builder.append(\" \")\n .append(entry.getKey())\n .append(\" : \")\n .append(valueBuilder.toString())\n .append(\"\\n\");\n }\n } else {\n builder.append(\" no headers\\n\");\n }\n builder.append(\"Response data:\\n\");\n if (TextUtils.isEmpty(data)) {\n builder.append(\" no data\\n\");\n } else {\n builder.append(data).append(\"\\n\");\n }\n builder.append(\"]\");\n return builder.toString();\n }\n}",
"public class AssistTransaction {\n\n public static final int UNREGISTERED_ID = -1;\n private long id;\n private String merchantID;\n private String orderDateUTC;\n private String orderDateDevice;\n private String orderNumber;\n private String orderComment;\n private String orderAmount;\n private Currency orderCurrency;\n private PaymentMethod paymentMethod;\n private boolean requireUserSignature;\n private byte[] userSignature;\n private AssistResult result;\n private List<AssistOrderItem> orderItems;\n\n public enum PaymentMethod {\n CARD_MANUAL,\n CARD_PHOTO_SCAN,\n CARD_TERMINAL,\n CASH\n }\n\n public AssistTransaction() {\n result = new AssistResult(AssistResult.OrderState.UNKNOWN);\n id = UNREGISTERED_ID;\n }\n\n public boolean isStored() {\n return id != UNREGISTERED_ID;\n }\n\n public long getId() {\n return id;\n }\n\n public String getMerchantID() {\n return merchantID;\n }\n\n public String getOrderDateUTC() {\n return orderDateUTC;\n }\n\n public String getOrderDateDevice() {\n return orderDateDevice;\n }\n\n public String getOrderNumber() {\n return orderNumber;\n }\n\n public String getOrderComment() {\n return orderComment;\n }\n\n public String getOrderAmount() {\n return orderAmount;\n }\n\n public Currency getOrderCurrency() {\n return orderCurrency;\n }\n\n public PaymentMethod getPaymentMethod() {\n return paymentMethod;\n }\n\n public boolean isRequireUserSignature() {\n return requireUserSignature;\n }\n\n public byte[] getUserSignature() {\n return userSignature;\n }\n\n public AssistResult getResult() {\n return result;\n }\n\n public boolean hasOrderItems() {\n return orderItems != null;\n }\n\n public List<AssistOrderItem> getOrderItems() {\n return orderItems;\n }\n\n public void setId(long value) {\n id = value;\n }\n\n public void setMerchantID(String value) {\n merchantID = value;\n }\n\n public void setOrderDateUTC(String value) {\n orderDateUTC = value;\n }\n\n public void setOrderDateDevice(String value) {\n orderDateDevice = value;\n }\n\n public void setOrderNumber(String value) {\n orderNumber = value;\n }\n\n public void setOrderComment(String value) {\n orderComment = value;\n }\n\n public void setOrderAmount(String value) {\n orderAmount = value;\n if (orderAmount != null) {\n if (orderAmount.contains(\",\")) {\n orderAmount = orderAmount.replace(\",\", \".\");\n }\n orderAmount = formatAmount(orderAmount);\n }\n }\n\n public void setOrderCurrency(Currency value) {\n orderCurrency = value;\n }\n\n public void setPaymentMethod(PaymentMethod value) {\n paymentMethod = value;\n }\n\n public void setRequireUserSignature(boolean value) {\n requireUserSignature = value;\n }\n\n public void setUserSignature(byte[] value) {\n userSignature = value;\n }\n\n public void setResult(AssistResult value) {\n result = value;\n }\n\n public void setOrderItems(List<AssistOrderItem> items) {\n orderItems = items;\n }\n\n public static String formatAmount(String amount) {\n if (TextUtils.isEmpty(amount))\n return amount;\n\n String outAmount;\n int diff = -1;\n if (amount.contains(\".\")) {\n diff = amount.length() - 1 - amount.indexOf(\".\");\n } else if (amount.contains(\",\")) {\n diff = amount.length() - 1 - amount.indexOf(\",\");\n }\n switch (diff) {\n case 0:\n outAmount = amount.concat(\"00\");\n break;\n case 1:\n outAmount = amount.concat(\"0\");\n break;\n default:\n outAmount = amount;\n break;\n }\n return outAmount;\n }\n}",
"public class XmlHelper {\n\n static public void skip(XmlPullParser parser) {\n try {\n if (parser.getEventType() != XmlPullParser.START_TAG) {\n throw new IllegalStateException();\n }\n int depth = 1;\n while (depth != 0) {\n switch (parser.next()) {\n case XmlPullParser.END_TAG:\n depth--;\n break;\n case XmlPullParser.START_TAG:\n depth++;\n break;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n static public String readValue(XmlPullParser parser, String tag) throws XmlPullParserException, IOException {\n parser.require(XmlPullParser.START_TAG, null, tag);\n String value = null;\n if (parser.next() == XmlPullParser.TEXT) {\n value = parser.getText();\n parser.nextTag();\n }\n parser.require(XmlPullParser.END_TAG, null, tag);\n\n return value;\n }\n\n static public boolean next(XmlPullParser parser, String tag) throws XmlPullParserException, IOException {\n while (parser.next() != XmlPullParser.END_TAG) {\n if (parser.getEventType() != XmlPullParser.START_TAG) {\n continue;\n }\n\n String name = parser.getName();\n // Starts by looking for the entry tag\n if (name.equals(tag)) {\n parser.require(XmlPullParser.START_TAG, null, tag);\n return true;\n } else {\n skip(parser);\n }\n }\n return false;\n }\n\n static public boolean nextTag(XmlPullParser parser) throws XmlPullParserException, IOException {\n while (parser.next() != XmlPullParser.END_TAG) {\n if (parser.getEventType() != XmlPullParser.START_TAG) {\n continue;\n }\n return true;\n }\n return false;\n }\n\n}"
] | import android.content.Context;
import android.util.Log;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import ru.assisttech.sdk.AssistResult;
import ru.assisttech.sdk.network.AssistNetworkEngine;
import ru.assisttech.sdk.network.HttpResponse;
import ru.assisttech.sdk.storage.AssistTransaction;
import ru.assisttech.sdk.xml.XmlHelper; |
@Override
public void asyncProcessing(HttpResponse response) {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
parser.setInput(new ByteArrayInputStream(response.getData().getBytes()), null);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
switch (parser.getName()) {
case OrderResult.TAG:
orderResult = new OrderResult(parser);
break;
case "Fault":
fault = new Fault(parser);
break;
}
}
eventType = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
errorMessage = e.getMessage();
isError = true;
}
}
@Override
public void syncPostProcessing() {
long tID = getTransaction().getId();
if (isError) {
if (hasListener()) {
getListener().onError(tID, errorMessage);
}
} else {
AssistResult result = new AssistResult();
if (orderResult != null && orderResult.getOrder() != null) {
result.setOrderState(orderResult.getOrder().orderstate);
result.setBillNumber(orderResult.getOrder().billnumber);
result.setOrderNumber(orderResult.getOrder().ordernumber);
result.setSignature(orderResult.getOrder().signature);
result.setCheckValue(orderResult.getOrder().checkvalue);
result.setComment(orderResult.getOrder().ordercomment);
result.setAmount(orderResult.getOrder().orderamount);
result.setCurrency(orderResult.getOrder().ordercurrency);
result.setFirstName(orderResult.getOrder().firstname);
result.setLastName(orderResult.getOrder().lastname);
result.setMiddleName(orderResult.getOrder().middlename);
result.setEmail(orderResult.getOrder().email);
if (orderResult.getOrder().getLastOperation() != null) {
result.setExtra(orderResult.getOrder().getLastOperation().usermessage);
result.setCardholder(orderResult.getOrder().getLastOperation().cardholder);
result.setMeanNumber(orderResult.getOrder().getLastOperation().meannumber);
result.setMeantypeName(orderResult.getOrder().getLastOperation().meantypename);
result.setCardExpirationDate(orderResult.getOrder().getLastOperation().cardexpirationdate);
}
} else if (fault != null) {
result.setExtra(fault.faultcode + " (" + fault.faultstring + ")");
}
if (hasListener()) {
getListener().onFinished(tID, result);
}
}
finish();
}
}
/**
* Represents XML tag "orderresult" in SOAP response from orderresult.cfm
*/
private class OrderResult {
static final String TAG = "orderresult";
ArrayList<Order> orders = new ArrayList<>();
OrderResult(XmlPullParser parser) throws XmlPullParserException, IOException {
while (!endOfTag(parser, OrderResult.TAG)) {
parser.next();
if (isTag(parser, Order.TAG)) {
orders.add(new Order(parser));
}
}
}
Order getOrder() {
if (orders.isEmpty()) {
return null;
} else {
return orders.get(orders.size() - 1);
}
}
}
/**
* Represents XML tag "order" in SOAP response from orderresult.cfm
*/
private class Order {
static final String TAG = "order";
String ordernumber;
String billnumber;
String orderstate;
String email;
String checkvalue;
String signature;
String orderamount;
String ordercurrency;
String ordercomment;
String firstname;
String lastname;
String middlename;
ArrayList<Operation> operations = new ArrayList<>();
Order(XmlPullParser parser) throws XmlPullParserException, IOException {
while (!endOfTag(parser, Order.TAG)) {
if (parser.next() == XmlPullParser.START_TAG) {
switch (parser.getName()) {
case "ordernumber": | ordernumber = XmlHelper.readValue(parser, "ordernumber"); | 4 |
R2RML-api/R2RML-api | r2rml-api-rdf4j-binding/src/test/java/rdf4jTest/NTriplesSyntax1_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}",
"@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_GRAPH_MAP)\r\npublic interface GraphMap extends TermMap {\r\n\r\n}",
"@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_JOIN)\r\npublic interface Join extends MappingComponent {\r\n\r\n\t/**\r\n\t * Set the child to a column that exists in the logical table of the triples\r\n\t * map that contains the referencing object map. A Join must have exactly\r\n\t * one child.\r\n\t * \r\n\t * @param columnName\r\n\t * The name of the column.\r\n\t * @throws NullPointerException\r\n\t * If columnName is null.\r\n\t */\r\n\t@W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_CHILD)\r\n\tpublic void setChild(String columnName);\r\n\r\n\t/**\r\n\t * Set the parent to a column that exists in the logical table of the\r\n\t * RefObjectMap's parent triples map. A Join must have exactly one parent.\r\n\t * \r\n\t * @param columnName\r\n\t * The name of the column.\r\n\t * @throws NullPointerException\r\n\t * If columnName is null.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PARENT)\r\n\tpublic void setParent(String columnName);\r\n\r\n\t/**\r\n\t * Get the child for this Join.\r\n\t * \r\n\t * @return The child associated with this Join.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_CHILD)\r\n\tpublic String getChild();\r\n\r\n\t/**\r\n\t * Get the parent for this Join.\r\n\t * \r\n\t * @return The parent associated with this Join.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PARENT)\r\n\tpublic String getParent();\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_REF_OBJECT_MAP)\r\npublic interface RefObjectMap extends MappingComponent {\r\n\r\n\t/**\r\n\t * Sets the parent triples map of this RefObjectMap. A\r\n\t * RefObjectMap must have exactly one parent triples map. This\r\n\t * method will overwrite any previously set parent triples map.\r\n\t * \r\n\t * @param tm\r\n\t * The triples map that will be set as the\r\n\t * parent triples map.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PARENT_TRIPLES_MAP)\r\n\tpublic void setParentMap(TriplesMap tm);\r\n\r\n\t/**\r\n\t * Adds the logical table of the parent triples map to this RefObjectMap.\r\n\t * This needs to be set to be able to use the getParentQuery and\r\n\t * getJointQuery methods.\r\n\t * \r\n\t * @param lt\r\n\t * The logical table of this RefObjectMap's parent triples map.\r\n *\r\n * @deprecated does not correspond to Recommendation: logicalTable is not a property of RefObjectMap\r\n\t */\r\n\t@Deprecated\r\n\tpublic void setParentLogicalTable(LogicalTable lt);\r\n\r\n\t/**\r\n\t * Adds the logical table of the triples map that this RefObjectMap is\r\n\t * contained in. This needs to be set to be able to use the getChildQuery\r\n\t * and getJointQuery methods.\r\n\t * \r\n\t * @param lt\r\n\t * The logical table of the triples map that contains this\r\n\t * RefObjectMap.\r\n * @deprecated does not correspond to Recommendation: logicalTable is not a property of RefObjectMap\r\n\t */\r\n @Deprecated\r\n\tpublic void setChildLogicalTable(LogicalTable lt);\r\n\r\n\t/**\r\n\t * Returns the child query for this RefObjectMap. The child query is the\r\n\t * effective SQL query of the LogicalTable of the TriplesMap that contains\r\n\t * the RefObjectMap.\r\n\t * \r\n\t * @return The child query for this RefObjectMap.\r\n\t * @throws NullPointerException\r\n\t * If the child logical table is null.\r\n\t */\r\n @Deprecated\r\n\tpublic String getChildQuery();\r\n\r\n\t/**\r\n\t * Returns the parent query for this RefObjectMap. The parent query is the\r\n\t * effective SQL query of the LogicalTable of the RefObjectMap's parent\r\n\t * TriplesMap.\r\n\t * \r\n\t * @return The parent query for this RefObjectMap.\r\n\t * @throws NullPointerException\r\n\t * If the parent logical table is null.\r\n\t */\r\n @Deprecated\r\n\tpublic String getParentQuery();\r\n\r\n\t/**\r\n\t * Returns the joint query for this RefObjectMap. The specification on what\r\n\t * this query will look like can be found here:\r\n\t * http://www.w3.org/TR/r2rml/#dfn-joint-sql-query\r\n\t * \r\n\t * @return The joint query for this RefObjectMap.\r\n\t */\r\n @Deprecated\r\n public String getJointQuery();\r\n\r\n\t/**\r\n\t * Add a join condition to this RefObjectMap. The Join will be added to the\r\n\t * end of the Join list. A RefObjectMap can have any number of join\r\n\t * conditions.\r\n\t * \r\n\t * @param j\r\n\t * The join condition to be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_JOIN_CONDITION)\r\n\tpublic void addJoinCondition(Join j);\r\n\r\n\t/**\r\n\t * Get the Join located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the Join.\r\n\t * @return The Join 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_JOIN_CONDITION)\r\n\tpublic Join getJoinCondition(int index);\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of Joins that have been added to\r\n\t * this RefObjectMap.\r\n\t * \r\n\t * @return An unmodifiable list of Joins.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_JOIN_CONDITION)\r\n public List<Join> getJoinConditions();\r\n\r\n\t/**\r\n\t * Get the parent triples map of this RefObjectMap.\r\n\t *\r\n\t * @return The parent triples map.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PARENT_TRIPLES_MAP)\r\n\tpublic TriplesMap getParentMap();\r\n\r\n\t/**\r\n\t * Removes the given join condition from this RefObjectMap. The subsequent\r\n\t * Joins in the list will be shifted left.\r\n\t * \r\n\t * @param j\r\n\t * The join condition that will be removed.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_JOIN_CONDITION)\r\n\tpublic void removeJoinCondition(Join j);\r\n\r\n\t\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",
"@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 org.eclipse.rdf4j.rio.helpers.StatementCollector;
import eu.optique.r2rml.api.model.GraphMap;
import eu.optique.r2rml.api.model.Join;
import eu.optique.r2rml.api.model.PredicateObjectMap;
import eu.optique.r2rml.api.model.RefObjectMap;
import eu.optique.r2rml.api.model.SubjectMap;
import eu.optique.r2rml.api.model.TriplesMap;
import java.io.InputStream;
import java.util.Collection;
import java.util.Iterator;
import eu.optique.r2rml.api.binding.rdf4j.RDF4JR2RMLMappingManager;
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;
| /*******************************************************************************
* 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 NTriplesSyntax1_Test{
@Test
public void test() throws Exception{
InputStream fis = getClass().getResourceAsStream("../mappingFiles/test28.ttl");
RDF4JR2RMLMappingManager mm = RDF4JR2RMLMappingManager.getInstance();
// Read the file into a model.
RDFParser rdfParser = Rio.createParser(RDFFormat.NTRIPLES);
Model m = new LinkedHashModel();
rdfParser.setRDFHandler(new StatementCollector(m));
rdfParser.parse(fis, "testMapping");
Collection<TriplesMap> coll = mm.importMappings(m);
Assert.assertTrue(coll.size()==2);
Iterator<TriplesMap> it=coll.iterator();
while(it.hasNext()){
TriplesMap current=it.next();
Iterator<PredicateObjectMap> pomit=current.getPredicateObjectMaps().iterator();
int cont=0;
while(pomit.hasNext()){
pomit.next();
cont++;
}
if(cont==1){ //we are analyzing the TriplesMap2
SubjectMap s=current.getSubjectMap();
| Iterator<GraphMap> gmit=s.getGraphMaps().iterator();
| 1 |
tvbarthel/SimpleWeatherForecast | SimpleWeatherForecast/src/main/java/fr/tvbarthel/apps/simpleweatherforcast/services/DailyForecastUpdateService.java | [
"@TargetApi(Build.VERSION_CODES.HONEYCOMB)\npublic class WeatherWidgetReceiver extends AppWidgetProvider {\n\n //An intent Action used to notify a data change: text color, temperature value\n // temperature unit etc.\n public static final String APPWIDGET_DATA_CHANGED =\n \"fr.tvbarthel.apps.simpleweatherforcast.receivers.WeatherWidgetReceiver.DataChanged\";\n\n @Override\n public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {\n super.onUpdate(context, appWidgetManager, appWidgetIds);\n if (SharedPreferenceUtils.isWeatherOutdated(context, false)) {\n DailyForecastUpdateService.startForUpdate(context);\n } else {\n updateWidget(context, appWidgetIds);\n }\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n super.onReceive(context, intent);\n final String action = intent.getAction();\n if (APPWIDGET_DATA_CHANGED.equals(action)) {\n notifyWidgetDataChanged(context);\n } else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)\n && ConnectivityUtils.isConnected(context)\n && SharedPreferenceUtils.isWeatherOutdated(context, false)) {\n DailyForecastUpdateService.startForUpdate(context);\n }\n }\n\n\n private RemoteViews buildLayout(Context context, int appWidgetId) {\n // Specify the service to provide data for the collection widget. Note that we need to\n // embed the appWidgetId via the data otherwise it will be ignored.\n final Intent intent = new Intent(context, AppWidgetService.class);\n intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);\n intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));\n final RemoteViews remoteViews;\n remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget);\n remoteViews.setRemoteAdapter(appWidgetId, R.id.app_widget_list_view, intent);\n remoteViews.setEmptyView(R.id.app_widget_list_view, R.id.app_widget_empty_view);\n\n // Bind a click listener template for the contents of the weather list.\n final Intent onClickIntent = new Intent(context, MainActivity.class);\n final PendingIntent onClickPendingIntent = PendingIntent.getActivity(context, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);\n remoteViews.setPendingIntentTemplate(R.id.app_widget_list_view, onClickPendingIntent);\n\n return remoteViews;\n }\n\n private void notifyWidgetDataChanged(Context context) {\n final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);\n final ComponentName thisWidget = new ComponentName(context, WeatherWidgetReceiver.class);\n final int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);\n for (int appWidgetId : appWidgetIds) {\n appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.app_widget_list_view);\n }\n }\n\n private void updateWidget(Context context, int[] appWidgetIds) {\n final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);\n // Update each of the widgets with the remote adapter\n for (int appWidgetId : appWidgetIds) {\n RemoteViews layout = buildLayout(context, appWidgetId);\n appWidgetManager.updateAppWidget(appWidgetId, layout);\n }\n }\n}",
"public class ConnectivityUtils {\n\n /**\n * Check if a connection is available.\n *\n * @param context the {@link android.content.Context} used to retrieve the {@link android.net.ConnectivityManager}.\n * @return true is a network connectivity exists, false otherwise.\n */\n public static boolean isConnected(Context context) {\n final ConnectivityManager connectivityManager = (ConnectivityManager)\n context.getSystemService(Service.CONNECTIVITY_SERVICE);\n final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();\n return networkInfo != null && networkInfo.isConnected();\n }\n}",
"public class LocationUtils {\n\n public static String getBestCoarseProvider(Context context) {\n //retrieve an instance of the LocationManager\n final LocationManager locationManager = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);\n //Get a location with a coarse accuracy\n final Criteria criteria = new Criteria();\n criteria.setAccuracy(Criteria.ACCURACY_COARSE);\n return locationManager.getBestProvider(criteria, true);\n }\n\n /**\n * Get the last known {@link android.location.Location} with a coarse accuracy.\n *\n * @param context the {@link android.content.Context} used to retrieve the {@link android.location.LocationManager}.\n * @return the last known {@link android.location.Location} or null.\n */\n public static Location getLastKnownLocation(Context context) {\n Location lastKnownLocation = null;\n final LocationManager locationManager = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);\n final Criteria locationCriteria = new Criteria();\n locationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);\n final String providerName = locationManager.getBestProvider(locationCriteria, true);\n if (providerName != null) {\n lastKnownLocation = locationManager.getLastKnownLocation(providerName);\n }\n return lastKnownLocation;\n }\n}",
"public class SharedPreferenceUtils {\n\n public static final long REFRESH_TIME_AUTO = 1000 * 60 * 60 * 2; // 2 hours in millis.\n public static final long REFRESH_TIME_MANUAL = 1000 * 60 * 10; // 10 minutes.\n\n public static String KEY_LAST_UPDATE = \"SharedPreferenceUtils.Key.LastUpdate\";\n public static String KEY_LAST_KNOWN_JSON_WEATHER = \"SharedPreferenceUtils.Key.LastKnownJsonWeather\";\n public static String KEY_TEMPERATURE_UNIT_SYMBOL = \"SharedPreferenceUtils.Key.TemperatureUnitSymbol\";\n\n private static SharedPreferences getDefaultSharedPreferences(final Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context);\n }\n\n public static String getLastKnownWeather(final Context context) {\n return getDefaultSharedPreferences(context).getString(KEY_LAST_KNOWN_JSON_WEATHER, null);\n }\n\n public static long getLastUpdate(final Context context) {\n return getDefaultSharedPreferences(context).getLong(KEY_LAST_UPDATE, 0);\n }\n\n public static void storeWeather(final Context context, final String jsonWeather) {\n final Editor editor = getDefaultSharedPreferences(context).edit();\n editor.putString(KEY_LAST_KNOWN_JSON_WEATHER, jsonWeather);\n editor.putLong(KEY_LAST_UPDATE, System.currentTimeMillis());\n editor.apply();\n }\n\n public static void storeTemperatureUnitSymbol(final Context context, final String unitSymbol) {\n final Editor editor = getDefaultSharedPreferences(context).edit();\n editor.putString(KEY_TEMPERATURE_UNIT_SYMBOL, unitSymbol);\n editor.apply();\n }\n\n public static String getTemperatureUnitSymbol(final Context context) {\n return getDefaultSharedPreferences(context).getString(KEY_TEMPERATURE_UNIT_SYMBOL,\n context.getString(R.string.temperature_unit_celsius_symbol));\n }\n\n public static void registerOnSharedPreferenceChangeListener(final Context context, SharedPreferences.OnSharedPreferenceChangeListener listener) {\n getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(listener);\n }\n\n public static void unregisterOnSharedPreferenceChangeListener(final Context context, SharedPreferences.OnSharedPreferenceChangeListener listener) {\n getDefaultSharedPreferences(context).unregisterOnSharedPreferenceChangeListener(listener);\n }\n\n public static boolean isWeatherOutdated(Context context, boolean isManualRefresh) {\n final long refreshTimeInMillis = isManualRefresh ? REFRESH_TIME_MANUAL : REFRESH_TIME_AUTO;\n final long lastUpdate = SharedPreferenceUtils.getLastUpdate(context);\n return System.currentTimeMillis() - lastUpdate > refreshTimeInMillis;\n }\n\n}",
"public class URLUtils {\n\n /**\n * Get the body of a http response as a String.\n *\n * @param urlString the url to get.\n * @return the inputStream pointed by the url as a String.\n * @throws IOException\n */\n public static String getAsString(String urlString) throws IOException {\n final URL url = new URL(urlString);\n String resultContent = null;\n\n final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();\n urlConnection.setUseCaches(false);\n\n if (urlConnection.getResponseCode() == HttpStatus.SC_OK) {\n final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n final StringBuilder stringBuilder = new StringBuilder();\n String line;\n while ((line = bufferedReader.readLine()) != null) {\n line += \"\\n\";\n stringBuilder.append(line);\n }\n resultContent = stringBuilder.toString();\n }\n\n return resultContent;\n }\n\n}"
] | import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.Locale;
import fr.tvbarthel.apps.simpleweatherforcast.R;
import fr.tvbarthel.apps.simpleweatherforcast.receivers.WeatherWidgetReceiver;
import fr.tvbarthel.apps.simpleweatherforcast.utils.ConnectivityUtils;
import fr.tvbarthel.apps.simpleweatherforcast.utils.LocationUtils;
import fr.tvbarthel.apps.simpleweatherforcast.utils.SharedPreferenceUtils;
import fr.tvbarthel.apps.simpleweatherforcast.utils.URLUtils; | package fr.tvbarthel.apps.simpleweatherforcast.services;
/**
* A Simple {@link android.app.Service} used to update the daily forecast.
*/
public class DailyForecastUpdateService extends Service implements LocationListener {
// update action
public static final String ACTION_UPDATE = "DailyForecastUpdateService.Actions.Update";
// update error action
public static final String ACTION_UPDATE_ERROR = "DailyForecastUpdateService.Actions.UpdateError";
// update error extra
public static final String EXTRA_UPDATE_ERROR = "DailyForecastUpdateService.Extra.UpdateError";
private LocationManager mLocationManager;
private Looper mServiceLooper;
private Handler mServiceHandler;
private Boolean mIsUpdatingTemperature;
public static void startForUpdate(Context context) {
final Intent intent = new Intent(context, DailyForecastUpdateService.class);
intent.setAction(ACTION_UPDATE);
context.startService(intent);
}
@Override
public void onCreate() {
super.onCreate();
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
HandlerThread thread = new HandlerThread("DailyForecastUpdateService", android.os.Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new Handler(mServiceLooper);
mIsUpdatingTemperature = false;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// We don't support binding.
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && ACTION_UPDATE.equals(intent.getAction()) && !mIsUpdatingTemperature) {
if (ConnectivityUtils.isConnected(getApplicationContext())) {
mIsUpdatingTemperature = true;
// First get a new location
getNewLocation();
} else {
broadcastErrorAndStop(R.string.toast_no_connection_available);
}
}
return START_STICKY;
}
private void updateForecast(final Location newLocation) {
mServiceHandler.post(new Runnable() {
@Override
public void run() {
try {
final String JSON = getForecastAsJSON(newLocation); | SharedPreferenceUtils.storeWeather(DailyForecastUpdateService.this, JSON); | 3 |
sumeetchhetri/gatf | alldep-jar/src/main/java/com/gatf/selenium/SeleniumTest.java | [
"public class AcceptanceTestContext {\r\n\r\n\tprivate Logger logger = Logger.getLogger(AcceptanceTestContext.class.getSimpleName());\r\n\t\r\n\tpublic final static String\r\n\t PROP_SOAP_ACTION_11 = \"SOAPAction\",\r\n\t PROP_SOAP_ACTION_12 = \"action=\",\r\n\t PROP_CONTENT_TYPE = \"Content-Type\",\r\n\t PROP_CONTENT_LENGTH = \"Content-Length\",\r\n\t PROP_AUTH = \"Authorization\",\r\n\t PROP_PROXY_AUTH = \"Proxy-Authorization\",\r\n\t PROP_PROXY_CONN = \"Proxy-Connection\",\r\n\t PROP_KEEP_ALIVE = \"Keep-Alive\",\r\n\t PROP_BASIC_AUTH = \"Basic\",\r\n\t PROP_DELIMITER = \"; \";\r\n\t\r\n\tpublic final static String\r\n\t SOAP_1_1_NAMESPACE = \"http://schemas.xmlsoap.org/soap/envelope/\",\r\n\t SOAP_1_2_NAMESPACE = \"http://www.w3.org/2003/05/soap-envelope\";\r\n\t\r\n\tpublic final static String\r\n\t MIMETYPE_TEXT_HTML = \"text/html\",\r\n\t MIMETYPE_TEXT_PLAIN = \"text/plain\",\r\n\t MIMETYPE_TEXT_XML = \"text/xml\",\r\n\t MIMETYPE_APPLICATION_XML = \"application/soap+xml\";\r\n\t\r\n\tpublic static final String GATF_SERVER_LOGS_API_FILE_NM = \"gatf-logging-api-int.xml\";\r\n\t\r\n\tprivate final Map<String, List<TestCase>> relatedTestCases = new HashMap<String, List<TestCase>>();\r\n\t\r\n\tprivate final Map<String, String> httpHeaders = new HashMap<String, String>();\r\n\r\n\tprivate ConcurrentHashMap<Integer, String> sessionIdentifiers = new ConcurrentHashMap<Integer, String>();\r\n\t\r\n\tprivate final Map<String, String> soapEndpoints = new HashMap<String, String>();\r\n\t\r\n\tprivate final Map<String, Document> soapMessages = new HashMap<String, Document>();\r\n\t\r\n\tprivate final Map<String, String> soapStrMessages = new HashMap<String, String>();\r\n\t\r\n\tprivate final Map<String, String> soapActions = new HashMap<String, String>();\r\n\t\r\n\tprivate final WorkflowContextHandler workflowContextHandler = new WorkflowContextHandler();\r\n\t\r\n\tprivate List<TestCase> serverLogsApiLst = new ArrayList<TestCase>();\r\n\t\r\n\tprivate GatfExecutorConfig gatfExecutorConfig;\r\n\t\r\n\tprivate ClassLoader projectClassLoader;\r\n\t\r\n\tprivate Map<String, Method> prePostTestCaseExecHooks = new HashMap<String, Method>();\r\n\t\r\n\tpublic static final UrlValidator URL_VALIDATOR = new UrlValidator(new String[]{\"http\",\"https\"}, UrlValidator.ALLOW_LOCAL_URLS);\r\n\t\r\n\tpublic static boolean isValidUrl(String url) {\r\n\t\tif(!URL_VALIDATOR.isValid(url)) {\r\n\t\t\tif(url.startsWith(\"host.docker.internal\")) {\r\n\t\t\t\turl = url.replace(\"host.docker.internal\", \"\");\r\n\t\t\t\tif(url.length()>0 && url.charAt(0)==':') {\r\n\t\t\t\t\turl = url.substring(1);\r\n\t\t\t\t}\r\n\t\t\t\tif(url.indexOf(\"/\")!=-1) {\r\n\t\t\t\t\turl = url.substring(0, url.indexOf(\"/\"));\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\tInteger.parseInt(url);\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tpublic static void setCorsHeaders(Response response) {\r\n\t\tif(Boolean.FALSE.toString().equalsIgnoreCase(System.getenv(\"cors.enabled\")) || Boolean.FALSE.toString().equalsIgnoreCase(System.getProperty(\"cors.enabled\"))) {\r\n\t\t} else {\r\n\t\t\tresponse.setHeader(\"Access-Control-Allow-Origin\", \"*\");\r\n\t\t\tresponse.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, DELETE, PUT\");\r\n\t\t\tresponse.setHeader(\"Access-Control-Allow-Headers\", \"*\");\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic ClassLoader getProjectClassLoader() {\r\n\t\treturn projectClassLoader;\r\n\t}\r\n\r\n\tprivate final Map<String, List<Map<String, String>>> providerTestDataMap = new HashMap<String, List<Map<String,String>>>();\r\n\tprivate final Map<String, String> fileProviderStateMap = new HashMap<String, String>();\r\n\t\r\n\tpublic List<Map<String, String>> getProviderTestDataMap(String providerName) {\r\n\t if(liveProviders.containsKey(providerName))\r\n {\r\n GatfTestDataProvider provider = liveProviders.get(providerName);\r\n return getProviderData(provider, null);\r\n }\r\n\t else \r\n\t {\r\n\t return providerTestDataMap.get(providerName);\r\n\t }\r\n\t}\r\n\t\r\n\tpublic String getFileProviderHash(String name) {\r\n\t if(!fileProviderStateMap.containsKey(name)) {\r\n\t return fileProviderStateMap.get(name);\r\n\t }\r\n\t return null;\r\n\t}\r\n\t\r\n\tpublic void newProvider(String name) {\r\n\t if(!providerTestDataMap.containsKey(name)) {\r\n\t providerTestDataMap.put(name, new ArrayList<Map<String,String>>());\r\n\t }\r\n\t}\r\n\t\r\n\tprivate final Map<String, TestDataSource> dataSourceMap = new HashMap<String, TestDataSource>();\r\n\t\r\n\tprivate final Map<String, TestDataSource> dataSourceMapForProfiling = new HashMap<String, TestDataSource>();\r\n\t\r\n\tprivate final Map<String, GatfTestDataSourceHook> dataSourceHooksMap = new HashMap<String, GatfTestDataSourceHook>();\r\n\r\n\tprivate final SingleTestCaseExecutor singleTestCaseExecutor = new SingleTestCaseExecutor();\r\n\t\r\n\tprivate final ScenarioTestCaseExecutor scenarioTestCaseExecutor = new ScenarioTestCaseExecutor();\r\n\t\r\n\tprivate final PerformanceTestCaseExecutor performanceTestCaseExecutor = new PerformanceTestCaseExecutor();\r\n\t\r\n\tprivate final Map<String, GatfTestDataProvider> liveProviders = new HashMap<String, GatfTestDataProvider>();\r\n\r\n\tpublic SingleTestCaseExecutor getSingleTestCaseExecutor() {\r\n\t\treturn singleTestCaseExecutor;\r\n\t}\r\n\r\n\tpublic ScenarioTestCaseExecutor getScenarioTestCaseExecutor() {\r\n\t\treturn scenarioTestCaseExecutor;\r\n\t}\r\n\r\n\tpublic PerformanceTestCaseExecutor getPerformanceTestCaseExecutor() {\r\n\t\treturn performanceTestCaseExecutor;\r\n\t}\r\n\r\n\tpublic AcceptanceTestContext(){}\r\n\t\r\n\tpublic AcceptanceTestContext(GatfExecutorConfig gatfExecutorConfig, ClassLoader projectClassLoader)\r\n\t{\r\n\t\tthis.gatfExecutorConfig = gatfExecutorConfig;\r\n\t\tthis.projectClassLoader = projectClassLoader;\r\n\t\tgetWorkflowContextHandler().init();\r\n\t}\r\n\t\r\n\tpublic AcceptanceTestContext(DistributedAcceptanceContext dContext, ClassLoader projectClassLoader)\r\n\t{\r\n this.projectClassLoader = projectClassLoader;\r\n\t\tthis.gatfExecutorConfig = dContext.getConfig();\r\n\t\tthis.httpHeaders.putAll(dContext.getHttpHeaders());\r\n\t\tthis.soapEndpoints.putAll(dContext.getSoapEndpoints());\r\n\t\tthis.soapActions.putAll(dContext.getSoapActions());\r\n\t\ttry {\r\n\t\t\tif(dContext.getSoapMessages()!=null) {\r\n\t\t\t\tDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n\t\t\t\tDocumentBuilder db = dbf.newDocumentBuilder();\r\n\t\t\t\tfor (Map.Entry<String, String> soapMsg : dContext.getSoapMessages().entrySet()) {\r\n\t\t\t\t\tDocument soapMessage = db.parse(new ByteArrayInputStream(soapMsg.getValue().getBytes()));\r\n\t\t\t\t\tthis.soapMessages.put(soapMsg.getKey(), soapMessage);\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\t// TODO: handle exception\r\n\t\t}\r\n\t\tgetWorkflowContextHandler().init();\r\n\t}\r\n\t\r\n\tpublic GatfExecutorConfig getGatfExecutorConfig() {\r\n\t\treturn gatfExecutorConfig;\r\n\t}\r\n\r\n\tpublic void setGatfExecutorConfig(GatfExecutorConfig gatfExecutorConfig) {\r\n\t\tthis.gatfExecutorConfig = gatfExecutorConfig;\r\n\t}\r\n\r\n\tpublic ConcurrentHashMap<Integer, String> getSessionIdentifiers() {\r\n\t\treturn sessionIdentifiers;\r\n\t}\r\n\r\n\tpublic void setSessionIdentifiers(\r\n\t\t\tConcurrentHashMap<Integer, String> sessionIdentifiers) {\r\n\t\tthis.sessionIdentifiers = sessionIdentifiers;\r\n\t}\r\n\r\n\tpublic void setSessionIdentifier(String identifier, TestCase testCase) {\r\n\t\tInteger simulationNumber = testCase.getSimulationNumber();\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\tsimulationNumber = -1;\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\tsimulationNumber = -2;\r\n\t\t} else if(simulationNumber==null) {\r\n\t\t\tsimulationNumber = 0;\r\n\t\t}\r\n\t\tsessionIdentifiers.put(simulationNumber, identifier);\r\n\t}\r\n\t\r\n\tpublic String getSessionIdentifier(TestCase testCase) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn sessionIdentifiers.get(-1);\r\n\t\t}\r\n\t\tif(testCase.isExternalApi()) {\r\n\t\t\treturn sessionIdentifiers.get(-2);\r\n\t\t}\r\n\t\tif(testCase.getSimulationNumber()!=null)\r\n\t\t\treturn sessionIdentifiers.get(testCase.getSimulationNumber());\r\n\t\t\r\n\t\treturn sessionIdentifiers.get(0);\r\n\t}\r\n\t\r\n\tpublic Map<String, String> getHttpHeaders() {\r\n\t\treturn httpHeaders;\r\n\t}\r\n\r\n\tpublic Map<String, String> getSoapEndpoints() {\r\n\t\treturn soapEndpoints;\r\n\t}\r\n\r\n\tpublic Map<String, Document> getSoapMessages() {\r\n\t\treturn soapMessages;\r\n\t}\r\n\r\n\tpublic Map<String, String> getSoapActions() {\r\n\t\treturn soapActions;\r\n\t}\r\n\r\n\tpublic WorkflowContextHandler getWorkflowContextHandler() {\r\n\t\treturn workflowContextHandler;\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"rawtypes\")\r\n\tpublic Class addTestCaseHooks(Method method) {\r\n\t\tClass claz = null;\r\n\t\tif(method!=null && Modifier.isStatic(method.getModifiers())) {\r\n\t\t\t\r\n\t\t\tAnnotation preHook = method.getAnnotation(PreTestCaseExecutionHook.class);\r\n Annotation postHook = method.getAnnotation(PostTestCaseExecutionHook.class);\r\n\t\t\t\r\n\t\t\tif(preHook!=null)\r\n\t\t\t{\r\n\t\t\t\tPreTestCaseExecutionHook hook = (PreTestCaseExecutionHook)preHook;\r\n\t\t\t\t\r\n\t\t\t\tif(method.getParameterTypes().length!=1 || !method.getParameterTypes()[0].equals(TestCase.class))\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.severe(\"PreTestCaseExecutionHook annotated methods should \" +\r\n\t\t\t\t\t\t\t\"confirm to the method signature - `public static void {methodName} (\" +\r\n\t\t\t\t\t\t\t\"TestCase testCase)`\");\r\n\t\t\t\t\treturn claz;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(hook.value()!=null && hook.value().length>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (String testCaseName : hook.value()) {\r\n\t\t\t\t\t\tif(testCaseName!=null && !testCaseName.trim().isEmpty()) {\r\n\t\t\t\t\t\t\tprePostTestCaseExecHooks.put(\"pre\"+testCaseName, method);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tprePostTestCaseExecHooks.put(\"preAll\", method);\r\n\t\t\t\t}\r\n\t\t\t\tclaz = method.getDeclaringClass();\r\n\t\t\t}\r\n\t\t\tif(postHook!=null)\r\n\t\t\t{\r\n\t\t\t\tPostTestCaseExecutionHook hook = (PostTestCaseExecutionHook)postHook;\r\n\t\t\t\t\r\n\t\t\t\tif(method.getParameterTypes().length!=1 || !method.getParameterTypes()[0].equals(TestCaseReport.class))\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.severe(\"PostTestCaseExecutionHook annotated methods should \" +\r\n\t\t\t\t\t\t\t\"confirm to the method signature - `public static void {methodName} (\" +\r\n\t\t\t\t\t\t\t\"TestCaseReport testCaseReport)`\");\r\n\t\t\t\t\treturn claz;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(hook.value()!=null && hook.value().length>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (String testCaseName : hook.value()) {\r\n\t\t\t\t\t\tif(testCaseName!=null && !testCaseName.trim().isEmpty()) {\r\n\t\t\t\t\t\t\tprePostTestCaseExecHooks.put(\"post\"+testCaseName, method);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tprePostTestCaseExecHooks.put(\"postAll\", method);\r\n\t\t\t\t}\r\n\t\t\t\tclaz = method.getDeclaringClass();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn claz;\r\n\t}\r\n\t\r\n\tpublic List<Method> getPrePostHook(TestCase testCase, boolean isPreHook) {\r\n\t\tList<Method> methods = new ArrayList<Method>();\r\n\t\tString hookKey = (isPreHook?\"pre\":\"post\") + testCase.getName();\r\n\t\tMethod meth = prePostTestCaseExecHooks.get(hookKey);\r\n\t\tif(meth!=null)\r\n\t\t\tmethods.add(meth);\r\n\t\tmeth = prePostTestCaseExecHooks.get((isPreHook?\"preAll\":\"postAll\"));\r\n\t\tif(meth!=null)\r\n\t\t\tmethods.add(meth);\r\n\t\treturn methods;\r\n\t}\r\n\t\r\n\tpublic File getResourceFile(String filename) {\r\n\t\tFile basePath = new File(gatfExecutorConfig.getTestCasesBasePath());\r\n\t File testPath = new File(basePath, gatfExecutorConfig.getTestCaseDir());\r\n\t File resource = new File(testPath, filename);\r\n if(!resource.exists()) {\r\n resource = new File(basePath, filename);\r\n }\r\n\t\treturn resource;\r\n\t}\r\n\t\r\n\tpublic File getNewOutResourceFile(String filename) {\r\n\t\tFile basePath = new File(gatfExecutorConfig.getOutFilesBasePath());\r\n\t\tFile resource = new File(basePath, gatfExecutorConfig.getOutFilesDir());\r\n\t\tFile file = new File(resource, filename);\r\n\t\tif(!file.exists()) {\r\n\t\t\ttry {\r\n\t\t\t\tfile.createNewFile();\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn file;\r\n\t}\r\n\t\r\n\tpublic File getOutDir() {\r\n\t\tFile basePath = new File(gatfExecutorConfig.getOutFilesBasePath());\r\n\t\tFile resource = new File(basePath, gatfExecutorConfig.getOutFilesDir());\r\n\t\treturn resource;\r\n\t}\r\n\t\r\n\tpublic String getOutDirPath() {\r\n\t\tFile basePath = new File(gatfExecutorConfig.getOutFilesBasePath());\r\n\t\tFile resource = new File(basePath, gatfExecutorConfig.getOutFilesDir());\r\n\t\treturn resource.getAbsolutePath();\r\n\t}\r\n\t\r\n\tpublic Map<String, List<TestCase>> getRelatedTestCases() {\r\n\t\treturn relatedTestCases;\r\n\t}\r\n\r\n\tpublic static void removeFolder(File folder)\r\n\t{\r\n\t\tif(folder==null || !folder.exists())return;\r\n\t\ttry {\r\n\t\t\tFileUtils.deleteDirectory(folder);\r\n\t\t} catch (IOException e) {\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void validateAndInit(boolean flag) throws Exception\r\n\t{\r\n\t\tgatfExecutorConfig.validate();\r\n\t\t\r\n\t\tif(gatfExecutorConfig.getOutFilesBasePath()!=null)\r\n\t\t{\r\n\t\t\tFile basePath = new File(gatfExecutorConfig.getOutFilesBasePath().trim());\r\n\t\t\tAssert.assertTrue(\"Invalid out files base path..\", basePath.exists());\r\n\t\t\tgatfExecutorConfig.setOutFilesBasePath(basePath.getAbsolutePath());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tFile basePath = new File(System.getProperty(\"user.dir\"));\r\n\t\t\tgatfExecutorConfig.setOutFilesBasePath(basePath.getAbsolutePath());\r\n\t\t}\r\n\t\t\r\n\t\tif(gatfExecutorConfig.getTestCasesBasePath()!=null)\r\n\t\t{\r\n\t\t\tFile basePath = new File(gatfExecutorConfig.getTestCasesBasePath());\r\n\t\t\tAssert.assertTrue(\"Invalid test cases base path..\", basePath.exists());\r\n\t\t\tgatfExecutorConfig.setTestCasesBasePath(basePath.getAbsolutePath());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tFile basePath = new File(System.getProperty(\"user.dir\"));\r\n\t\t\tgatfExecutorConfig.setTestCasesBasePath(basePath.getAbsolutePath());\r\n\t\t}\r\n\t\t\r\n\t\tAssert.assertEquals(\"Testcase directory not found...\", getResourceFile(gatfExecutorConfig.getTestCaseDir()).exists(), true);\r\n\t\t\r\n\t\tif(StringUtils.isNotBlank(gatfExecutorConfig.getBaseUrl()))\r\n\t\t{\r\n\t\t\tAssert.assertTrue(\"Base URL is not valid\", AcceptanceTestContext.isValidUrl(gatfExecutorConfig.getBaseUrl()));\r\n\t\t}\r\n\t\t\r\n\t\tif(gatfExecutorConfig.getOutFilesDir()!=null && !gatfExecutorConfig.getOutFilesDir().trim().isEmpty())\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tif(gatfExecutorConfig.getOutFilesBasePath()!=null)\r\n\t\t\t\t{\r\n\t\t\t\t\tFile basePath = new File(gatfExecutorConfig.getOutFilesBasePath());\r\n\t\t\t\t\tFile resource = new File(basePath, gatfExecutorConfig.getOutFilesDir());\r\n\t\t\t\t\tif(flag)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tremoveFolder(resource);\r\n\t\t\t\t\t\tFile nresource = new File(basePath, gatfExecutorConfig.getOutFilesDir());\r\n\t\t\t\t\t\tnresource.mkdirs();\r\n\t\t\t\t\t\tAssert.assertTrue(\"Out files directory could not be created...\", nresource.exists());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tFile resource = new File(System.getProperty(\"user.dir\"));\r\n\t\t\t\t\tFile file = new File(resource, gatfExecutorConfig.getOutFilesDir());\r\n\t\t\t\t\tif(flag)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tremoveFolder(file);\r\n\t\t\t\t\t\tFile nresource = new File(resource, gatfExecutorConfig.getOutFilesDir());\r\n\t\t\t\t\t\tnresource.mkdir();\r\n\t\t\t\t\t\tAssert.assertTrue(\"Out files directory could not be created...\", nresource.exists());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tgatfExecutorConfig.setOutFilesDir(null);\r\n\t\t\t}\r\n\t\t\tAssert.assertNotNull(\"Testcase out file directory not found...\", gatfExecutorConfig.getOutFilesDir());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tFile resource = new File(System.getProperty(\"user.dir\"));\r\n\t\t\tif(flag)\r\n\t\t\t{\r\n\t\t\t\tremoveFolder(resource);\r\n\t\t\t\tFile nresource = new File(System.getProperty(\"user.dir\"), \"out\");\r\n\t\t\t\tnresource.mkdir();\r\n\t\t\t}\r\n\t\t\tgatfExecutorConfig.setOutFilesDir(\"out\");\r\n\t\t\tgatfExecutorConfig.setOutFilesBasePath(System.getProperty(\"user.dir\"));\r\n\t\t}\r\n\t\t\r\n\t\tif(flag)\r\n\t\t{\r\n\t\t\tinitSoapContextAndHttpHeaders();\r\n\t\t\t\r\n\t\t\tinitTestDataProviderAndGlobalVariables();\r\n\t\t}\r\n\t\t\r\n\t\tinitServerLogsApis();\r\n\t}\r\n\t\r\n\tpublic void initServerLogsApis() throws Exception {\r\n\t\tFile basePath = new File(gatfExecutorConfig.getTestCasesBasePath());\r\n\t\tFile resource = new File(basePath, GATF_SERVER_LOGS_API_FILE_NM);\r\n\t\tif(resource.exists() && gatfExecutorConfig.isFetchFailureLogs()) {\r\n\t\t\tTestCaseFinder finder = new XMLTestCaseFinder();\r\n\t\t\tserverLogsApiLst.clear();\r\n\t\t\tserverLogsApiLst.addAll(finder.resolveTestCases(resource));\r\n\t\t\tfor (TestCase testCase : serverLogsApiLst) {\r\n\t\t\t\ttestCase.setSourcefileName(GATF_SERVER_LOGS_API_FILE_NM);\r\n\t\t\t\tif(testCase.getSimulationNumber()==null)\r\n\t\t\t\t{\r\n\t\t\t\t\ttestCase.setSimulationNumber(0);\r\n\t\t\t\t}\r\n\t\t\t\ttestCase.setExternalApi(true);\r\n\t\t\t\ttestCase.validate(getHttpHeaders(), null);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void initTestDataProviderAndGlobalVariables() throws Exception {\r\n\t\tGatfTestDataConfig gatfTestDataConfig = null;\r\n\t\tif(gatfExecutorConfig.getTestDataConfigFile()!=null) {\r\n\t\t\tFile file = getResourceFile(gatfExecutorConfig.getTestDataConfigFile());\r\n\t\t\tAssert.assertNotNull(\"Testdata configuration file not found...\", file);\r\n\t\t\tAssert.assertEquals(\"Testdata configuration file not found...\", file.exists(), true);\r\n\t\t\t\r\n\t\t\tif(gatfExecutorConfig.getTestDataConfigFile().trim().endsWith(\".xml\")) {\r\n\t\t\t\tXStream xstream = new XStream(new DomDriver(\"UTF-8\"));\r\n\t\t \r\n\t\t xstream.allowTypes(new Class[]{GatfTestDataConfig.class, GatfTestDataProvider.class});\r\n\t\t\t\txstream.processAnnotations(new Class[]{GatfTestDataConfig.class, GatfTestDataProvider.class});\r\n\t\t\t\txstream.alias(\"gatf-testdata-provider\", GatfTestDataProvider.class);\r\n\t\t\t\txstream.alias(\"args\", String[].class);\r\n\t\t\t\txstream.alias(\"arg\", String.class);\r\n\t\t\t\tgatfTestDataConfig = (GatfTestDataConfig)xstream.fromXML(file);\r\n\t\t\t} else {\r\n\t\t\t\tgatfTestDataConfig = WorkflowContextHandler.OM.readValue(file, GatfTestDataConfig.class);\r\n\t\t\t}\r\n\t\t\tgatfExecutorConfig.setGatfTestDataConfig(gatfTestDataConfig);\r\n\t\t} else {\r\n\t\t\tgatfTestDataConfig = gatfExecutorConfig.getGatfTestDataConfig();\r\n\t\t}\r\n\t\t\r\n\t\thandleTestDataSourcesAndHooks(gatfTestDataConfig);\r\n\t}\r\n\r\n\tpublic void handleTestDataSourcesAndHooks(GatfTestDataConfig gatfTestDataConfig) {\r\n\t\tif(gatfTestDataConfig!=null) {\r\n\t\t\tgetWorkflowContextHandler().addGlobalVariables(gatfTestDataConfig.getGlobalVariables());\r\n\t\t\t\r\n\t\t\tif(gatfTestDataConfig.getDataSourceList()!=null)\r\n\t\t\t{\r\n\t\t\t\thandleDataSources(gatfTestDataConfig.getDataSourceList(), false);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(gatfTestDataConfig.getDataSourceListForProfiling()!=null)\r\n\t\t\t{\r\n\t\t\t\thandleDataSources(gatfTestDataConfig.getDataSourceListForProfiling(), true);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(gatfTestDataConfig.getDataSourceHooks()!=null)\r\n\t\t\t{\r\n\t\t\t\thandleHooks(gatfTestDataConfig.getDataSourceHooks());\r\n\t\t\t}\r\n\t\t\t\t\r\n\t\t\tif(gatfTestDataConfig.getProviderTestDataList()!=null)\r\n\t\t\t{\r\n\t\t\t\thandleProviders(gatfTestDataConfig.getProviderTestDataList());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static Map<String, String> getHttpHeadersMap() throws Exception\r\n\t{\r\n\t\tMap<String, String> headers = new HashMap<String, String>();\r\n\t\tField[] declaredFields = HttpHeaders.class.getDeclaredFields();\r\n\t\tfor (Field field : declaredFields) {\r\n\t\t\tif (java.lang.reflect.Modifier.isStatic(field.getModifiers())\r\n\t\t\t\t\t&& field.getType().equals(String.class)) {\r\n\t\t\t\theaders.put(field.get(null).toString().toLowerCase(), field.get(null).toString());\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn headers;\r\n\t}\r\n\t\r\n\tprivate void initSoapContextAndHttpHeaders() throws Exception\r\n\t{\r\n\t\tField[] declaredFields = HttpHeaders.class.getDeclaredFields();\r\n\t\tfor (Field field : declaredFields) {\r\n\t\t\tif (java.lang.reflect.Modifier.isStatic(field.getModifiers())\r\n\t\t\t\t\t&& field.getType().equals(String.class)) {\r\n\t\t\t\thttpHeaders.put(field.get(null).toString().toLowerCase(), field.get(null).toString());\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tFile file = null;\r\n\t\tif(gatfExecutorConfig.getWsdlLocFile()!=null && !gatfExecutorConfig.getWsdlLocFile().trim().isEmpty())\r\n\t\t\tfile = getResourceFile(gatfExecutorConfig.getWsdlLocFile());\r\n\t\t\r\n\t\tif(file!=null)\r\n\t\t{\r\n\t\t\tScanner s = new Scanner(file);\r\n\t\t\ts.useDelimiter(\"\\n\");\r\n\t\t\tList<String> list = new ArrayList<String>();\r\n\t\t\twhile (s.hasNext()) {\r\n\t\t\t\tlist.add(s.next().replace(\"\\r\", \"\"));\r\n\t\t\t}\r\n\t\t\ts.close();\r\n\t\r\n\t\t\tfor (String wsdlLoc : list) {\r\n\t\t\t\tif(!wsdlLoc.trim().isEmpty())\r\n\t\t\t\t{\r\n\t\t\t\t\tString[] wsdlLocParts = wsdlLoc.split(\",\");\r\n\t\t\t\t\tlogger.info(\"Started Parsing WSDL location - \" + wsdlLocParts[1]);\r\n\t\t\t\t\tWsdl wsdl = Wsdl.parse(wsdlLocParts[1]);\r\n\t\t\t\t\tfor (QName bindingName : wsdl.getBindings()) {\r\n\t\t\t\t\t\tSoapBuilder builder = wsdl.getBuilder(bindingName);\r\n\t\t\t\t\t\tfor (SoapOperation operation : builder.getOperations()) {\r\n\t\t\t\t\t\t\tString request = builder.buildInputMessage(operation);\r\n\t\t\t\t\t\t\tDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n\t\t\t\t\t\t\tDocumentBuilder db = dbf.newDocumentBuilder();\r\n\t\t\t\t\t\t\tDocument soapMessage = db.parse(new ByteArrayInputStream(request.getBytes()));\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif(gatfExecutorConfig.isDistributedLoadTests()) {\r\n\t\t\t\t\t\t\t\tsoapStrMessages.put(wsdlLocParts[0]+operation.getOperationName(), request);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tsoapMessages.put(wsdlLocParts[0]+operation.getOperationName(), soapMessage);\r\n\t\t\t\t\t\t\tif(operation.getSoapAction()!=null) {\r\n\t\t\t\t\t\t\t\tsoapActions.put(wsdlLocParts[0]+operation.getOperationName(), operation.getSoapAction());\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tlogger.info(\"Adding message for SOAP operation - \" + operation.getOperationName());\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tsoapEndpoints.put(wsdlLocParts[0], builder.getServiceUrls().get(0));\r\n\t\t\t\t\t\tlogger.info(\"Adding SOAP Service endpoint - \" + builder.getServiceUrls().get(0));\r\n\t\t\t\t\t}\r\n\t\t\t\t\tlogger.info(\"Done Parsing WSDL location - \" + wsdlLocParts[1]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void shutdown() {\r\n\t\tfor (GatfTestDataSourceHook dataSourceHook : dataSourceHooksMap.values()) {\r\n\t\t\tTestDataSource dataSource = dataSourceMap.get(dataSourceHook.getDataSourceName());\r\n\t\t\t\r\n\t\t\tAssert.assertNotNull(\"No DataSource found\", dataSource);\r\n\t\t\t\r\n\t\t\tif(dataSourceHook.isExecuteOnShutdown() && dataSourceHook.getQueryStrs()!=null) {\r\n\t\t\t\tfor (String query : dataSourceHook.getQueryStrs()) {\r\n\t\t\t\t\tboolean flag = false;\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tflag = dataSource.execute(query);\r\n\t\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(!flag) {\r\n\t\t\t\t\t\tlogger.severe(\"Shutdown DataSourceHook execution for \" + dataSourceHook.getHookName()\r\n\t\t\t\t\t\t\t\t+ \" failed, queryString = \" + query);\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\tfor (GatfTestDataSourceHook dataSourceHook : dataSourceHooksMap.values()) {\r\n\t\t\tTestDataSource dataSource = dataSourceMap.get(dataSourceHook.getDataSourceName());\r\n\t\t\t\r\n\t\t\tAssert.assertNotNull(\"No DataSource found\", dataSource);\r\n\t\t\t\r\n\t\t\tdataSource.destroy();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void executeDataSourceHook(String hookName) {\r\n\t\tGatfTestDataSourceHook dataSourceHook = dataSourceHooksMap.get(hookName);\r\n\t\tAssert.assertNotNull(\"No DataSourceHook found\", dataSourceHook);\r\n\t\t\r\n\t\tTestDataSource dataSource = dataSourceMap.get(dataSourceHook.getDataSourceName());\r\n\t\tAssert.assertNotNull(\"No DataSource found\", dataSource);\r\n\t\t\r\n\t\tfor (String query : dataSourceHook.getQueryStrs()) {\r\n\t\t\tboolean flag = dataSource.execute(query);\r\n\t\t\tif(!flag) {\r\n\t\t\t\tAssert.assertNotNull(\"DataSourceHook execution for \" + dataSourceHook.getHookName()\r\n\t\t\t\t\t\t+ \" failed...\", null);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"rawtypes\")\r\n\tprivate void handleDataSources(List<GatfTestDataSource> dataSourceList, boolean forProfiling)\r\n\t{\r\n\t\tfor (GatfTestDataSource dataSource : dataSourceList) {\r\n\t\t\tAssert.assertNotNull(\"DataSource name is not defined\", dataSource.getDataSourceName());\r\n\t\t\tAssert.assertNotNull(\"DataSource class is not defined\", dataSource.getDataSourceClass());\r\n\t\t\tAssert.assertNotNull(\"DataSource args not defined\", dataSource.getArgs());\r\n\t\t\tAssert.assertTrue(\"DataSource args empty\", dataSource.getArgs().length>0);\r\n\t\t\tAssert.assertNull(\"Duplicate DataSource name found\", dataSourceMap.get(dataSource.getDataSourceName()));\r\n\t\t\t\r\n\t\t\tTestDataSource testDataSource = null;\r\n\t\t\tif(SQLDatabaseTestDataSource.class.getCanonicalName().equals(dataSource.getDataSourceClass())) {\r\n\t\t\t\ttestDataSource = new SQLDatabaseTestDataSource();\r\n\t\t\t} else if(MongoDBTestDataSource.class.getCanonicalName().equals(dataSource.getDataSourceClass())) {\r\n\t\t\t\ttestDataSource = new MongoDBTestDataSource();\r\n\t\t\t} else {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tClass claz = loadCustomClass(dataSource.getDataSourceClass());\r\n\t\t\t\t\tClass[] classes = claz.getInterfaces();\r\n\t\t\t\t\tboolean validProvider = false;\r\n\t\t\t\t\tif(classes!=null) {\r\n\t\t\t\t\t\tfor (Class class1 : classes) {\r\n\t\t\t\t\t\t\tif(class1.equals(TestDataSource.class)) {\r\n\t\t\t\t\t\t\t\tvalidProvider = true;\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tAssert.assertTrue(\"DataSource class should extend the TestDataSource class\", validProvider);\r\n\t\t\t\t\t@SuppressWarnings(\"unchecked\")\r\n\t\t\t\t\tObject providerInstance = claz.getDeclaredConstructor().newInstance();\r\n\t\t\t\t\ttestDataSource = (TestDataSource)providerInstance;\r\n\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tthrow new AssertionError(e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\ttestDataSource.setClassName(dataSource.getDataSourceClass());\r\n\t\t\ttestDataSource.setArgs(dataSource.getArgs());\r\n\t\t\ttestDataSource.setContext(this);\r\n\t\t\ttestDataSource.setDataSourceName(dataSource.getDataSourceName());\r\n\t\t\tif(dataSource.getPoolSize()>1)\r\n\t\t\t{\r\n\t\t\t\ttestDataSource.setPoolSize(dataSource.getPoolSize());\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(forProfiling)\r\n\t\t\t{\r\n\t\t\t\ttestDataSource.setPoolSize(1);\r\n\t\t\t\ttestDataSource.init();\r\n\t\t\t\tdataSourceMapForProfiling.put(dataSource.getDataSourceName(), testDataSource);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttestDataSource.init();\r\n\t\t\t\tdataSourceMap.put(dataSource.getDataSourceName(), testDataSource);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Map<String, TestDataSource> getDataSourceMapForProfiling()\r\n\t{\r\n\t\treturn dataSourceMapForProfiling;\r\n\t}\r\n\t\r\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\r\n\tprivate void handleHooks(List<GatfTestDataSourceHook> dataSourceHooks)\r\n\t{\r\n\t\tfor (GatfTestDataSourceHook dataSourceHook : dataSourceHooks) {\r\n\t\t\tAssert.assertNotNull(\"DataSourceHook name is not defined\", dataSourceHook.getHookName());\r\n\t\t\tAssert.assertNotNull(\"DataSourceHook query string is not defined\", dataSourceHook.getQueryStrs());\r\n\t\t\tAssert.assertNull(\"Duplicate DataSourceHook name found\", dataSourceHooksMap.get(dataSourceHook.getHookName()));\r\n\t\t\t\r\n\t\t\tTestDataSource dataSource = null;\r\n\t\t\tif(dataSourceHook.getDataSourceName()!=null && dataSourceHook.getHookClass()==null)\r\n\t\t\t{\r\n\t\t\t\tdataSource = dataSourceMap.get(dataSourceHook.getDataSourceName());\r\n\t\t\t\tAssert.assertNotNull(\"No DataSource found\", dataSource);\r\n\t\t\t}\r\n\t\t\telse if(dataSourceHook.getDataSourceName()!=null && dataSourceHook.getHookClass()!=null)\r\n\t\t\t{\r\n\t\t\t\tAssert.assertNotNull(\"Specify either hookClass or dataSourceName\", null);\r\n\t\t\t}\r\n\t\t\telse if(dataSourceHook.getDataSourceName()==null && dataSourceHook.getHookClass()==null)\r\n\t\t\t{\r\n\t\t\t\tAssert.assertNotNull(\"Specify any one of hookClass or dataSourceName\", null);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tdataSourceHooksMap.put(dataSourceHook.getHookName(), dataSourceHook);\r\n\t\t\t\r\n\t\t\tTestDataHook testDataHook = null;\r\n\t\t\tif(dataSourceHook.getHookClass()!=null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tClass claz = loadCustomClass(dataSourceHook.getHookClass());\r\n\t\t\t\t\tClass[] classes = claz.getInterfaces();\r\n\t\t\t\t\tboolean validProvider = false;\r\n\t\t\t\t\tif(classes!=null) {\r\n\t\t\t\t\t\tfor (Class class1 : classes) {\r\n\t\t\t\t\t\t\tif(class1.equals(TestDataProvider.class)) {\r\n\t\t\t\t\t\t\t\tvalidProvider = true;\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tAssert.assertTrue(\"Hook class should implement the TestDataHook class\", validProvider);\r\n\t\t\t\t\tObject providerInstance = claz.getDeclaredConstructor().newInstance();\r\n\t\t\t\t\ttestDataHook = (TestDataHook)providerInstance;\r\n\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tthrow new AssertionError(e);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\ttestDataHook = dataSource;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(dataSourceHook.isExecuteOnStart()) {\r\n\t\t\t\tfor (String query : dataSourceHook.getQueryStrs()) {\r\n\t\t\t\t\tboolean flag = false;\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tflag = testDataHook.execute(query);\r\n\t\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(!flag) {\r\n\t\t\t\t\t\tlogger.severe(\"Startup DataSourceHook execution for \" + dataSourceHook.getHookName()\r\n\t\t\t\t\t\t\t\t+ \" failed, queryString = \" + query);\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}\r\n\t\r\n\tprivate void handleProviders(List<GatfTestDataProvider> providerTestDataList)\r\n\t{\r\n\t\tfor (GatfTestDataProvider provider : providerTestDataList) {\r\n\t\t\tAssert.assertNotNull(\"Provider name is not defined\", provider.getProviderName());\r\n\t\t\t\r\n\t\t\tAssert.assertNotNull(\"Provider properties is not defined\", provider.getProviderProperties());\r\n\t\t\t\r\n\t\t\tAssert.assertNull(\"Duplicate Provider name found\", providerTestDataMap.get(provider.getProviderName()));\r\n\t\t\t\r\n\t\t\tTestDataSource dataSource = null;\r\n\t\t\tif(provider.getDataSourceName()!=null && provider.getProviderClass()==null)\r\n\t\t\t{\t\r\n\t\t\t\tAssert.assertNotNull(\"Provider DataSource name is not defined\", provider.getDataSourceName());\r\n\t\t\t\tdataSource = dataSourceMap.get(provider.getDataSourceName());\r\n\t\t\t\t\r\n\t\t\t\tAssert.assertNotNull(\"No DataSource found\", dataSource);\r\n\t\t\t\t\r\n\t\t\t\tif(dataSource instanceof MongoDBTestDataSource)\r\n\t\t\t\t{\r\n\t\t\t\t\tAssert.assertNotNull(\"Provider query string is not defined\", provider.getQueryStr());\r\n\t\t\t\t\tAssert.assertNotNull(\"Provider source properties not defined\", provider.getSourceProperties());\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(dataSource instanceof SQLDatabaseTestDataSource)\r\n\t\t\t\t{\r\n\t\t\t\t\tAssert.assertNotNull(\"Provider query string is not defined\", provider.getQueryStr());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if(provider.getDataSourceName()!=null && provider.getProviderClass()!=null)\r\n\t\t\t{\r\n\t\t\t\tAssert.assertNotNull(\"Specify either providerClass or dataSourceName\", null);\r\n\t\t\t}\r\n\t\t\telse if(provider.getDataSourceName()==null && provider.getProviderClass()==null)\r\n\t\t\t{\r\n\t\t\t\tAssert.assertNotNull(\"Specify any one of providerClass or dataSourceName\", null);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tif(provider.isEnabled()==null) {\r\n\t\t\t\tprovider.setEnabled(true);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(!provider.isEnabled()) {\r\n\t\t\t\tlogger.info(\"Provider \" + provider.getProviderName() + \" is Disabled...\");\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(provider.isLive()) {\r\n\t\t\t\tliveProviders.put(provider.getProviderName(), provider);\r\n\t\t\t\tlogger.info(\"Provider \" + provider.getProviderName() + \" is a Live one...\");\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tList<Map<String, String>> testData = getProviderData(provider, null);\r\n\t\t\tif(gatfExecutorConfig.isSeleniumExecutor() && gatfExecutorConfig.getConcurrentUserSimulationNum()>1) {\r\n\t\t\t for (int i = 0; i < gatfExecutorConfig.getConcurrentUserSimulationNum(); i++)\r\n {\r\n\t\t\t if(FileTestDataProvider.class.getCanonicalName().equals(provider.getProviderClass().trim())) {\r\n\t\t\t if(i==0) {\r\n\t\t\t providerTestDataMap.put(provider.getProviderName()+(i+1), testData);\r\n\t\t\t continue;\r\n\t\t\t }\r\n\t\t\t GatfTestDataProvider tp = new GatfTestDataProvider(provider);\r\n\t tp.setProviderName(provider.getProviderName()+(i+1));\r\n\t tp.getArgs()[0] = tp.getArgs()[0] + i;\r\n\t try {\r\n\t logger.info(\"Concurrent simulation scenario #\"+(i+1)+\" fetching provider with filePath \"+tp.getArgs()[0]);\r\n\t List<Map<String, String>> testDataT = getProviderData(tp, null);\r\n\t if(testDataT==null) {\r\n\t testDataT = testData;\r\n\t }\r\n\t providerTestDataMap.put(tp.getProviderName(), testDataT);\r\n\t } catch (Throwable e) {\r\n\t logger.severe(\"Cannot find data provider for the concurrent simulation scenario #\"+(i+1)+\" with name \" + tp.getProviderName());\r\n\t providerTestDataMap.put(tp.getProviderName(), testData);\r\n\t }\r\n\t\t\t } else {\r\n\t\t\t logger.severe(\"Concurrent simulation scenarios need file data providers\");\r\n\t\t\t }\r\n }\r\n\t\t\t} else {\r\n\t\t\t providerTestDataMap.put(provider.getProviderName(), testData);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic List<Map<String, String>> getLiveProviderData(String provName, TestCase testCase)\r\n\t{\r\n\t\tGatfTestDataProvider provider = liveProviders.get(provName);\r\n\t\treturn getProviderData(provider, testCase);\r\n\t}\r\n\t\r\n\tpublic List<Map<String, String>> getAnyProviderData(String provName, TestCase testCase)\r\n\t{\r\n\t\tif(liveProviders.containsKey(provName))\r\n\t\t{\r\n\t\t\tGatfTestDataProvider provider = liveProviders.get(provName);\r\n\t\t\treturn getProviderData(provider, testCase);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn providerTestDataMap.get(provName);\r\n\t\t}\r\n\t}\r\n\t\r\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\r\n\tprivate List<Map<String, String>> getProviderData(GatfTestDataProvider provider, TestCase testCase) {\r\n\t\t\r\n\t\tTestDataSource dataSource = dataSourceMap.get(provider.getDataSourceName());\r\n\t\t\r\n\t\tTestDataProvider testDataProvider = null;\r\n\t\tList<Map<String, String>> testData = null;\r\n\t\tif(provider.getProviderClass()!=null) {\r\n\t\t\tif(FileTestDataProvider.class.getCanonicalName().equals(provider.getProviderClass().trim())) {\r\n\t\t\t\ttestDataProvider = new FileTestDataProvider();\r\n\t\t\t} else if(InlineValueTestDataProvider.class.getCanonicalName().equals(provider.getProviderClass().trim())) {\r\n\t\t\t\ttestDataProvider = new InlineValueTestDataProvider();\r\n\t\t\t} else if(RandomValueTestDataProvider.class.getCanonicalName().equals(provider.getProviderClass().trim())) {\r\n\t\t\t\ttestDataProvider = new RandomValueTestDataProvider();\r\n\t\t\t} else {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tClass claz = loadCustomClass(provider.getProviderClass());\r\n\t\t\t\t\tClass[] classes = claz.getInterfaces();\r\n\t\t\t\t\tboolean validProvider = false;\r\n\t\t\t\t\tif(classes!=null) {\r\n\t\t\t\t\t\tfor (Class class1 : classes) {\r\n\t\t\t\t\t\t\tif(class1.equals(TestDataProvider.class)) {\r\n\t\t\t\t\t\t\t\tvalidProvider = true;\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tAssert.assertTrue(\"Provider class should implement the TestDataProvider class\", validProvider);\r\n\t\t\t\t\tObject providerInstance = claz.getDeclaredConstructor().newInstance();\r\n\t\t\t\t\ttestDataProvider = (TestDataProvider)providerInstance;\r\n\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tthrow new AssertionError(e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\ttestDataProvider = dataSource;\r\n\t\t}\r\n\t\t\r\n\t\t//Live provider queries can have templatized parameter names\r\n\t\tif(provider.isLive() && provider.getQueryStr()!=null)\r\n\t\t{\r\n\t\t\tString oQs = provider.getQueryStr();\r\n\t\t\tprovider = new GatfTestDataProvider(provider);\r\n\t\t\tif(testCase!=null)\r\n\t\t\t{\r\n\t\t\t\tprovider.setQueryStr(getWorkflowContextHandler().evaluateTemplate(testCase, provider.getQueryStr(), this));\r\n\t\t\t\tif(provider.getQueryStr()==null || provider.getQueryStr().isEmpty()) {\r\n\t\t\t\t\tprovider.setQueryStr(oQs);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\ttestData = testDataProvider.provide(provider, this);\r\n\t\tif(testDataProvider instanceof FileTestDataProvider) {\r\n\t\t\tfileProviderStateMap.put(provider.getProviderName(), ((FileTestDataProvider)testDataProvider).getHash());\r\n\t\t}\r\n\t\treturn testData;\r\n\t}\r\n\r\n\tpublic DistributedAcceptanceContext getDistributedContext(String node, List<Object[]> selTestdata)\r\n\t{\r\n\t\tDistributedAcceptanceContext distributedTestContext = new DistributedAcceptanceContext();\r\n\t\tdistributedTestContext.setConfig(gatfExecutorConfig);\r\n\t\tdistributedTestContext.setHttpHeaders(httpHeaders);\r\n\t\tdistributedTestContext.setSoapActions(soapActions);\r\n\t\tdistributedTestContext.setSoapEndpoints(soapEndpoints);\r\n\t\tdistributedTestContext.setSoapMessages(soapStrMessages);\r\n\t\tdistributedTestContext.setNode(node);\r\n\t\tdistributedTestContext.setSelTestdata(selTestdata);\r\n\t\t\r\n\t\treturn distributedTestContext;\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"rawtypes\")\r\n\tprivate Class loadCustomClass(String className) throws ClassNotFoundException\r\n\t{\r\n\t\treturn getProjectClassLoader().loadClass(className);\r\n\t}\r\n\t\r\n\tpublic List<TestCase> getServerLogsApiLst() {\r\n\t\treturn serverLogsApiLst;\r\n\t}\r\n\t\r\n\tpublic TestCase getServerLogApi(boolean isAuth)\r\n\t{\r\n\t\tif(serverLogsApiLst.size()>0)\r\n\t\t{\r\n\t\t\tfor (TestCase tc : serverLogsApiLst) {\r\n\t\t\t\tif(isAuth && gatfExecutorConfig.isServerLogsApiAuthEnabled() && \"authapi\".equals(tc.getName()))\r\n\t\t\t\t{\r\n\t\t\t\t\ttc.setServerApiAuth(true);\r\n\t\t\t\t\ttc.setExternalApi(true);\r\n\t\t\t\t\treturn tc;\r\n\t\t\t\t}\r\n\t\t\t\telse if(!isAuth && \"targetapi\".equals(tc.getName()))\r\n\t\t\t\t{\r\n\t\t\t\t\ttc.setServerApiTarget(true);\r\n\t\t\t\t\ttc.setSecure(gatfExecutorConfig.isServerLogsApiAuthEnabled());\r\n\t\t\t\t\ttc.setExternalApi(true);\r\n\t\t\t\t\treturn tc;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n}\r",
"@XStreamAlias(\"gatf-execute-config\")\r\n@JsonAutoDetect(getterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY, isGetterVisibility=Visibility.NONE)\r\n@JsonInclude(value = Include.NON_NULL)\r\npublic class GatfExecutorConfig implements Serializable, GatfPluginConfig {\r\n\r\n\tprivate static final long serialVersionUID = 1L;\r\n\t\r\n\tprivate String baseUrl;\r\n\t\r\n\tprivate String testCasesBasePath;\r\n\t\r\n\tprivate String testCaseDir;\r\n\t\r\n\tprivate String outFilesBasePath;\r\n\t\r\n\tprivate String outFilesDir;\r\n\t\r\n\tprivate boolean authEnabled;\r\n\t\r\n\tprivate String authUrl;\r\n\t\r\n\tprivate String authExtractAuth;\r\n\t\r\n\tprivate String authParamsDetails;\r\n\t\r\n\tprivate String wsdlLocFile;\r\n\t\r\n\tprivate boolean soapAuthEnabled;\r\n\t\r\n\tprivate String soapAuthWsdlKey;\r\n\t\r\n\tprivate String soapAuthOperation;\r\n\t\r\n\tprivate String soapAuthExtractAuth;\r\n\t\r\n\tprivate Integer numConcurrentExecutions;\r\n\t\r\n\tprivate boolean httpCompressionEnabled;\r\n\t\r\n\tprivate Integer httpConnectionTimeout;\r\n\t\r\n\tprivate Integer httpRequestTimeout;\r\n\t\r\n\tprivate Integer concurrentUserSimulationNum;\r\n\t\r\n\tprivate String testDataConfigFile;\r\n\t\r\n\tprivate String authDataProvider;\r\n\t\r\n\tprivate boolean compareEnabled;\r\n\t\r\n\tprivate GatfTestDataConfig gatfTestDataConfig; \r\n\t\r\n\tprivate Boolean enabled;\r\n\t\r\n\tprivate String[] testCaseHooksPaths;\r\n\t\r\n\tprivate boolean loadTestingEnabled;\r\n\t\r\n\tprivate Long loadTestingTime = 0L;\r\n\t\r\n\tprivate boolean distributedLoadTests;\r\n\t\r\n\tprivate String[] distributedNodes;\r\n\t\r\n\t@XStreamOmitField\r\n\tprivate Integer compareBaseUrlsNum;\r\n\t\r\n\tprivate Long concurrentUserRampUpTime;\r\n\t\r\n\tprivate Integer loadTestingReportSamples;\r\n\t\r\n\tprivate boolean debugEnabled;\r\n\t\r\n\tprivate String[] ignoreFiles;\r\n\t\r\n\tprivate String[] orderedFiles;\r\n\t\r\n\tprivate boolean isOrderByFileName;\r\n\t\r\n\tprivate boolean isServerLogsApiAuthEnabled;\r\n\t\r\n\tprivate String serverLogsApiAuthExtractAuth;\r\n\t\r\n\tprivate boolean isFetchFailureLogs;\r\n\t\r\n\tprivate Integer repeatSuiteExecutionNum = 0;\r\n\t\r\n\tprivate boolean isGenerateExecutionLogs = false;\r\n\t\r\n\tprivate boolean isSeleniumExecutor = false;\r\n\t\r\n\tprivate boolean isSeleniumModuleTests = false;\r\n\t\r\n\tprivate String[] seleniumScripts;\r\n\t\r\n\tprivate SeleniumDriverConfig[] seleniumDriverConfigs;\r\n\t\r\n\tprivate String seleniumLoggerPreferences;\r\n\t\r\n private String javaHome;\r\n \r\n private String javaVersion;\r\n \r\n private String gatfJarPath;\r\n \r\n private boolean selDebugger;\r\n \r\n private String wrkPath;\r\n \r\n private String wrk2Path;\r\n \r\n private String vegetaPath;\r\n \r\n private String autocannonPath;\r\n\t\r\n\tpublic String getBaseUrl() {\r\n\t\treturn baseUrl;\r\n\t}\r\n\r\n\tpublic void setBaseUrl(String baseUrl) {\r\n\t\tthis.baseUrl = baseUrl;\r\n\t}\r\n\r\n\tpublic String getTestCasesBasePath() {\r\n\t\treturn testCasesBasePath;\r\n\t}\r\n\r\n\tpublic void setTestCasesBasePath(String testCasesBasePath) {\r\n\t\tthis.testCasesBasePath = testCasesBasePath;\r\n\t}\r\n\r\n\tpublic String getTestCaseDir() {\r\n\t\treturn testCaseDir;\r\n\t}\r\n\r\n\tpublic void setTestCaseDir(String testCaseDir) {\r\n\t\tthis.testCaseDir = testCaseDir;\r\n\t}\r\n\r\n\tpublic String getOutFilesBasePath() {\r\n\t\treturn outFilesBasePath;\r\n\t}\r\n\r\n\tpublic void setOutFilesBasePath(String outFilesBasePath) {\r\n\t\tthis.outFilesBasePath = outFilesBasePath;\r\n\t}\r\n\r\n\tpublic String getOutFilesDir() {\r\n\t\treturn outFilesDir;\r\n\t}\r\n\r\n\tpublic void setOutFilesDir(String outFilesDir) {\r\n\t\tthis.outFilesDir = outFilesDir;\r\n\t}\r\n\r\n\tpublic void setAuthEnabled(boolean authEnabled) {\r\n\t\tthis.authEnabled = authEnabled;\r\n\t}\r\n\r\n\tpublic String getAuthUrl() {\r\n\t\treturn authUrl;\r\n\t}\r\n\r\n\tpublic void setAuthUrl(String authUrl) {\r\n\t\tthis.authUrl = authUrl;\r\n\t}\r\n\r\n\tpublic String getAuthExtractAuth() {\r\n\t\treturn authExtractAuth;\r\n\t}\r\n\r\n\tpublic void setAuthExtractAuth(String authExtractAuth) {\r\n\t\tthis.authExtractAuth = authExtractAuth;\r\n\t}\r\n\r\n\tpublic String getWsdlLocFile() {\r\n\t\treturn wsdlLocFile;\r\n\t}\r\n\r\n\tpublic void setWsdlLocFile(String wsdlLocFile) {\r\n\t\tthis.wsdlLocFile = wsdlLocFile;\r\n\t}\r\n\r\n\tpublic void setSoapAuthEnabled(boolean soapAuthEnabled) {\r\n\t\tthis.soapAuthEnabled = soapAuthEnabled;\r\n\t}\r\n\r\n\tpublic String getSoapAuthWsdlKey() {\r\n\t\treturn soapAuthWsdlKey;\r\n\t}\r\n\r\n\tpublic void setSoapAuthWsdlKey(String soapAuthWsdlKey) {\r\n\t\tthis.soapAuthWsdlKey = soapAuthWsdlKey;\r\n\t}\r\n\r\n\tpublic String getSoapAuthOperation() {\r\n\t\treturn soapAuthOperation;\r\n\t}\r\n\r\n\tpublic void setSoapAuthOperation(String soapAuthOperation) {\r\n\t\tthis.soapAuthOperation = soapAuthOperation;\r\n\t}\r\n\r\n\tpublic String getSoapAuthExtractAuth() {\r\n\t\treturn soapAuthExtractAuth;\r\n\t}\r\n\r\n\tpublic void setSoapAuthExtractAuth(String soapAuthExtractAuth) {\r\n\t\tthis.soapAuthExtractAuth = soapAuthExtractAuth;\r\n\t}\r\n\r\n\tpublic Integer getNumConcurrentExecutions() {\r\n\t\treturn numConcurrentExecutions;\r\n\t}\r\n\r\n\tpublic void setNumConcurrentExecutions(Integer numConcurrentExecutions) {\r\n\t\tthis.numConcurrentExecutions = numConcurrentExecutions;\r\n\t}\r\n\r\n\tpublic String[] getAuthExtractAuthParams() {\r\n\t\tif(authExtractAuth!=null) {\r\n\t\t\treturn authExtractAuth.split(\",\");\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic String[] getServerApiAuthExtractAuthParams() {\r\n\t\tif(serverLogsApiAuthExtractAuth!=null) {\r\n\t\t\treturn serverLogsApiAuthExtractAuth.split(\",\");\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic String[] getAuthParamDetails() {\r\n\t\tif(authParamsDetails!=null) {\r\n\t\t\treturn authParamsDetails.split(\",\");\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic String[] getSoapAuthExtractAuthParams() {\r\n\t\tif(soapAuthExtractAuth!=null) {\r\n\t\t\treturn soapAuthExtractAuth.split(\",\");\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic Boolean isEnabled() {\r\n\t\treturn enabled;\r\n\t}\r\n\r\n\tpublic void setEnabled(Boolean enabled) {\r\n\t\tthis.enabled = enabled;\r\n\t}\r\n\r\n\tpublic boolean isAuthEnabled() {\r\n\t\treturn authEnabled && getAuthExtractAuthParams()!=null;\r\n\t}\r\n\t\r\n\tpublic boolean isSoapAuthEnabled() {\r\n\t\treturn soapAuthEnabled && getSoapAuthExtractAuthParams()!=null;\r\n\t}\r\n\t\r\n\tpublic boolean isSoapAuthTestCase(TestCase tcase) {\r\n\t\treturn getSoapAuthWsdlKey()!=null && getSoapAuthOperation()!=null &&\r\n\t\t\t\t(getSoapAuthWsdlKey() + \r\n\t\t\t\t\t\tgetSoapAuthOperation()).equals(tcase.getWsdlKey()+tcase.getOperationName());\r\n\t}\r\n\r\n\tpublic boolean isHttpCompressionEnabled() {\r\n\t\treturn httpCompressionEnabled;\r\n\t}\r\n\r\n\tpublic void setHttpCompressionEnabled(boolean httpCompressionEnabled) {\r\n\t\tthis.httpCompressionEnabled = httpCompressionEnabled;\r\n\t}\r\n\r\n\tpublic Integer getHttpConnectionTimeout() {\r\n\t\treturn httpConnectionTimeout;\r\n\t}\r\n\r\n\tpublic void setHttpConnectionTimeout(Integer httpConnectionTimeout) {\r\n\t\tthis.httpConnectionTimeout = httpConnectionTimeout;\r\n\t}\r\n\r\n\tpublic Integer getHttpRequestTimeout() {\r\n\t\treturn httpRequestTimeout;\r\n\t}\r\n\r\n\tpublic void setHttpRequestTimeout(Integer httpRequestTimeout) {\r\n\t\tthis.httpRequestTimeout = httpRequestTimeout;\r\n\t}\r\n\t\r\n\tpublic Integer getConcurrentUserSimulationNum() {\r\n\t\treturn concurrentUserSimulationNum;\r\n\t}\r\n\r\n\tpublic void setConcurrentUserSimulationNum(Integer concurrentUserSimulationNum) {\r\n\t\tthis.concurrentUserSimulationNum = concurrentUserSimulationNum;\r\n\t}\r\n\t\r\n\tpublic GatfTestDataConfig getGatfTestDataConfig() {\r\n\t\treturn gatfTestDataConfig;\r\n\t}\r\n\r\n\tpublic void setGatfTestDataConfig(GatfTestDataConfig gatfTestDataConfig) {\r\n\t\tthis.gatfTestDataConfig = gatfTestDataConfig;\r\n\t}\r\n\r\n\tpublic String getTestDataConfigFile() {\r\n\t\treturn testDataConfigFile;\r\n\t}\r\n\r\n\tpublic void setTestDataConfigFile(String testDataConfigFile) {\r\n\t\tthis.testDataConfigFile = testDataConfigFile;\r\n\t}\r\n\r\n\tpublic String getAuthDataProvider() {\r\n\t\treturn authDataProvider;\r\n\t}\r\n\r\n\tpublic void setAuthDataProvider(String authDataProvider) {\r\n\t\tthis.authDataProvider = authDataProvider;\r\n\t}\r\n\r\n\tpublic Integer getCompareBaseUrlsNum() {\r\n\t\treturn compareBaseUrlsNum;\r\n\t}\r\n\r\n\tpublic void setCompareBaseUrlsNum(Integer compareBaseUrlsNum) {\r\n\t\tthis.compareBaseUrlsNum = compareBaseUrlsNum;\r\n\t}\r\n\r\n\tpublic boolean isCompareEnabled() {\r\n\t\treturn compareEnabled;\r\n\t}\r\n\r\n\tpublic void setCompareEnabled(boolean compareEnabled) {\r\n\t\tthis.compareEnabled = compareEnabled;\r\n\t}\r\n\r\n\tpublic String getAuthParamsDetails() {\r\n\t\treturn authParamsDetails;\r\n\t}\r\n\r\n\tpublic void setAuthParamsDetails(String authParamsDetails) {\r\n\t\tthis.authParamsDetails = authParamsDetails;\r\n\t}\r\n\r\n\tpublic String[] getTestCaseHooksPaths() {\r\n\t\treturn testCaseHooksPaths;\r\n\t}\r\n\r\n\tpublic void setTestCaseHooksPaths(String[] testCaseHooksPaths) {\r\n\t\tthis.testCaseHooksPaths = testCaseHooksPaths;\r\n\t}\r\n\r\n\tpublic boolean isLoadTestingEnabled() {\r\n\t\treturn loadTestingEnabled;\r\n\t}\r\n\r\n\tpublic void setLoadTestingEnabled(boolean loadTestingEnabled) {\r\n\t\tthis.loadTestingEnabled = loadTestingEnabled;\r\n\t}\r\n\r\n\tpublic boolean isFetchFailureLogs() {\r\n\t\treturn isFetchFailureLogs;\r\n\t}\r\n\r\n\tpublic void setFetchFailureLogs(boolean isFetchFailureLogs) {\r\n\t\tthis.isFetchFailureLogs = isFetchFailureLogs;\r\n\t}\r\n\r\n\tpublic Long getLoadTestingTime() {\r\n\t\treturn loadTestingTime;\r\n\t}\r\n\r\n\tpublic void setLoadTestingTime(Long loadTestingTime) {\r\n\t\tthis.loadTestingTime = loadTestingTime;\r\n\t}\r\n\r\n\tpublic boolean isDistributedLoadTests() {\r\n\t\treturn distributedLoadTests;\r\n\t}\r\n\r\n\tpublic void setDistributedLoadTests(boolean distributedLoadTests) {\r\n\t\tthis.distributedLoadTests = distributedLoadTests;\r\n\t}\r\n\r\n\tpublic String[] getDistributedNodes() {\r\n\t\treturn distributedNodes;\r\n\t}\r\n\r\n\tpublic void setDistributedNodes(String[] distributedNodes) {\r\n\t\tthis.distributedNodes = distributedNodes;\r\n\t}\r\n\r\n\tpublic Long getConcurrentUserRampUpTime() {\r\n\t\treturn concurrentUserRampUpTime;\r\n\t}\r\n\r\n\tpublic void setConcurrentUserRampUpTime(Long concurrentUserRampUpTime) {\r\n\t\tthis.concurrentUserRampUpTime = concurrentUserRampUpTime;\r\n\t}\r\n\r\n\tpublic Integer getLoadTestingReportSamples() {\r\n\t\treturn loadTestingReportSamples;\r\n\t}\r\n\r\n\tpublic void setLoadTestingReportSamples(Integer loadTestingReportSamples) {\r\n\t\tthis.loadTestingReportSamples = loadTestingReportSamples;\r\n\t}\r\n\r\n\tpublic boolean isDebugEnabled() {\r\n\t\treturn debugEnabled;\r\n\t}\r\n\r\n\tpublic void setDebugEnabled(boolean debugEnabled) {\r\n\t\tthis.debugEnabled = debugEnabled;\r\n\t}\r\n\r\n\tpublic String[] getIgnoreFiles() {\r\n\t\treturn ignoreFiles;\r\n\t}\r\n\r\n\tpublic void setIgnoreFiles(String[] ignoreFiles) {\r\n\t\tthis.ignoreFiles = ignoreFiles;\r\n\t}\r\n\r\n\tpublic String[] getOrderedFiles() {\r\n\t\treturn orderedFiles;\r\n\t}\r\n\r\n\tpublic void setOrderedFiles(String[] orderedFiles) {\r\n\t\tthis.orderedFiles = orderedFiles;\r\n\t}\r\n\r\n\tpublic boolean isOrderByFileName() {\r\n\t\treturn isOrderByFileName;\r\n\t}\r\n\r\n\tpublic void setOrderByFileName(boolean isOrderByFileName) {\r\n\t\tthis.isOrderByFileName = isOrderByFileName;\r\n\t}\r\n\r\n\tpublic boolean isServerLogsApiAuthEnabled() {\r\n\t\treturn isServerLogsApiAuthEnabled;\r\n\t}\r\n\r\n\tpublic void setServerLogsApiAuthEnabled(boolean isServerLogsApiAuthEnabled) {\r\n\t\tthis.isServerLogsApiAuthEnabled = isServerLogsApiAuthEnabled;\r\n\t}\r\n\r\n\tpublic String getServerLogsApiAuthExtractAuth() {\r\n\t\treturn serverLogsApiAuthExtractAuth;\r\n\t}\r\n\r\n\tpublic void setServerLogsApiAuthExtractAuth(String serverLogsApiAuthExtractAuth) {\r\n\t\tthis.serverLogsApiAuthExtractAuth = serverLogsApiAuthExtractAuth;\r\n\t}\r\n\r\n\tpublic Integer getRepeatSuiteExecutionNum() {\r\n\t\treturn repeatSuiteExecutionNum;\r\n\t}\r\n\r\n\tpublic void setRepeatSuiteExecutionNum(Integer repeatSuiteExecutionNum) {\r\n\t\tthis.repeatSuiteExecutionNum = repeatSuiteExecutionNum;\r\n\t}\r\n\r\n\tpublic boolean isGenerateExecutionLogs() {\r\n\t\treturn isGenerateExecutionLogs;\r\n\t}\r\n\r\n\tpublic void setGenerateExecutionLogs(boolean isGenerateExecutionLogs) {\r\n\t\tthis.isGenerateExecutionLogs = isGenerateExecutionLogs;\r\n\t}\r\n\r\n\tpublic boolean isSeleniumExecutor() {\r\n\t\treturn isSeleniumExecutor;\r\n\t}\r\n\r\n\tpublic void setSeleniumExecutor(boolean isSeleniumExecutor) {\r\n\t\tthis.isSeleniumExecutor = isSeleniumExecutor;\r\n\t}\r\n\r\n\tpublic boolean isSeleniumModuleTests() {\r\n\t\treturn isSeleniumModuleTests;\r\n\t}\r\n\r\n\tpublic void setSeleniumModuleTests(boolean isSeleniumModuleTests) {\r\n\t\tthis.isSeleniumModuleTests = isSeleniumModuleTests;\r\n\t}\r\n\r\n\tpublic String[] getSeleniumScripts() {\r\n\t\treturn seleniumScripts;\r\n\t}\r\n\r\n\tpublic void setSeleniumScripts(String[] seleniumScripts) {\r\n\t\tthis.seleniumScripts = seleniumScripts;\r\n\t}\r\n\r\n\tpublic SeleniumDriverConfig[] getSeleniumDriverConfigs() {\r\n\t\treturn seleniumDriverConfigs;\r\n\t}\r\n\r\n\tpublic void setSeleniumDriverConfigs(SeleniumDriverConfig[] seleniumDriverConfigs) {\r\n\t\tthis.seleniumDriverConfigs = seleniumDriverConfigs;\r\n\t}\r\n\t\r\n\tpublic Map<String, SeleniumDriverConfig> getSelDriverConfigMap() {\r\n\t Map<String, SeleniumDriverConfig> mp = new HashMap<String, SeleniumDriverConfig>();\r\n\t for (SeleniumDriverConfig sc : seleniumDriverConfigs)\r\n {\r\n if(!mp.containsKey(sc.getDriverName()) && sc.getName().matches(\"chrome|firefox|ie|opera|edge|safari|appium-android|appium-ios|selendroid|ios-driver\"))\r\n {\r\n mp.put(sc.getName(), sc);\r\n }\r\n }\r\n\t return mp;\r\n\t}\r\n\t\r\n\tpublic String getSeleniumLoggerPreferences()\r\n {\r\n return seleniumLoggerPreferences;\r\n }\r\n\r\n public void setSeleniumLoggerPreferences(String seleniumLoggerPreferences)\r\n {\r\n this.seleniumLoggerPreferences = seleniumLoggerPreferences;\r\n }\r\n\r\n public boolean isValidSeleniumRequest() {\r\n\t\treturn isSeleniumExecutor && /*seleniumScripts!=null && seleniumScripts.length>0 && */\r\n\t\t seleniumDriverConfigs!=null && seleniumDriverConfigs.length>0 &&\r\n\t\t StringUtils.isNotEmpty(seleniumDriverConfigs[0].getName()) && StringUtils.isNotEmpty(seleniumDriverConfigs[0].getPath());\r\n\t}\r\n\r\n\tpublic String getJavaHome()\r\n {\r\n return javaHome;\r\n }\r\n\r\n public void setJavaHome(String javaHome)\r\n {\r\n this.javaHome = javaHome;\r\n }\r\n\r\n public String getJavaVersion() {\r\n return javaVersion;\r\n }\r\n\r\n public void setJavaVersion(String javaVersion) {\r\n this.javaVersion = javaVersion;\r\n }\r\n\r\n public String getGatfJarPath() {\r\n return gatfJarPath;\r\n }\r\n\r\n public void setGatfJarPath(String gatfJarPath) {\r\n this.gatfJarPath = gatfJarPath;\r\n }\r\n\r\n public boolean isSelDebugger() {\r\n\t\treturn selDebugger;\r\n\t}\r\n\r\n\tpublic void setSelDebugger(boolean selDebugger) {\r\n\t\tthis.selDebugger = selDebugger;\r\n\t}\r\n\r\n\tpublic String getWrkPath() {\r\n\t\treturn wrkPath;\r\n\t}\r\n\r\n\tpublic void setWrkPath(String wrkPath) {\r\n\t\tthis.wrkPath = wrkPath;\r\n\t}\r\n\r\n\tpublic String getWrk2Path() {\r\n\t\treturn wrk2Path;\r\n\t}\r\n\r\n\tpublic void setWrk2Path(String wrk2Path) {\r\n\t\tthis.wrk2Path = wrk2Path;\r\n\t}\r\n\r\n\tpublic String getVegetaPath() {\r\n\t\treturn vegetaPath;\r\n\t}\r\n\r\n\tpublic void setVegetaPath(String vegetaPath) {\r\n\t\tthis.vegetaPath = vegetaPath;\r\n\t}\r\n\r\n\tpublic String getAutocannonPath() {\r\n\t\treturn autocannonPath;\r\n\t}\r\n\r\n\tpublic void setAutocannonPath(String autocannonPath) {\r\n\t\tthis.autocannonPath = autocannonPath;\r\n\t}\r\n\r\n\tpublic void validate()\r\n\t{\r\n\t\tAssert.assertTrue(\"Testcase directory name is blank...\", \r\n\t\t\t\tgetTestCaseDir()!=null && !getTestCaseDir().trim().isEmpty());\r\n\t\t\r\n\t\tif(isAuthEnabled()) {\r\n\t\t\tAssert.assertTrue(\"Invalid auth extract params\", getAuthExtractAuthParams().length==4);\r\n\t\t\tAssert.assertTrue(\"Invalid auth extract token name\", !getAuthExtractAuthParams()[0].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth extract mode specified, should be one of (xml,json,header,plain,cookie)\", \r\n\t\t\t\t\tgetAuthExtractAuthParams()[1].equalsIgnoreCase(\"json\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[1].equalsIgnoreCase(\"xml\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[1].equalsIgnoreCase(\"header\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[1].equalsIgnoreCase(\"plain\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[1].equalsIgnoreCase(\"cookie\"));\r\n\t\t\tAssert.assertTrue(\"Invalid auth name specified\", !getAuthExtractAuthParams()[2].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth mode specified, should be one of (queryparam,header,cookie)\", \r\n\t\t\t\t\tgetAuthExtractAuthParams()[3].equalsIgnoreCase(\"queryparam\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[3].equalsIgnoreCase(\"cookie\") ||\r\n\t\t\t\t\tgetAuthExtractAuthParams()[3].equalsIgnoreCase(\"header\"));\r\n\t\t\tAssert.assertTrue(\"Invalid auth url\", getAuthUrl()!=null && !getAuthUrl().isEmpty());\r\n\t\t\t\r\n\t\t\tAssert.assertNotNull(\"Invalid auth param details\",getAuthParamsDetails());\r\n\t\t\tAssert.assertTrue(\"Invalid auth param details\", getAuthParamDetails().length==4);\r\n\t\t\tAssert.assertTrue(\"Invalid auth user param name\", !getAuthParamDetails()[0].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth user param name mode specified, should be one of (header,postparam,queryparam)\", \r\n\t\t\t\t\tgetAuthParamDetails()[1].equalsIgnoreCase(\"header\") ||\r\n\t\t\t\t\tgetAuthParamDetails()[1].equalsIgnoreCase(\"postparam\") ||\r\n\t\t\t\t\tgetAuthParamDetails()[1].equalsIgnoreCase(\"queryparam\"));\r\n\t\t\tAssert.assertTrue(\"Invalid auth password param name\", !getAuthParamDetails()[2].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth password param name mode specified, should be one of (header,queryparam,header)\", \r\n\t\t\t\t\tgetAuthParamDetails()[3].equalsIgnoreCase(\"queryparam\") ||\r\n\t\t\t\t\tgetAuthParamDetails()[3].equalsIgnoreCase(\"postparam\") ||\r\n\t\t\t\t\tgetAuthParamDetails()[3].equalsIgnoreCase(\"header\"));\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tif(isSoapAuthEnabled()) {\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap wsdl key\", getSoapAuthWsdlKey()!=null && !getSoapAuthWsdlKey().isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap wsdl operation\", getSoapAuthOperation()!=null && !getSoapAuthOperation().isEmpty());\r\n\t\t\t\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap extract params\", getSoapAuthExtractAuthParams().length==3);\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap extract token name\", !getSoapAuthExtractAuthParams()[0].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap name specified\", !getSoapAuthExtractAuthParams()[1].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap name\", !getSoapAuthExtractAuthParams()[2].isEmpty());\r\n\t\t\tAssert.assertTrue(\"Invalid auth soap name\", getSoapAuthExtractAuthParams()[2].equalsIgnoreCase(\"queryparam\"));\r\n\t\t}\r\n\t}\r\n}\r",
"public class WorkflowContextHandler {\r\n\t\r\n\tpublic static final ObjectMapper OM = new ObjectMapper();\r\n\r\n\tprivate final VelocityEngine engine = new VelocityEngine();\r\n\t\r\n\tpublic enum ResponseType {\r\n\t\tJSON,\r\n\t\tXML,\r\n\t\tSOAP,\r\n\t\tPLAIN,\r\n\t\tNONE\r\n\t}\r\n\t\r\n\tpublic VelocityEngine getEngine() {\r\n\t\treturn engine;\r\n\t}\r\n\r\n\tpublic void init() {\r\n\t\ttry {\r\n\t\t\tengine.init();\r\n\t\t} catch (Exception e) {\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate final Map<String, String> globalworkflowContext = new ConcurrentHashMap<String, String>();\r\n\t\r\n\tprivate final Map<Integer, Map<String, String>> suiteWorkflowContext = new ConcurrentHashMap<Integer, Map<String, String>>();\r\n\t\r\n\tprivate final Map<Integer, Map<String, List<Map<String, String>>>> suiteWorkflowScenarioContext = \r\n\t\t\tnew ConcurrentHashMap<Integer, Map<String, List<Map<String, String>>>>();\r\n\t\r\n\tprivate final Map<Integer, Map<String, String>> cookies = new ConcurrentHashMap<Integer, Map<String, String>>();\r\n\t\r\n\tpublic void initializeSuiteContext(int numberOfRuns) {\r\n\t\tsuiteWorkflowContext.clear();\r\n\t\tsuiteWorkflowScenarioContext.clear();\r\n\t\tcookies.clear();\r\n\t\t\r\n\t\tfor (int i = -2; i < numberOfRuns+1; i++) {\r\n\t\t\tsuiteWorkflowContext.put(i, new ConcurrentHashMap<String, String>());\r\n\t\t\tsuiteWorkflowScenarioContext.put(i, new ConcurrentHashMap<String, List<Map<String, String>>>());\r\n\t\t\tcookies.put(i, new ConcurrentHashMap<String, String>());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void initializeSuiteContextWithnum(int index) {\r\n\t\tsuiteWorkflowContext.put(index, new ConcurrentHashMap<String, String>());\r\n\t\tsuiteWorkflowScenarioContext.put(index, new ConcurrentHashMap<String, List<Map<String, String>>>());\r\n\t\tcookies.put(index, new ConcurrentHashMap<String, String>());\r\n\t}\r\n\t\r\n\tvoid addGlobalVariables(Map<String, String> variableMap) {\r\n\t\tif(variableMap!=null) {\r\n\t\t\tfor (String property : variableMap.keySet()) {\r\n\t\t\t\tString value = variableMap.get(property);\r\n\t\t\t\tif(value.equals(\"env.var\")) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tvalue = System.getenv(property);\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if(value.equals(\"property.var\")) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tvalue = System.getProperty(property);\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if(value.startsWith(\"env.\")) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tvalue = System.getenv(value.substring(4));\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if(value.startsWith(\"property.\")) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tvalue = System.getProperty(value.substring(9));\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif(value==null) {\r\n\t\t\t\t\tvalue = variableMap.get(property);\r\n\t\t\t\t}\r\n\t\t\t\tglobalworkflowContext.put(property, value);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Map<String, String> getSuiteWorkflowContext(TestCase testCase) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn suiteWorkflowContext.get(-1);\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\treturn suiteWorkflowContext.get(-2);\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\treturn suiteWorkflowContext.get(0);\r\n\t\t} else {\r\n\t\t\treturn suiteWorkflowContext.get(testCase.getSimulationNumber());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Map<String, List<Map<String, String>>> getSuiteWorkflowScnearioContext(TestCase testCase) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(-1);\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(-2);\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(0);\r\n\t\t} else {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(testCase.getSimulationNumber());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic List<Map<String, String>> getSuiteWorkflowScenarioContextValues(TestCase testCase, String varName) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(-1).get(varName);\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(-2).get(varName);\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(0).get(varName);\r\n\t\t} else {\r\n\t\t\treturn suiteWorkflowScenarioContext.get(testCase.getSimulationNumber()).get(varName);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic String getCookie(TestCase testCase, String varName) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn cookies.get(-1).get(varName);\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\treturn cookies.get(-2).get(varName);\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\treturn cookies.get(0).get(varName);\r\n\t\t} else {\r\n\t\t\treturn cookies.get(testCase.getSimulationNumber()).get(varName);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Map<String, String> getCookies(TestCase testCase) {\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\treturn cookies.get(-1);\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\treturn cookies.get(-2);\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\treturn cookies.get(0);\r\n\t\t} else {\r\n\t\t\treturn cookies.get(testCase.getSimulationNumber());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic List<Cookie> storeCookies(TestCase testCase, List<String> cookieLst) {\r\n\t\tint simNumber = testCase.getSimulationNumber()==null?0:testCase.getSimulationNumber();\r\n\t\tif(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t\t\tsimNumber = -1;\r\n\t\t} else if(testCase.isExternalApi()) {\r\n\t\t\tsimNumber = -2;\r\n\t\t} else if(testCase.getSimulationNumber()==null) {\r\n\t\t\tsimNumber = 0;\r\n\t\t}\r\n\t\tList<Cookie> cooklst = new ArrayList<Cookie>();\r\n\t\tif(cookieLst!=null && cookies.get(simNumber)!=null)\r\n\t\t{\r\n\t\t\tfor (String cookie : cookieLst) {\r\n\t\t\t\tCookie c = Cookie.parse(HttpUrl.parse(testCase.getBaseUrl()), cookie);\r\n\t\t\t\tcooklst.add(c);\r\n\t\t\t\tcookies.get(simNumber).put(c.name(), c.value());\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn cooklst;\r\n\t}\r\n\t\r\n\tpublic Map<String, String> getGlobalSuiteAndTestLevelParameters(TestCase testCase, Map<String, String> variableMap, int index) {\r\n\t Map<String, String> nmap = new HashMap<String, String>(globalworkflowContext);\r\n\t if(testCase!=null) {\r\n\t index = testCase.getSimulationNumber();\r\n\t if(testCase.isServerApiAuth() || testCase.isServerApiTarget()) {\r\n\t index = -1;\r\n\t } else if(testCase.isExternalApi()) {\r\n\t index = -2;\r\n\t } else if(testCase.getSimulationNumber()==null) {\r\n\t index = 0;\r\n\t }\r\n\t nmap.putAll(suiteWorkflowContext.get(index));\r\n\t if(variableMap!=null && !variableMap.isEmpty()) {\r\n\t nmap.putAll(variableMap);\r\n\t }\r\n\t if(testCase.getCarriedOverVariables()!=null && !testCase.getCarriedOverVariables().isEmpty()) {\r\n\t nmap.putAll(testCase.getCarriedOverVariables());\r\n\t }\r\n\t } else {\r\n\t nmap.putAll(suiteWorkflowContext.get(index));\r\n\t if(variableMap!=null && !variableMap.isEmpty()) {\r\n nmap.putAll(variableMap);\r\n }\r\n\t }\r\n\t\treturn nmap;\r\n\t}\r\n\t\r\n\tpublic void addSuiteLevelParameter(int index, String name, String value) {\r\n\t if(suiteWorkflowContext.containsKey(index) && value!=null) {\r\n\t suiteWorkflowContext.get(index).put(name, value);\r\n\t }\r\n\t}\r\n\t\r\n\tpublic String evaluateTemplate(TestCase testCase, String template, AcceptanceTestContext acontext) {\r\n\t\tStringWriter writer = new StringWriter();\r\n\t\ttry {\r\n\t\t\tMap<String, String> nmap = getGlobalSuiteAndTestLevelParameters(testCase, null, -3);\r\n\t\t\tif(testCase!=null && !nmap.isEmpty()) {\r\n\t\t\t\tif(template!=null) {\r\n\t\t\t\t\tVelocityContext context = new VelocityContext(new HashMap<String, Object>(nmap));\r\n\t\t\t\t\tDataProviderAccessor dpa = new DataProviderAccessor(acontext, testCase);\r\n\t\t\t\t\tcontext.put(\"_DPA_\", dpa);\r\n\t\t\t\t\tengine.evaluate(context, writer, \"ERROR\", template);\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}\r\n\t\treturn writer.toString();\r\n\t}\r\n\t\r\n\tpublic String templatize(Map<String, Object> variableMap, String template) throws Exception {\r\n\t VelocityContext context = new VelocityContext(variableMap);\r\n\t StringWriter writer = new StringWriter();\r\n engine.evaluate(context, writer, \"ERROR\", template);\r\n return writer.toString();\r\n\t}\r\n \r\n public String templatize(String template) throws Exception {\r\n VelocityContext context = new VelocityContext(Collections.<String, Object>unmodifiableMap(globalworkflowContext));\r\n StringWriter writer = new StringWriter();\r\n engine.evaluate(context, writer, \"ERROR\", template);\r\n return writer.toString();\r\n }\r\n\t\r\n\tpublic void handleContextVariables(TestCase testCase, Map<String, String> variableMap, AcceptanceTestContext acontext) \r\n\t\t\tthrows Exception {\r\n\t\t\r\n\t\tMap<String, String> nmap = getGlobalSuiteAndTestLevelParameters(testCase, variableMap, -3);\r\n\t\t\r\n\t\tVelocityContext context = new VelocityContext(new HashMap<String, Object>(nmap));\r\n\t\tDataProviderAccessor dpa = new DataProviderAccessor(acontext, testCase);\r\n\t\tcontext.put(\"_DPA_\", dpa);\r\n\t\t\r\n\t\t//initialize cookies and headers\r\n\t\tif(testCase != null) {\r\n\t\t\tMap<String, String> cookieMap = getCookies(testCase);\r\n\t\t\tif(cookieMap!=null) {\r\n\t\t\t\tfor (Map.Entry<String, String> entry : cookieMap.entrySet()) {\r\n\t\t\t\t\tif(testCase.getHeaders()==null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttestCase.setHeaders(new HashMap<String, String>());\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttestCase.getHeaders().put(\"Cookie\", entry.getKey() + \"=\" + entry.getValue());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(MapUtils.isNotEmpty(testCase.getHeaders())) {\r\n\t\t\t for (Map.Entry<String, String> entry : testCase.getHeaders().entrySet()) {\r\n\t\t\t StringWriter writer = new StringWriter();\r\n\t\t\t engine.evaluate(context, writer, \"ERROR\", entry.getValue());\r\n\t\t\t testCase.getHeaders().put(entry.getKey(), writer.toString());\r\n\t\t\t }\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif(testCase!=null && !nmap.isEmpty()) {\r\n\t\t\tif(testCase.getUrl()!=null) {\r\n\t\t\t\tStringWriter writer = new StringWriter();\r\n\t\t\t\tengine.evaluate(context, writer, \"ERROR\", testCase.getUrl());\r\n\t\t\t\ttestCase.setAurl(writer.toString());\r\n\t\t\t}\r\n\t\t\tif(testCase.getContent()!=null) {\r\n\t\t\t\tStringWriter writer = new StringWriter();\r\n\t\t\t\tengine.evaluate(context, writer, \"ERROR\", testCase.getContent());\r\n\t\t\t\ttestCase.setAcontent(writer.toString());\r\n\t\t\t}\r\n\t\t\tif(testCase.getExQueryPart()!=null) {\r\n\t\t\t\tStringWriter writer = new StringWriter();\r\n\t\t\t\tengine.evaluate(context, writer, \"ERROR\", testCase.getExQueryPart());\r\n\t\t\t\ttestCase.setAexQueryPart(writer.toString());\r\n\t\t\t}\r\n\t\t\tif(testCase.getExpectedNodes()!=null && !testCase.getExpectedNodes().isEmpty()) {\r\n\t\t\t\tList<String> expectedNodes = new ArrayList<String>();\r\n\t\t\t\tfor (String nodecase : testCase.getExpectedNodes()) {\r\n\t\t\t\t\tStringWriter writer = new StringWriter();\r\n\t\t\t\t\tengine.evaluate(context, writer, \"ERROR\", nodecase);\r\n\t\t\t\t\texpectedNodes.add(writer.toString());\r\n\t\t\t\t}\r\n\t\t\t\ttestCase.setAexpectedNodes(expectedNodes);\r\n\t\t\t}\r\n\t\t} else if(testCase!=null) {\r\n\t\t\ttestCase.setAurl(testCase.getUrl());\r\n\t\t\ttestCase.setAcontent(testCase.getContent());\r\n\t\t\ttestCase.setAexQueryPart(testCase.getExQueryPart());\r\n\t\t\ttestCase.setAexpectedNodes(testCase.getExpectedNodes());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic boolean velocityValidate(TestCase testCase, String template, Map<String, String> smap, \r\n\t\t\tAcceptanceTestContext acontext) {\r\n\t\tif(testCase!=null && template!=null) {\r\n\t\t\tMap<String, String> nmap = getGlobalSuiteAndTestLevelParameters(testCase, null, -3);\r\n\t\t\tif(smap!=null) {\r\n\t\t\t\tnmap.putAll(smap);\r\n\t\t\t}\r\n\t\t\tStringWriter writer = new StringWriter();\r\n\t\t\tString condition = \"#if(\" + template + \")true#end\";\r\n\t\t\ttry {\r\n\t\t\t\tVelocityContext context = new VelocityContext(new HashMap<String, Object>(nmap));\r\n\t\t\t\tDataProviderAccessor dpa = new DataProviderAccessor(acontext, testCase);\r\n\t\t\t\tcontext.put(\"_DPA_\", dpa);\r\n\t\t\t\tengine.evaluate(context, writer, \"ERROR\", condition);\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t\treturn \"true\".equals(writer.toString());\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tpublic static List<Map<String, String>> getNodeCountMapList(String xmlValue, String nodeName)\r\n\t{\r\n\t\tint responseCount = -1;\r\n\t\ttry {\r\n\t\t\tresponseCount = Integer.valueOf(xmlValue);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new AssertionError(\"Invalid responseMappedCount variable defined, \" +\r\n\t\t\t\t\t\"derived value should be number - \"+nodeName);\r\n\t\t}\r\n\t\t\r\n\t\tList<Map<String, String>> xmlValues = new ArrayList<Map<String,String>>();\r\n\t\tfor (int i = 0; i < responseCount; i++) {\r\n\t\t\tMap<String, String> row = new HashMap<String, String>();\r\n\t\t\trow.put(\"index\", (i+1)+\"\");\r\n\t\t\txmlValues.add(row);\r\n\t\t}\r\n\t\t\r\n\t\treturn xmlValues;\r\n\t}\r\n\t\r\n\tpublic static List<Map<String, String>> getNodeValueMapList(String propNames, NodeList xmlNodeList)\r\n\t{\r\n\t\tList<Map<String, String>> nodeValues = new ArrayList<Map<String,String>>();\r\n\t\tif(propNames.endsWith(\"*\")) \r\n\t\t{\r\n\t\t\tfor (int i = 0; i < xmlNodeList.getLength(); i++) {\r\n\t\t\t\tMap<String, String> row = new HashMap<String, String>();\r\n\t\t\t\t\r\n\t\t\t\tNode node = xmlNodeList.item(i);\r\n\t\t\t\tif(node.getAttributes()!=null && node.getAttributes().getLength()>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (int j = 0; j < node.getAttributes().getLength(); j++) {\r\n\t\t\t\t\t\tAttr attr = (Attr) node.getAttributes().item(j);\r\n\t\t\t\t\t\trow.put(attr.getName(), attr.getValue());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(node.getChildNodes()!=null && node.getChildNodes().getLength()>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (int j = 0; j < node.getChildNodes().getLength(); j++) {\r\n\t\t\t\t\t\tString xmlValue = XMLResponseValidator.getXMLNodeValue(node.getChildNodes().item(j));\r\n\t\t\t\t\t\tif(xmlValue!=null)\r\n\t\t\t\t\t\t\trow.put(node.getChildNodes().item(j).getNodeName(), xmlValue);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tString xmlValue = XMLResponseValidator.getXMLNodeValue(node);\r\n\t\t\t\tif(xmlValue!=null)\r\n\t\t\t\t\trow.put(\"this\", xmlValue);\r\n\t\t\t\t\r\n\t\t\t\tif(row.size()>0)\r\n\t\t\t\t\tnodeValues.add(row);\r\n\t\t\t}\r\n\t\t} \r\n\t\telse\r\n\t\t{\r\n\t\t\tString[] props = propNames.split(\",\");\r\n\t\t\t\r\n\t\t\tfor (int i = 0; i < xmlNodeList.getLength(); i++) {\r\n\t\t\t\tMap<String, String> row = new HashMap<String, String>();\r\n\t\t\t\t\r\n\t\t\t\tNode node = xmlNodeList.item(i);\r\n\t\t\t\t\r\n\t\t\t\tboolean found = false;\r\n\t\t\t\t\r\n\t\t\t\tif(node.getAttributes()!=null && node.getAttributes().getLength()>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (int j = 0; j < node.getAttributes().getLength(); j++) {\r\n\t\t\t\t\t\tAttr attr = (Attr) node.getAttributes().item(j);\r\n\t\t\t\t\t\tfor (String propName : props) {\r\n\t\t\t\t\t\t\tif(attr.getName().equals(propName)) {\r\n\t\t\t\t\t\t\t\tfound = true;\r\n\t\t\t\t\t\t\t\trow.put(propName, attr.getValue());\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(!found && node.getChildNodes()!=null && node.getChildNodes().getLength()>0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (int j = 0; j < node.getChildNodes().getLength(); j++) {\r\n\t\t\t\t\t\tfor (String propName : props) {\r\n\t\t\t\t\t\t\tif(node.getChildNodes().item(j).getNodeName().equals(propName)) {\r\n\t\t\t\t\t\t\t\tfound = true;\r\n\t\t\t\t\t\t\t\tString xmlValue = XMLResponseValidator.getXMLNodeValue(node.getChildNodes().item(j));\r\n\t\t\t\t\t\t\t\trow.put(propName, xmlValue);\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif(row.size()>0)\r\n\t\t\t\t\tnodeValues.add(row);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn nodeValues;\r\n\t}\r\n\t\r\n\tpublic static void copyResourcesToDirectory(String resPath, String directory) {\r\n\t\tif(new File(directory).exists()) {\r\n\t\t\ttry {\r\n\t\t\t\t/*if(persistHtmlFiles) {\r\n\t\t\t\t\tFile tmpfolder = new File(FileUtils.getTempDirectory(), \"out\");\r\n\t\t\t\t\tif(tmpfolder.exists()) {\r\n\t\t\t\t\t\tFileUtils.deleteDirectory(tmpfolder);\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttmpfolder.mkdir();\r\n\t\t\t\t\tFile[] existingFiles = new File(directory).listFiles(new FilenameFilter() {\r\n\t\t\t\t\t\tpublic boolean accept(File folder, String name) {\r\n\t\t\t\t\t\t\treturn name.endsWith(\".html\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t\tfor (File file : existingFiles) {\r\n\t\t\t\t\t\tFileUtils.moveFile(file, new File(tmpfolder, file.getName()));\r\n\t\t\t\t\t}\r\n\t\t\t\t}*/\r\n\t\t\t\tFileUtils.deleteDirectory(new File(directory));\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t}\r\n\t\t}\r\n\t\tOptional<JarFile> jarFile = ResourceCopy.jar(WorkflowContextHandler.class);\r\n\t\tif(jarFile.isPresent()) {\r\n\t\t\ttry {\r\n\t\t\t\tResourceCopy.copyResourceDirectory(jarFile.get(), resPath, new File(directory));\r\n\t\t\t} catch (IOException e1) {\r\n\t\t\t\te1.printStackTrace();\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tURL resourcesUrl = WorkflowContextHandler.class.getResource(\"/\" + resPath);\r\n\t if (resourcesUrl != null)\r\n\t {\r\n\t \ttry {\r\n\t \t\tFileUtils.copyDirectory(new File(resourcesUrl.getPath()), new File(directory));\r\n\t \t} catch (Exception e) {\r\n\t \t\tthrow new RuntimeException(e);\r\n\t \t}\r\n\t }\r\n\t\t}\r\n\t\t\r\n\t\t/*if(persistHtmlFiles) {\r\n\t\t\tFile tmpfolder = new File(FileUtils.getTempDirectory(), \"out\");\r\n\t\t\tFile[] existingFiles = tmpfolder.listFiles(new FilenameFilter() {\r\n\t\t\t\tpublic boolean accept(File folder, String name) {\r\n\t\t\t\t\treturn name.endsWith(\".html\");\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\tfor (File file : existingFiles) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tFileUtils.moveFile(file, new File(directory));\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttry {\r\n\t\t\t\tFileUtils.deleteDirectory(tmpfolder);\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t}\r\n\t\t}*/\r\n\t}\r\n}\r",
"public class RuntimeReportUtil {\r\n \r\n\tpublic static class LoadTestEntry implements Serializable\r\n\t{\r\n\t\tprivate static final long serialVersionUID = 1L;\r\n\t\t\r\n\t\tString node;\r\n\t\tString prefix;\r\n\t\tint runNo;\r\n\t\tString url;\r\n\t\tDate time;\r\n\t\tTestSuiteStats currStats;\r\n\t\tMap<String, Map<String, List<Object[]>>> currSelStats;\r\n\t\t\r\n\t\tpublic LoadTestEntry(String node, String prefix, int runNo, String url, TestSuiteStats currStats, Date time) {\r\n\t\t\tsuper();\r\n\t\t\tthis.node = node;\r\n\t\t\tthis.prefix = prefix;\r\n\t\t\tthis.runNo = runNo;\r\n\t\t\tthis.url = url;\r\n\t\t\tthis.currStats = currStats;\r\n\t\t\tthis.time = time;\r\n\t\t}\r\n \r\n public LoadTestEntry(String node, String prefix, int runNo, String url, Map<String, Map<String, List<Object[]>>> currSelStats) {\r\n super();\r\n this.node = node;\r\n this.prefix = prefix;\r\n this.runNo = runNo;\r\n this.url = url;\r\n this.currSelStats = currSelStats;\r\n }\r\n \r\n public LoadTestEntry() {\r\n }\r\n\t\t\r\n\t\tpublic String getNode() {\r\n\t\t\treturn node;\r\n\t\t}\r\n\t\tpublic String getPrefix() {\r\n\t\t\treturn prefix;\r\n\t\t}\r\n\t\tpublic int getRunNo() {\r\n\t\t\treturn runNo;\r\n\t\t}\r\n\t\tpublic String getUrl() {\r\n\t\t\treturn url;\r\n\t\t}\r\n\t\tpublic Date getTime() {\r\n\t\t\treturn time;\r\n\t\t}\r\n\t\tpublic TestSuiteStats getCurrStats() {\r\n\t\t\treturn currStats;\r\n\t\t}\r\n public Map<String, Map<String, List<Object[]>>> getCurrSelStats() {\r\n return currSelStats;\r\n }\r\n\t}\r\n\t\r\n\tprivate static volatile boolean registered = false;\r\n\t\r\n\tprivate static TestSuiteStats gloadStats = new TestSuiteStats();\r\n\t\r\n\tprivate static ConcurrentLinkedQueue<Object> Q = new ConcurrentLinkedQueue<Object>();\r\n\t\r\n\tprivate static ConcurrentLinkedQueue<Object> Qdl = new ConcurrentLinkedQueue<Object>();\r\n\t\r\n\tpublic static void registerConfigUI()\r\n\t{\r\n\t\tregistered = true;\r\n\t}\r\n\t\r\n\tpublic static void unRegisterConfigUI()\r\n\t{\r\n\t\tregistered = false;\r\n\t\tQ.clear();\r\n\t\tQdl.clear();\r\n\t\tsynchronized (gloadStats) {\r\n\t\t\tgloadStats = new TestSuiteStats();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void addLEntry(LoadTestEntry lentry)\r\n\t{\r\n\t\tQdl.add(lentry);\r\n\t}\r\n\t\r\n\tpublic static void addEntry(int runNo, boolean subtestPassed)\r\n {\r\n\t if(registered)\r\n {\r\n\t try {\r\n Q.add(\"local|\"+runNo+\"|\"+(subtestPassed?1:0));\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n\t else\r\n\t {\r\n\t try {\r\n\t Qdl.add(runNo+\"|\"+(subtestPassed?1:0));\r\n\t } catch (Exception e) {\r\n\t e.printStackTrace();\r\n\t }\r\n\t }\r\n }\r\n\t\r\n\tpublic static void addEntry(Object entry)\r\n\t{\r\n\t\tif(registered)\r\n\t\t{\r\n\t\t if(entry instanceof LoadTestEntry) {\r\n\t\t LoadTestEntry lentry = (LoadTestEntry)entry;\r\n\t\t List<Object> parts = new ArrayList<Object>();\r\n\t if(lentry.prefix==null)\r\n\t lentry.prefix = \"Run\";\r\n\t parts.add(lentry.prefix);//\r\n\t parts.add(lentry.runNo+\"\");\r\n\t parts.add(lentry.url);\r\n\t parts.add(lentry.node);\r\n\t parts.add(lentry.time);\r\n\t parts.add(lentry.currStats.toList());\r\n\t parts.add(lentry.currSelStats);\r\n\t if(lentry.currStats!=null) {\r\n\t synchronized (gloadStats) {\r\n\t gloadStats.updateStats(lentry.currStats, false);\r\n\t try {\r\n\t Q.add(parts);\r\n\t } catch (Exception e) {\r\n\t e.printStackTrace();\r\n\t }\r\n\t }\r\n\t }\r\n\t\t } else {\r\n\t\t try {\r\n Q.add(entry);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n\t\t }\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t if(entry instanceof LoadTestEntry) {\r\n LoadTestEntry lentry = (LoadTestEntry)entry;\r\n \t\t if(lentry.currStats!=null) {\r\n synchronized (gloadStats) {\r\n \t\t\t\tgloadStats.updateStats(lentry.currStats, false);\r\n \t\t\t\tSystem.out.println(gloadStats);\r\n \t\t\t}\r\n \t\t }\r\n\t\t }\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void addEntry(String node, String prefix, int runNo, String url, TestSuiteStats currStats, Date time)\r\n\t{\r\n\t\tif(registered)\r\n\t\t{\r\n\t\t\tList<Object> parts = new ArrayList<Object>();\r\n\t\t\tif(prefix==null)\r\n\t\t\t\tprefix = \"Run\";\r\n\t\t\tparts.add(prefix);\r\n\t\t\tparts.add(runNo+\"\");\r\n\t\t\tparts.add(url);\r\n\t\t\tparts.add(node);\r\n\t\t\tparts.add(time.getTime());\r\n\t\t\tparts.add(currStats.toList());\r\n\t\t\tparts.add(null);\r\n\t\t\tsynchronized (gloadStats) {\r\n\t\t\t\tgloadStats.updateStats(currStats, false);\r\n\t\t\t\ttry {\r\n\t\t\t\t\tQ.add(parts);\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsynchronized (gloadStats) {\r\n\t\t\t\tgloadStats.updateStats(currStats, false);\r\n\t\t\t\tSystem.out.println(gloadStats);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static boolean isDone() {\r\n\t return Q.isEmpty();\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"unchecked\")\r\n public static byte[] getEntry()\r\n\t{\r\n\t try {\r\n \t List<List<Object>> st = new ArrayList<List<Object>>();\r\n \t List<String> sst = new ArrayList<String>();\r\n \t Object parts = null;\r\n \t while((parts = Q.poll())!=null) {\r\n \t if(parts instanceof String) {\r\n \t sst.add((String)parts);\r\n \t } /*else if(parts instanceof Map) {\r\n \t st.add((Map<String, Object>)parts);\r\n \t }*/ else {\r\n \t \tst.add((List<Object>)parts);\r\n \t }\r\n \t if(st.size()>=1000 || sst.size()>=1000)break;\r\n \t }\r\n \t //synchronized (gloadStats) {\r\n \t //\tgstats = \",\\\"gstats\\\":\" + WorkflowContextHandler.OM.writeValueAsString(gloadStats);\r\n \t //}\r\n \t ByteArrayOutputStream baos = new ByteArrayOutputStream();\r\n \t baos.write(\"{\\\"error\\\":\\\"Execution already in progress..\\\",\\\"lstats\\\":\".getBytes(\"UTF-8\"));\r\n \t baos.write(WorkflowContextHandler.OM.writeValueAsBytes(st));\r\n \t baos.write(\",\\\"sstats\\\":\".getBytes(\"UTF-8\"));\r\n \t baos.write(WorkflowContextHandler.OM.writeValueAsBytes(sst));\r\n\t \tbaos.write(\",\\\"gstats\\\":\".getBytes(\"UTF-8\"));\r\n \t synchronized (gloadStats) {\r\n \t baos.write(WorkflowContextHandler.OM.writeValueAsBytes(gloadStats));\r\n \t }\r\n \t baos.write(\"}\".getBytes(\"UTF-8\"));\r\n //String arr = \"{\\\"error\\\":\\\"Execution already in progress..\\\",\\\"lstats\\\":\" + \r\n // WorkflowContextHandler.OM.writeValueAsString(st) + \",\\\"sstats\\\":\" + \r\n // WorkflowContextHandler.OM.writeValueAsString(sst) + gstats + \"}\";\r\n return baos.toByteArray();\r\n\t } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n\t return new byte[] {};\r\n\t}\r\n\t\r\n\tpublic static Object getDLEntry()\r\n\t{\r\n\t\treturn Qdl.poll();\r\n\t}\r\n}\r",
"@SuppressWarnings(\"serial\")\r\npublic static class GatfSelCodeParseError extends RuntimeException {\r\n public GatfSelCodeParseError(String message) {\r\n super(message);\r\n }\r\n public GatfSelCodeParseError(String message, Throwable e) {\r\n super(message, e);\r\n }\r\n}\r",
"public static class SeleniumResult implements Serializable {\n private static final long serialVersionUID = 1L;\n\n String browserName;\n\n SeleniumTestResult result;\n\n Map<String, SeleniumTestResult> __cresult__ = new LinkedHashMap<String, SeleniumTestResult>();\n\n public SeleniumTestResult getResult()\n {\n return result;\n }\n\n public Map<String,SeleniumTestResult> getSubTestResults()\n {\n return __cresult__;\n }\n\n public String getBrowserName()\n {\n return browserName;\n }\n}"
] | import java.awt.AWTException;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.Security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.TargetLocator;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.gatf.executor.core.AcceptanceTestContext;
import com.gatf.executor.core.GatfExecutorConfig;
import com.gatf.executor.core.WorkflowContextHandler;
import com.gatf.executor.report.RuntimeReportUtil;
import com.gatf.selenium.Command.GatfSelCodeParseError;
import com.gatf.selenium.SeleniumTestSession.SeleniumResult;
import com.google.common.io.Resources;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileDriver;
import io.appium.java_client.MultiTouchAction;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.ios.IOSDriver;
import io.selendroid.client.SelendroidDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
| /*
Copyright 2013-2019, Sumeet Chhetri
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.gatf.selenium;
public abstract class SeleniumTest {
@SuppressWarnings("serial")
protected final static Map<String, Level> LOG_LEVEL_BY_NAME_MAP = new HashMap<String, Level>(){{
put(Level.ALL.getName().toLowerCase(), Level.ALL);
put(Level.CONFIG.getName().toLowerCase(), Level.CONFIG);
put(Level.FINE.getName().toLowerCase(), Level.FINE);
put(Level.FINER.getName().toLowerCase(), Level.FINER);
put(Level.FINEST.getName().toLowerCase(), Level.FINEST);
put(Level.INFO.getName().toLowerCase(), Level.INFO);
put(Level.OFF.getName().toLowerCase(), Level.OFF);
put(Level.SEVERE.getName().toLowerCase(), Level.SEVERE);
put(Level.WARNING.getName().toLowerCase(), Level.WARNING);
}};
@SuppressWarnings("serial")
protected final static HashSet<String> LOG_TYPES_SET = new HashSet<String>() {{
add(LogType.BROWSER);
add(LogType.CLIENT);
add(LogType.DRIVER);
add(LogType.PERFORMANCE);
add(LogType.PROFILER);
add(LogType.SERVER);
}};
private static final String TOP_LEVEL_PROV_NAME = UUID.randomUUID().toString();
private transient AcceptanceTestContext ___cxt___ = null;
List<SeleniumTestSession> sessions = new ArrayList<SeleniumTestSession>();
protected String name;
protected transient int sessionNum = -1;
protected int index;
protected void nextSession() {
if(sessions.size()>sessionNum+1) {
sessionNum++;
}
}
protected void setSession(String sns, int sn, boolean startFlag) {
if(sn>=0 && sessions.size()>sn) {
sessionNum = sn;
} else if(sns!=null) {
sn = 0;
for (SeleniumTestSession s : sessions) {
if(s.sessionName.equalsIgnoreCase(sns)) {
sessionNum = sn;
}
sn++;
}
} else if(sn==-1 && sns==null) {
sessionNum = 0;
}
if(startFlag) {
startTest();
}
}
@SuppressWarnings("serial")
protected Set<String> addTest(String sessionName, String browserName) {
final SeleniumTestSession s = new SeleniumTestSession();
s.sessionName = sessionName;
s.browserName = browserName;
sessions.add(s);
if(!s.__result__.containsKey(browserName)) {
SeleniumResult r = new SeleniumResult();
r.browserName = browserName;
s.__result__.put(browserName, r);
} else {
//throw new RuntimeException("Duplicate browser defined");
}
return new HashSet<String>(){{add(s.sessionName); add((sessions.size()-1)+"");}};
}
protected void startTest() {
if(getSession().__teststarttime__==0) {
getSession().__teststarttime__ = System.nanoTime();
}
}
public void pushResult(SeleniumTestResult result)
{
if(getSession().__subtestname__==null) {
result.executionTime = System.nanoTime() - getSession().__teststarttime__;
getSession().__result__.get(getSession().browserName).result = result;
} else {
getSession().__result__.get(getSession().browserName).__cresult__.put(getSession().__subtestname__, result);
| RuntimeReportUtil.addEntry(index, result.status);
| 3 |
jedwards1211/Jhrome | src/main/java/org/sexydock/tabs/demos/NotepadDemo.java | [
"public class DefaultFloatingTabHandler implements IFloatingTabHandler\r\n{\r\n\tprivate Window\tdragImageWindow\t= null;\r\n\tprivate Image\tdragImage\t\t= null;\r\n\t\r\n\tprivate int\t\txOffs;\r\n\tprivate int\t\tyOffs;\r\n\t\r\n\tpublic void initialize( Tab draggedTab , Point grabPoint )\r\n\t{\r\n\t\tJTabbedPane tabbedPane = SwingUtils.getJTabbedPaneAncestor( draggedTab );\r\n\t\tJhromeTabbedPaneUI tabbedPaneUI = SwingUtils.getJTabbedPaneAncestorUI( draggedTab );\r\n\t\t\r\n\t\tif( tabbedPaneUI != null )\r\n\t\t{\r\n\t\t\tdragImage = tabbedPaneUI.createDragImage( draggedTab );\r\n\t\t\tswitch( tabbedPane.getTabPlacement( ) )\r\n\t\t\t{\r\n\t\t\t\tcase JTabbedPane.TOP:\r\n\t\t\t\t\txOffs = -grabPoint.x * 3 / 4;\r\n\t\t\t\t\tyOffs = 10;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase JTabbedPane.BOTTOM:\r\n\t\t\t\t\txOffs = -grabPoint.x * 3 / 4;\r\n\t\t\t\t\tyOffs = -dragImage.getHeight( null ) - 10;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase JTabbedPane.LEFT:\r\n\t\t\t\t\txOffs = 10;\r\n\t\t\t\t\tyOffs = -grabPoint.y * 3 / 4;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase JTabbedPane.RIGHT:\r\n\t\t\t\t\txOffs = -dragImage.getWidth( null ) - 10;\r\n\t\t\t\t\tyOffs = -grabPoint.y * 3 / 4;\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t@SuppressWarnings( \"serial\" )\r\n\t@Override\r\n\tpublic void onFloatingBegin( Tab draggedTab , Point grabPoint )\r\n\t{\r\n\t\tinitialize( draggedTab , grabPoint );\r\n\t\t\r\n\t\tif( dragImage != null )\r\n\t\t{\r\n\t\t\tif( dragImageWindow == null )\r\n\t\t\t{\r\n\t\t\t\tdragImageWindow = new Window( null )\r\n\t\t\t\t{\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void paint( Graphics g )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tGraphics2D g2 = ( Graphics2D ) g;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif( dragImage != null )\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tg2.drawImage( dragImage , 0 , 0 , null );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\t\t\t\t\r\n\t\t\t\tAWTUtilities.setWindowOpaque( dragImageWindow , false );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tdragImageWindow.setSize( dragImage.getWidth( null ) , dragImage.getHeight( null ) );\r\n\t\t\tdragImageWindow.setAlwaysOnTop( true );\r\n\t\t}\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void onFloatingTabDragged( DragSourceDragEvent dsde , Tab draggedTab , double grabX )\r\n\t{\r\n\t\tif( dragImageWindow != null )\r\n\t\t{\r\n\t\t\tPoint p = new Point( dsde.getX( ) + xOffs , dsde.getY( ) + yOffs );\r\n\t\t\tdragImageWindow.setLocation( p );\r\n\t\t\tdragImageWindow.setVisible( true );\r\n\t\t}\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void onFloatingEnd( )\r\n\t{\r\n\t\tif( dragImageWindow != null )\r\n\t\t{\r\n\t\t\tdragImageWindow.dispose( );\r\n\t\t\tdragImageWindow = null;\r\n\t\t}\r\n\t\tdragImage = null;\r\n\t}\r\n}\r",
"public class DefaultTabDropFailureHandler implements ITabDropFailureHandler\r\n{\r\n\tpublic DefaultTabDropFailureHandler( ITabbedPaneWindowFactory windowFactory )\r\n\t{\r\n\t\tthis.windowFactory = windowFactory;\r\n\t}\r\n\t\r\n\tfinal ITabbedPaneWindowFactory\twindowFactory;\r\n\t\r\n\t@Override\r\n\tpublic void onDropFailure( DragSourceDropEvent dsde , Tab draggedTab , Dimension dragSourceWindowSize )\r\n\t{\r\n\t\tITabbedPaneWindow newJhromeWindow = windowFactory.createWindow( );\r\n\t\tWindow newWindow = newJhromeWindow.getWindow( );\r\n\t\tJTabbedPane tabbedPane = newJhromeWindow.getTabbedPane( );\r\n\t\t\r\n\t\tif( tabbedPane.getUI( ) instanceof JhromeTabbedPaneUI )\r\n\t\t{\r\n\t\t\tJhromeTabbedPaneUI ui = ( JhromeTabbedPaneUI ) tabbedPane.getUI( );\r\n\t\t\tui.addTab( tabbedPane.getTabCount( ) , draggedTab , false );\r\n\t\t\tui.finishAnimation( );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tJhromeTabbedPaneUI.insertTab( tabbedPane , tabbedPane.getTabCount( ) , draggedTab );\r\n\t\t}\r\n\t\tif( draggedTab.isEnabled( ) )\r\n\t\t{\r\n\t\t\ttabbedPane.setSelectedIndex( tabbedPane.getTabCount( ) - 1 );\r\n\t\t}\r\n\t\telse {\r\n\t\t\ttabbedPane.setSelectedIndex( -1 );\r\n\t\t}\r\n\t\t\r\n\t\tif( dragSourceWindowSize != null )\r\n\t\t{\r\n\t\t\tnewWindow.setSize( dragSourceWindowSize );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tnewWindow.pack( );\r\n\t\t}\r\n\t\t\r\n\t\tnewWindow.setLocation( dsde.getLocation( ) );\r\n\t\tnewWindow.setVisible( true );\r\n\t\t\r\n\t\tnewWindow.toFront( );\r\n\t\tnewWindow.requestFocus( );\r\n\t\t\r\n\t\tPoint loc = newWindow.getLocation( );\r\n\t\tComponent renderer = draggedTab.getRenderer( );\r\n\t\tPoint tabPos = new Point( renderer.getWidth( ) / 2 , renderer.getHeight( ) / 2 );\r\n\t\tSwingUtilities.convertPointToScreen( tabPos , renderer );\r\n\t\t\r\n\t\tloc.x += dsde.getX( ) - tabPos.x;\r\n\t\tloc.y += dsde.getY( ) - tabPos.y;\r\n\t\tnewWindow.setLocation( loc );\r\n\t}\r\n}\r",
"public class DefaultWindowsClosedHandler extends WindowAdapter\r\n{\r\n\t@Override\r\n\tpublic void windowClosed( WindowEvent e )\r\n\t{\r\n\t\tfor( Window window : Window.getWindows( ) )\r\n\t\t{\r\n\t\t\tif( window.isDisplayable( ) )\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor( Frame frame : Frame.getFrames( ) )\r\n\t\t{\r\n\t\t\tif( frame.isDisplayable( ) )\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tSystem.exit(0);\r\n\t}\r\n}\r",
"public interface ITabFactory\r\n{\r\n\t/**\r\n\t * @return a new {IJhromeTab}.\r\n\t */\r\n\tTab createTab( );\r\n\t\r\n\tTab createTabWithContent( );\r\n}\r",
"public interface ITabbedPaneDndPolicy\r\n{\r\n\t/**\r\n\t * Controls whether a jhromeTab may be \"torn away\" from a {@code JhromeTabbedPane} (if it can be removed by being dragged out of the tabbed pane).\r\n\t * \r\n\t * @param tabbedPane\r\n\t * the {@code JhromeTabbedPane} the user is dragging the jhromeTab out of.\r\n\t * @param tab\r\n\t * the {@code IJhromeTab} the user is dragging.\r\n\t * @return {@code true} if {@code jhromeTab} may be torn away from {@code tabbedPane}.\r\n\t */\r\n\tboolean isTearAwayAllowed( JTabbedPane tabbedPane , Tab tab );\r\n\t\r\n\t/**\r\n\t * Controls whether a jhromeTab may be \"snapped in\" to a {@code JhromeTabbedPane} (if it can be added by being dragged over the tabbed pane).\r\n\t * \r\n\t * @param tabbedPane\r\n\t * the {@code JhromeTabbedPane} the user is dragging the jhromeTab over.\r\n\t * @param tab\r\n\t * the {@code IJhromeTab} the user is dragging.\r\n\t * @return {@code true} if {@code jhromeTab} may be snapped into {@code tabbedPane}.\r\n\t */\r\n\tboolean isSnapInAllowed( JTabbedPane tabbedPane , Tab tab );\r\n}\r",
"public interface ITabbedPaneWindow\r\n{\r\n\t/**\r\n\t * @return the {@code JhromeTabbedPane} in the window.\r\n\t */\r\n\tJTabbedPane getTabbedPane( );\r\n\t\r\n\t/**\r\n\t * @return the {@code Window} containing the tabbed pane.\r\n\t */\r\n\tWindow getWindow( );\r\n}\r",
"public interface ITabbedPaneWindowFactory\r\n{\r\n\t\r\n\t/**\r\n\t * @return a new {@code IJhromeWindow}.\r\n\t */\r\n\tpublic abstract ITabbedPaneWindow createWindow( );\r\n\t\r\n}\r",
"public class Tab extends JComponent\r\n{\r\n\tprivate static final String\tuiClassId\t\t\t\t= \"TabUI\";\r\n\t\r\n\tprivate static final long\tserialVersionUID\t\t= 5209596149902613716L;\r\n\t\r\n\tprivate String\t\t\t\ttitle;\r\n\tprivate Icon\t\t\t\ticon;\r\n\tprivate Component\t\t\ttabComponent;\r\n\tprivate int\t\t\t\t\tmnemonic\t\t\t\t= '\\0';\r\n\tprivate int\t\t\t\t\tdisplayedMnemonicIndex\t= -1;\r\n\tprivate boolean\t\t\t\trollover;\r\n\tprivate boolean\t\t\t\tselected;\r\n\t\r\n\tprivate Component\t\t\tcontent;\r\n\t\r\n\tstatic\r\n\t{\r\n\t\tUIManager.getDefaults( ).put( uiClassId , JhromeTabUI.class.getName( ) );\r\n\t}\r\n\t\r\n\tpublic Tab( )\r\n\t{\r\n\t\tthis( null , null );\r\n\t}\r\n\t\r\n\tpublic Tab( String title )\r\n\t{\r\n\t\tthis( title , null );\r\n\t}\r\n\t\r\n\tpublic Tab( String title , Component content )\r\n\t{\r\n\t\tsetTitle( title );\r\n\t\tsetContent( content );\r\n\t\t\r\n\t\tupdateUI( );\r\n\t}\r\n\t\r\n\tpublic boolean isRollover( )\r\n\t{\r\n\t\treturn rollover;\r\n\t}\r\n\t\r\n\tpublic void setRollover( boolean rollover )\r\n\t{\r\n\t\tif( this.rollover != rollover )\r\n\t\t{\r\n\t\t\tthis.rollover = rollover;\r\n\t\t\tfirePropertyChange( \"rollover\" , !rollover , rollover );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic boolean isSelected( )\r\n\t{\r\n\t\treturn selected;\r\n\t}\r\n\t\r\n\tpublic void setSelected( boolean selected )\r\n\t{\r\n\t\tif( this.selected != selected )\r\n\t\t{\r\n\t\t\tthis.selected = selected;\r\n\t\t\tfirePropertyChange( \"selected\" , !selected , selected );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic TabUI getUI( )\r\n\t{\r\n\t\treturn ( TabUI ) ui;\r\n\t}\r\n\t\r\n\tpublic String getTitle( )\r\n\t{\r\n\t\treturn title;\r\n\t}\r\n\t\r\n\tprivate static boolean equals( Object o1 , Object o2 )\r\n\t{\r\n\t\treturn ( o1 == o2 ) || ( o1 != null && o1.equals( o2 ) ) || ( o2 != null && o2.equals( o1 ) );\r\n\t}\r\n\t\r\n\tpublic void setTitle( String title )\r\n\t{\r\n\t\tif( !equals( title , this.title ) )\r\n\t\t{\r\n\t\t\tString oldValue = this.title;\r\n\t\t\tthis.title = title;\r\n\t\t\tfirePropertyChange( \"title\" , oldValue , title );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Component getTabComponent( )\r\n\t{\r\n\t\treturn tabComponent;\r\n\t}\r\n\t\r\n\tpublic void setTabComponent( Component overrideTitle )\r\n\t{\r\n\t\tif( this.tabComponent != overrideTitle )\r\n\t\t{\r\n\t\t\tComponent oldValue = this.tabComponent;\r\n\t\t\tthis.tabComponent = overrideTitle;\r\n\t\t\tfirePropertyChange( \"overrideTitle\" , oldValue , overrideTitle );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Icon getIcon( )\r\n\t{\r\n\t\treturn icon;\r\n\t}\r\n\t\r\n\tpublic void setIcon( Icon icon )\r\n\t{\r\n\t\tif( this.icon != icon )\r\n\t\t{\r\n\t\t\tIcon oldValue = this.icon;\r\n\t\t\tthis.icon = icon;\r\n\t\t\tfirePropertyChange( \"icon\" , oldValue , icon );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic int getMnemonic( )\r\n\t{\r\n\t\treturn mnemonic;\r\n\t}\r\n\t\r\n\tpublic void setMnemonic( int mnemonic )\r\n\t{\r\n\t\tif( this.mnemonic != mnemonic )\r\n\t\t{\r\n\t\t\tint oldValue = this.mnemonic;\r\n\t\t\tthis.mnemonic = mnemonic;\r\n\t\t\tfirePropertyChange( \"mnemonic\" , oldValue , mnemonic );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic int getDisplayedMnemonicIndex( )\r\n\t{\r\n\t\treturn displayedMnemonicIndex;\r\n\t}\r\n\t\r\n\tpublic void setDisplayedMnemonicIndex( int displayedMnemonic )\r\n\t{\r\n\t\tif( this.displayedMnemonicIndex != displayedMnemonic )\r\n\t\t{\r\n\t\t\tint oldValue = this.displayedMnemonicIndex;\r\n\t\t\tthis.displayedMnemonicIndex = displayedMnemonic;\r\n\t\t\tfirePropertyChange( \"displayedMnemonic\" , oldValue , displayedMnemonic );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Component getRenderer( )\r\n\t{\r\n\t\treturn this;\r\n\t}\r\n\t\r\n\tpublic Component getContent( )\r\n\t{\r\n\t\treturn content;\r\n\t}\r\n\t\r\n\tpublic void setContent( Component tabContent )\r\n\t{\r\n\t\tthis.content = tabContent;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Specifies where the user can click and drag this jhromeTab. This way the jhromeTab component can behave as though it has a non-rectangular shape.\r\n\t * \r\n\t * @param p\r\n\t * the point at which the user pressed the mouse, in the renderer's coordinate system.\r\n\t * @return {@code true} if the user can drag the jhromeTab after dragging from {@code p}. NOTE: must return {@code false} for points over the close button\r\n\t * and other operable components, or the user will be able to drag the jhromeTab from these points!\r\n\t */\r\n\tpublic boolean isDraggableAt( Point p )\r\n\t{\r\n\t\treturn getUI( ).isDraggableAt( this , p );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Specifies where the user can click and select this jhromeTab. This way the jhromeTab component can behave as though it has a non-rectangular shape.\r\n\t * \r\n\t * @param p\r\n\t * the point at which the user pressed the mouse, in the renderer's coordinate system.\r\n\t * @return {@code true} if the user can select the jhromeTab by pressing the mouse at {@code p}. NOTE: must return {@code false} for points over the close\r\n\t * button and other operable components, or the user will be able to select the jhromeTab by clicking these components!\r\n\t */\r\n\tpublic boolean isSelectableAt( Point p )\r\n\t{\r\n\t\treturn getUI( ).isSelectableAt( this , p );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Specifies where the jhromeTab is \"hoverable.\" If the user moves the mouse over the hoverable areas of this jhromeTab, {@link TabbedPane} will set it to\r\n\t * the rollover state.\r\n\t * \r\n\t * @param p\r\n\t * the point the user moved the mouse over, in the renderer's coordinate system.\r\n\t * @return {@code true} if the jhromeTab should be set to the rollover state when the user moves the mouse over {@code p}.\r\n\t */\r\n\tpublic boolean isHoverableAt( Point p )\r\n\t{\r\n\t\treturn getUI( ).isHoverableAt( this , p );\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic String getUIClassID( )\r\n\t{\r\n\t\treturn uiClassId;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void updateUI( )\r\n\t{\r\n\t\tsetUI( ( TabUI ) UIManager.getUI( this ) );\r\n\t}\r\n\t\r\n\tpublic void setUI( TabUI ui )\r\n\t{\r\n\t\tsuper.setUI( ui );\r\n\t}\r\n}\r",
"@SuppressWarnings( \"serial\" )\r\npublic class JhromeTabbedPaneUI extends TabbedPaneUI\r\n{\r\n\tpublic static final String\tTAB_CLOSE_BUTTONS_VISIBLE\t= \"sexydock.tabbedPane.tabCloseButtonsVisible\";\r\n\t\r\n\tpublic static final String\tCONTENT_PANEL_BORDER\t\t= \"sexydock.tabbedPane.contentPanelBorder\";\r\n\t\r\n\tpublic static final String\tNEW_TAB_BUTTON_VISIBLE\t\t= \"sexydock.tabbedPane.newTabButtonVisible\";\r\n\t\r\n\tpublic static final String\tTAB_CLOSE_BUTTON_LISTENER\t= \"sexydock.tabbedPane.tabCloseButtonListener\";\r\n\t\r\n\tpublic static final String\tFLOATING_TAB_HANDLER\t\t= \"sexydock.tabbedPane.floatingTabHandler\";\r\n\t\r\n\tpublic static final String\tTAB_DROP_FAILURE_HANDLER\t= \"sexydock.tabbedPane.tabDropFailureHandler\";\r\n\t\r\n\tpublic static final String\tTAB_FACTORY\t\t\t\t\t= \"sexydock.tabbedPane.tabFactory\";\r\n\t\r\n\tpublic static final String\tDND_POLICY\t\t\t\t\t= \"sexydock.tabbedPane.dndPolicy\";\r\n\t\r\n\tpublic static final String\tNEW_TAB_BUTTON_UI\t\t\t= \"sexydock.tabbedPane.newTabButtonUI\";\r\n\t\r\n\tpublic static final String\tUSE_UNIFORM_WIDTH\t\t\t= \"sexydock.tabbedPane.useUniformWidth\";\r\n\t\r\n\tpublic static final String\tANIMATION_FACTOR\t\t\t= \"sexydock.tabbedPane.animationFactor\";\r\n\t\r\n\tpublic static final boolean\tDEFAULT_USE_UNIFORM_WIDTH\t= true;\r\n\t\r\n\tpublic static final double\tDEFAULT_ANIMATION_FACTOR\t= 0.7;\r\n\t\r\n\tpublic JhromeTabbedPaneUI( )\r\n\t{\r\n\t}\r\n\t\r\n\tprivate Map<Component, TabInfo>\tcontentMap\t= new HashMap<Component, TabInfo>( );\r\n\t\r\n\tprivate List<TabInfo>\t\t\ttabs\t\t= new ArrayList<TabInfo>( );\r\n\t\r\n\tprivate JTabbedPane\t\t\t\ttabbedPane;\r\n\tprivate JLayeredPane\t\t\ttabLayeredPane;\r\n\t\r\n\tprivate static class TabInfo\r\n\t{\r\n\t\tTab\t\t\ttab;\r\n\t\tDimension\tprefSize;\r\n\t\t\r\n\t\t/**\r\n\t\t * Whether the tab is being removed (contracting until its width reaches zero, when it will be completely removed)\r\n\t\t */\r\n\t\tboolean\t\tisBeingRemoved;\r\n\t\t\r\n\t\t/**\r\n\t\t * The tab's target x position in virtual coordinate space. It will be scaled down to produce the actual target x position.\r\n\t\t */\r\n\t\tint\t\t\tvTargetX;\r\n\t\t/**\r\n\t\t * The tab's target width in virtual coordinate space. This does not include the overlap area -- it is the distance to the virtual target x position of\r\n\t\t * the next tab. To get the actual target width, this value will be scaled down and the overlap amount will be added.\r\n\t\t */\r\n\t\tint\t\t\tvTargetWidth;\r\n\t\t\r\n\t\t/**\r\n\t\t * The tab's target bounds in actual coordinate space. Not valid for tabs that are being removed.\r\n\t\t */\r\n\t\tRectangle\ttargetBounds\t= new Rectangle( );\r\n\t\t\r\n\t\t/**\r\n\t\t * The tab's current x position in virtual coordinate space. It will be scaled down to produce the actual current x position.\r\n\t\t */\r\n\t\tint\t\t\tvCurrentX;\r\n\t\t/**\r\n\t\t * The tab's current width in virtual coordinate space. This does not include the overlap area -- it is the distance to the virtual current x position\r\n\t\t * of the next tab. To get the actual current width, this value will be scaled down and the overlap amount will be added.\r\n\t\t */\r\n\t\tint\t\t\tvCurrentWidth;\r\n\t\t\r\n\t\t/**\r\n\t\t * Whether the tab is being dragged.\r\n\t\t */\r\n\t\tboolean\t\tisBeingDragged;\r\n\t\t\r\n\t\t/**\r\n\t\t * The x position of the dragging mouse cursor in actual coordinate space.\r\n\t\t */\r\n\t\tint\t\t\tdragX;\r\n\t\t/**\r\n\t\t * The relative x position at which the tab was grabbed, as a proportion of its width (0.0 = left side, 0.5 = middle, 1.0 = right side). This way if the\r\n\t\t * tab width changes while it's being dragged, the layout manager can still give it a reasonable position relative to the mouse cursor.\r\n\t\t */\r\n\t\tdouble\t\tgrabX;\r\n\t}\r\n\t\r\n\tprivate int\t\t\t\t\t\t\toverlap\t\t\t\t\t= 13;\r\n\t\r\n\tprivate double\t\t\t\t\t\tanimFactor\t\t\t\t= DEFAULT_ANIMATION_FACTOR;\r\n\t\r\n\tprivate javax.swing.Timer\t\t\tanimTimer;\r\n\tprivate final Object\t\t\t\tanimLock\t\t\t\t= new Object( );\r\n\t\r\n\tprivate TabLayoutManager\t\t\tlayout;\r\n\t\r\n\tprivate boolean\t\t\t\t\t\tuseUniformWidth\t\t\t= true;\r\n\tprivate int\t\t\t\t\t\t\tmaxUniformWidth\t\t\t= 300;\r\n\t\r\n\tprivate boolean\t\t\t\t\t\tmouseOverTopZone\t\t= true;\r\n\t\r\n\tprivate MouseManager\t\t\t\tmouseOverManager;\r\n\t\r\n\tprivate TabInfo\t\t\t\t\t\tselectedTab\t\t\t\t= null;\r\n\t\r\n\tprivate Component\t\t\t\t\tcurrentContent\t\t\t= null;\r\n\t\r\n\t/**\r\n\t * How many pixels the content panel overlaps the tabs. This is necessary with the Google Chrome appearance to make the selected tab and the content panel\r\n\t * look like a contiguous object\r\n\t */\r\n\tprivate int\t\t\t\t\t\t\tcontentPanelOverlap\t\t= 1;\r\n\tprivate Border\t\t\t\t\t\tcontentPanelBorder\t\t= null;\r\n\tprivate Rectangle\t\t\t\t\tcontentPanelBounds\t\t= new Rectangle( );\r\n\t\r\n\tprivate int\t\t\t\t\t\t\ttabMargin\t\t\t\t= 2;\r\n\t\r\n\tprivate JPanel\t\t\t\t\t\trightButtonsPanel;\r\n\t\r\n\tprivate JButton\t\t\t\t\t\tnewTabButton;\r\n\t\r\n\tprivate ActionListener\t\t\t\tnewTabButtonListener;\r\n\t\r\n\tprivate DragHandler\t\t\t\t\tdragHandler;\r\n\t\r\n\tprivate ITabDropFailureHandler\t\ttabDropFailureHandler\t= null;\r\n\t\r\n\tprivate IFloatingTabHandler\t\t\tfloatingTabHandler\t\t= null;\r\n\t\r\n\tprivate InternalTransferableStore\ttransferableStore\t\t= InternalTransferableStore.getDefaultInstance( );\r\n\t\r\n\tprivate ITabFactory\t\t\t\t\ttabFactory\t\t\t\t= null;\r\n\t\r\n\tprivate Rectangle\t\t\t\t\ttopZone\t\t\t\t\t= new Rectangle( );\r\n\tprivate Rectangle\t\t\t\t\ttabZone\t\t\t\t\t= new Rectangle( );\r\n\t\r\n\tprivate int\t\t\t\t\t\t\textraDropZoneSpace\t\t= 25;\r\n\tprivate Rectangle\t\t\t\t\tdropZone\t\t\t\t= new Rectangle( );\r\n\t\r\n\tprivate ITabbedPaneDndPolicy\t\tdndPolicy\t\t\t\t= null;\r\n\t\r\n\tprivate List<ITabbedPaneListener>\ttabListeners\t\t\t= new ArrayList<ITabbedPaneListener>( );\r\n\t\r\n\tprivate Handler\t\t\t\t\t\thandler\t\t\t\t\t= new Handler( );\r\n\t\r\n\tprivate final Object\t\t\t\tupdateLock\t\t\t\t= new Object( );\r\n\t\r\n\tprivate class MouseManager extends RecursiveListener\r\n\t{\r\n\t\tMouseAdapter\tadapter\t= new MouseAdapter( )\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tprivate void updateHoldTabScale( MouseEvent e )\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tPoint p = e.getPoint( );\r\n\t\t\t\t\t\t\t\t\t\tp = SwingUtilities.convertPoint( ( Component ) e.getSource( ) , p , tabbedPane );\r\n\t\t\t\t\t\t\t\t\t\tboolean newMouseOver = Utils.contains( topZone , p );\r\n\t\t\t\t\t\t\t\t\t\tif( newMouseOver != mouseOverTopZone )\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tmouseOverTopZone = newMouseOver;\r\n\t\t\t\t\t\t\t\t\t\t\ttabbedPane.invalidate( );\r\n\t\t\t\t\t\t\t\t\t\t\ttabbedPane.validate( );\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\tpublic void mouseEntered( MouseEvent e )\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tupdateHoldTabScale( e );\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\tpublic void mouseExited( MouseEvent e )\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tupdateHoldTabScale( e );\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\tpublic void mouseMoved( MouseEvent e )\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tupdateHoldTabScale( e );\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tif( !tabbedPane.isEnabled( ) )\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tPoint p = SwingUtilities.convertPoint( e.getComponent( ) , e.getPoint( ) , tabbedPane );\r\n\t\t\t\t\t\t\t\t\t\tTab tab = getHoverableTabAt( p );\r\n\t\t\t\t\t\t\t\t\t\tfor( TabInfo info : tabs )\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tinfo.tab.setRollover( info.tab.isEnabled( ) && info.tab == tab );\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\tpublic void mousePressed( MouseEvent e )\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tif( !tabbedPane.isEnabled( ) )\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tPoint p = SwingUtilities.convertPoint( e.getComponent( ) , e.getPoint( ) , tabbedPane );\r\n\t\t\t\t\t\t\t\t\t\tTab tab = getSelectableTabAt( p );\r\n\t\t\t\t\t\t\t\t\t\tif( tab != null )\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tint vIndex = virtualizeIndex( getInfoIndex( tab ) );\r\n\t\t\t\t\t\t\t\t\t\t\tif( tabbedPane.getSelectedComponent( ) != tab.getContent( ) && tabbedPane.isEnabledAt( vIndex ) )\r\n\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\ttabbedPane.setSelectedComponent( tab.getContent( ) );\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\telse if( tabbedPane.isRequestFocusEnabled( ) )\r\n\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\ttabbedPane.requestFocus( );\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t};\r\n\t\t\r\n\t\t@Override\r\n\t\tprotected void install( Component c )\r\n\t\t{\r\n\t\t\tc.addMouseListener( adapter );\r\n\t\t\tc.addMouseMotionListener( adapter );\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tprotected void uninstall( Component c )\r\n\t\t{\r\n\t\t\tc.removeMouseListener( adapter );\r\n\t\t\tc.removeMouseMotionListener( adapter );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static JhromeTabbedPaneUI createUI( JComponent c )\r\n\t{\r\n\t\treturn new JhromeTabbedPaneUI( );\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void installUI( JComponent c )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\ttabbedPane = ( JTabbedPane ) c;\r\n\t\tinit( );\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void uninstallUI( JComponent c )\r\n\t{\r\n\t\tif( c != tabbedPane )\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException( \"Cannot uninstall from a different component than this was installed on\" );\r\n\t\t}\r\n\t\tcheckEDT( );\r\n\t\tdispose( );\r\n\t}\r\n\t\r\n\tprivate class TabLayeredPane extends JLayeredPane implements UIResource\r\n\t{\r\n\t\t\r\n\t}\r\n\t\r\n\tprivate void init( )\r\n\t{\r\n\t\tsynchronized( animLock )\r\n\t\t{\r\n\t\t\tanimTimer = new Timer( 15 , new ActionListener( )\r\n\t\t\t{\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void actionPerformed( ActionEvent e )\r\n\t\t\t\t{\r\n\t\t\t\t\tif( tabbedPane != null )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttabbedPane.invalidate( );\r\n\t\t\t\t\t\ttabbedPane.validate( );\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\tlayout = new TabLayoutManager( );\r\n\t\ttabbedPane.setLayout( layout );\r\n\t\ttabLayeredPane = new TabLayeredPane( );\r\n\t\ttabLayeredPane.setName( \"Tab Layered Pane\" );\r\n\t\ttabLayeredPane.setLayout( null );\r\n\t\ttabbedPane.add( tabLayeredPane );\r\n\t\t\r\n\t\ttabbedPane.invalidate( );\r\n\t\ttabbedPane.validate( );\r\n\t\t\r\n\t\tmouseOverManager = new MouseManager( );\r\n\t\tmouseOverManager.addExcludedComponent( tabLayeredPane );\r\n\t\tmouseOverManager.install( tabbedPane );\r\n\t\t\r\n\t\tnewTabButton = new JButton( );\r\n\t\t\r\n\t\tnewTabButtonListener = new ActionListener( )\r\n\t\t{\r\n\t\t\t@Override\r\n\t\t\tpublic void actionPerformed( ActionEvent e )\r\n\t\t\t{\r\n\t\t\t\tif( tabFactory == null )\r\n\t\t\t\t{\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\tTab newTab = tabFactory.createTabWithContent( );\r\n\t\t\t\tif( newTab != null )\r\n\t\t\t\t{\r\n\t\t\t\t\ttabbedPane.addTab( newTab.getTitle( ) , newTab.getContent( ) );\r\n\t\t\t\t\ttabbedPane.setSelectedComponent( newTab.getContent( ) );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n\t\t\r\n\t\tnewTabButton.addActionListener( newTabButtonListener );\r\n\t\tnewTabButton.setUI( PropertyGetter.get( ButtonUI.class , tabbedPane , NEW_TAB_BUTTON_UI , ( String ) null , new JhromeNewTabButtonUI( ) ) );\r\n\t\tnewTabButton.setVisible( PropertyGetter.get( Boolean.class , tabbedPane , NEW_TAB_BUTTON_VISIBLE , false ) );\r\n\t\tnewTabButton.setEnabled( tabbedPane.isEnabled( ) );\r\n\t\tcontentPanelBorder = PropertyGetter.get( Border.class , tabbedPane , CONTENT_PANEL_BORDER , ( String ) null , new JhromeContentPanelBorder( ) );\r\n\t\t\r\n\t\trightButtonsPanel = new JPanel( );\r\n\t\trightButtonsPanel.setLayout( new GridBagLayout( ) );\r\n\t\trightButtonsPanel.setOpaque( false );\r\n\t\t\r\n\t\tGridBagConstraints gbc = new GridBagConstraints( );\r\n\t\tgbc.anchor = GridBagConstraints.CENTER;\r\n\t\tgbc.insets = new Insets( 1 , 2 , 0 , 0 );\r\n\t\trightButtonsPanel.add( newTabButton , gbc );\r\n\t\ttabLayeredPane.add( rightButtonsPanel );\r\n\t\t\r\n\t\tdragHandler = new DragHandler( tabbedPane , DnDConstants.ACTION_MOVE );\r\n\t\tnew DropHandler( tabbedPane );\r\n\t\t\r\n\t\thandler = new Handler( );\r\n\t\ttabbedPane.addContainerListener( handler );\r\n\t\ttabbedPane.addChangeListener( handler );\r\n\t\ttabbedPane.addPropertyChangeListener( handler );\r\n\t\ttabbedPane.addFocusListener( handler );\r\n\t\t\r\n\t\ttabFactory = PropertyGetter.get( ITabFactory.class , tabbedPane , TAB_FACTORY , new DefaultTabFactory( ) );\r\n\t\tdndPolicy = PropertyGetter.get( ITabbedPaneDndPolicy.class , tabbedPane , DND_POLICY );\r\n\t\ttabDropFailureHandler = PropertyGetter.get( ITabDropFailureHandler.class , tabbedPane , TAB_DROP_FAILURE_HANDLER );\r\n\t\tfloatingTabHandler = PropertyGetter.get( IFloatingTabHandler.class , tabbedPane , FLOATING_TAB_HANDLER , new DefaultFloatingTabHandler( ) );\r\n\t\tuseUniformWidth = PropertyGetter.get( Boolean.class , tabbedPane , USE_UNIFORM_WIDTH , DEFAULT_USE_UNIFORM_WIDTH );\r\n\t\tanimFactor = PropertyGetter.get( Double.class , tabbedPane , ANIMATION_FACTOR , DEFAULT_ANIMATION_FACTOR );\r\n\t\tif( tabbedPane.getClientProperty( TAB_CLOSE_BUTTON_LISTENER ) == null )\r\n\t\t{\r\n\t\t\ttabbedPane.putClientProperty( TAB_CLOSE_BUTTON_LISTENER , PropertyGetter.get( ITabCloseButtonListener.class , TAB_CLOSE_BUTTON_LISTENER , new DefaultTabCloseButtonListener( ) ) );\r\n\t\t}\r\n\t\tif( tabbedPane.getClientProperty( TAB_CLOSE_BUTTONS_VISIBLE ) == null )\r\n\t\t{\r\n\t\t\ttabbedPane.putClientProperty( TAB_CLOSE_BUTTONS_VISIBLE , PropertyGetter.get( Boolean.class , TAB_CLOSE_BUTTONS_VISIBLE , false ) );\r\n\t\t}\r\n\t\t\r\n\t\tinstallKeyboardActions( );\r\n\t}\r\n\t\r\n\tpublic ITabFactory getTabFactory( )\r\n\t{\r\n\t\treturn tabFactory;\r\n\t}\r\n\t\r\n\tpublic void setTabFactory( ITabFactory tabFactory )\r\n\t{\r\n\t\tthis.tabFactory = tabFactory;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Sets the drop failure handler to a {@link DefaultTabDropFailureHandler} with the given window factory.\r\n\t */\r\n\tpublic void setWindowFactory( ITabbedPaneWindowFactory windowFactory )\r\n\t{\r\n\t\tsetDropFailureHandler( new DefaultTabDropFailureHandler( windowFactory ) );\r\n\t}\r\n\t\r\n\tpublic ITabDropFailureHandler getDropFailureHandler( )\r\n\t{\r\n\t\treturn tabDropFailureHandler;\r\n\t}\r\n\t\r\n\tpublic void setDropFailureHandler( DefaultTabDropFailureHandler dropFailureHandler )\r\n\t{\r\n\t\tthis.tabDropFailureHandler = dropFailureHandler;\r\n\t}\r\n\t\r\n\tpublic ITabbedPaneDndPolicy getDndPolicy( )\r\n\t{\r\n\t\treturn dndPolicy;\r\n\t}\r\n\t\r\n\tpublic void setDndPolicy( ITabbedPaneDndPolicy dndPolicy )\r\n\t{\r\n\t\tthis.dndPolicy = dndPolicy;\r\n\t}\r\n\t\r\n\tpublic IFloatingTabHandler getFloatingTabHandler( )\r\n\t{\r\n\t\treturn floatingTabHandler;\r\n\t}\r\n\t\r\n\tpublic void setFloatingTabHandler( IFloatingTabHandler floatingTabHandler )\r\n\t{\r\n\t\tthis.floatingTabHandler = floatingTabHandler;\r\n\t}\r\n\t\r\n\t/**\r\n\t * @return whether to make all tabs the same width. If uniform width is not used, the tabs' preferred widths will be used.\r\n\t */\r\n\tpublic boolean isUseUniformWidth( )\r\n\t{\r\n\t\treturn useUniformWidth;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Sets whether to make all tabs the same width. If uniform width is not used, the tabs' preferred widths will be used.\r\n\t */\r\n\tpublic void setUseUniformWidth( boolean useUniformWidth )\r\n\t{\r\n\t\tif( this.useUniformWidth != useUniformWidth )\r\n\t\t{\r\n\t\t\tthis.useUniformWidth = useUniformWidth;\r\n\t\t\ttabbedPane.invalidate( );\r\n\t\t\ttabbedPane.validate( );\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * @return the width to make each tab if {@link #isUseUniformWidth()} is {@code true}. If there are too many tabs in this tabbed pane to fit at this width,\r\n\t * they will of course be squashed down.\r\n\t */\r\n\tpublic int getMaxUniformWidth( )\r\n\t{\r\n\t\treturn maxUniformWidth;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Sets the width to make each tab if {@link #isUseUniformWidth()} is {@code true}. If there are too many tabs in this tabbed pane to fit at this width,\r\n\t * they will of course be squashed down.\r\n\t */\r\n\tpublic void setMaxUniformWidth( int maxUniformWidth )\r\n\t{\r\n\t\tif( this.maxUniformWidth != maxUniformWidth )\r\n\t\t{\r\n\t\t\tthis.maxUniformWidth = maxUniformWidth;\r\n\t\t\ttabbedPane.invalidate( );\r\n\t\t\ttabbedPane.validate( );\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * @param p\r\n\t * a {@link Point} in this tabbed pane's coordinate system.\r\n\t * \r\n\t * @return the hoverable tab under {@code p}, or {@code null} if no such tab exists.\r\n\t * \r\n\t * @see Tab#isHoverableAt(Point)\r\n\t */\r\n\tpublic Tab getHoverableTabAt( Point p )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tfor( int i = -1 ; i < tabs.size( ) ; i++ )\r\n\t\t{\r\n\t\t\tTabInfo info = i < 0 ? selectedTab : tabs.get( i );\r\n\t\t\tif( info == null || info.isBeingRemoved )\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif( info == selectedTab && i >= 0 )\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tTab tab = info.tab;\r\n\t\t\tComponent c = tab;\r\n\t\t\tPoint converted = SwingUtilities.convertPoint( tabbedPane , p , c );\r\n\t\t\tif( c.contains( converted ) )\r\n\t\t\t{\r\n\t\t\t\tif( tab.isHoverableAt( converted ) )\r\n\t\t\t\t{\r\n\t\t\t\t\treturn tab;\r\n\t\t\t\t}\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 * @param p\r\n\t * a {@link Point} in this tabbed pane's coordinate system.\r\n\t * \r\n\t * @return the draggable tab under {@code p}, or {@code null} if no such tab exists.\r\n\t * \r\n\t * @see Tab#isDraggableAt(Point)\r\n\t */\r\n\tpublic Tab getDraggableTabAt( Point p )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tfor( int i = -1 ; i < tabs.size( ) ; i++ )\r\n\t\t{\r\n\t\t\tTabInfo info = i < 0 ? selectedTab : tabs.get( i );\r\n\t\t\tif( info == null || info.isBeingRemoved )\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif( info == selectedTab && i >= 0 )\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tTab tab = info.tab;\r\n\t\t\tComponent c = tab;\r\n\t\t\tPoint converted = SwingUtilities.convertPoint( tabbedPane , p , c );\r\n\t\t\tif( c.contains( converted ) )\r\n\t\t\t{\r\n\t\t\t\tif( tab.isDraggableAt( converted ) )\r\n\t\t\t\t{\r\n\t\t\t\t\treturn tab;\r\n\t\t\t\t}\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 * @param p\r\n\t * a {@link Point} in this tabbed pane's coordinate system.\r\n\t * \r\n\t * @return the selectable tab under {@code p}, or {@code null} if no such tab exists.\r\n\t * \r\n\t * @see Tab#isSelectableAt(Point)\r\n\t */\r\n\tpublic Tab getSelectableTabAt( Point p )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tfor( int i = -1 ; i < tabs.size( ) ; i++ )\r\n\t\t{\r\n\t\t\tTabInfo info = i < 0 ? selectedTab : tabs.get( i );\r\n\t\t\tif( info == null || info.isBeingRemoved )\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif( info == selectedTab && i >= 0 )\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tTab tab = info.tab;\r\n\t\t\tComponent c = tab;\r\n\t\t\tPoint converted = SwingUtilities.convertPoint( tabbedPane , p , c );\r\n\t\t\tif( c.contains( converted ) )\r\n\t\t\t{\r\n\t\t\t\tif( tab.isSelectableAt( converted ) )\r\n\t\t\t\t{\r\n\t\t\t\t\treturn tab;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tprivate int getInfoIndex( Tab tab )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\tfor( int i = 0 ; i < tabs.size( ) ; i++ )\r\n\t\t{\r\n\t\t\tTabInfo info = tabs.get( i );\r\n\t\t\tif( info.tab == tab )\r\n\t\t\t{\r\n\t\t\t\treturn i;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn -1;\r\n\t}\r\n\t\r\n\tprivate TabInfo getInfo( Tab tab )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tfor( TabInfo info : tabs )\r\n\t\t{\r\n\t\t\tif( info.tab == tab )\r\n\t\t\t{\r\n\t\t\t\treturn info;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tprivate int actualizeIndex( int index )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tint virtual = 0;\r\n\t\t\r\n\t\tint actual;\r\n\t\tfor( actual = 0 ; actual < tabs.size( ) ; actual++ )\r\n\t\t{\r\n\t\t\tif( virtual == index )\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif( !tabs.get( actual ).isBeingRemoved )\r\n\t\t\t{\r\n\t\t\t\tvirtual++ ;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn actual;\r\n\t}\r\n\t\r\n\tprivate int virtualizeIndex( int index )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tint virtual = 0;\r\n\t\t\r\n\t\tfor( int actual = 0 ; actual < index ; actual++ )\r\n\t\t{\r\n\t\t\tif( !tabs.get( actual ).isBeingRemoved )\r\n\t\t\t{\r\n\t\t\t\tvirtual++ ;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn virtual;\r\n\t}\r\n\t\r\n\t/**\r\n\t * @return the number of tabs in this tabbed pane.\r\n\t */\r\n\tpublic int getTabCount( )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tint count = 0;\r\n\t\tfor( int i = 0 ; i < tabs.size( ) ; i++ )\r\n\t\t{\r\n\t\t\tif( !tabs.get( i ).isBeingRemoved )\r\n\t\t\t{\r\n\t\t\t\tcount++ ;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn count;\r\n\t}\r\n\t\r\n\tpublic Tab getTabAt( int vIndex )\r\n\t{\r\n\t\treturn tabs.get( actualizeIndex( vIndex ) ).tab;\r\n\t}\r\n\t\r\n\t/**\r\n\t * @return a newly-constructed {@link List} of the tabs in this tabbed pane.\r\n\t */\r\n\tpublic List<Tab> getTabs( )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tList<Tab> result = new ArrayList<Tab>( );\r\n\t\tfor( TabInfo info : tabs )\r\n\t\t{\r\n\t\t\tif( !info.isBeingRemoved )\r\n\t\t\t{\r\n\t\t\t\tresult.add( info.tab );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Inserts a tab at a specific index in the tabbed pane. The new tab will not be selected.\r\n\t * \r\n\t * @param vIndex\r\n\t * the index to add the tab at. Like {@link List#add(int, Object)}, this method will insert the new tab before the tab at {@code index}.\r\n\t * @param tab\r\n\t * the tab to add.\r\n\t * \r\n\t * @throws IllegalArgumentException\r\n\t * if {@code index} is less than 0 or greater than the tab count, or {@code tab} is already a member of this tabbed pane.\r\n\t */\r\n\tprivate void addTabInternal( int vIndex , final Tab tab )\r\n\t{\r\n\t\taddTabInternal( vIndex , tab , true );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Inserts a tab at a specific index in the tabbed pane.\r\n\t * \r\n\t * @param vIndex\r\n\t * the index to add the tab at. Like {@link List#add(int, Object)}, this method will insert the new tab before the tab at {@code index}.\r\n\t * @param tab\r\n\t * the tab to add.\r\n\t * @param expand\r\n\t * whether to animate the new tab expansion. If {@code false}, the new tab will immediately appear at full size.\r\n\t * \r\n\t * @throws IllegalArgumentException\r\n\t * if {@code index} is less than 0 or greater than the tab count, or {@code tab} is already a member of this tabbed pane.\r\n\t */\r\n\tprivate void addTabInternal( int vIndex , final Tab tab , boolean expand )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tint tabCount = getTabCount( );\r\n\t\tif( vIndex < 0 || vIndex > tabCount )\r\n\t\t{\r\n\t\t\tthrow new IndexOutOfBoundsException( String.format( \"Invalid insertion index: %d (tab count: %d)\" , vIndex , tabCount ) );\r\n\t\t}\r\n\t\tTabInfo existing = getInfo( tab );\r\n\t\t\r\n\t\tif( existing != null )\r\n\t\t{\r\n\t\t\tif( existing.isBeingRemoved )\r\n\t\t\t{\r\n\t\t\t\tactuallyRemoveTab( tab );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tthrow new IllegalArgumentException( \"Tab has already been added: \" + tab );\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tTabAddedEvent event = new TabAddedEvent( tabbedPane , System.currentTimeMillis( ) , tab , vIndex );\r\n\t\t\r\n\t\tint index = actualizeIndex( vIndex );\r\n\t\t\r\n\t\tboolean transpose = tabbedPane.getTabPlacement( ) == JTabbedPane.LEFT || tabbedPane.getTabPlacement( ) == JTabbedPane.RIGHT;\r\n\t\t\r\n\t\tTabInfo info = new TabInfo( );\r\n\t\tinfo.tab = tab;\r\n\t\tinfo.prefSize = tab.getPreferredSize( );\r\n\t\tint prefWidth = transpose ? info.prefSize.height : info.prefSize.width;\r\n\t\tinfo.vCurrentWidth = expand ? 0 : prefWidth;\r\n\t\tinfo.isBeingRemoved = false;\r\n\t\t\r\n\t\tif( index > 0 )\r\n\t\t{\r\n\t\t\tTabInfo prev = tabs.get( index - 1 );\r\n\t\t\tinfo.vCurrentX = prev.vCurrentX + prev.vCurrentWidth - overlap;\r\n\t\t}\r\n\t\ttabs.add( index , info );\r\n\t\tcontentMap.put( tab.getContent( ) , info );\r\n\t\t\r\n\t\ttabLayeredPane.add( tab );\r\n\t\t\r\n\t\ttabbedPane.invalidate( );\r\n\t\ttabbedPane.validate( );\r\n\t\t\r\n\t\tnotifyTabbedPaneListeners( event );\r\n\t}\r\n\t\r\n\tpublic void addTab( int vIndex , Tab tab , boolean expand )\r\n\t{\r\n\t\taddTabInternal( vIndex , tab , expand );\r\n\t\thandler.disable = true;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tinsertTab( tabbedPane , vIndex , tab );\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\thandler.disable = false;\r\n\t\t}\r\n\t\tsetSelectedIndexInternal( tabbedPane.getSelectedIndex( ) );\r\n\t}\r\n\t\r\n\tpublic static void insertTab( JTabbedPane tabbedPane , int index , Tab tab )\r\n\t{\r\n\t\ttabbedPane.insertTab( tab.getTitle( ) , tab.getIcon( ) , tab.getContent( ) , tab.getToolTipText( ) , index );\r\n\t\ttabbedPane.setTabComponentAt( index , tab.getTabComponent( ) );\r\n\t\ttabbedPane.setEnabledAt( index , tab.isEnabled( ) );\r\n\t\ttabbedPane.setMnemonicAt( index , tab.getMnemonic( ) );\r\n\t\ttabbedPane.setDisplayedMnemonicIndexAt( index , tab.getDisplayedMnemonicIndex( ) );\r\n\t\ttabbedPane.setBackgroundAt( index , tab.getBackground( ) );\r\n\t\ttabbedPane.setForegroundAt( index , tab.getForeground( ) );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Moves a tab from its current index to a new index.\r\n\t * \r\n\t * @param tab\r\n\t * the tab to move.\r\n\t * @param vNewIndex\r\n\t * the index to move the tab to. Like {@link List#add(int, Object)}, this method will insert {@code tab} before the tab at {@code newIndex}.\r\n\t * \r\n\t * @throws IllegalArgumentException\r\n\t * if {@code newIndex} is less than 0, greater than the tab count, or {@code tab} is not a member of this tabbed pane.\r\n\t */\r\n\tprivate void moveTabInternal( Tab tab , int vNewIndex )\r\n\t{\r\n\t\tint tabCount = getTabCount( );\r\n\t\tif( vNewIndex < 0 || vNewIndex > tabCount )\r\n\t\t{\r\n\t\t\tthrow new IndexOutOfBoundsException( String.format( \"Invalid new index: %d (tab count: %d)\" , vNewIndex , tabCount ) );\r\n\t\t}\r\n\t\t\r\n\t\tint actualNewIndex = actualizeIndex( vNewIndex );\r\n\t\tint currentIndex = getInfoIndex( tab );\r\n\t\t\r\n\t\tif( currentIndex < 0 )\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException( \"Tab is not a member of this tabbed pane: \" + tab );\r\n\t\t}\r\n\t\t\r\n\t\tTabInfo info = tabs.get( currentIndex );\r\n\t\t\r\n\t\tif( info.isBeingRemoved )\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException( \"Tab is not a member of this tabbed pane: \" + tab );\r\n\t\t}\r\n\t\t\r\n\t\tif( actualNewIndex != currentIndex )\r\n\t\t{\r\n\t\t\tint vCurrentIndex = virtualizeIndex( currentIndex );\r\n\t\t\t\r\n\t\t\tTabMovedEvent event = new TabMovedEvent( tabbedPane , System.currentTimeMillis( ) , info.tab , vCurrentIndex , vNewIndex );\r\n\t\t\t\r\n\t\t\tactualNewIndex = Math.min( actualNewIndex , tabs.size( ) - 1 );\r\n\t\t\ttabs.remove( info );\r\n\t\t\ttabs.add( actualNewIndex , info );\r\n\t\t\t\r\n\t\t\ttabbedPane.invalidate( );\r\n\t\t\ttabbedPane.validate( );\r\n\t\t\t\r\n\t\t\tnotifyTabbedPaneListeners( event );\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Moves the given tab with animation (if enabled). Attempting to do this by removing / adding back the tab in the {@link JTabbedPane} won't produce the\r\n\t * same effect.\r\n\t * \r\n\t * @param vCurrentIndex\r\n\t * the current index of the tab to move.\r\n\t * @param vNewIndex\r\n\t * the index to move the tab to.\r\n\t */\r\n\tpublic void moveTab( int vCurrentIndex , int vNewIndex )\r\n\t{\r\n\t\tTabInfo info = tabs.get( actualizeIndex( vCurrentIndex ) );\r\n\t\t\r\n\t\thandler.disable = true;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tint index = tabbedPane.indexOfComponent( info.tab.getContent( ) );\r\n\t\t\tif( index >= 0 && index != vNewIndex )\r\n\t\t\t{\r\n\t\t\t\ttabbedPane.removeTabAt( index );\r\n\t\t\t\tinsertTab( tabbedPane , vNewIndex , info.tab );\r\n\t\t\t}\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\thandler.disable = false;\r\n\t\t}\r\n\t\tmoveTabInternal( info.tab , vNewIndex );\r\n\t\tupdateMnemonics( );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Removes a tab from this tabbed pane with animation. The layout will animate the tab renderer shrinking before it is actually removed from the component\r\n\t * hierarchy. However, the tab will be immediately removed from the list of tabs in this tabbed pane, so {@link #getTabs()}, {@link #addTabInternal(Tab)},\r\n\t * {@link #moveTabInternal(Tab, int)}, etc. will all behave as if it is no longer a member of this tabbed pane. If you want to remove the tab and its\r\n\t * renderer component immediately, use {@link #removeTabImmediatelyInternal(Tab)}.\r\n\t * \r\n\t * If the selected tab is removed, one of the adjacent tabs will be selected before it is removed. If it is the only tab, the selection will be cleared\r\n\t * before it is removed.\r\n\t * \r\n\t * {@code tab} the tab to remove. If {@code tab} is not a member of this tabbed pane, this method has no effect.\r\n\t */\r\n\tprivate void removeTabInternal( Tab tab )\r\n\t{\r\n\t\tremoveTabInternal( tab , true );\r\n\t}\r\n\t\r\n\tprivate void removeTabInternal( Tab tab , boolean startTimer )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tint removedIndex = getInfoIndex( tab );\r\n\t\t\r\n\t\tif( removedIndex >= 0 )\r\n\t\t{\r\n\t\t\tTabInfo info = tabs.get( removedIndex );\r\n\t\t\tif( info.isBeingRemoved )\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tTabRemovedEvent event = new TabRemovedEvent( tabbedPane , System.currentTimeMillis( ) , tab , virtualizeIndex( removedIndex ) );\r\n\t\t\t\r\n\t\t\tif( info == selectedTab )\r\n\t\t\t{\r\n\t\t\t\tif( tabs.size( ) == 1 )\r\n\t\t\t\t{\r\n\t\t\t\t\tsetSelectedTabInternal( ( TabInfo ) null );\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tint index = tabs.indexOf( info );\r\n\t\t\t\t\t\r\n\t\t\t\t\t// select the closest tab that is not being removed\r\n\t\t\t\t\tTabInfo newSelectedTab = null;\r\n\t\t\t\t\t\r\n\t\t\t\t\tfor( int i = index + 1 ; i < tabs.size( ) ; i++ )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tTabInfo adjTab = tabs.get( i );\r\n\t\t\t\t\t\tif( !adjTab.isBeingRemoved )\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tnewSelectedTab = adjTab;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif( newSelectedTab == null )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor( int i = index - 1 ; i >= 0 ; i-- )\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tTabInfo adjTab = tabs.get( i );\r\n\t\t\t\t\t\t\tif( !adjTab.isBeingRemoved )\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tnewSelectedTab = adjTab;\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tsetSelectedTabInternal( newSelectedTab );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tinfo.isBeingDragged = false;\r\n\t\t\tinfo.isBeingRemoved = true;\r\n\t\t\ttabbedPane.invalidate( );\r\n\t\t\ttabbedPane.validate( );\r\n\t\t\t\r\n\t\t\tnotifyTabbedPaneListeners( event );\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Removes a tab from this tabbed pane without animation. This means the tab renderer will be removed from the component hierarchy immediately, unlike\r\n\t * {@link #removeTabInternal(Tab)}.\r\n\t * \r\n\t * If the selected tab is removed, one of the adjacent tabs will be selected before it is removed. If it is the only tab, the selection will be cleared\r\n\t * before it is removed.\r\n\t * \r\n\t * @param tab\r\n\t * the tab to remove. If {@code tab} is not a member of this tabbed pane, this method has no effect.\r\n\t */\r\n\tprivate void removeTabImmediatelyInternal( Tab tab )\r\n\t{\r\n\t\tremoveTabInternal( tab , false );\r\n\t\tactuallyRemoveTab( tab );\r\n\t}\r\n\t\r\n\tprivate void actuallyRemoveTab( Tab tab )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tTabInfo info = getInfo( tab );\r\n\t\tif( info != null )\r\n\t\t{\r\n\t\t\t// if( tab.getCloseButton( ) != null && info.closeButtonHandler != null )\r\n\t\t\t// {\r\n\t\t\t// tab.getCloseButton( ).removeActionListener( info.closeButtonHandler );\r\n\t\t\t// }\r\n\t\t\ttabLayeredPane.remove( tab );\r\n\t\t\ttabs.remove( info );\r\n\t\t\tcontentMap.remove( info.tab.getContent( ) );\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Removes all tabs from this tabbed pane without animation. This method is equivalent to setting the selected tab to {@code null} and then removing all\r\n\t * tabs one by one.\r\n\t */\r\n\tprivate void removeAllTabsInternal( )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tlong time = System.currentTimeMillis( );\r\n\t\t\r\n\t\tsetSelectedTabInternal( ( TabInfo ) null );\r\n\t\t\r\n\t\tList<Tab> removedTabs = new ArrayList<Tab>( );\r\n\t\t\r\n\t\twhile( !tabs.isEmpty( ) )\r\n\t\t{\r\n\t\t\tTabInfo info = tabs.get( 0 );\r\n\t\t\tremovedTabs.add( info.tab );\r\n\t\t\tremoveTabImmediatelyInternal( info.tab );\r\n\t\t}\r\n\t\t\r\n\t\tTabsClearedEvent event = new TabsClearedEvent( tabbedPane , time , Collections.unmodifiableList( removedTabs ) );\r\n\t\t\r\n\t\tnotifyTabbedPaneListeners( event );\r\n\t}\r\n\t\r\n\t/**\r\n\t * @return the selected tab, or {@code null} if no tab is selected.\r\n\t */\r\n\tpublic Tab getSelectedTab( )\r\n\t{\r\n\t\treturn selectedTab != null ? selectedTab.tab : null;\r\n\t}\r\n\t\r\n\tpublic void setSelectedTab( Tab tab )\r\n\t{\r\n\t\tint index = getInfoIndex( tab );\r\n\t\tif( index >= 0 )\r\n\t\t{\r\n\t\t\tindex = virtualizeIndex( index );\r\n\t\t}\r\n\t\tsetSelectedIndexInternal( index );\r\n\t}\r\n\t\r\n\tprivate void setSelectedIndexInternal( int vIndex )\r\n\t{\r\n\t\tif( vIndex < 0 )\r\n\t\t{\r\n\t\t\tsetSelectedTabInternal( ( TabInfo ) null );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsetSelectedTabInternal( tabs.get( actualizeIndex( vIndex ) ) );\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void setSelectedTabInternal( TabInfo info )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tif( selectedTab != info )\r\n\t\t{\r\n\t\t\tint prevIndex = selectedTab != null ? virtualizeIndex( tabs.indexOf( selectedTab ) ) : -1;\r\n\t\t\tint newIndex = info != null ? virtualizeIndex( tabs.indexOf( info ) ) : -1;\r\n\t\t\t\r\n\t\t\tTab prevTab = selectedTab != null ? selectedTab.tab : null;\r\n\t\t\tTab newTab = info != null ? info.tab : null;\r\n\t\t\t\r\n\t\t\tTabSelectedEvent event = new TabSelectedEvent( tabbedPane , System.currentTimeMillis( ) , prevTab , prevIndex , newTab , newIndex );\r\n\t\t\t\r\n\t\t\tif( selectedTab != null )\r\n\t\t\t{\r\n\t\t\t\tselectedTab.tab.setSelected( false );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tselectedTab = info;\r\n\t\t\t\r\n\t\t\tif( selectedTab != null )\r\n\t\t\t{\r\n\t\t\t\tselectedTab.tab.setSelected( true );\r\n\t\t\t\tsetContentInternal( selectedTab.tab.getContent( ) );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tsetContentInternal( null );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\ttabbedPane.invalidate( );\r\n\t\t\ttabbedPane.validate( );\r\n\t\t\t\r\n\t\t\tnotifyTabbedPaneListeners( event );\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void setContentInternal( Component newContent )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tif( currentContent != newContent )\r\n\t\t{\r\n\t\t\tif( currentContent != null && currentContent.getParent( ) == tabbedPane && currentContent.isVisible( ) )\r\n\t\t\t{\r\n\t\t\t\tcurrentContent.setVisible( false );\r\n\t\t\t}\r\n\t\t\tcurrentContent = newContent;\r\n\t\t\tif( newContent != null && !newContent.isVisible( ) )\r\n\t\t\t{\r\n\t\t\t\tnewContent.setVisible( true );\r\n\t\t\t}\r\n\t\t\tif( SwingUtilities.findFocusOwner( currentContent ) != null )\r\n\t\t\t{\r\n\t\t\t\tif( !requestFocusForVisibleComponent( ) )\r\n\t\t\t\t{\r\n\t\t\t\t\ttabbedPane.requestFocus( );\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 * Notifies this {@code TabbedPane} that a tab's content has changed. If that tab is selected, its old content will be removed from this {@code TabbedPane}\r\n\t * and replaced with the tab's new content.\r\n\t * \r\n\t * @param tab\r\n\t * the tab whose content has changed. If {@code tab} is not a member of this tabbed pane, this method has no effect.\r\n\t */\r\n\tpublic void tabContentChanged( Tab tab )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tTabInfo info = getInfo( tab );\r\n\t\tif( info == selectedTab )\r\n\t\t{\r\n\t\t\tsetContentInternal( tab.getContent( ) );\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Immediately updates the tabs' bounds to their eventual position where animation is complete.\r\n\t */\r\n\tpublic void finishAnimation( )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tlayout.finishAnimation = true;\r\n\t\ttabbedPane.invalidate( );\r\n\t\ttabbedPane.validate( );\r\n\t}\r\n\t\r\n\tpublic void waitForAnimationToFinish( ) throws InterruptedException\r\n\t{\r\n\t\tcheckNotEDT( );\r\n\t\t\r\n\t\tsynchronized( animLock )\r\n\t\t{\r\n\t\t\twhile( animTimer != null && animTimer.isRunning( ) )\r\n\t\t\t{\r\n\t\t\t\tanimLock.wait( );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void setDragState( Tab draggedTab , double grabX , int dragX )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tboolean validate = false;\r\n\t\t\r\n\t\tfor( TabInfo info : tabs )\r\n\t\t{\r\n\t\t\tif( info.tab == draggedTab )\r\n\t\t\t{\r\n\t\t\t\tif( !info.isBeingDragged || info.grabX != grabX || info.dragX != dragX )\r\n\t\t\t\t{\r\n\t\t\t\t\tinfo.isBeingDragged = true;\r\n\t\t\t\t\tinfo.grabX = grabX;\r\n\t\t\t\t\tinfo.dragX = dragX;\r\n\t\t\t\t\t\r\n\t\t\t\t\tvalidate = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif( info.isBeingDragged )\r\n\t\t\t\t{\r\n\t\t\t\t\tinfo.isBeingDragged = false;\r\n\t\t\t\t\tvalidate = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif( validate )\r\n\t\t{\r\n\t\t\ttabbedPane.invalidate( );\r\n\t\t\ttabbedPane.validate( );\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * @return the new tab button. This tabbed pane manages its appearance and action by default. You are free to modify it however you wish, but behavior is\r\n\t * undefined in this case so be careful.\r\n\t */\r\n\tpublic JButton getNewTabButton( )\r\n\t{\r\n\t\treturn newTabButton;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Removes all tabs, stops animation and attempts to unregister all listeners that could prevent this TabbedPane from being finalized. However, I am not yet\r\n\t * certain if this method eliminates all potential memory leaks (excluding references apart from internal TabbedPane code.\r\n\t */\r\n\tpublic void dispose( )\r\n\t{\r\n\t\tcheckEDT( );\r\n\t\t\r\n\t\tsynchronized( animLock )\r\n\t\t{\r\n\t\t\tanimTimer.stop( );\r\n\t\t\tanimLock.notifyAll( );\r\n\t\t}\r\n\t\t\r\n\t\tuninstallKeyboardActions( );\r\n\t\t\r\n\t\ttabbedPane.remove( tabLayeredPane );\r\n\t\tmouseOverManager.uninstall( tabbedPane );\r\n\t\tmouseOverManager.removeExcludedComponent( tabLayeredPane );\r\n\t\t\r\n\t\ttabbedPane.removeContainerListener( handler );\r\n\t\ttabbedPane.removeChangeListener( handler );\r\n\t\ttabbedPane.removePropertyChangeListener( handler );\r\n\t\ttabbedPane.removeFocusListener( handler );\r\n\t\t\r\n\t\ttry\r\n\t\t{\r\n\t\t\tremoveAllTabsInternal( );\r\n\t\t}\r\n\t\tcatch( Exception e )\r\n\t\t{\r\n\t\t\te.printStackTrace( );\r\n\t\t}\r\n\t\t\r\n\t\tdragHandler.dispose( );\r\n\t\ttabbedPane.setLayout( null );\r\n\t\ttabbedPane.setDropTarget( null );\r\n\t\t\r\n\t\tdragHandler = null;\r\n\t\thandler = null;\r\n\t\tmouseOverManager = null;\r\n\t\tlayout = null;\r\n\t\tsynchronized( animLock )\r\n\t\t{\r\n\t\t\tanimTimer = null;\r\n\t\t}\r\n\t\ttabLayeredPane = null;\r\n\t\ttabbedPane = null;\r\n\t}\r\n\t\r\n\tprivate int animate( int value , int target , double animFactor )\r\n\t{\r\n\t\tint d = value - target;\r\n\t\td *= animFactor;\r\n\t\treturn d == 0 ? target : target + d;\r\n\t}\r\n\t\r\n\tprivate int animate( int value , int target , double animFactor , BooleanHolder animNeeded )\r\n\t{\r\n\t\tint newValue = animate( value , target , animFactor );\r\n\t\tif( newValue != value )\r\n\t\t{\r\n\t\t\tanimNeeded.value = true;\r\n\t\t}\r\n\t\treturn newValue;\r\n\t}\r\n\t\r\n\tprivate int animateShrinkingOnly( int value , int target , double animFactor , BooleanHolder animNeeded )\r\n\t{\r\n\t\tint newValue = value < target ? target : animate( value , target , animFactor );\r\n\t\tif( newValue != value )\r\n\t\t{\r\n\t\t\tanimNeeded.value = true;\r\n\t\t}\r\n\t\treturn newValue;\r\n\t}\r\n\t\r\n\tprivate static final int\tMINIMUM\t\t= 0;\r\n\tprivate static final int\tPREFERRED\t= 1;\r\n\tprivate static final int\tMAXIMUM\t\t= 2;\r\n\t\r\n\tprivate class TabLayoutManager implements LayoutManager\r\n\t{\r\n\t\t/**\r\n\t\t * The sustained total width of the tab zone in virtual coordinate space. This does not include the overlap area of the last tab.\r\n\t\t */\r\n\t\tprivate int\t\tvSustainedTabZoneWidth\t= 0;\r\n\t\t\r\n\t\t/**\r\n\t\t * The current width scale.\r\n\t\t */\r\n\t\tprivate double\twidthScale\t\t\t\t= 1.0;\r\n\t\t\r\n\t\tprivate boolean\tfinishAnimation\t\t\t= false;\r\n\t\t\r\n\t\tprivate int getInsertIndex( Tab tab , double grabX , int dragX )\r\n\t\t{\r\n\t\t\tcheckEDT( );\r\n\t\t\t\r\n\t\t\tint targetWidth = useUniformWidth ? maxUniformWidth : tab.getPreferredSize( ).width;\r\n\t\t\ttargetWidth *= widthScale;\r\n\t\t\tint vX = dragX - ( int ) ( grabX * targetWidth );\r\n\t\t\tvX = ( int ) ( ( vX - tabZone.x ) / widthScale );\r\n\t\t\t\r\n\t\t\tint vIndex = 0;\r\n\t\t\t\r\n\t\t\tint vTargetX = 0;\r\n\t\t\t\r\n\t\t\tfor( int index = 0 ; index < tabs.size( ) ; index++ )\r\n\t\t\t{\r\n\t\t\t\tTabInfo info = tabs.get( index );\r\n\t\t\t\t\r\n\t\t\t\tif( info.tab == tab || info.isBeingRemoved )\r\n\t\t\t\t{\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif( vX < vTargetX + info.vTargetWidth / 2 )\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tvTargetX += info.vTargetWidth;\r\n\t\t\t\tvIndex++ ;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\treturn vIndex;\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void addLayoutComponent( String name , Component comp )\r\n\t\t{\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void removeLayoutComponent( Component comp )\r\n\t\t{\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic Dimension preferredLayoutSize( Container parent )\r\n\t\t{\r\n\t\t\treturn layoutSize( parent , PREFERRED );\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic Dimension minimumLayoutSize( Container parent )\r\n\t\t{\r\n\t\t\treturn layoutSize( parent , MINIMUM );\r\n\t\t}\r\n\t\t\r\n\t\tprivate Dimension layoutSize( Container parent , int sizeType )\r\n\t\t{\r\n\t\t\tboolean transpose = tabbedPane.getTabPlacement( ) == JTabbedPane.LEFT || tabbedPane.getTabPlacement( ) == JTabbedPane.RIGHT;\r\n\t\t\t\r\n\t\t\tint contentWidth = 0;\r\n\t\t\tint contentHeight = 0;\r\n\t\t\tfor( int i = 0 ; i < tabbedPane.getTabCount( ) ; i++ )\r\n\t\t\t{\r\n\t\t\t\tComponent content = tabbedPane.getComponentAt( i );\r\n\t\t\t\tDimension size = getSize( content , sizeType );\r\n\t\t\t\tcontentWidth = Math.max( contentWidth , size.width );\r\n\t\t\t\tcontentHeight = Math.max( contentHeight , size.height );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tint tabsHeight = 0;\r\n\t\t\t\r\n\t\t\tfor( TabInfo info : tabs )\r\n\t\t\t{\r\n\t\t\t\tinfo.prefSize = info.tab.getPreferredSize( );\r\n\t\t\t\ttabsHeight = Math.max( tabsHeight , transpose ? info.prefSize.width : info.prefSize.height );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tInsets insets = tabbedPane.getInsets( );\r\n\t\t\tint width = insets.left + insets.right + contentWidth;\r\n\t\t\tint height = insets.top + insets.bottom + contentHeight;\r\n\t\t\t\r\n\t\t\tif( transpose )\r\n\t\t\t{\r\n\t\t\t\twidth += tabsHeight;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\theight += tabsHeight;\r\n\t\t\t}\r\n\t\t\tif( contentPanelBorder != null )\r\n\t\t\t{\r\n\t\t\t\tInsets contentInsets = contentPanelBorder.getBorderInsets( tabbedPane );\r\n\t\t\t\twidth += contentInsets.left + contentInsets.right;\r\n\t\t\t\theight += contentInsets.top + contentInsets.bottom;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\treturn new Dimension( width , height );\r\n\t\t}\r\n\t\t\r\n\t\tprivate Dimension getSize( Component comp , int sizeType )\r\n\t\t{\r\n\t\t\tswitch( sizeType )\r\n\t\t\t{\r\n\t\t\t\tcase MINIMUM:\r\n\t\t\t\t\treturn comp.getMinimumSize( );\r\n\t\t\t\tcase PREFERRED:\r\n\t\t\t\t\treturn comp.getPreferredSize( );\r\n\t\t\t\tcase MAXIMUM:\r\n\t\t\t\t\treturn comp.getMaximumSize( );\r\n\t\t\t\tdefault:\r\n\t\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void layoutContainer( Container parent )\r\n\t\t{\r\n\t\t\tcheckEDT( );\r\n\t\t\t\r\n\t\t\tboolean reset = finishAnimation;\r\n\t\t\tfinishAnimation = false;\r\n\t\t\t\r\n\t\t\tdouble animFactor = reset ? 0.0 : JhromeTabbedPaneUI.this.animFactor;\r\n\t\t\t\r\n\t\t\tboolean transpose = tabbedPane.getTabPlacement( ) == JTabbedPane.LEFT || tabbedPane.getTabPlacement( ) == JTabbedPane.RIGHT;\r\n\t\t\t\r\n\t\t\tint parentWidth = parent.getWidth( );\r\n\t\t\tint parentHeight = parent.getHeight( );\r\n\t\t\t\r\n\t\t\tInsets insets = parent.getInsets( );\r\n\t\t\t\r\n\t\t\tDimension rightButtonsPanelPrefSize = rightButtonsPanel.getPreferredSize( );\r\n\t\t\t\r\n\t\t\tint availWidth = parentWidth - insets.left - insets.right;\r\n\t\t\tint availHeight = parentHeight - insets.top - insets.bottom;\r\n\t\t\tint availTopZoneWidth = ( transpose ? availHeight : availWidth ) - tabMargin * 2;\r\n\t\t\tint availTabZoneWidth = availTopZoneWidth - rightButtonsPanelPrefSize.width;\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Whether another animation step is needed after this one.\r\n\t\t\t */\r\n\t\t\tBooleanHolder animNeeded = new BooleanHolder( false );\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * The target x position of the next tab, in virtual coordinate space.\r\n\t\t\t */\r\n\t\t\tint vTargetX = 0;\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * The target width of the tab zone, which is the total target width of all tabs, except those being removed, in virtual coordinate space. This does\r\n\t\t\t * not include the overlap area of the last tab.\r\n\t\t\t */\r\n\t\t\tint vTargetTabZoneWidth = 0;\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * The current width of the tab zone, which is the total current width of all tabs, including those being removed, in virtual coordinate space. This\r\n\t\t\t * does not include the overlap area of the last tab.\r\n\t\t\t */\r\n\t\t\tint vCurrentTabZoneWidth = 0;\r\n\t\t\t\r\n\t\t\tint targetTabHeight = rightButtonsPanelPrefSize.height;\r\n\t\t\t\r\n\t\t\tboolean anyDragging = false;\r\n\t\t\t\r\n\t\t\tfor( int i = 0 ; i < tabs.size( ) ; i++ )\r\n\t\t\t{\r\n\t\t\t\tTabInfo info = tabs.get( i );\r\n\t\t\t\tinfo.vTargetX = vTargetX;\r\n\t\t\t\t\r\n\t\t\t\tinfo.prefSize = info.tab.getPreferredSize( );\r\n\t\t\t\t\r\n\t\t\t\tinfo.vTargetWidth = info.isBeingRemoved ? 0 : Math.max( 0 , useUniformWidth ? maxUniformWidth - overlap : info.prefSize.width - overlap );\r\n\t\t\t\t\r\n\t\t\t\t// animate the tab x position\r\n\t\t\t\tinfo.vCurrentX = animate( info.vCurrentX , vTargetX , animFactor , animNeeded );\r\n\t\t\t\t\r\n\t\t\t\t// animate the tab width\r\n\t\t\t\tinfo.vCurrentWidth = animate( info.vCurrentWidth , info.vTargetWidth , animFactor , animNeeded );\r\n\t\t\t\t\r\n\t\t\t\tif( info.isBeingDragged )\r\n\t\t\t\t{\r\n\t\t\t\t\tanyDragging = true;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif( !info.isBeingRemoved )\r\n\t\t\t\t{\r\n\t\t\t\t\tvTargetX += info.vTargetWidth;\r\n\t\t\t\t\tvTargetTabZoneWidth += info.vTargetWidth;\r\n\t\t\t\t\ttargetTabHeight = Math.max( targetTabHeight , info.prefSize.height );\r\n\t\t\t\t}\r\n\t\t\t\tvCurrentTabZoneWidth += info.vCurrentWidth;\r\n\t\t\t\t\r\n\t\t\t\tinfo.tab.getContent( ).setVisible( tabbedPane.getSelectedIndex( ) == virtualizeIndex( i ) );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tTabInfo lastInfo = tabs.isEmpty( ) ? null : tabs.get( tabs.size( ) - 1 );\r\n\t\t\t/**\r\n\t\t\t * The target x position for the right buttons panel, in virtual coordinate space. The logic for this is tricky.\r\n\t\t\t */\r\n\t\t\tint vTargetRightButtonsPanelX = lastInfo != null ? lastInfo.vCurrentX == lastInfo.vTargetX ? lastInfo.vCurrentX + lastInfo.vCurrentWidth : lastInfo.vTargetX + lastInfo.vCurrentWidth : 0;\r\n\t\t\t\r\n\t\t\t// Animate the tab zone (virtual) width.\r\n\t\t\t// if the sustained tab zone width must increase to reach the current, do it immediately, without animation; if it must shrink to reach the target,\r\n\t\t\t// do it with animation,\r\n\t\t\t// but only if the mouse is not over the top zone.\r\n\t\t\tif( reset || vCurrentTabZoneWidth > vSustainedTabZoneWidth )\r\n\t\t\t{\r\n\t\t\t\tvSustainedTabZoneWidth = vCurrentTabZoneWidth;\r\n\t\t\t}\r\n\t\t\telse if( !mouseOverTopZone && !anyDragging && vSustainedTabZoneWidth > vTargetTabZoneWidth )\r\n\t\t\t{\r\n\t\t\t\tanimNeeded.value = true;\r\n\t\t\t\tvSustainedTabZoneWidth = animate( vSustainedTabZoneWidth , vTargetTabZoneWidth , animFactor );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// Compute necessary width scale to fit all tabs on screen\r\n\t\t\twidthScale = vSustainedTabZoneWidth > availTabZoneWidth - overlap ? ( availTabZoneWidth - overlap ) / ( double ) vSustainedTabZoneWidth : 1.0;\r\n\t\t\t\r\n\t\t\t// Adjust width scale as necessary so that no tab (except those being removed) is narrower than its minimum width\r\n\t\t\tdouble adjWidthScale = widthScale;\r\n\t\t\tfor( int i = 0 ; i < tabs.size( ) ; i++ )\r\n\t\t\t{\r\n\t\t\t\tTabInfo info = tabs.get( i );\r\n\t\t\t\tif( info.isBeingRemoved )\r\n\t\t\t\t{\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tDimension minSize = info.tab.getMinimumSize( );\r\n\t\t\t\tif( minSize != null && info.vCurrentWidth >= minSize.width )\r\n\t\t\t\t{\r\n\t\t\t\t\tint prefWidth = transpose ? info.prefSize.height : info.prefSize.width;\r\n\t\t\t\t\tint targetWidth = useUniformWidth ? maxUniformWidth : prefWidth;\r\n\t\t\t\t\tadjWidthScale = Math.max( adjWidthScale , minSize.width / ( double ) targetWidth );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\twidthScale = adjWidthScale;\r\n\t\t\t\r\n\t\t\tint currentTabHeight = transpose ? tabZone.width : tabZone.height;\r\n\t\t\tint newTabHeight = targetTabHeight;\r\n\t\t\tif( currentTabHeight > 0 )\r\n\t\t\t{\r\n\t\t\t\tnewTabHeight = animate( currentTabHeight , targetTabHeight , animFactor , animNeeded );\r\n\t\t\t}\r\n\t\t\tif( transpose )\r\n\t\t\t{\r\n\t\t\t\ttopZone.setFrame( insets.left , insets.top + tabMargin , newTabHeight , availTopZoneWidth );\r\n\t\t\t\ttabZone.setFrame( insets.left , insets.top + tabMargin , topZone.height , availTabZoneWidth );\r\n\t\t\t\tdropZone.setFrame( insets.left , insets.top + tabMargin , Math.min( availWidth , currentTabHeight + extraDropZoneSpace ) , availTopZoneWidth );\r\n\t\t\t\t\r\n\t\t\t\tif( tabbedPane.getTabPlacement( ) == JTabbedPane.RIGHT )\r\n\t\t\t\t{\r\n\t\t\t\t\ttopZone.x = insets.left + availWidth - topZone.width - 1;\r\n\t\t\t\t\ttabZone.x = insets.left + availWidth - tabZone.width - 1;\r\n\t\t\t\t\tdropZone.x = insets.left + availWidth - dropZone.width - 1;\r\n\t\t\t\t\ttabLayeredPane.setBounds( tabZone.x , 0 , tabZone.width + insets.right , tabbedPane.getHeight( ) );\r\n\t\t\t\t\tcontentPanelBounds.setBounds( insets.left , insets.top , availWidth - tabZone.width + contentPanelOverlap , availHeight );\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\ttabLayeredPane.setBounds( 0 , 0 , tabZone.width + insets.left , tabbedPane.getHeight( ) );\r\n\t\t\t\t\tcontentPanelBounds.setBounds( tabZone.x + tabZone.width - contentPanelOverlap , insets.top , availWidth - tabZone.width + contentPanelOverlap , availHeight );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttopZone.setFrame( insets.left + tabMargin , insets.top , availTopZoneWidth , newTabHeight );\r\n\t\t\t\ttabZone.setFrame( insets.left + tabMargin , insets.top , availTabZoneWidth , topZone.height );\r\n\t\t\t\tdropZone.setFrame( insets.left + tabMargin , insets.top , availTopZoneWidth , Math.min( availHeight , tabZone.height + extraDropZoneSpace ) );\r\n\t\t\t\t\r\n\t\t\t\tif( tabbedPane.getTabPlacement( ) == JTabbedPane.BOTTOM )\r\n\t\t\t\t{\r\n\t\t\t\t\ttopZone.y = insets.top + availHeight - topZone.height - 1;\r\n\t\t\t\t\ttabZone.y = insets.top + availHeight - tabZone.height - 1;\r\n\t\t\t\t\tdropZone.y = insets.top + availHeight - dropZone.height - 1;\r\n\t\t\t\t\ttabLayeredPane.setBounds( 0 , tabZone.y , tabbedPane.getWidth( ) , tabZone.height + insets.bottom );\r\n\t\t\t\t\tcontentPanelBounds.setBounds( insets.left , insets.top , availWidth , availHeight - tabZone.height + contentPanelOverlap );\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\ttabLayeredPane.setBounds( 0 , 0 , tabbedPane.getWidth( ) , tabZone.height + insets.top );\r\n\t\t\t\t\tcontentPanelBounds.setBounds( insets.left , tabZone.y + tabZone.height - contentPanelOverlap , availWidth , availHeight - tabZone.height + contentPanelOverlap );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tint tabZoneX = transpose ? tabZone.y : tabZone.x;\r\n\t\t\tint topZoneX = transpose ? topZone.y : topZone.x;\r\n\t\t\tint topZoneY = transpose ? topZone.x : topZone.y;\r\n\t\t\tint topZoneWidth = transpose ? topZone.height : topZone.width;\r\n\t\t\tint topZoneHeight = transpose ? topZone.width : topZone.height;\r\n\t\t\tint tabZoneHeight = transpose ? tabZone.width : tabZone.height;\r\n\t\t\tint tabLayeredPaneY = transpose ? tabLayeredPane.getX( ) : tabLayeredPane.getY( );\r\n\t\t\t\r\n\t\t\t// now, lay out the tabs\r\n\t\t\tfor( int i = 0 ; i < tabs.size( ) ; i++ )\r\n\t\t\t{\r\n\t\t\t\tTabInfo info = tabs.get( i );\r\n\t\t\t\t\r\n\t\t\t\tint x = topZoneX + ( int ) ( info.vCurrentX * widthScale );\r\n\t\t\t\tint targetX = topZoneX + ( int ) ( info.vTargetX * widthScale );\r\n\t\t\t\tint width = ( int ) ( info.vCurrentWidth * widthScale ) + overlap;\r\n\t\t\t\tint targetWidth = ( int ) ( info.vTargetWidth * widthScale ) + overlap;\r\n\t\t\t\t\r\n\t\t\t\tif( info.isBeingDragged )\r\n\t\t\t\t{\r\n\t\t\t\t\tx = info.dragX - ( int ) ( info.grabX * width );\r\n\t\t\t\t\t// if( i == tabs.size( ) - 1 && x > targetX )\r\n\t\t\t\t\t// {\r\n\t\t\t\t\t// x = x / 2 + targetX / 2;\r\n\t\t\t\t\t// }\r\n\t\t\t\t\tx = Math.max( topZoneX , Math.min( topZoneX + topZoneWidth - width , x ) );\r\n\t\t\t\t\tinfo.vCurrentX = ( int ) ( ( x - topZoneX ) / widthScale );\r\n\t\t\t\t}\r\n\t\t\t\tinfo.tab.setBounds( x , topZoneY - tabLayeredPaneY , width , tabZoneHeight );\r\n\t\t\t\tinfo.targetBounds.setFrame( targetX , topZoneY , targetWidth , tabZoneHeight );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// lay out the content panel and right button panel\r\n\t\t\tInsets contentInsets = contentPanelBorder == null ? new Insets( 0 , 0 , 0 , 0 ) : contentPanelBorder.getBorderInsets( tabbedPane );\r\n\t\t\t\r\n\t\t\tint contentX = contentPanelBounds.x + contentInsets.left;\r\n\t\t\tint contentW = contentPanelBounds.width - contentInsets.left - contentInsets.right;\r\n\t\t\tint contentY = contentPanelBounds.y + contentInsets.top;\r\n\t\t\tint contentH = contentPanelBounds.height - contentInsets.top - contentInsets.bottom;\r\n\t\t\t\r\n\t\t\tfor( Component comp : tabbedPane.getComponents( ) )\r\n\t\t\t{\r\n\t\t\t\tif( comp != tabLayeredPane )\r\n\t\t\t\t{\r\n\t\t\t\t\tcomp.setBounds( contentX , contentY , contentW , contentH );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// animate the right buttons panel x position. If it must increase to reach the target, do it immediately, without animation;\r\n\t\t\t// If it must decrease, do it with animation.\r\n\t\t\tint vCurrentRightButtonsPanelX = ( int ) ( ( rightButtonsPanel.getX( ) - overlap / 2 - tabZoneX ) / widthScale );\r\n\t\t\tvCurrentRightButtonsPanelX = animateShrinkingOnly( vCurrentRightButtonsPanelX , vTargetRightButtonsPanelX , animFactor , animNeeded );\r\n\t\t\tint rightButtonsPanelX = tabZoneX + ( int ) ( vCurrentRightButtonsPanelX * widthScale ) + overlap / 2;\r\n\t\t\t\r\n\t\t\t// keep right buttons panel from getting pushed off the edge of the tabbed pane when minimum tab width is reached\r\n\t\t\trightButtonsPanelX = Math.min( rightButtonsPanelX , topZoneX + topZoneWidth - rightButtonsPanelPrefSize.width );\r\n\t\t\trightButtonsPanel.setBounds( rightButtonsPanelX , topZoneY - tabLayeredPaneY , rightButtonsPanelPrefSize.width , topZoneHeight );\r\n\t\t\t\r\n\t\t\tfor( int i = tabs.size( ) - 1 ; i >= 0 ; i-- )\r\n\t\t\t{\r\n\t\t\t\tTabInfo info = tabs.get( i );\r\n\t\t\t\tif( info.isBeingRemoved && info.vCurrentWidth == 0 )\r\n\t\t\t\t{\r\n\t\t\t\t\tactuallyRemoveTab( info.tab );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tint layer = JLayeredPane.DEFAULT_LAYER;\r\n\t\t\t\r\n\t\t\ttabLayeredPane.setComponentZOrder( rightButtonsPanel , layer++ );\r\n\t\t\t\r\n\t\t\tif( selectedTab != null )\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\ttabLayeredPane.setComponentZOrder( selectedTab.tab , layer++ );\r\n\t\t\t\t}\r\n\t\t\t\tcatch( Exception ex )\r\n\t\t\t\t{\r\n\t\t\t\t\tex.printStackTrace( );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// setComponentZOrder( contentPanel , layer++ );\r\n\t\t\t\r\n\t\t\tfor( TabInfo info : tabs )\r\n\t\t\t{\r\n\t\t\t\tif( info == selectedTab )\r\n\t\t\t\t{\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\ttabLayeredPane.setComponentZOrder( info.tab , layer++ );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\ttabLayeredPane.repaint( );\r\n\t\t\t\r\n\t\t\tsynchronized( animLock )\r\n\t\t\t{\r\n\t\t\t\tif( animTimer != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tif( animNeeded.value )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tanimTimer.start( );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tanimTimer.stop( );\r\n\t\t\t\t\t}\r\n\t\t\t\t\tanimLock.notifyAll( );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate class DragHandler implements DragSourceListener , DragSourceMotionListener , DragGestureListener\r\n\t{\r\n\t\tDragSource\t\t\t\tsource;\r\n\t\t\r\n\t\tDragGestureRecognizer\tdragGestureRecognizer;\r\n\t\t\r\n\t\tPoint\t\t\t\t\tdragOrigin;\r\n\t\t\r\n\t\tTabDragInfo\t\t\t\tdragInfo;\r\n\t\t\r\n\t\tpublic DragHandler( Component comp , int actions )\r\n\t\t{\r\n\t\t\tsource = new DragSource( );\r\n\t\t\tdragGestureRecognizer = source.createDefaultDragGestureRecognizer( comp , actions , this );\r\n\t\t\tsource.addDragSourceMotionListener( this );\r\n\t\t}\r\n\t\t\r\n\t\tpublic void dispose( )\r\n\t\t{\r\n\t\t\tsource.removeDragSourceListener( this );\r\n\t\t\tsource.removeDragSourceMotionListener( this );\r\n\t\t\tdragGestureRecognizer.removeDragGestureListener( this );\r\n\t\t\tdragGestureRecognizer.setComponent( null );\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dragGestureRecognized( DragGestureEvent dge )\r\n\t\t{\r\n\t\t\tif( !tabbedPane.isEnabled( ) )\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tdragOrigin = dge.getDragOrigin( );\r\n\t\t\t\r\n\t\t\tTab draggedTab = getDraggableTabAt( dragOrigin );\r\n\t\t\tif( draggedTab != null )\r\n\t\t\t{\r\n\t\t\t\tWindow window = SwingUtilities.getWindowAncestor( tabbedPane );\r\n\t\t\t\tDimension sourceWindowSize = null;\r\n\t\t\t\tif( window != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tsourceWindowSize = window.getSize( );\r\n\t\t\t\t}\r\n\t\t\t\tPoint p = SwingUtilities.convertPoint( tabbedPane , dragOrigin , draggedTab );\r\n\t\t\t\tdouble grabX = p.x / ( double ) draggedTab.getWidth( );\r\n\t\t\t\t\r\n\t\t\t\tdragInfo = new TabDragInfo( draggedTab , dragOrigin , grabX , floatingTabHandler , sourceWindowSize );\r\n\t\t\t\tsource.startDrag( dge , Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) , transferableStore.createTransferable( dragInfo ) , this );\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dragEnter( DragSourceDragEvent dsde )\r\n\t\t{\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dragExit( DragSourceEvent dse )\r\n\t\t{\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dragOver( DragSourceDragEvent dsde )\r\n\t\t{\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dragMouseMoved( DragSourceDragEvent dsde )\r\n\t\t{\r\n\t\t\tif( dragInfo != null )\r\n\t\t\t{\r\n\t\t\t\tJhromeTabbedPaneUI draggedParent = SwingUtils.getJTabbedPaneAncestorUI( dragInfo.tab );\r\n\t\t\t\tif( draggedParent != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tPoint p = dsde.getLocation( );\r\n\t\t\t\t\tSwingUtilities.convertPointFromScreen( p , draggedParent.tabbedPane );\r\n\t\t\t\t\tif( !Utils.contains( draggedParent.dropZone , p ) )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdragOut( dsde.getDragSourceContext( ).getComponent( ) , dragInfo );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif( dragInfo.floatingTabHandler != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tdragInfo.floatingTabHandler.onFloatingTabDragged( dsde , dragInfo.tab , dragInfo.grabX );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dropActionChanged( DragSourceDragEvent dsde )\r\n\t\t{\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dragDropEnd( final DragSourceDropEvent dsde )\r\n\t\t{\r\n\t\t\tif( dragInfo != null )\r\n\t\t\t{\r\n\t\t\t\tif( dragInfo.floatingTabHandler != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tdragInfo.floatingTabHandler.onFloatingEnd( );\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tJhromeTabbedPaneUI draggedParent = SwingUtils.getJTabbedPaneAncestorUI( dragInfo.tab );\r\n\t\t\t\t\r\n\t\t\t\tif( dragInfo.tab != null && draggedParent == null && tabDropFailureHandler != null )\r\n\t\t\t\t{\r\n\t\t\t\t\ttabDropFailureHandler.onDropFailure( dsde , dragInfo.tab , dragInfo.sourceWindowSize );\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif( draggedParent != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tdraggedParent.setDragState( null , 0 , 0 );\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// for( final Window window : dragInfo.deadWindows )\r\n\t\t\t\t// {\r\n\t\t\t\t// SwingUtilities.invokeLater( new Runnable( )\r\n\t\t\t\t// {\r\n\t\t\t\t// @Override\r\n\t\t\t\t// public void run( )\r\n\t\t\t\t// {\r\n\t\t\t\t// window.dispose( );\r\n\t\t\t\t// }\r\n\t\t\t\t// } );\r\n\t\t\t\t// }\r\n\t\t\t\t\r\n\t\t\t\tdragInfo = null;\r\n\t\t\t}\r\n\t\t\ttransferableStore.cleanUp( dsde.getDragSourceContext( ).getTransferable( ) );\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate class DropHandler implements DropTargetListener\r\n\t{\r\n\t\tprivate TabDragInfo\tdragInfo\t= null;\r\n\t\t\r\n\t\tpublic DropHandler( Component comp )\r\n\t\t{\r\n\t\t\tnew DropTarget( comp , this );\r\n\t\t}\r\n\t\t\r\n\t\tprivate void handleDrag( DropTargetDragEvent dtde )\r\n\t\t{\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dragEnter( DropTargetDragEvent dtde )\r\n\t\t{\r\n\t\t\tdragInfo = getDragInfo( dtde.getTransferable( ) );\r\n\t\t\thandleDrag( dtde );\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dragOver( DropTargetDragEvent dtde )\r\n\t\t{\r\n\t\t\thandleDrag( dtde );\r\n\t\t\tJhromeTabbedPaneUI.this.dragOver( dtde );\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dragExit( DropTargetEvent dte )\r\n\t\t{\r\n\t\t\tdragOut( dte.getDropTargetContext( ).getComponent( ) , dragInfo );\r\n\t\t\tdragInfo = null;\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void dropActionChanged( DropTargetDragEvent dtde )\r\n\t\t{\r\n\t\t\thandleDrag( dtde );\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void drop( DropTargetDropEvent dtde )\r\n\t\t{\r\n\t\t\tsetDragState( null , 0 , 0 );\r\n\t\t\t\r\n\t\t\tTabDragInfo dragInfo = getDragInfo( dtde.getTransferable( ) );\r\n\t\t\tif( dragInfo != null )\r\n\t\t\t{\r\n\t\t\t\tif( dragInfo.tab != null && Utils.contains( dropZone , dtde.getLocation( ) ) && isSnapInAllowed( dragInfo.tab ) )\r\n\t\t\t\t{\r\n\t\t\t\t\tdtde.acceptDrop( dtde.getDropAction( ) );\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tdtde.rejectDrop( );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tdtde.rejectDrop( );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tdtde.dropComplete( true );\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate TabDragInfo getDragInfo( Transferable t )\r\n\t{\r\n\t\tObject it = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tit = transferableStore.getTransferableData( t );\r\n\t\t}\r\n\t\tcatch( UnsupportedFlavorException e )\r\n\t\t{\r\n\t\t\tlog( e );\r\n\t\t}\r\n\t\tcatch( IOException e )\r\n\t\t{\r\n\t\t\tlog( e );\r\n\t\t}\r\n\t\tif( it instanceof TabDragInfo )\r\n\t\t{\r\n\t\t\treturn ( TabDragInfo ) it;\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tprivate boolean isTearAwayAllowed( Tab tab )\r\n\t{\r\n\t\treturn tabbedPane.isEnabled( ) && dndPolicy != null && dndPolicy.isTearAwayAllowed( tabbedPane , tab );\r\n\t}\r\n\t\r\n\tprivate boolean isSnapInAllowed( Tab tab )\r\n\t{\r\n\t\treturn tabbedPane.isEnabled( ) && dndPolicy != null && dndPolicy.isSnapInAllowed( tabbedPane , tab );\r\n\t}\r\n\t\r\n\tprivate void dragOut( Component dragComponent , TabDragInfo dragInfo )\r\n\t{\r\n\t\tif( dragInfo != null )\r\n\t\t{\r\n\t\t\tJhromeTabbedPaneUI draggedParent = SwingUtils.getJTabbedPaneAncestorUI( dragInfo.tab );\r\n\t\t\tif( draggedParent != null && dragComponent == draggedParent.tabbedPane && draggedParent.isTearAwayAllowed( dragInfo.tab ) )\r\n\t\t\t{\r\n\t\t\t\tif( dragInfo.floatingTabHandler != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tdragInfo.floatingTabHandler.onFloatingBegin( dragInfo.tab , dragInfo.getGrabPoint( ) );\r\n\t\t\t\t}\r\n\t\t\t\tremoveDraggedTabFromParent( dragInfo );\r\n\t\t\t\t// draggedParent.mouseOverTopZone = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void removeDraggedTabFromParent( TabDragInfo dragInfo )\r\n\t{\r\n\t\tJhromeTabbedPaneUI draggedParent = SwingUtils.getJTabbedPaneAncestorUI( dragInfo.tab );\r\n\t\tif( draggedParent != null )\r\n\t\t{\r\n\t\t\tdraggedParent.setDragState( null , 0 , 0 );\r\n\t\t\tComponent draggedTabComponent = dragInfo.tab.getTabComponent( );\r\n\t\t\tdraggedParent.removeTabImmediatelyInternal( dragInfo.tab );\r\n\t\t\tint tabIndex = draggedParent.tabbedPane.indexOfComponent( dragInfo.tab.getContent( ) );\r\n\t\t\tif( tabIndex < 0 )\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tdraggedParent.tabbedPane.removeTabAt( tabIndex );\r\n\t\t\tdragInfo.tab.setTabComponent( draggedTabComponent );\r\n\t\t\t// if( draggedParent.getTabCount( ) == 0 )\r\n\t\t\t// {\r\n\t\t\t// Window window = SwingUtilities.getWindowAncestor( draggedParent.tabbedPane );\r\n\t\t\t// window.setVisible( false );\r\n\t\t\t// dragInfo.deadWindows.add( window );\r\n\t\t\t// }\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void dragOver( DropTargetDragEvent dtde )\r\n\t{\r\n\t\tTabDragInfo dragInfo = getDragInfo( dtde.getTransferable( ) );\r\n\t\tif( dragInfo != null )\r\n\t\t{\r\n\t\t\tJhromeTabbedPaneUI tabbedPaneUI = SwingUtils.getJTabbedPaneAncestorUI( dtde.getDropTargetContext( ).getComponent( ) );\r\n\t\t\t\r\n\t\t\tPoint p = dtde.getLocation( );\r\n\t\t\tdragInfo.setGrabPoint( SwingUtilities.convertPoint( dtde.getDropTargetContext( ).getComponent( ) , p , tabbedPaneUI.tabbedPane ) );\r\n\t\t\t\r\n\t\t\tif( !Utils.contains( tabbedPaneUI.dropZone , p ) )\r\n\t\t\t{\r\n\t\t\t\tdragOut( dtde.getDropTargetContext( ).getComponent( ) , dragInfo );\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tJhromeTabbedPaneUI sourceUI = SwingUtils.getJTabbedPaneAncestorUI( dragInfo.tab );\r\n\t\t\t\r\n\t\t\tif( sourceUI != tabbedPaneUI && ( sourceUI == null || sourceUI.isTearAwayAllowed( dragInfo.tab ) ) && tabbedPaneUI.isSnapInAllowed( dragInfo.tab ) )\r\n\t\t\t{\r\n\t\t\t\tif( dragInfo.floatingTabHandler != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tdragInfo.floatingTabHandler.onFloatingEnd( );\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif( sourceUI != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tremoveDraggedTabFromParent( dragInfo );\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tsourceUI = tabbedPaneUI;\r\n\t\t\t\t\r\n\t\t\t\t// tabbedPane.mouseOverTopZone = true;\r\n\t\t\t\t\r\n\t\t\t\tWindow ancestor = SwingUtilities.getWindowAncestor( tabbedPaneUI.tabbedPane );\r\n\t\t\t\tif( ancestor != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tancestor.toFront( );\r\n\t\t\t\t\tancestor.requestFocus( );\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tint dragX = dtde.getLocation( ).x;\r\n\t\t\t\t\r\n\t\t\t\tint newIndex = tabbedPaneUI.layout.getInsertIndex( dragInfo.tab , dragInfo.grabX , dragX );\r\n\t\t\t\ttabbedPaneUI.addTab( newIndex , dragInfo.tab , false );\r\n\t\t\t\tif( dragInfo.tab.isEnabled( ) )\r\n\t\t\t\t{\r\n\t\t\t\t\ttabbedPaneUI.tabbedPane.setSelectedIndex( newIndex );\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\ttabbedPaneUI.setDragState( dragInfo.tab , dragInfo.grabX , dragX );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tTabInfo info = tabbedPaneUI.getInfo( dragInfo.tab );\r\n\t\t\t\tif( info != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tint dragX = dtde.getLocation( ).x;\r\n\t\t\t\t\ttabbedPaneUI.setDragState( dragInfo.tab , dragInfo.grabX , dragX );\r\n\t\t\t\t\t\r\n\t\t\t\t\tint newIndex = tabbedPaneUI.layout.getInsertIndex( dragInfo.tab , dragInfo.grabX , dragX );\r\n\t\t\t\t\tint currentIndex = tabbedPaneUI.getInfoIndex( dragInfo.tab );\r\n\t\t\t\t\ttabbedPaneUI.moveTab( currentIndex , newIndex );\r\n\t\t\t\t\tif( dragInfo.tab.isEnabled( ) )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttabbedPaneUI.tabbedPane.setSelectedComponent( dragInfo.tab.getContent( ) );\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}\r\n\t\r\n\tpublic Image createDragImage( Tab tab )\r\n\t{\r\n\t\tComponent rend = tab;\r\n\t\t\r\n\t\t// int width = rend.getWidth( );\r\n\t\t// int height = rend.getHeight( );\r\n\t\t\r\n\t\tint width = tabbedPane.getWidth( );\r\n\t\tint height = tabbedPane.getHeight( );\r\n\t\t\r\n\t\tif( width == 0 || height == 0 )\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\t\r\n\t\tBufferedImage image = new BufferedImage( width , height , BufferedImage.TYPE_INT_ARGB );\r\n\t\t\r\n\t\tGraphics2D g2 = ( Graphics2D ) image.getGraphics( );\r\n\t\t\r\n\t\tAffineTransform origXform = g2.getTransform( );\r\n\t\t\r\n\t\tif( contentPanelBorder != null )\r\n\t\t{\r\n\t\t\tcontentPanelBorder.paintBorder( tabbedPane , g2 , contentPanelBounds.x , contentPanelBounds.y , contentPanelBounds.width , contentPanelBounds.height );\r\n\t\t}\r\n\t\tif( tab.getContent( ) != null )\r\n\t\t{\r\n\t\t\tInsets contentInsets = contentPanelBorder == null ? new Insets( 0 , 0 , 0 , 0 ) : contentPanelBorder.getBorderInsets( tabbedPane );\r\n\t\t\tg2.translate( contentPanelBounds.x + contentInsets.left , contentPanelBounds.y + contentInsets.top );\r\n\t\t\ttab.getContent( ).paint( g2 );\r\n\t\t}\r\n\t\t\r\n\t\tg2.setTransform( origXform );\r\n\t\t\r\n\t\tint tabX = tabLayeredPane.getX( ) + tab.getX( );\r\n\t\tint tabY = tabLayeredPane.getY( ) + tab.getY( );\r\n\t\t\r\n\t\tg2.translate( tabX , tabY );\r\n\t\trend.paint( g2 );\r\n\t\t\r\n\t\tBufferedImage rescaled = new BufferedImage( width * 3 / 4 , height * 3 / 4 , BufferedImage.TYPE_INT_ARGB );\r\n\t\t\r\n\t\tg2 = ( Graphics2D ) rescaled.getGraphics( );\r\n\t\tg2.setRenderingHint( RenderingHints.KEY_INTERPOLATION , RenderingHints.VALUE_INTERPOLATION_BICUBIC );\r\n\t\tg2.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER , .5f ) );\r\n\t\t\r\n\t\tg2.drawImage( image , 0 , 0 , rescaled.getWidth( ) , rescaled.getHeight( ) , 0 , 0 , width , height , null );\r\n\t\t\r\n\t\treturn rescaled;\r\n\t}\r\n\t\r\n\tprivate static void checkEDT( )\r\n\t{\r\n\t\tif( !SwingUtilities.isEventDispatchThread( ) )\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException( \"Must be called on the AWT Event Dispatch Thread!\" );\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate static void checkNotEDT( )\r\n\t{\r\n\t\tif( SwingUtilities.isEventDispatchThread( ) )\r\n\t\t{\r\n\t\t\tthrow new IllegalArgumentException( \"Must not be called on the AWT Event Dispatch Thread!\" );\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void notifyTabbedPaneListeners( TabbedPaneEvent event )\r\n\t{\r\n\t\tfor( ITabbedPaneListener listener : tabListeners )\r\n\t\t{\r\n\t\t\tlistener.onEvent( event );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void addTabbedPaneListener( ITabbedPaneListener listener )\r\n\t{\r\n\t\ttabListeners.add( listener );\r\n\t}\r\n\t\r\n\tpublic void removeTabbedPaneListener( ITabbedPaneListener listener )\r\n\t{\r\n\t\ttabListeners.remove( listener );\r\n\t}\r\n\t\r\n\tpublic void setAnimationFactor( double factor )\r\n\t{\r\n\t\tanimFactor = factor;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void paint( Graphics g , JComponent c )\r\n\t{\r\n\t\tif( contentPanelBorder != null )\r\n\t\t{\r\n\t\t\tcontentPanelBorder.paintBorder( c , g , contentPanelBounds.x , contentPanelBounds.y , contentPanelBounds.width , contentPanelBounds.height );\r\n\t\t}\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void update( Graphics g , JComponent c )\r\n\t{\r\n\t\tupdateTabs( );\r\n\t\tsuper.update( g , c );\r\n\t\t\r\n\t\tsynchronized( updateLock )\r\n\t\t{\r\n\t\t\tupdateLock.notifyAll( );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void waitForUpdate( long timeout ) throws TimeoutException , InterruptedException\r\n\t{\r\n\t\tcheckNotEDT( );\r\n\t\t\r\n\t\tsynchronized( updateLock )\r\n\t\t{\r\n\t\t\tupdateLock.wait( timeout );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic int tabForCoordinate( JTabbedPane pane , int x , int y )\r\n\t{\r\n\t\tTab tab = getHoverableTabAt( new Point( x , y ) );\r\n\t\treturn virtualizeIndex( getInfoIndex( tab ) );\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic Rectangle getTabBounds( JTabbedPane pane , int vIndex )\r\n\t{\r\n\t\tTabInfo info = tabs.get( actualizeIndex( vIndex ) );\r\n\t\treturn info != null ? info.tab.getBounds( ) : null;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic int getTabRunCount( JTabbedPane pane )\r\n\t{\r\n\t\treturn 1;\r\n\t}\r\n\t\r\n\tprivate void updateTabs( )\r\n\t{\r\n\t\tList<Tab> toRemove = new LinkedList<Tab>( );\r\n\t\tfor( TabInfo info : tabs )\r\n\t\t{\r\n\t\t\tif( tabbedPane.indexOfComponent( info.tab.getContent( ) ) < 0 )\r\n\t\t\t{\r\n\t\t\t\ttoRemove.add( info.tab );\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor( Tab tab : toRemove )\r\n\t\t{\r\n\t\t\tremoveTabInternal( tab );\r\n\t\t}\r\n\t\t\r\n\t\tfor( int i = 0 ; i < tabbedPane.getTabCount( ) ; i++ )\r\n\t\t{\r\n\t\t\tupdateTab( i , true );\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void updateTab( int vIndex , boolean createIfNecessary )\r\n\t{\r\n\t\tString title = tabbedPane.getTitleAt( vIndex );\r\n\t\tIcon icon = tabbedPane.getIconAt( vIndex );\r\n\t\tComponent content = tabbedPane.getComponentAt( vIndex );\r\n\t\tComponent tabComponent = tabbedPane.getTabComponentAt( vIndex );\r\n\t\tint mnemonic = tabbedPane.getMnemonicAt( vIndex );\r\n\t\tint displayedMnemonicIndex = tabbedPane.getDisplayedMnemonicIndexAt( vIndex );\r\n\t\tColor background = tabbedPane.getBackgroundAt( vIndex );\r\n\t\tColor foreground = tabbedPane.getForegroundAt( vIndex );\r\n\t\tboolean selected = tabbedPane.getSelectedIndex( ) == vIndex;\r\n\t\tboolean enabled = tabbedPane.isEnabledAt( vIndex );\r\n\t\t\r\n\t\tTab tab = null;\r\n\t\tTabInfo info = contentMap.get( content );\r\n\t\tif( info != null )\r\n\t\t{\r\n\t\t\ttab = info.tab;\r\n\t\t}\r\n\t\telse if( createIfNecessary )\r\n\t\t{\r\n\t\t\ttab = tabFactory.createTab( );\r\n\t\t}\r\n\t\t\r\n\t\tif( tab != null )\r\n\t\t{\r\n\t\t\ttab.setTitle( title );\r\n\t\t\ttab.setIcon( icon );\r\n\t\t\ttab.setMnemonic( mnemonic );\r\n\t\t\ttab.setDisplayedMnemonicIndex( displayedMnemonicIndex );\r\n\t\t\ttab.setContent( content );\r\n\t\t\ttab.setTabComponent( tabComponent );\r\n\t\t\ttab.setSelected( selected );\r\n\t\t\ttab.setEnabled( enabled );\r\n\t\t\ttab.setBackground( background );\r\n\t\t\ttab.setForeground( foreground );\r\n\t\t\t\r\n\t\t\tif( info != null )\r\n\t\t\t{\r\n\t\t\t\tif( tabs.indexOf( info ) != vIndex )\r\n\t\t\t\t{\r\n\t\t\t\t\tmoveTabInternal( info.tab , vIndex );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if( createIfNecessary )\r\n\t\t\t{\r\n\t\t\t\taddTabInternal( vIndex , tab );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate class Handler implements PropertyChangeListener , ContainerListener , ChangeListener , FocusListener\r\n\t{\r\n\t\tboolean\tdisable\t= false;\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void propertyChange( PropertyChangeEvent evt )\r\n\t\t{\r\n\t\t\tif( disable )\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tif( \"indexForTabComponent\".equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tupdateTabs( );\r\n\t\t\t}\r\n\t\t\telse if( \"mnemonicAt\".equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tupdateTabs( );\r\n\t\t\t\tupdateMnemonics( );\r\n\t\t\t}\r\n\t\t\telse if( \"indexForTitle\".equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tupdateTab( ( Integer ) evt.getNewValue( ) , false );\r\n\t\t\t}\r\n\t\t\telse if( \"enabled\".equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tnewTabButton.setEnabled( tabbedPane.isEnabled( ) );\r\n\t\t\t\ttabbedPane.repaint( );\r\n\t\t\t}\r\n\t\t\telse if( NEW_TAB_BUTTON_VISIBLE.equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tnewTabButton.setVisible( PropertyGetter.get( Boolean.class , tabbedPane , NEW_TAB_BUTTON_VISIBLE , ( String ) null , false ) );\r\n\t\t\t}\r\n\t\t\telse if( NEW_TAB_BUTTON_UI.equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tButtonUI ui = PropertyGetter.get( ButtonUI.class , tabbedPane , NEW_TAB_BUTTON_UI , ( String ) null );\r\n\t\t\t\tif( ui != null )\r\n\t\t\t\t{\r\n\t\t\t\t\tnewTabButton.setUI( ui );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if( TAB_CLOSE_BUTTONS_VISIBLE.equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\ttabbedPane.repaint( );\r\n\t\t\t}\r\n\t\t\telse if( CONTENT_PANEL_BORDER.equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tcontentPanelBorder = PropertyGetter.get( Border.class , tabbedPane , CONTENT_PANEL_BORDER , ( String ) null );\r\n\t\t\t\ttabbedPane.repaint( );\r\n\t\t\t}\r\n\t\t\telse if( TAB_FACTORY.equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\ttabFactory = PropertyGetter.get( ITabFactory.class , tabbedPane , TAB_FACTORY );\r\n\t\t\t}\r\n\t\t\telse if( DND_POLICY.equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tdndPolicy = PropertyGetter.get( ITabbedPaneDndPolicy.class , tabbedPane , DND_POLICY );\r\n\t\t\t}\r\n\t\t\telse if( TAB_DROP_FAILURE_HANDLER.equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\ttabDropFailureHandler = PropertyGetter.get( ITabDropFailureHandler.class , tabbedPane , TAB_DROP_FAILURE_HANDLER );\r\n\t\t\t}\r\n\t\t\telse if( FLOATING_TAB_HANDLER.equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tfloatingTabHandler = PropertyGetter.get( IFloatingTabHandler.class , tabbedPane , FLOATING_TAB_HANDLER );\r\n\t\t\t}\r\n\t\t\telse if( ANIMATION_FACTOR.equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tanimFactor = PropertyGetter.get( Double.class , tabbedPane , ANIMATION_FACTOR , DEFAULT_ANIMATION_FACTOR );\r\n\t\t\t}\r\n\t\t\telse if( USE_UNIFORM_WIDTH.equals( evt.getPropertyName( ) ) )\r\n\t\t\t{\r\n\t\t\t\tuseUniformWidth = PropertyGetter.get( Boolean.class , tabbedPane , USE_UNIFORM_WIDTH , DEFAULT_USE_UNIFORM_WIDTH );\r\n\t\t\t\ttabbedPane.invalidate( );\r\n\t\t\t\ttabbedPane.validate( );\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void stateChanged( ChangeEvent e )\r\n\t\t{\r\n\t\t\tif( disable )\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tsetSelectedTabInternal( contentMap.get( tabbedPane.getSelectedComponent( ) ) );\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void componentAdded( ContainerEvent e )\r\n\t\t{\r\n\t\t\tif( disable )\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tupdateTabs( );\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void componentRemoved( ContainerEvent e )\r\n\t\t{\r\n\t\t\tif( disable )\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tupdateMnemonics( );\r\n\t\t\tupdateTabs( );\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void focusGained( FocusEvent e )\r\n\t\t{\r\n\t\t\ttabbedPane.repaint( );\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void focusLost( FocusEvent e )\r\n\t\t{\r\n\t\t\ttabbedPane.repaint( );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void addTab( Tab tab )\r\n\t{\r\n\t\taddTab( getTabCount( ) , tab , true );\r\n\t}\r\n\t\r\n\tprivate Hashtable<Integer, Integer>\tmnemonicToIndexMap;\r\n\t\r\n\t/**\r\n\t * InputMap used for mnemonics. Only non-null if the JTabbedPane has mnemonics associated with it. Lazily created in initMnemonics.\r\n\t */\r\n\tprivate InputMap\t\t\t\t\tmnemonicInputMap;\r\n\t\r\n\tprotected void installKeyboardActions( )\r\n\t{\r\n\t\tInputMap km = getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );\r\n\t\t\r\n\t\tSwingUtilities.replaceUIInputMap( tabbedPane , JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT , km );\r\n\t\tkm = getInputMap( JComponent.WHEN_FOCUSED );\r\n\t\tSwingUtilities.replaceUIInputMap( tabbedPane , JComponent.WHEN_FOCUSED , km );\r\n\t\tSwingUtilities.replaceUIActionMap( tabbedPane , loadActionMap( ) );\r\n\t\tupdateMnemonics( );\r\n\t}\r\n\t\r\n\tInputMap getInputMap( int condition )\r\n\t{\r\n\t\tif( condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT )\r\n\t\t{\r\n\t\t\treturn ( InputMap ) DefaultLookup.get( tabbedPane , this , \"TabbedPane.ancestorInputMap\" );\r\n\t\t}\r\n\t\telse if( condition == JComponent.WHEN_FOCUSED )\r\n\t\t{\r\n\t\t\treturn ( InputMap ) DefaultLookup.get( tabbedPane , this , \"TabbedPane.focusInputMap\" );\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tprotected void uninstallKeyboardActions( )\r\n\t{\r\n\t\tSwingUtilities.replaceUIActionMap( tabbedPane , null );\r\n\t\tSwingUtilities.replaceUIInputMap( tabbedPane , JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT , null );\r\n\t\tSwingUtilities.replaceUIInputMap( tabbedPane , JComponent.WHEN_FOCUSED , null );\r\n\t\tSwingUtilities.replaceUIInputMap( tabbedPane , JComponent.WHEN_IN_FOCUSED_WINDOW , null );\r\n\t\tmnemonicToIndexMap = null;\r\n\t\tmnemonicInputMap = null;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Reloads the mnemonics. This should be invoked when a memonic changes, when the title of a mnemonic changes, or when tabs are added/removed.\r\n\t */\r\n\tprivate void updateMnemonics( )\r\n\t{\r\n\t\tresetMnemonics( );\r\n\t\tfor( int counter = tabbedPane.getTabCount( ) - 1 ; counter >= 0 ; counter-- )\r\n\t\t{\r\n\t\t\tint mnemonic = tabbedPane.getMnemonicAt( counter );\r\n\t\t\t\r\n\t\t\tif( mnemonic > 0 )\r\n\t\t\t{\r\n\t\t\t\taddMnemonic( counter , mnemonic );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Resets the mnemonics bindings to an empty state.\r\n\t */\r\n\tprivate void resetMnemonics( )\r\n\t{\r\n\t\tif( mnemonicToIndexMap != null )\r\n\t\t{\r\n\t\t\tmnemonicToIndexMap.clear( );\r\n\t\t\tmnemonicInputMap.clear( );\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Adds the specified mnemonic at the specified index.\r\n\t */\r\n\tprivate void addMnemonic( int index , int mnemonic )\r\n\t{\r\n\t\tif( mnemonicToIndexMap == null )\r\n\t\t{\r\n\t\t\tinitMnemonics( );\r\n\t\t}\r\n\t\tmnemonicInputMap.put( KeyStroke.getKeyStroke( mnemonic , ActionEvent.ALT_MASK ) , \"setSelectedIndex\" );\r\n\t\tmnemonicToIndexMap.put( Integer.valueOf( mnemonic ) , Integer.valueOf( index ) );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Installs the state needed for mnemonics.\r\n\t */\r\n\tprivate void initMnemonics( )\r\n\t{\r\n\t\tmnemonicToIndexMap = new Hashtable<Integer, Integer>( );\r\n\t\tmnemonicInputMap = new ComponentInputMapUIResource( tabbedPane );\r\n\t\tmnemonicInputMap.setParent( SwingUtilities.getUIInputMap( tabbedPane , JComponent.WHEN_IN_FOCUSED_WINDOW ) );\r\n\t\tSwingUtilities.replaceUIInputMap( tabbedPane , JComponent.WHEN_IN_FOCUSED_WINDOW , mnemonicInputMap );\r\n\t}\r\n\t\r\n\tActionMap loadActionMap( )\r\n\t{\r\n\t\tActionMap map = new ActionMapUIResource( );\r\n\t\tput( map , new Actions( Actions.NEXT ) );\r\n\t\tput( map , new Actions( Actions.PREVIOUS ) );\r\n\t\tput( map , new Actions( Actions.RIGHT ) );\r\n\t\tput( map , new Actions( Actions.LEFT ) );\r\n\t\tput( map , new Actions( Actions.UP ) );\r\n\t\tput( map , new Actions( Actions.DOWN ) );\r\n\t\tput( map , new Actions( Actions.PAGE_UP ) );\r\n\t\tput( map , new Actions( Actions.PAGE_DOWN ) );\r\n\t\tput( map , new Actions( Actions.REQUEST_FOCUS ) );\r\n\t\tput( map , new Actions( Actions.REQUEST_FOCUS_FOR_VISIBLE ) );\r\n\t\tput( map , new Actions( Actions.SET_SELECTED ) );\r\n\t\tput( map , new Actions( Actions.SELECT_FOCUSED ) );\r\n\t\tput( map , new Actions( Actions.SCROLL_FORWARD ) );\r\n\t\tput( map , new Actions( Actions.SCROLL_BACKWARD ) );\r\n\t\treturn map;\r\n\t}\r\n\t\r\n\tprivate static void put( ActionMap map , Action action )\r\n\t{\r\n\t\tmap.put( action.getValue( Action.NAME ) , action );\r\n\t}\r\n\t\r\n\tprivate class Actions extends UIAction\r\n\t{\r\n\t\tfinal static String\tNEXT\t\t\t\t\t\t= \"navigateNext\";\r\n\t\tfinal static String\tPREVIOUS\t\t\t\t\t= \"navigatePrevious\";\r\n\t\tfinal static String\tRIGHT\t\t\t\t\t\t= \"navigateRight\";\r\n\t\tfinal static String\tLEFT\t\t\t\t\t\t= \"navigateLeft\";\r\n\t\tfinal static String\tUP\t\t\t\t\t\t\t= \"navigateUp\";\r\n\t\tfinal static String\tDOWN\t\t\t\t\t\t= \"navigateDown\";\r\n\t\tfinal static String\tPAGE_UP\t\t\t\t\t\t= \"navigatePageUp\";\r\n\t\tfinal static String\tPAGE_DOWN\t\t\t\t\t= \"navigatePageDown\";\r\n\t\tfinal static String\tREQUEST_FOCUS\t\t\t\t= \"requestFocus\";\r\n\t\tfinal static String\tREQUEST_FOCUS_FOR_VISIBLE\t= \"requestFocusForVisibleComponent\";\r\n\t\tfinal static String\tSET_SELECTED\t\t\t\t= \"setSelectedIndex\";\r\n\t\tfinal static String\tSELECT_FOCUSED\t\t\t\t= \"selectTabWithFocus\";\r\n\t\tfinal static String\tSCROLL_FORWARD\t\t\t\t= \"scrollTabsForwardAction\";\r\n\t\tfinal static String\tSCROLL_BACKWARD\t\t\t\t= \"scrollTabsBackwardAction\";\r\n\t\t\r\n\t\tActions( String key )\r\n\t\t{\r\n\t\t\tsuper( key );\r\n\t\t}\r\n\t\t\r\n\t\tpublic void actionPerformed( ActionEvent e )\r\n\t\t{\r\n\t\t\tString key = getName( );\r\n\t\t\tJTabbedPane pane = ( JTabbedPane ) e.getSource( );\r\n\t\t\t\r\n\t\t\tif( key == NEXT )\r\n\t\t\t{\r\n\t\t\t\t// navigateSelectedTab( SwingConstants.NEXT );\r\n\t\t\t}\r\n\t\t\telse if( key == PREVIOUS )\r\n\t\t\t{\r\n\t\t\t\t// navigateSelectedTab( SwingConstants.PREVIOUS );\r\n\t\t\t}\r\n\t\t\telse if( key == RIGHT )\r\n\t\t\t{\r\n\t\t\t\t// navigateSelectedTab( SwingConstants.EAST );\r\n\t\t\t}\r\n\t\t\telse if( key == LEFT )\r\n\t\t\t{\r\n\t\t\t\t// navigateSelectedTab( SwingConstants.WEST );\r\n\t\t\t}\r\n\t\t\telse if( key == UP )\r\n\t\t\t{\r\n\t\t\t\t// navigateSelectedTab( SwingConstants.NORTH );\r\n\t\t\t}\r\n\t\t\telse if( key == DOWN )\r\n\t\t\t{\r\n\t\t\t\t// navigateSelectedTab( SwingConstants.SOUTH );\r\n\t\t\t}\r\n\t\t\telse if( key == PAGE_UP )\r\n\t\t\t{\r\n\t\t\t\t// int tabPlacement = pane.getTabPlacement( );\r\n\t\t\t\t// if( tabPlacement == JTabbedPane.TOP || tabPlacement == JTabbedPane.BOTTOM )\r\n\t\t\t\t// {\r\n\t\t\t\t// navigateSelectedTab( SwingConstants.WEST );\r\n\t\t\t\t// }\r\n\t\t\t\t// else\r\n\t\t\t\t// {\r\n\t\t\t\t// navigateSelectedTab( SwingConstants.NORTH );\r\n\t\t\t\t// }\r\n\t\t\t}\r\n\t\t\telse if( key == PAGE_DOWN )\r\n\t\t\t{\r\n\t\t\t\t// int tabPlacement = pane.getTabPlacement( );\r\n\t\t\t\t// if( tabPlacement == JTabbedPane.TOP || tabPlacement == JTabbedPane.BOTTOM )\r\n\t\t\t\t// {\r\n\t\t\t\t// navigateSelectedTab( SwingConstants.EAST );\r\n\t\t\t\t// }\r\n\t\t\t\t// else\r\n\t\t\t\t// {\r\n\t\t\t\t// navigateSelectedTab( SwingConstants.SOUTH );\r\n\t\t\t\t// }\r\n\t\t\t}\r\n\t\t\telse if( key == REQUEST_FOCUS )\r\n\t\t\t{\r\n\t\t\t\tpane.requestFocus( );\r\n\t\t\t}\r\n\t\t\telse if( key == REQUEST_FOCUS_FOR_VISIBLE )\r\n\t\t\t{\r\n\t\t\t\trequestFocusForVisibleComponent( );\r\n\t\t\t}\r\n\t\t\telse if( key == SET_SELECTED )\r\n\t\t\t{\r\n\t\t\t\tString command = e.getActionCommand( );\r\n\t\t\t\t\r\n\t\t\t\tif( command != null && command.length( ) > 0 )\r\n\t\t\t\t{\r\n\t\t\t\t\tint mnemonic = ( int ) e.getActionCommand( ).charAt( 0 );\r\n\t\t\t\t\tif( mnemonic >= 'a' && mnemonic <= 'z' )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmnemonic -= ( 'a' - 'A' );\r\n\t\t\t\t\t}\r\n\t\t\t\t\tInteger index = mnemonicToIndexMap.get( Integer.valueOf( mnemonic ) );\r\n\t\t\t\t\tif( index != null && pane.isEnabledAt( index.intValue( ) ) )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tpane.setSelectedIndex( index.intValue( ) );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if( key == SELECT_FOCUSED )\r\n\t\t\t{\r\n\t\t\t\t// int focusIndex = getFocusIndex( );\r\n\t\t\t\t// if( focusIndex != -1 )\r\n\t\t\t\t// {\r\n\t\t\t\t// pane.setSelectedIndex( focusIndex );\r\n\t\t\t\t// }\r\n\t\t\t}\r\n\t\t\telse if( key == SCROLL_FORWARD )\r\n\t\t\t{\r\n\t\t\t\t// if( scrollableTabLayoutEnabled( ) )\r\n\t\t\t\t// {\r\n\t\t\t\t// tabScroller.scrollForward( pane.getTabPlacement( ) );\r\n\t\t\t\t// }\r\n\t\t\t}\r\n\t\t\telse if( key == SCROLL_BACKWARD )\r\n\t\t\t{\r\n\t\t\t\t// if( scrollableTabLayoutEnabled( ) )\r\n\t\t\t\t// {\r\n\t\t\t\t// tabScroller.scrollBackward( pane.getTabPlacement( ) );\r\n\t\t\t\t// }\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t// REMIND(aim,7/29/98): This method should be made\r\n\t// protected in the next release where\r\n\t// API changes are allowed\r\n\tboolean requestFocusForVisibleComponent( )\r\n\t{\r\n\t\treturn SwingUtilities2.tabbedPaneChangeFocusTo( currentContent );\r\n\t}\r\n\t\r\n\tprivate void navigateSelectedTab( int next )\r\n\t{\r\n\t\tint currentIndex = tabbedPane.getSelectedIndex( );\r\n\t\t\r\n\t\tswitch( next )\r\n\t\t{\r\n\t\t\tcase SwingConstants.NEXT:\r\n\t\t\tcase SwingConstants.EAST:\r\n\t\t\tcase SwingConstants.SOUTH:\r\n\t\t\t\tif( currentIndex < tabbedPane.getTabCount( ) - 1 )\r\n\t\t\t\t{\r\n\t\t\t\t\ttabbedPane.setSelectedIndex( currentIndex + 1 );\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase SwingConstants.PREVIOUS:\r\n\t\t\tcase SwingConstants.WEST:\r\n\t\t\tcase SwingConstants.NORTH:\r\n\t\t\t\tif( currentIndex > 0 )\r\n\t\t\t\t{\r\n\t\t\t\t\ttabbedPane.setSelectedIndex( currentIndex - 1 );\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate static boolean\tLOG_EXCEPTIONS\t= true;\r\n\t\r\n\tprivate static void log( Exception e )\r\n\t{\r\n\t\tif( LOG_EXCEPTIONS )\r\n\t\t{\r\n\t\t\te.printStackTrace( );\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void copySettings( JTabbedPane src , JTabbedPane dest )\r\n\t{\r\n\t\tdest.putClientProperty( TAB_FACTORY , src.getClientProperty( TAB_FACTORY ) );\r\n\t\tdest.putClientProperty( TAB_CLOSE_BUTTONS_VISIBLE , src.getClientProperty( TAB_CLOSE_BUTTONS_VISIBLE ) );\r\n\t\tdest.putClientProperty( NEW_TAB_BUTTON_VISIBLE , src.getClientProperty( NEW_TAB_BUTTON_VISIBLE ) );\r\n\t\tdest.putClientProperty( TAB_DROP_FAILURE_HANDLER , src.getClientProperty( TAB_DROP_FAILURE_HANDLER ) );\r\n\t\tdest.putClientProperty( FLOATING_TAB_HANDLER , src.getClientProperty( FLOATING_TAB_HANDLER ) );\r\n\t\tdest.putClientProperty( CONTENT_PANEL_BORDER , src.getClientProperty( CONTENT_PANEL_BORDER ) );\r\n\t\tdest.putClientProperty( NEW_TAB_BUTTON_UI , src.getClientProperty( NEW_TAB_BUTTON_UI ) );\r\n\t\tdest.putClientProperty( DND_POLICY , src.getClientProperty( DND_POLICY ) );\r\n\t\tdest.putClientProperty( TAB_CLOSE_BUTTON_LISTENER , src.getClientProperty( TAB_CLOSE_BUTTON_LISTENER ) );\r\n\t\tdest.putClientProperty( USE_UNIFORM_WIDTH , src.getClientProperty( USE_UNIFORM_WIDTH ) );\r\n\t\tdest.putClientProperty( ANIMATION_FACTOR , src.getClientProperty( ANIMATION_FACTOR ) );\r\n\t\tdest.setTabPlacement( src.getTabPlacement( ) );\r\n\t\tdest.setEnabled( src.isEnabled( ) );\r\n\t}\r\n}\r"
] | import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.sexydock.tabs.DefaultFloatingTabHandler;
import org.sexydock.tabs.DefaultTabDropFailureHandler;
import org.sexydock.tabs.DefaultWindowsClosedHandler;
import org.sexydock.tabs.ITabFactory;
import org.sexydock.tabs.ITabbedPaneDndPolicy;
import org.sexydock.tabs.ITabbedPaneWindow;
import org.sexydock.tabs.ITabbedPaneWindowFactory;
import org.sexydock.tabs.Tab;
import org.sexydock.tabs.jhrome.JhromeTabbedPaneUI;
| package org.sexydock.tabs.demos;
@SuppressWarnings( "serial" )
public class NotepadDemo extends JFrame implements ISexyTabsDemo , ITabbedPaneWindow , ITabbedPaneWindowFactory , ITabFactory
{
public static void main( String[ ] args )
{
SwingUtilities.invokeLater( new Runnable( )
{
@Override
public void run( )
{
new NotepadDemo( ).start( );
}
} );
}
public NotepadDemo( )
{
initGUI( );
}
private void initGUI( )
{
setTitle( "Notepad" );
tabbedPane = new JTabbedPane( );
| tabbedPane.setUI( new JhromeTabbedPaneUI( ) );
| 8 |
darko1002001/android-rest-client | rest-client-demo/src/main/java/com/dg/examples/restclientdemo/communication/requests/BlogsGoogleRequest.java | [
"public class RestConstants {\n\n public static final String TAG = RestConstants.class.getSimpleName();\n\n public static final String BASE_URL = \"https://ajax.googleapis.com\";\n public static final String LOG_SERVICE_URL = \"http://log-requests.herokuapp.com/\";\n public static final String HTTP_BIN_URL = \"http://httpbin.org/\";\n\n\n public static final String GOOGLE_BLOGS = BASE_URL + \"/ajax/services/feed/find\";\n}",
"public class BlogsGoogleParser extends BaseJacksonMapperResponseParser<ResponseModel> {\n\n public static final String TAG = BlogsGoogleParser.class.getSimpleName();\n\n @Override\n public ResponseModel parse(InputStream instream) throws Exception {\n return mapper.readValue(instream, ResponseModel.class);\n }\n}",
"public class ResponseModel {\n // To learn how to configure this go here:\n // http://wiki.fasterxml.com/JacksonInFiveMinutes\n // Url to pull down is set under communication/RestConstants.java\n public static final String TAG = ResponseModel.class.getSimpleName();\n\n @JsonProperty\n private String responseStatus;\n\n @JsonProperty\n private String responseDetails;\n\n @JsonProperty\n private ResponseDataModel responseData;\n\n public String getResponseStatus() {\n return responseStatus;\n }\n\n public void setResponseStatus(String responseStatus) {\n this.responseStatus = responseStatus;\n }\n\n public String getResponseDetails() {\n return responseDetails;\n }\n\n public void setResponseDetails(String responseDetails) {\n this.responseDetails = responseDetails;\n }\n\n public ResponseDataModel getResponseData() {\n return responseData;\n }\n\n public void setResponseData(ResponseDataModel responseData) {\n this.responseData = responseData;\n }\n\n @Override\n public String toString() {\n return \"ResponseModel [responseStatus=\" + responseStatus\n + \", responseDetails=\" + responseDetails + \", responseData=\"\n + responseData + \"]\";\n }\n\n\n}",
"public enum RequestMethod {\n GET, POST, PUT, PATCH, DELETE;\n}",
"public abstract class RestClientRequest<T> implements HttpRequest {\n\n private String TAG = RestClientRequest.class.getSimpleName();\n\n private HttpResponseParser<T> parser;\n private ResponseHandler<T> handler;\n private ResponseStatusHandler statusHandler;\n private BoundCallback<T> callback;\n private Request.Builder request = new Request.Builder();\n private StringBuilder queryParams;\n private String url;\n\n RequestOptions requestOptions = null;\n AuthenticationProvider authenticationProvider;\n\n protected RestClientRequest() {\n authenticationProvider = RestClientConfiguration.get().getAuthenticationProvider();\n }\n\n public RestClientRequest<T> setAuthenticationProvider(AuthenticationProvider authenticationProvider) {\n this.authenticationProvider = authenticationProvider;\n return this;\n }\n\n protected HttpCallback<T> getCallback() {\n return callback;\n }\n\n public RestClientRequest<T> setCallback(HttpCallback<T> callback) {\n BoundCallback<T> boundCallback = new BoundCallback<>(callback);\n this.callback = boundCallback;\n return this;\n }\n\n public RestClientRequest<T> setActivityBoundCallback(Activity activity, HttpCallback<T> callback) {\n this.callback = new ActivityBoundHttpCallback<>(activity, callback);\n return this;\n }\n\n public RestClientRequest<T> setFragmentBoundCallback(Fragment fragment, HttpCallback<T> callback) {\n this.callback = new FragmentBoundHttpCallback<>(fragment, callback);\n return this;\n }\n\n\n public RestClientRequest<T> setParser(HttpResponseParser<T> parser) {\n this.parser = parser;\n return this;\n }\n\n public ResponseHandler<T> getHandler() {\n return handler;\n }\n\n /**\n * Adds a new header value, existing value with same key will not be overwritten\n *\n * @param key\n * @param value\n */\n public RestClientRequest<T> addHeader(final String key, final String value) {\n request.addHeader(key, value);\n return this;\n }\n\n /**\n * Overrides an existing header value\n *\n * @param key\n * @param value\n */\n public RestClientRequest<T> header(final String key, final String value) {\n request.header(key, value);\n return this;\n }\n\n @Override\n public void run() {\n doBeforeRunRequestInBackgroundThread();\n validateRequestArguments();\n runRequest();\n }\n\n public void validateRequestArguments() {\n if (TextUtils.isEmpty(this.url)) {\n Log.e(TAG, \"Request url is empty or null\", new IllegalArgumentException());\n }\n }\n\n @Override\n public void cancel() {\n if (callback != null) {\n callback.unregister();\n }\n }\n\n public boolean isCanceled() {\n return callback != null && callback.isRegistered();\n }\n\n /**\n * Set a custom handler that will be triggered when the response returns\n * either Success or Fail. You can choose where this info is sent. **Default**\n * is the UIThreadREsponseHandler implementation which runs the appropriate\n * callback on the UI thread.\n *\n * @param handler\n */\n public RestClientRequest<T> setResponseHandler(ResponseHandler<T> handler) {\n this.handler = handler;\n return this;\n }\n\n /**\n * By default success is a code in the range of 2xx. Everything else triggers\n * an Error. You can set a handler which will take into account your own\n * custom error codes to determine if the response is a success or fail.\n *\n * @param statusHandler\n */\n public RestClientRequest<T> setStatusHandler(ResponseStatusHandler statusHandler) {\n this.statusHandler = statusHandler;\n return this;\n }\n\n protected HttpResponseParser<T> getParser() {\n return parser;\n }\n\n public RestClientRequest<T> setUrl(String url) {\n this.url = url;\n return this;\n }\n\n /**\n * Access URL formatting options with the format ex. /action/:type/otheraction/:other\n * Removes any suffixes such as query params (url ends with somepath?one=two becomes somepath)\n *\n * @param url a string url\n * @param params\n * @return\n */\n public RestClientRequest<T> setUrlWithFormat(String url, String... params) {\n if (params.length == 0) {\n this.url = url;\n return this;\n }\n int questionMark = url.indexOf(\"?\");\n StringBuilder sb = new StringBuilder(questionMark > -1 ? url.substring(0, questionMark) : url);\n for (String param : params) {\n int start = sb.indexOf(\"/:\");\n if (start == -1) {\n throw new IllegalArgumentException(\"Need to add the same amount of placeholder params in the string as /:value/ where you want to replace it\");\n }\n int end = sb.indexOf(\"/\", start + 1);\n if (end == -1) {\n end = sb.length();\n }\n sb.replace(start + 1, end, param);\n }\n this.url = sb.toString();\n return this;\n }\n\n public RestClientRequest<T> setRequestMethod(RequestMethod requestMethod) {\n return setRequestMethod(requestMethod, null);\n\n }\n\n public RestClientRequest<T> setRequestMethod(RequestMethod requestMethod, RequestBody requestBody) {\n request.method(requestMethod.name(), requestBody);\n return this;\n }\n\n protected void runRequest() {\n if (handler == null) {\n handler = new UIThreadResponseHandler<>(callback);\n }\n if (statusHandler == null) {\n statusHandler = new DefaultResponseStatusHandler();\n }\n\n OkHttpClient client = generateClient();\n StringBuilder url = new StringBuilder(this.url);\n StringBuilder queryParams = this.queryParams;\n if (queryParams != null) {\n url.append(queryParams);\n }\n\n request.url(url.toString());\n\n if (this.authenticationProvider != null) {\n authenticationProvider.authenticateRequest(this);\n }\n\n Request preparedRequest = request.build();\n Response response;\n try {\n response = client.newCall(preparedRequest).execute();\n } catch (final Exception e) {\n ResponseStatus responseStatus = ResponseStatus.getConnectionErrorStatus();\n Log.e(TAG, responseStatus.toString(), e);\n handler.handleError(responseStatus);\n doAfterRunRequestInBackgroundThread();\n return;\n }\n\n final ResponseStatus status = new ResponseStatus(response.code(), response.message());\n Log.d(TAG, status.toString());\n if (handleResponseStatus(status)) {\n doAfterRunRequestInBackgroundThread();\n return;\n }\n\n try {\n if (parser != null) {\n InputStream instream = response.body().byteStream();\n final T responseData = parser.parse(instream);\n close(response.body());\n doAfterSuccessfulRequestInBackgroundThread(responseData);\n handler.handleSuccess(responseData, status);\n } else {\n Log.i(TAG, \"You haven't added a parser for your request\");\n handler.handleSuccess(null, status);\n doAfterSuccessfulRequestInBackgroundThread(null);\n }\n } catch (final Exception e) {\n ResponseStatus responseStatus = ResponseStatus.getParseErrorStatus();\n Log.d(TAG, responseStatus.toString(), e);\n handler.handleError(responseStatus);\n }\n doAfterRunRequestInBackgroundThread();\n\n }\n\n /**\n * Return true if you have handled the status yourself.\n */\n protected boolean handleResponseStatus(ResponseStatus status) {\n if (statusHandler.hasErrorInStatus(status)) {\n handler.handleError(status);\n return true;\n }\n return false;\n }\n\n @Override\n public void executeAsync() {\n TaskStore.get(RestClientConfiguration.get().getContext()).queue(this, getRequestOptions());\n }\n\n public RequestOptions getRequestOptions() {\n return requestOptions;\n }\n\n public RestClientRequest<T> setRequestOptions(RequestOptions requestOptions) {\n this.requestOptions = requestOptions;\n return this;\n }\n\n /**\n * Use this method to add the required data to the request. This will happen\n * in the background thread which enables you to pre-process the parameters,\n * do queries etc..\n */\n protected void doBeforeRunRequestInBackgroundThread() {\n }\n\n /**\n * This will happen in the background thread which enables you to do some\n * cleanup in the background after the request finishes\n */\n protected void doAfterRunRequestInBackgroundThread() {\n }\n\n /**\n * This will happen in the background thread only if the request execution is successful\n */\n protected void doAfterSuccessfulRequestInBackgroundThread(T data) {\n }\n\n private OkHttpClient generateClient() {\n OkHttpClient client = new OkHttpClient();\n customizeClient(client);\n return client;\n }\n\n protected void customizeClient(OkHttpClient client) {\n client.setConnectTimeout(RestClientConfiguration.get().getConnectionTimeout(), TimeUnit.MILLISECONDS);\n client.setReadTimeout(RestClientConfiguration.get().getReadTimeout(), TimeUnit.MILLISECONDS);\n client.setWriteTimeout(RestClientConfiguration.get().getWriteTimeout(), TimeUnit.MILLISECONDS);\n }\n\n public RestClientRequest<T> addQueryParam(String name, String value) {\n addQueryParam(name, value, false, true);\n return this;\n }\n\n public RestClientRequest<T> addEncodedQueryParam(String name, String value) {\n addQueryParam(name, value, false, false);\n return this;\n }\n\n private void addQueryParam(String name, Object value, boolean encodeName, boolean encodeValue) {\n if (value instanceof Iterable) {\n for (Object iterableValue : (Iterable<?>) value) {\n if (iterableValue != null) { // Skip null values\n addQueryParam(name, iterableValue.toString(), encodeName, encodeValue);\n }\n }\n } else if (value.getClass().isArray()) {\n for (int x = 0, arrayLength = Array.getLength(value); x < arrayLength; x++) {\n Object arrayValue = Array.get(value, x);\n if (arrayValue != null) { // Skip null values\n addQueryParam(name, arrayValue.toString(), encodeName, encodeValue);\n }\n }\n } else {\n addQueryParam(name, value.toString(), encodeName, encodeValue);\n }\n }\n\n private void addQueryParam(String name, String value, boolean encodeName, boolean encodeValue) {\n if (name == null) {\n throw new IllegalArgumentException(\"Query param name must not be null.\");\n }\n if (value == null) {\n throw new IllegalArgumentException(\"Query param \\\"\" + name + \"\\\" value must not be null.\");\n }\n try {\n StringBuilder queryParams = this.queryParams;\n if (queryParams == null) {\n this.queryParams = queryParams = new StringBuilder();\n }\n\n queryParams.append(queryParams.length() > 0 ? '&' : '?');\n\n if (encodeName) {\n name = URLEncoder.encode(name, \"UTF-8\");\n }\n if (encodeValue) {\n value = URLEncoder.encode(value, \"UTF-8\");\n }\n queryParams.append(name).append('=').append(value);\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\n \"Unable to convert query parameter \\\"\" + name + \"\\\" value to UTF-8: \" + value, e);\n }\n }\n\n private void close(ResponseBody body) {\n try {\n if (body != null) {\n body.close();\n }\n } catch (IOException e) {\n }\n\n }\n}"
] | import android.util.Log;
import com.dg.examples.restclientdemo.communication.RestConstants;
import com.dg.examples.restclientdemo.communication.parsers.BlogsGoogleParser;
import com.dg.examples.restclientdemo.domain.ResponseModel;
import com.dg.libs.rest.client.RequestMethod;
import com.dg.libs.rest.requests.RestClientRequest;
import com.squareup.okhttp.OkHttpClient; | package com.dg.examples.restclientdemo.communication.requests;
public class BlogsGoogleRequest extends RestClientRequest<ResponseModel> {
public static final String TAG = BlogsGoogleRequest.class.getSimpleName();
public BlogsGoogleRequest(String query) {
super();
setRequestMethod(RequestMethod.GET);
setUrl(RestConstants.GOOGLE_BLOGS);
| setParser(new BlogsGoogleParser()); | 1 |
albertogiunta/justintrain-client-android | app/src/main/java/com/jaus/albertogiunta/justintrain_oraritreni/aboutAndSettings/ItemBuilder.java | [
"public enum ENUM_CATEGORIES {\n\n FR(\"Frecciarossa\"), FB(\"Frecciabianca\"), FA(\"Frecciargento\"), IC(\"Intercity\"), REG(\"Regionale\"), RV(\"Regionale Veloce\"), BUS(\"Bus\");\n\n private final String alias;\n\n ENUM_CATEGORIES(String alias) {\n this.alias = alias;\n }\n\n public String getAlias() {\n return alias;\n }\n}",
"public class AnalyticsHelper {\n\n /*\n\n adb shell setprop log.tag.FA VERBOSE\n adb shell setprop log.tag.FA-SVC VERBOSE\n adb logcat -v time -s FA FA-SVC\n\n */\n\n private FirebaseAnalytics firebase = null;\n\n private static AnalyticsHelper analyticsHelper;\n\n public static AnalyticsHelper getInstance(Context context) {\n if (analyticsHelper == null) {\n analyticsHelper = new AnalyticsHelper(context);\n }\n return analyticsHelper;\n }\n\n private AnalyticsHelper(Context context) {\n firebase = FirebaseAnalytics.getInstance(context);\n firebase.setMinimumSessionDuration(3000);\n// firebase.setUserId();\n// firebase.setUserProperty();\n }\n\n public void logScreenEvent(String screen, String action) {\n Bundle bundle = new Bundle();\n bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, screen);\n bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, action);\n bundle.putString(FirebaseAnalytics.Param.ITEM_ID, action);\n firebase.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);\n }\n}",
"public class SettingsPreferences {\n\n // recent\n public static boolean isRecentEnabled(Context context) {\n return SharedPreferencesHelper.getSharedPreferenceBoolean(context, SP_SETT_RECENT, true);\n }\n\n public static void enableRecent(Context context) {\n enableGenericSetting(context, SP_SETT_RECENT);\n }\n\n public static void disableRecent(Context context) {\n disableGenericSetting(context, SP_SETT_RECENT);\n }\n\n // recent hint\n public static boolean isRecentHintEnabled(Context context) {\n return SharedPreferencesHelper.getSharedPreferenceBoolean(context, SP_SP_RECENT_HINT, true);\n }\n\n public static void enableRecentHint(Context context) {\n enableGenericSetting(context, SP_SP_RECENT_HINT);\n }\n\n public static void disableRecentHint(Context context) {\n disableGenericSetting(context, SP_SP_RECENT_HINT);\n }\n\n // vibration\n public static boolean isVibrationEnabled(Context context) {\n return SharedPreferencesHelper.getSharedPreferenceBoolean(context, SP_SETT_NOTIF_VIBRATION, true);\n }\n\n public static void enableVibration(Context context) {\n enableGenericSetting(context, SP_SETT_NOTIF_VIBRATION);\n }\n\n public static void disableVibration(Context context) {\n disableGenericSetting(context, SP_SETT_NOTIF_VIBRATION);\n }\n\n // lightning\n public static boolean isLightningEnabled(Context context) {\n return SharedPreferencesHelper.getSharedPreferenceBoolean(context, SP_SETT_LIGHTNING, false);\n }\n\n public static void enableLightning(Context context) {\n enableGenericSetting(context, SP_SETT_LIGHTNING);\n }\n\n public static void disableLightning(Context context) {\n disableGenericSetting(context, SP_SETT_LIGHTNING);\n }\n\n // preemptive\n public static boolean isPreemptiveEnabled(Context context) {\n return SharedPreferencesHelper.getSharedPreferenceBoolean(context, SP_SETT_GET_PREEMPTIVE, true);\n }\n\n public static void enablePreemptive(Context context) {\n enableGenericSetting(context, SP_SETT_GET_PREEMPTIVE);\n }\n\n public static void disablePreemptive(Context context) {\n disableGenericSetting(context, SP_SETT_GET_PREEMPTIVE);\n }\n\n // changes\n public static boolean isIncludeChangesEnabled(Context context) {\n return SharedPreferencesHelper.getSharedPreferenceBoolean(context, SP_SETT_INCLUDE_CHANGES, true);\n }\n\n public static void enableIncludeChanges(Context context) {\n enableGenericSetting(context, SP_SETT_INCLUDE_CHANGES);\n }\n\n public static void disableIncludeChanges(Context context) {\n disableGenericSetting(context, SP_SETT_INCLUDE_CHANGES);\n }\n\n // train categories\n public static boolean isCategoryEnabled(Context context, ENUM_CATEGORIES category) {\n return isGenericSettingEnabled(context, PREFIX_CATEGORIES + category.name(), true);\n }\n\n public static void enableAllCategories(Context context) {\n for (ENUM_CATEGORIES cat : ENUM_CATEGORIES.values()) {\n enableCategory(context, cat.name());\n }\n }\n\n public static void disableAllCategories(Context context) {\n for (ENUM_CATEGORIES cat : ENUM_CATEGORIES.values()) {\n disableCategory(context, cat.name());\n }\n }\n\n public static void enableCategory(Context context, String catName) {\n enableGenericSetting(context, PREFIX_CATEGORIES + catName);\n }\n\n public static void disableCategory(Context context, String catName) {\n disableGenericSetting(context, PREFIX_CATEGORIES + catName);\n }\n\n public static void setCategory(Context context, String catName, boolean isEnabled) {\n if (isEnabled) {\n enableCategory(context, catName);\n } else {\n disableCategory(context, catName);\n }\n }\n\n public static boolean isPossibleToDisableCheckbox(Context context) {\n return getEnabledCategoriesAsStringList(context).size() > 1;\n }\n\n public static String[] getEnabledCategoriesAsStringArray(Context context) {\n return getEnabledCategoriesAsStringList(context).toArray(new String[0]);\n }\n\n public static List<String> getEnabledCategoriesAsStringList(Context context) {\n List<String> categoriesArray = new ArrayList<>();\n for (ENUM_CATEGORIES cat : ENUM_CATEGORIES.values()) {\n if (isCategoryEnabled(context, cat)) {\n categoriesArray.add(cat.name());\n }\n }\n return categoriesArray;\n }\n\n public static String getCategoriesAsString(Context context, String separator) {\n String categoriesString = \"\";\n for (String s : getEnabledCategoriesAsStringList(context)) {\n categoriesString += s + separator;\n }\n if (categoriesString.length() > separator.length()) {\n categoriesString = categoriesString.substring(0, categoriesString.length() - separator.length());\n }\n return categoriesString;\n }\n\n\n // version code\n public static int getPreviouslySavedVersionCode(Context context) {\n return SharedPreferencesHelper.getSharedPreferenceInt(context, SP_SP_SAVED_VERSION, 0);\n }\n\n public static void setCurrentVersionCode(Context context) {\n SharedPreferencesHelper.setSharedPreferenceInt(context, SP_SP_SAVED_VERSION, BuildConfig.VERSION_CODE);\n }\n\n // generic\n public static boolean isGenericSettingEnabled(Context context, String CONST, boolean defaultValue) {\n return SharedPreferencesHelper.getSharedPreferenceBoolean(context, CONST, defaultValue);\n }\n\n public static void enableGenericSetting(Context context, String CONST) {\n SharedPreferencesHelper.setSharedPreferenceBoolean(context, CONST, true);\n }\n\n public static void disableGenericSetting(Context context, String CONST) {\n SharedPreferencesHelper.setSharedPreferenceBoolean(context, CONST, false);\n }\n\n ////////////////////////////////////////////////////////////////////////////////////////////////\n\n private static void setNewSettingsNotPreviouslyIncludedBefore6(Context context) {\n // 6 - 0.7.4\n disableLightning(context);\n }\n\n private static void setNewSettingsNotPreviouslyIncludedBefore12(Context context) {\n // 12 - 0.8.2\n enableVibration(context);\n enablePreemptive(context);\n }\n\n private static void setNewSettingsNotPreviouslyIncludedBefore13(Context context) {\n // 13 - 0.8.4\n enableIncludeChanges(context);\n enableAllCategories(context);\n }\n\n private static void setNewSettingsNotPreviouslyIncludedBefore30(Context context) {\n // 27 - 1.0.0\n disableInstantDelay(context);\n disableLiveNotification(context);\n }\n\n private static void setNewSettingsNotPreviouslyIncludedBefore47(Context context) {\n // 43 - 1.0.0\n disableCompactNotification(context);\n }\n\n private static void setNewSettingsNotPreviouslyIncludedBefore48(Context context) {\n // 48 - 1.1.5\n enableRecentHint(context);\n enableRecent(context);\n }\n\n private static void setNewSettingsNotPreviouslyIncludedBefore51(Context context) {\n // 51 - 1.2.0\n disableAutoRemoveNotification(context);\n }\n\n public static void setDefaultSharedPreferencesOnFirstStart(Context context) {\n // preferences\n SharedPreferencesHelper.setSharedPreferenceBoolean(context, SP_SP_FIRST_START, false);\n SharedPreferencesHelper.setSharedPreferenceInt(context, SP_SP_SAVED_VERSION, BuildConfig.VERSION_CODE);\n SharedPreferencesHelper.setSharedPreferenceInt(context, SP_SP_VERSION, SP_VERSION);\n\n // settings screen\n setNewSettingsNotPreviouslyIncludedBefore6(context);\n setNewSettingsNotPreviouslyIncludedBefore12(context);\n setNewSettingsNotPreviouslyIncludedBefore13(context);\n setNewSettingsNotPreviouslyIncludedBefore30(context);\n setNewSettingsNotPreviouslyIncludedBefore47(context);\n setNewSettingsNotPreviouslyIncludedBefore48(context);\n setNewSettingsNotPreviouslyIncludedBefore51(context);\n }\n\n // inclusion of settings - update together with onFirstStart\n public static void setNewSettingsNotPreviouslyIncludedBefore(Context context) {\n if (getPreviouslySavedVersionCode(context) < 12) {\n setNewSettingsNotPreviouslyIncludedBefore12(context);\n }\n if (getPreviouslySavedVersionCode(context) < 13) {\n setNewSettingsNotPreviouslyIncludedBefore13(context);\n }\n if (getPreviouslySavedVersionCode(context) < 30) {\n setNewSettingsNotPreviouslyIncludedBefore30(context);\n }\n if (getPreviouslySavedVersionCode(context) < 47) {\n setNewSettingsNotPreviouslyIncludedBefore47(context);\n }\n if (getPreviouslySavedVersionCode(context) < 48) {\n setNewSettingsNotPreviouslyIncludedBefore48(context);\n }\n if (getPreviouslySavedVersionCode(context) < 51) {\n setNewSettingsNotPreviouslyIncludedBefore48(context);\n }\n }\n\n private static boolean areAllCategoriesEnabled(Context context) {\n return getEnabledCategoriesAsStringArray(context).length == ENUM_CATEGORIES.values().length;\n }\n\n public static boolean isAnySearchFilterEnabled(Context context) {\n return !isIncludeChangesEnabled(context) || !areAllCategoriesEnabled(context);\n }\n}",
"public static final ButterKnife.Action<View> GONE = (view, index) -> view.setVisibility(View.GONE);",
"public static final ButterKnife.Action<View> VISIBLE = (view, index) -> view.setVisibility(View.VISIBLE);",
"public static final String SCREEN_SETTINGS = \"SETT\";"
] | import com.google.android.flexbox.FlexboxLayout;
import android.content.Context;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.jaus.albertogiunta.justintrain_oraritreni.R;
import com.jaus.albertogiunta.justintrain_oraritreni.utils.constants.ENUM_CATEGORIES;
import com.jaus.albertogiunta.justintrain_oraritreni.utils.helpers.AnalyticsHelper;
import com.jaus.albertogiunta.justintrain_oraritreni.utils.sharedPreferences.SettingsPreferences;
import static butterknife.ButterKnife.apply;
import static com.jaus.albertogiunta.justintrain_oraritreni.utils.components.ViewsUtils.GONE;
import static com.jaus.albertogiunta.justintrain_oraritreni.utils.components.ViewsUtils.VISIBLE;
import static com.jaus.albertogiunta.justintrain_oraritreni.utils.constants.CONST_ANALYTICS.SCREEN_SETTINGS; | package com.jaus.albertogiunta.justintrain_oraritreni.aboutAndSettings;
public class ItemBuilder {
private final LayoutInflater inflater;
private final LinearLayout parent;
private View view;
public ItemBuilder(Context context, LinearLayout parent) {
this.inflater = LayoutInflater.from(context);
this.parent = parent;
}
public ItemBuilder addItemGroupHeader(String header) {
view = inflater.inflate(R.layout.item_element_header, parent, false);
RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.rl_container);
TextView tv = (TextView) rl.findViewById(R.id.tv_header);
tv.setText(header);
return this;
}
public ItemBuilder addItemWithTitle(String title) {
view = inflater.inflate(R.layout.item_element_title, parent, false);
TextView tv = (TextView) view.findViewById(R.id.tv_title);
tv.setText(title);
return this;
}
public ItemBuilder addItemWithIconTitle(int icon, String title) {
view = inflater.inflate(R.layout.item_element_icon_title, parent, false);
ImageView iv = (ImageView) view.findViewById(R.id.iv_icon);
iv.setImageResource(icon);
TextView tv = (TextView) view.findViewById(R.id.tv_title);
tv.setText(title);
return this;
}
public ItemBuilder addItemWithTitleSubtitle(String title, String subtitle) {
view = inflater.inflate(R.layout.item_element_title_subtitle, parent, false);
TextView tv = (TextView) view.findViewById(R.id.tv_title);
tv.setText(title);
TextView tv2 = (TextView) view.findViewById(R.id.tv_subtitle);
tv2.setText(subtitle);
return this;
}
public ItemBuilder addItemWithIconTitleSubtitle(int icon, String title, String subtitle) {
view = inflater.inflate(R.layout.item_element_icon_title_subtitle, parent, false);
ImageView iv = (ImageView) view.findViewById(R.id.iv_icon);
iv.setImageResource(icon);
TextView tv = (TextView) view.findViewById(R.id.tv_title);
tv.setText(title);
TextView tv2 = (TextView) view.findViewById(R.id.tv_subtitle);
tv2.setText(subtitle);
return this;
}
public ItemBuilder addItemPrefWithToggle(Context context, String title, String subtitle, boolean isChecked, boolean useSwitch, boolean isProFeature, boolean userIsPro, String preferenceCONST, String settingsEnabledAction, String settingsDisabledAction) {
view = inflater.inflate(R.layout.item_element_title_subtitle_checkbox, parent, false);
TextView tv = (TextView) view.findViewById(R.id.tv_title);
tv.setText(title);
TextView tv2 = (TextView) view.findViewById(R.id.tv_subtitle);
tv2.setText(subtitle);
CheckBox checkboxButton = (CheckBox) view.findViewById(R.id.cb_pref);
SwitchCompat switchButton = (SwitchCompat) view.findViewById(R.id.sw_pref);
checkboxButton.setChecked(isChecked);
switchButton.setChecked(isChecked);
if (useSwitch) {
apply(checkboxButton, GONE);
apply(switchButton, VISIBLE);
} else {
apply(checkboxButton, VISIBLE);
apply(switchButton, GONE);
}
View.OnClickListener listener = view1 -> {
if (SettingsPreferences.isGenericSettingEnabled(context, preferenceCONST, true)) {
SettingsPreferences.disableGenericSetting(context, preferenceCONST); | AnalyticsHelper.getInstance(context).logScreenEvent(SCREEN_SETTINGS, settingsDisabledAction); | 1 |
BoD/bikey | wear/src/main/java/org/jraf/android/bikey/wearable/app/display/DisplayActivity.java | [
"public class CommConstants {\n /*\n * Ride.\n */\n\n public static final String PATH_RIDE = \"/ride\";\n\n /**\n * Indicates whether a ride is currently ongoing ({@code boolean}).\n */\n public static final String PATH_RIDE_ONGOING = PATH_RIDE + \"/ongoing\";\n\n /**\n * Measurement values ({@code boolean}).\n */\n public static final String PATH_RIDE_VALUES = PATH_RIDE + \"/values\";\n\n /**\n * Control (message path).\n */\n public static final String PATH_RIDE_CONTROL = PATH_RIDE + \"/control\";\n\n /**\n * Resume.\n */\n public static final byte[] PAYLOAD_RESUME = {0};\n\n /**\n * Pause.\n */\n public static final byte[] PAYLOAD_PAUSE = {1};\n\n\n /**\n * Start date offset ({@code long}). To get the current duration of the ride, add {@code System.currentTimeMillis()} to this value.\n */\n public static final String EXTRA_START_DATE_OFFSET = \"EXTRA_START_DATE_OFFSET\";\n\n /**\n * Current speed ({@code float}).\n */\n public static final String EXTRA_SPEED = \"EXTRA_SPEED\";\n\n /**\n * Total distance ({@code float}).\n */\n public static final String EXTRA_DISTANCE = \"EXTRA_DISTANCE\";\n\n /**\n * Current heart rate ({@code int}).\n */\n public static final String EXTRA_HEART_RATE = \"EXTRA_HEART_RATE\";\n\n /**\n * All-purpose value.\n */\n public static final String EXTRA_VALUE = \"EXTRA_VALUE\";\n\n\n /*\n * Preferences.\n */\n\n public static final String PATH_PREFERENCES = \"/preferences\";\n public static final String EXTRA_UNITS = \"EXTRA_UNITS\";\n}",
"public class WearCommHelper {\n private static final WearCommHelper INSTANCE = new WearCommHelper();\n\n private GoogleApiClient mGoogleApiClient;\n\n private WearCommHelper() {}\n\n public static WearCommHelper get() {\n return INSTANCE;\n }\n\n public void connect(Context context) {\n Log.d();\n if (mGoogleApiClient != null) return;\n mGoogleApiClient = new GoogleApiClient.Builder(context).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {\n @Override\n public void onConnected(Bundle connectionHint) {\n Log.d(\"connectionHint=\" + connectionHint);\n }\n\n @Override\n public void onConnectionSuspended(int cause) {\n Log.d(\"cause=\" + cause);\n // TODO reconnect\n }\n }).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {\n @Override\n public void onConnectionFailed(ConnectionResult result) {\n Log.w(\"result=\" + result);\n // TODO handle failures\n }\n }).addApi(Wearable.API).build();\n mGoogleApiClient.connect();\n }\n\n public void disconnect() {\n Log.d();\n if (mGoogleApiClient != null) mGoogleApiClient.disconnect();\n mGoogleApiClient = null;\n }\n\n public void sendMessage(final String path, @Nullable final byte[] payload) {\n Log.d(\"path=\" + path);\n HashSet<String> results = new HashSet<>();\n PendingResult<NodeApi.GetConnectedNodesResult> nodesPendingResult = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);\n nodesPendingResult.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {\n @Override\n public void onResult(NodeApi.GetConnectedNodesResult result) {\n for (Node node : result.getNodes()) {\n Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), path, payload);\n }\n }\n });\n }\n\n @WorkerThread\n public void sendMessageRideResume() {\n sendMessage(CommConstants.PATH_RIDE_CONTROL, CommConstants.PAYLOAD_RESUME);\n }\n\n @WorkerThread\n public void sendMessageRidePause() {\n sendMessage(CommConstants.PATH_RIDE_CONTROL, CommConstants.PAYLOAD_PAUSE);\n }\n\n\n /*\n * Ride values.\n */\n\n public void updateRideOngoing(boolean ongoing) {\n Log.d();\n updateValueNow(CommConstants.PATH_RIDE_ONGOING, ongoing);\n }\n\n public void clearRideValues() {\n Log.d();\n Wearable.DataApi.deleteDataItems(mGoogleApiClient, createUri(CommConstants.PATH_RIDE_VALUES));\n }\n\n public void updateRideValues(long startDateOffset, float speed, float distance, int heartRate) {\n Log.d(\"startDateOffset=\" + startDateOffset + \" speed=\" + speed + \" distance=\" + distance + \" heartRate=\" + heartRate);\n PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(CommConstants.PATH_RIDE_VALUES);\n\n DataMap dataMap = putDataMapRequest.getDataMap();\n dataMap.putLong(CommConstants.EXTRA_START_DATE_OFFSET, startDateOffset);\n dataMap.putFloat(CommConstants.EXTRA_SPEED, speed);\n dataMap.putFloat(CommConstants.EXTRA_DISTANCE, distance);\n dataMap.putInt(CommConstants.EXTRA_HEART_RATE, heartRate);\n\n PutDataRequest request = putDataMapRequest.asPutDataRequest();\n Wearable.DataApi.putDataItem(mGoogleApiClient, request);\n }\n\n public Bundle retrieveRideValues() {\n Log.d();\n Uri uri = createUri(CommConstants.PATH_RIDE_VALUES);\n PendingResult<DataItemBuffer> pendingResult = Wearable.DataApi.getDataItems(mGoogleApiClient, uri);\n DataItemBuffer dataItemBuffer = pendingResult.await();\n if (dataItemBuffer.getCount() == 0) {\n Log.d(\"No result\");\n dataItemBuffer.release();\n return null;\n }\n DataItem dataItem = dataItemBuffer.get(0);\n DataMap dataMap = DataMap.fromByteArray(dataItem.getData());\n Bundle res = dataMap.toBundle();\n Log.d(\"res=\" + res);\n dataItemBuffer.release();\n return res;\n }\n\n\n /*\n * Preferences.\n */\n\n public void updatePreferences() {\n Log.d();\n PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(CommConstants.PATH_PREFERENCES);\n DataMap dataMap = putDataMapRequest.getDataMap();\n dataMap.putString(CommConstants.EXTRA_UNITS, UnitUtil.getUnits());\n\n PutDataRequest request = putDataMapRequest.asPutDataRequest();\n Wearable.DataApi.putDataItem(mGoogleApiClient, request);\n }\n\n public String retrievePreferences(String prefExtraName) {\n Log.d();\n Uri uri = new Uri.Builder().scheme(\"wear\").path(CommConstants.PATH_PREFERENCES).build();\n PendingResult<DataItemBuffer> pendingResult = Wearable.DataApi.getDataItems(mGoogleApiClient, uri);\n DataItemBuffer dataItemBuffer = pendingResult.await();\n if (dataItemBuffer.getCount() == 0) {\n Log.d(\"No result\");\n dataItemBuffer.release();\n return null;\n }\n DataItem dataItem = dataItemBuffer.get(0);\n DataMap dataMap = DataMap.fromByteArray(dataItem.getData());\n String res = dataMap.getString(prefExtraName);\n Log.d(\"res=\" + res);\n dataItemBuffer.release();\n return res;\n }\n\n\n private void updateValueNow(String path, boolean value) {\n Log.d(\"path=\" + path + \" value=\" + value);\n PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(path);\n\n DataMap dataMap = putDataMapRequest.getDataMap();\n dataMap.putBoolean(CommConstants.EXTRA_VALUE, value);\n\n PutDataRequest request = putDataMapRequest.asPutDataRequest();\n Wearable.DataApi.putDataItem(mGoogleApiClient, request);\n }\n\n private void updateValueNow(String path, float value) {\n Log.d(\"path=\" + path + \" value=\" + value);\n PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(path);\n\n DataMap dataMap = putDataMapRequest.getDataMap();\n dataMap.putFloat(CommConstants.EXTRA_VALUE, value);\n\n PutDataRequest request = putDataMapRequest.asPutDataRequest();\n Wearable.DataApi.putDataItem(mGoogleApiClient, request);\n }\n\n private void updateValueNow(String path, long value) {\n Log.d(\"path=\" + path + \" value=\" + value);\n PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(path);\n\n DataMap dataMap = putDataMapRequest.getDataMap();\n dataMap.putLong(CommConstants.EXTRA_VALUE, value);\n\n PutDataRequest request = putDataMapRequest.asPutDataRequest();\n Wearable.DataApi.putDataItem(mGoogleApiClient, request);\n }\n\n private void updateValueNow(String path, int value) {\n Log.d(\"path=\" + path + \" value=\" + value);\n PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(path);\n\n DataMap dataMap = putDataMapRequest.getDataMap();\n dataMap.putInt(CommConstants.EXTRA_VALUE, value);\n\n PutDataRequest request = putDataMapRequest.asPutDataRequest();\n Wearable.DataApi.putDataItem(mGoogleApiClient, request);\n }\n\n public void addDataApiListener(DataApi.DataListener dataListener) {\n Wearable.DataApi.addListener(mGoogleApiClient, dataListener);\n }\n\n public void removeDataApiListener(DataApi.DataListener dataListener) {\n Wearable.DataApi.removeListener(mGoogleApiClient, dataListener);\n }\n\n private static Uri createUri(String path) {\n return new Uri.Builder().scheme(\"wear\").path(path).build();\n }\n}",
"public class FragmentCycler {\n private int mContainerResId;\n private List<String> mFragmentTags = new ArrayList<>(10);\n private List<Checkable> mTabs = new ArrayList<>(10);\n private List<Integer> mTitles = new ArrayList<>(10);\n private int mCurrentVisibleIndex = 0;\n private TextView mTxtTitle;\n private Map<String, Boolean> mEnabled = new HashMap<>();\n private long mUpdateTitleDelay;\n private final int mTabColorEnabled;\n private final int mTabColorDisabled;\n\n public FragmentCycler(int containerResId, TextView txtTitle, long updateTitleDelay, int tabColorEnabled, int tabColorDisabled) {\n mContainerResId = containerResId;\n mTxtTitle = txtTitle;\n mUpdateTitleDelay = updateTitleDelay;\n mTabColorEnabled = tabColorEnabled;\n mTabColorDisabled = tabColorDisabled;\n }\n\n /**\n * @param tabResId Optional, use 0 for no tab.\n */\n public void add(FragmentActivity activity, Fragment fragment, int tabResId, int titleResId) {\n String tag = getTag(fragment);\n FragmentManager fragmentManager = activity.getSupportFragmentManager();\n Fragment foundFragment = fragmentManager.findFragmentByTag(tag);\n if (foundFragment == null) {\n FragmentTransaction t = fragmentManager.beginTransaction();\n t.add(mContainerResId, fragment, tag);\n t.hide(fragment);\n t.commit();\n } else {\n FragmentTransaction t = fragmentManager.beginTransaction();\n t.hide(foundFragment);\n t.commit();\n }\n mFragmentTags.add(tag);\n View tab = activity.findViewById(tabResId);\n if (tab != null) {\n mTabs.add((Checkable) tab);\n tab.setOnClickListener(mTabOnClickListener);\n }\n mTitles.add(titleResId);\n }\n\n public void show(FragmentActivity activity) {\n String tag = mFragmentTags.get(mCurrentVisibleIndex);\n FragmentManager fragmentManager = activity.getSupportFragmentManager();\n fragmentManager.executePendingTransactions();\n Fragment fragment = fragmentManager.findFragmentByTag(tag);\n FragmentTransaction t = fragmentManager.beginTransaction();\n t.show(fragment);\n t.commit();\n if (!mTabs.isEmpty()) {\n Checkable checkable = mTabs.get(mCurrentVisibleIndex);\n checkable.setChecked(true);\n }\n updateTitle();\n }\n\n public void cycle(FragmentActivity activity) {\n // Find the next *enabled* fragment to show\n int newIndex = mCurrentVisibleIndex;\n do {\n newIndex = (newIndex + 1) % mFragmentTags.size();\n } while (!isEnabled(newIndex));\n setCurrentVisibleIndex(activity, newIndex);\n }\n\n private void setCurrentVisibleIndex(FragmentActivity activity, int newIndex) {\n int previousVisibleIndex = mCurrentVisibleIndex;\n mCurrentVisibleIndex = newIndex;\n String hideTag = mFragmentTags.get(previousVisibleIndex);\n String showTag = mFragmentTags.get(mCurrentVisibleIndex);\n FragmentManager fragmentManager = activity.getSupportFragmentManager();\n Fragment showFragment = fragmentManager.findFragmentByTag(showTag);\n Fragment hideFragment = fragmentManager.findFragmentByTag(hideTag);\n FragmentTransaction t = fragmentManager.beginTransaction();\n t.hide(hideFragment);\n t.show(showFragment);\n t.commit();\n if (!mTabs.isEmpty()) {\n Checkable prevCheckable = mTabs.get(previousVisibleIndex);\n prevCheckable.setChecked(false);\n Checkable curCheckable = mTabs.get(mCurrentVisibleIndex);\n curCheckable.setChecked(true);\n }\n updateTitle();\n }\n\n private void updateTitle() {\n HandlerUtil.getMainHandler().postDelayed(new Runnable() {\n @Override\n public void run() {\n mTxtTitle.setText(mTitles.get(mCurrentVisibleIndex));\n }\n }, mUpdateTitleDelay);\n }\n\n private String getTag(Fragment fragment) {\n return getTag(fragment.getClass());\n }\n\n private String getTag(Class<? extends Fragment> fragmentClass) {\n return fragmentClass.getName();\n }\n\n private OnClickListener mTabOnClickListener = new OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!(v instanceof Checkable)) return;\n Checkable checkable = (Checkable) v;\n if (!checkable.isChecked()) checkable.setChecked(true);\n int newIndex = mTabs.indexOf(checkable);\n if (mCurrentVisibleIndex == newIndex) return;\n setCurrentVisibleIndex((FragmentActivity) v.getContext(), newIndex);\n }\n };\n\n public int getCurrentVisibleIndex() {\n return mCurrentVisibleIndex;\n }\n\n public void setCurrentVisibleIndex(int currentVisibleIndex) {\n mCurrentVisibleIndex = currentVisibleIndex;\n }\n\n public void setEnabled(Context context, Class<? extends Fragment> fragmentClass, boolean enabled) {\n String tag = getTag(fragmentClass);\n mEnabled.put(tag, enabled);\n\n int index = mFragmentTags.indexOf(tag);\n if (!mTabs.isEmpty()) {\n TextView textView = (TextView) mTabs.get(index);\n textView.setTextColor(enabled ? mTabColorEnabled : mTabColorDisabled);\n }\n }\n\n private boolean isEnabled(int index) {\n Boolean enabled = mEnabled.get(mFragmentTags.get(index));\n if (enabled == null) {\n // Treat no value (default) as enabled.\n enabled = true;\n }\n return enabled;\n }\n}",
"public class CurrentTimeDisplayFragment extends SimpleDisplayFragment {\n protected static final long REFRESH_RATE = 30 * 1000;\n private Handler mHandler = new Handler();\n private DateFormat mTimeFormat;\n\n public static CurrentTimeDisplayFragment newInstance() {\n return new CurrentTimeDisplayFragment();\n }\n\n @Override\n public void onStart() {\n super.onStart();\n mTimeFormat = android.text.format.DateFormat.getTimeFormat(getActivity());\n mHandler.post(mShowTimeRunnable);\n }\n\n @Override\n public void onStop() {\n mHandler.removeCallbacks(mShowTimeRunnable);\n super.onStop();\n }\n\n private Runnable mShowTimeRunnable = new Runnable() {\n @Override\n public void run() {\n setText(mTimeFormat.format(new Date()));\n mHandler.postDelayed(mShowTimeRunnable, REFRESH_RATE);\n }\n };\n}",
"public class ElapsedTimeDisplayFragment extends SimpleDisplayFragment {\n private Chronometer mChronometer;\n private long mRideStartDateOffset;\n\n public static ElapsedTimeDisplayFragment newInstance() {\n return new ElapsedTimeDisplayFragment();\n }\n\n @Override\n protected int getLayoutResId() {\n return R.layout.display_elapsed_time;\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n mChronometer = (Chronometer) view.findViewById(R.id.chronometer);\n }\n\n public void setStartDateOffset(long rideStartDateOffset) {\n if (mRideStartDateOffset != rideStartDateOffset) {\n mRideStartDateOffset = rideStartDateOffset;\n\n mChronometer.setBase(SystemClock.elapsedRealtime() - (System.currentTimeMillis() + mRideStartDateOffset));\n mChronometer.start();\n }\n }\n}",
"public class SpeedDisplayFragment extends SimpleDisplayFragment {\n public static SpeedDisplayFragment newInstance() {\n return new SpeedDisplayFragment();\n }\n\n public void setSpeed(float speed) {\n setText(UnitUtil.formatSpeed(speed));\n }\n}",
"public class TotalDistanceDisplayFragment extends SimpleDisplayFragment {\n public static TotalDistanceDisplayFragment newInstance() {\n return new TotalDistanceDisplayFragment();\n }\n\n public void setTotalDistance(float rideDistance) {\n setText(UnitUtil.formatDistance(rideDistance));\n }\n}"
] | import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import org.jraf.android.bikey.R;
import org.jraf.android.bikey.common.wear.CommConstants;
import org.jraf.android.bikey.common.wear.WearCommHelper;
import org.jraf.android.bikey.common.widget.fragmentcycler.FragmentCycler;
import org.jraf.android.bikey.databinding.DisplayBinding;
import org.jraf.android.bikey.wearable.app.display.fragment.currenttime.CurrentTimeDisplayFragment;
import org.jraf.android.bikey.wearable.app.display.fragment.elapsedtime.ElapsedTimeDisplayFragment;
import org.jraf.android.bikey.wearable.app.display.fragment.speed.SpeedDisplayFragment;
import org.jraf.android.bikey.wearable.app.display.fragment.totaldistance.TotalDistanceDisplayFragment;
import org.jraf.android.util.log.Log; | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2014 Benoit 'BoD' Lubek ([email protected])
*
* 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.jraf.android.bikey.wearable.app.display;
public class DisplayActivity extends FragmentActivity {
private DisplayBinding mBinding;
private FragmentCycler mFragmentCycler;
private SpeedDisplayFragment mSpeedDisplayFragment;
private ElapsedTimeDisplayFragment mElapsedTimeDisplayFragment;
private TotalDistanceDisplayFragment mTotalDistanceDisplayFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mBinding = DataBindingUtil.setContentView(this, R.layout.display);
mBinding.vieFragmentCycle.setOnTouchListener(this::fragmentCycleOnTouch);
setupFragments();
retrieveRideValues();
}
private void retrieveRideValues() {
// Retrieve the latest values now, to show the elapsed time
new AsyncTask<Void, Void, Bundle>() {
@Override
protected Bundle doInBackground(Void... params) { | return WearCommHelper.get().retrieveRideValues(); | 1 |
awslabs/amazon-sqs-java-messaging-lib | src/main/java/com/amazon/sqs/javamessaging/SQSMessageProducer.java | [
"public class SQSBytesMessage extends SQSMessage implements BytesMessage {\n private static final Log LOG = LogFactory.getLog(SQSBytesMessage.class);\n\n private byte[] bytes;\n\n private ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();\n\n private DataInputStream dataIn;\n \n private DataOutputStream dataOut = new DataOutputStream(bytesOut);\n\n /**\n * Convert received SQSMessage into BytesMessage.\n */\n public SQSBytesMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException {\n super(acknowledger, queueUrl, sqsMessage);\n try {\n /** Bytes is set by the reset() */\n dataOut.write(Base64.decode(sqsMessage.getBody()));\n /** Makes it read-only */\n reset();\n } catch (IOException e) {\n LOG.error(\"IOException: Message cannot be written\", e);\n throw convertExceptionToJMSException(e);\n } catch (Exception e) {\n LOG.error(\"Unexpected exception: \", e);\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Create new empty BytesMessage to send.\n */\n public SQSBytesMessage() throws JMSException {\n super();\n }\n \n /**\n * Gets the number of bytes of the message body when the message is in\n * read-only mode. The value returned can be used to allocate a byte array.\n * The value returned is the entire length of the message body, regardless\n * of where the pointer for reading the message is currently located.\n * \n * @return number of bytes in the message\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public long getBodyLength() throws JMSException {\n checkCanRead();\n return bytes.length;\n }\n \n /**\n * Reads a <code>boolean</code> from the bytes message stream.\n * \n * @return the <code>boolean</code> value\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public boolean readBoolean() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readBoolean();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads a signed 8-bit value from the bytes message stream.\n * \n * @return the next byte from the bytes message stream as a signed 8-bit\n * byte\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public byte readByte() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readByte();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads an unsigned 8-bit value from the bytes message stream.\n * \n * @return the next byte from the bytes message stream, interpreted as an\n * unsigned 8-bit number\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public int readUnsignedByte() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readUnsignedByte();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads a signed 16-bit number from the bytes message stream.\n * \n * @return the next two bytes from the bytes message stream, interpreted as\n * a signed 16-bit number\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public short readShort() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readShort();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads an unsigned 16-bit number from the bytes message stream.\n * \n * @return the next two bytes from the bytes message stream, interpreted as\n * an unsigned 16-bit integer\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public int readUnsignedShort() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readUnsignedShort();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads a Unicode character value from the bytes message stream. \n * \n * @return a Unicode character from the bytes message stream\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public char readChar() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readChar();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads a 32-bit integer from the bytes message stream.\n * \n * @return the next four bytes from the bytes message stream, interpreted as an int\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public int readInt() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readInt();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads a 64-bit integer from the bytes message stream.\n * \n * @return a 64-bit integer value from the bytes message stream, interpreted as a long\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public long readLong() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readLong();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads a <code>float</code> from the bytes message stream.\n * \n * @return a <code>float</code> value from the bytes message stream\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public float readFloat() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readFloat();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads a <code>double</code> from the bytes message stream. \n * \n * @return a <code>double</code> value from the bytes message stream\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public double readDouble() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readDouble();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads a string that has been encoded using a UTF-8 format from\n * the bytes message stream\n * \n * @return a Unicode string from the bytes message stream\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageEOFException\n * If unexpected end of bytes stream has been reached.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public String readUTF() throws JMSException {\n checkCanRead();\n try {\n return dataIn.readUTF();\n } catch (EOFException e) {\n throw new MessageEOFException(e.getMessage());\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Reads a byte array from the bytes message stream.\n * <P>\n * If the length of array value is less than the number of bytes remaining\n * to be read from the stream, the array should be filled. A subsequent call\n * reads the next increment, and so on.\n * <P>\n * If the number of bytes remaining in the stream is less than the length of\n * array value, the bytes should be read into the array. The return value of\n * the total number of bytes read will be less than the length of the array,\n * indicating that there are no more bytes left to be read from the stream.\n * The next read of the stream returns -1.\n * \n * @param value\n * The buffer into which the data is read\n * @return the total number of bytes read into the buffer, or -1 if there is\n * no more data because the end of the stream has been reached\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public int readBytes(byte[] value) throws JMSException {\n return readBytes(value, value.length);\n }\n \n \n /**\n * Reads a portion of the bytes message stream.\n * <P>\n * If the length of array value is less than the number of bytes remaining\n * to be read from the stream, the array should be filled. A subsequent call\n * reads the next increment, and so on.\n * <P>\n * If the number of bytes remaining in the stream is less than the length of\n * array value, the bytes should be read into the array. The return value of\n * the total number of bytes read will be less than the length of the array,\n * indicating that there are no more bytes left to be read from the stream.\n * The next read of the stream returns -1.\n * <P>\n * If length is negative, then an <code>IndexOutOfBoundsException</code> is\n * thrown. No bytes will be read from the stream for this exception case.\n * \n * @param value\n * The buffer into which the data is read\n * @param length\n * The number of bytes to read; must be less than or equal to\n * value.length\n * @return the total number of bytes read into the buffer, or -1 if there is\n * no more data because the end of the stream has been reached\n * @throws JMSException\n * If the JMS provider fails to read the message due to some\n * internal error.\n * @throws MessageNotReadableException\n * If the message is in write-only mode.\n */\n @Override\n public int readBytes(byte[] value, int length) throws JMSException {\n if (length < 0) {\n throw new IndexOutOfBoundsException(\"Length bytes to read can't be smaller than 0 but was \" +\n length);\n }\n checkCanRead();\n try {\n /**\n * Almost copy of readFully implementation except that EOFException\n * is not thrown if the stream is at the end of file and no byte is\n * available\n */\n int n = 0;\n while (n < length) {\n int count = dataIn.read(value, n, length - n);\n if (count < 0) {\n break;\n }\n n += count;\n }\n /**\n * JMS specification mentions that the next read of the stream\n * returns -1 if the previous read consumed the byte stream and\n * there are no more bytes left to be read from the stream\n */\n if (n == 0 && length > 0) {\n n = -1;\n }\n return n;\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a <code>boolean</code> to the bytes message stream\n * \n * @param value\n * The <code>boolean</code> value to be written\n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeBoolean(boolean value) throws JMSException {\n checkCanWrite();\n try {\n dataOut.writeBoolean(value);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a <code>byte</code> to the bytes message stream\n * \n * @param value\n * The <code>byte</code> value to be written\n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeByte(byte value) throws JMSException {\n checkCanWrite();\n try {\n dataOut.writeByte(value);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a <code>short</code> to the bytes message stream\n * \n * @param value\n * The <code>short</code> value to be written\n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeShort(short value) throws JMSException {\n checkCanWrite();\n try {\n dataOut.writeShort(value);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a <code>char</code> to the bytes message stream\n * \n * @param value\n * The <code>char</code> value to be written\n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeChar(char value) throws JMSException {\n checkCanWrite();\n try {\n dataOut.writeChar(value);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a <code>int</code> to the bytes message stream\n * \n * @param value\n * The <code>int</code> value to be written\n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeInt(int value) throws JMSException {\n checkCanWrite();\n try {\n dataOut.writeInt(value);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a <code>long</code> to the bytes message stream\n * \n * @param value\n * The <code>long</code> value to be written\n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeLong(long value) throws JMSException {\n checkCanWrite();\n try {\n dataOut.writeLong(value);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a <code>float</code> to the bytes message stream\n * \n * @param value\n * The <code>float</code> value to be written\n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeFloat(float value) throws JMSException {\n checkCanWrite();\n try {\n dataOut.writeFloat(value);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a <code>double</code> to the bytes message stream\n * \n * @param value\n * The <code>double</code> value to be written\n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeDouble(double value) throws JMSException {\n checkCanWrite();\n try {\n dataOut.writeDouble(value);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a string that has been encoded using a UTF-8 format to the bytes\n * message stream\n * \n * @param value\n * The <code>String</code> value to be written\n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeUTF(String value) throws JMSException {\n checkCanWrite();\n try {\n dataOut.writeUTF(value);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a byte array to the bytes\n * message stream\n * \n * @param value\n * The byte array value to be written \n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeBytes(byte[] value) throws JMSException {\n checkCanWrite();\n try {\n dataOut.write(value);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes a portion of a byte array to the bytes message stream.\n * \n * @param value\n * The portion of byte array value to be written\n * @param offset\n * The initial offset within the byte array\n * @param length\n * The number of bytes to use \n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void writeBytes(byte[] value, int offset, int length) throws JMSException {\n checkCanWrite();\n try {\n dataOut.write(value, offset, length);\n } catch (IOException e) {\n throw convertExceptionToJMSException(e);\n }\n }\n \n /**\n * Writes an object to the bytes message stream.\n * <P>\n * This method works only for the boxed primitive object types\n * (Integer, Double, Long ...), String objects, and byte arrays.\n * \n * @param value\n * The Java object to be written\n * @throws JMSException\n * If the JMS provider fails to write the message due to some\n * internal error.\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n * @throws MessageFormatException\n * If the object is of an invalid type.\n * @throws NullPointerException\n * If the object is null.\n */\n @Override\n public void writeObject(Object value) throws JMSException {\n if (value == null) {\n throw new NullPointerException(\"Cannot write null value of object\");\n }\n if (value instanceof Boolean) {\n writeBoolean((Boolean) value);\n } else if (value instanceof Character) {\n writeChar((Character) value);\n } else if (value instanceof Byte) {\n writeByte((Byte) value);\n } else if (value instanceof Short) {\n writeShort((Short) value);\n } else if (value instanceof Integer) {\n writeInt((Integer) value);\n } else if (value instanceof Long) {\n writeLong((Long) value);\n } else if (value instanceof Float) {\n writeFloat((Float) value);\n } else if (value instanceof Double) {\n writeDouble((Double) value);\n } else if (value instanceof String) {\n writeUTF(value.toString());\n } else if (value instanceof byte[]) {\n writeBytes((byte[]) value);\n } else {\n throw new MessageFormatException(\"Cannot write non-primitive type: \" + value.getClass());\n }\n }\n\n /**\n * Puts the message body in read-only mode and repositions the stream of\n * bytes to the beginning.\n */\n @Override\n public void reset() throws JMSException {\n\n if (dataOut != null) {\n bytes = bytesOut.toByteArray();\n dataOut = null;\n bytesOut = null;\n }\n dataIn = new DataInputStream(new ByteArrayInputStream(bytes));\n }\n \n /**\n * When the message is first created, and when clearBody is called, the body\n * of the message is in write-only mode. After the first call to reset is\n * made, the message body goes to read-only mode. when the message is sent,\n * the sender can retain and modify it without affecting the sent message.\n * If clearBody is called on a message, when it is in read-only mode, the\n * message body is cleared and the message goes to write-only mode.\n */\n @Override\n public void clearBody() throws JMSException {\n bytes = null;\n dataIn = null;\n bytesOut = new ByteArrayOutputStream();\n dataOut = new DataOutputStream(bytesOut);\n setBodyWritePermissions(true);\n }\n \n /**\n * Reads the body of message, which can be either the body returned from the\n * the receives message as bytes or the bytes put in bytesOut if it is a\n * sent message.\n * \n * @return value The body returned as byte array\n */\n public byte[] getBodyAsBytes() throws JMSException {\n if (bytes != null) {\n return Arrays.copyOf(bytes, bytes.length);\n } else {\n return bytesOut.toByteArray();\n }\n }\n\n void checkCanRead() throws JMSException {\n if (bytes == null) {\n throw new MessageNotReadableException(\"Message is not readable\");\n }\n }\n\n void checkCanWrite() throws JMSException {\n if (dataOut == null) {\n throw new MessageNotWriteableException(\"Message is not writeable\");\n }\n }\n\n /*\n * Unit Test Utility Function\n */\n\n void setDataIn(DataInputStream dataIn) {\n this.dataIn = dataIn;\n }\n\n void setDataOut(DataOutputStream dataOut) {\n this.dataOut = dataOut;\n }\n}",
"public class SQSMessage implements Message {\n \n private static final Charset DEFAULT_CHARSET = Charset.forName(\"UTF-8\");\n \n // Define constant message types.\n public static final String BYTE_MESSAGE_TYPE = \"byte\";\n public static final String OBJECT_MESSAGE_TYPE = \"object\";\n public static final String TEXT_MESSAGE_TYPE = \"text\";\n public static final String JMS_SQS_MESSAGE_TYPE = \"JMS_SQSMessageType\";\n public static final String JMS_SQS_REPLY_TO_QUEUE_NAME = \"JMS_SQSReplyToQueueName\";\n public static final String JMS_SQS_REPLY_TO_QUEUE_URL = \"JMS_SQSReplyToQueueURL\";\n public static final String JMS_SQS_CORRELATION_ID = \"JMS_SQSCorrelationID\";\n \n // Default JMS Message properties\n private int deliveryMode = Message.DEFAULT_DELIVERY_MODE;\n private int priority = Message.DEFAULT_PRIORITY;\n private long timestamp;\n private boolean redelivered;\n private String correlationID;\n private long expiration = Message.DEFAULT_TIME_TO_LIVE;\n private String messageID;\n private String type;\n private SQSQueueDestination replyTo;\n private Destination destination;\n\n private final Map<String, JMSMessagePropertyValue> properties = new HashMap<String, JMSMessagePropertyValue>();\n\n private boolean writePermissionsForProperties;\n private boolean writePermissionsForBody;\n\n /**\n * Function for acknowledging message. \n */\n private Acknowledger acknowledger;\n \n /**\n * Original SQS Message ID.\n */\n private String sqsMessageID;\n\n /**\n * QueueUrl the message came from.\n */\n private String queueUrl;\n /**\n * Original SQS Message receipt handle.\n */\n private String receiptHandle;\n\n /**\n * This is called at the receiver side to create a\n * JMS message from the SQS message received.\n */\n SQSMessage(Acknowledger acknowledger, String queueUrl, com.amazonaws.services.sqs.model.Message sqsMessage) throws JMSException{\n this.acknowledger = acknowledger;\n this.queueUrl = queueUrl;\n receiptHandle = sqsMessage.getReceiptHandle();\n this.setSQSMessageId(sqsMessage.getMessageId());\n Map<String,String> systemAttributes = sqsMessage.getAttributes();\n int receiveCount = Integer.parseInt(systemAttributes.get(APPROXIMATE_RECEIVE_COUNT));\n \n /**\n * JMSXDeliveryCount is set based on SQS ApproximateReceiveCount\n * attribute.\n */\n properties.put(JMSX_DELIVERY_COUNT, new JMSMessagePropertyValue(\n receiveCount, INT));\n if (receiveCount > 1) {\n setJMSRedelivered(true);\n }\n if (sqsMessage.getMessageAttributes() != null) {\n addMessageAttributes(sqsMessage);\n }\n\n // map the SequenceNumber, MessageGroupId and MessageDeduplicationId to JMS specific properties\n mapSystemAttributeToJmsMessageProperty(systemAttributes, SEQUENCE_NUMBER, JMS_SQS_SEQUENCE_NUMBER);\n mapSystemAttributeToJmsMessageProperty(systemAttributes, MESSAGE_DEDUPLICATION_ID, JMS_SQS_DEDUPLICATION_ID);\n mapSystemAttributeToJmsMessageProperty(systemAttributes, MESSAGE_GROUP_ID, JMSX_GROUP_ID);\n\n writePermissionsForBody = false;\n writePermissionsForProperties = false;\n }\n \n private void mapSystemAttributeToJmsMessageProperty(Map<String,String> systemAttributes, String systemAttributeName, String jmsMessagePropertyName) throws JMSException {\n String systemAttributeValue = systemAttributes.get(systemAttributeName);\n if (systemAttributeValue != null) {\n properties.put(jmsMessagePropertyName, new JMSMessagePropertyValue(systemAttributeValue, STRING));\n }\n }\n\n /**\n * Create new empty Message to send. SQSMessage cannot be sent without any\n * payload. One of SQSTextMessage, SQSObjectMessage, or SQSBytesMessage\n * should be used to add payload.\n */\n SQSMessage() {\n writePermissionsForBody = true;\n writePermissionsForProperties = true;\n }\n\n private void addMessageAttributes(com.amazonaws.services.sqs.model.Message sqsMessage) throws JMSException {\n for (Entry<String, MessageAttributeValue> entry : sqsMessage.getMessageAttributes().entrySet()) {\n properties.put(entry.getKey(), new JMSMessagePropertyValue(\n entry.getValue().getStringValue(), entry.getValue().getDataType()));\n }\n }\n\n protected void checkPropertyWritePermissions() throws JMSException {\n if (!writePermissionsForProperties) {\n throw new MessageNotWriteableException(\"Message properties are not writable\");\n }\n }\n \n protected void checkBodyWritePermissions() throws JMSException {\n if (!writePermissionsForBody) {\n throw new MessageNotWriteableException(\"Message body is not writable\");\n }\n }\n \n protected static JMSException convertExceptionToJMSException(Exception e) {\n JMSException ex = new JMSException(e.getMessage());\n ex.initCause(e);\n return ex;\n }\n \n protected static MessageFormatException convertExceptionToMessageFormatException(Exception e) {\n MessageFormatException ex = new MessageFormatException(e.getMessage());\n ex.initCause(e);\n return ex;\n }\n \n protected void setBodyWritePermissions(boolean enable) {\n writePermissionsForBody = enable;\n }\n \n /**\n * Get SQS Message Group Id (applicable for FIFO queues, available also as JMS property 'JMSXGroupId')\n * @throws JMSException \n */\n public String getSQSMessageGroupId() throws JMSException {\n return getStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID);\n }\n \n /**\n * Get SQS Message Deduplication Id (applicable for FIFO queues, available also as JMS property 'JMS_SQS_DeduplicationId')\n * @throws JMSException \n */\n public String getSQSMessageDeduplicationId() throws JMSException {\n return getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID);\n }\n \n /**\n * Get SQS Message Sequence Number (applicable for FIFO queues, available also as JMS property 'JMS_SQS_SequenceNumber')\n * @throws JMSException \n */\n public String getSQSMessageSequenceNumber() throws JMSException {\n return getStringProperty(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER);\n }\n \n /**\n * Get SQS Message Id.\n * \n * @return SQS Message Id.\n */\n public String getSQSMessageId() {\n return sqsMessageID;\n }\n \n /**\n * Set SQS Message Id, used on send.\n * \n * @param sqsMessageID\n * messageId assigned by SQS during send.\n */\n public void setSQSMessageId(String sqsMessageID) throws JMSException {\n this.sqsMessageID = sqsMessageID;\n this.setJMSMessageID(String.format(SQSMessagingClientConstants.MESSAGE_ID_FORMAT, sqsMessageID));\n }\n \n /**\n * Get SQS Message receiptHandle.\n * \n * @return SQS Message receiptHandle.\n */\n public String getReceiptHandle() {\n return receiptHandle;\n }\n\n /**\n * Get queueUrl the message came from.\n * \n * @return queueUrl.\n */\n public String getQueueUrl() {\n return queueUrl;\n }\n \n /**\n * Gets the message ID.\n * <P>\n * The JMSMessageID header field contains a value that uniquely identifies\n * each message sent by a provider. It is set to SQS messageId with the\n * prefix 'ID:'.\n * \n * @return the ID of the message.\n */\n @Override\n public String getJMSMessageID() throws JMSException {\n return messageID;\n }\n \n /**\n * Sets the message ID. It should have prefix 'ID:'.\n * <P>\n * Set when a message is sent. This method can be used to change the value\n * for a message that has been received.\n * \n * @param id\n * The ID of the message.\n */\n @Override\n public void setJMSMessageID(String id) throws JMSException {\n messageID = id;\n }\n\n @Override\n public long getJMSTimestamp() throws JMSException {\n return timestamp;\n }\n\n @Override\n public void setJMSTimestamp(long timestamp) throws JMSException {\n this.timestamp = timestamp;\n }\n\n @Override\n public byte[] getJMSCorrelationIDAsBytes() throws JMSException {\n return correlationID != null ? correlationID.getBytes(DEFAULT_CHARSET) : null;\n }\n\n @Override\n public void setJMSCorrelationIDAsBytes(byte[] correlationID) throws JMSException {\n try {\n this.correlationID = correlationID != null ? new String(correlationID, \"UTF-8\") : null;\n } catch (UnsupportedEncodingException e) {\n throw new JMSException(e.getMessage());\n }\n }\n\n @Override\n public void setJMSCorrelationID(String correlationID) throws JMSException {\n this.correlationID = correlationID;\n }\n\n @Override\n public String getJMSCorrelationID() throws JMSException {\n return correlationID;\n }\n\n @Override\n public Destination getJMSReplyTo() throws JMSException {\n return replyTo;\n }\n\n @Override\n public void setJMSReplyTo(Destination replyTo) throws JMSException {\n if (replyTo != null && !(replyTo instanceof SQSQueueDestination)) {\n throw new IllegalArgumentException(\"The replyTo Destination must be a SQSQueueDestination\");\n }\n this.replyTo = (SQSQueueDestination)replyTo;\n }\n \n /**\n * Gets the Destination object for this message.\n * <P>\n * The JMSDestination header field contains the destination to which the\n * message is being sent.\n * <P>\n * When a message is sent, this field is ignored. After completion of the\n * send or publish method, the field holds the destination specified by the\n * method.\n * <P>\n * When a message is received, its JMSDestination value must be equivalent\n * to the value assigned when it was sent.\n * \n * @return The destination of this message.\n */\n @Override\n public Destination getJMSDestination() throws JMSException {\n return destination;\n }\n \n /**\n * Sets the Destination object for this message.\n * <P>\n * Set when a message is sent. This method can be used to change the value\n * for a message that has been received.\n * \n * @param destination\n * The destination for this message.\n */\n @Override\n public void setJMSDestination(Destination destination) throws JMSException {\n this.destination = destination;\n }\n\n @Override\n public int getJMSDeliveryMode() throws JMSException {\n return deliveryMode;\n }\n\n @Override\n public void setJMSDeliveryMode(int deliveryMode) throws JMSException {\n this.deliveryMode = deliveryMode;\n }\n\n @Override\n public boolean getJMSRedelivered() throws JMSException {\n return redelivered;\n }\n\n @Override\n public void setJMSRedelivered(boolean redelivered) throws JMSException {\n this.redelivered = redelivered;\n }\n\n @Override\n public String getJMSType() throws JMSException {\n return type;\n }\n\n @Override\n public void setJMSType(String type) throws JMSException {\n this.type = type;\n }\n\n @Override\n public long getJMSExpiration() throws JMSException {\n return expiration;\n }\n\n @Override\n public void setJMSExpiration(long expiration) throws JMSException {\n this.expiration = expiration;\n }\n\n @Override\n public int getJMSPriority() throws JMSException {\n return priority;\n }\n\n @Override\n public void setJMSPriority(int priority) throws JMSException {\n this.priority = priority;\n }\n \n /**\n * Clears a message's properties and set the write permissions for\n * properties. The message's header fields and body are not cleared.\n */\n @Override\n public void clearProperties() throws JMSException {\n properties.clear();\n writePermissionsForProperties = true;\n }\n \n /**\n * Indicates whether a property value exists for the given property name.\n * \n * @param name\n * The name of the property.\n * @return true if the property exists.\n */\n @Override\n public boolean propertyExists(String name) throws JMSException {\n return properties.containsKey(name);\n }\n\n /**\n * Get the value for a property that represents a java primitive(e.g. int or\n * long).\n * \n * @param property\n * The name of the property to get.\n * @param type\n * The type of the property.\n * @return the converted value for the property.\n * @throws JMSException\n * On internal error.\n * @throws MessageFormatException\n * If the property cannot be converted to the specified type.\n * @throws NullPointerException\n * and NumberFormatException when property name or value is\n * null. Method throws same exception as primitives\n * corresponding valueOf(String) method.\n */\n <T> T getPrimitiveProperty(String property, Class<T> type) throws JMSException {\n if (property == null) {\n throw new NullPointerException(\"Property name is null\");\n }\n Object value = getObjectProperty(property);\n if (value == null) {\n return handleNullPropertyValue(property, type);\n }\n T convertedValue = TypeConversionSupport.convert(value, type);\n if (convertedValue == null) {\n throw new MessageFormatException(\"Property \" + property + \" was \" + value.getClass().getName() +\n \" and cannot be read as \" + type.getName());\n }\n return convertedValue;\n }\n\n @SuppressWarnings(\"unchecked\")\n private <T> T handleNullPropertyValue(String name, Class<T> clazz) {\n if (clazz == String.class) {\n return null;\n } else if (clazz == Boolean.class) {\n return (T) Boolean.FALSE;\n } else if (clazz == Double.class || clazz == Float.class) {\n throw new NullPointerException(\"Value of property with name \" + name + \" is null.\");\n } else {\n throw new NumberFormatException(\"Value of property with name \" + name + \" is null.\");\n }\n }\n \n /**\n * Returns the value of the <code>boolean</code> property with the specified\n * name.\n * \n * @param name\n * The name of the property to get.\n * @return the <code>boolean</code> property value for the specified name.\n * @throws JMSException\n * On internal error.\n * @throws MessageFormatException\n * If the property cannot be converted to the specified type.\n * @throws NullPointerException\n * When property name is null.\n */\n @Override\n public boolean getBooleanProperty(String name) throws JMSException {\n return getPrimitiveProperty(name, Boolean.class);\n }\n \n /**\n * Returns the value of the <code>byte</code> property with the specified\n * name.\n * \n * @param name\n * The name of the property to get.\n * @return the <code>byte</code> property value for the specified name.\n * @throws JMSException\n * On internal error.\n * @throws MessageFormatException\n * If the property cannot be converted to the specified type.\n * @throws NullPointerException\n * When property name is null.\n * @throws NumberFormatException\n * When property value is null.\n */\n @Override\n public byte getByteProperty(String name) throws JMSException {\n return getPrimitiveProperty(name, Byte.class);\n }\n \n /**\n * Returns the value of the <code>short</code> property with the specified\n * name.\n * \n * @param name\n * The name of the property to get.\n * @return the <code>short</code> property value for the specified name.\n * @throws JMSException\n * On internal error.\n * @throws MessageFormatException\n * If the property cannot be converted to the specified type.\n * @throws NullPointerException\n * When property name is null.\n * @throws NumberFormatException\n * When property value is null.\n */\n @Override\n public short getShortProperty(String name) throws JMSException {\n return getPrimitiveProperty(name, Short.class);\n }\n \n /**\n * Returns the value of the <code>int</code> property with the specified\n * name.\n * \n * @param name\n * The name of the property to get.\n * @return the <code>int</code> property value for the specified name.\n * @throws JMSException\n * On internal error.\n * @throws MessageFormatException\n * If the property cannot be converted to the specified type.\n * @throws NullPointerException\n * When property name is null.\n * @throws NumberFormatException\n * When property value is null.\n */\n @Override\n public int getIntProperty(String name) throws JMSException {\n return getPrimitiveProperty(name, Integer.class);\n }\n \n /**\n * Returns the value of the <code>long</code> property with the specified\n * name.\n * \n * @param name\n * The name of the property to get.\n * @return the <code>long</code> property value for the specified name.\n * @throws JMSException\n * On internal error.\n * @throws MessageFormatException\n * If the property cannot be converted to the specified type.\n * @throws NullPointerException\n * When property name is null.\n * @throws NumberFormatException\n * When property value is null.\n */\n @Override\n public long getLongProperty(String name) throws JMSException {\n return getPrimitiveProperty(name, Long.class);\n }\n \n /**\n * Returns the value of the <code>float</code> property with the specified\n * name.\n * \n * @param name\n * The name of the property to get.\n * @return the <code>float</code> property value for the specified name.\n * @throws JMSException\n * Wn internal error.\n * @throws MessageFormatException\n * If the property cannot be converted to the specified type.\n * @throws NullPointerException\n * When property name or value is null.\n */\n @Override\n public float getFloatProperty(String name) throws JMSException {\n return getPrimitiveProperty(name, Float.class);\n }\n \n /**\n * Returns the value of the <code>double</code> property with the specified\n * name.\n * \n * @param name\n * The name of the property to get.\n * @return the <code>double</code> property value for the specified name.\n * @throws JMSException\n * On internal error.\n * @throws MessageFormatException\n * If the property cannot be converted to the specified type.\n * @throws NullPointerException\n * When property name or value is null.\n */\n @Override\n public double getDoubleProperty(String name) throws JMSException {\n return getPrimitiveProperty(name, Double.class);\n }\n \n /**\n * Returns the value of the <code>String</code> property with the specified\n * name.\n * \n * @param name\n * The name of the property to get.\n * @return the <code>String</code> property value for the specified name.\n * @throws JMSException\n * On internal error.\n * @throws MessageFormatException\n * If the property cannot be converted to the specified type.\n * @throws NullPointerException\n * When property name is null.\n */\n @Override\n public String getStringProperty(String name) throws JMSException {\n return getPrimitiveProperty(name, String.class);\n }\n \n /**\n * Returns the value of the Java object property with the specified name.\n * <P>\n * This method can be used to return, in boxed format, an object that has\n * been stored as a property in the message with the equivalent\n * <code>setObjectProperty</code> method call, or its equivalent primitive\n * setter method.\n * \n * @param name\n * The name of the property to get.\n * @return the Java object property value with the specified name, in boxed\n * format (for example, if the property was set as an\n * <code>int</code>, an <code>Integer</code> is returned); if there\n * is no property by this name, a null value is returned.\n * @throws JMSException\n * On internal error.\n */\n @Override\n public Object getObjectProperty(String name) throws JMSException {\n JMSMessagePropertyValue propertyValue = getJMSMessagePropertyValue(name);\n if (propertyValue != null) {\n return propertyValue.getValue();\n }\n return null;\n }\n \n /**\n * Returns the property value with message attribute to object property\n * conversions took place.\n * <P>\n * \n * @param name\n * The name of the property to get.\n * @return <code>JMSMessagePropertyValue</code> with object value and\n * corresponding SQS message attribute type and message attribute\n * string value.\n * @throws JMSException\n * On internal error.\n */\n public JMSMessagePropertyValue getJMSMessagePropertyValue(String name) throws JMSException {\n return properties.get(name);\n }\n\n private static class PropertyEnum implements Enumeration<String> {\n private final Iterator<String> propertyItr;\n\n public PropertyEnum(Iterator<String> propertyItr) {\n this.propertyItr = propertyItr;\n }\n\n @Override\n public boolean hasMoreElements() {\n return propertyItr.hasNext();\n }\n\n @Override\n public String nextElement() {\n return propertyItr.next();\n }\n }\n \n /**\n * Returns an <code>Enumeration</code> of all the property names.\n * <P>\n * Note that JMS standard header fields are not considered properties and\n * are not returned in this enumeration.\n * \n * @return an enumeration of all the names of property values.\n * @throws JMSException\n * On internal error.\n */\n @Override\n public Enumeration<String> getPropertyNames() throws JMSException {\n return new PropertyEnum(properties.keySet().iterator());\n }\n \n /**\n * Sets a <code>boolean</code> property value with the specified name into\n * the message.\n * \n * @param name\n * The name of the property to set.\n * @param value\n * The <code>boolean</code> value of the property to set.\n * @throws JMSException\n * On internal error.\n * @throws IllegalArgumentException\n * If the name or value is null or empty string.\n * @throws MessageNotWriteableException\n * If properties are read-only.\n */\n @Override\n public void setBooleanProperty(String name, boolean value) throws JMSException {\n setObjectProperty(name, value);\n }\n \n /**\n * Sets a <code>byte</code> property value with the specified name into\n * the message.\n * \n * @param name\n * The name of the property to set.\n * @param value\n * The <code>byte</code> value of the property to set.\n * @throws JMSException\n * On internal error.\n * @throws IllegalArgumentException\n * If the name or value is null or empty string.\n * @throws MessageNotWriteableException\n * If properties are read-only.\n */\n @Override\n public void setByteProperty(String name, byte value) throws JMSException {\n setObjectProperty(name, value);\n }\n \n /**\n * Sets a <code>short</code> property value with the specified name into\n * the message.\n * \n * @param name\n * The name of the property to set.\n * @param value\n * The <code>short</code> value of the property to set.\n * @throws JMSException\n * On internal error.\n * @throws IllegalArgumentException\n * If the name or value is null or empty string.\n * @throws MessageNotWriteableException\n * If properties are read-only.\n */\n @Override\n public void setShortProperty(String name, short value) throws JMSException {\n setObjectProperty(name, value);\n }\n \n /**\n * Sets a <code>int</code> property value with the specified name into\n * the message.\n * \n * @param name\n * The name of the property to set.\n * @param value\n * The <code>int</code> value of the property to set.\n * @throws JMSException\n * On internal error.\n * @throws IllegalArgumentException\n * If the name or value is null or empty string.\n * @throws MessageNotWriteableException\n * If properties are read-only.\n */\n @Override\n public void setIntProperty(String name, int value) throws JMSException {\n setObjectProperty(name, value);\n }\n \n /**\n * Sets a <code>long</code> property value with the specified name into\n * the message.\n * \n * @param name\n * The name of the property to set.\n * @param value\n * The <code>long</code> value of the property to set.\n * @throws JMSException\n * On internal error.\n * @throws IllegalArgumentException\n * If the name or value is null or empty string.\n * @throws MessageNotWriteableException\n * If properties are read-only.\n */\n @Override\n public void setLongProperty(String name, long value) throws JMSException {\n setObjectProperty(name, value);\n }\n \n /**\n * Sets a <code>float</code> property value with the specified name into\n * the message.\n * \n * @param name\n * The name of the property to set.\n * @param value\n * The <code>float</code> value of the property to set.\n * @throws JMSException\n * On internal error.\n * @throws IllegalArgumentException\n * If the name or value is null or empty string.\n * @throws MessageNotWriteableException\n * If properties are read-only.\n */\n @Override\n public void setFloatProperty(String name, float value) throws JMSException {\n setObjectProperty(name, value);\n }\n \n /**\n * Sets a <code>double</code> property value with the specified name into\n * the message.\n * \n * @param name\n * The name of the property to set.\n * @param value\n * The <code>double</code> value of the property to set.\n * @throws JMSException\n * On internal error.\n * @throws IllegalArgumentException\n * If the name or value is null or empty string.\n * @throws MessageNotWriteableException\n * If properties are read-only.\n */\n @Override\n public void setDoubleProperty(String name, double value) throws JMSException {\n setObjectProperty(name, value);\n }\n \n /**\n * Sets a <code>String</code> property value with the specified name into\n * the message.\n * \n * @param name\n * The name of the property to set.\n * @param value\n * The <code>String</code> value of the property to set.\n * @throws JMSException\n * On internal error.\n * @throws IllegalArgumentException\n * If the name or value is null or empty string.\n * @throws MessageNotWriteableException\n * If properties are read-only.\n */\n @Override\n public void setStringProperty(String name, String value) throws JMSException {\n setObjectProperty(name, value);\n }\n \n /**\n * Sets a Java object property value with the specified name into the\n * message.\n * <P>\n * Note that this method works only for the boxed primitive object types\n * (Integer, Double, Long ...) and String objects.\n * \n * @param name\n * The name of the property to set.\n * @param value\n * The object value of the property to set.\n * @throws JMSException\n * On internal error.\n * @throws IllegalArgumentException\n * If the name or value is null or empty string.\n * @throws MessageFormatException\n * If the object is invalid type.\n * @throws MessageNotWriteableException\n * If properties are read-only.\n */\n @Override\n public void setObjectProperty(String name, Object value) throws JMSException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Property name can not be null or empty.\");\n }\n if (value == null || \"\".equals(value)) {\n throw new IllegalArgumentException(\"Property value can not be null or empty.\");\n }\n if(!isValidPropertyValueType(value)) {\n throw new MessageFormatException(\"Value of property with name \" + name + \" has incorrect type \" + value.getClass().getName() + \".\");\n }\n checkPropertyWritePermissions();\n properties.put(name, new JMSMessagePropertyValue(value));\n }\n \n /**\n * <P>\n * Acknowledges message(s).\n * <P>\n * A client may individually acknowledge each message as it is consumed, or\n * it may choose to acknowledge multiple messages based on acknowledge mode,\n * which in turn might might acknowledge all messages consumed by the\n * session.\n * <P>\n * Messages that have been received but not acknowledged may be redelivered.\n * <P>\n * If the session is closed, messages cannot be acknowledged.\n * <P>\n * If only the consumer is closed, messages can still be acknowledged.\n * \n * @see com.amazon.sqs.javamessaging.acknowledge.AcknowledgeMode\n * @throws JMSException\n * On Internal error\n * @throws IllegalStateException\n * If this method is called on a closed session.\n */\n @Override\n public void acknowledge() throws JMSException {\n if (acknowledger != null) {\n acknowledger.acknowledge(this);\n }\n }\n \n /**\n * <P>\n * Clears out the message body. Clearing a message's body does not clear its\n * header values or property entries.\n * <P>\n * This method cannot be called directly instead the implementation on the\n * subclasses should be used.\n * \n * @throws JMSException\n * If directly called\n */\n @Override\n public void clearBody() throws JMSException {\n throw new JMSException(\"SQSMessage does not have any body\");\n }\n\n private boolean isValidPropertyValueType(Object value) {\n return value instanceof Boolean || value instanceof Byte || value instanceof Short ||\n value instanceof Integer || value instanceof Long || value instanceof Float ||\n value instanceof Double || value instanceof String;\n }\n\n /**\n * Copied from org.apache.activemq.util.TypeConversionSupport to provide the\n * same property support provided by activemq without creating a dependency\n * on activemq.\n */\n public static class TypeConversionSupport {\n\n static class ConversionKey {\n final Class<?> from;\n\n final Class<?> to;\n\n public ConversionKey(Class<?> from, Class<?> to) {\n this.from = from;\n this.to = to;\n }\n \n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((from == null) ? 0 : from.hashCode());\n result = prime * result + ((to == null) ? 0 : to.hashCode());\n return result;\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 ConversionKey other = (ConversionKey) obj;\n if (from == null) {\n if (other.from != null)\n return false;\n } else if (!from.equals(other.from))\n return false;\n if (to == null) {\n if (other.to != null)\n return false;\n } else if (!to.equals(other.to))\n return false;\n return true;\n }\n }\n\n interface Converter {\n Object convert(Object value);\n }\n\n static final private Map<ConversionKey, Converter> CONVERSION_MAP = new HashMap<ConversionKey, Converter>();\n static {\n Converter toStringConverter = new Converter() {\n public Object convert(Object value) {\n return value.toString();\n }\n };\n CONVERSION_MAP.put(new ConversionKey(Boolean.class, String.class), toStringConverter);\n CONVERSION_MAP.put(new ConversionKey(Byte.class, String.class), toStringConverter);\n CONVERSION_MAP.put(new ConversionKey(Short.class, String.class), toStringConverter);\n CONVERSION_MAP.put(new ConversionKey(Integer.class, String.class), toStringConverter);\n CONVERSION_MAP.put(new ConversionKey(Long.class, String.class), toStringConverter);\n CONVERSION_MAP.put(new ConversionKey(Float.class, String.class), toStringConverter);\n CONVERSION_MAP.put(new ConversionKey(Double.class, String.class), toStringConverter);\n\n CONVERSION_MAP.put(new ConversionKey(String.class, Boolean.class), new Converter() {\n public Object convert(Object value) {\n String stringValue = (String) value;\n if (Boolean.valueOf(stringValue) || INT_TRUE.equals((String) value)) {\n return Boolean.TRUE;\n }\n return Boolean.FALSE;\n }\n });\n CONVERSION_MAP.put(new ConversionKey(String.class, Byte.class), new Converter() {\n public Object convert(Object value) {\n return Byte.valueOf((String) value);\n }\n });\n CONVERSION_MAP.put(new ConversionKey(String.class, Short.class), new Converter() {\n public Object convert(Object value) {\n return Short.valueOf((String) value);\n }\n });\n CONVERSION_MAP.put(new ConversionKey(String.class, Integer.class), new Converter() {\n public Object convert(Object value) {\n return Integer.valueOf((String) value);\n }\n });\n CONVERSION_MAP.put(new ConversionKey(String.class, Long.class), new Converter() {\n public Object convert(Object value) {\n return Long.valueOf((String) value);\n }\n });\n CONVERSION_MAP.put(new ConversionKey(String.class, Float.class), new Converter() {\n public Object convert(Object value) {\n return Float.valueOf((String) value);\n }\n });\n CONVERSION_MAP.put(new ConversionKey(String.class, Double.class), new Converter() {\n public Object convert(Object value) {\n return Double.valueOf((String) value);\n }\n });\n\n Converter longConverter = new Converter() {\n public Object convert(Object value) {\n return Long.valueOf(((Number) value).longValue());\n }\n };\n CONVERSION_MAP.put(new ConversionKey(Byte.class, Long.class), longConverter);\n CONVERSION_MAP.put(new ConversionKey(Short.class, Long.class), longConverter);\n CONVERSION_MAP.put(new ConversionKey(Integer.class, Long.class), longConverter);\n CONVERSION_MAP.put(new ConversionKey(Date.class, Long.class), new Converter() {\n public Object convert(Object value) {\n return Long.valueOf(((Date) value).getTime());\n }\n });\n\n Converter intConverter = new Converter() {\n public Object convert(Object value) {\n return Integer.valueOf(((Number) value).intValue());\n }\n };\n CONVERSION_MAP.put(new ConversionKey(Byte.class, Integer.class), intConverter);\n CONVERSION_MAP.put(new ConversionKey(Short.class, Integer.class), intConverter);\n\n CONVERSION_MAP.put(new ConversionKey(Byte.class, Short.class), new Converter() {\n public Object convert(Object value) {\n return Short.valueOf(((Number) value).shortValue());\n }\n });\n\n CONVERSION_MAP.put(new ConversionKey(Float.class, Double.class), new Converter() {\n public Object convert(Object value) {\n return Double.valueOf(((Number) value).doubleValue());\n }\n });\n }\n\n @SuppressWarnings(\"unchecked\")\n static public <T> T convert(Object value, Class<T> clazz) {\n\n assert value != null && clazz != null;\n\n if (value.getClass() == clazz)\n return (T) value;\n\n Converter c = (Converter) CONVERSION_MAP.get(new ConversionKey(value.getClass(), clazz));\n if (c == null)\n return null;\n return (T) c.convert(value);\n\n }\n }\n \n /**\n * This class is used fulfill object value, corresponding SQS message\n * attribute type and message attribute string value.\n */\n public static class JMSMessagePropertyValue {\n \n private final Object value;\n\n private final String type;\n \n private final String stringMessageAttributeValue;\n \n public JMSMessagePropertyValue(String stringValue, String type) throws JMSException{\n this.type = type;\n this.value = getObjectValue(stringValue, type);\n this.stringMessageAttributeValue = stringValue;\n }\n \n public JMSMessagePropertyValue(Object value) throws JMSException {\n this.type = getType(value);\n this.value = value;\n if (BOOLEAN.equals(type)) {\n if((Boolean) value) {\n stringMessageAttributeValue = INT_TRUE;\n } else {\n stringMessageAttributeValue = INT_FALSE;\n }\n } else {\n stringMessageAttributeValue = value.toString();\n }\n }\n \n public JMSMessagePropertyValue(Object value, String type) throws JMSException {\n this.value = value;\n this.type = type;\n if (BOOLEAN.equals(type)) {\n if((Boolean) value) {\n stringMessageAttributeValue = INT_TRUE;\n } else {\n stringMessageAttributeValue = INT_FALSE;\n }\n } else {\n stringMessageAttributeValue = value.toString();\n }\n }\n \n private static String getType(Object value) throws JMSException {\n if (value instanceof String) {\n return STRING;\n } else if (value instanceof Integer) {\n return INT;\n } else if (value instanceof Long) {\n return LONG;\n } else if (value instanceof Boolean) {\n return BOOLEAN;\n } else if (value instanceof Byte) {\n return BYTE;\n } else if (value instanceof Double) {\n return DOUBLE;\n } else if (value instanceof Float) {\n return FLOAT;\n } else if (value instanceof Short) {\n return SHORT;\n } else {\n throw new JMSException(\"Not a supported JMS property type\");\n }\n }\n\n private static Object getObjectValue(String value, String type) throws JMSException {\n if (INT.equals(type)) {\n return Integer.valueOf(value);\n } else if (LONG.equals(type)) {\n return Long.valueOf(value);\n } else if (BOOLEAN.equals(type)) {\n if (INT_TRUE.equals(value)) {\n return Boolean.TRUE;\n }\n return Boolean.FALSE;\n } else if (BYTE.equals(type)) {\n return Byte.valueOf(value);\n } else if (DOUBLE.equals(type)) {\n return Double.valueOf(value);\n } else if (FLOAT.equals(type)) {\n return Float.valueOf(value);\n } else if (SHORT.equals(type)) {\n return Short.valueOf(value);\n } else if (type != null && (type.startsWith(STRING) || type.startsWith(NUMBER))) {\n return value;\n } else {\n throw new JMSException(type + \" is not a supported JMS property type\");\n }\n } \n\n public String getType() {\n return type;\n }\n\n public Object getValue() {\n return value;\n }\n \n public String getStringMessageAttributeValue() {\n return stringMessageAttributeValue;\n }\n }\n\n\n /**\n * This method sets the JMS_SQS_SEQUENCE_NUMBER property on the message. It is exposed explicitly here, so that\n * it can be invoked even on read-only message object obtained through receing a message. \n * This support the use case of send a received message by using the same JMSMessage object.\n * \n * @param sequenceNumber Sequence number to set. If null or empty, the stored sequence number will be removed.\n * @throws JMSException\n */\n public void setSequenceNumber(String sequenceNumber) throws JMSException {\n if (sequenceNumber == null || sequenceNumber.isEmpty()) {\n properties.remove(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER);\n } else {\n properties.put(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER, new JMSMessagePropertyValue(sequenceNumber));\n }\n }\n\n /*\n * Unit Test Utility Functions\n */\n void setWritePermissionsForProperties(boolean writePermissionsForProperties) {\n this.writePermissionsForProperties = writePermissionsForProperties;\n }\n}",
"public static class JMSMessagePropertyValue {\n \n private final Object value;\n\n private final String type;\n \n private final String stringMessageAttributeValue;\n \n public JMSMessagePropertyValue(String stringValue, String type) throws JMSException{\n this.type = type;\n this.value = getObjectValue(stringValue, type);\n this.stringMessageAttributeValue = stringValue;\n }\n \n public JMSMessagePropertyValue(Object value) throws JMSException {\n this.type = getType(value);\n this.value = value;\n if (BOOLEAN.equals(type)) {\n if((Boolean) value) {\n stringMessageAttributeValue = INT_TRUE;\n } else {\n stringMessageAttributeValue = INT_FALSE;\n }\n } else {\n stringMessageAttributeValue = value.toString();\n }\n }\n \n public JMSMessagePropertyValue(Object value, String type) throws JMSException {\n this.value = value;\n this.type = type;\n if (BOOLEAN.equals(type)) {\n if((Boolean) value) {\n stringMessageAttributeValue = INT_TRUE;\n } else {\n stringMessageAttributeValue = INT_FALSE;\n }\n } else {\n stringMessageAttributeValue = value.toString();\n }\n }\n \n private static String getType(Object value) throws JMSException {\n if (value instanceof String) {\n return STRING;\n } else if (value instanceof Integer) {\n return INT;\n } else if (value instanceof Long) {\n return LONG;\n } else if (value instanceof Boolean) {\n return BOOLEAN;\n } else if (value instanceof Byte) {\n return BYTE;\n } else if (value instanceof Double) {\n return DOUBLE;\n } else if (value instanceof Float) {\n return FLOAT;\n } else if (value instanceof Short) {\n return SHORT;\n } else {\n throw new JMSException(\"Not a supported JMS property type\");\n }\n }\n\n private static Object getObjectValue(String value, String type) throws JMSException {\n if (INT.equals(type)) {\n return Integer.valueOf(value);\n } else if (LONG.equals(type)) {\n return Long.valueOf(value);\n } else if (BOOLEAN.equals(type)) {\n if (INT_TRUE.equals(value)) {\n return Boolean.TRUE;\n }\n return Boolean.FALSE;\n } else if (BYTE.equals(type)) {\n return Byte.valueOf(value);\n } else if (DOUBLE.equals(type)) {\n return Double.valueOf(value);\n } else if (FLOAT.equals(type)) {\n return Float.valueOf(value);\n } else if (SHORT.equals(type)) {\n return Short.valueOf(value);\n } else if (type != null && (type.startsWith(STRING) || type.startsWith(NUMBER))) {\n return value;\n } else {\n throw new JMSException(type + \" is not a supported JMS property type\");\n }\n } \n\n public String getType() {\n return type;\n }\n\n public Object getValue() {\n return value;\n }\n \n public String getStringMessageAttributeValue() {\n return stringMessageAttributeValue;\n }\n}",
"public class SQSObjectMessage extends SQSMessage implements ObjectMessage {\n private static final Log LOG = LogFactory.getLog(SQSObjectMessage.class);\n\n /**\n * Serialized message body\n */\n private String body;\n\n /**\n * Convert received SQSMessage into ObjectMessage\n */\n public SQSObjectMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException {\n super(acknowledger, queueUrl, sqsMessage);\n body = sqsMessage.getBody();\n }\n \n /**\n * Create new empty ObjectMessage to send.\n */\n public SQSObjectMessage() throws JMSException {\n super();\n }\n\n /**\n * Create new ObjectMessage with payload to send.\n */\n public SQSObjectMessage(Serializable payload) throws JMSException {\n super();\n body = serialize(payload);\n }\n \n /**\n * Sets the <code>Serializable</code> containing this message's body\n * \n * @param payload\n * The <code>Serializable</code> containing the message's body\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n * @throws MessageFormatException\n * If object serialization fails.\n */\n @Override\n public void setObject(Serializable payload) throws JMSException {\n checkBodyWritePermissions();\n body = serialize(payload);\n }\n \n /**\n * Gets the <code>Serializable</code> containing this message's body\n * \n * @throws MessageFormatException\n * If object deserialization fails.\n */\n @Override\n public Serializable getObject() throws JMSException {\n return deserialize(body);\n }\n \n /**\n * Sets the message body to write mode, and sets the object body to null\n */\n @Override\n public void clearBody() throws JMSException {\n body = null;\n setBodyWritePermissions(true);\n }\n \n /**\n * Deserialize the <code>String</code> into <code>Serializable</code>\n * object.\n */\n protected static Serializable deserialize(String serialized) throws JMSException {\n if (serialized == null) {\n return null;\n }\n Serializable deserializedObject;\n ObjectInputStream objectInputStream = null;\n try {\n byte[] bytes = Base64.decode(serialized);\n objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));\n deserializedObject = (Serializable) objectInputStream.readObject();\n } catch (IOException e) {\n LOG.error(\"IOException: Message cannot be written\", e);\n throw convertExceptionToMessageFormatException(e);\n } catch (Exception e) {\n LOG.error(\"Unexpected exception: \", e);\n throw convertExceptionToMessageFormatException(e);\n } finally {\n if (objectInputStream != null) {\n try {\n objectInputStream.close();\n } catch (IOException e) {\n LOG.warn(e.getMessage());\n }\n }\n }\n return deserializedObject;\n }\n \n /**\n * Serialize the <code>Serializable</code> object to <code>String</code>.\n */\n protected static String serialize(Serializable serializable) throws JMSException {\n if (serializable == null) {\n return null;\n }\n String serializedString;\n ObjectOutputStream objectOutputStream = null;\n try {\n ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();\n objectOutputStream = new ObjectOutputStream(bytesOut);\n objectOutputStream.writeObject(serializable);\n objectOutputStream.flush();\n serializedString = Base64.encodeAsString(bytesOut.toByteArray());\n } catch (IOException e) {\n LOG.error(\"IOException: cannot serialize objectMessage\", e);\n throw convertExceptionToMessageFormatException(e);\n } finally {\n if (objectOutputStream != null) {\n try {\n objectOutputStream.close();\n } catch (IOException e) {\n LOG.warn(e.getMessage());\n }\n }\n }\n return serializedString;\n }\n \n public String getMessageBody() {\n return body;\n }\n\n void setMessageBody(String body) {\n this.body = body;\n }\n}",
"public class SQSTextMessage extends SQSMessage implements TextMessage {\n\n /**\n * Text of the message. Assume this is safe from SQS invalid characters.\n */\n private String text;\n\n /**\n * Convert received SQSMessage into TextMessage.\n */\n public SQSTextMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException{\n super(acknowledger, queueUrl, sqsMessage);\n this.text = sqsMessage.getBody();\n }\n \n /**\n * Create new empty TextMessage to send.\n */\n public SQSTextMessage() throws JMSException {\n super();\n }\n\n /**\n * Create new TextMessage with payload to send.\n */\n public SQSTextMessage(String payload) throws JMSException {\n super();\n this.text = payload;\n }\n \n /**\n * Sets the text containing this message's body.\n * \n * @param string\n * The <code>String</code> containing the message's body\n * @throws MessageNotWriteableException\n * If the message is in read-only mode.\n */\n @Override\n public void setText(String string) throws JMSException {\n checkBodyWritePermissions();\n this.text = string;\n }\n \n /**\n * Gets the text containing this message's body.\n * \n * @return The <code>String</code> containing the message's body\n */\n @Override\n public String getText() throws JMSException {\n return text;\n }\n \n /**\n * Sets the message body to write mode, and sets the text to null\n */\n @Override\n public void clearBody() throws JMSException {\n text = null;\n setBodyWritePermissions(true);\n }\n}"
] | import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.jms.Destination;
import javax.jms.IllegalStateException;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageFormatException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueSender;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazon.sqs.javamessaging.message.SQSBytesMessage;
import com.amazon.sqs.javamessaging.message.SQSMessage;
import com.amazon.sqs.javamessaging.message.SQSMessage.JMSMessagePropertyValue;
import com.amazon.sqs.javamessaging.message.SQSObjectMessage;
import com.amazon.sqs.javamessaging.message.SQSTextMessage;
import com.amazonaws.services.sqs.model.MessageAttributeValue;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageResult;
import com.amazonaws.util.Base64; | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazon.sqs.javamessaging;
/**
* A client uses a MessageProducer object to send messages to a queue
* destination. A MessageProducer object is created by passing a Destination
* object to a message-producer creation method supplied by a session.
* <P>
* A client also has the option of creating a message producer without supplying
* a queue destination. In this case, a destination must be provided with every send
* operation.
* <P>
*/
public class SQSMessageProducer implements MessageProducer, QueueSender {
private static final Log LOG = LogFactory.getLog(SQSMessageProducer.class);
private long MAXIMUM_DELIVERY_DELAY_MILLISECONDS = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
private int deliveryDelaySeconds = 0;
/** This field is not actually used. */
private long timeToLive;
/** This field is not actually used. */
private int defaultPriority;
/** This field is not actually used. */
private int deliveryMode;
/** This field is not actually used. */
private boolean disableMessageTimestamp;
/** This field is not actually used. */
private boolean disableMessageID;
/**
* State of MessageProducer.
* True if MessageProducer is closed.
*/
final AtomicBoolean closed = new AtomicBoolean(false);
private final AmazonSQSMessagingClientWrapper amazonSQSClient;
private final SQSQueueDestination sqsDestination;
private final SQSSession parentSQSSession;
SQSMessageProducer(AmazonSQSMessagingClientWrapper amazonSQSClient, SQSSession parentSQSSession,
SQSQueueDestination destination) throws JMSException {
this.sqsDestination = destination;
this.amazonSQSClient = amazonSQSClient;
this.parentSQSSession = parentSQSSession;
}
void sendInternal(SQSQueueDestination queue, Message rawMessage) throws JMSException {
checkClosed();
String sqsMessageBody = null;
String messageType = null; | if (!(rawMessage instanceof SQSMessage)) { | 1 |
Catbag/redux-android-sample | app/src/main/java/br/com/catbag/gifreduxsample/reducers/AppStateReducer.java | [
"public final class AppStateActionCreator extends BaseActionCreator {\n\n public static final String APP_STATE_LOAD = \"APP_STATE_LOAD\";\n public static final String APP_STATE_LOADED = \"APP_STATE_LOADED\";\n\n private static AppStateActionCreator sInstance;\n\n private AppStateActionCreator() {\n MyApp.getFluxxan().inject(this);\n }\n\n public static AppStateActionCreator getInstance() {\n if (sInstance == null) {\n sInstance = new AppStateActionCreator();\n }\n return sInstance;\n }\n\n public void loadAppState() {\n dispatch(new Action(APP_STATE_LOAD));\n }\n\n}",
"public final class GifActionCreator extends BaseActionCreator {\n public static final String GIF_PLAY = \"GIF_PLAY\";\n public static final String GIF_PAUSE = \"GIF_PAUSE\";\n public static final String GIF_DOWNLOAD_SUCCESS = \"GIF_DOWNLOAD_SUCCESS\";\n public static final String GIF_DOWNLOAD_FAILURE = \"GIF_DOWNLOAD_FAILURE\";\n public static final String GIF_DOWNLOAD_START = \"GIF_DOWNLOAD_START\";\n\n private static GifActionCreator sInstance;\n\n private GifActionCreator() {\n MyApp.getFluxxan().inject(this);\n }\n\n public static GifActionCreator getInstance() {\n if (sInstance == null) {\n sInstance = new GifActionCreator();\n }\n return sInstance;\n }\n\n public void gifDownloadStart(Gif gif) {\n dispatch(new Action(GIF_DOWNLOAD_START, gif.getUuid()));\n }\n\n public void gifClick(Gif gif) {\n if (gif.getStatus() == Gif.Status.DOWNLOADED || gif.getStatus() == Gif\n .Status.PAUSED) {\n gifPlay(gif.getUuid());\n } else if (gif.getStatus() == Gif.Status.LOOPING) {\n gifPause(gif.getUuid());\n }\n }\n\n private void gifPlay(String uuid) {\n dispatch(new Action(GIF_PLAY, uuid));\n }\n\n private void gifPause(String uuid) {\n dispatch(new Action(GIF_PAUSE, uuid));\n }\n}",
"public final class GifListActionCreator extends BaseActionCreator {\n\n public static final String GIF_LIST_UPDATED = \"GIF_LIST_UPDATED\";\n public static final String GIF_LIST_FETCHING = \"GIF_LIST_FETCHING\";\n\n private static GifListActionCreator sInstance;\n\n private GifListActionCreator() {\n MyApp.getFluxxan().inject(this);\n }\n\n public static GifListActionCreator getInstance() {\n if (sInstance == null) {\n sInstance = new GifListActionCreator();\n }\n return sInstance;\n }\n\n public void fetchGifs() {\n dispatch(new Action(GIF_LIST_FETCHING));\n }\n}",
"public final class PayloadParams {\n\n public static final String PARAM_UUID = \"PARAM_UUID\";\n public static final String PARAM_PATH = \"PARAM_PATH\";\n public static final String PARAM_GIFS = \"PARAM_GIFS\";\n public static final String PARAM_HAS_MORE = \"PARAM_HAS_MORE\";\n\n private PayloadParams() {\n }\n}",
"@SuppressWarnings(\"PMD.BooleanGetMethodName\")\[email protected]\n@JsonSerialize(as = ImmutableAppState.class)\n@JsonDeserialize(as = ImmutableAppState.class)\npublic abstract class AppState {\n\n @Value.Default\n public Map<String, Gif> getGifs() {\n return new LinkedHashMap<>();\n }\n\n @Value.Default\n public boolean getHasMoreGifs() {\n return true;\n }\n\n public String toJson() throws JsonProcessingException {\n return new ObjectMapper().writeValueAsString(this);\n }\n\n public static AppState fromJson(String json) throws IOException {\n ObjectMapper mapper = new ObjectMapper();\n mapper.registerModule(new GuavaModule());\n return mapper.readValue(json, AppState.class);\n }\n\n}",
"@SuppressWarnings(\"PMD.BooleanGetMethodName\")\[email protected]\n@JsonSerialize(as = ImmutableGif.class)\n@JsonDeserialize(as = ImmutableGif.class)\npublic abstract class Gif {\n\n public enum Status {\n PAUSED, LOOPING, DOWNLOADING, DOWNLOADED, NOT_DOWNLOADED, DOWNLOAD_FAILED\n }\n\n //abstract method are immutable by default\n public abstract String getUuid();\n\n @Value.Default\n public String getPath() {\n return \"\";\n }\n\n public abstract String getUrl();\n \n public abstract String getTitle();\n\n @Value.Default\n public boolean getWatched() {\n return false;\n }\n\n @Value.Default\n public Status getStatus() {\n return Status.NOT_DOWNLOADED;\n }\n\n public String toJson() throws JsonProcessingException {\n return new ObjectMapper().writeValueAsString(this);\n }\n\n public static Gif fromJson(String json) throws IOException {\n return new ObjectMapper().readValue(json, Gif.class);\n }\n\n}"
] | import com.umaplay.fluxxan.annotation.BindAction;
import com.umaplay.fluxxan.impl.BaseAnnotatedReducer;
import java.util.LinkedHashMap;
import java.util.Map;
import br.com.catbag.gifreduxsample.actions.AppStateActionCreator;
import br.com.catbag.gifreduxsample.actions.GifActionCreator;
import br.com.catbag.gifreduxsample.actions.GifListActionCreator;
import br.com.catbag.gifreduxsample.actions.PayloadParams;
import br.com.catbag.gifreduxsample.models.AppState;
import br.com.catbag.gifreduxsample.models.Gif;
import br.com.catbag.gifreduxsample.models.ImmutableAppState; | package br.com.catbag.gifreduxsample.reducers;
/**
Copyright 26/10/2016
Felipe Piñeiro ([email protected]),
Nilton Vasques ([email protected]) and
Raul Abreu ([email protected])
Be free to ask for help, email us!
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.
**/
public class AppStateReducer extends BaseAnnotatedReducer<AppState> {
@BindAction(AppStateActionCreator.APP_STATE_LOADED)
public AppState stateLoaded(AppState oldState, AppState newState) {
return createImmutableAppBuilder(newState)
.build();
}
@BindAction(GifListActionCreator.GIF_LIST_UPDATED)
public AppState listUpdated(AppState state, Map<String, Object> params) { | Map<String, Gif> gifs = (Map<String, Gif>) params.get(PayloadParams.PARAM_GIFS); | 3 |
AwaisKing/Linked-Words | app/src/main/java/awais/sephiroth/numberpicker/HorizontalNumberPicker.java | [
"public final class Utils {\n static {\n AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);\n }\n\n private static final Intent SEARCH_QUERY_INTENT = new Intent(Intent.ACTION_WEB_SEARCH);\n\n public static final int[] CUSTOM_TAB_COLORS = new int[]{0xFF4888F2, 0xFF333333, 0xFF3B496B};\n public static final String CHARSET = \"UTF-8\";\n public static FirebaseCrashlytics firebaseCrashlytics;\n public static InputMethodManager inputMethodManager;\n public static NotificationManager notificationManager;\n public static Locale defaultLocale;\n public static int statusBarHeight = 0, navigationBarHeight = 0;\n private static ClipboardManager clipboard;\n\n @Nullable\n public static String getResponse(final String url) throws Exception {\n final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();\n\n try (final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {\n if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {\n final StringBuilder response = new StringBuilder();\n\n String currentLine;\n while ((currentLine = reader.readLine()) != null)\n response.append(currentLine);\n\n return response.toString();\n }\n return null;\n } finally {\n connection.disconnect();\n }\n }\n\n /**\n * thanks to weston\n * https://stackoverflow.com/questions/2711858/is-it-possible-to-set-a-custom-font-for-entire-of-application/16883281#16883281\n */\n public static void setDefaultFont(final String typefaceName, final Typeface fontTypeface) {\n try {\n final Field staticField = Typeface.class.getDeclaredField(typefaceName);\n if (!staticField.isAccessible()) staticField.setAccessible(true);\n staticField.set(null, fontTypeface);\n } catch (final Exception e) {\n if (BuildConfig.DEBUG) Log.e(\"AWAISKING_APP\", \"Utils::setDefaultFont\", e);\n else firebaseCrashlytics.recordException(e);\n }\n }\n\n public static boolean isEmpty(final CharSequence cs) {\n return cs == null || cs.length() <= 0 || cs.equals(\"\") || isEmpty(cs.toString());\n }\n\n @SuppressWarnings(\"ConstantConditions\")\n public static boolean isEmpty(String str) {\n if (str == null || str.length() <= 0 || str.isEmpty() || \"null\".equals(str)) return true;\n str = str.trim();\n return str.length() <= 0 || str.isEmpty() || \"null\".equals(str);\n }\n\n public static void stopAsyncSilent(final LocalAsyncTask<?, ?> localAsyncTask) {\n try {\n if (localAsyncTask != null)\n localAsyncTask.cancel(true);\n } catch (final Exception e) {\n // ignore\n }\n }\n\n public static void removeHandlerCallbacksSilent(final Handler handler, final Runnable runnable) {\n try {\n if (handler != null)\n handler.removeCallbacks(runnable);\n } catch (final Exception e) {\n // ignore\n }\n }\n\n public static void adsBox(@NonNull final Activity activity) {\n final View adLayout = activity.findViewById(R.id.adLayout);\n if (adLayout == null) return;\n if (SettingsHelper.showAds()) {\n MobileAds.initialize(activity, initializationStatus -> { });\n final AdView adView = activity.findViewById(R.id.adView);\n adView.setAdListener(new Listener(adLayout));\n adView.loadAd(new AdRequest.Builder().build());\n } else adLayout.setVisibility(View.GONE);\n }\n\n public static int getStatusBarHeight(final Window window, final Resources resources) {\n if (Build.VERSION.SDK_INT == 19 && window != null && resources != null) {\n final Rect rectangle = new Rect();\n window.getDecorView().getWindowVisibleDisplayFrame(rectangle);\n\n final View contentView = window.findViewById(Window.ID_ANDROID_CONTENT);\n\n final int resId = resources.getIdentifier(\"status_bar_height\", \"dimen\", \"android\");\n final int statusBarHeight1 = contentView.getTop() - rectangle.top;\n final int statusBarHeight2 = resId > 0 ? resources.getDimensionPixelSize(resId) : 0;\n\n return statusBarHeight1 == 0 && statusBarHeight2 == 0 ? 50 :\n statusBarHeight1 == 0 ? statusBarHeight2 : statusBarHeight1;\n }\n return 0;\n }\n\n public static int getNavigationBarHeight(final Window window, final Resources resources) {\n if (Build.VERSION.SDK_INT == 19 && window != null && resources != null) {\n final int appUsableSizeX, appUsableSizeY, realScreenSizeX, realScreenSizeY;\n\n final Display display = window.getWindowManager().getDefaultDisplay();\n final Point size = new Point();\n display.getSize(size);\n appUsableSizeX = size.x;\n appUsableSizeY = size.y;\n\n display.getRealSize(size);\n realScreenSizeX = size.x;\n realScreenSizeY = size.y;\n\n final int navBarHeight1;\n if (!(appUsableSizeX < realScreenSizeX) // !(navigation bar on the right)\n && appUsableSizeY < realScreenSizeY) // navigation bar at the bottom\n navBarHeight1 = realScreenSizeY - appUsableSizeY;\n else navBarHeight1 = 0;\n\n final int resId = resources.getIdentifier(\"navigation_bar_height\", \"dimen\", \"android\");\n final int navBarHeight2 = resId > 0 ? resources.getDimensionPixelSize(resId) : 0;\n\n return navBarHeight1 == 0 && navBarHeight2 == 0 ? 0 :\n navBarHeight1 == 0 ? navBarHeight2 : navBarHeight1;\n }\n return 0;\n }\n\n public static void copyText(final Context context, final String stringToCopy) {\n if (clipboard == null)\n clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);\n\n int toastMessage = R.string.error_copying_clipboard;\n if (clipboard != null) {\n clipboard.setPrimaryClip(ClipData.newPlainText(\"word\", stringToCopy));\n toastMessage = R.string.copied_clipboard;\n }\n\n Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();\n }\n\n @NonNull\n public static PopupMenu setPopupMenuSlider(@NonNull final View view, @NonNull final WordItem wordItem) {\n final Context context = view.getContext();\n\n Object tag = view.getTag(R.id.key_popup);\n final PopupMenu popup;\n if (tag instanceof PopupMenu) popup = (PopupMenu) tag;\n else {\n popup = new PopupMenu(context, view);\n popup.getMenuInflater().inflate(R.menu.menu_word, popup.getMenu());\n view.setTag(R.id.key_popup, popup);\n }\n\n tag = view.getTag(R.id.key_popup_item_listener);\n final WordContextItemListener itemListener;\n if (tag instanceof WordContextItemListener) itemListener = (WordContextItemListener) tag;\n else {\n itemListener = new WordContextItemListener(context);\n view.setTag(R.id.key_popup_item_listener, itemListener);\n }\n\n itemListener.setWord(wordItem.getWord());\n\n popup.setOnMenuItemClickListener(itemListener);\n view.setOnTouchListener(popup.getDragToOpenListener());\n\n return popup;\n }\n\n public static void showPopupMenu(@NonNull final View view, @NonNull final WordItem wordItem) {\n setPopupMenuSlider(view, wordItem).show();\n }\n\n @NonNull\n public static PopupMenu setPopupMenuSlider(final Dialog dialog, final Context context, @NonNull final View view, final String word) {\n final PopupMenu popup = new PopupMenu(context, view);\n final Menu menu = popup.getMenu();\n popup.getMenuInflater().inflate(R.menu.menu_search, menu);\n\n for (int i = tabBoolsArray.length - 1; i >= 0; i--)\n menu.getItem(i).setVisible(tabBoolsArray[i]);\n\n popup.setOnMenuItemClickListener(new WordClickSearchListener(context, dialog, word));\n\n view.setOnTouchListener(popup.getDragToOpenListener());\n view.setTag(R.id.key_popup, popup);\n\n return popup;\n }\n\n public static void showPopupMenu(final Dialog dialog, final Context context, final View view, final String word) {\n if (context != null && view != null && !isEmpty(word)) {\n final Object tag = view.getTag(R.id.key_popup);\n final PopupMenu popup = tag instanceof PopupMenu ? (PopupMenu) tag :\n setPopupMenuSlider(dialog, context, view, word);\n popup.show();\n }\n }\n\n public static void speakText(final CharSequence text) {\n if (tts != null && !isEmpty(text)) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)\n tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);\n else\n tts.speak(String.valueOf(text), TextToSpeech.QUEUE_FLUSH, null); // todo change deprecated\n }\n }\n\n public static float distance(@NonNull final PointF pointF, @NonNull final PointF other) {\n return (float) sqrt((other.y - pointF.y) * (other.y - pointF.y) + (other.x - pointF.x) * (other.x - pointF.x));\n }\n\n @NonNull\n public static ContextThemeWrapper getStyledContext(final Context context, @StyleRes int style) {\n if (context instanceof ContextThemeWrapper) return (ContextThemeWrapper) context;\n if (style == 0 || style == -1) {\n final Resources.Theme theme;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (theme = context.getTheme()) != null)\n return new ContextThemeWrapper(context, theme);\n else {\n final Context appContext = context.getApplicationContext();\n\n final PackageManager packageManager = appContext.getPackageManager();\n final String packageName = appContext.getPackageName();\n\n int styleHack;\n try {\n final PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);\n styleHack = packageInfo.applicationInfo.theme;\n Log.d(\"AWAISKING_APP\", \"styleHack1: \" + styleHack);\n } catch (final Exception e) {\n Log.e(\"AWAISKING_APP\", \"err1\", e);\n styleHack = -1;\n }\n\n if (styleHack == 0 || styleHack == -1) {\n try {\n final Intent intent = packageManager.getLaunchIntentForPackage(packageName);\n //noinspection ConstantConditions\n final ActivityInfo activityInfo = packageManager.getActivityInfo(intent.getComponent(), 0);\n styleHack = activityInfo.getThemeResource();\n Log.d(\"AWAISKING_APP\", \"styleHack2: \" + styleHack);\n } catch (final Exception e) {\n Log.e(\"AWAISKING_APP\", \"err2\", e);\n styleHack = -1;\n }\n }\n\n //try {\n // final ActivityInfo activityInfo = packageManager.getActivityInfo(new ComponentName(appContext, Main.class), 0);\n // styleHack = activityInfo.getThemeResource();\n //} catch (final Throwable e) {\n // styleHack = -1;\n //}\n //if (styleHack == 0 || styleHack == -1) {\n // try {\n // final ActivityInfo activityInfo = packageManager.getActivityInfo(new ComponentName(context, Main.class), 0);\n // styleHack = activityInfo.getThemeResource();\n // } catch (final Throwable e) {\n // styleHack = -1;\n // }\n //}\n\n if (styleHack != 0 && styleHack != -1) style = styleHack;\n }\n }\n return new ContextThemeWrapper(context, style);\n }\n\n public static boolean isAnySearchAppFound(@NonNull final Context context) {\n final String appID = context.getApplicationContext().getPackageName();\n final PackageManager packageManager = context.getPackageManager();\n\n final List<ResolveInfo> pkgAppsList = packageManager.queryIntentActivities(SEARCH_QUERY_INTENT, 0);\n int pkgsSize = pkgAppsList.size();\n for (int i = pkgsSize - 1; i >= 0; i--) {\n final ResolveInfo resolveInfo = pkgAppsList.get(i);\n final String strResolveInfo = String.valueOf(resolveInfo);\n\n if (strResolveInfo.contains(appID) && strResolveInfo.contains(\"TextProcessHelper\") ||\n resolveInfo != null && resolveInfo.activityInfo != null && appID.equals(resolveInfo.activityInfo.packageName))\n --pkgsSize;\n }\n\n return pkgsSize > 0;\n }\n\n // extracted from String class\n public static int indexOfChar(@NonNull final CharSequence sequence, final int ch, final int startIndex) {\n final int max = sequence.length();\n if (startIndex < max) {\n if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {\n for (int i = startIndex; i < max; i++) if (sequence.charAt(i) == ch) return i;\n } else if (Character.isValidCodePoint(ch)) {\n final char hi = (char) ((ch >>> 10) + (Character.MIN_HIGH_SURROGATE - (Character.MIN_SUPPLEMENTARY_CODE_POINT >>> 10)));\n final char lo = (char) ((ch & 0x3ff) + MIN_LOW_SURROGATE);\n for (int i = startIndex; i < max; i++)\n if (sequence.charAt(i) == hi && sequence.charAt(i + 1) == lo) return i;\n }\n }\n return -1;\n }\n}",
"public interface NumberPickerProgressListener {\n void onProgressChanged(final HorizontalNumberPicker numberPicker, final int progressValue,\n final boolean isChangeCompleted);\n}",
"public enum State {\n POSSIBLE,\n BEGAN,\n CHANGED,\n FAILED,\n CANCELLED,\n ENDED,\n}",
"public final class UIGestureRecognizerDelegate {\n private final LinkedHashSet<UIGestureRecognizer> gestureRecognizers = new LinkedHashSet<>();\n private boolean isEnabled = true;\n\n public void setEnabled(final boolean enabled) {\n isEnabled = enabled;\n for (final UIGestureRecognizer uiGestureRecognizer : gestureRecognizers) uiGestureRecognizer.setEnabled(enabled);\n }\n\n public void addGestureRecognizer(@NonNull final UIGestureRecognizer recognizer) {\n recognizer.delegate = this;\n gestureRecognizers.add(recognizer);\n }\n\n @SafeVarargs\n public final boolean onTouchEvent(final MotionEvent event, final boolean useOR,\n final Class<? extends UIGestureRecognizer>... recognizerTypesToExclude) {\n boolean handled = false;\n\n if (isEnabled) {\n boolean isFirst = true;\n final boolean excludeNotEmpty = recognizerTypesToExclude != null;\n final LinkedHashSet<Class<? extends UIGestureRecognizer>> exludedRecognizers = excludeNotEmpty ?\n new LinkedHashSet<>(Arrays.asList(recognizerTypesToExclude)) : null;\n\n for (final UIGestureRecognizer recognizer : gestureRecognizers) {\n final boolean exludeEvent = excludeNotEmpty && exludedRecognizers.contains(recognizer.getClass());\n if (exludeEvent) continue;\n\n if (useOR) handled |= recognizer.onTouchEvent(event);\n else if (isFirst) handled = recognizer.onTouchEvent(event);\n else handled &= recognizer.onTouchEvent(event);\n isFirst = false;\n }\n }\n return handled;\n }\n\n boolean shouldRecognizeSimultaneouslyWithGestureRecognizer(final UIGestureRecognizer recognizer) {\n if (gestureRecognizers.size() == 1) return true;\n\n boolean result = true;\n for (final UIGestureRecognizer other : gestureRecognizers) {\n if (other != recognizer)\n result = result & (!recognizer.hasBeganFiringEvents() | other.hasBeganFiringEvents());\n }\n\n return result;\n }\n}",
"public final class UILongPressGestureRecognizer extends UIGestureRecognizer {\n // request to change the current state to Failed\n private static final int MESSAGE_FAILED = 1;\n // request to change the current state to Possible\n private static final int MESSAGE_RESET = 2;\n // we handle the action_pointer_up received in the onTouchEvent with a delay\n // in order to check how many fingers were actually down when we're checking them\n // in the action_up.\n private static final int MESSAGE_POINTER_UP = 3;\n // post handle the long press event\n private static final int MESSAGE_LONG_PRESS = 4;\n\n private int numberOfTouches = 0, mNumTaps = 1;\n private long longPressTimeout = Math.max(LONG_PRESS_TIMEOUT, DOUBLE_TAP_TIMEOUT);\n private boolean mStarted, mBegan, mAlwaysInTapRegion = false;\n\n private final int allowableMovement, scaledTouchSlop;\n private final PointF mStartLocation = new PointF(), mDownFocusLocation = new PointF();\n\n public UILongPressGestureRecognizer(final int scaledTouchSlop) {\n super();\n\n this.mStarted = false;\n this.mBegan = false;\n\n this.scaledTouchSlop = scaledTouchSlop;\n this.allowableMovement = scaledTouchSlop;\n }\n\n @Override\n protected void removeMessages() {\n removeMessages(MESSAGE_FAILED, MESSAGE_RESET, MESSAGE_POINTER_UP, MESSAGE_LONG_PRESS);\n }\n\n @Override\n protected void handleMessage(@NonNull final Message msg) {\n if (msg.what == MESSAGE_RESET) handleReset();\n else if (msg.what == MESSAGE_FAILED) handleFailed();\n else if (msg.what == MESSAGE_POINTER_UP) numberOfTouches = msg.arg1;\n else if (msg.what == MESSAGE_LONG_PRESS) handleLongPress();\n }\n\n @Override\n public boolean hasBeganFiringEvents() {\n return super.hasBeganFiringEvents() && inState(State.BEGAN, State.CHANGED);\n }\n\n @Override\n public boolean onTouchEvent(final MotionEvent event) {\n super.onTouchEvent(event);\n\n if (!isEnabled) return false;\n\n final int action = event.getActionMasked();\n final int count = event.getPointerCount();\n\n switch (action & MotionEvent.ACTION_MASK) {\n case MotionEvent.ACTION_DOWN: {\n removeMessages();\n\n mAlwaysInTapRegion = true;\n numberOfTouches = count;\n mBegan = false;\n\n if (!mStarted) {\n state = State.POSSIBLE;\n setBeginFiringEvents(false);\n mNumTaps = 1;\n mStarted = true;\n } else {\n mNumTaps++;\n\n // if second tap is too far wawy from the first and only 1 finger is required\n }\n\n if (mNumTaps == 1) {\n mHandler.sendEmptyMessageAtTime(MESSAGE_LONG_PRESS, event.getDownTime() + longPressTimeout);\n } else {\n delayedFail();\n }\n\n mDownFocusLocation.set(mCurrentLocation);\n mStartLocation.set(mCurrentLocation);\n }\n break;\n\n case MotionEvent.ACTION_POINTER_DOWN: {\n if (state == State.POSSIBLE && mStarted) {\n removeMessages(MESSAGE_POINTER_UP);\n numberOfTouches = count;\n\n if (numberOfTouches > 1) {\n removeMessages();\n state = State.FAILED;\n }\n\n mDownFocusLocation.set(mCurrentLocation);\n computeFocusPoint(event, mStartLocation);\n\n } else if (inState(State.BEGAN, State.CHANGED) && mStarted) {\n numberOfTouches = count;\n }\n }\n break;\n\n case MotionEvent.ACTION_POINTER_UP: {\n if (state == State.POSSIBLE && mStarted) {\n removeMessages(MESSAGE_POINTER_UP);\n\n mDownFocusLocation.set(mCurrentLocation);\n\n final Message message = mHandler.obtainMessage(MESSAGE_POINTER_UP);\n message.arg1 = numberOfTouches - 1;\n mHandler.sendMessageDelayed(message, UIGestureRecognizer.TAP_TIMEOUT);\n\n computeFocusPoint(event, mStartLocation);\n\n } else if (inState(State.BEGAN, State.CHANGED)) {\n if (numberOfTouches - 1 < 1) {\n final boolean began = hasBeganFiringEvents();\n state = State.ENDED;\n\n if (began) fireActionEvent();\n\n setBeginFiringEvents(false);\n }\n }\n }\n break;\n\n case MotionEvent.ACTION_MOVE: {\n if (state == State.POSSIBLE && mStarted) {\n if (mAlwaysInTapRegion) {\n final float distance = Utils.distance(mCurrentLocation, mDownFocusLocation);\n\n if (distance > allowableMovement) {\n mAlwaysInTapRegion = false;\n removeMessages();\n state = State.FAILED;\n }\n }\n } else if (state == State.BEGAN) {\n if (!mBegan) {\n final float distance = Utils.distance(mCurrentLocation, mDownFocusLocation);\n\n if (distance > scaledTouchSlop) {\n mBegan = true;\n\n if (hasBeganFiringEvents()) {\n state = State.CHANGED;\n fireActionEvent();\n }\n }\n }\n } else if (state == State.CHANGED) {\n if (hasBeganFiringEvents()) fireActionEvent();\n }\n }\n break;\n\n case MotionEvent.ACTION_UP: {\n removeMessages(MESSAGE_RESET, MESSAGE_POINTER_UP, MESSAGE_LONG_PRESS);\n\n if (state == State.POSSIBLE && mStarted) {\n if (numberOfTouches != 1) {\n mStarted = false;\n removeMessages();\n state = State.FAILED;\n postReset();\n } else {\n if (mNumTaps < 1) {\n removeMessages(MESSAGE_FAILED);\n delayedFail();\n } else {\n mNumTaps = 1;\n mStarted = false;\n removeMessages();\n state = State.FAILED;\n }\n }\n } else if (inState(State.BEGAN, State.CHANGED)) {\n mNumTaps = 1;\n mStarted = false;\n final boolean began = hasBeganFiringEvents();\n state = State.ENDED;\n if (began) fireActionEvent();\n postReset();\n } else {\n mStarted = false;\n postReset();\n }\n setBeginFiringEvents(false);\n }\n break;\n\n case MotionEvent.ACTION_CANCEL: {\n removeMessages();\n mStarted = false;\n mNumTaps = 1;\n state = State.CANCELLED;\n postReset();\n }\n break;\n }\n\n if (state == State.POSSIBLE) return cancelsTouchesInView;\n else if (state == State.ENDED) return cancelsTouchesInView;\n\n return !cancelsTouchesInView;\n }\n\n @Override\n public void reset() {\n super.reset();\n handleReset();\n }\n\n private void postReset() {\n mHandler.sendEmptyMessage(MESSAGE_RESET);\n }\n\n private void delayedFail() {\n mHandler.sendEmptyMessageDelayed(MESSAGE_FAILED, DOUBLE_TAP_TIMEOUT);\n }\n\n private void handleFailed() {\n removeMessages();\n state = State.FAILED;\n setBeginFiringEvents(false);\n mStarted = false;\n }\n\n private void handleReset() {\n state = State.POSSIBLE;\n mStarted = false;\n }\n\n private void handleLongPress() {\n removeMessages(MESSAGE_FAILED);\n\n if (state == State.POSSIBLE && mStarted) {\n if (numberOfTouches == 1) {\n state = State.BEGAN;\n fireActionEventIfCanRecognizeSimultaneously();\n } else {\n state = State.FAILED;\n setBeginFiringEvents(false);\n mStarted = false;\n mNumTaps = 1;\n }\n }\n }\n\n private void fireActionEventIfCanRecognizeSimultaneously() {\n if (inState(State.CHANGED, State.ENDED)) {\n setBeginFiringEvents(true);\n fireActionEvent();\n } else if (delegate.shouldRecognizeSimultaneouslyWithGestureRecognizer(this)) {\n setBeginFiringEvents(true);\n fireActionEvent();\n }\n }\n\n public void setLongPressTimeout(final long longPressTimeout) {\n this.longPressTimeout = longPressTimeout;\n }\n}",
"public final class UITapGestureRecognizer extends UIGestureRecognizer {\n // request to change the current state to Failed\n private static final int MESSAGE_FAILED = 1;\n // request to change the current state to Possible\n private static final int MESSAGE_RESET = 2;\n // we handle the action_pointer_up received in the onTouchEvent with a delay\n // in order to check how many fingers were actually down when we're checking them\n // in the action_up.\n private static final int MESSAGE_POINTER_UP = 3;\n // a long press will make this gesture to fail\n private static final int MESSAGE_LONG_PRESS = 4;\n\n private final int scaledTouchSlop;\n private final long tapTimeout = TAP_TIMEOUT;\n private final PointF mDownFocus = new PointF(), mDownCurrentLocation = new PointF();\n private int mNumTaps = 0;\n private boolean mStarted, mAlwaysInTapRegion = false;\n\n public UITapGestureRecognizer(final int scaledTouchSlop) {\n super();\n this.mStarted = false;\n this.scaledTouchSlop = scaledTouchSlop;\n }\n\n @Override\n public boolean onTouchEvent(final MotionEvent event) {\n super.onTouchEvent(event);\n\n if (!isEnabled) return false;\n\n final int action = event.getActionMasked();\n final int count = event.getPointerCount();\n if (action == MotionEvent.ACTION_DOWN) {\n removeMessages();\n mAlwaysInTapRegion = true;\n mNumberOfTouches = count;\n\n state = State.POSSIBLE;\n setBeginFiringEvents(false);\n\n if (!mStarted) {\n mNumTaps = 0;\n mStarted = true;\n }\n\n mHandler.sendEmptyMessageDelayed(MESSAGE_LONG_PRESS, tapTimeout + TIMEOUT_DELAY_MILLIS);\n\n mNumTaps++;\n mDownFocus.set(mCurrentLocation);\n mDownCurrentLocation.set(mCurrentLocation);\n } else if (action == MotionEvent.ACTION_POINTER_DOWN) {\n if (state == State.POSSIBLE && mStarted) {\n removeMessages(MESSAGE_POINTER_UP);\n mNumberOfTouches = count;\n if (mNumberOfTouches > 1) state = State.FAILED;\n mDownFocus.set(mCurrentLocation);\n mDownCurrentLocation.set(mCurrentLocation);\n }\n } else if (action == MotionEvent.ACTION_POINTER_UP) {\n if (state == State.POSSIBLE && mStarted) {\n removeMessages(MESSAGE_FAILED, MESSAGE_RESET, MESSAGE_POINTER_UP);\n mDownFocus.set(mCurrentLocation);\n\n final Message message = mHandler.obtainMessage(MESSAGE_POINTER_UP);\n message.arg1 = mNumberOfTouches - 1;\n mHandler.sendMessageDelayed(message, UIGestureRecognizer.TAP_TIMEOUT);\n }\n } else if (action == MotionEvent.ACTION_MOVE) {\n // if taps and touches > 1 then we need to be less strict\n if (state == State.POSSIBLE && mStarted && mAlwaysInTapRegion && Utils.distance(mDownFocus, mCurrentLocation) > scaledTouchSlop) {\n mDownCurrentLocation.set(mCurrentLocation);\n mAlwaysInTapRegion = false;\n removeMessages();\n state = State.FAILED;\n }\n } else if (action == MotionEvent.ACTION_UP) {\n removeMessages(MESSAGE_RESET, MESSAGE_POINTER_UP, MESSAGE_LONG_PRESS);\n if (state != State.POSSIBLE || !mStarted) handleReset();\n else if (mNumberOfTouches != 1) handleFailed();\n else if (mNumTaps < 1) delayedFail();\n else {\n state = State.ENDED;\n fireActionEventIfCanRecognizeSimultaneously();\n postReset();\n mStarted = false;\n }\n } else if (action == MotionEvent.ACTION_CANCEL) {\n removeMessages();\n mStarted = false;\n state = State.CANCELLED;\n setBeginFiringEvents(false);\n postReset();\n }\n\n if (state == State.POSSIBLE) return !cancelsTouchesInView;\n else if (state == State.ENDED) return !cancelsTouchesInView;\n\n return cancelsTouchesInView;\n }\n\n @Override\n protected void handleMessage(@NonNull final Message msg) {\n if (msg.what == MESSAGE_RESET) handleReset();\n else if (msg.what == MESSAGE_POINTER_UP) mNumberOfTouches = msg.arg1;\n else if (msg.what == MESSAGE_FAILED || msg.what == MESSAGE_LONG_PRESS) handleFailed();\n }\n\n @Override\n public void reset() {\n super.reset();\n handleReset();\n }\n\n @Override\n public boolean hasBeganFiringEvents() {\n return super.hasBeganFiringEvents() && inState(State.ENDED);\n }\n\n @Override\n protected void removeMessages() {\n removeMessages(MESSAGE_FAILED, MESSAGE_RESET, MESSAGE_POINTER_UP, MESSAGE_LONG_PRESS);\n }\n\n private void handleReset() {\n state = State.POSSIBLE;\n setBeginFiringEvents(false);\n mStarted = false;\n }\n\n private void postReset() {\n mHandler.sendEmptyMessage(MESSAGE_RESET);\n }\n\n private void fireActionEventIfCanRecognizeSimultaneously() {\n if (delegate.shouldRecognizeSimultaneouslyWithGestureRecognizer(this)) {\n setBeginFiringEvents(true);\n fireActionEvent();\n }\n }\n\n private void handleFailed() {\n state = State.FAILED;\n setBeginFiringEvents(false);\n removeMessages();\n mStarted = false;\n }\n\n private void delayedFail() {\n mHandler.sendEmptyMessageDelayed(MESSAGE_FAILED, DOUBLE_TAP_TIMEOUT);\n }\n}",
"public final class Tooltip {\n private final Context context;\n private final LayoutInflater inflater;\n\n private final int padding;\n private final float toleranceSize;\n private final boolean mShowArrow = true;\n private final WindowManager windowManager;\n private final Handler handler = new Handler(Looper.getMainLooper());\n private final Point anchorPoint = new Point(0, 0);\n private final TooltipTextDrawable textDrawable;\n private final Runnable hideRunnable = this::hide, activateRunnable = () -> isActivated = true;\n private final Gravity[] gravities = {Gravity.LEFT, Gravity.RIGHT, Gravity.TOP, Gravity.BOTTOM};\n\n private boolean hasAnchorView = false;\n private boolean isActivated = false;\n private boolean isShowing = false;\n private boolean isVisible = false;\n private View contentView;\n private TextView textView;\n private CharSequence text;\n private Positions currentPosition = null;\n private TooltipFunctions tooltipFunctions;\n private WeakReference<View> anchorView = null;\n private TooltipViewContainer popupView = null;\n\n public Tooltip(@NonNull final Context context, final View anchorView, final CharSequence text) {\n this.context = context;\n this.text = text;\n\n final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();\n this.toleranceSize = displayMetrics.density * 10f;\n this.padding = Math.round(displayMetrics.density * 20f);\n\n this.inflater = LayoutInflater.from(context);\n this.windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n\n this.textDrawable = new TooltipTextDrawable(context);\n\n if (anchorView != null) {\n this.anchorView = new WeakReference<>(anchorView);\n this.hasAnchorView = true;\n }\n }\n\n public View getContentView() {\n return contentView;\n }\n\n public void setupTooltipFunction(final TooltipFunctions tooltipFunctions) {\n this.tooltipFunctions = tooltipFunctions;\n }\n\n public void update(final CharSequence text) {\n this.text = text;\n if (isShowing && null != popupView) textView.setText(text instanceof Spannable ? text :\n HtmlCompat.fromHtml(String.valueOf(text), HtmlCompat.FROM_HTML_MODE_COMPACT));\n }\n\n @Nullable\n private Positions findPosition(final View parent, @Nullable final View anchor, final Point offset, final ArrayList<Gravity> gravities,\n final WindowManager.LayoutParams params, final boolean fitToScreen) {\n if (popupView == null || gravities.isEmpty()) return null;\n\n final Gravity gravity = gravities.remove(0);\n\n final Rect displayFrame = new Rect();\n final int[] anchorPosition = {0, 0};\n\n parent.getWindowVisibleDisplayFrame(displayFrame);\n\n if (anchor != null) {\n anchor.getLocationOnScreen(anchorPosition);\n final int width = anchor.getWidth();\n final int height = anchor.getHeight();\n\n if (gravity == Gravity.LEFT) {\n anchorPosition[1] += height / 2;\n } else if (gravity == Gravity.RIGHT) {\n anchorPosition[0] += width;\n anchorPosition[1] += height / 2;\n } else if (gravity == Gravity.TOP) {\n anchorPosition[0] += width / 2;\n } else if (gravity == Gravity.BOTTOM) {\n anchorPosition[0] += width / 2;\n anchorPosition[1] += height;\n } else if (gravity == Gravity.CENTER) {\n anchorPosition[0] += width / 2;\n anchorPosition[1] += height / 2;\n }\n }\n\n anchorPosition[0] += offset.x;\n anchorPosition[1] += offset.y;\n\n final int w = contentView.getMeasuredWidth();\n final int h = contentView.getMeasuredHeight();\n\n final Point contentPosition = new Point(), arrowPosition = new Point();\n\n if (gravity == Gravity.LEFT) {\n contentPosition.x = anchorPosition[0] - w;\n contentPosition.y = anchorPosition[1] - h / 2;\n arrowPosition.y = h / 2 - padding / 2;\n } else if (gravity == Gravity.TOP) {\n contentPosition.x = anchorPosition[0] - w / 2;\n contentPosition.y = anchorPosition[1] - h;\n arrowPosition.x = w / 2 - padding / 2;\n } else if (gravity == Gravity.RIGHT) {\n contentPosition.x = anchorPosition[0];\n contentPosition.y = anchorPosition[1] - h / 2;\n arrowPosition.y = h / 2 - padding / 2;\n } else if (gravity == Gravity.BOTTOM) {\n contentPosition.x = anchorPosition[0] - w / 2;\n contentPosition.y = anchorPosition[1];\n arrowPosition.x = w / 2 - padding / 2;\n } else if (gravity == Gravity.CENTER) {\n contentPosition.x = anchorPosition[0] - w / 2;\n contentPosition.y = anchorPosition[1] - h / 2;\n }\n\n if (fitToScreen) {\n final Rect finalRect = new Rect(contentPosition.x, contentPosition.y,\n contentPosition.x + w, contentPosition.y + h);\n if (!displayFrame.contains(Math.round(finalRect.left + toleranceSize), Math.round(finalRect.top + toleranceSize),\n Math.round(finalRect.right - toleranceSize), Math.round(finalRect.bottom - toleranceSize))) {\n return findPosition(parent, anchor, offset, gravities, params, true);\n }\n }\n\n return new Positions(new PointF(arrowPosition), new PointF(contentPosition),\n gravity, params);\n }\n\n public float getOffsetY() {\n return currentPosition == null ? 0f : currentPosition.mOffsetY;\n }\n\n private void invokePopup(final Positions positions) {\n if (positions != null) {\n isShowing = true;\n currentPosition = positions;\n\n if (hasAnchorView && anchorView.get() != null) setupListeners(anchorView.get());\n\n textDrawable.setAnchor(positions.gravity, !mShowArrow ? 0 : padding / 2,\n !mShowArrow ? null : new PointF(positions.getArrowPointX(), positions.getArrowPointY()));\n\n offsetBy();\n\n positions.params.packageName = context.getPackageName();\n popupView.setFitsSystemWindows(true);\n windowManager.addView(popupView, positions.params);\n fadeIn();\n } else\n tooltipFunctions.doOnFailure(this);\n }\n\n void offsetBy() {\n if (isShowing && popupView != null && currentPosition != null) {\n contentView.setTranslationX(currentPosition.getContentPointX());\n contentView.setTranslationY(currentPosition.getContentPointY());\n }\n }\n\n public void offsetTo(final float xoff, final float yoff) {\n if (isShowing && popupView != null && currentPosition != null) {\n currentPosition.offsetTo(xoff, yoff);\n contentView.setTranslationX(currentPosition.getContentPointX());\n contentView.setTranslationY(currentPosition.getContentPointY());\n }\n }\n\n private void setupListeners(@NonNull final View anchorView) {\n anchorView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {\n @Override\n public void onViewDetachedFromWindow(final View v) {\n v.removeOnAttachStateChangeListener(this);\n dismiss();\n }\n\n @Override\n public void onViewAttachedToWindow(final View v) { }\n });\n }\n\n public void show(final View parent, final Gravity gravity, final boolean fitToScreen) {\n if (isShowing || (hasAnchorView && anchorView.get() == null)) return;\n\n isVisible = false;\n\n final WindowManager.LayoutParams params = new WindowManager.LayoutParams();\n params.gravity = android.view.Gravity.START | android.view.Gravity.TOP;\n params.width = WindowManager.LayoutParams.MATCH_PARENT;\n params.height = WindowManager.LayoutParams.MATCH_PARENT;\n params.format = PixelFormat.TRANSLUCENT;\n params.flags = params.flags | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |\n WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |\n WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |\n WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM | 0x00010000; // == FLAG_LAYOUT_INSET_DECOR\n params.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;\n params.token = parent.getWindowToken();\n params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;\n params.setTitle(\"ToolTip:\" + Integer.toHexString(hashCode()));\n\n popupView = new TooltipViewContainer(context);\n contentView = inflater.inflate(R.layout.tooltip_textview, popupView, false);\n\n textView = new MaterialTextView(new ContextThemeWrapper(context, R.style.ToolTipTextStyle));\n ((ViewGroup) contentView).addView(textView);\n\n if (textDrawable != null) textView.setBackground(textDrawable);\n if (mShowArrow) textView.setPadding(padding, padding, padding, padding);\n else textView.setPadding(padding / 2, padding / 2, padding / 2, padding / 2);\n textView.setText(text instanceof Spannable ? text :\n HtmlCompat.fromHtml(String.valueOf(text), HtmlCompat.FROM_HTML_MODE_COMPACT));\n\n popupView.addView(contentView, new FrameLayout.LayoutParams(\n ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));\n popupView.setMeasureAllChildren(true);\n popupView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);\n\n textView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {\n @Override\n public void onViewAttachedToWindow(final View v) {\n handler.removeCallbacks(activateRunnable);\n handler.postDelayed(activateRunnable, 0);\n }\n\n @Override\n public void onViewDetachedFromWindow(final View v) {\n if (v != null) v.removeOnAttachStateChangeListener(this);\n removeCallbacks();\n }\n });\n\n final ArrayList<Gravity> gravities = new ArrayList<>(0);\n Collections.addAll(gravities, this.gravities);\n gravities.remove(gravity);\n gravities.add(0, gravity);\n\n if (tooltipFunctions != null) tooltipFunctions.doOnPrepare(this);\n\n invokePopup(findPosition(parent, anchorView.get(),\n anchorPoint, gravities, params, fitToScreen));\n }\n\n void hide() {\n if (isShowing) fadeOut();\n }\n\n public void dismiss() {\n if (isShowing && popupView != null) {\n removeCallbacks();\n windowManager.removeView(popupView);\n popupView = null;\n isShowing = false;\n isVisible = false;\n\n if (tooltipFunctions != null) tooltipFunctions.doOnHidden(this);\n }\n }\n\n private void removeCallbacks() {\n handler.removeCallbacks(hideRunnable);\n handler.removeCallbacks(activateRunnable);\n }\n\n private void fadeIn() {\n if (!isShowing || isVisible) return;\n\n textView.clearAnimation();\n textView.startAnimation(AnimationUtils.loadAnimation(context, R.anim.anim_in_bottom));\n\n isVisible = true;\n if (tooltipFunctions != null) tooltipFunctions.doOnShown(this);\n }\n\n private void fadeOut() {\n if (!isShowing || !isVisible) return;\n\n final Animation animation = AnimationUtils.loadAnimation(context, R.anim.anim_out);\n animation.setAnimationListener(new AnimationListener() {\n @Override\n public void onAnimationEnd(final Animation animation) {\n isVisible = false;\n removeCallbacks();\n dismiss();\n }\n\n @Override\n public void onAnimationStart(final Animation animation) { }\n\n @Override\n public void onAnimationRepeat(final Animation animation) { }\n });\n animation.start();\n\n textView.clearAnimation();\n textView.startAnimation(animation);\n }\n\n ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n public enum Gravity {LEFT, RIGHT, TOP, BOTTOM, CENTER,}\n\n private final class TooltipViewContainer extends FrameLayout {\n private TooltipViewContainer(final Context context) {\n super(context);\n setClipChildren(false);\n setClipToPadding(false);\n }\n\n @Override\n protected void onLayout(final boolean changed, final int left, final int top, final int right, final int bottom) {\n super.onLayout(changed, left, top, right, bottom);\n\n if (changed) {\n final int[] out = {-1, -1};\n getLocationOnScreen(out);\n offsetTopAndBottom(-out[1]);\n }\n }\n\n @Override\n public boolean dispatchKeyEvent(final KeyEvent event) {\n if (isShowing && isVisible && isActivated && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {\n final KeyEvent.DispatcherState keyDispatcherState = getKeyDispatcherState();\n\n if (keyDispatcherState == null) return super.dispatchKeyEvent(event);\n\n final int action = event.getAction();\n if (action == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {\n keyDispatcherState.startTracking(event, this);\n return true;\n }\n if (action == KeyEvent.ACTION_UP) {\n if (keyDispatcherState.isTracking(event) && !event.isCanceled()) {\n hide();\n return true;\n }\n }\n }\n return super.dispatchKeyEvent(event);\n }\n\n @SuppressLint(\"ClickableViewAccessibility\")\n @Override\n public boolean onTouchEvent(final MotionEvent event) {\n if (!isShowing || !isVisible || !isActivated) return false;\n hide();\n return false;\n }\n }\n\n private static final class Positions {\n private final Gravity gravity;\n private final PointF arrowPoint, contentPoint;\n private final WindowManager.LayoutParams params;\n private float mOffsetX = 0f, mOffsetY = 0f;\n\n private Positions(final PointF arrowPoint, final PointF contentPoint, final Gravity gravity,\n final WindowManager.LayoutParams params) {\n this.arrowPoint = arrowPoint;\n this.contentPoint = contentPoint;\n this.gravity = gravity;\n this.params = params;\n }\n\n private void offsetTo(final float x, final float y) {\n mOffsetX = x;\n mOffsetY = y;\n }\n\n public float getArrowPointX() {\n return arrowPoint.x + mOffsetX;\n }\n\n public float getArrowPointY() {\n return arrowPoint.y + mOffsetY; // - displayFrame.top\n }\n\n public float getContentPointX() {\n return contentPoint.x + mOffsetX;\n }\n\n public float getContentPointY() {\n return contentPoint.y + mOffsetY; // - displayFrame.top\n }\n }\n}",
"public interface TooltipFunctions {\n void doOnPrepare(final Tooltip tooltip);\n void doOnShown(final Tooltip tooltip);\n default void doOnHidden(final Tooltip tooltip) {}\n default void doOnFailure(final Tooltip tooltip) {}\n}"
] | import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.view.ContextThemeWrapper;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;
import awais.backworddictionary.R;
import awais.backworddictionary.helpers.Utils;
import awais.backworddictionary.interfaces.NumberPickerProgressListener;
import awais.sephiroth.uigestures.UIGestureRecognizer.State;
import awais.sephiroth.uigestures.UIGestureRecognizerDelegate;
import awais.sephiroth.uigestures.UILongPressGestureRecognizer;
import awais.sephiroth.uigestures.UITapGestureRecognizer;
import awais.sephiroth.xtooltip.Tooltip;
import awais.sephiroth.xtooltip.TooltipFunctions; | package awais.sephiroth.numberpicker;
/**
* Thanks to sephiroth74 for his NumberPicker library written in Kotlin
* https://github.com/sephiroth74/NumberSlidingPicker
*/
public final class HorizontalNumberPicker extends LinearLayoutCompat implements TextWatcher {
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
private static final int DEFAULT_MAX_VALUE = 1000;
private static final int DEFAULT_MIN_VALUE = 1;
private static final long LONG_TAP_TIMEOUT = 300L;
private static final int[][] API_20_BELOW_STATE_DRAWABLES = {
new int[]{-android.R.attr.state_focused},
new int[]{android.R.attr.state_focused},
new int[]{-android.R.attr.state_enabled},
};
private static final int[] FOCUSED_STATE_ARRAY = {android.R.attr.state_focused};
private static final int[] UNFOCUSED_STATE_ARRAY = {-android.R.attr.state_focused}; // todo was 0, -focused
private final ExponentialTracker tracker;
private final UIGestureRecognizerDelegate delegate = new UIGestureRecognizerDelegate();
private final AppCompatImageButton btnLeft, btnRight;
private final EditText editText;
private int minValue = DEFAULT_MIN_VALUE, maxValue = DEFAULT_MAX_VALUE, value = 1;
private boolean requestedDisallowIntercept = false; | private NumberPickerProgressListener progressListener; | 1 |
philliphsu/ClockPlus | app/src/main/java/com/philliphsu/clock2/alarms/ui/ExpandedAlarmViewHolder.java | [
"@AutoValue\npublic abstract class Alarm extends ObjectWithId implements Parcelable {\n private static final int MAX_MINUTES_CAN_SNOOZE = 30;\n\n // =================== MUTABLE =======================\n private long snoozingUntilMillis;\n private boolean enabled;\n private final boolean[] recurringDays = new boolean[NUM_DAYS];\n private boolean ignoreUpcomingRingTime;\n // ====================================================\n\n public abstract int hour();\n public abstract int minutes();\n public abstract String label();\n public abstract String ringtone();\n public abstract boolean vibrates();\n /** Initializes a Builder to the same property values as this instance */\n public abstract Builder toBuilder();\n\n @Deprecated\n public static Alarm create(JSONObject jsonObject) {\n throw new UnsupportedOperationException();\n }\n\n public void copyMutableFieldsTo(Alarm target) {\n target.setId(this.getId());\n target.snoozingUntilMillis = this.snoozingUntilMillis;\n target.enabled = this.enabled;\n System.arraycopy(this.recurringDays, 0, target.recurringDays, 0, NUM_DAYS);\n target.ignoreUpcomingRingTime = this.ignoreUpcomingRingTime;\n }\n\n public static Builder builder() {\n // Unfortunately, default values must be provided for generated Builders.\n // Fields that were not set when build() is called will throw an exception.\n return new AutoValue_Alarm.Builder()\n .hour(0)\n .minutes(0)\n .label(\"\")\n .ringtone(\"\")\n .vibrates(false);\n }\n\n public void snooze(int minutes) {\n if (minutes <= 0 || minutes > MAX_MINUTES_CAN_SNOOZE)\n throw new IllegalArgumentException(\"Cannot snooze for \"+minutes+\" minutes\");\n snoozingUntilMillis = System.currentTimeMillis() + minutes * 60000;\n }\n\n public long snoozingUntil() {\n return isSnoozed() ? snoozingUntilMillis : 0;\n }\n\n public boolean isSnoozed() {\n if (snoozingUntilMillis <= System.currentTimeMillis()) {\n snoozingUntilMillis = 0;\n return false;\n }\n return true;\n }\n\n /** <b>ONLY CALL THIS WHEN CREATING AN ALARM INSTANCE FROM A CURSOR</b> */\n // TODO: To be even more safe, create a ctor that takes a Cursor and\n // initialize the instance here instead of in AlarmDatabaseHelper.\n public void setSnoozing(long snoozingUntilMillis) {\n this.snoozingUntilMillis = snoozingUntilMillis;\n }\n\n public void stopSnoozing() {\n snoozingUntilMillis = 0;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public boolean[] recurringDays() {\n return recurringDays;\n }\n\n public void setRecurring(int day, boolean recurring) {\n checkDay(day);\n recurringDays[day] = recurring;\n }\n\n public boolean isRecurring(int day) {\n checkDay(day);\n return recurringDays[day];\n }\n\n public boolean hasRecurrence() {\n return numRecurringDays() > 0;\n }\n\n public int numRecurringDays() {\n int count = 0;\n for (boolean b : recurringDays)\n if (b) count++;\n return count;\n }\n\n public void ignoreUpcomingRingTime(boolean ignore) {\n ignoreUpcomingRingTime = ignore;\n }\n\n public boolean isIgnoringUpcomingRingTime() {\n return ignoreUpcomingRingTime;\n }\n\n public long ringsAt() {\n // Always with respect to the current date and time\n Calendar calendar = new GregorianCalendar();\n calendar.set(Calendar.HOUR_OF_DAY, hour());\n calendar.set(Calendar.MINUTE, minutes());\n calendar.set(Calendar.SECOND, 0);\n calendar.set(Calendar.MILLISECOND, 0);\n\n long baseRingTime = calendar.getTimeInMillis();\n\n if (!hasRecurrence()) {\n if (baseRingTime <= System.currentTimeMillis()) {\n // The specified time has passed for today\n baseRingTime += TimeUnit.DAYS.toMillis(1);\n }\n return baseRingTime;\n } else {\n // Compute the ring time just for the next closest recurring day.\n // Remember that day constants defined in the Calendar class are\n // not zero-based like ours, so we have to compensate with an offset\n // of magnitude one, with the appropriate sign based on the situation.\n int weekdayToday = calendar.get(Calendar.DAY_OF_WEEK);\n int numDaysFromToday = -1;\n\n for (int i = weekdayToday; i <= Calendar.SATURDAY; i++) {\n if (isRecurring(i - 1 /*match up with our day constant*/)) {\n if (i == weekdayToday) {\n if (baseRingTime > System.currentTimeMillis()) {\n // The normal ring time has not passed yet\n numDaysFromToday = 0;\n break;\n }\n } else {\n numDaysFromToday = i - weekdayToday;\n break;\n }\n }\n }\n\n // Not computed yet\n if (numDaysFromToday < 0) {\n for (int i = Calendar.SUNDAY; i < weekdayToday; i++) {\n if (isRecurring(i - 1 /*match up with our day constant*/)) {\n numDaysFromToday = Calendar.SATURDAY - weekdayToday + i;\n break;\n }\n }\n }\n\n // Still not computed yet. The only recurring day is weekdayToday,\n // and its normal ring time has already passed.\n if (numDaysFromToday < 0 && isRecurring(weekdayToday - 1)\n && baseRingTime <= System.currentTimeMillis()) {\n numDaysFromToday = 7;\n }\n\n if (numDaysFromToday < 0)\n throw new IllegalStateException(\"How did we get here?\");\n\n return baseRingTime + TimeUnit.DAYS.toMillis(numDaysFromToday);\n }\n }\n\n public long ringsIn() {\n return ringsAt() - System.currentTimeMillis();\n }\n\n /**\n * Returns whether this Alarm is upcoming in the next {@code hours} hours.\n * To return true, this Alarm must not have its {@link #ignoreUpcomingRingTime}\n * member field set to true.\n * @see #ignoreUpcomingRingTime(boolean)\n */\n public boolean ringsWithinHours(int hours) {\n return !ignoreUpcomingRingTime && ringsIn() <= TimeUnit.HOURS.toMillis(hours);\n }\n\n // ============================ PARCELABLE ==============================\n // Unfortunately, we can't use the Parcelable extension for AutoValue because\n // our model isn't totally immutable. Our mutable properties will be left\n // out of the generated class.\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(hour());\n dest.writeInt(minutes());\n dest.writeString(label());\n dest.writeString(ringtone());\n dest.writeInt(vibrates() ? 1 : 0);\n // Mutable fields must be written after the immutable fields,\n // because when we recreate the object, we can't initialize\n // those mutable fields until after we call build(). Values\n // in the parcel are read in the order they were written.\n dest.writeLong(getId());\n dest.writeLong(snoozingUntilMillis);\n dest.writeInt(enabled ? 1 : 0);\n dest.writeBooleanArray(recurringDays);\n dest.writeInt(ignoreUpcomingRingTime ? 1 : 0);\n }\n\n private static Alarm create(Parcel in) {\n Alarm alarm = Alarm.builder()\n .hour(in.readInt())\n .minutes(in.readInt())\n .label(in.readString())\n .ringtone(in.readString())\n .vibrates(in.readInt() != 0)\n .build();\n alarm.setId(in.readLong());\n alarm.snoozingUntilMillis = in.readLong();\n alarm.enabled = in.readInt() != 0;\n in.readBooleanArray(alarm.recurringDays);\n alarm.ignoreUpcomingRingTime = in.readInt() != 0;\n return alarm;\n }\n\n public static final Parcelable.Creator<Alarm> CREATOR\n = new Parcelable.Creator<Alarm>() {\n @Override\n public Alarm createFromParcel(Parcel source) {\n return Alarm.create(source);\n }\n\n @Override\n public Alarm[] newArray(int size) {\n return new Alarm[size];\n }\n };\n\n // ======================================================================\n\n @AutoValue.Builder\n public abstract static class Builder {\n public abstract Builder hour(int hour);\n public abstract Builder minutes(int minutes);\n public abstract Builder label(String label);\n public abstract Builder ringtone(String ringtone);\n public abstract Builder vibrates(boolean vibrates);\n /* package */ abstract Alarm autoBuild();\n\n public Alarm build() {\n Alarm alarm = autoBuild();\n doChecks(alarm);\n return alarm;\n }\n }\n\n private static void doChecks(Alarm alarm) {\n checkTime(alarm.hour(), alarm.minutes());\n }\n\n private static void checkDay(int day) {\n if (day < SUNDAY || day > SATURDAY) {\n throw new IllegalArgumentException(\"Invalid day of week: \" + day);\n }\n }\n\n private static void checkTime(int hour, int minutes) {\n if (hour < 0 || hour > 23 || minutes < 0 || minutes > 59) {\n throw new IllegalStateException(\"Hour and minutes invalid\");\n }\n }\n}",
"public final class AlarmController {\n private static final String TAG = \"AlarmController\";\n\n private final Context mAppContext;\n private final View mSnackbarAnchor;\n // TODO: Why aren't we using AsyncAlarmsTableUpdateHandler?\n private final AlarmsTableManager mTableManager;\n\n /**\n *\n * @param context the Context from which the application context will be requested\n * @param snackbarAnchor an optional anchor for a Snackbar to anchor to\n */\n public AlarmController(Context context, View snackbarAnchor) {\n mAppContext = context.getApplicationContext();\n mSnackbarAnchor = snackbarAnchor;\n mTableManager = new AlarmsTableManager(context);\n }\n\n /**\n * Schedules the alarm with the {@link AlarmManager}.\n * If {@code alarm.}{@link Alarm#isEnabled() isEnabled()}\n * returns false, this does nothing and returns immediately.\n * \n * If there is already an alarm for this Intent scheduled (with the equality of two\n * intents being defined by filterEquals(Intent)), then it will be removed and replaced\n * by this one. For most of our uses, the relevant criteria for equality will be the\n * action, the data, and the class (component). Although not documented, the request code\n * of a PendingIntent is also considered to determine equality of two intents.\n */\n public void scheduleAlarm(Alarm alarm, boolean showSnackbar) {\n if (!alarm.isEnabled()) {\n return;\n }\n // Does nothing if it's not posted. This is primarily here for when alarms\n // are updated, instead of newly created, so that we don't leave behind\n // stray upcoming alarm notifications. This occurs e.g. when a single-use\n // alarm is updated to recur on a weekday later than the current day.\n removeUpcomingAlarmNotification(alarm);\n\n AlarmManager am = (AlarmManager) mAppContext.getSystemService(Context.ALARM_SERVICE);\n\n final long ringAt = alarm.isSnoozed() ? alarm.snoozingUntil() : alarm.ringsAt();\n final PendingIntent alarmIntent = alarmIntent(alarm, false);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n PendingIntent showIntent = ContentIntentUtils.create(mAppContext, MainActivity.PAGE_ALARMS, alarm.getId());\n AlarmManager.AlarmClockInfo info = new AlarmManager.AlarmClockInfo(ringAt, showIntent);\n am.setAlarmClock(info, alarmIntent);\n } else {\n // WAKEUP alarm types wake the CPU up, but NOT the screen;\n // you would handle that yourself by using a wakelock, etc..\n am.setExact(AlarmManager.RTC_WAKEUP, ringAt, alarmIntent);\n // Show alarm in the status bar\n Intent alarmChanged = new Intent(\"android.intent.action.ALARM_CHANGED\");\n alarmChanged.putExtra(\"alarmSet\", true/*enabled*/);\n mAppContext.sendBroadcast(alarmChanged);\n }\n\n final int hoursToNotifyInAdvance = AlarmPreferences.hoursBeforeUpcoming(mAppContext);\n if (hoursToNotifyInAdvance > 0 || alarm.isSnoozed()) {\n // If snoozed, upcoming note posted immediately.\n long upcomingAt = ringAt - HOURS.toMillis(hoursToNotifyInAdvance);\n // We use a WAKEUP alarm to send the upcoming alarm notification so it goes off even if the\n // device is asleep. Otherwise, it will not go off until the device is turned back on.\n am.set(AlarmManager.RTC_WAKEUP, upcomingAt, notifyUpcomingAlarmIntent(alarm, false));\n }\n\n if (showSnackbar) {\n String message = mAppContext.getString(R.string.alarm_set_for,\n DurationUtils.toString(mAppContext, alarm.ringsIn(), false/*abbreviate*/));\n showSnackbar(message);\n }\n }\n\n /**\n * Cancel the alarm. This does NOT check if you previously scheduled the alarm.\n * @param rescheduleIfRecurring True if the alarm should be rescheduled after cancelling.\n * This param will only be considered if the alarm has recurrence\n * and is enabled.\n */\n public void cancelAlarm(Alarm alarm, boolean showSnackbar, boolean rescheduleIfRecurring) {\n Log.d(TAG, \"Cancelling alarm \" + alarm);\n AlarmManager am = (AlarmManager) mAppContext.getSystemService(Context.ALARM_SERVICE);\n\n PendingIntent pi = alarmIntent(alarm, true);\n if (pi != null) {\n am.cancel(pi);\n pi.cancel();\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n // Remove alarm in the status bar\n Intent alarmChanged = new Intent(\"android.intent.action.ALARM_CHANGED\");\n alarmChanged.putExtra(\"alarmSet\", false/*enabled*/);\n mAppContext.sendBroadcast(alarmChanged);\n }\n }\n\n pi = notifyUpcomingAlarmIntent(alarm, true);\n if (pi != null) {\n am.cancel(pi);\n pi.cancel();\n }\n\n // Does nothing if it's not posted.\n removeUpcomingAlarmNotification(alarm);\n\n final int hoursToNotifyInAdvance = AlarmPreferences.hoursBeforeUpcoming(mAppContext);\n // ------------------------------------------------------------------------------------\n // TOneverDO: Place block after making value changes to the alarm.\n if ((hoursToNotifyInAdvance > 0 && showSnackbar\n // TODO: Consider showing the snackbar for non-upcoming alarms too;\n // then, we can remove these checks.\n && alarm.ringsWithinHours(hoursToNotifyInAdvance)) || alarm.isSnoozed()) {\n long time = alarm.isSnoozed() ? alarm.snoozingUntil() : alarm.ringsAt();\n String msg = mAppContext.getString(R.string.upcoming_alarm_dismissed,\n formatTime(mAppContext, time));\n showSnackbar(msg);\n }\n // ------------------------------------------------------------------------------------\n\n if (alarm.isSnoozed()) {\n alarm.stopSnoozing();\n }\n\n if (!alarm.hasRecurrence()) {\n alarm.setEnabled(false);\n } else if (alarm.isEnabled() && rescheduleIfRecurring) {\n if (alarm.ringsWithinHours(hoursToNotifyInAdvance)) {\n // Still upcoming today, so wait until the normal ring time\n // passes before rescheduling the alarm.\n alarm.ignoreUpcomingRingTime(true); // Useful only for VH binding\n Intent intent = new Intent(mAppContext, PendingAlarmScheduler.class)\n .putExtra(PendingAlarmScheduler.EXTRA_ALARM_ID, alarm.getId());\n pi = PendingIntent.getBroadcast(mAppContext, alarm.getIntId(),\n intent, FLAG_CANCEL_CURRENT);\n am.set(AlarmManager.RTC_WAKEUP, alarm.ringsAt(), pi);\n } else {\n scheduleAlarm(alarm, false);\n }\n }\n\n save(alarm);\n\n // If service is not running, nothing happens\n mAppContext.stopService(new Intent(mAppContext, AlarmRingtoneService.class));\n }\n\n public void snoozeAlarm(Alarm alarm) {\n int minutesToSnooze = AlarmPreferences.snoozeDuration(mAppContext);\n alarm.snooze(minutesToSnooze);\n scheduleAlarm(alarm, false);\n String message = mAppContext.getString(R.string.title_snoozing_until,\n formatTime(mAppContext, alarm.snoozingUntil()));\n // Since snoozing is always done by an app component away from\n // the list screen, the Snackbar will never be shown. In fact, this\n // controller has a null mSnackbarAnchor if we're using it for snoozing\n // an alarm. We solve this by preparing the message, and waiting until\n // the list screen is resumed so that it can display the Snackbar for us.\n DelayedSnackbarHandler.prepareMessage(message);\n save(alarm);\n }\n\n public void removeUpcomingAlarmNotification(Alarm a) {\n Intent intent = new Intent(mAppContext, UpcomingAlarmReceiver.class)\n .setAction(UpcomingAlarmReceiver.ACTION_CANCEL_NOTIFICATION)\n .putExtra(UpcomingAlarmReceiver.EXTRA_ALARM, ParcelableUtil.marshall(a));\n mAppContext.sendBroadcast(intent);\n }\n\n public void save(final Alarm alarm) {\n // TODO: Will using the Runnable like this cause a memory leak?\n new Thread(new Runnable() {\n @Override\n public void run() {\n mTableManager.updateItem(alarm.getId(), alarm);\n }\n }).start();\n }\n\n private PendingIntent alarmIntent(Alarm alarm, boolean retrievePrevious) {\n Intent intent = new Intent(mAppContext, AlarmActivity.class)\n .putExtra(AlarmActivity.EXTRA_RINGING_OBJECT, ParcelableUtil.marshall(alarm));\n int flag = retrievePrevious ? FLAG_NO_CREATE : FLAG_CANCEL_CURRENT;\n // Even when we try to retrieve a previous instance that actually did exist,\n // null can be returned for some reason. Thus, we don't checkNotNull().\n return getActivity(mAppContext, alarm.getIntId(), intent, flag);\n }\n\n private PendingIntent notifyUpcomingAlarmIntent(Alarm alarm, boolean retrievePrevious) {\n Intent intent = new Intent(mAppContext, UpcomingAlarmReceiver.class)\n .putExtra(UpcomingAlarmReceiver.EXTRA_ALARM, ParcelableUtil.marshall(alarm));\n if (alarm.isSnoozed()) {\n intent.setAction(UpcomingAlarmReceiver.ACTION_SHOW_SNOOZING);\n }\n int flag = retrievePrevious ? FLAG_NO_CREATE : FLAG_CANCEL_CURRENT;\n // Even when we try to retrieve a previous instance that actually did exist,\n // null can be returned for some reason. Thus, we don't checkNotNull().\n return PendingIntent.getBroadcast(mAppContext, alarm.getIntId(), intent, flag);\n }\n\n private void showSnackbar(final String message) {\n // Is the window containing this anchor currently focused?\n// Log.d(TAG, \"Anchor has window focus? \" + mSnackbarAnchor.hasWindowFocus());\n if (mSnackbarAnchor != null /*&& mSnackbarAnchor.hasWindowFocus()*/) {\n // Queue the message on the view's message loop, so the message\n // gets processed once the view gets attached to the window.\n // This executes on the UI thread, just like not queueing it will,\n // but the difference here is we wait for the view to be attached\n // to the window (if not already) before executing the runnable code.\n mSnackbarAnchor.post(new Runnable() {\n @Override\n public void run() {\n Snackbar.make(mSnackbarAnchor, message, Snackbar.LENGTH_LONG).show();\n }\n });\n }\n }\n}",
"public final class DaysOfWeek {\n private static final String TAG = \"DaysOfWeek\";\n // DAY_OF_WEEK constants in Calendar class not zero-based\n public static final int SUNDAY = 0;\n public static final int MONDAY = 1;\n public static final int TUESDAY = 2;\n public static final int WEDNESDAY = 3;\n public static final int THURSDAY = 4;\n public static final int FRIDAY = 5;\n public static final int SATURDAY = 6;\n public static final int NUM_DAYS = 7;\n\n private static final int[] DAYS = new int[NUM_DAYS];\n private static final String[] LABELS = new DateFormatSymbols().getShortWeekdays();\n\n private static DaysOfWeek sInstance;\n private static int sLastPreferredFirstDay;\n\n public static DaysOfWeek getInstance(Context context) {\n int preferredFirstDay = AlarmPreferences.firstDayOfWeek(context);\n if (sInstance == null || preferredFirstDay != sLastPreferredFirstDay) {\n sLastPreferredFirstDay = preferredFirstDay;\n sInstance = new DaysOfWeek(preferredFirstDay);\n }\n Log.d(TAG, sInstance.toString());\n return sInstance;\n }\n\n /**\n * @param weekday the zero-based index of the week day you would like to get the label for.\n\n */\n public static String getLabel(int weekday) {\n // This array was returned from DateFormatSymbols.getShortWeekdays().\n // We are supposed to use the constants in the Calendar class as indices, but the previous\n // implementation of this method used our own zero-based indices. For backward compatibility,\n // we add one to the index passed in to match up with the values of the Calendar constants.\n return LABELS[weekday + 1];\n }\n\n /** @return the week day at {@code position} within the user-defined week */\n public int weekDayAt(int position) {\n if (position < 0 || position > 6)\n throw new ArrayIndexOutOfBoundsException(\"Ordinal day out of range\");\n return DAYS[position];\n }\n\n /** @return the position of {@code weekDay} within the user-defined week */\n public int positionOf(int weekDay) {\n if (weekDay < SUNDAY || weekDay > SATURDAY)\n throw new ArrayIndexOutOfBoundsException(\"Week day (\"+weekDay+\") out of range\");\n for (int i = 0; i < DAYS.length; i++)\n if (DAYS[i] == weekDay)\n return i;\n return -1;\n }\n\n @Override\n public String toString() {\n return \"DaysOfWeek{\"\n + \"DAYS=\" + Arrays.toString(DAYS)\n + \"}\";\n }\n\n @VisibleForTesting\n DaysOfWeek(int firstDayOfWeek) {\n if (firstDayOfWeek != SATURDAY && firstDayOfWeek != SUNDAY && firstDayOfWeek != MONDAY)\n throw new IllegalArgumentException(\"Invalid first day of week: \" + firstDayOfWeek);\n DAYS[0] = firstDayOfWeek;\n for (int i = 1; i < 7; i++) {\n if (firstDayOfWeek == SATURDAY) {\n DAYS[i] = i - 1;\n } else if (firstDayOfWeek == MONDAY) {\n if (i == 6) {\n DAYS[i] = SUNDAY;\n } else {\n DAYS[i] = i + 1;\n }\n } else {\n DAYS[i] = i;\n }\n }\n }\n}",
"public class RingtonePickerDialog extends BaseAlertDialogFragment {\n private static final String TAG = \"RingtonePickerDialog\";\n private static final String KEY_RINGTONE_URI = \"key_ringtone_uri\";\n\n private RingtoneManager mRingtoneManager;\n private OnRingtoneSelectedListener mOnRingtoneSelectedListener;\n private Uri mRingtoneUri;\n private RingtoneLoop mRingtone;\n\n public interface OnRingtoneSelectedListener {\n void onRingtoneSelected(Uri ringtoneUri);\n }\n\n /**\n * @param ringtoneUri the URI of the ringtone to show as initially selected\n */\n public static RingtonePickerDialog newInstance(OnRingtoneSelectedListener l, Uri ringtoneUri) {\n RingtonePickerDialog dialog = new RingtonePickerDialog();\n dialog.mOnRingtoneSelectedListener = l;\n dialog.mRingtoneUri = ringtoneUri;\n return dialog;\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n mRingtoneUri = savedInstanceState.getParcelable(KEY_RINGTONE_URI);\n }\n mRingtoneManager = new RingtoneManager(getActivity());\n mRingtoneManager.setType(RingtoneManager.TYPE_ALARM);\n }\n\n @Override\n protected AlertDialog createFrom(AlertDialog.Builder builder) {\n // TODO: We set the READ_EXTERNAL_STORAGE permission. Verify that this includes the user's \n // custom ringtone files.\n Cursor cursor = mRingtoneManager.getCursor();\n int checkedItem = mRingtoneManager.getRingtonePosition(mRingtoneUri);\n String labelColumn = cursor.getColumnName(RingtoneManager.TITLE_COLUMN_INDEX);\n\n builder.setTitle(R.string.ringtones)\n .setSingleChoiceItems(cursor, checkedItem, labelColumn, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n if (mRingtone != null) {\n destroyLocalPlayer();\n }\n // Here, 'which' param refers to the position of the item clicked.\n mRingtoneUri = mRingtoneManager.getRingtoneUri(which);\n mRingtone = new RingtoneLoop(getActivity(), mRingtoneUri);\n mRingtone.play();\n }\n });\n return super.createFrom(builder);\n }\n\n @Override\n public void onDismiss(DialogInterface dialog) {\n super.onDismiss(dialog);\n destroyLocalPlayer();\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putParcelable(KEY_RINGTONE_URI, mRingtoneUri);\n }\n\n @Override\n protected void onOk() {\n if (mOnRingtoneSelectedListener != null) {\n // Here, 'which' param refers to the position of the item clicked.\n mOnRingtoneSelectedListener.onRingtoneSelected(mRingtoneUri);\n }\n dismiss();\n }\n\n public void setOnRingtoneSelectedListener(OnRingtoneSelectedListener onRingtoneSelectedListener) {\n mOnRingtoneSelectedListener = onRingtoneSelectedListener;\n }\n\n private void destroyLocalPlayer() {\n if (mRingtone != null) {\n mRingtone.stop();\n mRingtone = null;\n }\n }\n}",
"public class RingtonePickerDialogController extends DialogFragmentController<RingtonePickerDialog> {\n private static final String TAG = \"RingtonePickerCtrller\";\n\n private final RingtonePickerDialog.OnRingtoneSelectedListener mListener;\n\n public RingtonePickerDialogController(FragmentManager fragmentManager, RingtonePickerDialog.OnRingtoneSelectedListener l) {\n super(fragmentManager);\n mListener = l;\n }\n\n public void show(Uri initialUri, String tag) {\n RingtonePickerDialog dialog = RingtonePickerDialog.newInstance(mListener, initialUri);\n show(dialog, tag);\n }\n\n @Override\n public void tryRestoreCallback(String tag) {\n RingtonePickerDialog dialog = findDialog(tag);\n if (dialog != null) {\n Log.i(TAG, \"Restoring on ringtone selected callback\");\n dialog.setOnRingtoneSelectedListener(mListener);\n }\n }\n}",
"public interface OnListItemInteractionListener<T> {\n void onListItemClick(T item, int position);\n void onListItemDeleted(T item);\n void onListItemUpdate(T item, int position);\n}",
"public class Utils {\n\n public static final int MONDAY_BEFORE_JULIAN_EPOCH = Time.EPOCH_JULIAN_DAY - 3;\n public static final int PULSE_ANIMATOR_DURATION = 544;\n\n // Alpha level for time picker selection.\n public static final int SELECTED_ALPHA = 255;\n public static final int SELECTED_ALPHA_THEME_DARK = 255;\n // Alpha level for fully opaque.\n public static final int FULL_ALPHA = 255;\n\n static final String SHARED_PREFS_NAME = \"com.android.calendar_preferences\";\n\n public static boolean isJellybeanOrLater() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;\n }\n\n /**\n * Try to speak the specified text, for accessibility. Only available on JB or later.\n * @param text Text to announce.\n */\n @SuppressLint(\"NewApi\")\n public static void tryAccessibilityAnnounce(View view, CharSequence text) {\n if (isJellybeanOrLater() && view != null && text != null) {\n view.announceForAccessibility(text);\n }\n }\n\n public static int getDaysInMonth(int month, int year) {\n switch (month) {\n case Calendar.JANUARY:\n case Calendar.MARCH:\n case Calendar.MAY:\n case Calendar.JULY:\n case Calendar.AUGUST:\n case Calendar.OCTOBER:\n case Calendar.DECEMBER:\n return 31;\n case Calendar.APRIL:\n case Calendar.JUNE:\n case Calendar.SEPTEMBER:\n case Calendar.NOVEMBER:\n return 30;\n case Calendar.FEBRUARY:\n return (year % 4 == 0) ? 29 : 28;\n default:\n throw new IllegalArgumentException(\"Invalid Month\");\n }\n }\n\n /**\n * Takes a number of weeks since the epoch and calculates the Julian day of\n * the Monday for that week.\n *\n * This assumes that the week containing the {@link Time#EPOCH_JULIAN_DAY}\n * is considered week 0. It returns the Julian day for the Monday\n * {@code week} weeks after the Monday of the week containing the epoch.\n *\n * @param week Number of weeks since the epoch\n * @return The julian day for the Monday of the given week since the epoch\n */\n public static int getJulianMondayFromWeeksSinceEpoch(int week) {\n return MONDAY_BEFORE_JULIAN_EPOCH + week * 7;\n }\n\n /**\n * Returns the week since {@link Time#EPOCH_JULIAN_DAY} (Jan 1, 1970)\n * adjusted for first day of week.\n *\n * This takes a julian day and the week start day and calculates which\n * week since {@link Time#EPOCH_JULIAN_DAY} that day occurs in, starting\n * at 0. *Do not* use this to compute the ISO week number for the year.\n *\n * @param julianDay The julian day to calculate the week number for\n * @param firstDayOfWeek Which week day is the first day of the week,\n * see {@link Time#SUNDAY}\n * @return Weeks since the epoch\n */\n public static int getWeeksSinceEpochFromJulianDay(int julianDay, int firstDayOfWeek) {\n int diff = Time.THURSDAY - firstDayOfWeek;\n if (diff < 0) {\n diff += 7;\n }\n int refDay = Time.EPOCH_JULIAN_DAY - diff;\n return (julianDay - refDay) / 7;\n }\n\n /**\n * Render an animator to pulsate a view in place.\n * @param labelToAnimate the view to pulsate.\n * @return The animator object. Use .start() to begin.\n */\n public static ObjectAnimator getPulseAnimator(View labelToAnimate, float decreaseRatio,\n float increaseRatio) {\n Keyframe k0 = Keyframe.ofFloat(0f, 1f);\n Keyframe k1 = Keyframe.ofFloat(0.275f, decreaseRatio);\n Keyframe k2 = Keyframe.ofFloat(0.69f, increaseRatio);\n Keyframe k3 = Keyframe.ofFloat(1f, 1f);\n\n PropertyValuesHolder scaleX = PropertyValuesHolder.ofKeyframe(\"scaleX\", k0, k1, k2, k3);\n PropertyValuesHolder scaleY = PropertyValuesHolder.ofKeyframe(\"scaleY\", k0, k1, k2, k3);\n ObjectAnimator pulseAnimator =\n ObjectAnimator.ofPropertyValuesHolder(labelToAnimate, scaleX, scaleY);\n pulseAnimator.setDuration(PULSE_ANIMATOR_DURATION);\n\n return pulseAnimator;\n }\n\n /**\n * Gets the colorAccent from the current context, if possible/available\n * @param context The context to use as reference for the color\n * @return the accent color of the current context\n */\n public static int getThemeAccentColor(Context context) {\n // Source from MDTP\n// TypedValue typedValue = new TypedValue();\n// // First, try the android:colorAccent\n// if (Build.VERSION.SDK_INT >= 21) {\n// context.getTheme().resolveAttribute(android.R.attr.colorAccent, typedValue, true);\n// return typedValue.data;\n// }\n// // Next, try colorAccent from support lib\n// int colorAccentResId = context.getResources().getIdentifier(\"colorAccent\", \"attr\", context.getPackageName());\n// if (colorAccentResId != 0 && context.getTheme().resolveAttribute(colorAccentResId, typedValue, true)) {\n// return typedValue.data;\n// }\n//\n// return ContextCompat.getColor(context, R.color.accent_color);\n return getColorFromThemeAttr(context, R.attr.colorAccent);\n }\n\n public static int getTextColorFromThemeAttr(Context context, int resid) {\n // http://stackoverflow.com/a/33839580/5055032\n// final TypedValue value = new TypedValue();\n// context.getTheme().resolveAttribute(resid, value, true);\n// TypedArray a = context.obtainStyledAttributes(value.data,\n// new int[] {resid});\n TypedArray a = context.getTheme().obtainStyledAttributes(new int[] {resid});\n final int color = a.getColor(0/*index*/, 0/*defValue*/);\n a.recycle();\n return color;\n // Didn't work! Gave me white!\n// return getColorFromThemeAttr(context, android.R.attr.textColorPrimary);\n }\n\n /**\n * @param resId The resource identifier of the desired theme attribute.\n */\n public static int getColorFromThemeAttr(Context context, int resId) {\n // http://stackoverflow.com/a/28777489/5055032\n final TypedValue value = new TypedValue();\n context.getTheme().resolveAttribute(resId, value, true);\n return value.data;\n }\n\n /**\n * Mutates the given drawable, applies the specified tint list, and sets this tinted\n * drawable on the target ImageView.\n *\n * @param target the ImageView that should have the tinted drawable set on\n * @param drawable the drawable to tint\n * @param tintList Color state list to use for tinting this drawable, or null to clear the tint\n */\n public static void setTintList(ImageView target, Drawable drawable, ColorStateList tintList) {\n // TODO: What is the VectorDrawable counterpart for this process?\n // Use a mutable instance of the drawable, so we only affect this instance.\n // This is especially useful when you need to modify properties of drawables loaded from\n // resources. By default, all drawables instances loaded from the same resource share a\n // common state; if you modify the state of one instance, all the other instances will\n // receive the same modification.\n // Wrap drawable so that it may be used for tinting across the different\n // API levels, via the tinting methods in this class.\n drawable = DrawableCompat.wrap(drawable.mutate());\n DrawableCompat.setTintList(drawable, tintList);\n target.setImageDrawable(drawable);\n }\n\n public static void setTint(Drawable drawable, @ColorInt int color) {\n drawable = DrawableCompat.wrap(drawable.mutate());\n DrawableCompat.setTint(drawable, color);\n }\n\n /**\n * Returns a tinted drawable from the given drawable resource, if {@code tintList != null}.\n * Otherwise, no tint will be applied.\n */\n public static Drawable getTintedDrawable(@NonNull Context context,\n @DrawableRes int drawableRes,\n @Nullable ColorStateList tintList) {\n Drawable d = DrawableCompat.wrap(ContextCompat.getDrawable(context, drawableRes).mutate());\n DrawableCompat.setTintList(d, tintList);\n return d;\n }\n\n /**\n * Returns a tinted drawable from the given drawable resource and color resource.\n */\n public static Drawable getTintedDrawable(@NonNull Context context,\n @DrawableRes int drawableRes,\n @ColorInt int colorInt) {\n Drawable d = DrawableCompat.wrap(ContextCompat.getDrawable(context, drawableRes).mutate());\n DrawableCompat.setTint(d, colorInt);\n return d;\n }\n\n /**\n * Sets the color on the {@code view}'s {@code selectableItemBackground} or the\n * borderless variant, whichever was set as the background.\n * @param view the view that should have its highlight color changed\n */\n public static void setColorControlHighlight(@NonNull View view, @ColorInt int color) {\n Drawable selectableItemBackground = view.getBackground();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP\n && selectableItemBackground instanceof RippleDrawable) {\n ((RippleDrawable) selectableItemBackground).setColor(ColorStateList.valueOf(color));\n } else {\n // Draws the color (src) onto the background (dest) *in the same plane*.\n // That means the color is not overlapping (i.e. on a higher z-plane, covering)\n // the background. That would be done with SRC_OVER.\n // The DrawableCompat tinting APIs *could* be a viable alternative, if you\n // call setTintMode(). Previous attempts using those APIs failed without\n // the tint mode. However, those APIs have the overhead of mutating and wrapping\n // the drawable.\n selectableItemBackground.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);\n }\n }\n\n /**\n * Gets dialog type (Light/Dark) from current theme\n * @param context The context to use as reference for the boolean\n * @param current Default value to return if cannot resolve the attribute\n * @return true if dark mode, false if light.\n */\n public static boolean isDarkTheme(Context context, boolean current) {\n return resolveBoolean(context, R.attr.themeDark, current);\n }\n\n /**\n * Gets the required boolean value from the current context, if possible/available\n * @param context The context to use as reference for the boolean\n * @param attr Attribute id to resolve\n * @param fallback Default value to return if no value is specified in theme\n * @return the boolean value from current theme\n */\n private static boolean resolveBoolean(Context context, @AttrRes int attr, boolean fallback) {\n TypedArray a = context.getTheme().obtainStyledAttributes(new int[]{attr});\n try {\n return a.getBoolean(0, fallback);\n } finally {\n a.recycle();\n }\n }\n}",
"public final class FragmentTagUtils {\n\n /**\n * For general use.\n */\n public static String makeTag(Class<?> cls, @IdRes int viewId) {\n return cls.getName() + \":\" + viewId;\n }\n\n /**\n * A version suitable for our ViewHolders.\n */\n public static String makeTag(Class<?> cls, @IdRes int viewId, long itemId) {\n return makeTag(cls, viewId) + \":\" + itemId;\n }\n\n private FragmentTagUtils() {}\n}"
] | import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;
import android.support.annotation.IdRes;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ToggleButton;
import com.philliphsu.clock2.R;
import com.philliphsu.clock2.alarms.Alarm;
import com.philliphsu.clock2.alarms.misc.AlarmController;
import com.philliphsu.clock2.alarms.misc.DaysOfWeek;
import com.philliphsu.clock2.dialogs.RingtonePickerDialog;
import com.philliphsu.clock2.dialogs.RingtonePickerDialogController;
import com.philliphsu.clock2.list.OnListItemInteractionListener;
import com.philliphsu.clock2.timepickers.Utils;
import com.philliphsu.clock2.util.FragmentTagUtils;
import butterknife.Bind;
import butterknife.OnClick; | /*
* Copyright 2017 Phillip Hsu
*
* This file is part of ClockPlus.
*
* ClockPlus 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.
*
* ClockPlus 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 ClockPlus. If not, see <http://www.gnu.org/licenses/>.
*/
package com.philliphsu.clock2.alarms.ui;
/**
* Created by Phillip Hsu on 7/31/2016.
*/
public class ExpandedAlarmViewHolder extends BaseAlarmViewHolder {
private static final String TAG = "ExpandedAlarmViewHolder";
@Bind(R.id.ok) Button mOk;
@Bind(R.id.delete) Button mDelete;
@Bind(R.id.ringtone) Button mRingtone;
@Bind(R.id.vibrate) TempCheckableImageButton mVibrate;
@Bind({R.id.day0, R.id.day1, R.id.day2, R.id.day3, R.id.day4, R.id.day5, R.id.day6})
ToggleButton[] mDays;
private final ColorStateList mDayToggleColors;
private final ColorStateList mVibrateColors;
private final RingtonePickerDialogController mRingtonePickerController;
public ExpandedAlarmViewHolder(ViewGroup parent, final OnListItemInteractionListener<Alarm> listener,
AlarmController controller) {
super(parent, R.layout.item_expanded_alarm, listener, controller);
// Manually bind listeners, or else you'd need to write a getter for the
// OnListItemInteractionListener in the BaseViewHolder for use in method binding.
mDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onListItemDeleted(getAlarm());
}
});
mOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Since changes are persisted as soon as they are made, there's really
// nothing we have to persist here. Let the listener know we should
// collapse this VH.
// While this works, it also makes an update to the DB and thus reschedules
// the alarm, so the snackbar will show up as well. We want to avoid that..
// listener.onListItemUpdate(getAlarm(), getAdapterPosition());
// TODO: This only works because we know what the implementation looks like..
// This is bad because we just made the proper function of this dependent
// on the implementation.
listener.onListItemClick(getAlarm(), getAdapterPosition());
}
});
// https://code.google.com/p/android/issues/detail?id=177282
// https://stackoverflow.com/questions/15673449/is-it-confirmed-that-i-cannot-use-themed-color-attribute-in-color-state-list-res
// Programmatically create the ColorStateList for our day toggles using themed color
// attributes, "since prior to M you can't create a themed ColorStateList from XML but you
// can from code." (quote from google)
// The first array level is analogous to an XML node defining an item with a state list.
// The second level lists all the states considered by the item from the first level.
// An empty list of states represents the default stateless item.
int[][] states = {
/*item 1*/{/*states*/android.R.attr.state_checked},
/*item 2*/{/*states*/}
};
// TODO: Phase out Utils.getColorFromThemeAttr because it doesn't work for text colors.
// WHereas getTextColorFromThemeAttr works for both regular colors and text colors.
int[] dayToggleColors = {
/*item 1*/Utils.getTextColorFromThemeAttr(getContext(), R.attr.colorAccent),
/*item 2*/Utils.getTextColorFromThemeAttr(getContext(), android.R.attr.textColorHint)
};
int[] vibrateColors = {
/*item 1*/Utils.getTextColorFromThemeAttr(getContext(), R.attr.colorAccent),
/*item 2*/Utils.getTextColorFromThemeAttr(getContext(), R.attr.themedIconTint)
};
mDayToggleColors = new ColorStateList(states, dayToggleColors);
mVibrateColors = new ColorStateList(states, vibrateColors);
mRingtonePickerController = new RingtonePickerDialogController(mFragmentManager,
new RingtonePickerDialog.OnRingtoneSelectedListener() {
@Override
public void onRingtoneSelected(Uri ringtoneUri) {
Log.d(TAG, "Selected ringtone: " + ringtoneUri.toString());
final Alarm oldAlarm = getAlarm();
Alarm newAlarm = oldAlarm.toBuilder()
.ringtone(ringtoneUri.toString())
.build();
oldAlarm.copyMutableFieldsTo(newAlarm);
persistUpdatedAlarm(newAlarm, false);
}
}
);
}
@Override
public void onBind(Alarm alarm) {
super.onBind(alarm);
mRingtonePickerController.tryRestoreCallback(makeTag(R.id.ringtone));
bindDays(alarm);
bindRingtone();
bindVibrate(alarm.vibrates());
}
@Override
protected void bindLabel(boolean visible, String label) {
super.bindLabel(true, label);
}
@OnClick(R.id.ok)
void save() {
// TODO
}
// @OnClick(R.id.delete)
// void delete() {
// // TODO
// }
@OnClick(R.id.ringtone)
void showRingtonePickerDialog() {
// Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
// intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM)
// .putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false)
// // The ringtone to show as selected when the dialog is opened
// .putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, getSelectedRingtoneUri())
// // Whether to show "Default" item in the list
// .putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
// // The ringtone that plays when default option is selected
// //.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, DEFAULT_TONE);
// // TODO: This is VERY BAD. Use a Controller/Presenter instead.
// // The result will be delivered to MainActivity, and then delegated to AlarmsFragment.
// ((Activity) getContext()).startActivityForResult(intent, AlarmsFragment.REQUEST_PICK_RINGTONE);
mRingtonePickerController.show(getSelectedRingtoneUri(), makeTag(R.id.ringtone));
}
@OnClick(R.id.vibrate)
void onVibrateToggled() {
final boolean checked = mVibrate.isChecked();
if (checked) {
Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(300);
}
final Alarm oldAlarm = getAlarm();
Alarm newAlarm = oldAlarm.toBuilder()
.vibrates(checked)
.build();
oldAlarm.copyMutableFieldsTo(newAlarm);
persistUpdatedAlarm(newAlarm, false);
}
@OnClick({ R.id.day0, R.id.day1, R.id.day2, R.id.day3, R.id.day4, R.id.day5, R.id.day6 })
void onDayToggled(ToggleButton view) {
final Alarm oldAlarm = getAlarm();
Alarm newAlarm = oldAlarm.toBuilder().build();
oldAlarm.copyMutableFieldsTo(newAlarm);
// ---------------------------------------------------------------------------------
// TOneverDO: precede copyMutableFieldsTo()
int position = ((ViewGroup) view.getParent()).indexOfChild(view); | int weekDayAtPosition = DaysOfWeek.getInstance(getContext()).weekDayAt(position); | 2 |
vdmeer/svg2vector | src/main/java/de/vandermeer/svg2vector/applications/fh/Svg2Vector_FH.java | [
"public abstract class AppBase <L extends SV_DocumentLoader, P extends AppProperties<L>> implements ExecS_Application {\r\n\r\n\t/** CLI parser. */\r\n\tfinal private ExecS_CliParser cli;\r\n\r\n\t/** The properties of the application. */\r\n\tfinal private P props;\r\n\r\n\t/**\r\n\t * Creates a new base application.\r\n\t * @param props the application properties\r\n\t * @throws NullPointerException if props was null\r\n\t */\r\n\tprotected AppBase(P props){\r\n\t\tValidate.notNull(props);\r\n\t\tthis.props = props;\r\n\r\n\t\tthis.cli = new ExecS_CliParser();\r\n\t\tthis.cli.addAllOptions(this.props.getAppOptions());\r\n\t}\r\n\r\n\t/**\r\n\t * Adds a new option to CLI parser and option list.\r\n\t * @param option new option, ignored if null\r\n\t */\r\n\tprotected void addOption(ApplicationOption<?> option){\r\n\t\tif(option!=null){\r\n\t\t\tthis.getCli().addOption(option);\r\n\t\t\tthis.props.addOption(option);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int executeApplication(String[] args) {\r\n\t\t// parse command line, exit with help screen if error\r\n\t\tint ret = ExecS_Application.super.executeApplication(args);\r\n\t\tif(ret!=0){\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tthis.props.setMessageMode();\r\n\r\n\t\tSvgTargets target = this.props.getTarget();\r\n\t\tif(target==null){\r\n\t\t\tthis.printErrorMessage(\"given target <\" + this.props.getTargetValue() + \"> not supported. Use one of the supported targets: \" + new StrBuilder().appendWithSeparators(this.props.getSupportedTargetts(), \", \"));\r\n\t\t\treturn -10;\r\n\t\t}\r\n\r\n\t\tString err = null;\r\n\r\n\t\tif((err = this.props.setInput()) != null){\r\n\t\t\tthis.printErrorMessage(err);\r\n\t\t\treturn -11;\r\n\t\t}\r\n\t\tthis.printWarnings();\r\n\r\n\t\tif((err = this.props.setOutput()) != null){\r\n\t\t\tthis.printErrorMessage(err);\r\n\t\t\treturn -12;\r\n\t\t}\r\n\t\tthis.printWarnings();\r\n\r\n\t\tif(this.props.doesNoLayers()){\r\n\t\t\tthis.printProgressMessage(\"processing single output, no layers\");\r\n\t\t\tthis.printDetailMessage(\"target: \" + target.name());\r\n\t\t\tthis.printDetailMessage(\"input fn: \" + this.props.getFinFn());\r\n\t\t\tthis.printDetailMessage(\"output fn: \" + this.props.getFoutFn());\r\n\t\t}\r\n\t\telse if(props.doesLayers()){\r\n\t\t\tthis.printProgressMessage(\"processing multi layer, multi file output\");\r\n\t\t\tthis.printDetailMessage(\"target: \" + target.name());\r\n\t\t\tthis.printDetailMessage(\"input fn: \" + this.props.getFinFn());\r\n\t\t\tthis.printDetailMessage(\"output dir: \" + this.props.getDout());\r\n\t\t\tthis.printDetailMessage(\"fn pattern: \" + this.props.getFoutPattern());\r\n\t\t}\r\n\t\telse{\r\n\t\t\tthis.printErrorMessage(\"implementation error: something wrong with property settings\");\r\n\t\t\treturn -13;\r\n\t\t}\r\n\r\n\t\tif(this.props.doesCreateDirectories()){\r\n\t\t\tthis.printProgressMessage(\"creating directories for output\");\r\n\t\t\tif(this.props.getFoutFile()!=null){\r\n\t\t\t\tif(this.props.canWriteFiles()){\r\n\t\t\t\t\tthis.props.getFoutFile().getParentFile().mkdirs();\r\n\t\t\t\t}\r\n\t\t\t\tthis.printDetailMessage(\"create directories (fout): \" + this.props.getFoutFile().getParent());\r\n\t\t\t}\r\n\t\t\tif(this.props.getDoutFile()!=null){\r\n\t\t\t\tif(this.props.canWriteFiles()){\r\n\t\t\t\t\tthis.props.getDoutFile().mkdirs();\r\n\t\t\t\t}\r\n\t\t\t\tthis.printDetailMessage(\"create directories (dout): \" + this.props.getDout());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic ApplicationOption<?>[] getAppOptions() {\r\n\t\treturn this.props.getAppOptions();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic ExecS_CliParser getCli() {\r\n\t\treturn this.cli;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the application properties.\r\n\t * @return application properties\r\n\t */\r\n\tpublic P getProps(){\r\n\t\treturn this.props;\r\n\t}\r\n\r\n\t/**\r\n\t * Tests if the type is activate in the given mode.\r\n\t * @param mask the mask to test against\r\n\t * @return true if the message type (mask) is activated in the message mode, false otherwise\r\n\t */\r\n\tprivate boolean isSet(int mask){\r\n\t\treturn ((this.props.getMsgMode() & mask) == mask);\r\n\t}\r\n\r\n\t/**\r\n\t * Prints a detail message if activated in mode\r\n\t * @param msg the detail message, not printed if null\r\n\t */\r\n\tpublic void printDetailMessage(String msg){\r\n\t\tthis.printMessage(msg, AppProperties.P_OPTION_DEAILS);\r\n\t}\r\n\r\n\t/**\r\n\t * Prints a error message if activated in mode\r\n\t * @param err the error message, not printed if null\r\n\t */\r\n\tpublic void printErrorMessage(String err){\r\n\t\tthis.printMessage(err, AppProperties.P_OPTION_ERROR);\r\n\t}\r\n\r\n\t/**\r\n\t * Prints a message of give type.\r\n\t * @param msg the message, not printed if null\r\n\t * @param type the message type, nothing printed if not set in message mode\r\n\t */\r\n\tprivate void printMessage(String msg, int type){\r\n\t\tif(msg==null){\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif(this.isSet(type)){\r\n\t\t\tif(type==AppProperties.P_OPTION_ERROR){\r\n\t\t\t\tSystem.err.println(this.getAppName() + \" error: \" + msg);\r\n\t\t\t}\r\n\t\t\telse if(type==AppProperties.P_OPTION_WARNING){\r\n\t\t\t\tSystem.out.println(this.getAppName() + \" warning: \" + msg);\r\n\t\t\t}\r\n\t\t\telse if(type==AppProperties.P_OPTION_PROGRESS){\r\n\t\t\t\tSystem.out.println(this.getAppName() + \": --- \" + msg);\r\n\t\t\t}\r\n\t\t\telse if(type==AppProperties.P_OPTION_DEAILS){\r\n\t\t\t\tSystem.out.println(this.getAppName() + \": === \" + msg);\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tthrow new IllegalArgumentException(\"messaging: unknown type: \" + type);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Prints a progress message if activated in mode\r\n\t * @param msg the progress message, not printed if null\r\n\t */\r\n\tpublic void printProgressMessage(String msg){\r\n\t\tthis.printMessage(msg, AppProperties.P_OPTION_PROGRESS);\r\n\t}\r\n\r\n\t/**\r\n\t * Prints a warning message if activated in mode\r\n\t * @param msg the warning message, not printed if null\r\n\t */\r\n\tpublic void printWarningMessage(String msg){\r\n\t\tthis.printMessage(msg, AppProperties.P_OPTION_WARNING);\r\n\t}\r\n\r\n\t/**\r\n\t * Prints all warnings collected in properties and empties the warning list.\r\n\t */\r\n\tpublic void printWarnings(){\r\n\t\tif(this.props.warnings.size()>0){\r\n\t\t\tfor(String msg : this.props.warnings){\r\n\t\t\t\tthis.printWarningMessage(msg);\r\n\t\t\t}\r\n\t\t\tthis.props.warnings.clear();\r\n\t\t}\r\n\t}\r\n}\r",
"public class AppProperties <L extends SV_DocumentLoader> {\r\n\r\n\t/** Print option quiet. */\r\n\tpublic static int P_OPTION_QUIET = 0b000;\r\n\r\n\t/** Print option error. */\r\n\tpublic static int P_OPTION_ERROR = 0b0001;\r\n\r\n\t/** Print option warning. */\r\n\tpublic static int P_OPTION_WARNING = 0b0010;\r\n\r\n\t/** Print option progress. */\r\n\tpublic static int P_OPTION_PROGRESS = 0b0100;\r\n\r\n\t/** Print option details. */\r\n\tpublic static int P_OPTION_DEAILS = 0b1000;\r\n\r\n\t/** Print option verbose. */\r\n\tpublic static int P_OPTION_VERBOSE = P_OPTION_ERROR | P_OPTION_WARNING | P_OPTION_PROGRESS | P_OPTION_DEAILS;\r\n\r\n\t/** Substitution pattern for layers using layer index in output file names. */\r\n\tpublic static String SUBST_PATTERN_INDEX = \"${index}\";\r\n\r\n\t/** Substitution pattern for layers using layer identifier (id) in output file names. */\r\n\tpublic static String SUBST_PATTERN_ID = \"${id}\";\r\n\r\n\t/** List of application options. */\r\n\tfinal private ArrayList<ApplicationOption<?>> options = new ArrayList<>();\r\n\r\n\t/** List of application options that should cause a warning when used in no-layer process. */\r\n\tfinal private ArrayList<ApplicationOption<?>> noLayersWarnings;\r\n\r\n\t/** List of application options that should cause a warning when used in with-layer process. */\r\n\tfinal private ArrayList<ApplicationOption<?>> withLayersWarnings;\r\n\r\n\t/** Application option for verbose mode. */\r\n\tfinal private AO_Verbose aoVerbose = new AO_Verbose('v');\r\n\r\n\t/** Application option for quiet mode. */\r\n\tfinal private AO_Quiet aoQuiet = new AO_Quiet(\"appliction will be absolutely quiet, no output to sterr or stout.\");\r\n\r\n\t/** Application option for printing progress information. */\r\n\tfinal private AO_MsgProgress aoMsgProgress = new AO_MsgProgress();\r\n\r\n\t/** Application option for printing warning messages. */\r\n\tfinal private AO_MsgWarning aoMsgWarning = new AO_MsgWarning();\r\n\r\n\t/** Application option for printing detailed messages. */\r\n\tfinal private AO_MsgDetail aoMsgDetail = new AO_MsgDetail();\r\n\r\n\t/** Application option to switch off error messages. */\r\n\tfinal private AO_NoErrors aoNoErrors = new AO_NoErrors();\r\n\r\n\t/** Application option for target. */\r\n\tfinal private AO_TargetExt aoTarget;\r\n\r\n\t/** Application option for input file. */\r\n\tfinal private AO_FileIn aoFileIn = new AO_FileIn(true, 'f', \"input file <file>, must be a valid SVG file, can be compressed SVG (svgz)\");\r\n\r\n\t/** Application option for output file. */\r\n\tfinal private AO_FileOut aoFileOut = new AO_FileOut(false, 'o', \"output file name, default is the basename of the input file plus target extension\");\r\n\r\n\t/** Application option for output directory. */\r\n\tfinal private AO_DirectoryOut aoDirOut = new AO_DirectoryOut(false, 'd', \"output directory, default value is the current directory\");\r\n\r\n\t/** Application option to automatically create output directories. */\r\n\tfinal private AO_CreateDirectories aoCreateDirs = new AO_CreateDirectories();\r\n\r\n\t/** Application option to automatically overwrite existing files on output. */\r\n\tfinal private AO_OverwriteExisting aoOverwriteExisting = new AO_OverwriteExisting();\r\n\r\n\t/** Application option to keep (not remove) temporary created artifacts (files and directories). */\r\n\tfinal private AO_KeepTmpArtifacts aoKeepTmpArtifacts = new AO_KeepTmpArtifacts();\r\n\r\n\t/** Application option activating simulation mode. */\r\n\tfinal private AO_Simulate aoSimulate = new AO_Simulate();\r\n\r\n\t/** Application option to automatically switch on all layers when no layers are processed. */\r\n\tfinal private AO_SwitchOnLayers aoSwitchOnLayers = new AO_SwitchOnLayers();\r\n\r\n\t/** Application option for processing layers. */\r\n\tfinal private AO_Layers aoLayers = new AO_Layers();\r\n\r\n\t/** Application option for processing layers if layers exist in input file. */\r\n\tfinal private AO_LayersIfExist aoLayersIfExists = new AO_LayersIfExist();\r\n\r\n\t/** Application option for using layer index in output file name. */\r\n\tfinal private AO_FoutLayerIndex aoFoutLayerIndex = new AO_FoutLayerIndex();\r\n\r\n\t/** Application option for using layer identifier in output file name. */\r\n\tfinal private AO_FoutLayerId aoFoutLayerId = new AO_FoutLayerId();\r\n\r\n\t/** Application option for not using a base name when processing layers. */\r\n\tfinal private AO_FoutNoBasename aoFoutNoBasename = new AO_FoutNoBasename();\r\n\r\n\t/** Application option for using a specified base name when processing layers. */\r\n\tfinal private AO_UseBaseName aoUseBaseName = new AO_UseBaseName();\r\n\r\n\t/** Application option for text-as-shape mode. */\r\n\tfinal private AO_TextAsShape aoTextAsShape = new AO_TextAsShape();\r\n\r\n\t/** The file name of the input file. */\r\n\tprivate String fin;\r\n\r\n\t/** The file object for an output file (no layer mode only). */\r\n\tprivate File fout;\r\n\r\n\t/** The output directory name (layer mode only). */\r\n\tprivate String dout;\r\n\r\n\t/** The output directory file (layer mode only). */\r\n\tprivate File doutFile;\r\n\r\n\t/** A pattern for generating fout when processing layers, in StrSubstitutor format. */\r\n\tprivate String foutPattern;\r\n\r\n\t/** The SVG document loader. */\r\n\tprivate L loader;\r\n\r\n\t/** List of warning messages collected during process. */\r\n\tprotected ArrayList<String> warnings = new ArrayList<>();\r\n\r\n\t/** Message mode for the application, 0 is quiet, all other values are generated using message type bit masks. */\r\n\tprivate int msgMode = P_OPTION_ERROR;\r\n\r\n\tpublic AppProperties(SvgTargets[] targets, L loader){\r\n\t\tValidate.noNullElements(targets);\r\n\t\tValidate.notNull(loader);\r\n\t\tthis.loader = loader;\r\n\r\n\t\tthis.aoDirOut.setDefaultValue(System.getProperty(\"user.dir\"));\r\n\t\tthis.aoTarget = new AO_TargetExt(true, 't', \"target for the conversion\", targets);\r\n\r\n\t\tthis.addOption(this.aoVerbose);\r\n\t\tthis.addOption(this.aoQuiet);\r\n\t\tthis.addOption(this.aoMsgProgress);\r\n\t\tthis.addOption(this.aoMsgDetail);\r\n\t\tthis.addOption(this.aoMsgWarning);\r\n\t\tthis.addOption(this.aoNoErrors);\r\n\r\n\t\tthis.addOption(this.aoTarget);\r\n\t\tthis.addOption(this.aoSimulate);\r\n\t\tthis.addOption(this.aoKeepTmpArtifacts);\r\n\r\n\t\tthis.addOption(this.aoFileIn);\r\n\t\tthis.addOption(this.aoFileOut);\r\n\t\tthis.addOption(this.aoDirOut);\r\n\t\tthis.addOption(this.aoCreateDirs);\r\n\t\tthis.addOption(this.aoOverwriteExisting);\r\n\r\n\t\tthis.addOption(this.aoSwitchOnLayers);\r\n\r\n\t\tthis.addOption(this.aoLayers);\r\n\t\tthis.addOption(this.aoLayersIfExists);\r\n\t\tthis.addOption(this.aoFoutLayerIndex);\r\n\t\tthis.addOption(this.aoFoutLayerId);\r\n\t\tthis.addOption(this.aoFoutNoBasename);\r\n\t\tthis.addOption(this.aoUseBaseName);\r\n\r\n\t\tthis.addOption(this.aoTextAsShape);\r\n\r\n\t\tthis.noLayersWarnings = new ArrayList<>();\r\n\t\tthis.noLayersWarnings.add(this.aoFoutLayerIndex);\r\n\t\tthis.noLayersWarnings.add(this.aoFoutLayerId);\r\n\t\tthis.noLayersWarnings.add(this.aoFoutNoBasename);\r\n\t\tthis.noLayersWarnings.add(this.aoUseBaseName);\r\n\r\n\t\tthis.withLayersWarnings = new ArrayList<>();\r\n\t\tthis.withLayersWarnings.add(this.aoSwitchOnLayers);\r\n\t\tthis.withLayersWarnings.add(this.aoFileOut);\r\n\t}\r\n\r\n\t/**\r\n\t * Adds an application option.\r\n\t * @param option new option, ignored if null\r\n\t */\r\n\tpublic void addOption(ApplicationOption<?> option){\r\n\t\tif(option!=null){\r\n\t\t\tthis.options.add(option);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Tests if the properties are set to process layers.\r\n\t * @return true if set to process layers, false otherwise\r\n\t */\r\n\tpublic boolean doesLayers(){\r\n\t\treturn this.getFoutFn()==null && this.getDout()!=null && this.getFoutPattern()!=null;\r\n\t}\r\n\r\n\t/**\r\n\t * Tests if the properties are set to process for a single output file, not processing patterns.\r\n\t * @return true if set of single output file, false otherwise\r\n\t */\r\n\tpublic boolean doesNoLayers(){\r\n\t\treturn this.getFoutFn()!=null && this.getDout()==null && this.getFoutPattern()==null;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the simulation flag.\r\n\t * @return true if application is in simulation mode, false otherwise\r\n\t */\r\n\tpublic boolean doesSimulate(){\r\n\t\treturn this.aoSimulate.inCli();\r\n\t}\r\n\r\n\t/**\r\n\t * Tests if the application is allowed to write output files and directories.\r\n\t * @return true if allowed, false otherwise\r\n\t */\r\n\tpublic boolean canWriteFiles(){\r\n\t\treturn !this.aoSimulate.inCli();\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the create-directories flag.\r\n\t * @return true if application automatically creates directories, false otherwise\r\n\t */\r\n\tpublic boolean doesCreateDirectories(){\r\n\t\treturn this.aoCreateDirs.inCli();\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the text-as-shape flag as set by CLI.\r\n\t * @return true if text-as-shape is set, false otherwise\r\n\t */\r\n\tpublic boolean doesTextAsShape(){\r\n\t\treturn this.aoTextAsShape.inCli();\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the list of added application options.\r\n\t * @return application option list, empty if none added\r\n\t */\r\n\tpublic ApplicationOption<?>[] getAppOptions() {\r\n\t\treturn this.options.toArray(new ApplicationOption<?>[]{});\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the output directory name for processing layers.\r\n\t * @return directory name, null if not set or errors on setting\r\n\t */\r\n\tpublic String getDout(){\r\n\t\treturn this.dout;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the output directory file for processing layers.\r\n\t * @return directory file, null if not set or errors on setting\r\n\t */\r\n\tpublic File getDoutFile(){\r\n\t\treturn this.doutFile;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the input file name.\r\n\t * @return input file name, null if none set\r\n\t */\r\n\tpublic String getFinFn(){\r\n\t\treturn this.fin;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns a file name when dealing with layers.\r\n\t * @param entry file name, null if entry or any parts was null or if not set to process layers\r\n\t * @return file name with directory element\r\n\t */\r\n\tpublic String getFnOut(Entry<String, Integer> entry){\r\n\t\tif(!this.doesLayers() || entry==null || entry.getKey()==null || entry.getValue()==null){\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tMap<String, String> valuesMap = new HashMap<>();\r\n\t\tvaluesMap.put(\"id\", entry.getKey());\r\n\t\tvaluesMap.put(\"index\", String.format(\"%02d\", entry.getValue()));\r\n\r\n\t\treturn new StrSubstitutor(valuesMap).replace(this.foutPattern);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns a file name when dealing with layers without any directory element.\r\n\t * @param entry file name, null if entry or any parts was null or if not set to process layers\r\n\t * @return file name without directory element\r\n\t */\r\n\tpublic String getFnOutNoDir(Entry<String, Integer> entry){\r\n\t\tString fn = this.getFnOut(entry);\r\n\t\tif(fn==null){\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\treturn StringUtils.substringAfterLast(fn, \"/\");\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the file name for a single output file when not processing layers.\r\n\t * @return file name, null if not set or if errors on setting\r\n\t */\r\n\tpublic String getFoutFn(){\r\n\t\treturn this.aoFileOut.getDefaultValue();\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the file for a single output file when not processing layers.\r\n\t * @return file, null if not set or if errors on setting\r\n\t */\r\n\tpublic File getFoutFile(){\r\n\t\treturn this.fout;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the generated pattern for output files.\r\n\t * @return generated pattern, null if not set\r\n\t */\r\n\tpublic String getFoutPattern(){\r\n\t\treturn this.foutPattern;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the document loader.\r\n\t * @return the document loader\r\n\t */\r\n\tpublic L getLoader(){\r\n\t\treturn this.loader;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the message mode.\r\n\t * @return message mode: 0 for quiet, bit mask otherwise\r\n\t */\r\n\tpublic int getMsgMode(){\r\n\t\treturn this.msgMode;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the supported targets.\r\n\t * @return supported targets\r\n\t */\r\n\tpublic SvgTargets[] getSupportedTargetts(){\r\n\t\treturn this.aoTarget.getSupportedTargets();\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the application target.\r\n\t * @return application target, null if none set or if a set target was not in the list of supported targets\r\n\t */\r\n\tpublic SvgTargets getTarget(){\r\n\t\treturn this.aoTarget.getTarget();\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the set value of the target option.\r\n\t * @return target option value\r\n\t */\r\n\tpublic String getTargetValue(){\r\n\t\treturn this.aoTarget.getValue();\r\n\t}\r\n\r\n\t/**\r\n\t * Returns current warnings.\r\n\t * @return current warnings, empty (size 0) if none collected\r\n\t */\r\n\tpublic ArrayList<String> getWarnings(){\r\n\t\treturn this.warnings;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the flag for processing layers individually.\r\n\t * @return true if layers should be processed, false otherwise\r\n\t */\r\n\tpublic boolean processLayers(){\r\n\t\treturn this.aoLayers.inCli();\r\n\t}\r\n\r\n\t/**\r\n\t * Tests input file settings and loads it.\r\n\t * @return null in success, error string on error\r\n\t */\r\n\tpublic String setInput(){\r\n\t\tif(StringUtils.isBlank(this.aoFileIn.getCliValue())){\r\n\t\t\treturn \"no input file given\";\r\n\t\t}\r\n\t\telse{\r\n\t\t\tString fn = this.aoFileIn.getValue();\r\n\t\t\tFile testFD = new File(fn);\r\n\t\t\tif(!testFD.exists()){\r\n\t\t\t\treturn \"input file <\" + fn + \"> does not exist, please check path and filename\";\r\n\t\t\t}\r\n\t\t\tif(!testFD.isFile()){\r\n\t\t\t\treturn \"input file <\" + fn + \"> is not a file, please check path and filename\";\r\n\t\t\t}\r\n\t\t\tif(!testFD.canRead()){\r\n\t\t\t\treturn \"cannot read input file <\" + fn + \">, please file permissions\";\r\n\t\t\t}\r\n\t\t\tthis.fin = fn;\r\n\t\t}\r\n\t\treturn this.loader.load(this.fin);\r\n\t}\r\n\r\n\t/**\r\n\t * Sets the message mode according to CLI settings.\r\n\t */\r\n\tpublic void setMessageMode(){\r\n\t\tif(this.aoQuiet.inCli()){\r\n\t\t\tthis.msgMode = P_OPTION_QUIET;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif(this.aoVerbose.inCli()){\r\n\t\t\tthis.msgMode = P_OPTION_VERBOSE;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif(this.aoMsgProgress.inCli()){\r\n\t\t\tthis.msgMode = this.msgMode | P_OPTION_PROGRESS;\r\n\t\t}\r\n\t\tif(this.aoMsgWarning.inCli()){\r\n\t\t\tthis.msgMode = this.msgMode | P_OPTION_WARNING;\r\n\t\t}\r\n\t\tif(this.aoMsgDetail.inCli()){\r\n\t\t\tthis.msgMode = this.msgMode | P_OPTION_DEAILS;\r\n\t\t}\r\n\t\tif(this.aoNoErrors.inCli()){\r\n\t\t\tthis.msgMode = this.msgMode &= ~P_OPTION_ERROR;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Tests all CLI options that influence output names and sets the output name\r\n\t * @return null in success, error string on error\r\n\t */\r\n\tpublic String setOutput(){\r\n\t\t//fin, fout, dout, l, layer-i, layers-I, b, L\r\n\r\n\t\tSvgTargets target = this.getTarget();\r\n\t\tif(target==null){\r\n\t\t\treturn \"implementation error: cannot set output file w/o a valid target\";\r\n\t\t}\r\n\t\tif(this.getFinFn()==null){\r\n\t\t\treturn \"implementation error: no input file name set\";\r\n\t\t}\r\n\r\n\t\tif(this.aoLayers.inCli() && !this.loader.hasInkscapeLayers()){\r\n\t\t\tthis.warnings.add(\"layers activated but input file has no layers, continue for single output file\");\r\n\t\t}\r\n\r\n\t\tif((this.aoLayers.inCli() || this.aoLayersIfExists.inCli()) && this.loader.hasInkscapeLayers()){\r\n\t\t\treturn this.setOutputWithLayers(target);\r\n\t\t}\r\n\t\telse{\r\n\t\t\treturn this.setOutputNoLayers(target);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Set output and do all tests for no layer processing.\r\n\t * @param target the set target\r\n\t * @return null on success, error message on error\r\n\t */\r\n\tprivate String setOutputNoLayers(SvgTargets target){\r\n\t\t//warnings first\r\n\t\tfor(ApplicationOption<?> ao : this.noLayersWarnings){\r\n\t\t\tif(ao.inCli()){\r\n\t\t\t\tthis.warnings.add(\"no layers processed but CLI option <\" + ao.getCliOption().getLongOpt() + \"> used, will be ignored\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tString fn = null;\r\n\t\tif(this.aoFileOut.inCli()){\r\n\t\t\tfn = this.aoFileOut.getCliValue();\r\n\t\t\tif(StringUtils.isBlank(fn)){\r\n\t\t\t\treturn \"output filename is blank\";\r\n\t\t\t}\r\n\t\t\tif(fn.endsWith(\".\" + target.name())){\r\n\t\t\t\treturn \"output filename <\" + fn + \"> should not contain target file extension\";\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(this.fin!=null){\r\n\t\t\tfn = this.fin;\r\n\t\t\tif(fn.endsWith(\".\" + target.name())){\r\n\t\t\t\treturn \"no output name given and target extension same as input extension, do not want to overwrite input file\";\r\n\t\t\t}\r\n\t\t\telse if(fn.endsWith(\".svg\")){\r\n\t\t\t\tfn = fn.substring(0, fn.lastIndexOf('.'));\r\n\t\t\t}\r\n\t\t\telse if(fn.endsWith(\".svgz\")){\r\n\t\t\t\tfn = fn.substring(0, fn.lastIndexOf('.'));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//in any case add Dout if it exists\r\n\t\tif(this.aoDirOut.inCli()){\r\n\t\t\t//an output dir is set, so change the directory part of fn to the output directory\r\n\t\t\tif(fn.contains(\"/\")){\r\n\t\t\t\t//fn has path, substitute with our directory\r\n\t\t\t\tfn = this.aoDirOut.getValue() + \"/\" + StringUtils.substringAfterLast(fn, \"/\");\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\t//fn has no path, simply use directory then\r\n\t\t\t\tfn = this.aoDirOut.getValue() + \"/\" + fn;\r\n\t\t\t}\r\n\t\t\t//if we have double //, remove them\r\n\t\t\tfn = StringUtils.replace(fn, \"//\", \"/\");\r\n\t\t}\r\n\r\n\t\tfn += \".\" + target.name();\r\n\t\tFile fnF = new File(fn);\r\n\t\tif(fnF.exists() && fnF.isDirectory()){\r\n\t\t\treturn \"output file <\" + fn + \"> exists but is a directory\";\r\n\t\t}\r\n\t\tif(fnF.exists() && !this.aoOverwriteExisting.inCli()){\r\n\t\t\treturn \"output file <\" + fn + \"> exists and no option <\" + this.aoOverwriteExisting.getCliOption().getLongOpt() + \"> used\";\r\n\t\t}\r\n\t\tif(fnF.exists() && !fnF.canWrite() && this.aoOverwriteExisting.inCli()){\r\n\t\t\treturn \"output file <\" + fn + \"> exists but cannot write to it\";\r\n\t\t}\r\n\t\tFile fnFParent = fnF.getParentFile();\r\n\t\tif(fnFParent!=null){\r\n\t\t\tif(fnFParent.exists() && !fnFParent.isDirectory()){\r\n\t\t\t\treturn \"output directory <\" + fnFParent.toString().replace('\\\\', '/') + \"> exists but is not a directory\";\r\n\t\t\t}\r\n\t\t\tif(!fnFParent.exists() && !this.aoCreateDirs.inCli()){\r\n\t\t\t\treturn \"output directory <\" + fnFParent.toString().replace('\\\\', '/') + \"> does not exist and CLI option <\" + this.aoCreateDirs.getCliOption().getLongOpt() + \"> not used\";\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//switch on all layers if requested\r\n\t\tif(this.aoSwitchOnLayers.inCli()){\r\n\t\t\tthis.loader.switchOnAllLayers();\r\n\t\t}\r\n\r\n\t\t//all tests ok, out fn into Fout\r\n\t\tthis.aoFileOut.setDefaultValue(fn);\r\n\t\tthis.fout = fnF;\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * Set output and do all tests for layer processing.\r\n\t * @param target the set target\r\n\t * @return null on success, error message on error\r\n\t */\r\n\tprivate String setOutputWithLayers(SvgTargets target){\r\n\t\t//warnings first\r\n\t\tfor(ApplicationOption<?> ao : this.withLayersWarnings){\r\n\t\t\tif(ao.inCli()){\r\n\t\t\t\tthis.warnings.add(\"layers processed but CLI option <\" + ao.getCliOption().getLongOpt() + \"> used, will be ignored\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tString dout = this.aoDirOut.getValue();\r\n\t\tFile testDir = new File(dout);\r\n\t\tif(testDir.exists() && !testDir.isDirectory()){\r\n\t\t\treturn \"output directory <\" + dout + \"> exists but is not a directory\";\r\n\t\t}\r\n\t\tif(testDir.exists() && !testDir.canWrite()){\r\n\t\t\treturn \"output directory <\" + dout + \"> exists but cannot write into it, check permissions\";\r\n\t\t}\r\n\t\tif(!testDir.exists() && !this.aoCreateDirs.inCli()){\r\n\t\t\treturn \"output directory <\" + dout + \"> does not exist and CLI option <\" + this.aoCreateDirs.getCliOption().getLongOpt() + \"> not used\";\r\n\t\t}\r\n\r\n\t\tif(!this.aoFoutLayerId.inCli() && !this.aoFoutLayerIndex.inCli()){\r\n\t\t\treturn \"processing layers but neither <\" + this.aoFoutLayerId.getCliOption().getLongOpt() + \"> nor <\" + this.aoFoutLayerIndex.getCliOption().getLongOpt() + \"> options requestes, amigious output file names\";\r\n\t\t}\r\n\r\n\t\tStrBuilder pattern = new StrBuilder();\r\n\t\tpattern.append(dout);\r\n\t\tif(!pattern.endsWith(\"/\")){\r\n\t\t\tpattern.append('/');\r\n\t\t}\r\n\r\n\t\tif(!this.aoFoutNoBasename.inCli()){\r\n\t\t\tif(this.aoUseBaseName.inCli()){\r\n\t\t\t\tpattern.append(this.aoUseBaseName.getValue());\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tString bn = StringUtils.substringAfterLast(this.fin, \"/\");\r\n\t\t\t\tbn = StringUtils.substringBeforeLast(bn, \".\");\r\n\t\t\t\tpattern.append(bn);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\n\t\tif(this.aoFoutLayerIndex.inCli()){\r\n\t\t\tif(!pattern.endsWith(\"/\")){\r\n\t\t\t\tpattern.append('-');\r\n\t\t\t}\r\n\t\t\tpattern.append(SUBST_PATTERN_INDEX);\r\n\t\t}\r\n\r\n\t\tif(this.aoFoutLayerId.inCli()){\r\n\t\t\tif(!pattern.endsWith(\"/\")){\r\n\t\t\t\tpattern.append('-');\r\n\t\t\t}\r\n\t\t\tpattern.append(SUBST_PATTERN_ID);\r\n\t\t}\r\n\r\n\t\tthis.dout = dout;\r\n\t\tthis.doutFile = testDir;\r\n\t\tthis.foutPattern = pattern.toString();\r\n\t\treturn null;\r\n\t}\r\n\r\n\t/**\r\n\t * Tests if the application should keep (not remove) temporary artifacts (files and directories).\r\n\t * @return true if artifacts should be kept, false otherwise\r\n\t */\r\n\tpublic boolean doesKeepTempArtifacts(){\r\n\t\treturn this.aoKeepTmpArtifacts.inCli();\r\n\t}\r\n}\r",
"public enum SvgTargets {\r\n\r\n\t/** SVG (plain) as target. */\r\n\tsvg,\r\n\r\n\t/** PDF as target, optionally with PDF version. */\r\n\tpdf,\r\n\r\n\t/** EMF as target. */\r\n\temf,\r\n\r\n\t/** WMF as target. */\r\n\twmf,\r\n\r\n\t/** PS as target, optionally with PS version. */\r\n\tps,\r\n\r\n\t/** EPS as target. */\r\n\teps,\r\n\r\n\t/** PNG as target, optionally with DPI. */\r\n\tpng,\r\n\t;\r\n}\r",
"public class BatikLoader extends SV_DocumentLoader {\r\n\r\n\t/** Local bridge context. */\r\n\tprivate BridgeContext bridgeContext;\r\n\r\n\t/** SVG document object. */\r\n\tprivate Document svgDocument;\r\n\r\n\t/** Size value. */\r\n\tprivate Dimension size;\r\n\r\n\t/** Mapping from node id to actual DOM node. */\r\n\tprivate final Map<String, Node> layerNodes = new HashMap<>();\r\n\r\n\t/**\r\n\t * Returns the Inkscape label for a given node.\r\n\t * @param node XML/SVG node\r\n\t * @return null if node was null or no Inkscape label found, label otherwise\r\n\t */\r\n\tpublic static String getLabel(Node node){\r\n\t\tif(node==null){\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tNamedNodeMap nnm = node.getAttributes();\r\n\t\tfor(int i=0; i<nnm.getLength(); i++){\r\n\t\t\tif(\"inkscape:label\".equals(nnm.item(i).getNodeName())){\r\n\t\t\t\treturn nnm.item(i).getNodeValue();\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 * Returns the Inkscape index (actual id with layer removed) for a given node.\r\n\t * @param node XML/SVG node\r\n\t * @return 0 if node was null or no IDs found, index otherwise\r\n\t */\r\n\tstatic int getIndex(Node node){\r\n\t\tif(node==null){\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tNamedNodeMap nnm = node.getAttributes();\r\n\t\tfor(int i=0; i<nnm.getLength(); i++){\r\n\t\t\tif(\"id\".equals(nnm.item(i).getNodeName())){\r\n\t\t\t\tString index = nnm.item(i).getNodeValue();\r\n\t\t\t\tindex = StringUtils.substringAfter(index, \"layer\");\r\n\t\t\t\treturn new Integer(index);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String load(String fn) {\r\n\t\tValidate.notBlank(fn);\r\n\r\n\t\tif(!this.isLoaded){\r\n\t\t\tthis.bridgeContext = null;\r\n\t\t\tthis.svgDocument = null;\r\n\r\n\t\t\tUserAgent userAgent = new UserAgentAdapter();\r\n\t\t\tDocumentLoader documentLoader = new DocumentLoader(userAgent);\r\n\r\n\t\t\tthis.bridgeContext = new BridgeContext(userAgent, documentLoader);\r\n\t\t\tthis.bridgeContext.setDynamic(true);\r\n\r\n\t\t\ttry{\r\n\t\t\t\tthis.svgDocument = documentLoader.loadDocument(new File(fn).toURI().toString());\r\n\t\t\t}\r\n\t\t\tcatch(Exception ex){\r\n\t\t\t\tthis.bridgeContext = null;\r\n\t\t\t\tthis.svgDocument = null;\r\n\t\t\t\treturn this.getClass().getSimpleName() + \": exception loading svgDocument - \" + ex.getMessage();\r\n\t\t\t}\r\n\t\t\tdocumentLoader.dispose();\r\n\r\n\t\t\tElement elem = this.svgDocument.getDocumentElement();\r\n\t\t\tthis.size = new Dimension();\r\n\t\t\ttry{\r\n\t\t\t\tthis.size.setSize(Double.valueOf(elem.getAttribute(\"width\")), Double.valueOf(elem.getAttribute(\"height\")));\r\n\t\t\t}\r\n\t\t\tcatch(Exception ex){\r\n\t\t\t\tthis.bridgeContext = null;\r\n\t\t\t\tthis.svgDocument = null;\r\n\t\t\t\tthis.size = null;\r\n\t\t\t\treturn this.getClass().getSimpleName() + \": exception setting docucment size - \" + ex.getMessage();\r\n\t\t\t}\r\n\r\n\t\t\tNodeList nodes = elem.getChildNodes();\r\n\t\t\tif(nodes!=null){\r\n\t\t\t\tfor(int i=0; i<nodes.getLength(); i++){\r\n\t\t\t\t\tif(\"g\".equals(nodes.item(i).getNodeName())){\r\n\t\t\t\t\t\tNamedNodeMap nnm = nodes.item(i).getAttributes();\r\n\t\t\t\t\t\tfor(int node=0; node<nnm.getLength(); node++){\r\n\t\t\t\t\t\t\tif(\"inkscape:groupmode\".equals(nnm.item(node).getNodeName())){\r\n\t\t\t\t\t\t\t\tString id = BatikLoader.getLabel(nodes.item(i));\r\n\t\t\t\t\t\t\t\tint index = BatikLoader.getIndex(nodes.item(i));\r\n\t\t\t\t\t\t\t\tthis.layers.put(id, index);\r\n\t\t\t\t\t\t\t\tthis.layerNodes.put(id, nodes.item(i));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis.isLoaded = true;\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void switchOnAllLayers() {\r\n\t\tfor(Node node : this.layerNodes.values()){\r\n\t\t\tNamedNodeMap nnm = node.getAttributes();\r\n\t\t\tfor(int i=0; i<nnm.getLength(); i++){\r\n\t\t\t\tif(\"style\".equals(nnm.item(i).getNodeName())){\r\n\t\t\t\t\tnnm.item(i).setNodeValue(\"display:inline\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void switchOffAllLayers() {\r\n\t\tfor(Node node : this.layerNodes.values()){\r\n\t\t\tNamedNodeMap nnm = node.getAttributes();\r\n\t\t\tfor(int i=0; i<nnm.getLength(); i++){\r\n\t\t\t\tif(\"style\".equals(nnm.item(i).getNodeName())){\r\n\t\t\t\t\tnnm.item(i).setNodeValue(\"display:none\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void switchOnLayer(String layer) {\r\n\t\tif(StringUtils.isBlank(layer)){\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tNode node = this.layerNodes.get(layer);\r\n\t\tif(node==null){\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tNamedNodeMap nnm = node.getAttributes();\r\n\t\tfor(int i=0; i<nnm.getLength(); i++){\r\n\t\t\tif(\"style\".equals(nnm.item(i).getNodeName())){\r\n\t\t\t\tnnm.item(i).setNodeValue(\"display:inline\");\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the loader's document.\r\n\t * @return loaded document, null if none loaded\r\n\t */\r\n\tpublic Document getDocument() {\r\n\t\treturn this.svgDocument;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the loader's bridge context.\r\n\t * @return bridge context, null if no document loaded\r\n\t */\r\n\tpublic BridgeContext getBridgeContext(){\r\n\t\treturn this.bridgeContext;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the document size.\r\n\t * @return document size, null if no document loaded\r\n\t */\r\n\tpublic Dimension getSize(){\r\n\t\treturn this.size;\r\n\t}\r\n\r\n\r\n}\r",
"public abstract class FhConverter {\r\n\r\n\t/** Properties that can be set for conversion. */\r\n\tprotected UserProperties properties;\r\n\r\n\t/**\r\n\t * Creates a new converter with default configuration.\r\n\t * Sets transparency to true, background to false, background color to white, clipping to false, text as shapes to false.\r\n\t */\r\n\tpublic FhConverter(){\r\n\t\tthis.properties=new UserProperties();\r\n\r\n\t\tthis.setPropertyTransparent(true);\r\n\t\tthis.setPropertyBackground(false);\r\n\t\tthis.setPropertyBackgroundColor(Color.WHITE);\r\n\t\tthis.setPropertyClip(false);\r\n\t\tthis.setPropertyTextAsShapes(false);\r\n\t}\r\n\r\n\t/**\r\n\t * Sets background property on or off.\r\n\t * @param on new setting\r\n\t */\r\n\tpublic abstract void setPropertyBackground(boolean on);\r\n\r\n\t/**\r\n\t * Sets background color property to a color.\r\n\t * @param color background color\r\n\t */\r\n\tpublic abstract void setPropertyBackgroundColor(Color color);\r\n\r\n\t/**\r\n\t * Sets transparency property on or off.\r\n\t * @param on new setting\r\n\t */\r\n\tpublic abstract void setPropertyTransparent(boolean on);\r\n\r\n\t/**\r\n\t * Sets clipping property on or off.\r\n\t * @param on new setting\r\n\t */\r\n\tpublic void setPropertyClip(boolean on){\r\n\t\tthis.properties.setProperty(AbstractVectorGraphicsIO.CLIP, on);\r\n\t}\r\n\r\n\t/**\r\n\t * Sets text-as-shape property on or off.\r\n\t * @param on new setting\r\n\t */\r\n\tpublic void setPropertyTextAsShapes(boolean on){\r\n\t\tthis.properties.setProperty(AbstractVectorGraphicsIO.TEXT_AS_SHAPES, on);\r\n\t}\r\n\r\n\t/**\r\n\t * Converts the document maintained by the loader to a target format.\r\n\t * @param loader the document loader, must have a document successfully loaded\r\n\t * @param fout the file for the output\r\n\t * @return null on success, error message otherwise\r\n\t */\r\n\tpublic abstract String convertDocument(BatikLoader loader, File fout);\r\n\r\n\t/**\r\n\t * Returns the user properties of the converter.\r\n\t * @return user properties\r\n\t */\r\n\tpublic UserProperties getProperties(){\r\n\t\treturn this.properties;\r\n\t}\r\n}\r",
"public class Fh_Svg2Emf extends FhConverter {\r\n\r\n\t@Override\r\n\tpublic void setPropertyBackground(boolean on) {\r\n\t\tthis.properties.setProperty(EMFGraphics2D.BACKGROUND, on);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setPropertyBackgroundColor(Color color) {\r\n\t\tthis.properties.setProperty(EMFGraphics2D.BACKGROUND_COLOR, color);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setPropertyTransparent(boolean on) {\r\n\t\tthis.properties.setProperty(EMFGraphics2D.TRANSPARENT, on);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String convertDocument(BatikLoader loader, File fout) {\r\n\t\t//TODO error messages and parameter checks\r\n\r\n\t\tGVTBuilder gvtBuilder = new GVTBuilder();\r\n\t\tGraphicsNode rootNode = gvtBuilder.build(loader.getBridgeContext(), loader.getDocument());\r\n\r\n\t\tFileOutputStream emfStream;\r\n\t\tEMFGraphics2D emfGraphics2D;\r\n\r\n\t\ttry {\r\n\t\t\temfStream = new FileOutputStream(fout);\r\n\t\t\temfGraphics2D = new EMFGraphics2D(fout, loader.getSize());\r\n\t\t}\r\n\t\tcatch (FileNotFoundException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t\treturn \"##\";\r\n\t\t}\r\n\r\n\t\temfGraphics2D.setProperties(this.properties);\r\n\t\temfGraphics2D.setDeviceIndependent(true);\r\n\t\temfGraphics2D.startExport();\r\n\t\trootNode.paint(emfGraphics2D);\r\n\t\temfGraphics2D.endExport();\r\n\t\temfGraphics2D.dispose();\r\n\r\n\t\ttry{\r\n\t\t\temfStream.close();\r\n\t\t}\r\n\t\tcatch(Exception ignore){}\r\n\r\n\t\treturn null;\r\n\t}\r\n\r\n}\r",
"public class Fh_Svg2Pdf extends FhConverter {\r\n\r\n\t/**\r\n\t * Creates a new PDF converter and sets margins.\r\n\t */\r\n\tpublic Fh_Svg2Pdf() {\r\n\t\tthis.properties.setProperty(PDFGraphics2D.PAGE_MARGINS, \"0, 0, 0, 0\");\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setPropertyBackground(boolean on) {\r\n\t\tthis.properties.setProperty(PDFGraphics2D.BACKGROUND, on);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setPropertyBackgroundColor(Color color) {\r\n\t\tthis.properties.setProperty(PDFGraphics2D.BACKGROUND_COLOR, color);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setPropertyTransparent(boolean on) {\r\n\t\tthis.properties.setProperty(PDFGraphics2D.TRANSPARENT, on);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String convertDocument(BatikLoader loader, File fout) {\r\n\t\t//TODO error messages and parameter checks\r\n\r\n\t\tGVTBuilder gvtBuilder=new GVTBuilder();\r\n\t\tGraphicsNode rootNode = gvtBuilder.build(loader.getBridgeContext(), loader.getDocument());\r\n\r\n\t\tFileOutputStream pdfStream;\r\n\t\tPDFGraphics2D pdfGraphics2D;\r\n\t\ttry{\r\n\t\t\tpdfStream = new FileOutputStream(fout);\r\n\t\t\tpdfGraphics2D = new PDFGraphics2D(pdfStream, loader.getSize());\r\n\t\t}\r\n\t\tcatch(IOException fnfe){\r\n\t\t\t//TODO\r\n\t\t\treturn \"###\";\r\n\t\t}\r\n\r\n\t\tthis.properties.setProperty(PDFGraphics2D.PAGE_SIZE, PDFGraphics2D.CUSTOM_PAGE_SIZE);\r\n\t\tthis.properties.setProperty(PDFGraphics2D.CUSTOM_PAGE_SIZE, loader.getSize());//TODO change if other page size required\r\n\r\n\t\tpdfGraphics2D.setProperties(this.properties);\r\n\t\tpdfGraphics2D.setDeviceIndependent(true);\r\n\t\tpdfGraphics2D.startExport();\r\n\t\trootNode.paint(pdfGraphics2D);\r\n\t\tpdfGraphics2D.endExport();\r\n\t\tpdfGraphics2D.dispose();\r\n\r\n\t\ttry{\r\n\t\t\tpdfStream.close();\r\n\t\t}\r\n\t\tcatch(Exception ignore){}\r\n\r\n\t\treturn null;\r\n\t}\r\n\r\n}\r",
"public class Fh_Svg2Svg extends FhConverter {\r\n\r\n\t@Override\r\n\tpublic void setPropertyBackground(boolean on) {\r\n\t\tthis.properties.setProperty(SVGGraphics2D.BACKGROUND, on);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setPropertyBackgroundColor(Color color) {\r\n\t\tthis.properties.setProperty(SVGGraphics2D.BACKGROUND_COLOR, color);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setPropertyTransparent(boolean on) {\r\n\t\tthis.properties.setProperty(SVGGraphics2D.TRANSPARENT, on);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String convertDocument(BatikLoader loader, File fout) {\r\n\t\t//TODO error messages and parameter checks\r\n\r\n\t\tGVTBuilder gvtBuilder = new GVTBuilder();\r\n\t\tGraphicsNode rootNode = gvtBuilder.build(loader.getBridgeContext(), loader.getDocument());\r\n\r\n\t\tFileOutputStream svgStream;\r\n\t\tSVGGraphics2D svgGraphics2D;\r\n\t\ttry{\r\n\t\t\tsvgStream = new FileOutputStream(fout);\r\n\t\t\tsvgGraphics2D = new SVGGraphics2D(fout, loader.getSize());\r\n\t\t}\r\n\t\tcatch(IOException fnfe){\r\n\t\t\t//TODO\r\n\t\t\treturn \"###\";\r\n\t\t}\r\n\r\n\t\tsvgGraphics2D.setProperties(this.properties);\r\n\t\tsvgGraphics2D.setDeviceIndependent(true);\r\n\t\tsvgGraphics2D.startExport();\r\n\t\trootNode.paint(svgGraphics2D);\r\n\t\tsvgGraphics2D.endExport();\r\n\t\tsvgGraphics2D.dispose();\r\n\r\n\t\ttry{\r\n\t\t\tsvgStream.close();\r\n\t\t}\r\n\t\tcatch(Exception ignore){}\r\n\r\n\t\treturn null;\r\n\t}\r\n\r\n}\r"
] | import de.vandermeer.svg2vector.applications.fh.converters.Fh_Svg2Svg;
import java.awt.Color;
import java.io.File;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import org.freehep.graphicsbase.util.UserProperties;
import de.vandermeer.svg2vector.applications.base.AppBase;
import de.vandermeer.svg2vector.applications.base.AppProperties;
import de.vandermeer.svg2vector.applications.base.SvgTargets;
import de.vandermeer.svg2vector.applications.fh.converters.BatikLoader;
import de.vandermeer.svg2vector.applications.fh.converters.FhConverter;
import de.vandermeer.svg2vector.applications.fh.converters.Fh_Svg2Emf;
import de.vandermeer.svg2vector.applications.fh.converters.Fh_Svg2Pdf;
| /* Copyright 2017 Sven van der Meer <[email protected]>
*
* 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 de.vandermeer.svg2vector.applications.fh;
/**
* The Svg2Vector application using the FreeHep library.
* It an SVG graphic to a vector format.
* Currently supported are EMF, PDF and SVG.
* The tool does support SVG and SVGZ input formats from file or URI.
* It also can deal with SVG layers.
* All options can be set via command line.
*
* @author Sven van der Meer <[email protected]>
* @version v2.0.0 build 170413 (13-Apr-17) for Java 1.8
* @since v1.1.0
*/
public class Svg2Vector_FH extends AppBase<BatikLoader, AppProperties<BatikLoader>> {
/** Application name. */
public final static String APP_NAME = "s2v-fh";
/** Application display name. */
public final static String APP_DISPLAY_NAME = "Svg2Vector FreeHep";
/** Application version, should be same as the version in the class JavaDoc. */
public final static String APP_VERSION = "v2.0.0 build 170413 (13-Apr-17) for Java 1.8";
/** Application option for not-transparent mode. */
AO_NotTransparent optionNotTransparent = new AO_NotTransparent(false, 'n', "switch off transparency");
/** Application option for clip mode. */
AO_Clip optionClip = new AO_Clip(false, 'c', "activate clip property");
/** Application option for background-color mode. */
AO_BackgroundColor optionBackgroundColor = new AO_BackgroundColor(false, 'r', "sets the background color");
/** Application option for no-background mode. */
AO_NoBackground optionNoBackground = new AO_NoBackground(false, 'b', "switch off background property");
/**
* Returns a new application.
*/
public Svg2Vector_FH(){
super(new AppProperties<BatikLoader>(new SvgTargets[]{SvgTargets.pdf, SvgTargets.emf, SvgTargets.svg}, new BatikLoader()));
this.addOption(this.optionNotTransparent);
this.addOption(this.optionClip);
this.addOption(this.optionBackgroundColor);
this.addOption(this.optionNoBackground);
}
@Override
public int executeApplication(String[] args) {
// parse command line, exit with help screen if error
int ret = super.executeApplication(args);
if(ret!=0){
return ret;
}
SvgTargets target = this.getProps().getTarget();
FhConverter converter = TARGET_2_CONVERTER(target);
if(converter==null){
this.printErrorMessage("no converter found for target <" + target.name() + ">");
return -20;
}
converter.setPropertyTransparent(!this.optionNotTransparent.inCli());
converter.setPropertyClip(this.optionClip.inCli());
converter.setPropertyBackground(!this.optionNoBackground.inCli());
converter.setPropertyTextAsShapes(this.getProps().doesTextAsShape());
if(this.optionBackgroundColor.inCli()){
Color color = Color.getColor(this.optionBackgroundColor.getValue());
converter.setPropertyBackgroundColor(color);
}
UserProperties up = converter.getProperties();
Set<Object> keys = up.keySet();
Iterator<Object>it = keys.iterator();
while(it.hasNext()){
String key = it.next().toString();
String val = up.getProperty(key);
key=key.substring(key.lastIndexOf('.')+1, key.length());
this.printDetailMessage("using SVG property " + key + "=" + val);
}
String err;
BatikLoader loader = this.getProps().getLoader();
if(this.getProps().doesLayers()){
for(Entry<String, Integer> entry : loader.getLayers().entrySet()){
loader.switchOffAllLayers();
loader.switchOnLayer(entry.getKey());
this.printProgressMessage("processing layer " + entry.getKey());
this.printDetailMessage("writing to file " + this.getProps().getFnOut(entry) + "." + target.name());
if(this.getProps().canWriteFiles()){
err = converter.convertDocument(loader, new File(this.getProps().getFnOut(entry) + "." + target.name()));
if(err!=null){
this.printErrorMessage(err);
return -99;//TODO
}
}
}
}
else{
this.printProgressMessage("converting input");
this.printDetailMessage("writing to file " + this.getProps().getFoutFile());
if(this.getProps().canWriteFiles()){
err = converter.convertDocument(loader, this.getProps().getFoutFile());
if(err!=null){
this.printErrorMessage(err);
return -99;//TODO
}
}
}
this.printProgressMessage("finished successfully");
return 0;
}
@Override
public String getAppName() {
return APP_NAME;
}
@Override
public String getAppDisplayName(){
return APP_DISPLAY_NAME;
}
@Override
public String getAppDescription() {
return "Converts SVG graphics into other vector formats using FreeHep libraries, with options for handling layers";
}
@Override
public String getAppVersion() {
return APP_VERSION;
}
/**
* Returns a converter for a given target
* @param target the target, can be null
* @return null if target was null or no converter found, a new converter object for the target otherwise
*/
public static FhConverter TARGET_2_CONVERTER(SvgTargets target){
if(target==null){
return null;
}
switch(target){
case eps:
case png:
case ps:
case wmf:
break;
case pdf:
return new Fh_Svg2Pdf();
case svg:
return new Fh_Svg2Svg();
case emf:
| return new Fh_Svg2Emf();
| 5 |
roadhouse-dev/RxDbflow | examplerx1/src/main/java/au/com/roadhouse/rxdbflow/examplerx1/MainActivity.java | [
"@Table(database = au.com.roadhouse.rxdbflow.example.model.ExampleDatabase.class, name = InheritanceTestModel.NAME, insertConflict = ConflictAction.REPLACE)\npublic class InheritanceTestModel extends RxBaseModel<InheritanceTestModel> {\n\n public static final String NAME = \"test-inheritance\";\n\n @PrimaryKey(autoincrement = true)\n @Column(name = \"id\", getterName = \"getId\", setterName = \"setId\")\n private long id;\n\n @Column(name = \"first_name\", getterName = \"getFirstName\", setterName = \"setFirstName\")\n private String firstName;\n\n @Column(name = \"last_name\", getterName = \"getLastName\", setterName = \"setLastName\")\n private String lastName;\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 getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n}",
"@Table(database = au.com.roadhouse.rxdbflow.example.model.ExampleDatabase.class, name = TestModel.NAME, insertConflict = ConflictAction.REPLACE)\npublic class TestModel {\n\n public static final String NAME = \"test\";\n\n @PrimaryKey(autoincrement = true)\n @Column(name = \"id\", getterName = \"getId\", setterName = \"setId\")\n private long id;\n\n @Column(name = \"first_name\", getterName = \"getFirstName\", setterName = \"setFirstName\")\n private String firstName;\n\n @Column(name = \"last_name\", getterName = \"getLastName\", setterName = \"setLastName\")\n private String lastName;\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 getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n}",
"public class DBFlowSchedulers {\n\n private static Scheduler sScheduler;\n\n /**\n * A single threaded background scheduler, this should be used for dbflow observable operations\n * to avoid slamming the connection pool with multiple connection.\n *\n * @return A DBFlow background scheduler\n */\n public static Scheduler background() {\n if (sScheduler == null) {\n BlockingQueue<Runnable> threadQueue = new ArrayBlockingQueue<>(200);\n ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, threadQueue);\n sScheduler = Schedulers.from(threadPoolExecutor);\n }\n\n return sScheduler;\n }\n}",
"public class RxSQLite {\n /**\n * @param properties The properties/columns to SELECT.\n * @return A beginning of the SELECT statement.\n */\n public static RxSelect select(IProperty... properties) {\n return new RxSelect(properties);\n }\n\n /**\n * Starts a new SELECT COUNT(property1, property2, propertyn) (if properties specified) or\n * SELECT COUNT(*).\n *\n * @param properties Optional, if specified returns the count of non-null ROWs from a specific single/group of columns.\n * @return A new select statement SELECT COUNT(expression)\n */\n public static RxSelect selectCountOf(IProperty... properties) {\n return new RxSelect(Method.count(properties));\n }\n\n /**\n * @param table The tablet to update.\n * @param <TModel> The class that implements {@link Model}.\n * @return A new UPDATE statement.\n */\n public static <TModel extends Model> RxUpdate<TModel> update(Class<TModel> table) {\n return new RxUpdate<>(table);\n }\n\n /**\n * @param table The table to insert.\n * @param <TModel> The class that implements {@link Model}.\n * @return A new INSERT statement.\n */\n public static <TModel extends Model> RxInsert<TModel> insert(Class<TModel> table) {\n return new RxInsert<>(table);\n }\n\n /**\n * @return Begins a DELETE statement.\n */\n public static RxDelete delete() {\n return new RxDelete();\n }\n\n /**\n * Starts a DELETE statement on the specified table.\n *\n * @param table The table to delete from.\n * @param <TModel> The class that implements {@link Model}.\n * @return A {@link From} with specified DELETE on table.\n */\n @SuppressWarnings(\"unchecked\")\n public static <TModel> RxFrom<TModel> delete(Class<TModel> table) {\n return delete().from(table);\n }\n\n /**\n * Starts an INDEX statement on specified table.\n *\n * @param name The name of the index.\n * @param <TModel> The class that implements {@link Model}.\n * @return A new INDEX statement.\n */\n public static <TModel extends Model> Index<TModel> index(String name) {\n return new Index<>(name);\n }\n\n /**\n * Starts a TRIGGER statement.\n *\n * @param name The name of the trigger.\n * @return A new TRIGGER statement.\n */\n public static Trigger createTrigger(String name) {\n return Trigger.create(name);\n }\n\n /**\n * Starts a CASE statement.\n *\n * @param condition The condition to check for in the WHEN.\n * @return A new {@link CaseCondition}.\n */\n //TODO: Wrap Case\n public static <TReturn> CaseCondition<TReturn> caseWhen(@NonNull SQLOperator condition) {\n return SQLite.caseWhen(condition);\n }\n\n /**\n * Starts an efficient CASE statement. The value passed here is only evaulated once. A non-efficient\n * case statement will evaluate all of its {@link SQLOperator}.\n *\n * @param caseColumn The value\n * @param <TReturn>\n * @return\n */\n public static <TReturn> Case<TReturn> _case(Property<TReturn> caseColumn) {\n return SQLite._case(caseColumn);\n }\n\n /**\n * Starts an efficient CASE statement. The value passed here is only evaulated once. A non-efficient\n * case statement will evaluate all of its {@link SQLOperator}.\n *\n * @param caseColumn The value\n * @param <TReturn>\n * @return\n */\n public static <TReturn> Case<TReturn> _case(IProperty caseColumn) {\n return SQLite._case(caseColumn);\n }\n}",
"public class RxGenericTransactionBlock extends Observable<Void> {\n\n private RxGenericTransactionBlock(Builder builder) {\n super(new OnTransactionSubscribe<Void>(builder.mTransactionProcessList, builder.mDatabaseWrapper));\n }\n\n private static class OnTransactionSubscribe<T> implements OnSubscribe<Void> {\n\n private final List<TransactionOperation> mTransactionProcessList;\n private final DatabaseWrapper mDatabaseWrapper;\n\n private OnTransactionSubscribe(List<TransactionOperation> transactionProcessList, DatabaseWrapper databaseWrapper) {\n mTransactionProcessList = transactionProcessList;\n mDatabaseWrapper = databaseWrapper;\n }\n\n @Override\n public void call(Subscriber<? super Void> subscriber) {\n\n try {\n mDatabaseWrapper.beginTransaction();\n\n for (int i = 0; i < mTransactionProcessList.size(); i++) {\n if(!mTransactionProcessList.get(i).onProcess(mDatabaseWrapper)){\n throw new SQLiteException(\"A transaction process item failed\");\n }\n }\n subscriber.onNext(null);\n subscriber.onCompleted();\n\n\n mDatabaseWrapper.setTransactionSuccessful();\n } catch (Exception e){\n subscriber.onError(e);\n } finally{\n mDatabaseWrapper.endTransaction();\n }\n }\n }\n\n /**\n * A build which creates a new generic transaction block.\n */\n public static class Builder {\n\n private final DatabaseWrapper mDatabaseWrapper;\n private List<TransactionOperation> mTransactionProcessList;\n\n /**\n * Creates a new builder with a specific database wrapper.\n * @param databaseWrapper The database wrapper to run the transaction against\n */\n public Builder(@NonNull DatabaseWrapper databaseWrapper){\n mTransactionProcessList = new ArrayList<>();\n mDatabaseWrapper = databaseWrapper;\n }\n\n /**\n * Creates a new builder, using a Model class to derive the target database. The class passed\n * to the parameter does not restrict the tables on which the database operations are performed.\n * As long as the operations run on a single database.\n * @param clazz The model class used to derive the target database.\n */\n public Builder(@NonNull Class<? extends Model> clazz){\n mTransactionProcessList = new ArrayList<>();\n mDatabaseWrapper = FlowManager.getDatabaseForTable(clazz).getWritableDatabase();\n }\n\n /**\n * Adds a new transaction operation to be performed within a transaction block.\n * @param operation The operation to perform\n * @return An instance of the current builder object.\n */\n public Builder addOperation(@NonNull TransactionOperation operation){\n mTransactionProcessList.add(operation);\n return this;\n }\n\n /**\n * Builds a new GenericTransactionBlock observable which will run all database operations within\n * a single transaction once it's subscribed to.\n * @return A new GenericTransactionBlock containing all database operations\n */\n public RxGenericTransactionBlock build(){\n return new RxGenericTransactionBlock(this);\n }\n }\n\n /**\n * Represents a single transaction operation to perform within a transaction block.\n */\n public interface TransactionOperation {\n boolean onProcess(DatabaseWrapper databaseWrapper);\n }\n}",
"public class RxModelOperationTransaction extends Observable<Void> {\n\n @IntDef({MODEL_OPERATION_UNSET, MODEL_OPERATION_SAVE, MODEL_OPERATION_UPDATE, MODEL_OPERATION_DELETE, MODEL_OPERATION_INSERT})\n @Retention(RetentionPolicy.SOURCE)\n public @interface ModelOperation {\n }\n\n public static final int MODEL_OPERATION_UNSET = -1;\n public static final int MODEL_OPERATION_SAVE = 0;\n public static final int MODEL_OPERATION_UPDATE = 1;\n public static final int MODEL_OPERATION_INSERT = 2;\n public static final int MODEL_OPERATION_DELETE = 3;\n\n private RxModelOperationTransaction(Builder builder) {\n //noinspection unchecked\n super(new OnTransactionSubscribe(builder.mModelList, builder.mOperationList, builder.mDatabaseWrapper, builder.mCanBatchTransaction, builder.mMustUseAdapters));\n }\n\n private static class OnTransactionSubscribe implements OnSubscribe<Void> {\n\n private final List<Object> mModelList;\n private final List<Integer> mOperationList;\n private final DatabaseWrapper mDatabaseWrapper;\n private final boolean mCanBatchTransaction;\n private boolean mMustUserAdapter;\n\n private OnTransactionSubscribe(List<Object> modelList, List<Integer> operationList, DatabaseWrapper databaseWrapper, boolean canBatchTransaction, boolean mustUseAdapter) {\n mModelList = modelList;\n mOperationList = operationList;\n mDatabaseWrapper = databaseWrapper;\n mCanBatchTransaction = canBatchTransaction;\n mMustUserAdapter = mustUseAdapter;\n }\n\n @Override\n public void call(Subscriber<? super Void> subscriber) {\n\n if (mOperationList.size() != mModelList.size()) {\n subscriber.onError(new IllegalStateException(\"model list and operation list must be of the same size\"));\n return;\n }\n\n try {\n mDatabaseWrapper.beginTransaction();\n if (mModelList.size() == 0) {\n subscriber.onNext(null);\n subscriber.onCompleted();\n return;\n } else if (mCanBatchTransaction) { //All operations are the same, and all Model types are the same\n @ModelOperation int batchOperation = mOperationList.get(0);\n performBatchOperation(batchOperation);\n } else if (mMustUserAdapter) {\n performIndividualAdapterOperations();\n } else {\n performIndividualOperations();\n }\n mDatabaseWrapper.setTransactionSuccessful();\n\n subscriber.onNext(null);\n subscriber.onCompleted();\n } catch (Exception e) {\n subscriber.onError(e);\n } finally {\n mDatabaseWrapper.endTransaction();\n }\n }\n\n private void performIndividualOperations() {\n for (int i = 0; i < mModelList.size(); i++) {\n @ModelOperation int operation = mOperationList.get(i);\n Model model = (Model) mModelList.get(i);\n\n if (operation == MODEL_OPERATION_SAVE) {\n model.save();\n } else if (operation == MODEL_OPERATION_DELETE) {\n model.delete();\n } else if (operation == MODEL_OPERATION_INSERT) {\n model.insert();\n } else if (operation == MODEL_OPERATION_UPDATE) {\n model.update();\n }\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private void performIndividualAdapterOperations() {\n for (int i = 0; i < mModelList.size(); i++) {\n @ModelOperation int operation = mOperationList.get(i);\n Object model = mModelList.get(i);\n ModelAdapter modelAdapter = FlowManager.getModelAdapter(model.getClass());\n\n if (operation == MODEL_OPERATION_SAVE) {\n modelAdapter.save(model);\n } else if (operation == MODEL_OPERATION_DELETE) {\n modelAdapter.delete(model);\n } else if (operation == MODEL_OPERATION_INSERT) {\n modelAdapter.insert(model);\n } else if (operation == MODEL_OPERATION_UPDATE) {\n modelAdapter.update(model);\n }\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private void performBatchOperation(@ModelOperation int batchOperation) {\n ModelAdapter adapter = FlowManager.getModelAdapter(mModelList.get(0).getClass());\n if (batchOperation == MODEL_OPERATION_SAVE) {\n adapter.saveAll(mModelList);\n } else if (batchOperation == MODEL_OPERATION_INSERT) {\n adapter.insertAll(mModelList);\n } else if (batchOperation == MODEL_OPERATION_UPDATE) {\n adapter.updateAll(mModelList);\n }\n }\n }\n\n /**\n * A builder which creates a new model operation transaction block.\n */\n public static class Builder {\n private final DatabaseWrapper mDatabaseWrapper;\n private List<Object> mModelList;\n private List<Integer> mOperationList;\n @ModelOperation\n private int mDefaultOperation = MODEL_OPERATION_UNSET;\n //If all models and operations are the same we can optimise for speed\n private boolean mCanBatchTransaction;\n private boolean mMustUseAdapters;\n\n /**\n * Creates a new builder with a specific database wrapper.\n *\n * @param databaseWrapper The database wrapper to run the transaction against\n */\n public Builder(DatabaseWrapper databaseWrapper) {\n mModelList = new ArrayList<>();\n mOperationList = new ArrayList<>();\n mDatabaseWrapper = databaseWrapper;\n }\n\n /**\n * Creates a new builder, using a Model class to derive the target database. The class passed\n * to the parameter does not restrict the tables on which the database operations are performed.\n * As long as the operations run on a single database.\n *\n * @param clazz The model class used to derive the target database.\n */\n public Builder(Class<? extends Model> clazz) {\n this(FlowManager.getDatabaseForTable(clazz).getWritableDatabase());\n }\n\n /**\n * Sets a default operation, this is useful when adding a list of models to the builder.\n *\n * @param modelOperation The model operation to use when no model operation is specified\n * @return An instance of the current builder.\n */\n public Builder setDefaultOperation(@ModelOperation int modelOperation) {\n mDefaultOperation = modelOperation;\n\n return this;\n }\n\n /**\n * Adds a model and it's associated operation to be performed within the transaction\n * block\n *\n * @param model The model to perform the transaction on\n * @param modelOperation The operation to be performed.\n * @return An instance of the current builder.\n */\n public Builder addModel(Object model, @ModelOperation int modelOperation) {\n if (mModelList.size() == 0) {\n mCanBatchTransaction = true;\n mMustUseAdapters = false;\n } else {\n\n if (!mMustUseAdapters) {\n mMustUseAdapters = !(model instanceof RxBaseModel);\n }\n\n if (mCanBatchTransaction) {\n //noinspection WrongConstant\n mCanBatchTransaction =\n (mModelList.get(0).getClass() == model.getClass()) &&\n mOperationList.get(0) == modelOperation &&\n modelOperation != MODEL_OPERATION_DELETE;\n }\n }\n\n mModelList.add(model);\n mOperationList.add(modelOperation);\n return this;\n }\n\n /**\n * Adds a model for which the default operation will be performed within the transaction\n * block.\n * <p><b>Please Note: </b> The default operation must be set before calling this</p>\n *\n * @param model The model to perform the default operation on.\n * @return An instance of the current builder.\n */\n public Builder addModel(Object model) {\n if (mDefaultOperation == MODEL_OPERATION_UNSET) {\n throw new IllegalStateException(\"No default operation set\");\n }\n addModel(model, mDefaultOperation);\n\n return this;\n }\n\n /**\n * Adds a list of models, with a single operation to be performed on each model within the\n * transaction block\n *\n * @param modelList A list of models\n * @param modelOperation The operation to be performed on each model\n * @return An instance of the current builder.\n */\n public Builder addAll(List<Object> modelList, @ModelOperation int modelOperation) {\n for (int i = 0; i < modelList.size(); i++) {\n addModel(modelList.get(i), modelOperation);\n }\n return this;\n }\n\n\n /**\n * Adds a list of models, with a paired list of operations. Each model within the list will have\n * have the operation at the same index applied to it, as such both lists must have the same number\n * of elements.\n *\n * @param modelList A list of models\n * @param modelOperationList A list of paired operations\n * @return An instance of the current builder.\n */\n public Builder addAll(List<Object> modelList, List<Integer> modelOperationList) {\n if (modelList.size() != modelOperationList.size()) {\n throw new IllegalArgumentException(\"model list and operation list must be of the same size\");\n }\n for (int i = 0; i < modelList.size(); i++) {\n //noinspection WrongConstant\n addModel(modelList.get(i), modelOperationList.get(i));\n }\n return this;\n }\n\n /**\n * Adds a list of models which will have the default operation performed on them.\n * * <p><b>Please Note: </b> The default operation must be set before calling this</p>\n *\n * @param modelList A list of models to be effected by the default operation\n * @return An instance of the current builder.\n */\n public Builder addAll(List<Object> modelList) {\n addAll(modelList, mDefaultOperation);\n\n return this;\n }\n\n\n /**\n * Builds a new ModelOperationTransaction observable which will run all database operations within\n * a single transaction once it's subscribed to.\n *\n * @return A new GenericTransactionBlock containing all database operations\n */\n public RxModelOperationTransaction build() {\n return new RxModelOperationTransaction(this);\n }\n }\n}",
"public class RxModelAdapter<TModel> implements InternalAdapter<TModel> {\n\n private ModelAdapter<TModel> mModelAdapter;\n\n /**\n * Creates a new RxModelAdapter from an standard ModelAdapter\n *\n * @param modelAdapter The model adapter to create the RxModelAdapter from\n */\n public RxModelAdapter(ModelAdapter<TModel> modelAdapter) {\n mModelAdapter = modelAdapter;\n }\n\n /**\n * Retrieves a RxModelAdapter instance for a model\n * @param clazz The class of the model\n * @param <TModel> The model type\n * @return A RxModelAdapter instane\n */\n public static <TModel> RxModelAdapter<TModel> getModelAdapter(Class<TModel> clazz) {\n return new RxModelAdapter<>(FlowManager.getModelAdapter(clazz));\n }\n\n /**\n * Retrieves the table name for the adapter\n * @return The table name\n */\n @Override\n public String getTableName() {\n return mModelAdapter.getTableName();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean save(TModel tModel) {\n return mModelAdapter.save(tModel);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean save(TModel tModel, DatabaseWrapper databaseWrapper) {\n return mModelAdapter.save(tModel, databaseWrapper);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void saveAll(Collection<TModel> tModels) {\n mModelAdapter.saveAll(tModels);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void saveAll(Collection<TModel> tModels, DatabaseWrapper databaseWrapper) {\n mModelAdapter.saveAll(tModels, databaseWrapper);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public long insert(TModel tModel) {\n return mModelAdapter.insert(tModel);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public long insert(TModel tModel, DatabaseWrapper databaseWrapper) {\n return mModelAdapter.insert(tModel, databaseWrapper);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void insertAll(Collection<TModel> tModels) {\n mModelAdapter.insertAll(tModels);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void insertAll(Collection<TModel> tModels, DatabaseWrapper databaseWrapper) {\n mModelAdapter.insertAll(tModels, databaseWrapper);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean update(TModel tModel) {\n return mModelAdapter.update(tModel);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean update(TModel tModel, DatabaseWrapper databaseWrapper) {\n return mModelAdapter.update(tModel, databaseWrapper);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void updateAll(Collection<TModel> tModels) {\n mModelAdapter.updateAll(tModels);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void updateAll(Collection<TModel> tModels, DatabaseWrapper databaseWrapper) {\n mModelAdapter.updateAll(tModels, databaseWrapper);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean delete(TModel tModel) {\n return mModelAdapter.delete(tModel);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean delete(TModel tModel, DatabaseWrapper databaseWrapper) {\n return mModelAdapter.delete(tModel, databaseWrapper);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void deleteAll(Collection<TModel> tModels) {\n mModelAdapter.deleteAll(tModels);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void deleteAll(Collection<TModel> tModels, DatabaseWrapper databaseWrapper) {\n mModelAdapter.deleteAll(tModels, databaseWrapper);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void bindToStatement(DatabaseStatement sqLiteStatement, TModel tModel) {\n mModelAdapter.bindToStatement(sqLiteStatement, tModel);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void bindToInsertStatement(DatabaseStatement sqLiteStatement, TModel tModel, @IntRange(from = 0L, to = 1L) int start) {\n mModelAdapter.bindToInsertStatement(sqLiteStatement, tModel, start);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void bindToInsertStatement(DatabaseStatement sqLiteStatement, TModel tModel) {\n mModelAdapter.bindToInsertStatement(sqLiteStatement, tModel);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void bindToContentValues(ContentValues contentValues, TModel tModel) {\n mModelAdapter.bindToContentValues(contentValues, tModel);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void bindToInsertValues(ContentValues contentValues, TModel tModel) {\n mModelAdapter.bindToInsertValues(contentValues, tModel);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void updateAutoIncrement(TModel tModel, Number id) {\n mModelAdapter.updateAutoIncrement(tModel, id);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Number getAutoIncrementingId(TModel tModel) {\n return mModelAdapter.getAutoIncrementingId(tModel);\n }\n\n /**\n * Loads or refreshes the data of a model based on the primary key\n * @param model The model to load or refresh\n */\n public void load(TModel model) {\n mModelAdapter.load(model);\n }\n\n /**\n * Loads or refreshes the data of a model based on the primary key\n * @param model The model to load or refresh\n * @param databaseWrapper The manually specified wrapper\n */\n public void load(TModel model, DatabaseWrapper databaseWrapper) {\n mModelAdapter.load(model, databaseWrapper);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean cachingEnabled() {\n return mModelAdapter.cachingEnabled();\n }\n\n /**\n * Returns an observable for saving the object in the database\n * @return An observable\n */\n public Observable<TModel> saveAsObservable(final TModel model) {\n return Observable.defer(new Func0<Observable<TModel>>() {\n @Override\n public Observable<TModel> call() {\n return Observable.fromCallable(new Callable<TModel>() {\n @Override\n public TModel call() throws Exception {\n save(model);\n return model;\n }\n });\n }\n });\n }\n\n /**\n * Returns an observable for saving the object in the database\n * @return An observable\n */\n public Observable<TModel> saveAsObservable(final TModel model, final DatabaseWrapper databaseWrapper) {\n return Observable.defer(new Func0<Observable<TModel>>() {\n @Override\n public Observable<TModel> call() {\n return Observable.fromCallable(new Callable<TModel>() {\n @Override\n public TModel call() throws Exception {\n save(model, databaseWrapper);\n return model;\n }\n });\n }\n });\n }\n\n /**\n * Returns an observable for inserting the object in the database\n * @return An observable\n */\n public Observable<TModel> insertAsObservable(final TModel model) {\n return Observable.defer(new Func0<Observable<TModel>>() {\n @Override\n public Observable<TModel> call() {\n return Observable.fromCallable(new Callable<TModel>() {\n @Override\n public TModel call() throws Exception {\n insert(model);\n return model;\n }\n });\n }\n });\n }\n\n /**\n * Returns an observable for inserting the object in the database\n * @return An observable\n */\n public Observable<TModel> insertAsObservable(final TModel model, final DatabaseWrapper databaseWrapper) {\n return Observable.defer(new Func0<Observable<TModel>>() {\n @Override\n public Observable<TModel> call() {\n return Observable.fromCallable(new Callable<TModel>() {\n @Override\n public TModel call() throws Exception {\n insert(model, databaseWrapper);\n return model;\n }\n });\n }\n });\n }\n\n /**\n * Returns an observable for deleting the object from the database\n * @return An observable\n */\n public Observable<TModel> deleteAsObservable(final TModel model) {\n return Observable.defer(new Func0<Observable<TModel>>() {\n @Override\n public Observable<TModel> call() {\n return Observable.fromCallable(new Callable<TModel>() {\n @Override\n public TModel call() throws Exception {\n delete(model);\n return model;\n }\n });\n }\n });\n }\n\n /**\n * Returns an observable for deleting the object from the database\n * @return An observable\n */\n public Observable<TModel> deleteAsObservable(final TModel model, final DatabaseWrapper databaseWrapper) {\n return Observable.defer(new Func0<Observable<TModel>>() {\n @Override\n public Observable<TModel> call() {\n return Observable.fromCallable(new Callable<TModel>() {\n @Override\n public TModel call() throws Exception {\n delete(model, databaseWrapper);\n return model;\n }\n });\n }\n });\n }\n\n /**\n * Returns an observable for update the object in the database\n * @return An observable\n */\n public Observable<TModel> updateAsObservable(final TModel model) {\n return Observable.defer(new Func0<Observable<TModel>>() {\n @Override\n public Observable<TModel> call() {\n return Observable.fromCallable(new Callable<TModel>() {\n @Override\n public TModel call() throws Exception {\n update(model);\n return model;\n }\n });\n }\n });\n }\n\n /**\n * Returns an observable for update the object in the database\n * @return An observable\n */\n public Observable<TModel> updateAsObservable(final TModel model, final DatabaseWrapper databaseWrapper) {\n return Observable.defer(new Func0<Observable<TModel>>() {\n @Override\n public Observable<TModel> call() {\n return Observable.fromCallable(new Callable<TModel>() {\n @Override\n public TModel call() throws Exception {\n update(model, databaseWrapper);\n return model;\n }\n });\n }\n });\n }\n\n /**\n * Returns an observable for update the object in the database\n * @return An observable\n */\n public Observable<TModel> loadAsObservable(final TModel model) {\n return Observable.defer(new Func0<Observable<TModel>>() {\n @Override\n public Observable<TModel> call() {\n return Observable.fromCallable(new Callable<TModel>() {\n @Override\n public TModel call() throws Exception {\n load(model);\n return model;\n }\n });\n }\n });\n }\n\n /**\n * Returns an observable which will refresh the model's data based on the primary key when subscribed.\n * @return An observable\n */\n public Observable<TModel> loadAsObservable(final TModel model, final DatabaseWrapper databaseWrapper) {\n return Observable.defer(new Func0<Observable<TModel>>() {\n @Override\n public Observable<TModel> call() {\n return Observable.fromCallable(new Callable<TModel>() {\n @Override\n public TModel call() throws Exception {\n load(model, databaseWrapper);\n return model;\n }\n });\n }\n });\n }\n}"
] | import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.raizlabs.android.dbflow.sql.language.Method;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import java.util.List;
import au.com.roadhouse.rxdbflow.exampleRx1.model.InheritanceTestModel;
import au.com.roadhouse.rxdbflow.exampleRx1.model.TestModel;
import au.com.roadhouse.rxdbflow.rx1.DBFlowSchedulers;
import au.com.roadhouse.rxdbflow.rx1.sql.language.RxSQLite;
import au.com.roadhouse.rxdbflow.rx1.sql.transaction.RxGenericTransactionBlock;
import au.com.roadhouse.rxdbflow.rx1.sql.transaction.RxModelOperationTransaction;
import au.com.roadhouse.rxdbflow.rx1.structure.RxModelAdapter;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription; | package au.com.roadhouse.rxdbflow.exampleRx1;
public class MainActivity extends AppCompatActivity {
private CompositeSubscription mDataSubscribers;
private Subscription mDatabaseInitSubscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDataSubscribers = new CompositeSubscription();
| mDatabaseInitSubscription = RxSQLite.select(Method.count()) | 3 |
Lambda-3/DiscourseSimplification | src/main/java/org/lambda3/text/simplification/discourse/runner/discourse_tree/extraction/rules/ListNP/ListNPExtractor.java | [
"public class Extraction {\n private String extractionRule;\n private boolean referring;\n private String cuePhrase; // optional\n private Relation relation;\n private boolean contextRight; // only for subordinate relations\n private List<Leaf> constituents;\n\n public Extraction(String extractionRule, boolean referring, List<Word> cuePhraseWords, Relation relation, boolean contextRight, List<Leaf> constituents) {\n if ((referring) && (constituents.size() != 1)) {\n throw new AssertionError(\"Referring relations should have one constituent\");\n }\n\n if ((!referring) && (!relation.isCoordination()) && (constituents.size() != 2)) {\n throw new AssertionError(\"(Non-referring) subordinate relations rules should have two constituents\");\n }\n\n this.extractionRule = extractionRule;\n this.referring = referring;\n this.cuePhrase = (cuePhraseWords == null)? null : WordsUtils.wordsToString(cuePhraseWords);\n this.relation = relation;\n this.contextRight = contextRight;\n this.constituents = constituents;\n }\n\n public Optional<DiscourseTree> generate(Leaf currChild) {\n\n if (relation.isCoordination()) {\n if (referring) {\n\n // find previous node to use as a reference\n Optional<DiscourseTree> prevNode = currChild.getPreviousNode();\n if ((prevNode.isPresent()) && (prevNode.get().usableAsReference())) {\n\n // use prev node as a reference\n prevNode.get().useAsReference();\n\n Coordination res = new Coordination(\n extractionRule,\n relation,\n cuePhrase,\n Collections.emptyList()\n );\n res.addCoordination(prevNode.get()); // set prev node as a reference\n res.addCoordination(constituents.get(0));\n\n return Optional.of(res);\n }\n } else {\n return Optional.of(new Coordination(\n extractionRule,\n relation,\n cuePhrase,\n constituents.stream().collect(Collectors.toList())\n ));\n }\n } else {\n if (referring) {\n\n // find previous node to use as a reference\n Optional<DiscourseTree> prevNode = currChild.getPreviousNode();\n if ((prevNode.isPresent()) && (prevNode.get().usableAsReference())) {\n\n // use prev node as a reference\n prevNode.get().useAsReference();\n\n Subordination res = new Subordination(\n extractionRule,\n relation,\n cuePhrase,\n new Leaf(), // tmp\n constituents.get(0),\n contextRight\n );\n res.replaceLeftConstituent(prevNode.get()); // set prev node as a reference\n\n return Optional.of(res);\n }\n } else {\n return Optional.of(new Subordination(\n extractionRule,\n relation,\n cuePhrase,\n constituents.get(0),\n constituents.get(1),\n contextRight\n ));\n }\n }\n\n return Optional.empty();\n }\n}",
"public abstract class ExtractionRule {\n protected static final Logger LOGGER = LoggerFactory.getLogger(ExtractionRule.class);\n\n protected enum Tense {\n PRESENT,\n PAST\n }\n\n protected enum Number {\n SINGULAR,\n PLURAL\n }\n\n protected CuePhraseClassifier classifer;\n\n public ExtractionRule() {\n }\n\n public void setConfig(Config config) {\n this.classifer = new CuePhraseClassifier(config);\n }\n\n public abstract Optional<Extraction> extract(Leaf leaf) throws ParseTreeException;\n\n protected static List<Tree> getSiblings(Tree parseTree, List<String> tags) {\n return parseTree.getChildrenAsList().stream().filter(c -> tags.contains(c.value())).collect(Collectors.toList());\n }\n\n protected static Number getNumber(Tree np) {\n Number res = Number.SINGULAR;\n\n // find plural forms\n TregexPattern p = TregexPattern.compile(\"NNS|NNPS\");\n TregexMatcher matcher = p.matcher(np);\n if (matcher.find()) {\n res = Number.PLURAL;\n }\n\n // find and\n p = TregexPattern.compile(\"CC <<: and\");\n matcher = p.matcher(np);\n if (matcher.find()) {\n res = Number.PLURAL;\n }\n\n return res;\n }\n\n protected static Tense getTense(Tree vp) {\n Tense res = Tense.PRESENT;\n\n // find past tense\n TregexPattern p = TregexPattern.compile(\"VBD|VBN\");\n TregexMatcher matcher = p.matcher(vp);\n\n if (matcher.find()) {\n res = Tense.PAST;\n }\n\n return res;\n }\n\n protected static Optional<Word> getHeadVerb(Tree vp) {\n TregexPattern pattern = TregexPattern.compile(vp.value() + \" [ <+(VP) (VP=lowestvp !< VP < /V../=v) | ==(VP=lowestvp !< VP < /V../=v) ]\");\n TregexMatcher matcher = pattern.matcher(vp);\n while (matcher.findAt(vp)) {\n return Optional.of(ParseTreeExtractionUtils.getContainingWords(matcher.getNode(\"v\")).get(0));\n }\n return Optional.empty();\n }\n\n private static List<Word> appendWordsFromTree(List<Word> words, Tree tree) {\n List<Word> res = new ArrayList<Word>();\n res.addAll(words);\n\n TregexPattern p = TregexPattern.compile(tree.value() + \" <<, NNP|NNPS\");\n TregexMatcher matcher = p.matcher(tree);\n\n boolean isFirst = true;\n for (Word word : tree.yieldWords()) {\n if ((isFirst) && (!matcher.findAt(tree))) {\n res.add(WordsUtils.lowercaseWord(word));\n } else {\n res.add(word);\n }\n isFirst = false;\n }\n\n return res;\n }\n\n // pp is optional\n protected static List<Word> rephraseIntraSententialAttribution(List<Word> words) {\n try {\n List<Word> res = new ArrayList<>();\n\n Tree parseTree = ParseTreeParser.parse(WordsUtils.wordsToProperSentenceString(words));\n\n TregexPattern p = TregexPattern.compile(\"ROOT << (S !> S < (NP=np ?$,, PP=pp $.. VP=vp))\");\n TregexMatcher matcher = p.matcher(parseTree);\n if (matcher.findAt(parseTree)) {\n Tree pp = matcher.getNode(\"pp\"); // optional\n Tree np = matcher.getNode(\"np\");\n Tree vp = matcher.getNode(\"vp\");\n\n Tense tense = getTense(vp);\n if (tense.equals(Tense.PRESENT)) {\n res.add(new Word(\"This\"));\n res.add(new Word(\"is\"));\n res.add(new Word(\"what\"));\n } else {\n res.add(new Word(\"This\"));\n res.add(new Word(\"was\"));\n res.add(new Word(\"what\"));\n }\n res = appendWordsFromTree(res, np);\n res = appendWordsFromTree(res, vp);\n if (pp != null) {\n res = appendWordsFromTree(res, pp);\n }\n }\n\n return res;\n } catch (ParseTreeException e) {\n return words;\n }\n }\n\n protected static List<Word> rephraseEnablement(Tree s, Tree vp) {\n List<Word> res = new ArrayList<>();\n\n Tense tense = getTense(vp);\n if (tense.equals(Tense.PRESENT)) {\n res.add(new Word(\"This\"));\n res.add(new Word(\"is\"));\n } else {\n res.add(new Word(\"This\"));\n res.add(new Word(\"was\"));\n }\n res = appendWordsFromTree(res, s);\n\n return res;\n }\n\n \n protected static String rephraseApposition(Tree vp, String np) {\n String res = \"\";\n\n Tense tense = getTense(vp);\n //Number number = getNumber(np);\n if (tense.equals(Tense.PRESENT)) {\n \tif (np.equals(\"NN\") || np.equals(\"NNP\")) {\n \t\tres = \" is \";\n \t} else {\n \t\tres = \" are \";\n \t}\n } else {\n \tif (np.equals(\"NN\") || np.equals(\"NNP\")) {\n \t\tres = \" was \";\n \t} else {\n \t\tres = \" were \";\n \t}\n }\n \n return res;\n }\n \n protected static List<Word> rephraseAppositionNonRes(Tree vp, Tree np, Tree np2) {\n List<Word> res = new ArrayList<>();\n\n Tense tense = getTense(vp);\n Number number = getNumber(np);\n if (tense.equals(Tense.PRESENT)) {\n \tif (number.equals(Number.SINGULAR)) {\n \t\t res.add(new Word(\"is\"));\n \t} else {\n \t\t res.add(new Word(\"are\"));\n \t}\n } else {\n \tif (number.equals(Number.SINGULAR)) {\n \t\t res.add(new Word(\"was\"));\n \t} else {\n \t\t res.add(new Word(\"were\"));\n \t}\n }\n res = appendWordsFromTree(res, np2);\n \n return res;\n }\n\n\n protected static List<Word> getRephrasedParticipalS(Tree np, Tree vp, Tree s, Tree vbgn) {\n Number number = getNumber(np);\n Tense tense = getTense(vp);\n\n TregexPattern p = TregexPattern.compile(vbgn.value() + \" <<: (having . (been . VBN=vbn))\");\n TregexPattern p2 = TregexPattern.compile(vbgn.value() + \" <<: (having . VBN=vbn)\");\n TregexPattern p3 = TregexPattern.compile(vbgn.value() + \" <<: (being . VBN=vbn)\");\n\n TregexMatcher matcher = p.matcher(s);\n if (matcher.findAt(s)) {\n List<Word> res = new ArrayList<>();\n\n res.add(new Word((number.equals(Number.SINGULAR))? \"has\" : \"have\"));\n res.add(new Word(\"been\"));\n List<Word> next = ParseTreeExtractionUtils.getFollowingWords(s, matcher.getNode(\"vbn\"), true);\n if (next.size() > 0) {\n next.set(0, WordsUtils.lowercaseWord(next.get(0)));\n }\n res.addAll(next);\n\n return res;\n }\n\n matcher = p2.matcher(s);\n if (matcher.findAt(s)) {\n List<Word> res = new ArrayList<>();\n\n res.add(new Word((number.equals(Number.SINGULAR))? \"has\" : \"have\"));\n List<Word> next = ParseTreeExtractionUtils.getFollowingWords(s, matcher.getNode(\"vbn\"), true);\n if (next.size() > 0) {\n next.set(0, WordsUtils.lowercaseWord(next.get(0)));\n }\n res.addAll(next);\n\n return res;\n }\n\n matcher = p3.matcher(s);\n if (matcher.findAt(s)) {\n List<Word> res = new ArrayList<>();\n if (tense.equals(Tense.PRESENT)) {\n res.add(new Word((number.equals(Number.SINGULAR)) ? \"is\" : \"are\"));\n } else {\n res.add(new Word((number.equals(Number.SINGULAR)) ? \"was\" : \"were\"));\n }\n List<Word> next = ParseTreeExtractionUtils.getFollowingWords(s, matcher.getNode(\"vbn\"), true);\n if (next.size() > 0) {\n next.set(0, WordsUtils.lowercaseWord(next.get(0)));\n }\n res.addAll(next);\n\n return res;\n }\n\n // default\n List<Word> res = new ArrayList<>();\n if (tense.equals(Tense.PRESENT)) {\n res.add(new Word((number.equals(Number.SINGULAR)) ? \"is\" : \"are\"));\n } else {\n res.add(new Word((number.equals(Number.SINGULAR)) ? \"was\" : \"were\"));\n }\n List<Word> next = ParseTreeExtractionUtils.getFollowingWords(s, vbgn, true);\n if (next.size() > 0) {\n next.set(0, WordsUtils.lowercaseWord(next.get(0)));\n }\n res.addAll(next);\n\n return res;\n }\n\n}",
"public class ListNPSplitter {\n private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ListNPSplitter.class);\n\n public static class Result {\n private final List<Word> introductionWords; //optional\n private final List<List<Word>> elementsWords;\n\n private final Relation relation;\n\n public Result(List<Word> introductionWords, List<List<Word>> elementsWords, Relation relation) {\n this.introductionWords = introductionWords;\n this.elementsWords = elementsWords;\n this.relation = relation;\n }\n\n public Optional<List<Word>> getIntroductionWords() {\n return Optional.ofNullable(introductionWords);\n }\n\n public List<List<Word>> getElementsWords() {\n return elementsWords;\n }\n\n public Relation getRelation() {\n return relation;\n }\n\n }\n\n private static class ConjunctionLeafChecker implements ParseTreeExtractionUtils.INodeChecker {\n private final String word;\n\n public ConjunctionLeafChecker(String word) {\n this.word = word;\n }\n\n @Override\n public boolean check(Tree anchorTree, Tree leaf) {\n return ((leaf.yieldWords().get(0).value().equals(word)) && (leaf.parent(anchorTree) != null) && (leaf.parent(anchorTree).value().equals(\"CC\")));\n }\n }\n\n private static class ValueLeafChecker implements ParseTreeExtractionUtils.INodeChecker {\n private final String word;\n\n public ValueLeafChecker(String word) {\n this.word = word;\n }\n\n @Override\n public boolean check(Tree anchorTree, Tree leaf) {\n return leaf.value().equals(word);\n }\n }\n\n private static boolean checkElementLeaves(Tree anchorTree, List<Tree> leaves) {\n Optional<Tree> spanningTree = ParseTreeExtractionUtils.findSpanningTree(anchorTree, leaves.get(0), leaves.get(leaves.size() - 1));\n return (spanningTree.isPresent()) && (spanningTree.get().value().equals(\"NP\"));\n\n }\n\n private static boolean isFollowedByConjDisjunction(Tree anchorTree, Tree np, ParseTreeExtractionUtils.INodeChecker conjDisjChecker, ParseTreeExtractionUtils.INodeChecker separatorChecker) {\n List<Tree> followingLeaves = ParseTreeExtractionUtils.getFollowingLeaves(anchorTree, np, false);\n for (Tree followingLeaf : followingLeaves) {\n if (conjDisjChecker.check(anchorTree, followingLeaf)) {\n return true;\n } else if (separatorChecker.check(anchorTree, followingLeaf)) {\n // nothing\n } else {\n return false;\n }\n }\n return false;\n }\n\n private static Optional<Result> check(Tree anchorTree, Tree np, ParseTreeExtractionUtils.INodeChecker conjDisjChecker, ParseTreeExtractionUtils.INodeChecker separatorChecker, Relation relation) {\n List<Tree> checkLeaves = ParseTreeExtractionUtils.getContainingLeaves(np);\n\n // find introduction\n List<Word> introductionWords = null;\n List<Tree> introSeparators = findLeaves(anchorTree, checkLeaves, new ValueLeafChecker(\":\"), false);\n if (introSeparators.size() > 0) {\n List<Word> iws = ParseTreeExtractionUtils.getPrecedingWords(np, introSeparators.get(0), false);\n if (iws.size() > 0) {\n introductionWords = iws;\n checkLeaves = ParseTreeExtractionUtils.getFollowingLeaves(np, introSeparators.get(0), false);\n }\n }\n\n if (checkLeaves.size() == 0) {\n return Optional.empty();\n }\n\n // special case (Con/Disjunction is right after the NP e.g. initiating a verb phrase)\n // e.g. \"To leave monuments to his reign , he built [the Collège des Quatre-Nations , Place Vendôme , Place des Victoires ,] and began Les Invalides .\"\n if (isFollowedByConjDisjunction(anchorTree, np, conjDisjChecker, separatorChecker)) {\n List<List<Tree>> elements = splitLeaves(np, checkLeaves, separatorChecker, true);\n boolean valid = true;\n\n // check elements\n if (elements.size() >= 2) {\n for (List<Tree> element : elements) {\n if (!checkElementLeaves(np, element)) {\n valid = false;\n break;\n }\n }\n } else {\n valid = false;\n }\n\n if (valid) {\n List<List<Word>> elementsWords = elements.stream().map(e -> ParseTreeExtractionUtils.leavesToWords(e)).collect(Collectors.toList());\n\n return Optional.of(new Result(introductionWords, elementsWords, relation));\n }\n }\n\n // check different conjunction/disjunction leaves (from right to left)\n for (Tree cdLeaf : findLeaves(np, checkLeaves, conjDisjChecker, true)) {\n boolean valid = true;\n List<Tree> beforeLeaves = ParseTreeExtractionUtils.getLeavesInBetween(np, checkLeaves.get(0), cdLeaf, true, false);\n List<Tree> afterLeaves = ParseTreeExtractionUtils.getLeavesInBetween(np, cdLeaf, checkLeaves.get(checkLeaves.size() - 1), false, true);\n\n List<List<Tree>> beforeElements = splitLeaves(np, beforeLeaves, separatorChecker, true);\n List<Tree> afterElement = afterLeaves;\n\n // check before elements\n if (beforeElements.size() >= 1) {\n for (List<Tree> beforeElement : beforeElements) {\n if (!checkElementLeaves(np, beforeElement)) {\n valid = false;\n break;\n }\n }\n } else {\n valid = false;\n }\n\n // check after element\n if (afterElement.size() >= 1) {\n// if (!checkElementLeaves(anchorTree, afterElement)) {\n// valid = false;\n// }\n } else {\n valid = false;\n }\n\n if (valid) {\n List<List<Word>> elementsWords = new ArrayList<>();\n elementsWords.addAll(beforeElements.stream().map(e -> ParseTreeExtractionUtils.leavesToWords(e)).collect(Collectors.toList()));\n elementsWords.add(ParseTreeExtractionUtils.leavesToWords(afterLeaves));\n\n return Optional.of(new Result(introductionWords, elementsWords, relation));\n }\n }\n\n return Optional.empty();\n }\n\n public static Optional<Result> splitList(Tree anchorTree, Tree np) {\n boolean containsSemicolon = ParseTreeExtractionUtils.findLeaves(np, ParseTreeExtractionUtils.getContainingLeaves(np), new ValueLeafChecker(\";\"), false).size() > 0;\n if (containsSemicolon) {\n\n // check for conjunction with elements separated by ;\n Optional<Result> r = check(anchorTree, np, new ConjunctionLeafChecker(\"and\"), new ValueLeafChecker(\";\"), Relation.LIST);\n if (r.isPresent()) {\n return r;\n }\n\n // check for disjunction with elements separated by ;\n r = check(anchorTree, np, new ConjunctionLeafChecker(\"or\"), new ValueLeafChecker(\";\"), Relation.DISJUNCTION);\n if (r.isPresent()) {\n return r;\n }\n } else {\n\n // check for conjunction with elements separated by ,\n Optional<Result> r = check(anchorTree, np, new ConjunctionLeafChecker(\"and\"), new ValueLeafChecker(\",\"), Relation.LIST);\n if (r.isPresent()) {\n return r;\n }\n\n // check for disjunction with elements separated by ,\n r = check(anchorTree, np, new ConjunctionLeafChecker(\"or\"), new ValueLeafChecker(\",\"), Relation.DISJUNCTION);\n if (r.isPresent()) {\n return r;\n }\n }\n\n return Optional.empty();\n }\n}",
"public class Leaf extends DiscourseTree {\n private Tree parseTree;\n private boolean allowSplit; // true, if extraction-rules will be applied on the text\n private boolean toSimpleContext;\n\n public Leaf() {\n super(\"UNKNOWN\");\n }\n\n public Leaf(String extractionRule, Tree parseTree) {\n super(extractionRule);\n this.parseTree = parseTree;\n this.allowSplit = true;\n this.toSimpleContext = false;\n }\n\n // not efficient -> prefer to use constructor with tree\n public Leaf(String extractionRule, String text) throws ParseTreeException {\n this(extractionRule, ParseTreeParser.parse(text));\n }\n\n public void dontAllowSplit() {\n this.allowSplit = false;\n }\n\n public Tree getParseTree() {\n return parseTree;\n }\n\n public void setParseTree(Tree parseTree) {\n this.parseTree = parseTree;\n }\n\n public String getText() {\n return WordsUtils.wordsToString(ParseTreeExtractionUtils.getContainingWords(parseTree));\n }\n\n public void setToSimpleContext(boolean toSimpleContext) {\n this.toSimpleContext = toSimpleContext;\n }\n\n public boolean isAllowSplit() {\n return allowSplit;\n }\n\n public boolean isToSimpleContext() {\n return toSimpleContext;\n }\n\n // VISUALIZATION ///////////////////////////////////////////////////////////////////////////////////////////////////\n\n @Override\n public List<String> getPTPCaption() {\n return Collections.singletonList(\"'\" + getText() + \"'\");\n }\n\n @Override\n public List<PrettyTreePrinter.Edge> getPTPEdges() {\n return new ArrayList<>();\n }\n}",
"public class ParseTreeException extends Exception {\n\n public ParseTreeException(String text) {\n super(\"Failed to parse text: \\\"\" + text + \"\\\"\");\n }\n}",
"public class ParseTreeExtractionUtils {\n\n public interface INodeChecker {\n boolean check(Tree anchorTree, Tree node);\n }\n\n\n public static List<Integer> getLeafNumbers(Tree anchorTree, Tree node) {\n List<Integer> res = new ArrayList<>();\n for (Tree leaf : node.getLeaves()) {\n res.add(leaf.nodeNumber(anchorTree));\n }\n return res;\n }\n\n private static IndexRange getLeafIndexRange(Tree anchorTree, Tree node) {\n int fromIdx = -1;\n int toIdx = -1;\n\n List<Integer> leafNumbers = getLeafNumbers(anchorTree, anchorTree);\n List<Integer> nodeLeafNumbers = getLeafNumbers(anchorTree, node);\n int fromNumber = nodeLeafNumbers.get(0);\n int toNumber = nodeLeafNumbers.get(nodeLeafNumbers.size() - 1);\n\n int idx = 0;\n for (int leafNumber : leafNumbers) {\n if (leafNumber == fromNumber) {\n fromIdx = idx;\n }\n if (leafNumber == toNumber) {\n toIdx = idx;\n }\n ++idx;\n }\n\n if ((fromIdx >= 0) && (toIdx >= 0)) {\n return new IndexRange(fromIdx, toIdx);\n } else {\n throw new IllegalArgumentException(\"node should be a subtree of anchorTree.\");\n }\n }\n\n // returns True, if the model of node would not check/divide a NER group, else False\n public static boolean isNERSafeExtraction(Tree anchorTree, NERString anchorNERString, Tree node) {\n IndexRange leafIdxRange = getLeafIndexRange(anchorTree, node);\n List<IndexRange> nerIdxRanges = NERExtractionUtils.getNERIndexRanges(anchorNERString);\n\n for (IndexRange nerIdxRange : nerIdxRanges) {\n if (((nerIdxRange.getFromIdx() < leafIdxRange.getFromIdx()) && (leafIdxRange.getFromIdx() <= nerIdxRange.getToIdx()))\n || ((nerIdxRange.getFromIdx() <= leafIdxRange.getToIdx()) && (leafIdxRange.getToIdx() < nerIdxRange.getToIdx()))) {\n return false;\n }\n }\n\n return true;\n }\n\n\n\n\n public static List<Word> leavesToWords(List<Tree> leaves) {\n return leaves.stream().map(l -> l.yieldWords().get(0)).collect(Collectors.toList());\n }\n\n public static List<List<Tree>> splitLeaves(Tree anchorTree, List<Tree> leaves, INodeChecker leafChecker, boolean removeEmpty) {\n List<List<Tree>> res = new ArrayList<>();\n List<Tree> currElement = new ArrayList<>();\n for (Tree leaf : leaves) {\n if (leafChecker.check(anchorTree, leaf)) {\n if ((currElement.size() > 0) || (!removeEmpty))\n res.add(currElement);\n currElement = new ArrayList<>();\n } else {\n currElement.add(leaf);\n }\n }\n if ((currElement.size() > 0) || (!removeEmpty))\n res.add(currElement);\n\n return res;\n }\n\n public static List<Tree> findLeaves(Tree anchorTree, List<Tree> leaves, INodeChecker leafChecker, boolean reversed) {\n List<Tree> res = leaves.stream().filter(l -> leafChecker.check(anchorTree, l)).collect(Collectors.toList());\n if (reversed) {\n Collections.reverse(res);\n }\n return res;\n }\n\n public static Tree getFirstLeaf(Tree tree) {\n if (tree.isLeaf()) {\n return tree;\n } else {\n return getFirstLeaf(tree.firstChild());\n }\n }\n\n public static Tree getLastLeaf(Tree tree) {\n if (tree.isLeaf()) {\n return tree;\n } else {\n return getLastLeaf(tree.lastChild());\n }\n }\n\n public static List<Tree> getLeavesInBetween(Tree anchorTree, Tree leftNode, Tree rightNode, boolean includeLeft, boolean includeRight) {\n List<Tree> res = new ArrayList<>();\n\n if (leftNode == null) {\n leftNode = getFirstLeaf(anchorTree);\n }\n if (rightNode == null) {\n rightNode = getLastLeaf(anchorTree);\n }\n\n int startLeafNumber = (includeLeft) ? getFirstLeaf(leftNode).nodeNumber(anchorTree) : getLastLeaf(leftNode).nodeNumber(anchorTree) + 1;\n int endLeafNumber = (includeRight) ? getLastLeaf(rightNode).nodeNumber(anchorTree) : getFirstLeaf(rightNode).nodeNumber(anchorTree) - 1;\n if ((startLeafNumber < 0) || (endLeafNumber < 0)) {\n return res;\n }\n\n for (int i = startLeafNumber; i <= endLeafNumber; ++i) {\n Tree node = anchorTree.getNodeNumber(i);\n if (node.isLeaf()) {\n res.addAll(node);\n }\n }\n\n return res;\n }\n\n public static List<Tree> getPrecedingLeaves(Tree anchorTree, Tree node, boolean include) {\n return getLeavesInBetween(anchorTree, getFirstLeaf(anchorTree), node, true, include);\n }\n\n public static List<Tree> getFollowingLeaves(Tree anchorTree, Tree node, boolean include) {\n return getLeavesInBetween(anchorTree, node, getLastLeaf(anchorTree), include, true);\n }\n\n public static List<Tree> getContainingLeaves(Tree node) {\n return getLeavesInBetween(node, getFirstLeaf(node), getLastLeaf(node), true, true);\n }\n\n public static List<Word> getWordsInBetween(Tree anchorTree, Tree leftNode, Tree rightNode, boolean includeLeft, boolean includeRight) {\n return leavesToWords(getLeavesInBetween(anchorTree, leftNode, rightNode, includeLeft, includeRight));\n }\n\n public static List<Word> getPrecedingWords(Tree anchorTree, Tree node, boolean include) {\n return leavesToWords(getPrecedingLeaves(anchorTree, node, include));\n }\n\n public static List<Word> getFollowingWords(Tree anchorTree, Tree node, boolean include) {\n return leavesToWords(getFollowingLeaves(anchorTree, node, include));\n }\n\n public static List<Word> getContainingWords(Tree node) {\n return leavesToWords(getContainingLeaves(node));\n }\n\n public static Optional<Tree> findSpanningTree(Tree anchorTree, Tree firstLeaf, Tree lastLeaf) {\n return findSpanningTreeRec(anchorTree, anchorTree, firstLeaf, lastLeaf);\n }\n\n private static Optional<Tree> findSpanningTreeRec(Tree anchorTree, Tree currTree, Tree firstLeaf, Tree lastLeaf) {\n int firstNumber = firstLeaf.nodeNumber(anchorTree);\n int lastNumber = lastLeaf.nodeNumber(anchorTree);\n int currFirstNumber = getFirstLeaf(currTree).nodeNumber(anchorTree);\n int currLastNumber = getLastLeaf(currTree).nodeNumber(anchorTree);\n if (((currFirstNumber <= firstNumber) && (firstNumber <= currLastNumber)) && ((currFirstNumber <= lastNumber) && (lastNumber <= currLastNumber))) {\n if ((currFirstNumber == firstNumber) && (lastNumber == currLastNumber)) {\n return Optional.of(currTree);\n } else {\n // recursion\n for (Tree child : currTree.getChildrenAsList()) {\n Optional<Tree> cr = findSpanningTreeRec(anchorTree, child, firstLeaf, lastLeaf);\n if (cr.isPresent()) {\n return Optional.of(cr.get());\n }\n }\n }\n }\n\n return Optional.empty();\n }\n}",
"public class WordsUtils {\n\n public static Word lemmatize(Word word) {\n Sentence sentence = new Sentence(word.value());\n return new Word(sentence.lemma(0));\n }\n\n public static List<Word> splitIntoWords(String sentence) {\n PTBTokenizer<CoreLabel> ptbt = new PTBTokenizer<>(new StringReader(sentence), new CoreLabelTokenFactory(), \"\");\n List<Word> words = new ArrayList<>();\n\n while (ptbt.hasNext()) {\n CoreLabel label = ptbt.next();\n words.add(new Word(label));\n }\n\n return words;\n }\n\n public static String wordsToString(List<Word> words) {\n return SentenceUtils.listToString(words);\n }\n\n public static String wordsToProperSentenceString(List<Word> words) {\n return wordsToString(wordsToProperSentence(words));\n }\n\n private static Word capitalizeWord(Word word) {\n String s = word.value();\n if (s.length() > 0) {\n s = s.substring(0, 1).toUpperCase() + s.substring(1);\n }\n\n return new Word(s);\n }\n\n public static Word lowercaseWord(Word word) {\n return new Word(word.value().toLowerCase());\n }\n\n private static List<Word> wordsToProperSentence(List<Word> words) {\n List<Word> res = new ArrayList<>();\n res.addAll(words);\n\n // trim '.' and ',' at beginning and the end and remove multiple, consecutive occurrences\n for (String c : Arrays.asList(\".\", \",\")) {\n Word prev = null;\n Iterator<Word> it = res.iterator();\n while (it.hasNext()) {\n Word word = it.next();\n if (word.value().equals(c)) {\n if (prev == null || prev.value().equals(word.value())) {\n it.remove();\n }\n }\n prev = word;\n }\n if ((!res.isEmpty()) && (res.get(res.size() - 1).value().equals(c))) {\n res.remove(res.size() - 1);\n }\n }\n\n // add a '.' at the end\n res.add(new Word(\".\"));\n\n // capitalize first word\n if (!res.isEmpty()) {\n res.set(0, capitalizeWord(res.get(0)));\n }\n\n return res;\n }\n}"
] | import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeExtractionUtils;
import org.lambda3.text.simplification.discourse.utils.words.WordsUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import edu.stanford.nlp.ling.Word;
import edu.stanford.nlp.trees.tregex.TregexMatcher;
import edu.stanford.nlp.trees.tregex.TregexPattern;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.Extraction;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.ExtractionRule;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.utils.ListNPSplitter;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.model.Leaf;
import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeException; | /*
* ==========================License-Start=============================
* DiscourseSimplification : ListNPExtractor
*
* Copyright © 2017 Lambda³
*
* GNU General Public License 3
* 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/.
* ==========================License-End==============================
*/
package org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.rules.ListNP;
/**
*
*/
public abstract class ListNPExtractor extends ExtractionRule {
private final String pattern;
public ListNPExtractor(String pattern) {
this.pattern = pattern;
}
@Override
public Optional<Extraction> extract(Leaf leaf) throws ParseTreeException {
TregexPattern p = TregexPattern.compile(pattern);
TregexMatcher matcher = p.matcher(leaf.getParseTree());
while (matcher.findAt(leaf.getParseTree())) {
Optional<ListNPSplitter.Result> r = ListNPSplitter.splitList(leaf.getParseTree(), matcher.getNode("np"));
if (r.isPresent()) {
// constituents
List<Word> precedingWords = ParseTreeExtractionUtils.getPrecedingWords(leaf.getParseTree(), matcher.getNode("np"), false);
List<Word> followingWords = ParseTreeExtractionUtils.getFollowingWords(leaf.getParseTree(), matcher.getNode("np"), false);
List<Leaf> constituents = new ArrayList<>();
if (r.get().getIntroductionWords().isPresent()) {
List<Word> words = new ArrayList<Word>();
words.addAll(precedingWords);
words.addAll(r.get().getIntroductionWords().get());
words.addAll(followingWords);
| Leaf constituent = new Leaf(getClass().getSimpleName(), WordsUtils.wordsToProperSentenceString(words)); | 6 |
YiuChoi/MicroReader | app/src/main/java/name/caiyao/microreader/ui/adapter/VideoAdapter.java | [
"public class UtilRequest {\n\n private UtilRequest() {}\n\n private static UtilApi utilApi = null;\n private static final Object monitor = new Object();\n\n public static UtilApi getUtilApi() {\n synchronized (monitor) {\n if (utilApi == null) {\n utilApi = new Retrofit.Builder()\n .baseUrl(\"http://www.baidu.com\")\n .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n .build().create(UtilApi.class);\n }\n return utilApi;\n }\n }\n}",
"public class WeiboVideoBlog implements Parcelable {\n @SerializedName(\"mblog\")\n private WeiboVideoMBlog mBlog;\n\n protected WeiboVideoBlog(Parcel in) {\n in.readParcelable(WeiboVideoMBlog.class.getClassLoader());\n }\n\n public WeiboVideoMBlog getBlog() {\n return mBlog;\n }\n\n public void setBlog(WeiboVideoMBlog blog) {\n mBlog = blog;\n }\n\n public static final Creator<WeiboVideoBlog> CREATOR = new Creator<WeiboVideoBlog>() {\n @Override\n public WeiboVideoBlog createFromParcel(Parcel in) {\n return new WeiboVideoBlog(in);\n }\n\n @Override\n public WeiboVideoBlog[] newArray(int size) {\n return new WeiboVideoBlog[size];\n }\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.writeParcelable(mBlog, flags);\n }\n}",
"public class Config {\n public static final String TX_APP_KEY = \"1ae28fc9dd5afadc696ad94cd59426d8\";\n\n public static final String DB__IS_READ_NAME = \"IsRead\";\n public static final String WEIXIN = \"weixin\";\n public static final String GUOKR = \"guokr\";\n public static final String ZHIHU = \"zhihu\";\n public static final String VIDEO = \"video\";\n public static final String IT = \"it\";\n\n public static boolean isNight = false;\n\n public enum Channel {\n WEIXIN( R.string.fragment_wexin_title, R.drawable.icon_weixin),\n GUOKR(R.string.fragment_guokr_title, R.drawable.icon_guokr),\n ZHIHU(R.string.fragment_zhihu_title, R.drawable.icon_zhihu),\n VIDEO(R.string.fragment_video_title, R.drawable.icon_video),\n IT( R.string.fragment_it_title, R.drawable.icon_it);\n\n private int title;\n private int icon;\n\n Channel(int title, int icon) {\n this.title = title;\n this.icon = icon;\n }\n\n public int getTitle() {\n return title;\n }\n\n public int getIcon() {\n return icon;\n }\n }\n}",
"public class VideoActivity extends AppCompatActivity {\n\n @BindView(R.id.vv_gank)\n VideoView vvGank;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_video);\n ButterKnife.bind(this);\n final String url = getIntent().getStringExtra(\"url\");\n final String shareUrl = getIntent().getStringExtra(\"shareUrl\");\n final String title = getIntent().getStringExtra(\"title\");\n vvGank.setVideoPath(url);\n final ProgressDialog progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(getString(R.string.common_loading));\n progressDialog.show();\n vvGank.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {\n @Override\n public void onPrepared(MediaPlayer mp) {\n progressDialog.dismiss();\n }\n });\n vvGank.setOnErrorListener(new MediaPlayer.OnErrorListener() {\n @Override\n public boolean onError(MediaPlayer mp, int what, int extra) {\n progressDialog.dismiss();\n Toast.makeText(VideoActivity.this,\"视频不存在或已被删除!\",Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n CustomMediaController customMediaController = new CustomMediaController(this);\n customMediaController.setListener(new OnMediaControllerInteractionListener() {\n @Override\n public void onShareClickListener() {\n Intent shareIntent = new Intent();\n shareIntent.setAction(Intent.ACTION_SEND);\n shareIntent.putExtra(Intent.EXTRA_TEXT, title + \" \" + shareUrl + getString(R.string.share_tail));\n shareIntent.setType(\"text/plain\");\n //设置分享列表的标题,并且每次都显示分享列表\n startActivity(Intent.createChooser(shareIntent, getString(R.string.share)));\n }\n });\n vvGank.setMediaController(customMediaController);\n vvGank.start();\n }\n\n public interface OnMediaControllerInteractionListener {\n void onShareClickListener();\n }\n\n class CustomMediaController extends MediaController {\n\n Context mContext;\n private OnMediaControllerInteractionListener mListener;\n\n public CustomMediaController(Context context) {\n super(context);\n mContext = context;\n }\n\n public void setListener(OnMediaControllerInteractionListener listener) {\n mListener = listener;\n }\n\n @Override\n public void setAnchorView(View view) {\n super.setAnchorView(view);\n FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(\n LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);\n frameParams.setMargins(0,50,500,0);\n frameParams.gravity = Gravity.RIGHT|Gravity.TOP;\n\n ImageButton fullscreenButton = (ImageButton) LayoutInflater.from(mContext)\n .inflate(R.layout.share_buttion, null,false);\n\n fullscreenButton.setOnClickListener(new OnClickListener() {\n public void onClick(View v) {\n if(mListener != null) {\n mListener.onShareClickListener();\n }\n }\n });\n\n addView(fullscreenButton, frameParams);\n }\n\n @Override\n public void show(int timeout) {\n super.show(timeout);\n // fix pre Android 4.3 strange positioning when used in Fragments\n int currentapiVersion = android.os.Build.VERSION.SDK_INT;\n if (currentapiVersion < Build.VERSION_CODES.JELLY_BEAN_MR2) {\n try {\n Field field1 = MediaController.class.getDeclaredField(\"mAnchor\");\n field1.setAccessible(true);\n View mAnchor = (View)field1.get(this);\n\n Field field2 = MediaController.class.getDeclaredField(\"mDecor\");\n field2.setAccessible(true);\n View mDecor = (View)field2.get(this);\n\n Field field3 = MediaController.class.getDeclaredField(\"mDecorLayoutParams\");\n field3.setAccessible(true);\n WindowManager.LayoutParams mDecorLayoutParams = (WindowManager.LayoutParams)field3.get(this);\n\n Field field4 = MediaController.class.getDeclaredField(\"mWindowManager\");\n field4.setAccessible(true);\n WindowManager mWindowManager = (WindowManager)field4.get(this);\n\n // NOTE: this appears in its own Window so co-ordinates are screen co-ordinates\n int [] anchorPos = new int[2];\n mAnchor.getLocationOnScreen(anchorPos);\n\n // we need to know the size of the controller so we can properly position it\n // within its space\n mDecor.measure(MeasureSpec.makeMeasureSpec(mAnchor.getWidth(), MeasureSpec.AT_MOST),\n MeasureSpec.makeMeasureSpec(mAnchor.getHeight(), MeasureSpec.AT_MOST));\n\n mDecor.setPadding(0,0,0,0);\n\n mDecorLayoutParams.verticalMargin = 0;\n mDecorLayoutParams.horizontalMargin = 0;\n mDecorLayoutParams.width = mAnchor.getWidth();\n mDecorLayoutParams.gravity = Gravity.LEFT|Gravity.TOP;\n mDecorLayoutParams.x = anchorPos[0];// + (mAnchor.getWidth() - p.width) / 2;\n mDecorLayoutParams.y = anchorPos[1] + mAnchor.getHeight() - mDecor.getMeasuredHeight();\n mWindowManager.updateViewLayout(mDecor, mDecorLayoutParams);\n\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n }\n}",
"public class VideoWebViewActivity extends BaseActivity {\n\n @BindView(R.id.wv_video)\n WebView wvVideo;\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_video_webview);\n ButterKnife.bind(this);\n String url = getIntent().getStringExtra(\"url\");\n\n WebSettings webSettings = wvVideo.getSettings();\n webSettings.setJavaScriptEnabled(true);\n webSettings.setUseWideViewPort(true);\n webSettings.setBuiltInZoomControls(true);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);\n }\n webSettings.setAllowFileAccess(true);\n webSettings.setLoadWithOverviewMode(true);\n wvVideo.setWebViewClient(new WebViewClient() {\n @SuppressWarnings(\"deprecation\")\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String urlTo) {\n //处理自动跳转到浏览器的问题\n view.loadUrl(urlTo);\n return true;\n }\n });\n wvVideo.setWebChromeClient(new WebChromeClient() {\n\n //显示全屏按钮\n private View myView = null;\n private CustomViewCallback myCallback = null;\n\n @Override\n public void onShowCustomView(View view, CustomViewCallback callback) {\n if (myCallback != null) {\n myCallback.onCustomViewHidden();\n myCallback = null;\n return;\n }\n ViewGroup parent = (ViewGroup) wvVideo.getParent();\n parent.removeView(wvVideo);\n parent.addView(view);\n myView = view;\n myCallback = callback;\n }\n\n @Override\n public void onHideCustomView() {\n if (myView != null) {\n if (myCallback != null) {\n myCallback.onCustomViewHidden();\n myCallback = null;\n }\n ViewGroup parent = (ViewGroup) myView.getParent();\n parent.removeView(myView);\n parent.addView(wvVideo);\n myView = null;\n }\n }\n\n @Override\n public boolean onJsAlert(WebView view, String url, String message, JsResult result) {\n result.confirm();\n return super.onJsAlert(view, url, message, result);\n }\n });\n wvVideo.loadUrl(url);\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n try {\n wvVideo.getClass().getMethod(\"onResume\").invoke(wvVideo, (Object[]) null);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n try {\n wvVideo.getClass().getMethod(\"onPause\").invoke(wvVideo, (Object[]) null);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onDestroy() {\n if (wvVideo != null) {\n ((ViewGroup) wvVideo.getParent()).removeView(wvVideo);\n wvVideo.destroy();\n wvVideo = null;\n }\n super.onDestroy();\n }\n}",
"public class DBUtils {\n public static final String CREATE_TABLE_IF_NOT_EXISTS = \"create table if not exists %s \" +\n \"(id integer primary key autoincrement,key text unique,is_read integer)\";\n\n private static DBUtils sDBUtis;\n private SQLiteDatabase mSQLiteDatabase;\n\n private DBUtils(Context context) {\n mSQLiteDatabase = new DBHelper(context, Config.DB__IS_READ_NAME + \".db\").getWritableDatabase();\n }\n\n public static synchronized DBUtils getDB(Context context) {\n if (sDBUtis == null)\n sDBUtis = new DBUtils(context);\n return sDBUtis;\n }\n\n\n public void insertHasRead(String table, String key, int value) {\n Cursor cursor = mSQLiteDatabase.query(table, null, null, null, null, null, \"id asc\");\n if (cursor.getCount() > 200 && cursor.moveToNext()) {\n mSQLiteDatabase.delete(table, \"id=?\", new String[]{String.valueOf(cursor.getInt(cursor.getColumnIndex(\"id\")))});\n }\n cursor.close();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"key\", key);\n contentValues.put(\"is_read\", value);\n mSQLiteDatabase.insertWithOnConflict(table, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);\n }\n\n public boolean isRead(String table, String key,int value) {\n boolean isRead = false;\n Cursor cursor = mSQLiteDatabase.query(table, null, \"key=?\", new String[]{key}, null, null, null);\n if (cursor.moveToNext() && (cursor.getInt(cursor.getColumnIndex(\"is_read\")) == value)) {\n isRead = true;\n }\n cursor.close();\n return isRead;\n }\n\n public class DBHelper extends SQLiteOpenHelper {\n\n public DBHelper(Context context, String name) {\n super(context, name, null, 1);\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n db.execSQL(String.format(CREATE_TABLE_IF_NOT_EXISTS, Config.GUOKR));\n db.execSQL(String.format(CREATE_TABLE_IF_NOT_EXISTS, Config.IT));\n db.execSQL(String.format(CREATE_TABLE_IF_NOT_EXISTS, Config.VIDEO));\n db.execSQL(String.format(CREATE_TABLE_IF_NOT_EXISTS, Config.ZHIHU));\n db.execSQL(String.format(CREATE_TABLE_IF_NOT_EXISTS, Config.WEIXIN));\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\n }\n }\n}",
"public class ImageLoader {\n private ImageLoader() {\n }\n\n public static void loadImage(Context context, String url, ImageView imageView) {\n if (Config.isNight) {\n imageView.setAlpha(0.2f);\n imageView.setBackgroundColor(Color.BLACK);\n }\n Glide.with(context).load(url).into(imageView);\n }\n}",
"public class SharePreferenceUtil {\n\n private SharePreferenceUtil() {}\n\n public static final String SHARED_PREFERENCE_NAME = \"micro_reader\";\n public static final String IMAGE_DESCRIPTION = \"image_description\";\n public static final String VIBRANT = \"vibrant\";\n public static final String MUTED = \"muted\";\n public static final String IMAGE_GET_TIME = \"image_get_time\";\n public static final String SAVED_CHANNEL = \"saved_channel\";\n\n public static boolean isRefreshOnlyWifi(Context context) {\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n return sharedPreferences.getBoolean(context.getResources().getString(R.string.pre_refresh_data), false);\n }\n\n public static boolean isChangeThemeAuto(Context context) {\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n return sharedPreferences.getBoolean(context.getResources().getString(R.string.pre_get_image), true);\n }\n\n public static boolean isImmersiveMode(Context context) {\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n return sharedPreferences.getBoolean(context.getString(R.string.pre_status_bar), true);\n }\n\n public static boolean isChangeNavColor(Context context) {\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n return sharedPreferences.getBoolean(context.getString(R.string.pre_nav_color), true);\n }\n\n public static boolean isUseLocalBrowser(Context context) {\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n return sharedPreferences.getBoolean(context.getString(R.string.pre_use_local), false);\n }\n}"
] | import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import name.caiyao.microreader.R;
import name.caiyao.microreader.api.util.UtilRequest;
import name.caiyao.microreader.bean.weiboVideo.WeiboVideoBlog;
import name.caiyao.microreader.config.Config;
import name.caiyao.microreader.ui.activity.VideoActivity;
import name.caiyao.microreader.ui.activity.VideoWebViewActivity;
import name.caiyao.microreader.utils.DBUtils;
import name.caiyao.microreader.utils.ImageLoader;
import name.caiyao.microreader.utils.SharePreferenceUtil;
import okhttp3.ResponseBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers; | package name.caiyao.microreader.ui.adapter;
/**
* Created by 蔡小木 on 2016/4/29 0029.
*/
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {
private ArrayList<WeiboVideoBlog> gankVideoItems;
private Context mContext;
public VideoAdapter(Context context, ArrayList<WeiboVideoBlog> gankVideoItems) {
this.gankVideoItems = gankVideoItems;
this.mContext = context;
}
@Override
public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new VideoViewHolder(LayoutInflater.from(mContext).inflate(R.layout.video_item, parent, false));
}
@Override
public void onBindViewHolder(final VideoViewHolder holder, int position) {
final WeiboVideoBlog weiboVideoBlog = gankVideoItems.get(position);
final String title = weiboVideoBlog.getBlog().getText().replaceAll("&[a-zA-Z]{1,10};", "").replaceAll(
"<[^>]*>", "");
if (DBUtils.getDB(mContext).isRead(Config.VIDEO, weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(), 1))
holder.tvTitle.setTextColor(Color.GRAY);
else
holder.tvTitle.setTextColor(Color.BLACK);
ImageLoader.loadImage(mContext, weiboVideoBlog.getBlog().getPageInfo().getVideoPic(), holder.mIvVideo);
holder.tvTitle.setText(title);
holder.tvTime.setText(weiboVideoBlog.getBlog().getCreateTime());
holder.btnVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(mContext, holder.btnVideo);
popupMenu.getMenuInflater().inflate(R.menu.pop_menu, popupMenu.getMenu());
popupMenu.getMenu().removeItem(R.id.pop_fav);
final boolean isRead = DBUtils.getDB(mContext).isRead(Config.VIDEO, weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(), 1);
if (!isRead)
popupMenu.getMenu().findItem(R.id.pop_unread).setTitle(R.string.common_set_read);
else
popupMenu.getMenu().findItem(R.id.pop_unread).setTitle(R.string.common_set_unread);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.pop_unread:
if (isRead) {
DBUtils.getDB(mContext).insertHasRead(Config.VIDEO, weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(), 0);
holder.tvTitle.setTextColor(Color.BLACK);
} else {
DBUtils.getDB(mContext).insertHasRead(Config.VIDEO, weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(), 1);
holder.tvTitle.setTextColor(Color.GRAY);
}
break;
case R.id.pop_share:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, title + " " + weiboVideoBlog.getBlog().getPageInfo().getVideoUrl() + mContext.getString(R.string.share_tail));
shareIntent.setType("text/plain");
//设置分享列表的标题,并且每次都显示分享列表
mContext.startActivity(Intent.createChooser(shareIntent, mContext.getString(R.string.share)));
break;
}
return true;
}
});
popupMenu.show();
}
});
holder.cvVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DBUtils.getDB(mContext).insertHasRead(Config.VIDEO, weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(), 1);
holder.tvTitle.setTextColor(Color.GRAY);
VideoAdapter.this.getPlayUrl(weiboVideoBlog, title);
}
});
}
private void getPlayUrl(final WeiboVideoBlog weiboVideoBlog, final String title) {
final ProgressDialog progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage(mContext.getString(R.string.fragment_video_get_url));
progressDialog.show();
UtilRequest.getUtilApi().getVideoUrl(weiboVideoBlog.getBlog().getPageInfo().getVideoUrl())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (progressDialog.isShowing()) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(mContext, "视频解析失败!", Toast.LENGTH_SHORT).show();
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(weiboVideoBlog.getBlog().getPageInfo().getVideoUrl())));
}
}
@Override
public void onNext(ResponseBody responseBody) {
//防止停止后继续执行
if (progressDialog.isShowing()) {
progressDialog.dismiss();
try {
String shareUrl = weiboVideoBlog.getBlog().getPageInfo().getVideoUrl();
String url = responseBody.string();
if (TextUtils.isEmpty(shareUrl)) {
Toast.makeText(mContext, "播放地址为空", Toast.LENGTH_SHORT).show();
return;
}
Log.i("TAG", shareUrl);
Log.i("TAG", url);
if (url.contains("http")) { | mContext.startActivity(new Intent(mContext, VideoActivity.class) | 3 |
mathisdt/trackworktime | app/src/main/java/org/zephyrsoft/trackworktime/report/CsvGenerator.java | [
"public class DAO {\n\n\t// TODO use prepared statements as described here: http://stackoverflow.com/questions/7255574\n\n\tprivate volatile SQLiteDatabase db;\n\tprivate final MySQLiteHelper dbHelper;\n\tprivate final Context context;\n\tprivate final WorkTimeTrackerBackupManager backupManager;\n\tprivate final Basics basics;\n\n\tprivate static final Pattern RESTORE_PATTERN = Pattern.compile(\";\");\n\n\t/**\n\t * Constructor\n\t */\n\tpublic DAO(Context context) {\n\t\tthis.context = context;\n\t\tdbHelper = new MySQLiteHelper(context);\n\t\tbackupManager = new WorkTimeTrackerBackupManager(context);\n\t\tbasics = Basics.getOrCreateInstance(context);\n\t}\n\n\t/**\n\t * Open the underlying database. Implicitly called before any database operation.\n\t */\n\tprivate synchronized void open() throws SQLException {\n\t\tif(db == null || !db.isOpen()) {\n\t\t\tdb = dbHelper.getWritableDatabase();\n\t\t}\n\t}\n\n\t/**\n\t * Close the underlying database.\n\t */\n\tpublic synchronized void close() {\n\t\tdbHelper.close();\n\t}\n\n\t// =======================================================\n\n\tprivate static final String[] TASK_FIELDS = { TASK_ID, TASK_NAME, TASK_ACTIVE, TASK_ORDERING, TASK_DEFAULT };\n\n\tprivate Task cursorToTask(Cursor cursor) {\n\t\tTask task = new Task();\n\t\ttask.setId(cursor.getInt(0));\n\t\ttask.setName(cursor.getString(1));\n\t\ttask.setActive(cursor.getInt(2));\n\t\ttask.setOrdering(cursor.getInt(3));\n\t\ttask.setIsDefault(cursor.getInt(4));\n\t\treturn task;\n\t}\n\n\tprivate ContentValues taskToContentValues(Task task) {\n\t\tContentValues ret = new ContentValues();\n\t\tret.put(TASK_NAME, task.getName());\n\t\tret.put(TASK_ACTIVE, task.getActive());\n\t\tret.put(TASK_ORDERING, task.getOrdering());\n\t\tret.put(TASK_DEFAULT, task.getIsDefault());\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Insert a new task.\n\t *\n\t * @param task\n\t * the task to add\n\t * @return the newly created task as read from the database (complete with ID)\n\t */\n\tpublic synchronized Task insertTask(Task task) {\n\t\topen();\n\t\tContentValues args = taskToContentValues(task);\n\t\tlong insertId = db.insert(TASK, null, args);\n\t\t// now fetch the newly inserted row and return it as Task object\n\t\tList<Task> created = getTasksWithConstraint(TASK_ID + \"=\" + insertId);\n\t\tdataChanged();\n\t\treturn created.get(0);\n\t}\n\n\t/**\n\t * Get all tasks.\n\t *\n\t * @return all existing tasks\n\t */\n\tpublic List<Task> getAllTasks() {\n\t\treturn getTasksWithConstraint(null);\n\t}\n\n\t/**\n\t * Get all active tasks.\n\t *\n\t * @return all existing tasks that are active at the moment\n\t */\n\tpublic List<Task> getActiveTasks() {\n\t\treturn getTasksWithConstraint(TASK_ACTIVE + \"!=0\");\n\t}\n\n\t/**\n\t * Get the default task.\n\t *\n\t * @return the default task or {@code null} (if no task was marked as default or if the default task is deactivated)\n\t */\n\tpublic Task getDefaultTask() {\n\t\tList<Task> tasks = getTasksWithConstraint(TASK_ACTIVE + \"!=0 AND \" + TASK_DEFAULT + \"!=0\");\n\t\treturn tasks.isEmpty() ? null : tasks.get(0);\n\t}\n\n\t/**\n\t * Get the task with a specific ID.\n\t *\n\t * @param id\n\t * the ID\n\t * @return the task or {@code null} if the specified ID does not exist\n\t */\n\tpublic Task getTask(Integer id) {\n\t\tList<Task> tasks = getTasksWithConstraint(TASK_ID + \"=\" + id);\n\t\treturn tasks.isEmpty() ? null : tasks.get(0);\n\t}\n\n\t/**\n\t * Get the first task with a specific name.\n\t *\n\t * @param name\n\t * the name\n\t * @return the task (first if more than one exist) or {@code null} if the specified name does not exist at all\n\t */\n\tpublic Task getTask(String name) {\n\t\tList<Task> tasks = getTasksWithConstraint(TASK_NAME + \"=\\\"\" + name + \"\\\"\");\n\t\treturn tasks.isEmpty() ? null : tasks.get(0);\n\t}\n\n\t/**\n\t * Return if the task with the given ID is used in an event.\n\t */\n\tpublic synchronized boolean isTaskUsed(Integer id) {\n\t\tCursor cursor = db.query(EVENT, new String[] { \"count(*)\" }, EVENT_TASK + \" = \" + id, null,\n\t\t\tnull, null, null, null);\n\t\tcursor.moveToFirst();\n\t\tint count = 0;\n\t\tif (!cursor.isAfterLast()) {\n\t\t\tcount = cursor.getInt(0);\n\t\t}\n\t\tcursor.close();\n\t\treturn count > 0;\n\t}\n\n\tprivate synchronized List<Task> getTasksWithConstraint(String constraint) {\n\t\topen();\n\t\tList<Task> ret = new ArrayList<>();\n\t\t// TODO sort tasks by TASK_ORDERING when the UI supports manual ordering of tasks\n\t\tCursor cursor = db.query(TASK, TASK_FIELDS, constraint, null, null, null, TASK_NAME);\n\t\tcursor.moveToFirst();\n\t\twhile (!cursor.isAfterLast()) {\n\t\t\tTask task = cursorToTask(cursor);\n\t\t\tret.add(task);\n\t\t\tcursor.moveToNext();\n\t\t}\n\t\tcursor.close();\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Update a task.\n\t *\n\t * @param task\n\t * the task to update - the ID has to be set!\n\t * @return the task as newly read from the database\n\t */\n\tpublic synchronized Task updateTask(Task task) {\n\t\topen();\n\t\tContentValues args = taskToContentValues(task);\n\t\tdb.update(TASK, args, TASK_ID + \"=\" + task.getId(), null);\n\t\t// now fetch the newly updated row and return it as Task object\n\t\tList<Task> updated = getTasksWithConstraint(TASK_ID + \"=\" + task.getId() + \"\");\n\t\tdataChanged();\n\t\treturn updated.get(0);\n\t}\n\n\t/**\n\t * Remove a task.\n\t *\n\t * @param task\n\t * the task to delete - the ID has to be set!\n\t * @return {@code true} if successful, {@code false} if not\n\t */\n\tpublic synchronized boolean deleteTask(Task task) {\n\t\topen();\n\t\tfinal boolean result = db.delete(TASK, TASK_ID + \"=\" + task.getId(), null) > 0;\n\t\tdataChanged();\n\t\treturn result;\n\t}\n\n\n\t// =======================================================\n\n\tprivate static final String[] EVENT_FIELDS = { EVENT_ID, EVENT_TIME, EVENT_ZONE_OFFSET, EVENT_TYPE, EVENT_TASK, EVENT_TEXT };\n\tprivate static final String[] MAX_EVENT_FIELDS = { EVENT_ID, \"max(\" + EVENT_TIME + \")\", EVENT_ZONE_OFFSET, EVENT_TYPE,\n\t\tEVENT_TASK, EVENT_TEXT };\n\n\tprivate Event cursorToEvent(Cursor cursor) {\n\t\tEvent event = new Event();\n\t\tevent.setId(cursor.getInt(0));\n\n\t\tInstant instant = Instant.ofEpochSecond(cursor.getLong(1));\n\t\tZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(cursor.getInt(2) * 60);\n\t\tevent.setDateTime(instant.atOffset(zoneOffset));\n\n\t\tevent.setType(cursor.getInt(3));\n\t\tevent.setTask(cursor.getInt(4));\n\t\tevent.setText(cursor.getString(5));\n\t\treturn event;\n\t}\n\n\tprivate ContentValues eventToContentValues(Event event) {\n\t\tContentValues ret = new ContentValues();\n\n\t\tOffsetDateTime dateTime = event.getDateTime();\n\t\tret.put(EVENT_TIME, dateTime.toEpochSecond());\n\t\tret.put(EVENT_ZONE_OFFSET, dateTime.getOffset().getTotalSeconds() / 60);\n\n\t\tret.put(EVENT_TYPE, event.getType());\n\t\tret.put(EVENT_TASK, event.getTask());\n\t\tret.put(EVENT_TEXT, event.getText());\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Insert a new event.\n\t *\n\t * @param event\n\t * the event to add\n\t * @return the newly created event as read from the database (complete with ID)\n\t */\n\tpublic synchronized Event insertEvent(Event event) {\n\t\topen();\n\t\tContentValues args = eventToContentValues(event);\n\t\tlong insertId = db.insert(EVENT, null, args);\n\t\t// now fetch the newly created row and return it as Event object\n\t\tList<Event> created = getEventsWithConstraint(EVENT_ID + \"=\" + insertId);\n\t\tif (created.size() > 0) {\n\t\t\tdataChanged();\n\t\t\treturn created.get(0);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Return all events - attention: this may be slow if many events exist!\n\t */\n\tpublic List<Event> getAllEvents() {\n\t\treturn getEventsWithConstraint(null);\n\t}\n\n\t/**\n\t * Return the events that are in the specified time frame.\n\t */\n\tpublic List<Event> getEvents(Instant beginOfTimeFrame, Instant endOfTimeFrame) {\n\t\treturn getEventsWithConstraint(EVENT_TIME + \" >= \\\"\" + beginOfTimeFrame.getEpochSecond()\n\t\t\t+ \"\\\" AND \" + EVENT_TIME + \" < \\\"\" + endOfTimeFrame.getEpochSecond() + \"\\\"\");\n\t}\n\n\t/**\n\t * Return all events in a certain week.\n\t *\n\t * @param week\n\t * the week in which the events are searched - the ID has to be set!\n\t */\n\tpublic List<Event> getEventsInWeek(Week week, ZoneId zoneId) {\n\t\t// FIXME\n\t\tif (week == null) {\n\t\t\treturn Collections.emptyList();\n\t\t} else {\n\t\t\tInstant instantA = week.getStart().atStartOfDay(zoneId).toInstant();\n\t\t\tInstant instantB = week.getEnd().atTime(LocalTime.MAX).atZone(zoneId).toInstant();\n\n\t\t\treturn getEvents(instantA, instantB);\n\t\t}\n\t}\n\n\t/**\n\t * Return all events on a certain day.\n\t *\n\t * @param date\n\t * the day on which the events are searched\n\t */\n\tpublic List<Event> getEventsOnDay(ZonedDateTime date) {\n\t\treturn getEventsOnDayBefore(date.with(LocalTime.MAX));\n\t}\n\n\t/**\n\t * Return all events on a certain day before the given timestamp.\n\t *\n\t * @param date the day on which the events are searched\n\t */\n\tpublic List<Event> getEventsOnDayBefore(ZonedDateTime date) {\n\t\tlong instantA = date.with(LocalTime.MIN).toEpochSecond();\n\t\tlong instantB = date.toEpochSecond();\n\n\t\treturn getEventsWithConstraint(EVENT_TIME + \" >= \\\"\" + instantA +\n\t\t\t\"\\\" AND \" + EVENT_TIME + \" < \\\"\" + instantB + \"\\\"\");\n\t}\n\n\t/**\n\t * Return all events on a certain day up to and including the given timestamp.\n\t *\n\t * @param date the day on which the events are searched\n\t */\n\tpublic List<Event> getEventsOnDayUpTo(ZonedDateTime date) {\n\t\tlong instantA = date.with(LocalTime.MIN).toEpochSecond();\n\t\tlong instantB = date.toEpochSecond();\n\n\t\treturn getEventsWithConstraint(EVENT_TIME + \" >= \\\"\" + instantA +\n\t\t\t\t\"\\\" AND \" + EVENT_TIME + \"<= \\\"\" + instantB + \"\\\"\");\n\t}\n\n\t/**\n\t * Return all events on a certain day after the given timestamp.\n\t *\n\t * @param date the day on which the events are searched\n\t */\n\tpublic List<Event> getEventsOnDayAfter(ZonedDateTime date) {\n\t\tlong instantA = date.toEpochSecond();\n\t\tlong instantB = date.with(LocalTime.MAX).toEpochSecond();\n\n\n\t\treturn getEventsWithConstraint(EVENT_TIME + \" > \\\"\" + instantA +\n\t\t\t\t\"\\\" AND \" + EVENT_TIME + \"<= \\\"\" + instantB + \"\\\"\");\n\t}\n\n\t/**\n\t * Fetch a specific event.\n\t *\n\t * @param id\n\t * the ID of the event\n\t * @return the event, or {@code null} if the id does not exist\n\t */\n\tpublic Event getEvent(Integer id) {\n\t\tList<Event> event = getEventsWithParameters(EVENT_FIELDS, EVENT_ID + \" = \" + id, false, true);\n\t\t// if event is empty, then there is no such event in the database\n\t\treturn event.isEmpty() ? null : event.get(0);\n\t}\n\n\t/**\n\t * Return the last event before a certain date and time or {@code null} if there is no such event.\n\t *\n\t * @param dateTime\n\t * the date and time before which the event is searched\n\t */\n\tpublic Event getLastEventBefore(OffsetDateTime dateTime) {\n\t\tList<Event> lastEvent = getEventsWithParameters(EVENT_FIELDS, EVENT_TIME + \" < \\\"\"\n\t\t\t+ dateTime.toEpochSecond() + \"\\\"\", true, true);\n\t\t// if lastEvent is empty, then there is no such event in the database\n\t\treturn lastEvent.isEmpty() ? null : lastEvent.get(0);\n\t}\n\n\t/**\n\t * Return the last event before a certain date and time (including the hour and minute given!)\n\t * or {@code null} if there is no such event.\n\t *\n\t * @param dateTime\n\t * the date and time before which the event is searched\n\t */\n\tpublic Event getLastEventUpTo(OffsetDateTime dateTime) {\n\t\tList<Event> lastEvent = getEventsWithParameters(EVENT_FIELDS, EVENT_TIME + \" <= \\\"\"\n\t\t\t+ dateTime.toEpochSecond() + \"\\\"\", true, true);\n\t\t// if lastEvent is empty, then there is no such event in the database\n\t\treturn lastEvent.isEmpty() ? null : lastEvent.get(0);\n\t}\n\n\t/**\n\t * Return the first event after a certain date and time or {@code null} if there is no such event.\n\t *\n\t * @param dateTime\n\t * the date and time after which the event is searched\n\t */\n\tpublic Event getFirstEventAfter(OffsetDateTime dateTime) {\n\t\tList<Event> firstEvent = getEventsWithParameters(EVENT_FIELDS, EVENT_TIME + \" > \\\"\"\n\t\t\t+ dateTime.toEpochSecond() + \"\\\"\", false, true);\n\t\t// if firstEvent is empty, then there is no such event in the database\n\t\treturn firstEvent.isEmpty() ? null : firstEvent.get(0);\n\t}\n\n\t/**\n\t * Return the first event with the given type on a certain day after a certain time\n\t * or {@code null} if there is no such event.\n\t *\n\t * @param dateTime\n\t * the date and time after which the event is searched\n\t */\n\tpublic Event getFirstEventAfterWithType(ZonedDateTime dateTime, TypeEnum type) {\n\t\tlong instantA = dateTime.toEpochSecond();\n\n\t\tString constraint =\n\t\t\t\tEVENT_TIME + \" > \\\"\" + instantA + \"\\\" AND \" + EVENT_TYPE + \" = \" + type.toString();\n\n\t\tList<Event> firstEvent = getEventsWithParameters(EVENT_FIELDS, constraint, false, true);\n\n\t\t// if firstEvent is empty, then there is no such event in the database\n\t\treturn firstEvent.isEmpty() ? null : firstEvent.get(0);\n\t}\n\n\t/**\n\t * Return the first recorded event or {@code null} if no event exists.\n\t */\n\tpublic Event getFirstEvent() {\n\t\tList<Event> firstEvent = getEventsWithParameters(EVENT_FIELDS, null, false, true);\n\t\t// if firstEvent is empty, then there is no event in the database\n\t\treturn firstEvent.isEmpty() ? null : firstEvent.get(0);\n\t}\n\n\t/**\n\t * Return the last recorded event or {@code null} if no event exists.\n\t */\n\tpublic Event getLatestEvent() {\n\t\tList<Event> latestEvent = getEventsWithParameters(MAX_EVENT_FIELDS, null, false, true);\n\t\t// if latestEvent is empty, then there is no event in the database\n\t\treturn latestEvent.isEmpty() ? null : latestEvent.get(0);\n\t}\n\n\tprivate synchronized List<Event> getEventsWithParameters(String[] fields, String constraint,\n\t\t\tboolean descending,\n\t\tboolean limitedToOne) {\n\t\topen();\n\t\tList<Event> ret = new ArrayList<>();\n\t\tCursor cursor = db.query(EVENT, fields, constraint, null, null, null, EVENT_TIME + (descending ? \" desc\" : \"\")\n\t\t\t+ \",\" + EVENT_ID + (descending ? \" desc\" : \"\"), (limitedToOne ? \"1\" : null));\n\t\tcursor.moveToFirst();\n\t\twhile (!cursor.isAfterLast()) {\n\t\t\tEvent event = cursorToEvent(cursor);\n\t\t\tret.add(event);\n\t\t\tcursor.moveToNext();\n\t\t}\n\t\tcursor.close();\n\t\treturn ret;\n\t}\n\n\tprivate List<Event> getEventsWithConstraint(String constraint) {\n\t\treturn getEventsWithParameters(EVENT_FIELDS, constraint, false, false);\n\t}\n\n\t/**\n\t * Update an event.\n\t *\n\t * @param event\n\t * the event to update - the ID has to be set!\n\t * @return the event as newly read from the database\n\t */\n\tpublic synchronized Event updateEvent(Event event) {\n\t\topen();\n\t\tContentValues args = eventToContentValues(event);\n\t\tdb.update(EVENT, args, EVENT_ID + \"=\" + event.getId(), null);\n\t\t// now fetch the newly updated row and return it as Event object\n\t\tList<Event> updated = getEventsWithConstraint(EVENT_ID + \"=\" + event.getId());\n\t\tdataChanged();\n\t\treturn updated.get(0);\n\t}\n\n\t/**\n\t * Remove an event.\n\t *\n\t * @param event\n\t * the event to delete - the ID has to be set!\n\t * @return {@code true} if successful, {@code false} if not\n\t */\n\tpublic synchronized boolean deleteEvent(Event event) {\n\t\topen();\n\t\tfinal boolean result = db.delete(EVENT, EVENT_ID + \"=\" + event.getId(), null) > 0;\n\t\tdataChanged();\n\t\treturn result;\n\t}\n\n\tprivate synchronized boolean deleteAll() {\n\t\topen();\n\t\tboolean result = db.delete(TASK, null, null) > 0;\n\t\tresult |= db.delete(EVENT, null, null) > 0;\n\t\tdataChanged();\n\t\treturn result;\n\t}\n\n\tpublic synchronized Cursor getAllEventsAndTasks() {\n\t\topen();\n\t\tfinal String querySelectPart = \"SELECT\"\n\t\t\t+ \" \" + MySQLiteHelper.EVENT + \".\" + MySQLiteHelper.EVENT_ID + \" AS eventId\"\n\t\t\t+ \", \" + MySQLiteHelper.EVENT_TYPE\n\t\t\t+ \", \" + MySQLiteHelper.EVENT_TIME\n\t\t\t+ \", \" + MySQLiteHelper.EVENT_ZONE_OFFSET\n\t\t\t+ \", \" + MySQLiteHelper.EVENT_TASK\n\t\t\t+ \", \" + MySQLiteHelper.EVENT_TEXT\n\t\t\t+ \", \" + MySQLiteHelper.TASK + \".\" + MySQLiteHelper.TASK_ID + \" AS taskId\"\n\t\t\t+ \", \" + MySQLiteHelper.TASK_NAME\n\t\t\t+ \", \" + MySQLiteHelper.TASK_ACTIVE\n\t\t\t+ \", \" + MySQLiteHelper.TASK_ORDERING\n\t\t\t+ \", \" + MySQLiteHelper.TASK_DEFAULT;\n\n\t\t// this is a FULL OUTER JOIN.\n\t\t// see http://stackoverflow.com/questions/1923259/full-outer-join-with-sqlite\n\t\tfinal String query = \"\"\n\t\t\t+ querySelectPart\n\t\t\t+ \" FROM\"\n\t\t\t+ \" \" + MySQLiteHelper.EVENT\n\t\t\t+ \" LEFT JOIN\"\n\t\t\t+ \" \" + MySQLiteHelper.TASK\n\t\t\t+ \" ON \"\n\t\t\t+ \" taskId = \" + MySQLiteHelper.EVENT_TASK\n\n\t\t\t+ \" UNION ALL \"\n\n\t\t\t+ querySelectPart\n\t\t\t+ \" FROM\"\n\t\t\t+ \" \" + MySQLiteHelper.TASK\n\t\t\t+ \" LEFT JOIN\"\n\t\t\t+ \" \" + MySQLiteHelper.EVENT\n\t\t\t+ \" ON \"\n\t\t\t+ \" taskId = \" + MySQLiteHelper.EVENT_TASK\n\n\t\t\t+ \" WHERE\"\n\t\t\t+ \" eventId IS NULL\"\n\n\t\t\t+ \" ORDER BY\"\n\t\t\t+ \" eventId\";\n\n\t\treturn db.rawQuery(query, new String[] {});\n\t}\n\n\t// ---------------------------------------------------------------------------------------------\n\t// backup/restore methods for Google servers\n\t// ---------------------------------------------------------------------------------------------\n\tpublic long getLastDbModification() {\n\t\tfinal File dbFile = context.getDatabasePath(MySQLiteHelper.DATABASE_NAME);\n\t\treturn dbFile.lastModified();\n\t}\n\n\t/**\n\t * Called internally by the data base methods where data is changed.\n\t */\n\tprivate void dataChanged() {\n\t\tbackupManager.dataChanged();\n\t}\n\n\t// ---------------------------------------------------------------------------------------------\n\t// backup/restore methods\n\t// ---------------------------------------------------------------------------------------------\n\tpublic void backupEventsToWriter(final Writer writer) throws IOException {\n\t\tfinal String eol = System.getProperty(\"line.separator\");\n\t\tfinal Cursor cur = getAllEventsAndTasks();\n\t\tcur.moveToFirst();\n\n\t\tfinal int eventIdCol = cur.getColumnIndex(\"eventId\");\n\t\tfinal int eventTypeCol = cur.getColumnIndex(MySQLiteHelper.EVENT_TYPE);\n\t\tfinal int eventTimeCol = cur.getColumnIndex(MySQLiteHelper.EVENT_TIME);\n\t\tfinal int eventZoneCol = cur.getColumnIndex(MySQLiteHelper.EVENT_ZONE_OFFSET);\n\t\tfinal int eventTaskCol = cur.getColumnIndex(MySQLiteHelper.EVENT_TASK);\n\t\tfinal int eventTextCol = cur.getColumnIndex(MySQLiteHelper.EVENT_TEXT);\n\n\t\tfinal int taskIdCol = cur.getColumnIndex(\"taskId\");\n\t\tfinal int taskNameCol = cur.getColumnIndex(MySQLiteHelper.TASK_NAME);\n\t\tfinal int taskActiveCol = cur.getColumnIndex(MySQLiteHelper.TASK_ACTIVE);\n\t\tfinal int taskOrderingCol = cur.getColumnIndex(MySQLiteHelper.TASK_ORDERING);\n\t\tfinal int taskDefaultCol = cur.getColumnIndex(MySQLiteHelper.TASK_DEFAULT);\n\n\t\twriter.write(\n\t\t\tMySQLiteHelper.EVENT_TYPE\n\t\t\t\t+ \";\" + MySQLiteHelper.EVENT_TIME\n\t\t\t\t+ \";\" + MySQLiteHelper.EVENT_TASK\n\t\t\t\t+ \";\" + MySQLiteHelper.EVENT_TEXT\n\t\t\t\t+ \";taskId\"\n\t\t\t\t+ \";\" + MySQLiteHelper.TASK_NAME\n\t\t\t\t+ \";\" + MySQLiteHelper.TASK_ACTIVE\n\t\t\t\t+ \";\" + MySQLiteHelper.TASK_ORDERING\n\t\t\t\t+ \";\" + MySQLiteHelper.TASK_DEFAULT\n\t\t\t\t+ eol);\n\n\t\tfinal StringBuilder buf = new StringBuilder();\n\t\twhile (!cur.isAfterLast()) {\n\t\t\tif (!cur.isNull(eventIdCol)) {\n\t\t\t\tbuf.append(TypeEnum.byValue(cur.getInt(eventTypeCol)).getReadableName());\n\t\t\t\tbuf.append(\";\");\n\n\t\t\t\tInstant instant = Instant.ofEpochSecond(cur.getLong(eventTimeCol));\n\t\t\t\tZoneOffset offset = ZoneOffset.ofTotalSeconds(cur.getInt(eventZoneCol) * 60);\n\t\t\t\tbuf.append(instant.atOffset(offset).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));\n\t\t\t\tbuf.append(\";\");\n\n\t\t\t\tbuf.append(cur.getInt(eventTaskCol));\n\t\t\t\tbuf.append(\";\");\n\n\t\t\t\tString eventComment = cur.getString(eventTextCol);\n\t\t\t\tbuf.append(eventComment == null ? \"\" : eventComment);\n\t\t\t\tbuf.append(\";\");\n\t\t\t} else {\n\t\t\t\t// this is a task that has no events\n\t\t\t\tbuf.append(\";;;;\");\n\t\t\t}\n\t\t\tif (!cur.isNull(taskIdCol)) {\n\t\t\t\tbuf.append(cur.getInt(taskIdCol));\n\t\t\t\tbuf.append(\";\");\n\t\t\t\tbuf.append(cur.getString(taskNameCol));\n\t\t\t\tbuf.append(\";\");\n\t\t\t\tbuf.append(cur.getInt(taskActiveCol));\n\t\t\t\tbuf.append(\";\");\n\t\t\t\tbuf.append(cur.getInt(taskOrderingCol));\n\t\t\t\tbuf.append(\";\");\n\t\t\t\tbuf.append(cur.getInt(taskDefaultCol));\n\t\t\t\tbuf.append(\";\");\n\t\t\t} else {\n\t\t\t\t// this is an event that has no task (TypeEnum.CLOCK_OUT)\n\t\t\t\tbuf.append(\";;;;;\");\n\t\t\t}\n\t\t\tbuf.append(eol);\n\t\t\twriter.write(buf.toString());\n\t\t\tbuf.setLength(0);\n\t\t\tcur.moveToNext();\n\t\t}\n\t\tcur.close();\n\t}\n\n\tprivate static final int INDEX_EVENT_TYPE = 0;\n\tprivate static final int INDEX_EVENT_TIME = 1;\n\tprivate static final int INDEX_EVENT_TASK = 2;\n\tprivate static final int INDEX_EVENT_TEXT = 3;\n\tprivate static final int INDEX_TASK_ID = 4;\n\tprivate static final int INDEX_TASK_NAME = 5;\n\tprivate static final int INDEX_TASK_ACTIVE = 6;\n\tprivate static final int INDEX_TASK_ORDERING = 7;\n\tprivate static final int INDEX_TASK_DEFAULT = 8;\n\n\t/** ONLY FOR PARSING! reads new and old backup timestamp format */\n\tprivate static final DateTimeFormatter BACKUP_DATETIME_PARSER = new DateTimeFormatterBuilder()\n\t\t.parseCaseInsensitive()\n\t\t.append(DateTimeFormatter.ISO_LOCAL_DATE)\n\t\t.optionalStart()\n\t\t.appendLiteral('T')\n\t\t.optionalEnd()\n\t\t.optionalStart()\n\t\t.appendLiteral(' ')\n\t\t.optionalEnd()\n\t\t.append(DateTimeFormatter.ISO_LOCAL_TIME)\n\t\t.optionalStart()\n\t\t.appendOffsetId()\n\t\t.optionalEnd()\n\t\t.toFormatter()\n\t\t.withResolverStyle(ResolverStyle.STRICT)\n\t\t.withChronology(IsoChronology.INSTANCE);\n\n\tpublic void restoreEventsFromReader(final BufferedReader reader) throws IOException {\n final String eol = System.getProperty(\"line.separator\");\n final TimerManager timerManager = Basics.getInstance().getTimerManager();\n\n deleteAll();\n\n\t\treader.readLine();\t// skip header\n\n String line;\n // cache values\n final String clockInReadableName = TypeEnum.CLOCK_IN.getReadableName();\n final String clockOutNowReadableName = TypeEnum.CLOCK_OUT_NOW.getReadableName();\n\n\t\twhile ((line = reader.readLine()) != null) {\n final String[] columns = RESTORE_PATTERN.split(line, -1);\n try {\n if (columns.length > 8 && columns[INDEX_TASK_ID].length() > 0) {\n final int taskId = Integer.parseInt(columns[INDEX_TASK_ID]);\n if (getTask(taskId) == null) {\n final Task task = new Task(\n taskId,\n columns[INDEX_TASK_NAME],\n Integer.parseInt(columns[INDEX_TASK_ACTIVE]),\n Integer.parseInt(columns[INDEX_TASK_ORDERING]),\n Integer.parseInt(columns[INDEX_TASK_DEFAULT])\n );\n final ContentValues args = taskToContentValues(task);\n args.put(MySQLiteHelper.TASK_ID, taskId);\n db.insert(TASK, null, args);\n }\n\t\t\t\t}\n\n if (columns.length > 2 && columns[INDEX_EVENT_TYPE].length() > 0) {\n\t\t\t\t\tOffsetDateTime dateTime = parseOffsetDateTime(timerManager, columns[INDEX_EVENT_TIME]);\n\t\t\t\t\tfinal TypeEnum typeEnum;\n if (clockInReadableName.equalsIgnoreCase(columns[INDEX_EVENT_TYPE])) {\n typeEnum = TypeEnum.CLOCK_IN;\n } else if (clockOutNowReadableName.equalsIgnoreCase(columns[INDEX_EVENT_TYPE])) {\n typeEnum = TypeEnum.CLOCK_OUT_NOW;\n } else {\n typeEnum = TypeEnum.CLOCK_OUT;\n }\n timerManager.createEvent(dateTime,\n Integer.parseInt(columns[INDEX_EVENT_TASK]),\n typeEnum,\n columns.length > INDEX_EVENT_TEXT ?\n columns[INDEX_EVENT_TEXT] : \"\", true);\n }\n } catch (NumberFormatException e) {\n // ignore rest of current row\n }\n }\n\t}\n\n\t@VisibleForTesting\n\tstatic OffsetDateTime parseOffsetDateTime(TimerManager timerManager, String timestamp) {\n\t\tTemporalAccessor eventTimestamp = BACKUP_DATETIME_PARSER.parse(timestamp);\n\t\tif (!eventTimestamp.isSupported(ChronoField.OFFSET_SECONDS)) {\n\t\t\tLocalDateTime localDateTime = LocalDateTime.from(eventTimestamp);\n\t\t\treturn localDateTime\n\t\t\t\t.atOffset(timerManager.getHomeTimeZoneOffset(localDateTime));\n\t\t} else {\n\t\t\treturn OffsetDateTime.from(eventTimestamp);\n\t\t}\n\t}\n\n\n\t// =======================================================\n\n\tprivate static final String[] TARGET_FIELDS = { TARGET_ID, TARGET_TIME, TARGET_TYPE, TARGET_VALUE, TARGET_TEXT };\n\n\tprivate Target cursorToTarget(Cursor cursor) {\n\t\tTarget target = new Target();\n\t\ttarget.setId(cursor.getInt(0));\n\t\ttarget.setDate(LocalDate.ofEpochDay(cursor.getLong(1)));\n\t\ttarget.setType(cursor.getInt(2));\n\t\ttarget.setValue(cursor.getInt(3));\n\t\ttarget.setComment(cursor.getString(4));\n\t\treturn target;\n\t}\n\n\tprivate ContentValues targetToContentValues(Target target) {\n\t\tContentValues ret = new ContentValues();\n\t\tret.put(TARGET_TIME, target.getDate().toEpochDay());\n\t\tret.put(TARGET_TYPE, target.getType());\n\t\tret.put(TARGET_VALUE, target.getValue());\n\t\tret.put(TARGET_TEXT, target.getComment());\n\t\treturn ret;\n\t}\n\n\n\t/**\n\t * Insert a new target.\n\t *\n\t * @param target the target to add\n\t * @return the newly created target as read from the database (complete with ID)\n\t */\n\tpublic synchronized Target insertTarget(Target target) {\n\t\topen();\n\t\tContentValues args = targetToContentValues(target);\n\t\tlong insertId = db.insert(TARGET, null, args);\n\n\t\t// now fetch the newly created row and return it as Target object\n\t\tList<Target> created = getTargetsWithConstraint(TARGET_ID + \"=\" + insertId);\n\t\tif (created.size() > 0) {\n\t\t\t//dataChanged(); // TODO\n\t\t\treturn created.get(0);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate List<Target> getTargetsWithConstraint(String constraint) {\n\t\topen();\n\t\tList<Target> ret = new ArrayList<>();\n\n\t\tCursor cursor = db.query(TARGET, TARGET_FIELDS, constraint, null, null, null, TARGET_TIME);\n\t\tcursor.moveToFirst();\n\n\t\twhile (!cursor.isAfterLast()) {\n\t\t\tTarget target = cursorToTarget(cursor);\n\t\t\tret.add(target);\n\t\t\tcursor.moveToNext();\n\t\t}\n\t\tcursor.close();\n\n\t\treturn ret;\n\t}\n\n\tpublic Target getDayTarget(LocalDate day) {\n\t\tList<Target> ret = getTargetsWithConstraint(TARGET_TIME + \"=\" + day.toEpochDay() +\n\t\t\t\t\" AND \" + TARGET_TYPE + \"<=\" + TargetEnum.DAY_IGNORE.getValue());\n\n\t\tif (ret.size() == 1) {\n\t\t\tLogger.debug(\"Got day target: {}\", ret.get(0));\n\n\t\t\treturn ret.get(0);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Update an target.\n\t *\n\t * @param target the target to update - the ID has to be set!\n\t * @return the target as newly read from the database\n\t */\n\tpublic synchronized Target updateTarget(Target target) {\n\t\topen();\n\t\tContentValues args = targetToContentValues(target);\n\t\tdb.update(TARGET, args, TARGET_ID + \"=\" + target.getId(), null);\n\n\t\t// now fetch the newly updated row and return it as Target object\n\t\tList<Target> updated = getTargetsWithConstraint(TARGET_ID + \"=\" + target.getId());\n\t\t//dataChanged(); // TODO\n\t\treturn updated.get(0);\n\t}\n\n\t/**\n\t * Remove an target.\n\t *\n\t * @param target the target to delete - the ID has to be set!\n\t * @return {@code true} if successful, {@code false} if not\n\t */\n\tpublic boolean deleteTarget(Target target) {\n\t\topen();\n\t\tfinal boolean result = db.delete(TARGET, TARGET_ID + \"=\" + target.getId(), null) > 0;\n\t\t//dataChanged(); // TODO\n\t\treturn result;\n\t}\n\n\tprivate synchronized boolean deleteAllTargets() {\n\t\topen();\n\t\tboolean result = db.delete(TARGET, null, null) > 0;\n\t\tdataChanged();\n\t\treturn result;\n\t}\n\n\tpublic synchronized Cursor getAllTargets() {\n\t\topen();\n\t\tfinal String query = \"SELECT\"\n\t\t\t\t+ \" \" + TARGET_TIME\n\t\t\t\t+ \", \" + TARGET_TYPE\n\t\t\t\t+ \", \" + TARGET_VALUE\n\t\t\t\t+ \", \" + TARGET_TEXT\n\t\t\t\t+ \" FROM \" + MySQLiteHelper.TARGET\n\t\t\t\t+ \" ORDER BY \" + TARGET_TIME;\n\n\t\treturn db.rawQuery(query, new String[] {});\n\t}\n\n\tpublic List<Target> getTargets(Instant from, Instant to) {\n\t\treturn getTargetsWithConstraint(TARGET_TIME + \" >= \"\n\t\t\t+ ChronoUnit.DAYS.between(Instant.EPOCH, from) +\n\t\t\t\" AND \" + TARGET_TIME + \" <= \"\n\t\t\t+ ChronoUnit.DAYS.between(Instant.EPOCH, to));\n\t}\n\n\n\t// ---------------------------------------------------------------------------------------------\n\t// backup/restore methods\n\t// ---------------------------------------------------------------------------------------------\n\tpublic void backupTargetsToWriter(final Writer writer) throws IOException {\n\t\tfinal String eol = System.getProperty(\"line.separator\");\n\t\tfinal Cursor cur = getAllTargets();\n\t\tcur.moveToFirst();\n\n\t\tfinal int targetTimeCol = cur.getColumnIndex(TARGET_TIME);\n\t\tfinal int targetTypeCol = cur.getColumnIndex(TARGET_TYPE);\n\t\tfinal int targetValueCol = cur.getColumnIndex(TARGET_VALUE);\n\t\tfinal int targetTextCol = cur.getColumnIndex(TARGET_TEXT);\n\n\t\twriter.write(\n\t\t\t\tTARGET_TIME\n\t\t\t\t\t\t+ \";\" + TARGET_TYPE\n\t\t\t\t\t\t+ \";\" + TARGET_VALUE\n\t\t\t\t\t\t+ \";\" + TARGET_TEXT\n\t\t\t\t\t\t+ eol);\n\n\t\tfinal StringBuilder buf = new StringBuilder();\n\t\twhile (!cur.isAfterLast()) {\n\t\t\tLocalDate date = LocalDate.ofEpochDay(cur.getLong(targetTimeCol));\n\t\t\tbuf.append(date.format(DateTimeFormatter.ISO_DATE));\n\t\t\tbuf.append(\";\");\n\n\t\t\tbuf.append(TargetEnum.byValue(cur.getInt(targetTypeCol)).toString());\n\t\t\tbuf.append(\";\");\n\n\t\t\tbuf.append(cur.getInt(targetValueCol));\n\t\t\tbuf.append(\";\");\n\n\t\t\tString targetComment = cur.getString(targetTextCol);\n\t\t\tbuf.append(targetComment == null ? \"\" : targetComment);\n\t\t\tbuf.append(eol);\n\n\t\t\twriter.write(buf.toString());\n\t\t\tbuf.setLength(0);\n\t\t\tcur.moveToNext();\n\t\t}\n\t\tcur.close();\n\t}\n\n\tprivate static final int INDEX_TARGET_TIME = 0;\n\tprivate static final int INDEX_TARGET_TYPE = 1;\n\tprivate static final int INDEX_TARGET_VALUE = 2;\n\tprivate static final int INDEX_TARGET_TEXT = 3;\n\n\tpublic void restoreTargetsFromReader(final BufferedReader reader) throws IOException {\n\t\tdeleteAllTargets();\n\n\t\treader.readLine();\t// skip header\n\t\tString line;\n\t\twhile ((line = reader.readLine()) != null) {\n\t\t\tfinal String[] columns = RESTORE_PATTERN.split(line, -1);\n\n\t\t\ttry {\n\t\t\t\tif (columns.length >= 4 && columns[INDEX_TARGET_TIME].length() > 0) {\n\n\t\t\t\t\tfinal Target target = new Target(0,\n\t\t\t\t\t\t\tTargetEnum.byName(columns[INDEX_TARGET_TYPE]).getValue(),\n\t\t\t\t\t\t\tInteger.parseInt(columns[INDEX_TARGET_VALUE]),\n\t\t\t\t\t\t\tLocalDate.parse(columns[INDEX_TARGET_TIME]),\n\t\t\t\t\t\t\tcolumns[INDEX_TARGET_TEXT]\n\t\t\t\t\t);\n\t\t\t\t\tfinal ContentValues args = targetToContentValues(target);\n\t\t\t\t\tdb.insert(TARGET, null, args);\n\t\t\t\t} else {\n\t\t\t\t\tLogger.debug(\"could not restore target line: {}\", line);\n\t\t\t\t}\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t// ignore rest of current row\n\t\t\t}\n\t\t}\n\t}\n\n\n\t// =======================================================\n\n\tprivate static final String[] CACHE_FIELDS = {CACHE_DATE, CACHE_WORKED, CACHE_TARGET};\n\n\tprivate CalcCacheEntry cursorToCache(Cursor cursor) {\n\t\tCalcCacheEntry cache = new CalcCacheEntry();\n\t\tcache.setDateFromId(cursor.getLong(0));\n\t\tcache.setWorked(cursor.getLong(1));\n\t\tcache.setTarget(cursor.getLong(2));\n\t\treturn cache;\n\t}\n\n\tprivate ContentValues cacheToContentValues(CalcCacheEntry cache) {\n\t\tContentValues ret = new ContentValues();\n\t\tret.put(CACHE_DATE, cache.getDateAsId());\n\t\tret.put(CACHE_WORKED, cache.getWorked());\n\t\tret.put(CACHE_TARGET, cache.getTarget());\n\t\treturn ret;\n\t}\n\n\n\t/**\n\t * Insert a new target.\n\t *\n\t * @param cache the cache entry to add\n\t * @return the newly created cache entry as read from the database (complete with ID)\n\t */\n\tpublic synchronized CalcCacheEntry insertCache(CalcCacheEntry cache) {\n\t\topen();\n\t\tContentValues args = cacheToContentValues(cache);\n\t\tlong insertId = db.insert(CACHE, null, args);\n\n\t\t// now fetch the newly created row and return it as Target object\n\t\treturn getCacheWithConstraint(CACHE_DATE + \"=\" + insertId);\n\t}\n\n\n\tprivate CalcCacheEntry getCacheWithConstraint(String constraint) {\n\t\topen();\n\n\t\tCalcCacheEntry ret = null;\n\n\t\tCursor cursor = db.query(CACHE, CACHE_FIELDS, constraint, null, null, null, CACHE_DATE + \" DESC\", \"1\");\n\t\tcursor.moveToFirst();\n\n\t\tif (!cursor.isAfterLast()) {\n\t\t\tret = cursorToCache(cursor);\n\t\t}\n\n\t\tcursor.close();\n\n\t\treturn ret;\n\t}\n\n\tpublic CalcCacheEntry getCacheAt(LocalDate date) {\n\t\treturn getCacheWithConstraint(CACHE_DATE + \"<=\" + date.toEpochDay());\n\t}\n\n\t/**\n\t * Remove cache entries.\n\t *\n\t * @param date the date from which to delete, deletes everything if {@code null}\n\t * @return {@code true} if successful, {@code false} if not\n\t */\n\tpublic boolean deleteCacheFrom(LocalDate date) {\n\t\topen();\n\n\t\tif (date != null) {\n\t\t\treturn db.delete(CACHE, CACHE_DATE + \">=\" + date.toEpochDay(), null) > 0;\n\t\t} else {\n\t\t\treturn db.delete(CACHE, null, null) > 0;\n\t\t}\n\t}\n\n\n\tpublic void executePendingMigrations() {\n\t\topen();\n\n\t\tSQLiteStatement s = db.compileStatement(\"SELECT count(*) FROM sqlite_master WHERE type=\\\"table\\\" AND name=\\\"\" + EVENT_V1 + \"\\\"\");\n\n\t\tif (s.simpleQueryForLong() > 0) {\n\t\t\tLogger.debug(\"Starting upgrade activity.\");\n\t\t\t//close();\n\n\t\t\tIntent i = new Intent(context, UpgradeActivity.class);\n\t\t\tif (!(context instanceof Activity)) {\n\t\t\t\ti.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);\n\t\t\t}\n\t\t\tcontext.startActivity(i);\n\t\t}\n\t}\n\n\t/*\n\tMigrate events to v2\n\t */\n\tpublic void migrateEventsToV2(ZoneId zoneId, MigrationCallback callback) {\n\t\tnew MigrateEventsV2(zoneId, callback).execute();\n\t}\n\n private class MigrateEventsV2 extends AsyncTask<Void, Integer, Void> {\n\n\t\tprivate final DateTimeFormatter DATETIME_FORMAT = DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss.SSSS\");\n\t\tprivate final int TYPE_FLEX = 2;\n\n\t\tprivate final ZoneId zoneId;\n\t\tprivate final WeakReference<MigrationCallback> callback;\n\n\t\tprivate MigrateEventsV2(ZoneId zoneId, MigrationCallback callback) {\n\t\t\tthis.zoneId = zoneId;\n\t\t\tthis.callback = new WeakReference<>(callback);\n\t\t}\n\n\t\t@Override\n\t\tprotected Void doInBackground(Void... voids) {\n\t\t\topen();\n\n\t\t\tlong numEntries = DatabaseUtils.queryNumEntries(db, EVENT_V1);\n\t\t\tlong count = 0;\n\n\t\t\tLogger.debug(\"Migrating {} rows.\", numEntries);\n\n\t\t\tdb.beginTransaction();\n\t\t\ttry {\n\t\t\t\tCursor cursor = db.query(EVENT_V1, null, null, null,\n\t\t\t\t\t\tnull, null, EVENT_TIME + \",\" + EVENT_ID, null);\n\t\t\t\tcursor.moveToFirst();\n\n\t\t\t\twhile (!cursor.isAfterLast()) {\n\t\t\t\t\tpublishProgress((int)((count * 100) / numEntries));\n\n\t\t\t\t\tint type = cursor.getInt(2);\n\t\t\t\t\tLocalDateTime eventDateTime =\n\t\t\t\t\t\t\tLocalDateTime.parse(cursor.getString(3), DATETIME_FORMAT);\n\n\t\t\t\t\tString text = cursor.getString(5);\n\n\t\t\t\t\tInteger task = null;\n\n\t\t\t\t\tif (type == TYPE_FLEX) {\n\t\t\t\t\t\t// migrate flex event to target table, time -> target work time for the day\n\t\t\t\t\t\tLocalTime localTime = eventDateTime.toLocalTime();\n\t\t\t\t\t\tlong targetTime = localTime.getHour() * 60 + localTime.getMinute();\n\n\t\t\t\t\t\tContentValues cv = new ContentValues();\n\t\t\t\t\t\tcv.put(TARGET_TIME, eventDateTime.toLocalDate().toEpochDay());\n\t\t\t\t\t\tcv.put(TARGET_TYPE,TargetEnum.DAY_SET.getValue());\n\t\t\t\t\t\tcv.put(TARGET_VALUE, targetTime);\n\t\t\t\t\t\tcv.put(TARGET_TEXT, text);\n\n\t\t\t\t\t\tdb.insert(TARGET, null, cv);\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (!cursor.isNull(4)) {\n\t\t\t\t\t\t\ttask = cursor.getInt(4);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// migrate local datetime assuming home time zone\n\t\t\t\t\t\tOffsetDateTime newTime = eventDateTime.atZone(zoneId).toOffsetDateTime();\n\n\t\t\t\t\t\t// entry in new event table\n\t\t\t\t\t\tContentValues cv = new ContentValues();\n\t\t\t\t\t\tcv.put(EVENT_TIME, newTime.toInstant().getEpochSecond());\n\t\t\t\t\t\tcv.put(EVENT_ZONE_OFFSET, newTime.getOffset().getTotalSeconds() / 60);\n\t\t\t\t\t\tcv.put(EVENT_TYPE, type);\n\t\t\t\t\t\tcv.put(EVENT_TASK, task);\n\t\t\t\t\t\tcv.put(EVENT_TEXT, text);\n\n\t\t\t\t\t\tdb.insert(EVENT, null, cv);\n\t\t\t\t\t}\n\n\t\t\t\t\tcount++;\n\t\t\t\t\tcursor.moveToNext();\n\t\t\t\t}\n\t\t\t\tcursor.close();\n\n\t\t\t\t// for now only rename the old event table\n\t\t\t\tdb.execSQL(\"ALTER TABLE \" + EVENT_V1 + \" RENAME TO \" + EVENT_V1 + \"_mig\");\n\n\t\t\t\tdb.setTransactionSuccessful();\n\t\t\t} finally {\n\t\t\t\tdb.endTransaction();\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tprotected void onProgressUpdate(Integer... values) {\n\t\t\tMigrationCallback cb = callback.get();\n\n\t\t\tif (cb != null) {\n\t\t\t\tcb.onProgressUpdate(values[0]);\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tprotected void onPostExecute(Void v) {\n\t\t\tLogger.debug(\"Migration done.\");\n\n\t\t\tMigrationCallback cb = callback.get();\n\t\t\tif (cb != null) {\n\t\t\t\tcb.migrationDone();\n\t\t\t}\n\t\t}\n\t}\n}",
"public class Event extends Base implements Comparable<Event> {\n\tprivate Integer id = null;\n\tprivate Integer task = null;\n\tprivate Integer type = null;\n\tprivate OffsetDateTime time = null;\n\tprivate String text = null;\n\n\tpublic Event() {\n\t\t// do nothing\n\t}\n\n\tpublic Event(Integer id, Integer task, Integer type, OffsetDateTime time, String text) {\n\t\tthis.id = id;\n\t\tthis.task = task;\n\t\tthis.type = type;\n\t\tthis.time = time;\n\t\tthis.text = text;\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic Integer getTask() {\n\t\treturn task;\n\t}\n\n\tpublic Integer getType() {\n\t\treturn type;\n\t}\n\n\tpublic TypeEnum getTypeEnum() {\n\t\treturn TypeEnum.byValue(type);\n\t}\n\n\t// used for report generation\n\tpublic OffsetDateTime getTime() {\n\t\treturn time;\n\t}\n\n\tpublic OffsetDateTime getDateTime() {\n\t\treturn time;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic void setTask(Integer task) {\n\t\tthis.task = task;\n\t}\n\n\tpublic void setType(Integer type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic void setDateTime(OffsetDateTime datetime) {\n\t\tthis.time = datetime;\n\t}\n\n\tpublic String getText() {\n\t\treturn text;\n\t}\n\n\tpublic void setText(String text) {\n\t\tthis.text = text;\n\t}\n\n\t@Override\n\tpublic int compareTo(Event another) {\n\t\treturn compare(getDateTime(), another.getDateTime(), compare(getId(), another.getId(), 0));\n\t}\n\n\t/**\n\t * This is used e.g. by an ArrayAdapter in a ListView and it is also useful for debugging.\n\t * \n\t * @see org.zephyrsoft.trackworktime.model.Base#toString()\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn getDateTime() + \" / \" + TypeEnum.byValue(getType()).name() + \" / \" + getTask() + \" - \" + getText();\n\t}\n\n}",
"public class Target extends Base implements Comparable<Target> {\n\tprivate Integer id = null;\n\tprivate Integer type = null;\n\tprivate Integer value = null;\n\tprivate LocalDate date = null;\n\tprivate String comment = null;\n\n\tpublic Target() {\n\t\t// do nothing\n\t}\n\n\tpublic Target(Integer id, Integer type, Integer value, LocalDate date, String comment) {\n\t\tthis.id = id;\n\t\tthis.type = type;\n\t\tthis.value = value;\n\t\tthis.date = date;\n\t\tthis.comment = comment;\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic Integer getType() {\n\t\treturn type;\n\t}\n\n\tpublic Integer getValue() {\n\t\treturn value;\n\t}\n\n\tpublic LocalDate getDate() {\n\t\treturn date;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic void setType(Integer type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic void setValue(Integer value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic void setDate(LocalDate date) {\n\t\tthis.date = date;\n\t}\n\n\tpublic String getComment() {\n\t\treturn comment;\n\t}\n\n\tpublic void setComment(String comment) {\n\t\tthis.comment = comment;\n\t}\n\n\t@Override\n\tpublic int compareTo(Target another) {\n\t\treturn compare(getDate(), another.getDate(), compare(getId(), another.getId(), 0));\n\t}\n\n\t/**\n\t * This is used e.g. by an ArrayAdapter in a ListView and it is also useful for debugging.\n\t *\n\t * @see Base#toString()\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn date.format(ISO_LOCAL_DATE) + \" / \" + TargetEnum.byValue(getType()).name() + \" / \" + getValue() + \" / \" + getComment();\n\t}\n\n}",
"public class TargetWrapper {\n private final Target wrapped;\n\n public TargetWrapper(Target wrapped) {\n this.wrapped = wrapped;\n }\n\n public LocalDate getDate() {\n return wrapped.getDate();\n }\n\n public static String getType(Target target) {\n TargetEnum type = TargetEnum.byValue(target.getType());\n if (type == TargetEnum.DAY_SET\n && target.getValue() != null\n && target.getValue() > 0) {\n return \"change target time\";\n } else if (type == TargetEnum.DAY_SET\n && (target.getValue() == null\n || target.getValue() == 0)) {\n return \"holiday / vacation / non-working day\";\n } else if (type == TargetEnum.DAY_GRANT) {\n return \"working time = target time\";\n }\n return \"unknown type\";\n }\n\n public String getType() {\n return getType(wrapped);\n }\n\n public Integer getValue() {\n return wrapped.getValue();\n }\n\n public String getComment() {\n return wrapped.getComment();\n }\n}",
"public class Task extends Base implements Comparable<Task> {\n\tprivate Integer id = null;\n\tprivate String name = null;\n\tprivate Integer active = null;\n\tprivate Integer ordering = null;\n\tprivate Integer isDefault = null;\n\n\tpublic Task() {\n\t\t// do nothing\n\t}\n\n\tpublic Task(Integer id, String name, Integer active, Integer ordering, Integer isDefault) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.active = active;\n\t\tthis.ordering = ordering;\n\t\tthis.isDefault = isDefault;\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic Integer getActive() {\n\t\treturn active;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic void setActive(Integer active) {\n\t\tthis.active = active;\n\t}\n\n\tpublic Integer getOrdering() {\n\t\treturn ordering;\n\t}\n\n\tpublic void setOrdering(Integer ordering) {\n\t\tthis.ordering = ordering;\n\t}\n\n\tpublic Integer getIsDefault() {\n\t\treturn isDefault;\n\t}\n\n\tpublic void setIsDefault(Integer isDefault) {\n\t\tthis.isDefault = isDefault;\n\t}\n\n\t@Override\n\tpublic int compareTo(Task another) {\n\t\treturn compare(getName(), another.getName(), compare(getId(), another.getId(), 0));\n\t}\n\n\t/**\n\t * This is used e.g. by an ArrayAdapter in a ListView and it is also useful for debugging.\n\t * \n\t * @see org.zephyrsoft.trackworktime.model.Base#toString()\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn getName() + (isDefault != null && isDefault.equals(1) ? \" *\" : \"\");\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\tTask other = (Task) obj;\n\n\t\tif (id == null) {\n\t\t\treturn other.id == null;\n\t\t} else {\n\t\t\treturn id.equals(other.id);\n\t\t}\n\t}\n}",
"public class TimeSum {\n\n\t/** can also be counted negative */\n\tprivate int hours = 0;\n\t/** always counted positive */\n\tprivate int minutes = 0;\n\n\tpublic void set(int minutes) {\n\t\tthis.minutes = minutes;\n\t\tbalance();\n\t}\n\n\t/**\n\t * Set time to specific values\n\t * @param hours positive or negative\n\t * @param minutes only positive. Does not spillover to hours.\n\t */\n\tpublic void set(int hours, int minutes) {\n\t\tif(minutes < 0 || minutes > 59) {\n\t\t\tthrow new IllegalArgumentException(\"Minutes out of range: \" + minutes);\n\t\t}\n\t\tif(hours < 0 && minutes > 0) {\n\t\t\tminutes = 60 - minutes;\n\t\t\thours -= 1;\n\t\t}\n\t\tthis.hours = hours;\n\t\tthis.minutes = minutes;\n\t}\n\n\t/**\n\t * Add some hours and minutes. The minutes value doesn't have to be < 60, but both values have to be >= 0.\n\t */\n\tpublic void add(int hoursToAdd, int minutesToAdd) {\n\t\tif (hoursToAdd < 0 || minutesToAdd < 0) {\n\t\t\tthrow new IllegalArgumentException(\"both values have to be >= 0\");\n\t\t}\n\t\thours += hoursToAdd;\n\t\tminutes += minutesToAdd;\n\t\tbalance();\n\t}\n\n\t/**\n\t * Subtracts some hours and minutes. The minutes value doesn't have to be < 60, but both values have to be >= 0.\n\t */\n\tpublic void substract(int hoursToSubstract, int minutesToSubstract) {\n\t\tif (hoursToSubstract < 0 || minutesToSubstract < 0) {\n\t\t\tthrow new IllegalArgumentException(\"both values have to be >= 0\");\n\t\t}\n\t\thours -= hoursToSubstract;\n\t\tminutes -= minutesToSubstract;\n\t\tbalance();\n\t}\n\n\t/**\n\t * Add or substract the value of the given time sum.\n\t */\n\tpublic void addOrSubstract(TimeSum timeSum) {\n\t\tif (timeSum == null) {\n\t\t\treturn;\n\t\t}\n\t\thours += timeSum.hours;\n\t\tminutes += timeSum.minutes;\n\t\tbalance();\n\t}\n\n\tprivate void balance() {\n\t\twhile (minutes >= 60) {\n\t\t\thours += 1;\n\t\t\tminutes -= 60;\n\t\t}\n\t\twhile (minutes < 0) {\n\t\t\thours -= 1;\n\t\t\tminutes += 60;\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tint hoursForDisplay = hours;\n\t\tint minutesForDisplay = minutes;\n\t\tboolean negative = false;\n\t\tif (hoursForDisplay < 0) {\n\t\t\tnegative = true;\n\t\t\tif (minutesForDisplay != 0) {\n\t\t\t\thoursForDisplay += 1;\n\t\t\t\tminutesForDisplay = 60 - minutesForDisplay;\n\t\t\t}\n\t\t}\n\t\treturn (negative && hoursForDisplay == 0 ? \"-\" : \"\") + hoursForDisplay + \":\"\n\t\t\t+ DateTimeUtil.padToTwoDigits(minutesForDisplay);\n\t}\n\n\t/**\n\t * Get the time sum as accumulated value in minutes.\n\t */\n\tpublic int getAsMinutes() {\n\t\treturn hours * 60 + minutes;\n\t}\n\n\tpublic void reset() {\n\t\thours = 0;\n\t\tminutes = 0;\n\t}\n\n}",
"public enum TypeEnum {\n\n\t/**\n\t * clock-in type of event\n\t */\n\tCLOCK_IN(Values.CLOCK_IN_VALUE, \"in\"),\n\t/**\n\t * clock-out type of event\n\t */\n\tCLOCK_OUT(Values.CLOCK_OUT_VALUE, \"out\"),\n\t/**\n\t * clock-out now type of event used to display correct amount of worked time on current day when currently clocked\n\t * in - THIS TYPE NEVER COMES FROM THE DATABASE\n\t */\n\tCLOCK_OUT_NOW(Values.CLOCK_OUT_NOW_VALUE, \"out (current time)\");\n\n\tprivate final Integer value;\n\tprivate final String readableName;\n\n\tTypeEnum(Integer value, String readableName) {\n\t\tthis.value = value;\n\t\tthis.readableName = readableName;\n\t}\n\n\t/**\n\t * Gets the value of this enum for storing it in database.\n\t */\n\tpublic Integer getValue() {\n\t\treturn value;\n\t}\n\n\tpublic String getReadableName() {\n\t\treturn readableName;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.valueOf(getValue());\n\t}\n\n\t/**\n\t * Gets the \"default\" types, meaning those that get saved. At the moment, only CLOCK_IN and CLOCK_OUT make sense\n\t * here.\n\t */\n\tpublic static List<TypeEnum> getDefaultTypes() {\n\t\treturn Arrays.asList(CLOCK_IN, CLOCK_OUT);\n\t}\n\n\t/**\n\t * Get the enum for a specific value.\n\t *\n\t * @param value\n\t * the value\n\t * @return the corresponding enum\n\t */\n\tpublic static TypeEnum byValue(Integer value) {\n\t\tif (value == null) {\n\t\t\treturn null;\n\t\t} else if (value == Values.CLOCK_IN_VALUE) {\n\t\t\treturn CLOCK_IN;\n\t\t} else if (value == Values.CLOCK_OUT_VALUE) {\n\t\t\treturn CLOCK_OUT;\n\t\t} else if (value == Values.CLOCK_OUT_NOW_VALUE) {\n\t\t\treturn CLOCK_OUT_NOW;\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"unknown value\");\n\t\t}\n\t}\n\n\tprivate static class Values {\n\t\tprivate static final int CLOCK_IN_VALUE = 1;\n\t\tprivate static final int CLOCK_OUT_VALUE = 0;\n\t\tprivate static final int CLOCK_OUT_NOW_VALUE = -1;\n\t}\n}",
"public class DateTimeUtil {\n\tprivate static final DateTimeFormatter LOCALIZED_DATE = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);\n\tprivate static final DateTimeFormatter LOCALIZED_DATE_SHORT = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);\n\tprivate static final DateTimeFormatter LOCALIZED_TIME = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);\n\tprivate static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern(\"yyyy-MM-dd\");\n\tprivate static final DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern(\"yyyy-MM-dd-HH-mm-ss\");\n\tprivate static final DateTimeFormatter LOCALIZED_DAY_AND_DATE = new DateTimeFormatterBuilder()\n\t\t\t.appendPattern(\"eeee\")\n\t\t\t.appendLiteral(\", \")\n\t\t\t.appendLocalized(FormatStyle.SHORT, null)\n\t\t\t.toFormatter();\n\n\t/** E.g. Fri, 12.9 */\n\tprivate static final DateTimeFormatter LOCALIZED_DAY_AND_SHORT_DATE =\n\t\t\tcreateLocalizedDayAndShortDateFormat();\n\n\tprivate static DateTimeFormatter createLocalizedDayAndShortDateFormat() {\n\t\tString shortDate = DateTimeFormatterBuilder.getLocalizedDateTimePattern(\n\t\t\t\tFormatStyle.SHORT,\n\t\t\t\tnull,\n\t\t\t\tIsoChronology.INSTANCE,\n\t\t\t\tLocale.getDefault())\n\t\t\t\t// remove year and some year-separators (at least in german dates, the dot after the month has to exist)\n\t\t\t\t.replaceAll(\"[ /-]? *[yY]+ *[ 年/.-]?\", \"\");\n\t\tString pattern = \"eee, \" + shortDate;\n\t\treturn DateTimeFormatter.ofPattern(pattern);\n\t}\n\n\t/**\n\t * Determines if the given {@link LocalDateTime} is in the future.\n\t */\n\tpublic static boolean isInFuture(LocalDateTime dateTime) {\n\t\treturn dateTime.isAfter(LocalDateTime.now());\n\t}\n\n\tpublic static boolean isInFuture(OffsetDateTime dateTime) {\n\t\treturn dateTime.isAfter(OffsetDateTime.now());\n\t}\n\n\t/**\n\t * Determines if the given {@link LocalDateTime} is in the past.\n\t */\n\tpublic static boolean isInPast(LocalDateTime dateTime) {\n\t\treturn dateTime.isBefore(LocalDateTime.now());\n\t}\n\n\tpublic static boolean isInPast(OffsetDateTime dateTime) {\n\t\treturn dateTime.isBefore(OffsetDateTime.now());\n\t}\n\n\tpublic static LocalDate getWeekStart(LocalDate date) {\n\t\treturn date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));\n\t}\n\n\tpublic static LocalDateTime getWeekStart(LocalDateTime dateTime) {\n\t\treturn dateTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));\n\t}\n\n\tpublic static ZonedDateTime getWeekStart(ZonedDateTime dateTime) {\n\t\treturn dateTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));\n\t}\n\n\t/**\n\t * Formats a {@link OffsetDateTime} to a String.\n\t *\n\t * @param dateTime the input (may not be null)\n\t * @return the String which corresponds to the given input\n\t */\n\tpublic static String formatLocalizedDateTime(OffsetDateTime dateTime) {\n\t\treturn formatLocalizedDate(dateTime.toLocalDate()) + \" / \" + formatLocalizedTime(dateTime);\n\t}\n\n\t/**\n\t * Formats a {@link LocalDate} to a String.\n\t *\n\t * @param date the input (may not be null)\n\t * @return the String which corresponds to the given input\n\t */\n\tpublic static String formatLocalizedDate(LocalDate date) {\n\t\treturn date.format(LOCALIZED_DATE);\n\t}\n\n\tpublic static String formatLocalizedDateShort(TemporalAccessor temporal) {\n\t\treturn LOCALIZED_DATE_SHORT.format(temporal);\n\t}\n\n\t/**\n\t * Formats a {@link TemporalAccessor} to a String, containing only hours and minutes.\n\t *\n\t * @param temporal the input (may not be null)\n\t * @return the String which corresponds to the given input\n\t */\n\tpublic static String formatLocalizedTime(TemporalAccessor temporal) {\n\t\treturn LOCALIZED_TIME.format(temporal);\n\t}\n\n\t/**\n\t * Formats a {@link TemporalAccessor} to a String.\n\t *\n\t * @param date the input (may not be null)\n\t * @return the String which corresponds to the given input. E.g. \"Friday, 22.2.2222\".\n\t */\n\tpublic static String formatLocalizedDayAndDate(TemporalAccessor date) {\n\t\tString dateString = LOCALIZED_DAY_AND_DATE.format(date);\n\t\treturn StringUtils.capitalize(dateString);\n\t}\n\n\tpublic static String formatLocalizedDayAndShortDate(TemporalAccessor date) {\n\t\tString dateString = LOCALIZED_DAY_AND_SHORT_DATE.format(date)\n\t\t\t\t// remove possible abbreviation point (\"Mo., 27.09.\" (german) or \"Lun., 27/09\" (french) looks odd):\n\t\t\t\t.replaceAll(\"^(\\\\p{Alpha}+)\\\\., \", \"$1, \");\n\t\treturn StringUtils.capitalize(dateString);\n\t}\n\n\t/**\n\t * Formats a {@link ZonedDateTime} to a String.\n\t *\n\t * @param dateTime the input (may not be null)\n\t * @return the String which corresponds to the given input\n\t */\n\tpublic static String dateToULString(ZonedDateTime dateTime) {\n\t\treturn dateTime.format(DATE);\n\t}\n\n\t/**\n\t * Parse a time string to a LocalTime\n\t *\n\t * @param timeString a String which contains the hour and minute only, e.g. \"14:30\"\n\t * @return a LocalTime which represents the given time\n\t */\n\tpublic static LocalTime parseTime(String timeString) {\n\t\treturn LocalTime.parse(refineTime(timeString));\n\t}\n\n\t/**\n\t * Prepare the a user-entered time string to suffice for {@link #parseTime}.\n\t */\n\tpublic static String refineTime(String timeString) {\n\t\tString ret = refineHourMinute(timeString);\n\t\t// append seconds\n\t\tret += \":00\";\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Prepare the a user-entered time string to represent \"hours:minutes\".\n\t * TODO DateTimeFormatterBuilder\n\t */\n\tpublic static String refineHourMinute(String timeString) {\n\t\tif (timeString == null || timeString.isEmpty()) {\n\t\t\t// empty means midnight\n\t\t\treturn \"00:00\";\n\t\t}\n\t\tString ret = timeString.replace('.', ':');\n\t\t// cut off seconds if present\n\t\tret = ret.replaceAll(\"^(\\\\d\\\\d?):(\\\\d\\\\d?):.*$\", \"$1:$2\");\n\t\t// fix only one digit as hour\n\t\tret = ret.replaceAll(\"^(\\\\d):\", \"0$1:\");\n\t\t// fix only one digit as minute\n\t\tret = ret.replaceAll(\":(\\\\d)$\", \":0$1\");\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Return the given number left-padded with 0 if applicable.\n\t */\n\tpublic static String padToTwoDigits(int number) {\n\t\tif (number < 0) {\n\t\t\tthrow new IllegalArgumentException(\"number has to be >= 0\");\n\t\t} else if (number < 10) {\n\t\t\treturn \"0\" + number;\n\t\t} else {\n\t\t\treturn String.valueOf(number);\n\t\t}\n\t}\n\n\tpublic static long dateToEpoch(ZonedDateTime accessor) {\n\t\treturn Instant.from(accessor).toEpochMilli();\n\t}\n\n\tpublic static boolean isDurationValid(String value) {\n\t\tString[] pieces = value.split(\"[:.]\");\n\t\tif (pieces.length == 2) {\n\t\t\ttry {\n\t\t\t\tInteger.parseInt(pieces[0]);\n\t\t\t\tInteger.parseInt(pieces[1]);\n\t\t\t\treturn true;\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t// ignore and return false\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic static String formatDuration(Integer duration) {\n\t\tif (duration != null) {\n\t\t\treturn String.format(Locale.US, \"%d:%02d\", duration / 60, duration % 60);\n\t\t} else {\n\t\t\treturn \"0:00\";\n\t\t}\n\t}\n\n\tpublic static String timestampNow() {\n\t\treturn LocalDateTime.now().format(TIMESTAMP);\n\t}\n}"
] | import androidx.arch.core.util.Function;
import org.pmw.tinylog.Logger;
import org.supercsv.cellprocessor.CellProcessorAdaptor;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
import org.supercsv.util.CsvContext;
import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.zephyrsoft.trackworktime.database.DAO;
import org.zephyrsoft.trackworktime.model.Event;
import org.zephyrsoft.trackworktime.model.Target;
import org.zephyrsoft.trackworktime.model.TargetWrapper;
import org.zephyrsoft.trackworktime.model.Task;
import org.zephyrsoft.trackworktime.model.TimeSum;
import org.zephyrsoft.trackworktime.model.TypeEnum;
import org.zephyrsoft.trackworktime.util.DateTimeUtil;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; | /*
* This file is part of TrackWorkTime (TWT).
*
* TWT is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License 3.0 as published by
* the Free Software Foundation.
*
* TWT 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 3.0 for more details.
*
* You should have received a copy of the GNU General Public License 3.0
* along with TWT. If not, see <http://www.gnu.org/licenses/>.
*/
package org.zephyrsoft.trackworktime.report;
/**
* Creates CSV reports from events.
*/
public class CsvGenerator {
private final DAO dao;
public CsvGenerator(DAO dao) {
this.dao = dao;
}
/** time, type, task, text */
private final CellProcessor[] eventProcessors = new CellProcessor[] {
new CellProcessorAdaptor() {
@Override
public Object execute(Object arg0, CsvContext arg1) {
if (arg0 == null) {
throw new IllegalStateException("event time may not be null");
} else {
return ((OffsetDateTime) arg0).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
}
},
new CellProcessorAdaptor() {
@Override
public Object execute(Object arg0, CsvContext arg1) {
if (arg0 == null) {
throw new IllegalStateException("event type may not be null");
} else {
return TypeEnum.byValue((Integer) arg0).getReadableName();
}
}
},
new CellProcessorAdaptor() {
@Override
public Object execute(Object arg0, CsvContext arg1) {
if (arg0 == null) {
return null;
} else {
Task task = dao.getTask((Integer) arg0);
return task == null ? "" : task.getName();
}
}
},
new Optional()
};
/** date, type, value, comment */
private final CellProcessor[] targetProcessors = new CellProcessor[] {
new CellProcessorAdaptor() {
@Override
public Object execute(Object arg0, CsvContext arg1) {
if (arg0 == null) {
throw new IllegalStateException("target date may not be null");
} else {
return ((LocalDate) arg0).format(DateTimeFormatter.ISO_LOCAL_DATE);
}
}
},
new CellProcessorAdaptor() {
@Override
public Object execute(Object arg0, CsvContext arg1) {
if (arg0 == null) {
throw new IllegalStateException("target type may not be null");
} else {
return arg0;
}
}
},
new CellProcessorAdaptor() {
@Override
public Object execute(Object arg0, CsvContext arg1) {
if (arg0 == null || (arg0 instanceof Integer && ((Integer) arg0).intValue() == 0)) {
return null;
} else {
return DateTimeUtil.formatDuration((Integer) arg0);
}
}
},
new Optional()
};
/** task, spent */
private final CellProcessor[] sumsProcessors = new CellProcessor[] {
new NotNull(),
new CellProcessorAdaptor() {
@Override
public Object execute(Object arg0, CsvContext arg1) {
if (arg0 == null) {
throw new IllegalStateException("time sum may not be null");
} else {
return arg0.toString();
}
}
}
};
/** (month|week), task, spent */
private final CellProcessor[] sumsPerRangeProcessors = new CellProcessor[] {
new NotNull(),
new NotNull(),
new CellProcessorAdaptor() {
@Override
public Object execute(Object arg0, CsvContext arg1) {
if (arg0 == null) {
throw new IllegalStateException("time sum may not be null");
} else {
return arg0.toString();
}
}
}
};
/**
* Warning: could modify the provided event list!
*/
public String createTargetCsv(List<Target> targets) {
ICsvBeanWriter beanWriter = null;
StringWriter resultWriter = new StringWriter();
try {
beanWriter = new CsvBeanWriter(resultWriter, CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE);
// the header elements are used to map the bean values to each column (names must match!)
final String[] header = new String[] { "date", "type", "value", "comment" };
beanWriter.writeHeader(header);
for (Target target : targets) {
beanWriter.write(new TargetWrapper(target), header, targetProcessors);
}
} catch (IOException e) {
Logger.error(e, "error while writing");
} finally {
if (beanWriter != null) {
try {
beanWriter.close();
} catch (IOException e) {
// do nothing
}
}
}
return resultWriter.toString();
}
/**
* Warning: could modify the provided event list!
*/ | public String createEventCsv(List<Event> events) { | 1 |
albfernandez/javadbf | src/test/java/com/linuxense/javadbf/bug94_error_f5/Bug94ErrorF5Test.java | [
"public class DBFException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1906727217048909819L;\n\n\n\t/**\n\t * Constructs an DBFException with the specified detail message.\n\t * @param message The detail message (which is saved for later retrieval by the Throwable.getMessage() method)\n\t */\n\tpublic DBFException(String message) {\n\t\tsuper(message);\n\t}\n\t/**\n\t * Constructs an DBFException with the specified detail message and cause.\n\t * @param message The detail message (which is saved for later retrieval by the Throwable.getMessage() method)\n\t * @param cause The cause (which is saved for later retrieval by the Throwable.getCause() method).\n\t */\n\tpublic DBFException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\t/**\n\t * Constructs an DBFException with the specified cause.\n\t * @param cause The cause (which is saved for later retrieval by the Throwable.getCause() method).\n\t */\n\tpublic DBFException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n\n\n}",
"public final class DBFUtils {\n\n\tprivate static final CharsetEncoder ASCII_ENCODER = Charset.forName(\"US-ASCII\").newEncoder();\n\n\tprivate DBFUtils() {\n\t\tthrow new AssertionError(\"No instances of this class are allowed\");\n\t}\n\n\t/**\n\t * Reads a number from a stream,\n\t * @param dataInput the stream data\n\t * @param length the legth of the number\n\t * @return The number as a Number (BigDecimal)\n\t * @throws IOException if an IO error happens\n\t * @throws EOFException if reached end of file before length bytes\n\t */\n\tpublic static Number readNumericStoredAsText(DataInputStream dataInput, int length) throws IOException {\n\t\tbyte[] t_float = new byte[length];\n\t\tdataInput.readFully(t_float);\n\t\t\n\t\tt_float = DBFUtils.removeSpaces(t_float);\n\t\tt_float = DBFUtils.removeNullBytes(t_float);\n\t\tif (t_float.length > 0 && DBFUtils.isPureAscii(t_float) && !DBFUtils.contains(t_float, (byte) '?') && !DBFUtils.contains(t_float, (byte) '*')) {\n\t\t\tString aux = new String(t_float, DBFStandardCharsets.US_ASCII).replace(',', '.');\n\t\t\tif (\".\".equals(aux)) {\n\t\t\t\treturn BigDecimal.ZERO;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn new BigDecimal(aux);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\tthrow new DBFException(\"Failed to parse Float value [\" + aux + \"] : \" + e.getMessage(), e);\n\t\t\t}\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t}\n\n\t/**\n\t * Read a littleEndian integer(32b its) from DataInput\n\t * @param in DataInput to read from\n\t * @return int value of next 32 bits as littleEndian\n\t * @throws IOException if an IO error happens\n\t * @throws EOFException if reached end of file before 4 bytes are readed\n\t */\n\tpublic static int readLittleEndianInt(DataInput in) throws IOException {\n\t\tint bigEndian = 0;\n\t\tfor (int shiftBy = 0; shiftBy < 32; shiftBy += 8) {\n\t\t\tbigEndian |= (in.readUnsignedByte() & 0xff) << shiftBy;\n\t\t}\n\t\treturn bigEndian;\n\t}\n\n\t/**\n\t * Read a littleEndian short(16 bits) from DataInput\n\t * @param in DataInput to read from\n\t * @return short value of next 16 bits as littleEndian\n\t * @throws IOException if an IO error happens\n\t */\n\tpublic static short readLittleEndianShort(DataInput in) throws IOException {\n\t\tint low = in.readUnsignedByte() & 0xff;\n\t\tint high = in.readUnsignedByte();\n\t\treturn (short) (high << 8 | low);\n\t}\n\n\t/**\n\t * Remove all spaces (32) found in the data.\n\t * @param array the data\n\t * @return the data cleared of whitespaces\n\t */\n\tpublic static byte[] removeSpaces(byte[] array) {\n\t\tByteArrayOutputStream baos = new ByteArrayOutputStream(array.length);\n\t\tfor (byte b : array) {\n\t\t\tif (b != ' ') {\n\t\t\t\tbaos.write(b);\n\t\t\t}\n\t\t}\n\t\treturn baos.toByteArray();\n\t}\n\n\t/**\n\t * Remove all nulls (0) found in the data.\n\t * @param array the data\n\t * @return the data cleared of whitespaces\n\t */\n\tpublic static byte[] removeNullBytes(byte[] array) {\n\t\tByteArrayOutputStream baos = new ByteArrayOutputStream(array.length);\n\t\tfor (byte b : array) {\n\t\t\tif (b != 0x00) {\n\t\t\t\tbaos.write(b);\n\t\t\t}\n\t\t}\n\t\treturn baos.toByteArray();\n\t}\n\n\t/**\n\t * Convert a short value to littleEndian\n\t * @param value value to be converted\n\t * @return littleEndian short\n\t */\n\tpublic static short littleEndian(short value) {\n\n\t\tshort num1 = value;\n\t\tshort mask = (short) 0xff;\n\n\t\tshort num2 = (short) (num1 & mask);\n\t\tnum2 <<= 8;\n\t\tmask <<= 8;\n\n\t\tnum2 |= (num1 & mask) >> 8;\n\n\t\treturn num2;\n\t}\n\n\t/**\n\t * Convert an int value to littleEndian\n\t * @param value value to be converted\n\t * @return littleEndian int\n\t */\n\tpublic static int littleEndian(int value) {\n\n\t\tint num1 = value;\n\t\tint mask = 0xff;\n\t\tint num2 = 0x00;\n\n\t\tnum2 |= num1 & mask;\n\n\t\tfor (int i = 1; i < 4; i++) {\n\t\t\tnum2 <<= 8;\n\t\t\tmask <<= 8;\n\t\t\tnum2 |= (num1 & mask) >> (8 * i);\n\t\t}\n\n\t\treturn num2;\n\t}\n\n\t/**\n\t * pad a string and convert it to byte[] to write to a dbf file (by default, add whitespaces to the end of the string)\n\t * @param text The text to be padded\n\t * @param charset Charset to use to encode the string\n\t * @param length Size of the padded string\n\t * @return bytes to write to the dbf file\n\t */\n\tpublic static byte[] textPadding(String text, Charset charset, int length) {\n\t\treturn textPadding(text, charset, length, DBFAlignment.LEFT, (byte) ' ');\n\t}\n\n\t/**\n\t * pad a string and convert it to byte[] to write to a dbf file\n\t * @param text The text to be padded\n\t * @param charset Charset to use to encode the string\n\t * @param length Size of the padded string\n\t * @param alignment alignment to use to padd\n\t * @param paddingByte the byte used to pad the string\n\t * @return bytes to write to the dbf file\n\t */\n\tpublic static byte[] textPadding(String text, Charset charset, int length, DBFAlignment alignment, byte paddingByte) {\n\t\tbyte[] response = new byte[length];\n\t\tArrays.fill(response, paddingByte);\n\t\tbyte[] stringBytes = text.getBytes(charset);\n\n\t\twhile (stringBytes.length > length) {\n\t\t\ttext = text.substring(0, text.length() - 1);\n\t\t\tstringBytes = text.getBytes(charset);\n\t\t}\n\n\t\tint t_offset = 0;\n\t\tswitch (alignment) {\n\t\tcase RIGHT:\n\t\t\tt_offset = length - stringBytes.length;\n\t\t\tbreak;\n\t\tcase LEFT:\n\t\tdefault:\n\t\t\tt_offset = 0;\n\t\t\tbreak;\n\n\t\t}\n\t\tSystem.arraycopy(stringBytes, 0, response, t_offset, stringBytes.length);\n\n\t\treturn response;\n\t}\n\n\t/**\n\t * Format a double number to write to a dbf file\n\t * @param num number to format\n\t * @param charset charset to use\n\t * @param fieldLength field length\n\t * @param sizeDecimalPart decimal part size\n\t * @return bytes to write to the dbf file\n\t */\n\n\tpublic static byte[] doubleFormating(Number num, Charset charset, int fieldLength, int sizeDecimalPart) {\n\t\tint sizeWholePart = fieldLength - (sizeDecimalPart > 0 ? sizeDecimalPart + 1 : 0);\n\n\t\tStringBuilder format = new StringBuilder(fieldLength);\n\t\tfor (int i = 0; i < sizeWholePart-1; i++) {\n\t\t\tformat.append(\"#\");\n\t\t}\n\t\tif (format.length() < sizeWholePart) {\n\t\t\tformat.append(\"0\");\n\t\t}\n\t\tif (sizeDecimalPart > 0) {\n\t\t\tformat.append(\".\");\n\t\t\tfor (int i = 0; i < sizeDecimalPart; i++) {\n\t\t\t\tformat.append(\"0\");\n\t\t\t}\n\t\t}\n\n\t\tDecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);\n\t\tdf.applyPattern(format.toString());\n\t\treturn textPadding(df.format(num), charset, fieldLength, DBFAlignment.RIGHT,\n\t\t\t\t(byte) ' ');\n\t}\n\n\t/**\n\t * Checks that a byte array contains some specific byte\n\t * @param array The array to search in\n\t * @param value The byte to search for\n\t * @return true if the array contains spcified value\n\t */\n\tpublic static boolean contains(byte[] array, byte value) {\n\t\tif (array != null) {\n\t\t\tfor (byte data : array) {\n\t\t\t\tif (data == value) {\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\n\t/**\n\t * Checks if a string is pure Ascii\n\t * @param stringToCheck the string\n\t * @return true if is ascci\n\t */\n\tpublic static boolean isPureAscii(String stringToCheck) {\n\t\tif (stringToCheck == null || stringToCheck.length() == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tsynchronized (ASCII_ENCODER) {\n\t\t\treturn ASCII_ENCODER.canEncode(stringToCheck);\n\t\t}\n\t}\n\n\t/**\n\t * Test if the data in the array is pure ASCII\n\t * @param data data to check\n\t * @return true if there are only ASCII characters\n\t */\n\tpublic static boolean isPureAscii(byte[] data) {\n\t\tif (data == null) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (byte b : data) {\n\t\t\tif (b < 0x20) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Convert LOGICAL (L) byte to boolean value\n\t * @param t_logical The byte value as stored in the file\n\t * @return The boolean value\n\t */\n\tpublic static Object toBoolean(byte t_logical) {\n\t\tif (t_logical == 'Y' || t_logical == 'y' || t_logical == 'T' || t_logical == 't') {\n\t\t\treturn Boolean.TRUE;\n\t\t} else if (t_logical == 'N' || t_logical == 'n' || t_logical == 'F' || t_logical == 'f') {\n\t\t\treturn Boolean.FALSE;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Trims right spaces from string\n\t * @param b_array the string\n\t * @return the string without right spaces\n\t */\n\tpublic static byte[] trimRightSpaces(byte[] b_array) {\n\t\tif (b_array == null || b_array.length == 0) {\n\t\t\treturn new byte[0];\n\t\t}\n\t\tint pos = getRightPos(b_array);\n\t\tint length = pos + 1;\n\t\tbyte[] newBytes = new byte[length];\n\t\tSystem.arraycopy(b_array, 0, newBytes, 0, length);\n\t\treturn newBytes;\n\t}\n\n\tprivate static int getRightPos(byte[] b_array) {\n\n\t\tint pos = b_array.length - 1;\n\t\twhile (pos >= 0 && b_array[pos] == (byte) ' ') {\n\t\t\tpos--;\n\t\t}\n\t\treturn pos;\n\t}\n\n\t/**\n\t * Closes silently a #{@link java.io.Closeable}.\n\t * it can be null or throws an exception, will be ignored.\n\t * @param closeable The item to close\n\t */\n\tpublic static void close(Closeable closeable) {\n\t\tif (closeable != null) {\n\t\t\ttry {\n\t\t\t\tcloseable.close();\n\t\t\t} catch (Exception ignore) {\n\t\t\t\t// nop\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Safely skip bytesToSkip bytes (in some bufferd scenarios skip doesn't really skip all requested bytes)\n\t * @param inputStream the Inputstream\n\t * @param bytesToSkip number of bytes to skip\n\t * @throws IOException if some IO error happens\n\t */\n\tpublic static void skip(InputStream inputStream, long bytesToSkip) throws IOException {\n\t\tif (inputStream != null && bytesToSkip > 0) {\n\t\t\tlong skipped = inputStream.skip(bytesToSkip);\n\t\t\tfor (long i = skipped; i < bytesToSkip; i++) {\n\t\t\t\tinputStream.read();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Safely skip bytesToSkip\n\t * @param dataInput the DataInput\n\t * @param bytesToSkip number of bytes to skip\n\t * @throws IOException if some IO error happens\n\t */\n\tprotected static void skipDataInput(DataInput dataInput, int bytesToSkip) throws IOException {\n\t\tif (dataInput != null && bytesToSkip > 0) {\n\t\t\tint skipped = dataInput.skipBytes(bytesToSkip);\n\t\t\tfor (int i = skipped; i < bytesToSkip; i++) {\n\t\t\t\tdataInput.readByte();\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected static byte[] readAllBytes(File file) throws IOException {\n\t\tif (file == null) {\n\t\t\tthrow new IllegalArgumentException(\"file must not be null\");\n\t\t}\n\t\tbyte[] data = new byte[(int) file.length()];\n\t\tInputStream is = null;\n\t\ttry {\n\t\t\tis = new BufferedInputStream(new FileInputStream(file));\n\t\t\tis.read(data);\n\t\t}\n\t\tfinally {\n\t\t\tclose(is);\n\t\t}\n\t\treturn data;\n\t}\n\n\tprotected static BitSet getBitSet(byte[] bytes) {\n//\t\treturn BitSet.valueOf(bytes);\n\t\t\n\t\tBitSet bits = new BitSet();\n\t for (int i = 0; i < bytes.length * 8; i++) {\n\t byte b = bytes[i/8];\n\t int bit = (b & (1 << (i % 8)));\n\t if (bit > 0) {\n\t bits.set(i);\n\t }\n\t }\n\t return bits;\n\t}\n}",
"public class DBFWriter extends DBFBase implements java.io.Closeable {\n\n\tprivate DBFHeader header;\n\tprivate List<Object[]> v_records = new ArrayList<Object[]>();\n\tprivate int recordCount = 0;\n\t//Open and append records to an existing DBF\n\tprivate RandomAccessFile raf = null;\n\tprivate OutputStream outputStream = null;\n\n\tprivate boolean closed = false;\n\n\t/**\n\t * Creates an empty DBFWriter.\n\t * @deprecated use {@link #DBFWriter(OutputStream)}\n\t */\n\t@Deprecated\n\tpublic DBFWriter() {\n\t\tthis(DEFAULT_CHARSET);\n\t}\n\t/**\n\t * Creates an empty DBFWriter.\n\t * @param charset Charset used to encode field names and field contents\n\t * @deprecated use {@link #DBFWriter(OutputStream, Charset)}\n\t */\n\t@Deprecated\n\tpublic DBFWriter(Charset charset) {\n\t\tsuper();\n\t\tsetCharset(charset);\n\t\tthis.header = new DBFHeader();\n\t\tthis.header.setUsedCharset(charset);\n\t}\n\n\t/**\n\t * Creates a DBFWriter wich write data to the given OutputStream.\n\t * Uses default charset iso-8859-1\n\t * @param out stream to write the data to.\n\t */\n\n\tpublic DBFWriter(OutputStream out) {\n\t\tthis(out, DEFAULT_CHARSET);\n\t}\n\t/**\n\t * Creates a DBFWriter wich write data to the given OutputStream.\n\t * @param out stream to write the data to.\n\t * @param charset Encoding to use in resulting dbf file\n\t */\n\tpublic DBFWriter(OutputStream out, Charset charset) {\n\t\tsuper();\n\t\tsetCharset(charset);\n\t\tthis.header = new DBFHeader();\n\t\tthis.header.setUsedCharset(charset);\n\t\tthis.outputStream = out;\n\t}\n\n\t/**\n\t * Creates a DBFWriter which can append to records to an existing DBF file.\n\t *\n\t * @param dbfFile The file passed in shouls be a valid DBF file.\n\t * @exception DBFException\n\t * if the passed in file does exist but not a valid DBF file,\n\t * or if an IO error occurs.\n\t */\n\tpublic DBFWriter(File dbfFile) {\n\t\tthis(dbfFile, null);\n\t}\n\n\n\t/**\n\t * Creates a DBFWriter which can append to records to an existing DBF file.\n\t *\n\t * @param dbfFile The file passed in shouls be a valid DBF file.\n\t * @param charset The charset used to encode field name and field contents\n\t * @exception DBFException\n\t * if the passed in file does exist but not a valid DBF file,\n\t * or if an IO error occurs.\n\t */\n\tpublic DBFWriter(File dbfFile, Charset charset) {\n\t\tsuper();\n\t\ttry {\n\t\t\tthis.raf = new RandomAccessFile(dbfFile, \"rw\");\n\t\t\tthis.header = new DBFHeader();\n\n\t\t\t/*\n\t\t\t * before proceeding check whether the passed in File object is an\n\t\t\t * empty/non-existent file or not.\n\t\t\t */\n\t\t\tif (dbfFile.length() == 0) {\n\t\t\t\tif (charset != null) {\n\t\t\t\t\tif (DBFCharsetHelper.getDBFCodeForCharset(charset) == 0 && !DBFStandardCharsets.UTF_8.equals(charset)) {\n\t\t\t\t\t\tthrow new DBFException(\"Unssuported charset \" + charset);\n\t\t\t\t\t}\n\t\t\t\t\tsetCharset(charset);\n\t\t\t\t\tthis.header.setUsedCharset(charset);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsetCharset(DBFStandardCharsets.ISO_8859_1);\n\t\t\t\t\tthis.header.setUsedCharset(DBFStandardCharsets.ISO_8859_1);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.header.read(this.raf, charset, false);\n\t\t\tsetCharset(this.header.getUsedCharset());\n\n\t\t\t// position file pointer at the end of the raf\n\t\t\t// to ignore the END_OF_DATA byte at EoF\n\t\t\t// only if there are records,\n\t\t\tif (this.raf.length() > header.headerLength) {\n\t\t\t\tthis.raf.seek(this.raf.length() - 1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.raf.seek(this.raf.length());\n\t\t\t}\n\t\t} catch (FileNotFoundException e) {\n\t\t\tthrow new DBFException(\"Specified file is not found. \" + e.getMessage(), e);\n\t\t} catch (IOException e) {\n\t\t\tthrow new DBFException(e.getMessage() + \" while reading header\", e);\n\t\t}\n\n\t\tthis.recordCount = this.header.numberOfRecords;\n\t}\n\n\n\n\t/**\n\t * Sets fields definition.\n\t * To keep maximum compatibility a maximum of 255 columns should be used.\n\t * https://docs.microsoft.com/en-us/previous-versions/visualstudio/foxpro/3kfd3hw9(v=vs.80)\n\t * @param fields fields definition\n\t */\n\tpublic void setFields(DBFField[] fields) {\n\t\tif (this.closed) {\n\t\t\tthrow new IllegalStateException(\"You can not set fields to a closed DBFWriter\");\n\t\t}\n\t\tif (this.header.fieldArray != null) {\n\t\t\tthrow new DBFException(\"Fields has already been set\");\n\t\t}\n\t\tif (fields == null || fields.length == 0) {\n\t\t\tthrow new DBFException(\"Should have at least one field\");\n\t\t}\n\t\tif (fields.length > 255) {\n\t\t\tthrow new DBFException(\"Exceded column limit of 255 (\" + fields.length + \")\");\n\t\t}\n\t\tList<Integer> fieldsWithNull = new ArrayList<Integer>();\n\t\tfor (int i = 0; i < fields.length; i++) {\n\t\t\tif (fields[i] == null) {\n\t\t\t\tfieldsWithNull.add(i);\n\t\t\t}\n\t\t}\n\t\tif (!fieldsWithNull.isEmpty()) {\n\t\t\tif (fieldsWithNull.size() == 1) {\n\t\t\t\tthrow new DBFException(\"Field \" + fieldsWithNull.get(0) + \" is null\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new DBFException(\"Fields \" + fieldsWithNull.toString() + \" are null\");\n\t\t\t}\n\t\t}\n\t\tfor (DBFField field: fields) {\n\t\t\tif (!field.getType().isWriteSupported()) {\n\t\t\t\tthrow new DBFException(\n\t\t\t\t\"Field \" + field.getName() + \" is of type \" + field.getType() + \" that is not supported for writting\");\n\t\t\t}\n\t\t}\n\t\tthis.header.fieldArray = new DBFField[fields.length];\n\t\tfor (int i = 0; i < fields.length; i++) {\n\t\t\tthis.header.fieldArray[i] = new DBFField(fields[i]);\n\t\t}\n\t\t\n\t\t\n\t\ttry {\n\t\t\tif (this.raf != null && this.raf.length() > 0) {\n\t\t\t\tthrow new DBFException(\"You can not change fields on an existing file\");\n\t\t\t}\n\t\t\tif (this.raf != null && this.raf.length() == 0) {\n\t\t\t\t// this is a new/non-existent file. So write header before proceeding\n\t\t\t\tthis.header.write(this.raf);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new DBFException(\"Error accesing file:\" + e.getMessage(), e);\n\t\t}\n\t}\n\n\t/**\n\t * Add a record.\n\t * @param values fields of the record\n\t */\n\tpublic void addRecord(Object[] values) {\n\t\tif (this.closed) {\n\t\t\tthrow new IllegalStateException(\"You can add records a closed DBFWriter\");\n\t\t}\n\t\tif (this.header.fieldArray == null) {\n\t\t\tthrow new DBFException(\"Fields should be set before adding records\");\n\t\t}\n\n\t\tif (values == null) {\n\t\t\tthrow new DBFException(\"Null cannot be added as row\");\n\t\t}\n\n\t\tif (values.length != this.header.fieldArray.length) {\n\t\t\tthrow new DBFException(\"Invalid record. Invalid number of fields in row\");\n\t\t}\n\n\t\tfor (int i = 0; i < this.header.fieldArray.length; i++) {\n\t\t\tObject value = values[i];\n\t\t\tif (value == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch (this.header.fieldArray[i].getType()) {\n\n\t\t\tcase CHARACTER:\n\t\t\t\tif (!(value instanceof String)) {\n\t\t\t\t\tthrow new DBFException(\"Invalid value for field \" + i + \":\" + value);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase LOGICAL:\n\t\t\t\tif (!(value instanceof Boolean)) {\n\t\t\t\t\tthrow new DBFException(\"Invalid value for field \" + i + \":\" + value);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase DATE:\n\t\t\t\tif (!(value instanceof Date)) {\n\t\t\t\t\tthrow new DBFException(\"Invalid value for field \" + i + \":\" + value);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase NUMERIC:\n\t\t\tcase FLOATING_POINT:\n\t\t\t\tif (!(value instanceof Number)) {\n\t\t\t\t\tthrow new DBFException(\"Invalid value for field \" + i + \":\" + value);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new DBFException(\"Unsupported writting of field type \" + i + \" \"\n\t\t\t\t\t\t+ this.header.fieldArray[i].getType());\n\t\t\t}\n\n\t\t}\n\n\t\tif (this.raf == null) {\n\t\t\tthis.v_records.add(values);\n\t\t} else {\n\t\t\ttry {\n\t\t\t\twriteRecord(this.raf, values);\n\t\t\t\tthis.recordCount++;\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new DBFException(\"Error occured while writing record. \" + e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\tprivate void writeToStream(OutputStream out) {\n\t\ttry {\n\n\t\t\tDataOutputStream outStream = new DataOutputStream(out);\n\t\t\tthis.header.numberOfRecords = this.v_records.size();\n\t\t\tthis.header.write(outStream);\n\n\t\t\t/* Now write all the records */\n\t\t\tfor (Object[] record : this.v_records) {\n\t\t\t\twriteRecord(outStream, record);\n\t\t\t}\n\n\t\t\toutStream.write(END_OF_DATA);\n\t\t\toutStream.flush();\n\n\t\t} catch (IOException e) {\n\t\t\tthrow new DBFException(e.getMessage(), e);\n\t\t}\n\t}\n\t/**\n\t * In sync mode, write the header and close the file\n\t */\n\t@Override\n\tpublic void close() {\n\t\tif (this.closed) {\n\t\t\treturn;\n\t\t}\n\t\tthis.closed = true;\n\t\tif (this.raf != null) {\n\t\t\t/*\n\t\t\t * everything is written already. just update the header for\n\t\t\t * record count and the END_OF_DATA mark\n\t\t\t */\n\t\t\ttry {\n\t\t\t\tthis.header.numberOfRecords = this.recordCount;\n\t\t\t\tthis.raf.seek(0);\n\t\t\t\tthis.header.write(this.raf);\n\t\t\t\tthis.raf.seek(this.raf.length());\n\t\t\t\tthis.raf.writeByte(END_OF_DATA);\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow new DBFException(e.getMessage(), e);\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tDBFUtils.close(this.raf);\n\t\t\t}\n\t\t}\n\t\telse if (this.outputStream != null) {\n\t\t\ttry {\n\t\t\t\twriteToStream(this.outputStream);\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tDBFUtils.close(this.outputStream);\n\t\t\t}\n\t\t}\n\n\t}\n\n\n\tprivate void writeRecord(DataOutput dataOutput, Object[] objectArray) throws IOException {\n\t\tdataOutput.write((byte) ' ');\n\t\tfor (int j = 0; j < this.header.fieldArray.length; j++) {\n\t\t\t/* iterate throught fields */\n\t\t\tswitch (this.header.fieldArray[j].getType()) {\n\n\t\t\tcase CHARACTER:\n\t\t\t\tString strValue = \"\";\n\t\t\t\tif (objectArray[j] != null) {\n\t\t\t\t\tstrValue = objectArray[j].toString();\n\t\t\t\t}\n\t\t\t\tdataOutput.write(DBFUtils.textPadding(strValue, getCharset(), this.header.fieldArray[j].getLength(), DBFAlignment.LEFT, (byte) ' '));\n\n\t\t\t\tbreak;\n\n\t\t\tcase DATE:\n\t\t\t\tif (objectArray[j] != null) {\n\t\t\t\t\tGregorianCalendar calendar = new GregorianCalendar();\n\t\t\t\t\tcalendar.setTime((Date) objectArray[j]);\n\t\t\t\t\tdataOutput.write(DBFUtils.textPadding(String.valueOf(calendar.get(Calendar.YEAR)),\n\t\t\t\t\t\t\tDBFStandardCharsets.US_ASCII, 4, DBFAlignment.RIGHT, (byte) '0'));\n\t\t\t\t\tdataOutput.write(DBFUtils.textPadding(String.valueOf(calendar.get(Calendar.MONTH) + 1),\n\t\t\t\t\t\t\tDBFStandardCharsets.US_ASCII, 2, DBFAlignment.RIGHT, (byte) '0'));\n\t\t\t\t\tdataOutput.write(DBFUtils.textPadding(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)),\n\t\t\t\t\t\t\tDBFStandardCharsets.US_ASCII, 2, DBFAlignment.RIGHT, (byte) '0'));\n\t\t\t\t} else {\n\t\t\t\t\tdataOutput.write(\" \".getBytes(DBFStandardCharsets.US_ASCII));\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\tcase NUMERIC:\n\t\t\tcase FLOATING_POINT:\n\n\t\t\t\tif (objectArray[j] != null) {\n\t\t\t\t\tdataOutput.write(DBFUtils.doubleFormating((Number) objectArray[j], getCharset(),\n\t\t\t\t\t\t\tthis.header.fieldArray[j].getLength(), this.header.fieldArray[j].getDecimalCount()));\n\t\t\t\t} else {\n\t\t\t\t\tdataOutput.write(DBFUtils.textPadding(\" \", getCharset(), this.header.fieldArray[j].getLength(), DBFAlignment.RIGHT, (byte) ' '));\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase LOGICAL:\n\n\t\t\t\tif (objectArray[j] instanceof Boolean) {\n\t\t\t\t\tif ((Boolean) objectArray[j]) {\n\t\t\t\t\t\tdataOutput.write((byte) 'T');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdataOutput.write((byte) 'F');\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tdataOutput.write((byte) '?');\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tthrow new DBFException(\"Unknown field type \" + this.header.fieldArray[j].getType());\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Check if the writer is closed\n\t * @return true if already closed\n\t */\n\tprotected boolean isClosed() {\n\t\treturn this.closed;\n\t}\n\n\t/**\n\t * Get de underlying RandomAccessFile. It can be null if OutputStream constructor is used.\n\t * @return the underlying RandomAccessFile\n\t */\n\tprotected RandomAccessFile getRamdonAccessFile() {\n\t\treturn this.raf;\n\t}\n\n\n\t/**\n\t * Writes the set data to the OutputStream.\n\t * @param out the output stream\n\t * @deprecated use {@link #DBFWriter(OutputStream)} constructor and call close\n\t */\n\t@Deprecated\n\tpublic void write(OutputStream out) {\n\t\tif (this.raf == null) {\n\t\t\twriteToStream(out);\n\t\t}\n\t}\n\n\t/**\n\t * In sync mode, write the header and close the file\n\t * @deprecated use {@link #close()}\n\t */\n\t@Deprecated\n\tpublic void write() {\n\t\tthis.close();\n\t}\n\n}",
"public class ReadDBFAssert {\n\n\tprivate ReadDBFAssert() {\n\t\tthrow new AssertionError(\"No instances\");\n\t}\n\t\n\tpublic static void testReadDBFFile(String fileName, int expectedColumns, int expectedRows) throws DBFException, IOException {\n\t\ttestReadDBFFile(fileName, expectedColumns, expectedRows, false);\n\t}\n\n\tpublic static void testReadDBFFile(String fileName, int expectedColumns, int expectedRows, Boolean showDeletedRows) throws DBFException, IOException {\n\t\ttestReadDBFFile(new File(\"src/test/resources/\" + fileName + \".dbf\"), expectedColumns, expectedRows, showDeletedRows);\n\t}\n\n\tpublic static void testReadDBFFile(File file, int expectedColumns, int expectedRows, Boolean showDeletedRows) throws DBFException, IOException {\n\t\tDBFReader reader = null;\n\t\ttry {\n\t\t\treader = new DBFReader(new BufferedInputStream(new FileInputStream(file)), showDeletedRows);\n\t\t\ttestReadDBFFile(reader, expectedColumns, expectedRows);\n\t\t} finally {\n\t\t\tDBFUtils.close(reader);\n\t\t}\n\n\t}\n\tpublic static void testReadDBFFile(InputStream is, int expectedColumns, int expectedRows) throws DBFException {\n\t\ttestReadDBFFile(new DBFReader(is), expectedColumns, expectedRows);\n\t}\n\n\tpublic static void testReadDBFFile(DBFReader reader, int expectedColumns, int expectedRows) throws DBFException {\n\t\t\n\n\t\tint numberOfFields = reader.getFieldCount();\n\t\tAssert.assertEquals(expectedColumns, numberOfFields);\n\t\tfor (int i = 0; i < numberOfFields; i++) {\n\t\t\tDBFField field = reader.getField(i);\n\t\t\tAssert.assertNotNull(field.getName());\n\t\t}\n\t\tObject[] rowObject;\n\t\tint countedRows = 0;\n\t\twhile ((rowObject = reader.nextRecord()) != null) {\n\t\t\tAssert.assertEquals(numberOfFields, rowObject.length);\n\t\t\tcountedRows++;\n\t\t}\n\t\tAssert.assertEquals(expectedRows, countedRows);\n\t\tAssert.assertEquals(expectedRows, reader.getRecordCount());\n\t}\n\n\tpublic static void testReadDBFFileDeletedRecords(String fileName, int expectedRows, int expectedDeleted) throws DBFException, IOException {\n\n\t\tDBFReader reader = null;\n\t\ttry {\n\t\t\treader = new DBFReader(new BufferedInputStream(new FileInputStream(new File(\"src/test/resources/\" + fileName + \".dbf\"))), true);\n\t\t\tObject[] rowObject;\n\n\t\t\tint countedRows = 0;\n\t\t\tint countedDeletes = 0;\n\t\t\tint headerStoredRows = reader.getHeader().numberOfRecords;\n\t\t\twhile ((rowObject = reader.nextRecord()) != null) {\n\t\t\t\tif(rowObject[0] == Boolean.TRUE) {\n\t\t\t\t\tcountedDeletes++;\n\t\t\t\t}\n\t\t\t\tcountedRows++;\n\t\t\t}\n\n\t\t\tAssert.assertEquals(expectedRows, countedRows);\n\t\t\tAssert.assertEquals(expectedDeleted, countedDeletes);\n\t\t\tAssert.assertEquals(expectedRows, headerStoredRows);\n\t\t} finally {\n\t\t\tDBFUtils.close(reader);\n\t\t}\n\n\n\t}\n}",
"public final class FileUtils {\n\t\n\tprivate FileUtils() {\n\t\tthrow new AssertionError(\"No instances allowed\");\n\t}\n\tpublic static void copyFile(File source, File dest) throws IOException {\n\t InputStream is = null;\n\t OutputStream os = null;\n\t try {\n\t is = new FileInputStream(source);\n\t os = new FileOutputStream(dest);\n\t byte[] buffer = new byte[1024];\n\t int length;\n\t while ((length = is.read(buffer)) > 0) {\n\t os.write(buffer, 0, length);\n\t }\n\t } finally {\n\t is.close();\n\t os.close();\n\t }\n\t}\n}"
] | import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.junit.Assert;
import org.junit.Test;
import com.linuxense.javadbf.DBFException;
import com.linuxense.javadbf.DBFUtils;
import com.linuxense.javadbf.DBFWriter;
import com.linuxense.javadbf.ReadDBFAssert;
import com.linuxense.javadbf.testutils.FileUtils; | package com.linuxense.javadbf.bug94_error_f5;
public class Bug94ErrorF5Test {
private File testFile = new File("src/test/resources/fixtures/dbase_f5.dbf");
public Bug94ErrorF5Test() {
super();
}
@Test
public void testSimpleRead() throws DBFException, IOException {
ReadDBFAssert.testReadDBFFile(testFile, 60, 975, true);
}
@Test
public void testWrite() throws Exception {
File tmpFile = Files.createTempFile("tmp", ".dbf").toFile(); | FileUtils.copyFile(testFile, tmpFile); | 4 |
XhinLiang/Studio | app/src/main/java/com/wecan/xhin/studio/activity/RegisterActivity.java | [
"public abstract class BaseActivity extends RxAppCompatActivity {\n\n protected void setHasHomeButton() {\n if (getSupportActionBar() != null) {\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n getSupportActionBar().setHomeButtonEnabled(true);\n }\n }\n\n\n public Observable<ViewClickEvent> setRxClick(View view) {\n return RxView.clickEvents(view)\n .throttleFirst(500, TimeUnit.MILLISECONDS);\n }\n\n\n protected void showSimpleDialog(CharSequence content) {\n new AlertDialog.Builder(this)\n .setMessage(content)\n .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n }\n })\n .create()\n .show();\n }\n\n protected void showSimpleDialog(int titleRes, int contentRes) {\n new AlertDialog.Builder(this)\n .setMessage(contentRes)\n .setTitle(titleRes)\n .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n }\n })\n .create()\n .show();\n }\n\n protected void showSimpleDialog(int titleRes, CharSequence content) {\n new AlertDialog.Builder(this)\n .setMessage(content)\n .setTitle(titleRes)\n .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n }\n })\n .create()\n .show();\n }\n\n protected void showSimpleDialog(int contentRes) {\n new AlertDialog.Builder(this)\n .setMessage(contentRes)\n .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n }\n })\n .create()\n .show();\n }\n\n public class SpinnerFilter implements Func1<ViewClickEvent, Boolean> {\n AppCompatSpinner spinner;\n int messageRes;\n\n public SpinnerFilter(AppCompatSpinner spinner, int messageRes) {\n this.spinner = spinner;\n this.messageRes = messageRes;\n }\n\n @Override\n public Boolean call(ViewClickEvent viewClickEvent) {\n if (spinner.getSelectedItemPosition() == 0) {\n showSimpleDialog(messageRes);\n return false;\n }\n return true;\n }\n }\n\n public class EditTextFilter implements Func1<ViewClickEvent, Boolean> {\n EditText editText;\n int messageRes;\n\n public EditTextFilter(EditText editText, int messageRes) {\n this.editText = editText;\n this.messageRes = messageRes;\n }\n\n @Override\n public Boolean call(ViewClickEvent viewClickEvent) {\n if (editText.getText().toString().isEmpty()) {\n showSimpleDialog(messageRes);\n return false;\n }\n return true;\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n finish();\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n }\n}",
"public class RxNetworking {\n\n public static <T> Observable.Transformer<T, T> bindRefreshing(final SwipeRefreshLayout srl) {\n return new Observable.Transformer<T, T>() {\n //类似装饰者模式\n @Override\n public Observable<T> call(Observable<T> original) {\n return original.doOnSubscribe(new Action0() {\n @Override\n public void call() {\n srl.post(new Runnable() {\n @Override\n public void run() {\n srl.setRefreshing(true);\n }\n });\n }\n }).doOnCompleted(new Action0() {\n @Override\n public void call() {\n srl.post(new Runnable() {\n @Override\n public void run() {\n srl.setRefreshing(false);\n }\n });\n }\n });\n }\n };\n }\n\n public static <T> Observable.Transformer<T, T> bindConnecting(final ProgressDialog pd) {\n return new Observable.Transformer<T, T>() {\n @Override\n public Observable<T> call(Observable<T> original) {\n return original.doOnSubscribe(new Action0() {\n @Override\n public void call() {\n pd.show();\n }\n }).doOnCompleted(new Action0() {\n @Override\n public void call() {\n pd.hide();\n }\n }).doOnError(new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n pd.hide();\n }\n });\n }\n };\n }\n}",
"public class App extends Application {\n\n\n public static final String VALUE_AVOS_APPID = \"AkVsXJ4RoWq1juPauOHe1OW5\";\n public static final String VALUE_AVOS_APPKEY = \"gFICBkjJSxlI5fHnvNyB7Lfj\";\n\n public static final String KEY_PREFERENCE_USER = \"user\";\n public static final String KEY_PREFERENCE_PHONE = \"phone\";\n public static final String KEY_BUILD_VERSION = \"build_version\";\n public static final String DATE_FORMAT_PATTERN = \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\";\n\n private final HashMap<Class, Object> apis = new HashMap<>();\n\n private Retrofit retrofit;\n\n //返回当前单例的静态方法,判断是否是当前的App调用\n public static App from(Context context) {\n Context application = context.getApplicationContext();\n if (application instanceof App)\n return (App) application;\n throw new IllegalArgumentException(\"Context must be from Studio\");\n }\n\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n AVOSCloud.initialize(this, VALUE_AVOS_APPID, VALUE_AVOS_APPKEY);\n OkHttpClient okHttpClient = new OkHttpClient();\n //OKHttp的使用\n okHttpClient.networkInterceptors().add(new Interceptor() {\n @Override\n public Response intercept(Chain chain) throws IOException {\n return chain.proceed(chain.request().newBuilder()\n .header(KEY_BUILD_VERSION, BuildConfig.VERSION_NAME)\n .build());\n }\n });\n\n if (BuildConfig.DEBUG) {\n okHttpClient.networkInterceptors().add(new LoggingInterceptor());\n }\n\n //初始化Gson\n Gson gson = new GsonBuilder()\n .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)\n .setDateFormat(DATE_FORMAT_PATTERN)\n .create();\n\n\n //初始化Retrofit\n retrofit = new Retrofit.Builder()\n .client(okHttpClient)\n .addConverterFactory(GsonConverterFactory.create(gson))\n .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n .baseUrl(Api.BASE_URL)\n .build();\n }\n\n //返回Retrofit的API\n public <T> T createApi(Class<T> service) {\n if (!apis.containsKey(service)) {\n T instance = retrofit.create(service);\n apis.put(service, instance);\n }\n //noinspection unchecked\n return (T) apis.get(service);\n }\n\n public OkHttpClient getHttpClient() {\n return retrofit.client();\n }\n}",
"public interface Api {\n\n String BASE_URL = \"http://121.42.209.19/RestfulApi/index.php/\";\n\n @GET(\"api/users\")\n Observable<User> login(@Query(\"name\") String name, @Query(\"phone\") String phone);\n\n @POST(\"api/users\")\n Observable<BaseData> register(@Body RegisterBody registerUser);\n\n @PUT(\"api/users\")\n Observable<User> updateUser(@Body User updateUser);\n\n @POST(\"api/sign\")\n Observable<BaseData> sign(@Body SignBody user);\n\n @DELETE(\"api/sign\")\n Observable<BaseData> unSign(@Query(\"name\") String name);\n\n @GET(\"api/message_all\")\n Observable<UsersData> getAllUser();\n\n @GET(\"api/message\")\n Observable<UsersData> getSignedUser();\n\n @GET(\"api/addplease/{code}\")\n Observable<BaseData> addCode(@Path(\"code\") String code);\n\n}",
"public class BaseData {\n public int status;\n public String message;\n}",
"public class RegisterBody {\n\n private int position;\n private int group_name;\n private int sex;\n private String phone;\n private String name;\n private String imgurl;\n private String code;\n private String description;\n\n public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) {\n this.position = position;\n this.group_name = group_name;\n this.phone = phone;\n this.sex = sex;\n this.name = name;\n this.code = code;\n this.imgurl = \"\";\n this.description = \"\";\n }\n}"
] | import android.app.ProgressDialog;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import com.jakewharton.rxbinding.view.ViewClickEvent;
import com.wecan.xhin.baselib.activity.BaseActivity;
import com.wecan.xhin.baselib.rx.RxNetworking;
import com.wecan.xhin.studio.App;
import com.wecan.xhin.studio.R;
import com.wecan.xhin.studio.api.Api;
import com.wecan.xhin.studio.bean.down.BaseData;
import com.wecan.xhin.studio.bean.up.RegisterBody;
import com.wecan.xhin.studio.databinding.ActivityRegisterBinding;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.schedulers.Schedulers; | package com.wecan.xhin.studio.activity;
/**
* Created by xhinliang on 15-11-23.
* [email protected]
*/
public class RegisterActivity extends BaseActivity {
private ActivityRegisterBinding binding;
private Api api;
private Observable<BaseData> observableRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_register);
setSupportActionBar(binding.toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
api = App.from(this).createApi(Api.class);
ProgressDialog pd = new ProgressDialog(this);
Observable.Transformer<BaseData, BaseData> networkingIndicator = RxNetworking.bindConnecting(pd);
observableRegister = Observable
//defer操作符是直到有订阅者订阅时,才通过Observable的工厂方法创建Observable并执行
//defer操作符能够保证Observable的状态是最新的
.defer(new Func0<Observable<BaseData>>() {
@Override
public Observable<BaseData> call() { | return api.register(new RegisterBody(binding.acpPosition.getSelectedItemPosition() | 5 |
dmfs/xmlobjects | src/org/dmfs/xmlobjects/builder/TransientObjectBuilder.java | [
"public final class ElementDescriptor<T>\n{\n\tpublic final static XmlContext DEFAULT_CONTEXT = new XmlContext()\n\t{\n\t};\n\n\t/**\n\t * The {@link QualifiedName} of this element.\n\t */\n\tpublic final QualifiedName qualifiedName;\n\n\t/**\n\t * An {@link IObjectBuilder} for elements of this type.\n\t */\n\tpublic final IObjectBuilder<T> builder;\n\n\t/**\n\t * A {@link WeakReference} to the context this element was registered in.\n\t */\n\tprivate final WeakReference<XmlContext> mContext;\n\n\t/**\n\t * A synchronized map of {@link QualifiedName}s to {@link ElementDescriptor}s of Elements valid in the context of this element. May be <code>null</code>.\n\t */\n\tprivate Map<QualifiedName, ElementDescriptor<?>> mElementContext;\n\n\n\t/**\n\t * Return the {@link ElementDescriptor} of the element having the given {@link QualifiedName} from the default {@link XmlContext}.\n\t * \n\t * @param qname\n\t * The {@link QualifiedName} of the {@link ElementDescriptor} to return.\n\t * @return The {@link ElementDescriptor} or <code>null</code> if there is no such element in the default {@link XmlContext}.\n\t */\n\tpublic static ElementDescriptor<?> get(QualifiedName qname)\n\t{\n\t\tsynchronized (DEFAULT_CONTEXT)\n\t\t{\n\t\t\treturn DEFAULT_CONTEXT.DESCRIPTOR_MAP.get(qname);\n\t\t}\n\t}\n\n\n\t/**\n\t * Return the {@link ElementDescriptor} of the element having the given {@link QualifiedName} from the given {@link XmlContext}.\n\t * \n\t * @param qname\n\t * The {@link QualifiedName} of the {@link ElementDescriptor} to return.\n\t * @param context\n\t * The {@link XmlContext}.\n\t * @return The {@link ElementDescriptor} or <code>null</code> if there is no such element in the given {@link XmlContext}.\n\t */\n\tpublic static ElementDescriptor<?> get(QualifiedName qname, XmlContext context)\n\t{\n\t\tif (context == null)\n\t\t{\n\t\t\tcontext = DEFAULT_CONTEXT;\n\t\t}\n\n\t\tsynchronized (context)\n\t\t{\n\t\t\tfinal Map<QualifiedName, ElementDescriptor<?>> contextMap = context.DESCRIPTOR_MAP;\n\t\t\tElementDescriptor<?> result = contextMap.get(qname);\n\t\t\tif (result != null)\n\t\t\t{\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\n\t\tsynchronized (DEFAULT_CONTEXT)\n\t\t{\n\t\t\treturn DEFAULT_CONTEXT.DESCRIPTOR_MAP.get(qname);\n\t\t}\n\t}\n\n\n\t/**\n\t * Return the {@link ElementDescriptor} of the element having the given {@link QualifiedName}. This method returns first checks the context of the given\n\t * parent {@link ElementDescriptor} for matching element and falls back to the default {@link XmlContext}if no matching element is found in the parent\n\t * context.\n\t * \n\t * @param qname\n\t * The {@link QualifiedName} of the {@link ElementDescriptor} to return.\n\t * @param parentElement\n\t * The parent {@link ElementDescriptor}.\n\t * @return The {@link ElementDescriptor} or <code>null</code> if there is no such element in the parent context of the default {@link XmlContext}.\n\t */\n\tpublic static ElementDescriptor<?> get(QualifiedName qname, ElementDescriptor<?> parentElement)\n\t{\n\t\tif (parentElement == null || parentElement.mElementContext == null)\n\t\t{\n\t\t\treturn get(qname);\n\t\t}\n\n\t\tElementDescriptor<?> result = parentElement.mElementContext.get(qname);\n\t\treturn result == null ? get(qname) : result;\n\t}\n\n\n\t/**\n\t * Return the {@link ElementDescriptor} of the element having the given {@link QualifiedName}. This method returns first checks the context of the given\n\t * parent {@link ElementDescriptor} for matching element and falls back to the given {@link XmlContext}if no matching element is found in the parent\n\t * context.\n\t * \n\t * @param qname\n\t * The {@link QualifiedName} of the {@link ElementDescriptor} to return.\n\t * @param parentElement\n\t * The parent {@link ElementDescriptor}.\n\t * @param context\n\t * An {@link XmlContext}, may be <code>null</code> for the default context.\n\t * @return The {@link ElementDescriptor} or <code>null</code> if there is no such element in the parent context of the given {@link XmlContext}.\n\t */\n\tpublic static ElementDescriptor<?> get(QualifiedName qname, ElementDescriptor<?> parentElement, XmlContext context)\n\t{\n\t\tif (parentElement == null || parentElement.mElementContext == null)\n\t\t{\n\t\t\treturn get(qname, context);\n\t\t}\n\n\t\tElementDescriptor<?> result = parentElement.mElementContext.get(qname);\n\t\treturn result == null ? get(qname, context) : result;\n\t}\n\n\n\t/**\n\t * Register an element with the given name and no name space using the given {@link IObjectBuilder} in the default {@link XmlContext}.\n\t * \n\t * @param name\n\t * The name of the element.\n\t * @param builder\n\t * The {@link IObjectBuilder} to build and serialize this element.\n\t * @return The {@link ElementDescriptor}.\n\t */\n\tpublic static <T> ElementDescriptor<T> register(String name, IObjectBuilder<T> builder)\n\t{\n\t\treturn register(QualifiedName.get(name), builder, DEFAULT_CONTEXT);\n\t}\n\n\n\t/**\n\t * Register an element with the given {@link QualifiedName} using the given {@link IObjectBuilder} in the default {@link XmlContext}.\n\t * \n\t * @param qname\n\t * The {@link QualifiedName} of the element.\n\t * @param builder\n\t * The {@link IObjectBuilder} to build and serialize this element.\n\t * @return The {@link ElementDescriptor}.\n\t */\n\tpublic static <T> ElementDescriptor<T> register(QualifiedName qname, IObjectBuilder<T> builder)\n\t{\n\t\treturn register(qname, builder, DEFAULT_CONTEXT);\n\t}\n\n\n\t/**\n\t * Register an element with the given name and no name space using the given {@link IObjectBuilder} in the given {@link XmlContext}.\n\t * \n\t * @param name\n\t * The name of the element.\n\t * @param builder\n\t * The {@link IObjectBuilder} to build and serialize this element.\n\t * @param context\n\t * An {@link XmlContext}.\n\t * @return The {@link ElementDescriptor}.\n\t */\n\tpublic static <T> ElementDescriptor<T> register(String name, IObjectBuilder<T> builder, XmlContext context)\n\t{\n\t\treturn register(QualifiedName.get(name), builder, context);\n\t}\n\n\n\t/**\n\t * Register an element with the given {@link QualifiedName} using the given {@link IObjectBuilder} in the given {@link XmlContext}.\n\t * \n\t * @param qname\n\t * The {@link QualifiedName} of the element.\n\t * @param builder\n\t * The {@link IObjectBuilder} to build and serialize this element.\n\t * @param context\n\t * An {@link XmlContext} or <code>null</code> to use the default {@link XmlContext}.\n\t * @return The {@link ElementDescriptor}.\n\t */\n\tpublic static <T> ElementDescriptor<T> register(QualifiedName qname, IObjectBuilder<T> builder, XmlContext context)\n\t{\n\t\tif (context == null)\n\t\t{\n\t\t\tcontext = DEFAULT_CONTEXT;\n\t\t}\n\n\t\tsynchronized (context)\n\t\t{\n\t\t\tMap<QualifiedName, ElementDescriptor<?>> descriptorMap = context.DESCRIPTOR_MAP;\n\n\t\t\tif (descriptorMap.containsKey(qname))\n\t\t\t{\n\t\t\t\tthrow new IllegalStateException(\"descriptor for \" + qname + \" already exists, use 'overload' to override the definition\");\n\t\t\t}\n\n\t\t\tElementDescriptor<T> descriptor = new ElementDescriptor<T>(qname, builder, context);\n\t\t\tdescriptorMap.put(qname, descriptor);\n\t\t\treturn descriptor;\n\t\t}\n\t}\n\n\n\t/**\n\t * Register an element with the given name and no name space using the given {@link IObjectBuilder} in the context of the given parent\n\t * {@link ElementDescriptor}s. An element that is registered with this method will not be available in a general {@link XmlContext}, but only when providing\n\t * the parent {@link ElementDescriptor} using {@link #get(QualifiedName, ElementDescriptor)} or {@link #get(QualifiedName, ElementDescriptor, XmlContext)}.\n\t * <p>\n\t * Note: All parents must be registered within in the same {@link XmlContext}.\n\t * </p>\n\t * \n\t * @param name\n\t * The name of the element.\n\t * @param builder\n\t * The {@link IObjectBuilder} to build and serialize this element.\n\t * @param parentElements\n\t * The {@link ElementDescriptor}s of the parent elements to register the new element with.\n\t * @return The {@link ElementDescriptor}.\n\t */\n\tpublic static <T> ElementDescriptor<T> registerWithParents(String name, IObjectBuilder<T> builder, ElementDescriptor<?>... parentElements)\n\t{\n\t\treturn registerWithParents(QualifiedName.get(name), builder, parentElements);\n\t}\n\n\n\t/**\n\t * Register an element with the given {@link QualifiedName} using the given {@link IObjectBuilder} in the context of the given parent\n\t * {@link ElementDescriptor}s. An element that is registered with this method will not be available in a general {@link XmlContext}, but only when providing\n\t * the parent {@link ElementDescriptor} using {@link #get(QualifiedName, ElementDescriptor)} or {@link #get(QualifiedName, ElementDescriptor, XmlContext)}.\n\t * <p>\n\t * Note: All parents must be registered within in the same {@link XmlContext}.\n\t * </p>\n\t * \n\t * @param qname\n\t * The {@link QualifiedName} of the element.\n\t * @param builder\n\t * The {@link IObjectBuilder} to build and serialize this element.\n\t * @param parentElements\n\t * The {@link ElementDescriptor}s of the parent elements to register the new element with.\n\t * @return The {@link ElementDescriptor}.\n\t */\n\tpublic static <T> ElementDescriptor<T> registerWithParents(QualifiedName qname, IObjectBuilder<T> builder, ElementDescriptor<?>... parentElements)\n\t{\n\t\tif (parentElements == null || parentElements.length == 0)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"no parent elements provided\");\n\t\t}\n\n\t\t// create the new descriptor with the context of the first parent\n\t\tElementDescriptor<T> descriptor = new ElementDescriptor<T>(qname, builder, parentElements[0].getContext());\n\n\t\t// register the descriptor with all parents\n\t\tfor (ElementDescriptor<?> parentElement : parentElements)\n\t\t{\n\t\t\tif (descriptor.getContext() != parentElement.getContext())\n\t\t\t{\n\t\t\t\tthrow new IllegalArgumentException(\"Parent descriptors don't belong to the same XmlContext\");\n\t\t\t}\n\t\t\tMap<QualifiedName, ElementDescriptor<?>> descriptorMap = parentElement.mElementContext;\n\n\t\t\tif (descriptorMap == null)\n\t\t\t{\n\t\t\t\tdescriptorMap = parentElement.mElementContext = Collections.synchronizedMap(new HashMap<QualifiedName, ElementDescriptor<?>>(8));\n\t\t\t}\n\t\t\telse if (descriptorMap.containsKey(qname))\n\t\t\t{\n\t\t\t\tthrow new IllegalStateException(\"descriptor for \" + qname + \" already exists in parent \" + parentElement.qualifiedName);\n\t\t\t}\n\n\t\t\tdescriptorMap.put(qname, descriptor);\n\t\t}\n\t\treturn descriptor;\n\t}\n\n\n\tpublic static <T> ElementDescriptor<T> overload(ElementDescriptor<? super T> oldDescriptor, IObjectBuilder<T> builder)\n\t{\n\t\tXmlContext context = oldDescriptor.mContext.get();\n\t\tif (context == null)\n\t\t{\n\t\t\tthrow new IllegalStateException(\"can not overload element in gc'ed context\");\n\t\t}\n\n\t\tsynchronized (context)\n\t\t{\n\t\t\tMap<QualifiedName, ElementDescriptor<?>> descriptorMap = context.DESCRIPTOR_MAP;\n\t\t\tQualifiedName qname = oldDescriptor.qualifiedName;\n\t\t\tElementDescriptor<T> descriptor = new ElementDescriptor<T>(qname, builder, context);\n\n\t\t\t// both elements have the same child descriptors, if any\n\t\t\tdescriptor.mElementContext = oldDescriptor.mElementContext;\n\t\t\tdescriptorMap.put(qname, descriptor);\n\t\t\treturn descriptor;\n\t\t}\n\t}\n\n\n\tprivate ElementDescriptor(QualifiedName qname, IObjectBuilder<T> builder, XmlContext context)\n\t{\n\t\tif (qname == null)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"qname must not be null\");\n\t\t}\n\n\t\tthis.qualifiedName = qname;\n\t\tthis.builder = builder;\n\t\tthis.mContext = new WeakReference<XmlContext>(context);\n\t}\n\n\n\tpublic XmlContext getContext()\n\t{\n\t\treturn mContext.get();\n\t}\n\n\n\t@Override\n\tpublic int hashCode()\n\t{\n\t\treturn qualifiedName.hashCode();\n\t}\n\n\n\t@Override\n\tpublic boolean equals(Object o)\n\t{\n\t\treturn o == this;\n\t}\n}",
"public final class QualifiedName\n{\n\t/**\n\t * A cache of all known {@link QualifiedName}s. This is a map of namespaces to a map of names (in the respective name space) to the {@link QualifiedName}\n\t * object.\n\t */\n\tprivate final static Map<String, Map<String, QualifiedName>> QUALIFIED_NAME_CACHE = new HashMap<String, Map<String, QualifiedName>>(64);\n\n\t/**\n\t * The namespace of this qualified name.\n\t */\n\tpublic final String namespace;\n\n\t/**\n\t * The name part of this qualified name.\n\t */\n\tpublic final String name;\n\n\t/**\n\t * The cached hash code.\n\t */\n\tprivate final int mHashCode;\n\n\n\t/**\n\t * Returns a {@link QualifiedName} with an empty name space. If the {@link QualifiedName} already exists, the existing instance is returned, otherwise it's\n\t * created.\n\t * \n\t * @param name\n\t * The name of the {@link QualifiedName}.\n\t * @return The {@link QualifiedName} instance.\n\t */\n\tpublic static QualifiedName get(String name)\n\t{\n\t\treturn get(null, name);\n\t}\n\n\n\t/**\n\t * Returns a {@link QualifiedName} with a specific name space. If the {@link QualifiedName} already exists, the existing instance is returned, otherwise\n\t * it's created.\n\t * \n\t * @param namespace\n\t * The namespace of the {@link QualifiedName}.\n\t * @param name\n\t * The name of the {@link QualifiedName}.\n\t * @return The {@link QualifiedName} instance.\n\t */\n\tpublic static QualifiedName get(String namespace, String name)\n\t{\n\t\tif (namespace != null && namespace.length() == 0)\n\t\t{\n\t\t\tnamespace = null;\n\t\t}\n\n\t\tsynchronized (QUALIFIED_NAME_CACHE)\n\t\t{\n\t\t\tMap<String, QualifiedName> qualifiedNameMap = QUALIFIED_NAME_CACHE.get(namespace);\n\t\t\tQualifiedName qualifiedName;\n\t\t\tif (qualifiedNameMap == null)\n\t\t\t{\n\t\t\t\tqualifiedNameMap = new HashMap<String, QualifiedName>();\n\t\t\t\tqualifiedName = new QualifiedName(namespace, name);\n\t\t\t\tqualifiedNameMap.put(name, qualifiedName);\n\t\t\t\tQUALIFIED_NAME_CACHE.put(namespace, qualifiedNameMap);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tqualifiedName = qualifiedNameMap.get(name);\n\t\t\t\tif (qualifiedName == null)\n\t\t\t\t{\n\t\t\t\t\tqualifiedName = new QualifiedName(namespace, name);\n\t\t\t\t\tqualifiedNameMap.put(name, qualifiedName);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn qualifiedName;\n\t\t}\n\t}\n\n\n\t/**\n\t * Instantiate a new {@link QualifiedName} with the given name and namespace.\n\t * \n\t * @param namespace\n\t * The namespace of the qualified name.\n\t * @param name\n\t * The name part of the qualified name.\n\t */\n\tprivate QualifiedName(String namespace, String name)\n\t{\n\t\tif (name == null)\n\t\t{\n\t\t\tthrow new IllegalArgumentException(\"name part of a qualified name must not be null\");\n\t\t}\n\n\t\tthis.namespace = namespace;\n\t\tthis.name = name;\n\n\t\tmHashCode = namespace == null ? name.hashCode() : namespace.hashCode() * 31 + name.hashCode();\n\t}\n\n\n\t@Override\n\tpublic int hashCode()\n\t{\n\t\treturn mHashCode;\n\t}\n\n\n\t@Override\n\tpublic boolean equals(Object o)\n\t{\n\t\treturn o == this;\n\t}\n\n\n\t@Override\n\tpublic String toString()\n\t{\n\t\treturn namespace == null ? name : namespace + \":\" + name;\n\t}\n\n\n\t/**\n\t * Returns the qualified name in Clark notation.\n\t * \n\t * @return A {@link String} representing the qualified name.\n\t * \n\t * @see <a href=\"https://tools.ietf.org/html/draft-saintandre-json-namespaces-00\">JavaScript Object Notation (JSON) Namespaces</a>\n\t */\n\tpublic String toClarkString()\n\t{\n\t\treturn namespace == null ? name : \"{\" + namespace + \"}\" + name;\n\t}\n}",
"public class XmlContext\n{\n\tfinal Map<QualifiedName, ElementDescriptor<?>> DESCRIPTOR_MAP = new HashMap<QualifiedName, ElementDescriptor<?>>(32);\n}",
"public class ParserContext\n{\n\n\t/**\n\t * A cache of recycled objects. We cache one object per {@link ElementDescriptor}.\n\t */\n\tprivate final Map<ElementDescriptor<?>, Object> mRecycledObjects = new HashMap<ElementDescriptor<?>, Object>(32);\n\n\tprivate List<Map<ElementDescriptor<?>, Object>> mState;\n\n\t/**\n\t * The current {@link XmlPullParser} instance.\n\t */\n\tprivate XmlPullParser mParser;\n\n\tprivate XmlObjectPull mObjectPullParser;\n\n\n\t/**\n\t * Set the current {@link XmlObjectPull} parser this instance belongs to.\n\t * \n\t * @param objectPullParser\n\t */\n\tvoid setObjectPullParser(XmlObjectPull objectPullParser)\n\t{\n\t\tmObjectPullParser = objectPullParser;\n\t}\n\n\n\t/**\n\t * Set the current {@link XmlPullParser} instance.\n\t * \n\t * @param parser\n\t * The current {@link XmlPullParser}.\n\t */\n\tvoid setXmlPullParser(XmlPullParser parser)\n\t{\n\t\tmParser = parser;\n\t}\n\n\n\t/**\n\t * Returns the current {@link XmlPullParser} instance. You MUST NOT change the state of the parser, so don't call {@link XmlPullParser#next()},\n\t * {@link XmlPullParser#nextTag()}, {@link XmlPullParser#nextText()} or {@link XmlPullParser#nextToken()}.\n\t * \n\t * @return The current {@link XmlPullParser} instance.\n\t */\n\tpublic XmlPullParser getXmlPullParser()\n\t{\n\t\treturn mParser;\n\t}\n\n\n\t/**\n\t * Recycle the given object. The basic implementation will store only one recycled object instance per {@link ElementDescriptor} in the recycler.\n\t * \n\t * @param descriptor\n\t * The {@link ElementDescriptor} of the XML element\n\t * @param object\n\t * The object to recycle.\n\t */\n\tpublic <T> void recycle(ElementDescriptor<T> descriptor, T object)\n\t{\n\t\tif (object != null)\n\t\t{\n\t\t\tmRecycledObjects.put(descriptor, object);\n\t\t}\n\t}\n\n\n\t/**\n\t * Get a recycled instance. If there was no instance in the recycler this method returns <code>null</code>.\n\t * <p>\n\t * <stong>Note:</strong> The object is returned exactly as passed to {@link #recycle(ElementDescriptor, Object)}, so you need to ensure you reset the state\n\t * yourself.\n\t * </p>\n\t * \n\t * @param descriptor\n\t * The {@link ElementDescriptor} for which to return a recycled object.\n\t * @return a recycled object or <code>null</code> if there is none.\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T> T getRecycled(ElementDescriptor<T> descriptor)\n\t{\n\t\t// we can safely cast here, because we know that recycle always puts the right type\n\t\treturn (T) mRecycledObjects.remove(descriptor);\n\t}\n\n\n\t/**\n\t * Stores a state object for the current element and depth. Only elements with the same {@link ElementDescriptor} at the same depth can retrieve this state\n\t * object through {@link #getState()}.\n\t * <p>\n\t * Builders should recycle the state object whenever possible.\n\t * </p>\n\t * \n\t * @param object\n\t * The state object to store or <code>null</code> to free this object.\n\t */\n\tpublic void setState(Object object)\n\t{\n\t\tMap<ElementDescriptor<?>, Object> depthStateMap = getDepthStateMap(mObjectPullParser.getCurrentDepth(), true);\n\n\t\tElementDescriptor<?> currentDescriptor = mObjectPullParser.getCurrentElementDescriptor();\n\t\tdepthStateMap.put(currentDescriptor, object);\n\t}\n\n\n\t/**\n\t * Get the state object of the current element. The object must have been set by {@link #setState(Object)}.\n\t * \n\t * @return An {@link Object} or <code>null</code> if there is no state object.\n\t */\n\tpublic Object getState()\n\t{\n\t\tMap<ElementDescriptor<?>, Object> stateMap = getDepthStateMap(mObjectPullParser.getCurrentDepth(), false);\n\t\tif (stateMap == null)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\n\t\tElementDescriptor<?> currentDescriptor = mObjectPullParser.getCurrentElementDescriptor();\n\t\treturn stateMap.get(currentDescriptor);\n\t}\n\n\n\t/**\n\t * Return the element state map for the given depth, creating non-existing maps if required.\n\t * \n\t * @param depth\n\t * The depth for which to retrieve the state map.\n\t * @param create\n\t * <code>true</code> to create a new map if it doesn't exist.\n\t * @return\n\t */\n\tprivate Map<ElementDescriptor<?>, Object> getDepthStateMap(int depth, boolean create)\n\t{\n\t\tif (mState == null)\n\t\t{\n\t\t\tmState = new ArrayList<Map<ElementDescriptor<?>, Object>>(Math.max(16, depth + 8));\n\t\t}\n\n\t\t// fill array list with null values up to the current depth\n\t\twhile (depth > mState.size())\n\t\t{\n\t\t\tmState.add(null);\n\t\t}\n\n\t\tMap<ElementDescriptor<?>, Object> map = mState.get(depth - 1 /* depth is at least 1 */);\n\n\t\tif (!create || map != null)\n\t\t{\n\t\t\treturn map;\n\t\t}\n\n\t\t// map is null and we shall create it\n\t\tmap = new HashMap<ElementDescriptor<?>, Object>(8);\n\t\tmState.set(depth - 1, map);\n\t\treturn map;\n\t}\n\n}",
"public class XmlObjectPullParserException extends Exception\n{\n\n\t/**\n\t * Generated serial ID.\n\t */\n\tprivate static final long serialVersionUID = 7963991276367967034L;\n\n\n\tpublic XmlObjectPullParserException()\n\t{\n\t\tsuper();\n\t}\n\n\n\tpublic XmlObjectPullParserException(String message)\n\t{\n\t\tsuper(message);\n\t}\n\n\n\tpublic XmlObjectPullParserException(String message, Throwable cause)\n\t{\n\t\tsuper(message, cause);\n\t}\n\n}",
"public class SerializerContext\n{\n\t/**\n\t * The {@link XmlContext}.\n\t */\n\tXmlContext xmlContext;\n\n\t/**\n\t * The actual serializer.\n\t */\n\tXmlSerializer serializer;\n\n\t/**\n\t * A set of known name spaces.\n\t */\n\tSet<String> knownNamespaces;\n\n\n\tpublic SerializerContext(XmlContext xmlContext) throws SerializerException\n\t{\n\t\tthis.xmlContext = xmlContext;\n\t\ttry\n\t\t{\n\t\t\tthis.serializer = XmlPullParserFactory.newInstance().newSerializer();\n\t\t}\n\t\tcatch (XmlPullParserException e)\n\t\t{\n\t\t\tthrow new SerializerException(\"can't get serializer\", e);\n\t\t}\n\t}\n\n\n\t/**\n\t * Returns the current {@link XmlContext}.\n\t * \n\t * @return The {@link XmlContext}, never <code>null</code>.\n\t */\n\tpublic XmlContext getXmlContext()\n\t{\n\t\treturn xmlContext;\n\t}\n}",
"public class SerializerException extends Exception\n{\n\t/**\n\t * Generated serial ID.\n\t */\n\tprivate static final long serialVersionUID = -3185565961108391727L;\n\n\n\tpublic SerializerException(String message)\n\t{\n\t\tsuper(message);\n\t}\n\n\n\tpublic SerializerException(String message, Throwable cause)\n\t{\n\t\tsuper(message, cause);\n\t}\n}",
"public interface IXmlChildWriter\n{\n\t/**\n\t * Add the given child element to the current element.\n\t * \n\t * @param descriptor\n\t * The descriptor of the child to add.\n\t * @param child\n\t * The child object.\n\t * @param serializerContext\n\t * The current {@link SerializerContext}.\n\t * @throws SerializerException\n\t * @throws IOException\n\t */\n\tpublic <T> void writeChild(ElementDescriptor<T> descriptor, T child, SerializerContext serializerContext) throws SerializerException, IOException;\n\n\n\t/**\n\t * Add a text node to the current element.\n\t * \n\t * @param text\n\t * The text to write.\n\t * @param serializerContext\n\t * The current {@link SerializerContext}.\n\t * @throws SerializerException\n\t * @throws IOException\n\t */\n\tpublic void writeText(String text, SerializerContext serializerContext) throws SerializerException, IOException;\n}"
] | import java.io.IOException;
import org.dmfs.xmlobjects.ElementDescriptor;
import org.dmfs.xmlobjects.QualifiedName;
import org.dmfs.xmlobjects.XmlContext;
import org.dmfs.xmlobjects.pull.ParserContext;
import org.dmfs.xmlobjects.pull.XmlObjectPullParserException;
import org.dmfs.xmlobjects.serializer.SerializerContext;
import org.dmfs.xmlobjects.serializer.SerializerException;
import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; | /*
* Copyright (C) 2014 Marten Gajda <[email protected]>
*
* 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.dmfs.xmlobjects.builder;
/**
* A builder that just returns one of its child elements. It always returns the last child with the given {@link ElementDescriptor} or {@link IObjectBuilder}.
* It's handy in cases like this, when the parent element can have only one child element of a specific type:
*
* <pre>
* <location><href>http://example.com</href></location>
* </pre>
*
* <p>
* <strong>Note:</strong> Serialization requires that either an {@link ElementDescriptor} is provided or the child element is a {@link QualifiedName}s.
* </p>
*
* <p>
* Please be aware that the child object is not serialized if the object is <code>null</code>.
* </p>
*
* @author Marten Gajda <[email protected]>
*/
public class TransientObjectBuilder<T> extends AbstractObjectBuilder<T>
{
/**
* The descriptor of the child element to pass through.
*/
private final ElementDescriptor<T> mChildDescriptor;
private final IObjectBuilder<T> mChildBuilder;
public TransientObjectBuilder(ElementDescriptor<T> childDescriptor)
{
mChildDescriptor = childDescriptor;
mChildBuilder = null;
}
public TransientObjectBuilder(IObjectBuilder<T> childBuilder)
{
mChildDescriptor = null;
mChildBuilder = childBuilder;
}
@SuppressWarnings("unchecked")
@Override | public <V> T update(ElementDescriptor<T> descriptor, T object, ElementDescriptor<V> childDescriptor, V child, ParserContext context) | 3 |
hiBrianLee/AndroidMvvm | sample/src/main/java/com/hibrianlee/sample/mvvm/fragment/AndroidVersionsFragment.java | [
"public abstract class ViewModelFragment extends Fragment {\n\n private static final String EXTRA_VIEW_MODEL_STATE = \"viewModelState\";\n\n private ViewModel viewModel;\n\n protected void inject(AppComponent appComponent) {\n appComponent.inject(this);\n }\n\n @Nullable\n protected abstract ViewModel createAndBindViewModel(View root,\n @NonNull ActivityComponent activityComponent,\n @Nullable ViewModel.State savedViewModelState);\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n AppComponent appComponent =\n ((MvvmApplication) getActivity().getApplication()).getAppComponent();\n inject(appComponent);\n }\n\n @Override\n public void onActivityCreated(@Nullable Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n ViewModel.State savedViewModelState = null;\n if (savedInstanceState != null) {\n savedViewModelState = savedInstanceState.getParcelable(EXTRA_VIEW_MODEL_STATE);\n }\n ViewModelActivity activity = (ViewModelActivity) getActivity();\n viewModel = createAndBindViewModel(getView(), activity.getActivityComponent(),\n savedViewModelState);\n }\n\n @Override\n public void onStart() {\n super.onStart();\n if (viewModel != null) {\n viewModel.onStart();\n }\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n if (viewModel != null) {\n outState.putParcelable(EXTRA_VIEW_MODEL_STATE, viewModel.getInstanceState());\n }\n }\n\n @Override\n public void onStop() {\n super.onStop();\n if (viewModel != null) {\n viewModel.onStop();\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 abstract class ViewModel extends BaseObservable {\n\n @Inject\n @AppContext\n protected Context appContext;\n\n @Inject\n protected AttachedActivity attachedActivity;\n\n protected ViewModel(@NonNull ActivityComponent activityComponent,\n @Nullable State savedInstanceState) {\n activityComponent.inject(this);\n }\n\n @CallSuper\n public void onStart() {\n\n }\n\n public State getInstanceState() {\n return new State(this);\n }\n\n @CallSuper\n public void onStop() {\n\n }\n\n public static class State implements Parcelable {\n\n protected State(ViewModel viewModel) {\n\n }\n\n public State(Parcel in) {\n\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @CallSuper\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n\n }\n\n public static Creator<State> CREATOR = new Creator<State>() {\n @Override\n public State createFromParcel(Parcel source) {\n return new State(source);\n }\n\n @Override\n public State[] newArray(int size) {\n return new State[size];\n }\n };\n }\n}",
"public class AndroidVersionsAdapter\n extends RecyclerViewAdapter<AndroidVersion, AndroidVersionItemViewModel> {\n\n private final ViewModelFactory viewModelFactory;\n\n public AndroidVersionsAdapter(ViewModelFactory viewModelFactory,\n @NonNull ActivityComponent activityComponent) {\n super(activityComponent);\n this.viewModelFactory = viewModelFactory;\n }\n\n @Override\n public AndroidVersionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View itemView = LayoutInflater.from(parent.getContext())\n .inflate(R.layout.item_android_version, parent, false);\n\n AndroidVersionItemViewModel viewModel =\n viewModelFactory.createAndroidVersionItemViewModel(getActivityComponent());\n\n ItemAndroidVersionBinding binding = ItemAndroidVersionBinding.bind(itemView);\n binding.setViewModel(viewModel);\n\n return new AndroidVersionViewHolder(itemView, binding, viewModel);\n }\n\n public void setItems(ArrayList<AndroidVersion> newItems) {\n items.clear();\n items.addAll(newItems);\n notifyDataSetChanged();\n }\n\n public ArrayList<AndroidVersion> getItems() {\n return items;\n }\n\n static class AndroidVersionViewHolder\n extends ItemViewHolder<AndroidVersion, AndroidVersionItemViewModel> {\n\n public AndroidVersionViewHolder(View itemView, ViewDataBinding binding,\n AndroidVersionItemViewModel viewModel) {\n super(itemView, binding, viewModel);\n ButterKnife.bind(this, itemView);\n }\n\n @OnClick(R.id.versionItem)\n void onClickVersionItem() {\n viewModel.onClick();\n }\n }\n}",
"public class AndroidVersionsViewModel extends RecyclerViewViewModel {\n\n AndroidVersionsAdapter adapter;\n\n AndroidVersionsViewModel(@NonNull AndroidVersionsAdapter adapter,\n @NonNull ActivityComponent activityComponent,\n @Nullable State savedInstanceState) {\n super(activityComponent, savedInstanceState);\n\n ArrayList<AndroidVersion> versions;\n if (savedInstanceState instanceof AndroidVersionsState) {\n versions = ((AndroidVersionsState) savedInstanceState).versions;\n } else {\n versions = getVersions();\n }\n this.adapter = adapter;\n adapter.setItems(versions);\n }\n\n @Override\n protected RecyclerViewAdapter getAdapter() {\n return adapter;\n }\n\n @Override\n protected RecyclerView.LayoutManager createLayoutManager() {\n return new LinearLayoutManager(appContext);\n }\n\n @Override\n public RecyclerViewViewModelState getInstanceState() {\n return new AndroidVersionsState(this);\n }\n\n public void onClickHiBrianLee() {\n try {\n attachedActivity.openUrl(appContext.getString(R.string.twitter_url));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private ArrayList<AndroidVersion> getVersions() {\n ArrayList<AndroidVersion> versions = new ArrayList<>();\n versions.add(new AndroidVersion(\"Cupcake\", \"Android 1.5\"));\n versions.add(new AndroidVersion(\"Donut\", \"Android 1.6\"));\n versions.add(new AndroidVersion(\"Eclair\", \"Android 2.0-2.1\"));\n versions.add(new AndroidVersion(\"Froyo\", \"Android 2.2\"));\n versions.add(new AndroidVersion(\"Gingerbread\", \"Android 2.3\"));\n versions.add(new AndroidVersion(\"Honeycomb\", \"Android 3.0-3.2\"));\n versions.add(new AndroidVersion(\"Ice Cream Sandwich\", \"Android 4.0\"));\n versions.add(new AndroidVersion(\"Jelly Bean\", \"Android 4.1-4.3\"));\n versions.add(new AndroidVersion(\"KitKat\", \"Android 4.4\"));\n versions.add(new AndroidVersion(\"Lollipop\", \"Android 5.0-5.1\"));\n versions.add(new AndroidVersion(\"Marshmallow\", \"Android 6.0\"));\n return versions;\n }\n\n private static class AndroidVersionsState extends RecyclerViewViewModelState {\n\n private final ArrayList<AndroidVersion> versions;\n\n public AndroidVersionsState(AndroidVersionsViewModel viewModel) {\n super(viewModel);\n versions = viewModel.adapter.getItems();\n }\n\n public AndroidVersionsState(Parcel in) {\n super(in);\n versions = in.createTypedArrayList(AndroidVersion.CREATOR);\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n super.writeToParcel(dest, flags);\n dest.writeTypedList(versions);\n }\n\n public static Creator<AndroidVersionsState> CREATOR = new Creator<AndroidVersionsState>() {\n @Override\n public AndroidVersionsState createFromParcel(Parcel source) {\n return new AndroidVersionsState(source);\n }\n\n @Override\n public AndroidVersionsState[] newArray(int size) {\n return new AndroidVersionsState[size];\n }\n };\n }\n}"
] | import butterknife.ButterKnife;
import butterknife.OnClick;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hibrianlee.mvvmapp.fragment.ViewModelFragment;
import com.hibrianlee.mvvmapp.inject.ActivityComponent;
import com.hibrianlee.mvvmapp.viewmodel.ViewModel;
import com.hibrianlee.sample.mvvm.R;
import com.hibrianlee.sample.mvvm.adapter.AndroidVersionsAdapter;
import com.hibrianlee.sample.mvvm.databinding.FragmentAndroidVersionsBinding;
import com.hibrianlee.sample.mvvm.viewmodel.AndroidVersionsViewModel; | /*
* 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.fragment;
public class AndroidVersionsFragment extends BaseFragment {
private AndroidVersionsViewModel androidVersionsViewModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_android_versions, container, false);
ButterKnife.bind(this, root);
return root;
}
@Nullable
@Override
protected ViewModel createAndBindViewModel(View root, | @NonNull ActivityComponent activityComponent, | 1 |
mmonkey/Destinations | src/main/java/com/github/mmonkey/destinations/commands/BringCommand.java | [
"public class PlayerTeleportBringEvent extends AbstractPlayerTeleportEvent implements PlayerTeleportEvent.Bring {\n\n /**\n * PlayerTeleportBringEvent constructor\n *\n * @param player Player\n * @param location Location\n * @param rotation Vector3d\n */\n public PlayerTeleportBringEvent(Player player, Location<World> location, Vector3d rotation) {\n super(player, location, rotation);\n }\n}",
"public class PlayerTeleportPreEvent extends AbstractPlayerTeleportEvent implements PlayerTeleportEvent.Pre {\n\n /**\n * PlayerTeleportPreEvent constructor\n *\n * @param player Player\n * @param location Location\n * @param rotation Vector3d\n */\n public PlayerTeleportPreEvent(Player player, Location<World> location, Vector3d rotation) {\n super(player, location, rotation);\n }\n\n}",
"public class TeleportationService {\n\n public static final TeleportationService instance = new TeleportationService();\n private final Map<Transaction, Timestamp> transactions = new ConcurrentHashMap<>();\n private final int expires;\n\n /**\n * TeleportationService constructor\n */\n private TeleportationService() {\n expires = DestinationsConfig.getTeleportRequestExpiration();\n this.startCleanupTask();\n }\n\n /**\n * TeleportationService.Transaction class\n */\n private class Transaction {\n private Player caller;\n private Player target;\n\n /**\n * @return Player\n */\n Player getCaller() {\n return this.caller;\n }\n\n /**\n * @return Player\n */\n Player getTarget() {\n return this.target;\n }\n\n /**\n * CallModel constructor\n *\n * @param caller Player\n * @param target Player\n */\n Transaction(Player caller, Player target) {\n Preconditions.checkNotNull(caller);\n Preconditions.checkNotNull(target);\n\n this.caller = caller;\n this.target = target;\n }\n }\n\n /**\n * Start the teleportationCleanupTask\n */\n private void startCleanupTask() {\n Sponge.getScheduler().createTaskBuilder()\n .interval(1, TimeUnit.SECONDS)\n .name(\"teleportationCleanupTask\")\n .execute(this::cleanup)\n .submit(Destinations.getInstance());\n }\n\n /**\n * Cleanup teleportation transactions\n */\n private void cleanup() {\n Timestamp now = new Timestamp(System.currentTimeMillis());\n\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (now.after(call.getValue())) {\n this.expiredNotification(call.getKey().getCaller(), call.getKey().getTarget());\n this.transactions.remove(call.getKey());\n }\n }\n }\n\n /**\n * Send teleportation request expiration notices to players\n *\n * @param caller Player\n * @param target Player\n */\n private void expiredNotification(Player caller, Player target) {\n Optional<Player> optionalCaller = Sponge.getServer().getPlayer(caller.getUniqueId());\n Optional<Player> optionalTarget = Sponge.getServer().getPlayer(target.getUniqueId());\n\n optionalCaller.ifPresent(player -> player.sendMessage(MessagesUtil.warning(player, \"call.request_expire_to\", target.getName())));\n optionalTarget.ifPresent(player -> player.sendMessage(MessagesUtil.warning(player, \"call.request_expire_from\", caller.getName())));\n }\n\n /**\n * Add a call transaction\n *\n * @param caller Player\n * @param target Player\n */\n public void call(Player caller, Player target) {\n Transaction call = new Transaction(caller, target);\n Timestamp expireTime = new Timestamp(System.currentTimeMillis() + this.expires * 1000);\n this.transactions.put(call, expireTime);\n }\n\n /**\n * Remove a call transaction\n *\n * @param caller Player\n * @param target Player\n */\n public void removeCall(Player caller, Player target) {\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (call.getKey().getCaller().getUniqueId().equals(caller.getUniqueId())\n && call.getKey().getTarget().getUniqueId().equals(target.getUniqueId())) {\n this.transactions.remove(call.getKey());\n }\n }\n }\n\n /**\n * Get the first caller from this player's current calls\n *\n * @param target Player\n * @return Player\n */\n public Player getFirstCaller(Player target) {\n Player caller = null;\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (call.getKey().getTarget().getUniqueId().equals(target.getUniqueId())) {\n caller = call.getKey().getCaller();\n }\n }\n\n return caller;\n }\n\n /**\n * Get the total number of current callers\n *\n * @param target Player\n * @return int\n */\n public int getNumCallers(Player target) {\n int callers = 0;\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (call.getKey().getTarget().getUniqueId().equals(target.getUniqueId())) {\n callers++;\n }\n }\n\n return callers;\n }\n\n /**\n * Get the current list of callers\n *\n * @param target Player\n * @return List<String>\n */\n public List<String> getCalling(Player target) {\n List<String> list = new ArrayList<>();\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (call.getKey().getTarget().getUniqueId().equals(target.getUniqueId())) {\n list.add(call.getKey().getCaller().getName());\n }\n }\n\n return list;\n }\n\n /**\n * Get whether or not a Player is currently waiting for a call reply\n *\n * @param caller Player\n * @param target Player\n * @return bool\n */\n public boolean isCalling(Player caller, Player target) {\n\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (call.getKey().getTarget().getUniqueId().equals(target.getUniqueId())\n && call.getKey().getCaller().getUniqueId().equals(caller.getUniqueId())) {\n return true;\n }\n }\n\n return false;\n }\n}",
"public class FormatUtil {\n\t\n\tpublic static final int COMMAND_WINDOW_LENGTH = 53;\n\t\n\t// Message Levels\n\tpublic static final TextColor SUCCESS = TextColors.GREEN;\n\tpublic static final TextColor WARN = TextColors.GOLD;\n\tpublic static final TextColor ERROR = TextColors.RED;\n\tpublic static final TextColor INFO = TextColors.WHITE;\n\tpublic static final TextColor DIALOG = TextColors.GRAY;\n\t\n\t// Object Levels\n\tpublic static final TextColor OBJECT = TextColors.GOLD;\n\tpublic static final TextColor DELETED_OBJECT = TextColors.RED;\n\t\n\t// Links\n\tpublic static final TextColor CANCEL = TextColors.RED;\n\tpublic static final TextColor DELETE = TextColors.RED;\n\tpublic static final TextColor CONFIRM = TextColors.GREEN;\n\tpublic static final TextColor GENERIC_LINK = TextColors.DARK_AQUA;\n\t\n\t//Other\n\tpublic static final TextColor HEADLINE = TextColors.DARK_GREEN;\n\t\n\tpublic static Text empty() {\n\t\t\n\t\tText.Builder text = Text.builder();\n\t\tfor (int i = 0; i < 20; i++) {\n\t\t\ttext.append(Text.NEW_LINE);\n\t\t}\n\t\t\n\t\treturn text.build();\n\t\t\n\t}\n\t\n\tpublic static String getFill(int length, char fill) {\n\t\treturn new String(new char[length]).replace('\\0', fill);\n\t}\n\t\n\tpublic static String getFill(int length) {\n\t\treturn new String(new char[length]).replace('\\0', ' ');\n\t}\n\t\n\tpublic FormatUtil(){\n\t}\n\n}",
"public class MessagesUtil {\n\n /**\n * Get the message associated with this key, for this player's locale\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text get(Player player, String key, Object... args) {\n ResourceBundle messages = PlayerCache.instance.getResourceCache(player);\n return messages.containsKey(key) ? Text.of(String.format(messages.getString(key), args)) : Text.EMPTY;\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as a success (green).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text success(Player player, String key, Object... args) {\n return Text.of(TextColors.GREEN, get(player, key, args));\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as a warning (gold).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text warning(Player player, String key, Object... args) {\n return Text.of(TextColors.GOLD, get(player, key, args));\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as an error (red).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text error(Player player, String key, Object... args) {\n return Text.of(TextColors.RED, get(player, key, args));\n }\n\n}"
] | import com.github.mmonkey.destinations.events.PlayerTeleportBringEvent;
import com.github.mmonkey.destinations.events.PlayerTeleportPreEvent;
import com.github.mmonkey.destinations.teleportation.TeleportationService;
import com.github.mmonkey.destinations.utilities.FormatUtil;
import com.github.mmonkey.destinations.utilities.MessagesUtil;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.service.pagination.PaginationService;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextStyles;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList; | package com.github.mmonkey.destinations.commands;
public class BringCommand implements CommandExecutor {
public static final String[] ALIASES = {"bring", "tpaccept", "tpyes"};
/**
* Get the Command Specifications for this command
*
* @return CommandSpec
*/
public static CommandSpec getCommandSpec() {
return CommandSpec.builder()
.permission("destinations.tpa")
.description(Text.of("/bring [player] or /tpaccept [player] or /tpyes [player]"))
.extendedDescription(Text.of("Teleports a player that has issued a call request to your current location."))
.executor(new BringCommand())
.arguments(GenericArguments.optional(GenericArguments.firstParsing(GenericArguments.player(Text.of("player")))))
.build();
}
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
if (!(src instanceof Player)) {
return CommandResult.empty();
}
Player target = (Player) src;
Player caller = args.getOne("player").isPresent() ? (Player) args.getOne("player").get() : null;
if (caller == null) {
int numCallers = TeleportationService.instance.getNumCallers(target);
switch (numCallers) {
case 0:
target.sendMessage(MessagesUtil.error(target, "bring.empty"));
return CommandResult.success();
case 1:
Player calling = TeleportationService.instance.getFirstCaller(target);
return executeBring(calling, target);
default:
return listCallers(target, args);
}
}
if (TeleportationService.instance.isCalling(caller, target)) {
return executeBring(caller, target);
}
target.sendMessage(MessagesUtil.error(target, "bring.not_found", caller.getName()));
return CommandResult.success();
}
private CommandResult listCallers(Player target, CommandContext args) {
List<String> callList = TeleportationService.instance.getCalling(target);
List<Text> list = new CopyOnWriteArrayList<>();
callList.forEach(caller -> list.add(getBringAction(caller)));
PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
paginationService.builder().title(MessagesUtil.get(target, "bring.title")).contents(list).padding(Text.of("-")).sendTo(target);
return CommandResult.success();
}
private CommandResult executeBring(Player caller, Player target) {
TeleportationService.instance.removeCall(caller, target);
Sponge.getGame().getEventManager().post(new PlayerTeleportPreEvent(caller, caller.getLocation(), caller.getRotation()));
Sponge.getGame().getEventManager().post(new PlayerTeleportBringEvent(caller, target.getLocation(), target.getRotation()));
caller.sendMessage(MessagesUtil.success(caller, "bring.teleport", target.getName()));
return CommandResult.success();
}
static Text getBringAction(String name) {
return Text.builder("/bring " + name)
.onClick(TextActions.runCommand("/bring " + name)) | .onHover(TextActions.showText(Text.of(FormatUtil.DIALOG, "/bring ", FormatUtil.OBJECT, name))) | 3 |
KaloyanBogoslovov/Virtual-Trading | src/data/updating/DataUpdating.java | [
"public class Database {\n\n private static final String DBURL = \"jdbc:h2:~/test\";\n private static final String DBUSER = \"Kaloyan_Bogoslovov\";\n private static final String DBPASS = \"qwerty\";\n private static Connection connection;\n\n public static void connectingToDB() throws ClassNotFoundException, SQLException {\n Class.forName(\"org.h2.Driver\");\n connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);\n }\n\n public static void createDB() throws ClassNotFoundException, SQLException {\n Class.forName(\"org.h2.Driver\");\n Connection con = DriverManager.getConnection(\"jdbc:h2:~/test\", \"Kaloyan_Bogoslovov\", \"qwerty\");\n Statement st = con.createStatement();\n String createUsersTable =\n \"CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);\";\n String createTradesTable =\n \"CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);\";\n st.executeUpdate(createUsersTable);\n st.executeUpdate(createTradesTable);\n con.close();\n }\n\n public static ResultSet SelectDB(String data) throws SQLException {\n Statement st = connection.createStatement();\n ResultSet rs = st.executeQuery(data);\n return rs;\n }\n\n public static void insertDB(String data) throws SQLException {\n Statement st = connection.createStatement();\n st.executeUpdate(data);\n }\n\n public static void closeConnectionToDB() throws SQLException {\n connection.close();\n }\n\n}",
"public class LogFile {\n private static File customDir;\n\n public static void initPathLocationAndCreateFile() {\n try {\n String path = System.getProperty(\"user.home\") + File.separator;\n path += File.separator + \"Virtual_Trading_1.1.0_Update_LogFile.txt\";\n customDir = new File(path);\n customDir.createNewFile();\n } catch (IOException o) {\n System.out.println(\"initPathLocationAndCreateFile throws exception\");\n }\n }\n\n\n public static void saveDataToLogFile(String data) {\n try {\n FileWriter fileWriter = new FileWriter(customDir, true);\n BufferedWriter br = new BufferedWriter(fileWriter);\n PrintWriter save = new PrintWriter(br);\n String timeStamp = getTimeStamp().toString();\n save.write(timeStamp + \" \" + data + \"\\n\");\n save.close();\n } catch (IOException e) {\n System.out.println(\"saveDataToLogFile throws exception\");\n }\n }\n\n private static StringBuilder getTimeStamp() {\n DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n Calendar cal = Calendar.getInstance();\n StringBuilder date = new StringBuilder(dateFormat.format(cal.getTime()));\n return date;\n }\n\n\n}",
"public class UpdateData {\n private String name;\n private String symbol;\n private BigDecimal bid;\n private BigDecimal ask;\n\n public UpdateData() {}\n\n public UpdateData(String name, String symbol, String bid, String ask) {\n this.name = name;\n this.symbol = symbol;\n this.bid = new BigDecimal(bid);\n this.ask = new BigDecimal(ask);\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 getSymbol() {\n return symbol;\n }\n\n public void setSymbol(String symbol) {\n this.symbol = symbol;\n }\n\n public BigDecimal getBid() {\n return bid;\n }\n\n public void setBid(String bid) {\n this.bid = new BigDecimal(bid);\n }\n\n public BigDecimal getAsk() {\n return ask;\n }\n\n public void setAsk(String ask) {\n this.ask = new BigDecimal(ask);\n }\n}",
"public class UpdateDataFromYahoo extends YahooFinance {\n private String[] companies;\n private List<UpdateData> result = new ArrayList<UpdateData>();\n String[] data;\n\n public UpdateDataFromYahoo(String[] companies) {\n this.companies = companies;\n }\n\n public Object getData() {\n String url = makeURL();\n URLConnection connection = setConnectionWithYahoo(url);\n getInformationFromYahoo(connection);\n return result;\n }\n\n private String makeURL() {\n String company = \"\";\n for (int i = 0; i < companies.length - 1; i++) {\n company = company + companies[i] + \"%2C\";\n }\n company = company + companies[companies.length - 1];\n String url =\n \"http://finance.yahoo.com/d/quotes.csv?s=\" + company + \"&f=nsbal1oghpva2b4s6j4j2j1&e=.csv\";\n LogFile.saveDataToLogFile(\"URL:\" + url);\n return url;\n }\n\n private void getInformationFromYahoo(URLConnection connection) {\n try {\n InputStreamReader is = new InputStreamReader(connection.getInputStream());\n BufferedReader br = new BufferedReader(is);\n String line = br.readLine();\n addChartDataObjectsToList(line, br);\n } catch (final java.net.SocketTimeoutException e) {\n System.out.println(\"SocketTimeoutException\");\n LogFile.saveDataToLogFile(\"Exception: SocketTimeoutException\");\n new DataUpdating().dataUpdate();\n } catch (java.io.IOException e) {\n LogFile.saveDataToLogFile(\"Exception: IOException\");\n System.out.println(\"Exception: IOException\");\n e.printStackTrace();\n new DataUpdating().dataUpdate();\n }\n }\n\n private void addChartDataObjectsToList(String line, BufferedReader br) throws IOException {\n result = new ArrayList<UpdateData>();\n while (line != null) {\n System.out.println(\"Parsing:\" + line);\n LogFile.saveDataToLogFile(\"Parsing:\" + line);\n UpdateData quote = parseCSVLine(line);\n result.add(quote);\n line = br.readLine();\n }\n br.close();\n }\n\n private UpdateData parseCSVLine(String line) {\n // removing the first element '\"' to be able to get the name of the company\n line = line.substring(1);\n int iend = line.indexOf('\"');\n // getting the company name\n String companyName = line.substring(0, iend);\n line = line.substring(iend);\n data = line.split(\",\");\n data[0] = companyName;\n // if there isnt available data for sell/buy price set the price at 0\n checkDataAvailability();\n return new UpdateData(data[0], data[1], data[2], data[3]);\n }\n\n private void checkDataAvailability() {\n if (!data[2].matches(\"[0-9.]*\")) {\n data[2] = \"0\";\n }\n if (!data[3].matches(\"[0-9.]*\")) {\n data[3] = \"0\";\n }\n }\n\n\n}",
"public abstract class YahooFinance {\n public static final int CONNECTION_TIMEOUT =\n Integer.parseInt(System.getProperty(\"yahoofinance.connection.timeout\", \"10000\"));\n\n public abstract Object getData();\n\n public URLConnection setConnectionWithYahoo(String url) {\n URLConnection connection = null;\n try {\n System.out.println(\"URL:\" + url);\n URL request = new URL(url);\n connection = request.openConnection();\n connection.setConnectTimeout(CONNECTION_TIMEOUT);\n connection.setReadTimeout(CONNECTION_TIMEOUT);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return connection;\n }\n\n\n\n}"
] | import static java.util.concurrent.TimeUnit.SECONDS;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import database.Database;
import logfile.LogFile;
import yahoo.UpdateData;
import yahoo.UpdateDataFromYahoo;
import yahoo.YahooFinance; | package data.updating;
public class DataUpdating {
private BigDecimal zero = new BigDecimal(0);
private int i = 0;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private BigDecimal liveProfit = new BigDecimal(0);
public void dataUpdate() {
final Runnable beeper = new Runnable() {
public void run() {
if (userLogedIn()) {
try {
Database.connectingToDB();
String[] companies = getCompanies();
System.out.println("companies");
if (companies.length != 0) { | LogFile.saveDataToLogFile( | 1 |
feedzai/fos-core | fos-server/src/main/java/com/feedzai/fos/server/FosServer.java | [
"public class FosConfig {\n /**\n * The config fqn for factory name.\n */\n public static final String FACTORY_NAME = \"fos.factoryName\";\n /**\n * The config fqn for registry port.\n */\n public static final String REGISTRY_PORT = \"fos.registryPort\";\n /**\n * The config fqn for scoring port.\n */\n public static final String SCORING_PORT = \"fos.scoringPort\";\n /**\n * The config fqn for embedded registry.\n */\n public static final String EMBEDDED_REGISTRY = \"fos.embeddedRegistry\";\n /**\n * The config fqn for the headers.\n */\n public static final String HEADER_LOCATION = \"fos.headerLocation\";\n /**\n * The config fqn for the size of the thread pool classifier.\n */\n public static final String THREADPOOL_SIZE = \"fos.threadPoolSize\";\n\n public static final int DEFAULT_SCORING_PORT = 2534;\n\n /**\n * The configuration object that contains all the configured properties in a key value format.\n */\n private Configuration config;\n\n /**\n * Defines if the current instance should start a RMI registry or connects to an existing one.\n */\n private boolean embeddedRegistry;\n /**\n * RMI registry port (for lookup or for bind if embeddedRegistry is true)\n */\n private int registryPort;\n /**\n * The factory fqn of the {@link com.feedzai.fos.api.ManagerFactory ManagerFactory} to use.\n */\n private String factoryName;\n /**\n * The location of the model headers.\n */\n private String headerLocation;\n /**\n * The size of the thread pool classifier.\n */\n private int threadPoolSize;\n /**\n * The port to use for fast scoring.\n */\n private int scoringPort;\n\n /**\n * Creates a new instance of the {@link FosConfig} class.\n *\n * @param configuration The base configuration to use.\n */\n public FosConfig(Configuration configuration) {\n checkNotNull(configuration, \"Configuration cannot be null.\");\n checkArgument(configuration.containsKey(FACTORY_NAME), \"The configuration parameter \" + FACTORY_NAME + \" should be defined.\");\n this.config = configuration;\n this.embeddedRegistry = configuration.getBoolean(EMBEDDED_REGISTRY, false);\n this.registryPort = configuration.getInt(REGISTRY_PORT, Registry.REGISTRY_PORT);\n this.factoryName = configuration.getString(FACTORY_NAME);\n this.headerLocation = configuration.getString(HEADER_LOCATION, \"models\");\n this.threadPoolSize = configuration.getInt(THREADPOOL_SIZE, 20);\n this.scoringPort = configuration.getInt(SCORING_PORT, DEFAULT_SCORING_PORT);\n }\n\n /**\n * Gets the configuration object that contains all the configured properties in a key value format.\n *\n * @return The configuration object that contains all the configured properties in a key value format.\n */\n public Configuration getConfig() {\n return config;\n }\n\n /**\n * Gets if the current instance should start a RMI registry or connects to an existing one.\n *\n * @return {@code true} if the current instance should start a RMI registry, {@code false} to connect to an existing one.\n */\n public boolean isEmbeddedRegistry() {\n return embeddedRegistry;\n }\n\n /**\n * Gets the RMI registry port (for lookup or for bind if embeddedRegistry is true)\n *\n * @return The RMI registry port (for lookup or for bind if embeddedRegistry is true)\n */\n public int getRegistryPort() {\n return registryPort;\n }\n\n /**\n * Gets the factory fqn of the {@link com.feedzai.fos.api.ManagerFactory ManagerFactory} to use.\n *\n * @return The factory fqn of the {@link com.feedzai.fos.api.ManagerFactory ManagerFactory} to use.\n */\n public String getFactoryName() {\n return factoryName;\n }\n\n /**\n * Gets the location of the model headers.\n *\n * @return The location of the model headers.\n */\n public File getHeaderLocation() {\n return new File(headerLocation);\n }\n\n /**\n * Gets the size of the thread pool classifier.\n *\n * @return The size of the thread pool classifier.\n */\n public int getThreadPoolSize() {\n return threadPoolSize;\n }\n\n /**\n * Gets the port to use for fast scoring.\n *\n * @return The port to use for fast scoring.\n */\n public int getScoringPort() {\n return scoringPort;\n }\n\n @Override\n public String toString() {\n return Objects.toStringHelper(this).\n add(\"config\", config).\n add(\"embeddedRegistry\", embeddedRegistry).\n add(\"registryPort\", registryPort).\n add(\"factoryName\", factoryName).\n add(\"headerLocation\", headerLocation).\n add(\"threadPoolSize\", threadPoolSize).\n add(\"scoringPort\", scoringPort).\n toString();\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(config, embeddedRegistry, registryPort, factoryName, headerLocation);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n final FosConfig other = (FosConfig) obj;\n return Objects.equal(this.config, other.config) && Objects.equal(this.embeddedRegistry, other.embeddedRegistry) && Objects.equal(this.registryPort, other.registryPort) && Objects.equal(this.factoryName, other.factoryName) && Objects.equal(this.headerLocation, other.headerLocation);\n }\n}",
"@RemoteInterface(of = Manager.class)\npublic interface IRemoteManager extends Remote {\n /**\n * Adds a new model with the given configuration and using the given serialized classifier.\n *\n * @param config the configuration of the model\n * @param model the new serialized classifier\n * @return the id of the new model\n * @throws RemoteException when creating the classifier was not possible\n */\n UUID addModel(ModelConfig config, Model model) throws RemoteException, FOSException;\n\n /**\n * Adds a new model with the given configuration and using a local classifier source.\n *\n * @param config the configuration of the model\n * @param descriptor the {@link com.feedzai.fos.api.ModelDescriptor} describing the classifier\n * @return the id of the new model\n * @throws RemoteException when creating the classifier was not possible\n */\n UUID addModel(ModelConfig config, @NotBlank ModelDescriptor descriptor) throws RemoteException, FOSException;\n\n /**\n * Removes the model identified by <code>modelId</code> from the list of active scorers (does not delete classifier file).\n *\n * @param modelId the id of the model to remove\n * @throws RemoteException when removing the model was not possible\n */\n void removeModel(UUID modelId) throws RemoteException, FOSException;\n\n /**\n * Reconfigures the model identified by <code>modelId</code> with the given configuration.\n *\n * @param modelId the id of the model to update\n * @param config the new configuration of the model\n * @throws RemoteException when reconfiguring the model was not possible\n */\n void reconfigureModel(UUID modelId,ModelConfig config) throws RemoteException, FOSException;\n\n /**\n * Reconfigures the model identified by <code>modelId</code> with the given configuration.\n * <p/>\n * Reloads the model now using the classifier <code>model</code> (does not delete previous classifier file).\n *\n * @param modelId the id of the model to update\n * @param config the new configuration of the model\n * @param model the new serialized classifier\n * @throws RemoteException when reconfiguring the model was not possible\n */\n void reconfigureModel(UUID modelId,ModelConfig config, Model model) throws RemoteException, FOSException;\n\n /**\n * Reconfigures the model identified by <code>modelId</code> with the given configuration.\n * <p/>\n * Reloads the model now using the classifier in the local file <code>localFileName</code> (does not delete previous classifier file).\n *\n * @param modelId the id of the model to update\n * @param config the new configuration of the model\n * @param descriptor the {@link com.feedzai.fos.api.ModelDescriptor} describing the classifier\n * @throws RemoteException when reconfiguring the model was not possible\n */\n void reconfigureModel(UUID modelId,ModelConfig config, @NotBlank ModelDescriptor descriptor) throws RemoteException, FOSException;\n\n /**\n * Lists the models configured in the system.\n *\n * @return a map of <code>modelId</code> to model configuration\n * @throws RemoteException when listing the maps was not possible\n */\n @NotNull\n Map<UUID, ? extends ModelConfig> listModels() throws RemoteException, FOSException;\n\n /**\n * Gets a scorer loaded with all the active models.\n *\n * @return a scorer\n * @throws RemoteException when loading the scorer was not possible\n */\n @NotNull\n RemoteScorer getScorer() throws RemoteException, FOSException;\n\n /**\n * Trains a new classifier with the given configuration and using the given <code>instances</code>.\n * <p/> Automatically add the new model to the existing scorer.\n *\n * @param config the model configuration\n * @param instances the training instances\n * @return the id of the new model\n * @throws RemoteException when training was not possible\n */\n UUID trainAndAdd(ModelConfig config,List<Object[]> instances) throws RemoteException, FOSException;\n\n /**\n * Trains a new classifier with the given configuration and using the <code>instances</code>.\n * in a CSV encoded file\n * <p/> Automatically add the new model to the existing scorer.\n *\n * @param config the model configuration\n * @param path the training instances\n * @return the id of the new model\n * @throws FOSException when training was not possible\n */\n UUID trainAndAddFile(ModelConfig config,String path) throws RemoteException,FOSException;\n\n /**\n * Trains a new classifier with the given configuration and using the given <code>instances</code>.\n *\n * @param config the model configuration\n * @param instances the training instances\n * @return a serialized representation of the model\n * @throws RemoteException when training was not possible\n */\n @NotNull\n Model train(ModelConfig config,List<Object[]> instances) throws RemoteException, FOSException;\n\n /**\n * Compute the feature importance for the model.\n *\n * @param uuid The uuid of the model whose feature importance should be computed.\n * @param instances An optional set of instances that can be used to compute feature importance.\n * This set of instances should not be the ones used for training.\n * @param seed The random number generator seed.\n * @return Aan array with the feature importance, one element for each feature.\n * @throws RemoteException If there was a problem with the communication layer.\n * @throws FOSException If the underlying model does not support computing feature importance.\n * @since 1.0.9\n */\n @NotNull\n double[] featureImportance(UUID uuid, Optional<List<Object[]>> instances, long seed) throws RemoteException, FOSException;\n\n /**\n * Trains a new classifier with the given configuration and using the given <code>instances</code>.\n *\n * @param config the model configuration\n * @param path File with the training instances\n * @return a serialized representation of the model\n * @throws FOSException when training was not possible\n */\n @NotNull\n Model trainFile(ModelConfig config, String path) throws RemoteException, FOSException;\n\n /**\n * Frees any resources allocated to this manager.\n *\n * @throws RemoteException when closing resources was not possible\n */\n void close() throws RemoteException, FOSException;\n\n /**\n * Saves a UUID identified classifier to a given savepath\n * @param uuid model uuid\n * @param savepath export model path\n */\n void save(UUID uuid, String savepath) throws RemoteException, FOSException;\n\n /**\n * @see com.feedzai.fos.api.Manager#saveAsPMML(java.util.UUID, String, boolean)\n */\n void saveAsPMML(UUID uuid, String savePath, boolean compress) throws RemoteException, FOSException;\n}",
"public interface RemoteScorer extends Remote {\n /**\n * Score the <code>scorable</code> against the given <core>modelIds</core>.\n * <p/> The score must be between 0 and 999.\n * <p/> The resulting scores are returned by the same order as the <code>modelIds</code> (modelsIds(pos) » return(pos)).\n *\n * @param modelIds the list of models to score\n * @param scorable the instance data to score\n * @return a list of scores (int between 0 and 999)\n * @throws RemoteException when scoring was not possible\n */\n @NotNull\n List<double[]> score(List<UUID> modelIds,Object[] scorable) throws RemoteException;\n\n /**\n * Score all <code>scorables agains</code> the given <code>modelId</code>.\n * <p/> The score must be between 0 and 999.\n * <p/> The resulting scores are returned in the same order as the <code>scorables</code> (scorables(pos) » return(pos)).\n *\n * @param modelId the id of the model\n * @param scorables an array of instances to score\n * @return a map of scores where the key is the <code>modelId</code> (int between 0 and 999)\n * @throws RemoteException when scoring was not possible\n */\n @NotNull\n List<double[]> score(UUID modelId,List<Object[]> scorables) throws RemoteException;\n\n /**\n * Score a single <code>scorable</code> against the given <code>modelId</code>.\n *\n * <p/> The score must be between 0 and 999.\n *\n * @param modelId the id of the model\n * @param scorable the instance data to score\n * @return the scores\n * @throws RemoteException when scoring was not possible\n */\n @NotNull\n double[] score(UUID modelId, Object[] scorable) throws RemoteException;\n\n /**\n * Frees any resources allocated to this scorer.\n *\n * @throws RemoteException when closing resources was not possible\n */\n void close() throws RemoteException;\n\n}",
"public class RemoteManager implements IRemoteManager {\n private static final Logger logger = LoggerFactory.getLogger(RemoteManager.class);\n\n private Manager manager;\n private RemoteScorer remoteScorer;\n\n /**\n * Creates a new @{Manager} that delegates all calls to the underlying @{Manager}.\n *\n * @param manager the underlying manager\n * @throws Exception when retrieving the @{Scorer} from the underlying implementation\n */\n public RemoteManager(Manager manager) throws Exception {\n this.manager = manager;\n this.remoteScorer = new RemoteScorer(manager.getScorer());\n }\n\n\n @Override\n public UUID addModel(ModelConfig config, Model model) throws RemoteException, FOSException {\n return this.manager.addModel(config, model);\n }\n\n @Override\n public UUID addModel(ModelConfig config, @NotBlank ModelDescriptor descriptor) throws RemoteException, FOSException {\n return this.manager.addModel(config, descriptor);\n }\n\n @Override\n public void removeModel(UUID modelId) throws RemoteException, FOSException {\n this.manager.removeModel(modelId);\n }\n\n @Override\n public void reconfigureModel(UUID modelId, ModelConfig config) throws RemoteException, FOSException {\n this.manager.reconfigureModel(modelId, config);\n }\n\n @Override\n public void reconfigureModel(UUID modelId, ModelConfig config, Model model) throws RemoteException, FOSException {\n this.manager.reconfigureModel(modelId, config, model);\n }\n\n @Override\n public void reconfigureModel(UUID modelId, ModelConfig config, ModelDescriptor descriptor) throws RemoteException, FOSException {\n this.manager.reconfigureModel(modelId, config, descriptor);\n }\n\n @Override\n @NotNull\n public Map<UUID, ? extends ModelConfig> listModels() throws RemoteException, FOSException {\n return this.manager.listModels();\n\n }\n\n @Override\n @NotNull\n public RemoteScorer getScorer() throws RemoteException {\n return this.remoteScorer;\n }\n\n @Override\n public void close() throws RemoteException, FOSException {\n this.manager.close();\n\n }\n\n @Override\n public UUID trainAndAdd(ModelConfig config, List<Object[]> instances) throws RemoteException, FOSException {\n return this.manager.trainAndAdd(config, instances);\n\n }\n\n @Override\n public UUID trainAndAddFile(ModelConfig config, String path) throws RemoteException, FOSException {\n return this.manager.trainAndAddFile(config, path);\n }\n\n @Override\n public Model train(ModelConfig config, List<Object[]> instances) throws RemoteException, FOSException {\n return manager.train(config, instances);\n }\n\n @Override\n public double[] featureImportance(UUID uuid, Optional<List<Object[]>> instances, long seed) throws RemoteException, FOSException {\n return manager.featureImportance(uuid, instances, seed);\n }\n\n @Override\n public Model trainFile(ModelConfig config, String path) throws RemoteException, FOSException {\n return manager.trainFile(config, path);\n }\n\n @Override\n public void save(UUID uuid, String savepath) throws RemoteException, FOSException {\n this.manager.save(uuid, savepath);\n }\n\n @Override\n public void saveAsPMML(UUID uuid, String savePath, boolean compress) throws FOSException {\n this.manager.saveAsPMML(uuid, savePath, compress);\n }\n}",
"public class RemoteManagerFactory {\n\n /**\n * Creates a new RemoteManager.\n * <p/> Must be able to delegate the actual execution to an underlying implementation.\n * <p/> The configuration must specify a parameter with the factory class of the underlying configuration:\n * <ul>\n * <li>{@link FosConfig#FACTORY_NAME} the classname of the underlying {@link ManagerFactory} implementation</li>\n * </ul>\n * The <code>configuration</code> must also contain all required parameters for the underlying implementation.\n *\n * @param configuration the configuration parameters specific for an implementation\n * @return a <code>RemoteManager</code> that extends remote\n */\n @NotNull\n public RemoteManager createManager(FosConfig configuration) {\n ManagerFactory factory;\n try {\n factory = ManagerFactory.class.cast(Class.forName(configuration.getFactoryName()).newInstance());\n } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {\n throw new IllegalArgumentException(\"Could not instantiate factory \" + configuration.getFactoryName(), e);\n }\n\n try {\n return new RemoteManager(factory.createManager(configuration));\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }\n}"
] | import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import com.feedzai.fos.api.config.FosConfig;
import com.feedzai.fos.server.remote.api.IRemoteManager;
import com.feedzai.fos.server.remote.api.RemoteScorer;
import com.feedzai.fos.server.remote.impl.RemoteManager;
import com.feedzai.fos.server.remote.impl.RemoteManagerFactory;
import org.apache.commons.configuration.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* $#
* FOS Server
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.server;
/**
* Server that registers the classification implementation in the RMI registry.
*
* @author Marco Jorge ([email protected])
*/
public class FosServer {
private final static Logger logger = LoggerFactory.getLogger(FosServer.class);
private FosConfig parameters;
private final RemoteManager remoteManager;
private Registry registry;
/**
* Creates a new server with the given parameters.
* <p/> Creates a new @{RemoteManager} from the configuration file defined in the parameters.
*
* @param parameters a list of parameters
* @throws ConfigurationException when the configuration file specified in the parameters cannot be open/read.
*/
public FosServer(FosConfig parameters) throws ConfigurationException {
this.parameters = parameters;
this.remoteManager = new RemoteManagerFactory().createManager(parameters);
}
/**
* Binds the Manager and Scorer to the RMI Registry.
* <p/> Also registers a shutdown hook for closing and removing the items from the registry.
*
* @throws RemoteException when binding was not possible.
*/
public void bind() throws RemoteException {
registry = LocateRegistry.getRegistry(parameters.getRegistryPort()); | registry.rebind(IRemoteManager.class.getSimpleName(), UnicastRemoteObject.exportObject(remoteManager, parameters.getRegistryPort())); | 1 |
free46000/MultiItem | demo/src/main/java/com/freelib/multiitem/demo/MultiItemActivity.java | [
"public class BaseItemAdapter extends RecyclerView.Adapter<BaseViewHolder> {\n private List<Object> dataItems = new ArrayList<>();\n private List<Object> headItems = new ArrayList<>();\n private List<Object> footItems = new ArrayList<>();\n private ItemTypeManager itemTypeManager;\n private LoadMoreManager loadMoreManager;\n private OnItemClickListener onItemClickListener;\n private OnItemLongClickListener onItemLongClickListener;\n private ViewHolderParams params = new ViewHolderParams();\n protected AnimationLoader animationLoader = new AnimationLoader();\n\n\n public BaseItemAdapter() {\n itemTypeManager = new ItemTypeManager();\n }\n\n\n /**\n * 为数据源注册ViewHolder的管理类{@link ViewHolderManager}<br>\n * ViewHolder的管理类使adapter与view holder的创建绑定解耦<br>\n * 通过{@link ItemTypeManager}管理不同数据源和ViewHolder的关系<br>\n *\n * @param cls 数据源class\n * @param manager 数据源管理类\n * @param <T> 数据源\n * @param <V> ViewHolder\n * @see #register(Class, ViewHolderManagerGroup) 为相同数据源注册多个ViewHolder的管理类\n */\n public <T, V extends BaseViewHolder> void register(@NonNull Class<T> cls, @NonNull ViewHolderManager<T, V> manager) {\n itemTypeManager.register(cls, manager);\n }\n\n /**\n * 为相同数据源注册多个ViewHolder的管理类{@link ViewHolderManagerGroup}<br>\n * 主要为相同数据源根据内部属性的值对应多个ViewHolderManager设计,常见的如聊天界面的消息<br>\n *\n * @param cls 数据源class\n * @param group 对应相同数据源的一组数据源管理类\n * @param <T> 数据源\n * @param <V> ViewHolder\n * @see #register(Class, ViewHolderManager) 为数据源注册ViewHolder的管理类\n */\n public <T, V extends BaseViewHolder> void register(@NonNull Class<T> cls, @NonNull ViewHolderManagerGroup<T> group) {\n itemTypeManager.register(cls, group);\n }\n\n /**\n * 设置Item view点击监听\n */\n public void setOnItemClickListener(@NonNull OnItemClickListener onItemClickListener) {\n this.onItemClickListener = onItemClickListener;\n }\n\n /**\n * 设置item view长按监听\n */\n public void setOnItemLongClickListener(@NonNull OnItemLongClickListener onItemLongClickListener) {\n this.onItemLongClickListener = onItemLongClickListener;\n }\n\n /**\n * 设置Item list\n */\n public void setDataItems(@NonNull List<? extends Object> dataItems) {\n setItem(dataItems);\n }\n\n /**\n * 添加Item\n */\n public void addDataItem(@NonNull Object item) {\n addDataItem(dataItems.size(), item);\n }\n\n /**\n * 在指定位置添加Item\n */\n public void addDataItem(int position, @NonNull Object item) {\n addDataItems(position, Collections.singletonList(item));\n }\n\n /**\n * 添加ItemList\n */\n public void addDataItems(@NonNull List<? extends Object> items) {\n addDataItems(dataItems.size(), items);\n }\n\n /**\n * 在指定位置添加ItemList\n */\n public void addDataItems(int position, @NonNull List<? extends Object> items) {\n addItem(position, items);\n }\n\n /**\n * add item的最后调用处\n */\n protected void addItem(int position, @NonNull List<? extends Object> items) {\n dataItems.addAll(position, items);\n notifyItemRangeInserted(position + getHeadCount(), items.size());\n }\n\n /**\n * 设置item的最后调用处\n */\n protected void setItem(@NonNull List<? extends Object> dataItems) {\n this.dataItems = (List<Object>) dataItems;\n notifyDataSetChanged();\n }\n\n /**\n * 移动Item的位置 包括数据源和界面的移动\n *\n * @param fromPosition Item之前所在位置\n * @param toPosition Item新的位置\n */\n public void moveDataItem(int fromPosition, int toPosition) {\n //考虑到跨position(如0->2)移动的时候处理不能Collections.swap\n // if(from<to) to = to + 1 - 1;//+1是因为add的时候应该是to位置后1位,-1是因为先remove了from所以位置往前挪了1位\n dataItems.add(toPosition, dataItems.remove(fromPosition));\n notifyItemMoved(fromPosition + getHeadCount(), toPosition + getHeadCount());\n }\n\n\n /**\n * 移除Item 包括数据源和界面的移除\n *\n * @param position 需要被移除Item的position\n */\n public void removeDataItem(int position) {\n removeDataItem(position, 1);\n }\n\n /**\n * 改变Item 包括数据源和界面的移除\n *\n * @param position 需要被移除第一个Item的position\n * @param position 需要被移除Item的个数\n */\n public void removeDataItem(int position, int itemCount) {\n for (int i = 0; i < itemCount; i++) {\n dataItems.remove(position);\n }\n notifyItemRangeRemoved(position + getHeadCount(), itemCount);\n }\n\n /**\n * 添加foot View,默认为充满父布局\n * <p>\n * {@link ViewHolderManager#isFullSpan()}\n * {@link ViewHolderManager#getSpanSize(int)}\n *\n * @param footView foot itemView\n * @see HeadFootHolderManager\n * @see UniqueItemManager\n */\n public void addFootView(@NonNull View footView) {\n addFootItem(new UniqueItemManager(new HeadFootHolderManager(footView)));\n }\n\n /**\n * 添加foot ItemManager ,如是表格不居中需要充满父布局请设置对应属性<br>\n * {@link ViewHolderManager#isFullSpan()}\n * {@link ViewHolderManager#getSpanSize(int)}\n *\n * @param footItem foot item\n * @see HeadFootHolderManager\n */\n public void addFootItem(@NonNull Object footItem) {\n footItems.add(footItem);\n }\n\n /**\n * 添加head View,默认为充满父布局\n * <p>\n * {@link ViewHolderManager#isFullSpan()}\n * {@link ViewHolderManager#getSpanSize(int)}\n *\n * @param headView head itemView\n * @see HeadFootHolderManager\n * @see UniqueItemManager\n */\n public void addHeadView(@NonNull View headView) {\n addHeadItem(new UniqueItemManager(new HeadFootHolderManager(headView)));\n }\n\n /**\n * 添加head ItemManager ,如是表格不居中需要充满父布局请设置对应属性<br>\n * {@link ViewHolderManager#isFullSpan()}\n * {@link ViewHolderManager#getSpanSize(int)}\n *\n * @param headItem head item\n * @see HeadFootHolderManager\n */\n public void addHeadItem(@NonNull Object headItem) {\n headItems.add(headItem);\n }\n\n /**\n * 开启loadMore,使列表支持加载更多<p>\n * 本方法原理是添加{@link #addFootItem(Object)} 并且对添加顺序敏感需要注意在最后调用本方法才可以将加载更多视图放在底部\n *\n * @param loadMoreManager LoadMoreManager\n */\n public void enableLoadMore(@NonNull LoadMoreManager loadMoreManager) {\n this.loadMoreManager = loadMoreManager;\n loadMoreManager.setAdapter(this);\n addFootItem(loadMoreManager);\n }\n\n /**\n * 加载完成\n *\n * @see LoadMoreManager#loadCompleted(boolean)\n */\n public void setLoadCompleted(boolean isLoadAll) {\n if (loadMoreManager != null) {\n loadMoreManager.loadCompleted(isLoadAll);\n }\n }\n\n /**\n * 加载失败\n *\n * @see LoadMoreManager#loadFailed()\n */\n public void setLoadFailed() {\n if (loadMoreManager != null) {\n loadMoreManager.loadFailed();\n }\n }\n\n /**\n * 启动加载动画\n *\n * @param animation BaseAnimation\n */\n public void enableAnimation(BaseAnimation animation) {\n animationLoader.enableLoadAnimation(animation, true);\n }\n\n /**\n * 启动加载动画\n *\n * @param animation BaseAnimation\n * @param isShowAnimWhenFirstLoad boolean 是否只有在第一次展示的时候才使用动画\n */\n public void enableAnimation(BaseAnimation animation, boolean isShowAnimWhenFirstLoad) {\n animationLoader.enableLoadAnimation(animation, isShowAnimWhenFirstLoad);\n }\n\n /**\n * @see AnimationLoader#setInterpolator(Interpolator)\n */\n public void setInterpolator(@NonNull Interpolator interpolator) {\n animationLoader.setInterpolator(interpolator);\n }\n\n /**\n * @see AnimationLoader#setAnimDuration(long)\n */\n public void setAnimDuration(long animDuration) {\n animationLoader.setAnimDuration(animDuration);\n }\n\n /**\n * @return 获取当前数据源List,不包含head和foot\n */\n public List<Object> getDataList() {\n return dataItems;\n }\n\n\n /**\n * @param position int\n * @return 返回指定位置Item\n */\n public Object getItem(int position) {\n if (position < headItems.size()) {\n return headItems.get(position);\n }\n\n position -= headItems.size();\n if (position < dataItems.size()) {\n return dataItems.get(position);\n }\n\n position -= dataItems.size();\n if (position < footItems.size()) {\n return footItems.get(position);\n }\n\n return null;\n }\n\n /**\n * 清空数据\n */\n public void clearAllData() {\n clearData();\n headItems.clear();\n footItems.clear();\n }\n\n /**\n * 清空Item数据不含head 和 foot\n */\n public void clearData() {\n dataItems.clear();\n animationLoader.clear();\n }\n\n\n @Override\n public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n ViewHolderManager provider = itemTypeManager.getViewHolderManager(viewType);\n BaseViewHolder viewHolder = provider.onCreateViewHolder(parent);\n viewHolder.viewHolderManager = provider;\n return viewHolder;\n }\n\n @Override\n public void onBindViewHolder(BaseViewHolder holder, int position) {\n Object item = getItem(position);\n ViewHolderManager manager = holder.viewHolderManager;\n params.setItemCount(getItemCount()).setClickListener(onItemClickListener)\n .setLongClickListener(onItemLongClickListener);\n manager.onBindViewHolder(holder, item, params);\n //赋值 方便以后使用\n holder.itemView.setTag(Const.VIEW_HOLDER_TAG, holder);\n holder.itemData = item;\n }\n\n @Override\n public int getItemViewType(int position) {\n int type = itemTypeManager.getItemType(getItem(position));\n if (type < 0) {\n throw new RuntimeException(\"没有为\" + getItem(position).getClass() + \"找到对应的item itemView manager,是否注册了?\");\n }\n return type;\n }\n\n @Override\n public int getItemCount() {\n return dataItems.size() + getHeadCount() + getFootCount();\n }\n\n @Override\n public void onViewAttachedToWindow(BaseViewHolder holder) {\n super.onViewAttachedToWindow(holder);\n// System.out.println(\"onViewAttachedToWindow:::\" + holder.getItemPosition() + \"==\" + holder.getItemData());\n //当StaggeredGridLayoutManager的时候设置充满横屏\n if (holder.getViewHolderManager().isFullSpan() && holder.itemView.getLayoutParams() instanceof StaggeredGridLayoutManager.LayoutParams) {\n StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();\n params.setFullSpan(true);\n }\n animationLoader.startAnimation(holder);\n }\n\n @Override\n public void onAttachedToRecyclerView(final RecyclerView recyclerView) {\n super.onAttachedToRecyclerView(recyclerView);\n// System.out.println(\"onAttachedToRecyclerView:::\" + getItemCount());\n RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();\n if (manager instanceof GridLayoutManager) {\n //GridLayoutManager时设置每行的span\n final GridLayoutManager gridManager = ((GridLayoutManager) manager);\n gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {\n ViewHolderManager holderManager;\n\n @Override\n public int getSpanSize(int position) {\n holderManager = itemTypeManager.getViewHolderManager(getItemViewType(position));\n return holderManager.getSpanSize(gridManager.getSpanCount());\n }\n });\n }\n }\n\n /**\n * @return head view个数\n */\n public int getHeadCount() {\n return headItems.size();\n }\n\n /**\n * @return foot view个数\n */\n public int getFootCount() {\n return footItems.size();\n }\n\n}",
"public class ImageBean {\n private int img;\n\n public ImageBean(int img) {\n this.img = img;\n }\n\n public int getImg() {\n return img;\n }\n\n public void setImg(int img) {\n this.img = img;\n }\n\n @Override\n public String toString() {\n return img + \"\";\n }\n}",
"public class ImageTextBean extends BaseItemData {\n private int img;\n private String imgUrl;\n private String text;\n\n public ImageTextBean(int img, String text) {\n this.img = img;\n this.text = text;\n }\n\n public ImageTextBean(String imgUrl, String text) {\n this.imgUrl = imgUrl;\n this.text = text;\n }\n\n public int getImg() {\n return img;\n }\n\n public void setImg(int img) {\n this.img = img;\n }\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n public String getImgUrl() {\n return imgUrl;\n }\n\n public void setImgUrl(String imgUrl) {\n this.imgUrl = imgUrl;\n }\n\n @Override\n public String toString() {\n return text;\n }\n}",
"public class TextBean {\n private String text;\n\n public TextBean(String text) {\n this.text = text;\n }\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n @Override\n public String toString() {\n return text;\n }\n}",
"public class ImageAndTextManager extends BaseViewHolderManager<ImageTextBean> {\n\n\n @Override\n public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull ImageTextBean data) {\n TextView textView = getView(holder, R.id.text);\n textView.setText(data.getText());\n ImageView imageView = getView(holder, R.id.image);\n imageView.setImageResource(data.getImg());\n }\n\n @Override\n protected int getItemLayoutId() {\n return R.layout.item_image_text;\n }\n\n}",
"public class ImageViewManager extends BaseViewHolderManager<ImageBean> {\n\n\n @Override\n public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull ImageBean data) {\n ImageView imageView = getView(holder, R.id.image);\n imageView.setImageResource(data.getImg());\n }\n\n @Override\n protected int getItemLayoutId() {\n return R.layout.item_image;\n }\n\n}",
"public class TextViewManager<T extends TextBean> extends BaseViewHolderManager<T> {\n\n\n @Override\n public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull T data) {\n TextView textView = getView(holder, R.id.text);\n textView.setText(data.getText());\n }\n\n @Override\n protected int getItemLayoutId() {\n return R.layout.item_text;\n }\n\n}"
] | import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.freelib.multiitem.adapter.BaseItemAdapter;
import com.freelib.multiitem.demo.bean.ImageBean;
import com.freelib.multiitem.demo.bean.ImageTextBean;
import com.freelib.multiitem.demo.bean.TextBean;
import com.freelib.multiitem.demo.viewholder.ImageAndTextManager;
import com.freelib.multiitem.demo.viewholder.ImageViewManager;
import com.freelib.multiitem.demo.viewholder.TextViewManager;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List; | package com.freelib.multiitem.demo;
@EActivity(R.layout.layout_recycler)
public class MultiItemActivity extends AppCompatActivity {
@ViewById(R.id.recyclerView)
protected RecyclerView recyclerView;
public static void startActivity(Context context) {
MultiItemActivity_.intent(context).start();
}
@AfterViews
protected void initViews() {
setTitle(R.string.multi_item_title);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//初始化adapter | BaseItemAdapter adapter = new BaseItemAdapter(); | 0 |